// NewKazoo creates a new connection instance
358851
func NewKazoo(servers []string, conf *Config) (*Kazoo, error) {
	if conf == nil {
		conf = NewConfig()
	}

	conn, _, err := zk.Connect(
		servers,
		conf.Timeout,
		func(c *zk.Conn) { c.SetLogger(conf.Logger) },
	)

	if err != nil {
		return nil, err
	}
	return &Kazoo{conn, conf}, nil
}
19602
func NewDBConn(
	cp *Pool,
	appParams *mysql.ConnParams) (*DBConn, error) {
	c, err := dbconnpool.NewDBConnection(appParams, tabletenv.MySQLStats)
	if err != nil {
		cp.checker.CheckMySQL()
		return nil, err
	}
	return &DBConn{
		conn:    c,
		info:    appParams,
		pool:    cp,
		dbaPool: cp.dbaPool,
	}, nil
}
985742
func NewRedisPool(connstr string) (*redis.Pool, error) {

	u, err := url.Parse(connstr)
	if err != nil {
		return nil, err
	}

	// auth if necessary
	passwd := ""
	if u.User != nil {
		passwd, _ = u.User.Password()
	}

	pool := newPool(u.Host, passwd)

	return pool, nil
}
1106693
func (db *DB) NewConnection(c *mysql.Conn) {
	db.mu.Lock()
	defer db.mu.Unlock()

	if db.t != nil {
		db.t.Logf("NewConnection(%v): client %v", db.name, c.ConnectionID)
	}

	if db.isConnFail {
		panic(fmt.Errorf("simulating a connection failure"))
	}

	if db.connDelay != 0 {
		time.Sleep(db.connDelay)
	}

	if conn, ok := db.connections[c.ConnectionID]; ok {
		db.t.Fatalf("BUG: connection with id: %v is already active. existing conn: %v new conn: %v", c.ConnectionID, conn, c)
	}
	db.connections[c.ConnectionID] = c
}
1127975
func newConnection(db *Database) (*Connection, error) {
	conn := &Connection{
		database: db,
	}
	err := conn.ensureProtocol()
	if err != nil {
		return nil, err
	}
	// Perform authentication and database selection.
	err = conn.resp.authenticate()
	if err != nil {
		conn.database.pool.kill(conn.resp)
		return nil, err
	}
	err = conn.resp.selectDatabase()
	if err != nil {
		conn.database.pool.kill(conn.resp)
		return nil, err
	}
	return conn, nil
}
1323966
func newDBConn(ops Options) (*ScyllaDB, error) {
	r, err := newScyllaDB(ScyllaDBOpts{
		KeySpaceName: ops.Keyspace,
		NodeIps:      ops.Hosts,
		Username:     ops.Username,
		Password:     ops.Password,
		Debug:        true,
	})
	if err != nil {
		return nil, err
	}
	return r, nil
}
523707
func New() *Cache {
	return &Cache{
		nlocker: locker.NewLocker(),
		cache:   make(map[string]cacheEntry),
	}
}
1094512
func NewConn(c net.Conn) net.Conn {
	return NewConnWith(stats.DefaultEngine, c)
}
225298
func NewNamespacedKV(db *Lowlevel, prefix string) *NamespacedKV {
	prefixBs := []byte(prefix)
	// After the conversion from string the cap will be larger than the len (in Go 1.11.5,
	// 32 bytes cap for small strings). We need to cut it down to ensure append() calls
	// on the prefix make a new allocation.
	prefixBs = prefixBs[:len(prefixBs):len(prefixBs)]
	return &NamespacedKV{
		db:     db,
		prefix: prefixBs,
	}
}
210522
func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
	if err != nil {
		return accounts.Account{}, err
	}
	// Add the account to the cache immediately rather
	// than waiting for file system notifications to pick it up.
	ks.cache.add(account)
	ks.refreshWallets()
	return account, nil
}
257122
func newDbConn(mdb *MemDb) *dbConn {
	c := &dbConn{md: mdb, db: mdb.db}
	return c
}
537888
func NewLobby(mapName string, lobbyType format.Format, league string, serverInfo gameserver.ServerRecord, whitelist string, mumble bool, whitelistGroup string) *Lobby {
	lobby := &Lobby{
		Mode:            getGamemode(mapName, lobbyType),
		Type:            lobbyType,
		State:           Initializing,
		League:          league,
		MapName:         mapName,
		Whitelist:       whitelist, // that's a strange line
		Mumble:          mumble,
		ServerInfo:      serverInfo,
		PlayerWhitelist: whitelistGroup,
		RedTeamName:     "Red",
		BluTeamName:     "Blu",
	}

	// Must specify CreatedBy manually if the lobby is created by a player
	return lobby
}
35142
func NewConnPool(config ConnPoolConfig) (p *ConnPool, err error) {
	p = new(ConnPool)
	p.config = config.ConnConfig
	p.connInfo = minimalConnInfo
	p.maxConnections = config.MaxConnections
	if p.maxConnections == 0 {
		p.maxConnections = 5
	}
	if p.maxConnections < 1 {
		return nil, errors.New("MaxConnections must be at least 1")
	}
	p.acquireTimeout = config.AcquireTimeout
	if p.acquireTimeout < 0 {
		return nil, errors.New("AcquireTimeout must be equal to or greater than 0")
	}

	p.afterConnect = config.AfterConnect

	if config.LogLevel != 0 {
		p.logLevel = config.LogLevel
	} else {
		// Preserve pre-LogLevel behavior by defaulting to LogLevelDebug
		p.logLevel = LogLevelDebug
	}
	p.logger = config.Logger
	if p.logger == nil {
		p.logLevel = LogLevelNone
	}

	p.allConnections = make([]*Conn, 0, p.maxConnections)
	p.availableConnections = make([]*Conn, 0, p.maxConnections)
	p.preparedStatements = make(map[string]*PreparedStatement)
	p.cond = sync.NewCond(new(sync.Mutex))

	// Initially establish one connection
	var c *Conn
	c, err = p.createConnection()
	if err != nil {
		return
	}
	p.allConnections = append(p.allConnections, c)
	p.availableConnections = append(p.availableConnections, c)
	p.connInfo = c.ConnInfo.DeepCopy()

	return
}
746163
func NewConnection(config ConnectionConfig, connectionBuilder ServerConnectionBuilder, endpoints []string) (driver.Connection, error) {
	if connectionBuilder == nil {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "Must a connection builder"})
	}
	if len(endpoints) == 0 {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "Must provide at least 1 endpoint"})
	}
	if config.DefaultTimeout == 0 {
		config.DefaultTimeout = defaultTimeout
	}
	cConn := &clusterConnection{
		connectionBuilder: connectionBuilder,
		defaultTimeout:    config.DefaultTimeout,
	}
	// Initialize endpoints
	if err := cConn.UpdateEndpoints(endpoints); err != nil {
		return nil, driver.WithStack(err)
	}
	return cConn, nil
}
666159
func NewKamEvapiPool(maxconns int, kamAddr, connId string, reconnects int, l *log.Logger) (*KamEvapiPool, error) {
	pool := &KamEvapiPool{kamAddr: kamAddr, connId: connId, reconnects: reconnects, logger: l}
	pool.allowedConns = make(chan struct{}, maxconns)
	var emptyConn struct{}
	for i := 0; i < maxconns; i++ {
		pool.allowedConns <- emptyConn // Empty initiate so we do not need to wait later when we pop
	}
	pool.conns = make(chan *KamEvapi, maxconns)
	return pool, nil
}
692953
func (cp *connProducer) NewConnection() (*grpc.ClientConn, string, error) {
	cp.Lock()
	defer cp.Unlock()

	for endpoint, timeout := range cp.disabledEndpoints {
		if time.Since(timeout) >= EndpointDisableInterval {
			delete(cp.disabledEndpoints, endpoint)
		}
	}

	endpoints := shuffle(cp.endpoints)
	checkedEndpoints := make([]string, 0)
	for _, endpoint := range endpoints {
		if _, ok := cp.disabledEndpoints[endpoint]; !ok {
			checkedEndpoints = append(checkedEndpoints, endpoint)
			conn, err := cp.connect(endpoint)
			if err != nil {
				logger.Error("Failed connecting to", endpoint, ", error:", err)
				continue
			}
			return conn, endpoint, nil
		}
	}
	return nil, "", fmt.Errorf("Could not connect to any of the endpoints: %v", checkedEndpoints)
}
1322932
func New(zkConnCreator ZkConnCreator, publishAddress string, config *Config) (*Disco, error) {
	conf := pointer.FillDefaultFrom(config, DefaultConfig).(*Config)
	var GUID [16]byte
	_, err := io.ReadFull(conf.RandomSource, GUID[:16])
	if err != nil {
		return nil, errors.Annotate(err, "cannot create random GUID")
	}

	d := &Disco{
		zkConnCreator:        zkConnCreator,
		myAdvertisedServices: make(map[string]ServiceInstance),
		myEphemeralNodes:     make(map[string][]byte),
		GUIDbytes:            GUID,
		jsonMarshal:          json.Marshal,
		publishAddress:       publishAddress,
		shouldQuit:           make(chan struct{}),
		eventLoopDone:        make(chan struct{}),
		watchedServices:      make(map[string]*Service),
		manualEvents:         make(chan zk.Event),
	}
	d.stateLog = log.NewContext(conf.Logger).With(logkey.GUID, d.GUID())
	d.zkConn, d.eventChan, err = zkConnCreator.Connect()
	if err != nil {
		return nil, errors.Annotate(err, "cannot create first zk connection")
	}
	go d.eventLoop()
	return d, nil
}