// GetSpiConnection returns an spi connection to a device on a specified bus.
// Valid bus number is [0..1] which corresponds to /dev/spidev0.0 through /dev/spidev0.1.
555288
func (r *Adaptor) GetSpiConnection(busNum, chipNum, mode, bits int, maxSpeed int64) (connection spi.Connection, err error) {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if (busNum < 0) || (busNum > 1) {
		return nil, fmt.Errorf("Bus number %d out of range", busNum)
	}

	if r.spiDevices[busNum] == nil {
		r.spiDevices[busNum], err = spi.GetSpiConnection(busNum, chipNum, mode, bits, maxSpeed)
	}

	return r.spiDevices[busNum], err
}
518099
func GetSocket(ctx context.Context, dsn string) (string, error) {
	var socket string
	var err error
	socket, err = GetSocketFromTCPConnection(ctx, dsn)
	if err != nil {
		socket, err = GetSocketFromProcessList(ctx)
		if err != nil {
			socket, err = GetSocketFromNetstat(ctx)
		}
	}
	return socket, err
}
77152
func (a *Adaptor) Reconnect() (err error) {
	if a.connected {
		a.Disconnect()
	}
	return a.Connect()
}
1022629
func (s *PresenceService) GetTunnelConnection(clusterName, connectionName string, opts ...services.MarshalOption) (services.TunnelConnection, error) {
	item, err := s.Get(context.TODO(), backend.Key(tunnelConnectionsPrefix, clusterName, connectionName))
	if err != nil {
		if trace.IsNotFound(err) {
			return nil, trace.NotFound("trusted cluster connection %q is not found", connectionName)
		}
		return nil, trace.Wrap(err)
	}
	conn, err := services.UnmarshalTunnelConnection(item.Value,
		services.AddOptions(opts, services.WithResourceID(item.ID), services.WithExpires(item.Expires))...)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return conn, nil
}
829781
func GetCSIEndpointListener() (net.Listener, error) {
	proto, addr, err := GetCSIEndpoint()
	if err != nil {
		return nil, err
	}
	return net.Listen(proto, addr)
}
1040441
func (d *Driver) GetIP() (string, error) {
	ip, err := net.ChooseBindAddress(nil)
	if err != nil {
		return "", err
	}
	return ip.String(), nil
}
128863
func SelectorConnectOption(s gosocks5.Selector) ConnectOption {
	return func(opts *ConnectOptions) {
		opts.Selector = s
	}
}
301780
func (s *Server) getNodeConn(nodeID string) (*nodeConnState, bool) {
	s.nodeConnsLock.RLock()
	defer s.nodeConnsLock.RUnlock()
	conns, ok := s.nodeConns[nodeID]
	if !ok {
		return nil, false
	}

	// Return the latest conn
	var state *nodeConnState
	for _, conn := range conns {
		if state == nil || state.Established.Before(conn.Established) {
			state = conn
		}
	}

	// Shouldn't happen but rather be safe
	if state == nil {
		s.logger.Named("client_rpc").Warn("node exists in node connection map without any connection", "node_id", nodeID)
		return nil, false
	}

	return state, ok
}
163650
func (nd *Node) getConnectionWithHint(deadline time.Time, timeout time.Duration, hint byte) (conn *Connection, err error) {

	var socketDeadline time.Time
	connReqd := false

L:
	// try to get a valid connection from the connection pool
	for conn = nd.connections.Poll(hint); conn != nil; conn = nd.connections.Poll(hint) {
		if conn.IsConnected() {
			break
		}
		conn.Close()
		conn = nil
	}

	// don't loop forever; return the goroutine after deadline.
	// deadline will always be set when requesting for a connection.
	if connReqd && time.Now().After(socketDeadline) {
		atomic.AddInt64(&nd.stats.ConnectionsPoolEmpty, 1)

		return nil, ErrConnectionPoolEmpty
	}

	if conn == nil {
		if !connReqd {
			go nd.makeConnectionForPool(deadline, hint)

			// do not request to open a connection more than once.
			connReqd = true

			// only try to set a deadline once without a penalty on each run.
			// most call to this function will find a connection in the queue.
			if timeout > 0 {
				socketDeadline = time.Now().Add(timeout)
			} else {
				socketDeadline = time.Now().Add(_DEFAULT_TIMEOUT)
			}
		}

		time.Sleep(time.Millisecond)
		goto L
	}

	if err = conn.SetTimeout(deadline, timeout); err != nil {
		atomic.AddInt64(&nd.stats.ConnectionsFailed, 1)

		// Do not put back into pool.
		conn.Close()
		return nil, err
	}

	conn.setIdleTimeout(nd.cluster.clientPolicy.IdleTimeout)
	conn.refresh()

	return conn, nil
}
366667
func (bridge *Bridge) GetScene(id string) (Scene, error) {
	uri := fmt.Sprintf("/api/%s/scenes/%s", bridge.Username, id)
	body, _, err := bridge.Get(uri)
	if err != nil {
		return Scene{}, err
	}

	scene := Scene{}
	err = json.Unmarshal(body, &scene)
	if err != nil {
		return Scene{}, err
	}
	return scene, nil
}
644416
func dialConnection(ctx context.Context, c *Connector, p connectParams) (conn net.Conn, err error) {
	var ips []net.IP
	ips, err = net.LookupIP(p.host)
	if err != nil {
		ip := net.ParseIP(p.host)
		if ip == nil {
			return nil, err
		}
		ips = []net.IP{ip}
	}
	if len(ips) == 1 {
		d := c.getDialer(&p)
		addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port)))
		conn, err = d.DialContext(ctx, "tcp", addr)

	} else {
		//Try Dials in parallel to avoid waiting for timeouts.
		connChan := make(chan net.Conn, len(ips))
		errChan := make(chan error, len(ips))
		portStr := strconv.Itoa(int(p.port))
		for _, ip := range ips {
			go func(ip net.IP) {
				d := c.getDialer(&p)
				addr := net.JoinHostPort(ip.String(), portStr)
				conn, err := d.DialContext(ctx, "tcp", addr)
				if err == nil {
					connChan <- conn
				} else {
					errChan <- err
				}
			}(ip)
		}
		// Wait for either the *first* successful connection, or all the errors
	wait_loop:
		for i, _ := range ips {
			select {
			case conn = <-connChan:
				// Got a connection to use, close any others
				go func(n int) {
					for i := 0; i < n; i++ {
						select {
						case conn := <-connChan:
							conn.Close()
						case <-errChan:
						}
					}
				}(len(ips) - i - 1)
				// Remove any earlier errors we may have collected
				err = nil
				break wait_loop
			case err = <-errChan:
			}
		}
	}
	// Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection
	if conn == nil {
		f := "Unable to open tcp connection with host '%v:%v': %v"
		return nil, fmt.Errorf(f, p.host, p.port, err.Error())
	}
	return conn, err
}
453058
func (in *IncomingConnection) AcceptConnection(opts ...ConnectionOption) Connection {
	return in.accept(func() Endpoint {
		for _, opt := range opts {
			opt(in.c)
		}
		in.c.pConnection.Open()
		return in.c
	}).(Connection)
}
93824
func (d *logDrain) getConnection(forceNew bool) (net.Conn, error) {
	// If we have a connection, it's not old, and we're not focing a new one...
	if d.conn != nil && !forceNew {
		// then return the existing connection
		return d.conn, nil
	}
	// If ANY of those conditions weren't met, it's time for a new connection.
	// If we have an existing one, close it and nil it out, too for good measure.
	if d.conn != nil {
		if err := d.conn.Close(); err != nil {
			log.Println("drain: Error closing connection.  Drain may be leaking connections.", err)
		}
		d.conn = nil
	}
	// Try a few times...
	var err error
	for attempt := 1; attempt <= maxFailedConns; attempt++ {
		d.conn, err = net.DialTimeout(d.proto, d.uri, dialTimeout)
		if err == nil {
			// We got our connection...
			// Make it good for only so long.  See comment above on connRefreshInterval.
			err = d.conn.SetWriteDeadline(time.Now().Add(connRefreshInterval))
			if err != nil {
				return nil, err
			}
			// Break out of the loop and return
			return d.conn, nil
		}
	}
	// Multiple attempts to dial have failed.  Whatever the problem is, we shouldn't expect that
	// it will resolve itself quickly.
	log.Printf("drain: Experienced %d consecutive failed connection attempts; muting drain for %s.", maxFailedConns, mutePeriod)
	// Immediately "mute" the drain.  This will prevent us from wasting resources repeatedly dialing
	// and failing while the message queue gets backed up.  This will give the network a break and
	// allow us to empty the queue.
	d.muted = true
	// Unmute the drain when the mute interval has elapsed
	go func() {
		time.Sleep(mutePeriod)
		d.muted = false
	}()
	// Return the error from the last failed connection attempt
	return nil, err
}
77788
func (c *Peer) OnDisconnect(f func()) {
	c.onDisconnect = append(c.onDisconnect, f)
}
1310020
func GetSpiConnection(busNum, chipNum, mode, bits int, maxSpeed int64) (Connection, error) {
	p, err := xsysfs.NewSPI(busNum, chipNum)
	if err != nil {
		return nil, err
	}
	c, err := p.Connect(physic.Frequency(maxSpeed)*physic.Hertz, xspi.Mode(mode), bits)
	if err != nil {
		return nil, err
	}
	return NewConnection(p, c), nil
}
872879
func (fmd *FakeMysqlDaemon) GetAppConnection(ctx context.Context) (*dbconnpool.PooledDBConnection, error) {
	return fmd.appPool.Get(ctx)
}
701650
func (d *Adaptor) GetConnection(address int, bus int) (connection i2c.Connection, err error) {
	if bus != 0 {
		return nil, fmt.Errorf("Invalid bus number %d, only 0 is supported", bus)
	}
	c := NewDigisparkI2cConnection(d, uint8(address))
	if err := c.Init(); err != nil {
		return nil, err
	}
	return i2c.Connection(c), nil
}