// connect is a forever loop
// at each iteration, ask the overlay driver to suggest the most preferred peer to connect to
// as well as advertises saturation depth if needed
422405
func (h *Hive) connect() {
	for range h.ticker.C {

		addr, depth, changed := h.SuggestPeer()
		if h.Discovery && changed {
			NotifyDepth(uint8(depth), h.Kademlia)
		}
		if addr == nil {
			continue
		}

		log.Trace(fmt.Sprintf("%08x hive connect() suggested %08x", h.BaseAddr()[:4], addr.Address()[:4]))
		under, err := enode.ParseV4(string(addr.Under()))
		if err != nil {
			log.Warn(fmt.Sprintf("%08x unable to connect to bee %08x: invalid node URL: %v", h.BaseAddr()[:4], addr.Address()[:4], err))
			continue
		}
		log.Trace(fmt.Sprintf("%08x attempt to connect to bee %08x", h.BaseAddr()[:4], addr.Address()[:4]))
		h.addPeer(under)
	}
}
95225
func (t *TimeSeries) Connect(ctx context.Context, src *chronograf.Source) error {
	return t.ConnectF(ctx, src)
}
1268982
func (m *UDPAdaptor) Connect() error {
	m.close()

	addr, err := net.ResolveUDPAddr("udp", m.Port())
	if err != nil {
		return err
	}

	m.sock, err = net.ListenUDP("udp", addr)
	if err != nil {
		return err
	}
	return nil
}
586901
func (c *Client) Connect() (client.Session, error) {
	if c.conn == nil {
		if err := c.initConnection(); err != nil {
			return nil, err
		}
	}
	return &Session{c.conn, c.ch}, nil
}
613756
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) {
	conn, err := c.driver.connect(ctx, c, c.params)
	if err == nil {
		err = conn.ResetSession(ctx)
	}
	return conn, err
}
398629
func (stanOpts *StanOptions) Connect() (*Stan, error) {
	if len(stanOpts.ClientId) == 0 {
		panic("Must set client id in StanOptions")
	}
	if len(stanOpts.ClusterId) == 0 {
		panic("Must set cluster id in StanOptions")
	}

	con, err := stanOpts.Options.Connect()
	if err != nil {
		return nil, fmt.Errorf("Failed to connect to underlying nats: %s", err)
	}

	stanCon, err := stan.Connect(stanOpts.ClusterId, stanOpts.ClientId, stan.NatsConn(con))
	if err != nil {
		return nil, fmt.Errorf("Failed to get stan con: %s", err)
	}

	return &Stan{Con: stanCon, Opts: stanOpts}, nil
}
1165410
func (cli *Client) Connect(opts *ConnectOptions) error {
	// Lock for the connection.
	cli.muConn.Lock()

	// Unlock.
	defer cli.muConn.Unlock()

	// Return an error if the Client has already connected to the Server.
	if cli.conn != nil {
		return ErrAlreadyConnected
	}

	// Initialize the options.
	if opts == nil {
		opts = &ConnectOptions{}
	}

	// Establish a Network Connection.
	conn, err := newConnection(opts.Network, opts.Address, opts.TLSConfig)
	if err != nil {
		return err
	}

	// Set the Network Connection to the Client.
	cli.conn = conn

	// Lock for reading and updating the Session.
	cli.muSess.Lock()

	// Create a Session or reuse the current Session.
	if opts.CleanSession || cli.sess == nil {
		// Create a Session and set it to the Client.
		cli.sess = newSession(opts.CleanSession, opts.ClientID)
	} else {
		// Reuse the Session and set its Client Identifier to the options.
		opts.ClientID = cli.sess.clientID
	}

	// Unlock.
	cli.muSess.Unlock()

	// Send a CONNECT Packet to the Server.
	err = cli.sendCONNECT(&packet.CONNECTOptions{
		ClientID:     opts.ClientID,
		UserName:     opts.UserName,
		Password:     opts.Password,
		CleanSession: opts.CleanSession,
		KeepAlive:    opts.KeepAlive,
		WillTopic:    opts.WillTopic,
		WillMessage:  opts.WillMessage,
		WillQoS:      opts.WillQoS,
		WillRetain:   opts.WillRetain,
	})

	if err != nil {
		// Close the Network Connection.
		cli.conn.Close()

		// Clean the Network Connection and the Session if necessary.
		cli.clean()

		return err
	}

	// Launch a goroutine which waits for receiving the CONNACK Packet.
	cli.conn.wg.Add(1)
	go cli.waitPacket(cli.conn.connack, opts.CONNACKTimeout, ErrCONNACKTimeout)

	// Launch a goroutine which receives a Packet from the Server.
	cli.conn.wg.Add(1)
	go cli.receivePackets()

	// Launch a goroutine which sends a Packet to the Server.
	cli.conn.wg.Add(1)
	go cli.sendPackets(time.Duration(opts.KeepAlive), opts.PINGRESPTimeout)

	// Resend the unacknowledged PUBLISH and PUBREL Packets to the Server
	// if the Clean Session is false.
	if !opts.CleanSession {
		// Lock for reading and updating the Session.
		cli.muSess.Lock()

		// Unlock.
		defer cli.muSess.Unlock()

		for id, p := range cli.sess.sendingPackets {
			// Extract the MQTT Control MQTT Control Packet type.
			ptype, err := p.Type()
			if err != nil {
				return err
			}

			switch ptype {
			case packet.TypePUBLISH:
				// Set the DUP flag of the PUBLISH Packet to true.
				p.(*packet.PUBLISH).DUP = true
				// Resend the PUBLISH Packet to the Server.
				cli.conn.send <- p
			case packet.TypePUBREL:
				// Resend the PUBREL Packet to the Server.
				cli.conn.send <- p
			default:
				// Delete the Packet from the Session.
				delete(cli.sess.sendingPackets, id)
			}
		}
	}

	return nil
}
632700
func Connect(addr string) (*Client, error) {
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		return nil, err
	}

	return NewClient(conn), nil
}
1283144
func (s *Sling) Connect(pathURL string) *Sling {
	s.method = "CONNECT"
	return s.Path(pathURL)
}
216582
func (s *Service) connect(fail chan struct{}) (*Client, bool) {
	// prepare new client
	client := New()
	client.Session = s.Session
	client.Logger = s.Logger
	client.futureStore = s.futureStore

	// set callback
	client.Callback = func(msg *packet.Message, err error) error {
		if err != nil {
			s.err("Client", err)
			close(fail)
			return nil
		}

		// call the handler
		if s.MessageCallback != nil {
			return s.MessageCallback(msg)
		}

		return nil
	}

	// attempt to connect
	connectFuture, err := client.Connect(s.config)
	if err != nil {
		s.err("Connect", err)
		return nil, false
	}

	// wait for connack
	err = connectFuture.Wait(s.ConnectTimeout)

	// check if future has been canceled
	if err == future.ErrCanceled {
		s.err("Connect", err)
		return nil, false
	}

	// check if future has timed out
	if err == future.ErrTimeout {
		client.Close()

		s.err("Connect", err)
		return nil, false
	}

	return client, connectFuture.SessionPresent()
}
213435
func (c *Connection) connect() (err error) {
	c.connected(false)
	c.connectLock.Lock()
	defer c.connectLock.Unlock()

	// If we blocked on the lock, and another routine connected in the mean
	// time, return early
	if c.Connected {
		return
	}

	if c.conn != nil {
		_ = c.conn.Close()
	}

	c.conn, err = net.Dial(`tcp`, c.address)
	if err != nil {
		success := make(chan bool, 1)
		done := make(chan bool, 1)
		go func() {
			for err != nil {
				log.WithField(`error`, err).Error(`Connecting to Kodi`)
				log.Info(`Attempting reconnect...`)
				time.Sleep(time.Second)
				c.conn, err = net.Dial(`tcp`, c.address)
				select {
				case <-done:
					break
				default:
				}
			}
			success <- true
		}()
		if c.timeout > 0 {
			select {
			case <-success:
			case <-time.After(c.timeout * time.Second):
				done <- true
				log.Error(`Timeout connecting to Kodi`)
				return err
			}
		} else {
			<-success
		}
	}

	c.enc = json.NewEncoder(c.conn)
	c.dec = json.NewDecoder(c.conn)

	log.Info(`Connected to Kodi`)
	c.connected(true)

	return
}
218850
func (u *udpTransport) connect() error {
	c, err := net.DialTimeout("udp", u.endpoint, 1*time.Second)
	if err != nil {
		return err
	}

	u.conn = c

	return nil
}
82081
func (a *Adaptor) Connect() (err error) {
	a.client, err = a.connect()
	return
}
952908
func (c *Client) Connect() (client.Session, error) {
	if c.pqSession == nil {
		// there's really no way for this to error because we know the driver we're passing is
		// available.
		c.pqSession, _ = sql.Open("postgres", c.uri)
		uri, _ := url.Parse(c.uri)
		if uri.Path != "" {
			c.db = uri.Path[1:]
		}
	}
	err := c.pqSession.Ping()
	return &Session{c.pqSession, c.db}, err
}
615413
func (conn *Connection) Connect(ctx context.Context) (err error) {
	obs := prometheus.NewTimer(connInitialConnectTime)
	defer obs.ObserveDuration()

	conn.conMu.Lock()
	defer conn.conMu.Unlock()

	var tlsc *tls.Config

	if !conn.choria.Config.DisableTLS {
		tlsc, err = conn.choria.TLSConfig()
		if err != nil {
			err = fmt.Errorf("Could not create TLS Config: %s", err)
			return err
		}
	}

	urls := []string{}
	var url *url.URL

	servers, err := conn.servers()
	if err != nil {
		err = fmt.Errorf("Could not resolve servers during initial connect: %s", err)
	}

	for _, server := range servers {
		url, err = server.URL()
		if err != nil {
			err = fmt.Errorf("Could not determine URL for server %#v", server)
			return
		}

		urls = append(urls, url.String())
	}

	options := []nats.Option{
		nats.MaxReconnects(-1),
		nats.Name(conn.name),

		// This is specifically set quite small, just about enough to handle short
		// reconnects rather than the 8MB long buffer that's default.  30 000 nodes
		// each sending several MB after reconnect is not what anyone wants
		nats.ReconnectBufSize(10 * 1024),

		// nats.SetPend
		nats.DisconnectHandler(func(nc *nats.Conn) {
			err = nc.LastError()

			if err != nil {
				conn.logger.Warnf("NATS client connection got disconnected: %s", nc.LastError())
			}
		}),

		nats.ReconnectHandler(func(nc *nats.Conn) {
			conn.logger.Warnf("NATS client reconnected after a previous disconnection, connected to %s", nc.ConnectedUrl())
			connReconnectCtr.Inc()
		}),

		nats.ClosedHandler(func(nc *nats.Conn) {
			err = nc.LastError()
			if err != nil {
				conn.logger.Warnf("NATS client connection closed: %s", nc.LastError())
			}
			connClosedCtr.Inc()
		}),

		nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
			conn.logger.Errorf("NATS client on %s encountered an error: %s", nc.ConnectedUrl(), err)
			connErrorCtr.Inc()
		}),
	}

	if !conn.choria.Config.DisableTLS {
		options = append(options, nats.Secure(tlsc))
	}

	if !conn.choria.Config.Choria.RandomizeMiddlewareHosts {
		options = append(options, nats.DontRandomize())
	}

	try := 0

	for {
		try++

		conn.nats, err = nats.Connect(strings.Join(urls, ", "), options...)
		if err != nil {
			connInitialConnectCtr.Inc()

			conn.logger.Warnf("Initial connection to the NATS broker cluster failed: %s", err)

			if ctx.Err() != nil {
				err = fmt.Errorf("Initial connection cancelled due to shut down")
				return
			}

			s := backoff.FiveSec.Duration(try)
			conn.logger.Infof("Sleeping %s after failed connection attempt %d", s, try)
			time.Sleep(s)

			continue
		}

		conn.logger.Debugf("Connected to %s", conn.nats.ConnectedUrl())

		break
	}

	return
}
827055
func (d *Databases) Connect(ctx context.Context, src *chronograf.Source) error {
	return d.ConnectF(ctx, src)
}
1113290
func (s *Stackdriver) Connect() error {
	if s.Project == "" {
		return fmt.Errorf("Project is a required field for stackdriver output")
	}

	if s.Namespace == "" {
		return fmt.Errorf("Namespace is a required field for stackdriver output")
	}

	if s.ResourceType == "" {
		s.ResourceType = "global"
	}

	if s.ResourceLabels == nil {
		s.ResourceLabels = make(map[string]string, 1)
	}

	s.ResourceLabels["project_id"] = s.Project

	if s.client == nil {
		ctx := context.Background()
		client, err := monitoring.NewMetricClient(ctx)
		if err != nil {
			return err
		}
		s.client = client
	}

	return nil
}