/**
 * Connect to mongo
 */
321414
func Connect() (*mgo.Session, *mgo.Database, string) {
	uri := os.Getenv("MONGODB_URL")

	if uri == "" {
		uri = "mongodb://localhost:27017/notifications_testing"
	}

	const SSL_SUFFIX = "?ssl=true"
	connStringForDb := uri
	if strings.HasSuffix(uri, SSL_SUFFIX) {
		connStringForDb = strings.TrimSuffix(uri, SSL_SUFFIX)
	}

	mInfo, _ := mgo.ParseURL(connStringForDb)
	conn := db.GetConn(uri, mInfo.Database)
	session := conn.Session
	session.SetSafe(&mgo.Safe{})
	fmt.Println("Connected to", uri, "\n")

	sess := session.Clone()

	return session, sess.DB(mInfo.Database), mInfo.Database
}
845913
func (c *client) connect() (byte, bool) {
	DEBUG.Println(NET, "connect started")

	ca, err := packets.ReadPacket(c.conn)
	if err != nil {
		ERROR.Println(NET, "connect got error", err)
		return packets.ErrNetworkError, false
	}
	if ca == nil {
		ERROR.Println(NET, "received nil packet")
		return packets.ErrNetworkError, false
	}

	msg, ok := ca.(*packets.ConnackPacket)
	if !ok {
		ERROR.Println(NET, "received msg that was not CONNACK")
		return packets.ErrNetworkError, false
	}

	DEBUG.Println(NET, "received connack")
	return msg.ReturnCode, msg.SessionPresent
}
1006814
func InitConnection() {
	connectionAttempted = true
	if variables.DBAddress == "" {
		MongoConn = nil
		log.Println("No mongo server to connect to")
		return
	}

	connection, err := mgo.Dial(variables.DBAddress)
	if err != nil {
		connection = nil
		log.Println("Could not connect to mongo server")
		return
	}

	// Optional. Switch the connection to a monotonic behavior.
	connection.SetMode(mgo.Monotonic, true)
	connection.SetSafe(&mgo.Safe{})

	MongoConn = connection
	return
}
308422
func (c *configInternal) MongoInfo() (info *mongo.MongoInfo, ok bool) {
	ssi, ok := c.StateServingInfo()
	if !ok {
		return nil, false
	}
	// We return localhost first and then all addresses of known API
	// endpoints - this lets us connect to other Mongo instances and start
	// state even if our own Mongo has not started yet (see lp:1749383 #1).
	// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,
	// and when/if this changes localhost should resolve to IPv6 loopback
	// in any case (lp:1644009). Review.
	local := net.JoinHostPort("localhost", strconv.Itoa(ssi.StatePort))
	addrs := []string{local}

	for _, addr := range c.apiDetails.addresses {
		host, _, err := net.SplitHostPort(addr)
		if err != nil {
			return nil, false
		}
		if host := net.JoinHostPort(host, strconv.Itoa(ssi.StatePort)); host != local {
			addrs = append(addrs, host)
		}
	}
	return &mongo.MongoInfo{
		Info: mongo.Info{
			Addrs:  addrs,
			CACert: c.caCert,
		},
		Password: c.statePassword,
		Tag:      c.tag,
	}, true
}
1294488
func (natsOpts *NatsOptions) Connect() (natsObj *Nats, err error) {
	if len(natsOpts.Name) == 0 {
		panic("Must set Name in NatsOptions")
	}
	con, err := natsOpts.Options.Connect()
	if err != nil {
		return
	}

	natsObj = &Nats{Opts: natsOpts}

	natsObj.EncCon, err = nats.NewEncodedConn(con, natsOpts.encoding)
	return
}
1334840
func CreateMongoDB(uri, db, coll string) *MongoDB {
	log.Printf("Connecting to MongoDB: %s\n", uri)
	session, err := mgo.Dial(uri)
	if err != nil {
		log.Printf("Error connecting to MongoDB: %s", err)
		return nil
	}
	err = session.DB(db).C(coll).EnsureIndexKey("created")
	if err != nil {
		log.Printf("Failed creating index: %s", err)
		return nil
	}
	return &MongoDB{
		Session:    session,
		Collection: session.DB(db).C(coll),
	}
}
852873
func (cp *ConnectionPool) connect() (pools.Resource, error) {
	c, err := NewDBConnection(cp.info, cp.mysqlStats)
	if err != nil {
		return nil, err
	}
	return &PooledDBConnection{
		DBConnection: c,
		pool:         cp,
	}, nil
}
11588
func (c *socks5MuxBindConnector) Connect(conn net.Conn, addr string, options ...ConnectOption) (net.Conn, error) {
	accepter, ok := conn.(Accepter)
	if !ok {
		return nil, errors.New("wrong connection type")
	}

	return accepter.Accept()
}
667864
func (db *Database) Connect(ctx context.Context) error {
	if err := db.auth.Setup(ctx, db); err != nil {
		return err
	}
	if _, err := db.Send(ctx, &requests.CurrentDatabase{}); err != nil {
		return err
	}
	return nil
}
716839
func (pc *ProtoClient) ConnectTo(addr string) error {
	err := pc.Client.ConnectTo(addr)
	if err != nil {
		return err
	}

	if !pc.ready {
		err = pc.LoadServerInfo(addr)
		if err != nil {
			return err
		}
	}

	if pc.ready {
		go pc.waitForData()
	}
	return nil
}
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
}
371981
func (l *Adaptor) Connect() (err error) {
	ws, e := l.connect(l.Port())
	if e != nil {
		return e
	}

	l.ws = ws
	return
}
204407
func MongoDB(ctx context.Context) (*mgo.Session, bool) {
	key := mongodb(mongoDBName)
	session, ok := ctx.Value(key).(*mgo.Session)
	return session, ok
}
783460
func (c *stdClient) connect() {
	c.lock.Lock()
	defer c.lock.Unlock()

	auth := c.cluster.auth

	config := &gocbcore.AgentConfig{
		UserString:           "gocb/" + Version(),
		ConnectTimeout:       c.cluster.sb.ConnectTimeout,
		UseMutationTokens:    c.state.UseMutationTokens,
		ServerConnectTimeout: 7000 * time.Millisecond,
		NmvRetryDelay:        100 * time.Millisecond,
		UseKvErrorMaps:       true,
		UseDurations:         true,
		NoRootTraceSpans:     true,
		UseCollections:       true,
		UseEnhancedErrors:    true,
	}

	err := config.FromConnStr(c.cluster.connSpec().String())
	if err != nil {
		c.bootstrapErr = err
	}

	useCertificates := config.TlsConfig != nil && len(config.TlsConfig.Certificates) > 0
	if useCertificates {
		if auth == nil {
			c.bootstrapErr = configurationError{message: "invalid mixed authentication configuration, client certificate and CertAuthenticator must be used together"}
		}
		_, ok := auth.(CertAuthenticator)
		if !ok {
			c.bootstrapErr = configurationError{message: "invalid mixed authentication configuration, client certificate and CertAuthenticator must be used together"}
		}
	}

	_, ok := auth.(CertAuthenticator)
	if ok && !useCertificates {
		c.bootstrapErr = configurationError{message: "invalid mixed authentication configuration, client certificate and CertAuthenticator must be used together"}
	}

	config.BucketName = c.state.BucketName
	config.UseMutationTokens = c.state.UseMutationTokens
	config.Auth = &coreAuthWrapper{
		auth:       c.cluster.authenticator(),
		bucketName: c.state.BucketName,
	}

	agent, err := gocbcore.CreateAgent(config)
	if err != nil {
		c.bootstrapErr = maybeEnhanceErr(err, "")
	}

	c.agent = agent
}
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
}
768330
func (c *Client) Connect(host string, port uint) (err error) {
	return c.dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
}
876216
func (connection *VSphereConnection) Connect(ctx context.Context) error {
	var err error
	clientLock.Lock()
	defer clientLock.Unlock()

	if connection.Client == nil {
		connection.Client, err = connection.NewClient(ctx)
		if err != nil {
			klog.Errorf("Failed to create govmomi client. err: %+v", err)
			return err
		}
		return nil
	}
	m := session.NewManager(connection.Client)
	userSession, err := m.UserSession(ctx)
	if err != nil {
		klog.Errorf("Error while obtaining user session. err: %+v", err)
		return err
	}
	if userSession != nil {
		return nil
	}
	klog.Warningf("Creating new client session since the existing session is not valid or not authenticated")

	connection.Client, err = connection.NewClient(ctx)
	if err != nil {
		klog.Errorf("Failed to create govmomi client. err: %+v", err)
		return err
	}
	return nil
}