// All ConnStats that include this connection. Some objects are not known
// until the handshake is complete, after which it's expected to reconcile the
// differences.
484266
func (cn *connection) allStats(f func(*ConnStats)) {
	f(&cn.stats)
	if cn.reconciledHandshakeStats {
		cn.postHandshakeStats(f)
	}
}
1076557
func (pn *peernet) allConns() []*conn {
	pn.RLock()
	var cs []*conn
	for _, csl := range pn.connsByPeer {
		for c := range csl {
			cs = append(cs, c)
		}
	}
	pn.RUnlock()
	return cs
}
1249883
func (s *Store) checkConnections() {
	s.wg.Add(1)
	ticker := time.NewTicker(s.connPollPeriod)
	go func() {
		defer s.wg.Done()
		defer ticker.Stop()
		for {
			select {
			case <-s.done:
				return
			case <-ticker.C:
				// This is not a 100% correct check, but is right almost all
				// the time, and saves the node from most unneeded network
				// access. Read https://github.com/rqlite/rqlite/issues/5
				if !s.IsLeader() {
					continue
				}

				var conns []*Connection
				s.connsMu.RLock()
				for _, c := range s.conns {
					// Sometimes IDs are in the slice without a connection, if a
					// connection is in process of being formed via consensus.
					if c == nil || c.ID == defaultConnID {
						continue
					}
					if c.IdleTimedOut() || c.TxTimedOut() {
						conns = append(conns, c)
					}
				}
				s.connsMu.RUnlock()

				for _, c := range conns {
					if err := c.Close(); err != nil {
						if err == ErrNotLeader {
							// Not an issue, the actual leader will close it.
							continue
						}
						s.logger.Printf("%s failed to close: %s", c, err.Error())
					}
					s.logger.Printf("%s closed due to timeout", c)
					// Only increment stat here to make testing easier.
					stats.Add(numConnTimeouts, 1)
				}
			}
		}
	}()
}
914363
func (f *PeerEventsFilter) Connect() *PeerEventsFilter {
	f.eventType = simulations.EventTypeConn
	b := true
	f.connUp = &b
	return f
}
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
}
572444
func newParsedConnection(namespace, suffix, hubName, keyName, key string) *ParsedConn {
	return &ParsedConn{
		Host:      "amqps://" + namespace + "." + suffix,
		Suffix:    suffix,
		Namespace: namespace,
		KeyName:   keyName,
		Key:       key,
		HubName:   hubName,
	}
}
808934
func (h *ConnectionsStatsHandler) HandleConn(ctx context.Context, stat stats.ConnStats) {
	lab, _ := ctx.Value(tagConnKey).(prometheus.Labels)

	switch stat.(type) {
	case *stats.ConnBegin:
		switch {
		case stat.IsClient() && h.subsystem == Client:
			h.vec.With(lab).Inc()
		case !stat.IsClient() && h.subsystem == Server:
			h.vec.With(lab).Inc()
		}
	case *stats.ConnEnd:
		switch {
		case stat.IsClient() && h.subsystem == Client:
			h.vec.With(lab).Dec()
		case !stat.IsClient() && h.subsystem == Server:
			h.vec.With(lab).Dec()
		}
	}
}
273529
func (st *State) OfferConnections(offerUUID string) (conns []*OfferConnection, err error) {
	offerConnectionCollection, closer := st.db().GetCollection(offerConnectionsC)
	defer closer()

	connDocs := []offerConnectionDoc{}
	err = offerConnectionCollection.Find(bson.D{{"offer-uuid", offerUUID}}).All(&connDocs)
	if err != nil {
		return nil, errors.Errorf("cannot get the offer connections for %v", offerUUID)
	}
	for _, v := range connDocs {
		conns = append(conns, newOfferConnection(st, &v))
	}
	return conns, nil
}
1184600
func (cm *ConnManager) Connect(c *ConnReq) {
	if atomic.LoadInt32(&cm.stop) != 0 {
		return
	}

	// During the time we wait for retry there is a chance that
	// this connection was already cancelled
	if c.State() == ConnCanceled {
		log.Debugf("Ignoring connect for canceled connreq=%v", c)
		return
	}

	if atomic.LoadUint64(&c.id) == 0 {
		atomic.StoreUint64(&c.id, atomic.AddUint64(&cm.connReqCount, 1))

		// Submit a request of a pending connection attempt to the
		// connection manager. By registering the id before the
		// connection is even established, we'll be able to later
		// cancel the connection via the Remove method.
		done := make(chan struct{})
		select {
		case cm.requests <- registerPending{c, done}:
		case <-cm.quit:
			return
		}

		// Wait for the registration to successfully add the pending
		// conn req to the conn manager's internal state.
		select {
		case <-done:
		case <-cm.quit:
			return
		}
	}

	log.Debugf("Attempting to connect to %v", c)

	conn, err := cm.cfg.Dial(c.Addr)
	if err != nil {
		select {
		case cm.requests <- handleFailed{c, err}:
		case <-cm.quit:
		}
		return
	}

	select {
	case cm.requests <- handleConnected{c, conn}:
	case <-cm.quit:
	}
}
849257
func OnConnect(c websocket.Connection) {
	fmt.Println("socket.OnConnect()")
	c.On("join", func(message string) { OnJoin(message, c) })
	c.On("objectupdate", func(message string) { OnObjectUpdated(message, c) })
	// ok works too c.EmitMessage([]byte("dsadsa"))
	c.OnDisconnect(func() { OnDisconnect(c) })

}
819944
func Connect(config ConnConfig) (c *Conn, err error) {
	return connect(config, minimalConnInfo)
}
290136
func (c connector) Connect(ctx context.Context) (driver.Conn, error) {
	var (
		err  error
		conn *pgx.Conn
	)

	if conn, err = pgx.Connect(c.ConnConfig); err != nil {
		return nil, err
	}

	if err = c.AfterConnect(conn); err != nil {
		return nil, err
	}

	return &Conn{conn: conn, driver: c.driver, connConfig: c.ConnConfig}, nil
}
96549
func (client *Client) WrapConnection(wrapper ConnectionWrapper) {
	client.connection = wrapper.Wrap(client.connection)
}
23726
func (c *Cache) GetAllTunnelConnections(opts ...services.MarshalOption) (conns []services.TunnelConnection, err error) {
	return c.presenceCache.GetAllTunnelConnections(opts...)
}
176799
func (s *Server) HandleConnection(conn net.Conn) {
	s.trackConnections(1)
	defer s.trackConnections(-1)
	// initiate an SSH connection, note that we don't need to close the conn here
	// in case of error as ssh server takes care of this
	remoteAddr, _, err := net.SplitHostPort(conn.RemoteAddr().String())
	if err != nil {
		log.Errorf(err.Error())
	}
	if err := s.limiter.AcquireConnection(remoteAddr); err != nil {
		log.Errorf(err.Error())
		conn.Close()
		return
	}
	defer s.limiter.ReleaseConnection(remoteAddr)

	// apply idle read/write timeout to this connection.
	conn = utils.ObeyIdleTimeout(conn,
		defaults.DefaultIdleConnectionDuration,
		s.component)

	// Wrap connection with a tracker used to monitor how much data was
	// transmitted and received over the connection.
	wconn := utils.NewTrackingConn(conn)

	// create a new SSH server which handles the handshake (and pass the custom
	// payload structure which will be populated only when/if this connection
	// comes from another Teleport proxy):
	sconn, chans, reqs, err := ssh.NewServerConn(wrapConnection(wconn), &s.cfg)
	if err != nil {
		conn.SetDeadline(time.Time{})
		return
	}

	user := sconn.User()
	if err := s.limiter.RegisterRequest(user); err != nil {
		log.Errorf(err.Error())
		sconn.Close()
		conn.Close()
		return
	}
	// Connection successfully initiated
	s.Debugf("Incoming connection %v -> %v vesion: %v.",
		sconn.RemoteAddr(), sconn.LocalAddr(), string(sconn.ClientVersion()))

	// will be called when the connection is closed
	connClosed := func() {
		s.Debugf("Closed connection %v.", sconn.RemoteAddr())
	}

	// The keepalive ticket will ensure that SSH keepalive requests are being sent
	// to the client at an interval much shorter than idle connection kill switch
	keepAliveTick := time.NewTicker(defaults.DefaultIdleConnectionDuration / 3)
	defer keepAliveTick.Stop()
	keepAlivePayload := [8]byte{0}

	for {
		select {
		// handle out of band ssh requests
		case req := <-reqs:
			if req == nil {
				connClosed()
				return
			}
			s.Debugf("Received out-of-band request: %+v.", req)
			if s.reqHandler != nil {
				go s.reqHandler.HandleRequest(req)
			}
			// handle channels:
		case nch := <-chans:
			if nch == nil {
				connClosed()
				return
			}
			go s.newChanHandler.HandleNewChan(wconn, sconn, nch)
			// send keepalive pings to the clients
		case <-keepAliveTick.C:
			const wantReply = true
			sconn.SendRequest(teleport.KeepAliveReqType, wantReply, keepAlivePayload[:])
		}
	}
}
78830
func (c *Conn) Connect() error {
	ret := C.rados_connect(c.cluster)
	if ret != 0 {
		return RadosError(int(ret))
	}
	c.connected = true
	return nil
}
922657
func (s *Session) UserConnections() (conn []*UserConnection, err error) {
	response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"))
	if err != nil {
		return nil, err
	}

	err = unmarshal(response, &conn)
	if err != nil {
		return
	}

	return
}