// Create a connection wrapping the supplied file descriptor connected to the
// kernel. You must eventually call c.close().
//
// The loggers may be nil.
348807
func newConnection(
	cfg MountConfig,
	debugLogger *log.Logger,
	errorLogger *log.Logger,
	dev *os.File) (c *Connection, err error) {
	c = &Connection{
		cfg:         cfg,
		debugLogger: debugLogger,
		errorLogger: errorLogger,
		dev:         dev,
		cancelFuncs: make(map[uint64]func()),
	}

	// Initialize.
	err = c.Init()
	if err != nil {
		c.close()
		err = fmt.Errorf("Init: %v", err)
		return
	}

	return
}
599894
func (process *TeleportProcess) ExportFileDescriptors() ([]FileDescriptor, error) {
	var out []FileDescriptor
	process.Lock()
	defer process.Unlock()
	for _, r := range process.registeredListeners {
		file, err := utils.GetListenerFile(r.Listener)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		out = append(out, FileDescriptor{File: file, Type: r.Type, Address: r.Address})
	}
	return out, nil
}
970288
func (ac *addrConn) createTransport(addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) (transport.ClientTransport, *grpcsync.Event, error) {
	prefaceReceived := make(chan struct{})
	onCloseCalled := make(chan struct{})
	reconnect := grpcsync.NewEvent()

	target := transport.TargetInfo{
		Addr:      addr.Addr,
		Metadata:  addr.Metadata,
		Authority: ac.cc.authority,
	}

	onGoAway := func(r transport.GoAwayReason) {
		ac.mu.Lock()
		ac.adjustParams(r)
		ac.mu.Unlock()
		reconnect.Fire()
	}

	onClose := func() {
		close(onCloseCalled)
		reconnect.Fire()
	}

	onPrefaceReceipt := func() {
		close(prefaceReceived)
	}

	connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline)
	defer cancel()
	if channelz.IsOn() {
		copts.ChannelzParentID = ac.channelzID
	}

	newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt, onGoAway, onClose)
	if err != nil {
		// newTr is either nil, or closed.
		grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err)
		return nil, nil, err
	}

	if ac.dopts.reqHandshake == envconfig.RequireHandshakeOn {
		select {
		case <-time.After(connectDeadline.Sub(time.Now())):
			// We didn't get the preface in time.
			newTr.Close()
			grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v: didn't receive server preface in time. Reconnecting...", addr)
			return nil, nil, errors.New("timed out waiting for server handshake")
		case <-prefaceReceived:
			// We got the preface - huzzah! things are good.
		case <-onCloseCalled:
			// The transport has already closed - noop.
			return nil, nil, errors.New("connection closed")
			// TODO(deklerk) this should bail on ac.ctx.Done(). Add a test and fix.
		}
	}
	return newTr, reconnect, nil
}
1283702
func (c *Connect) Close() (int, error) {
	var err C.virError
	result := int(C.virConnectCloseWrapper(c.ptr, &err))
	if result == -1 {
		return result, makeError(&err)
	}
	if result == 0 {
		// No more reference to this connection, release data.
		releaseConnectionData(c)
		c.ptr = nil
	}
	return result, nil
}
281169
func closeCallback(conn C.virConnectPtr, reason ConnectCloseReason, goCallbackId int) {
	callbackFunc := getCallbackId(goCallbackId)
	callback, ok := callbackFunc.(CloseCallback)
	if !ok {
		panic("Inappropriate callback type called")
	}
	callback(&Connect{ptr: conn}, reason)
}
1351293
func createMConnection(
	conn net.Conn,
	p *peer,
	reactorsByCh map[byte]Reactor,
	chDescs []*tmconn.ChannelDescriptor,
	onPeerError func(Peer, interface{}),
	config tmconn.MConnConfig,
) *tmconn.MConnection {

	onReceive := func(chID byte, msgBytes []byte) {
		reactor := reactorsByCh[chID]
		if reactor == nil {
			// Note that its ok to panic here as it's caught in the conn._recover,
			// which does onPeerError.
			panic(fmt.Sprintf("Unknown channel %X", chID))
		}
		p.metrics.PeerReceiveBytesTotal.With("peer_id", string(p.ID())).Add(float64(len(msgBytes)))
		reactor.Receive(chID, p, msgBytes)
	}

	onError := func(r interface{}) {
		onPeerError(p, r)
	}

	return tmconn.NewMConnectionWithConfig(
		conn,
		chDescs,
		onReceive,
		onError,
		config,
	)
}
419733
func NewConnWithClusterAndUser(clusterName string, userName string) (*Conn, error) {
	c_cluster_name := C.CString(clusterName)
	defer C.free(unsafe.Pointer(c_cluster_name))

	c_name := C.CString(userName)
	defer C.free(unsafe.Pointer(c_name))

	conn := makeConn()
	ret := C.rados_create2(&conn.cluster, c_cluster_name, c_name, 0)
	if ret == 0 {
		return conn, nil
	} else {
		return nil, RadosError(int(ret))
	}
}
308820
func NewReaderCloser() (io.ReadCloser, error) {
	nl := unix.SockaddrNetlink{
		Family: unix.AF_NETLINK,
		// Passing Pid as 0 here allows the kernel to take care of assigning
		// it. This allows multiple netlink sockets to be used.
		Pid:    uint32(0),
		Groups: 1,
	}

	fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW, unix.NETLINK_KOBJECT_UEVENT)
	if err != nil {
		return nil, err
	}

	if err := unix.Bind(fd, &nl); err != nil {
		return nil, err
	}

	return &ReaderCloser{fd}, nil
}
334788
func (c *connection) Close() error {
	c.mu.Lock()
	if c.stopErr == nil {
		c.stopErr = ErrClosed
		close(c.stop)
	}
	c.mu.Unlock()
	return c.rw.Close()
}
895876
func createConn(d *Daemon, w http.ResponseWriter, r *http.Request) *HttpErr {
	if r.Body == nil {
		return &HttpErr{http.StatusBadRequest, "request body is empty"}
	}

	con := &Connection{}
	err := json.NewDecoder(r.Body).Decode(con)

	if err != nil {
		return &HttpErr{http.StatusInternalServerError, err.Error()}
	}

	if con.Network == "" {
		con.Network = defaultNetwork
	}

	ctx := &ConnectionCtx{
		addConn,
		con,
		make(chan *Connection),
	}

	d.connectionChan <- ctx

	res := <-ctx.Result

	if res.OvsPortID == "-1" {
		return &HttpErr{http.StatusBadRequest, "resp body not valid"}
	}

	data, _ := json.Marshal(res)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(data)

	return nil
}
89887
func (logger *Logger) ensureOpenConnection() error {
	if !logger.isOpenConnection() {
		if err := logger.openConnection(); err != nil {
			return err
		}
	}

	return nil
}
918122
func (c *GRPCConnection) Close() {
	if !c.setClosed() {
		logger.Debug("Already closed")
		return
	}

	logger.Debug("Releasing connection....")
	c.commManager.ReleaseConn(c.conn)

	logger.Debug("... connection successfully closed.")
}
645907
func (retry *RetryRequest) Wrap(innerconnection plugin.Connection) plugin.Connection {
	retry.connection = innerconnection
	return retry
}
1158181
func (c *Client) LinodeConfigCreate(linodeID int, kernelID int, label string,
	diskList string, conf LinodeConfigCreateOpts) (configID int, err error) {

	args, err := c.argMarshal(conf)
	if err != nil {
		return 0, err
	}
	args["LinodeID"] = linodeID
	args["KernelID"] = kernelID
	args["Label"] = label
	args["DiskList"] = diskList

	data, err := c.apiCall("linode.config.create", args)
	if err != nil {
		return 0, err
	}

	err = unmarshalSingle(data, "ConfigID", &configID)
	if err != nil {
		return 0, err
	}

	return configID, nil
}
50914
func (c *connection) Close() error {
	c.streamLock.Lock()
	for _, s := range c.streams {
		// calling Reset instead of Close ensures that all streams are fully torn down
		s.Reset()
	}
	c.streams = make([]httpstream.Stream, 0)
	c.streamLock.Unlock()

	// now that all streams are fully torn down, it's safe to call close on the underlying connection,
	// which should be able to terminate immediately at this point, instead of waiting for any
	// remaining graceful stream termination.
	return c.conn.Close()
}
711518
func (h *Client) connect(ctx context.Context) (conn *grpc.ClientConn, err error) {
	opts := []grpc.DialOption{
		grpc.WithBlock(),
		grpc.WithKeepaliveParams(keepalive.ClientParameters{
			// Send keepalive every 30 seconds to prevent the connection from
			// getting closed by upstreams
			Time: time.Duration(30) * time.Second,
		}),
		grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)),
	}
	switch {
	case h.opts.useTLS:
		opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(h.opts.tlsConfig)))
	default:
		opts = append(opts, grpc.WithInsecure())
	}
	ctx, cancel := context.WithTimeout(ctx, h.opts.connectTimeout)
	defer cancel()
	if conn, err = grpc.DialContext(ctx, h.opts.host, opts...); err != nil {
		return nil, err
	}
	return conn, nil
}
686495
func (c *proxyConnection) Close() {
	scopedLog := log.WithField(fieldConn, c)

	c.closeLocker.Lock()
	select {
	case <-c.close:
		// Already closed. Nothing to do.
		c.closeLocker.Unlock()
		return
	default:
	}
	// Cause writeQueuedMessages to terminate.
	close(c.close)
	c.closeLocker.Unlock()

	// Actually close the TCP connection. This will unblock any eventually
	// blocking c.conn.Write call in writeQueuedMessages.
	if !c.Closed() {
		scopedLog.Debug("Closing socket")
		c.conn.Close()
	}

	// Call connectionPair.close() concurrently so that this call doesn't block
	// while waiting for the other connection in the pair to close.
	go c.afterClose()
}