// Setup the MongoDB connection based on passed in config. It can be called multiple times to setup connection to
// multiple MongoDB instances.
329828
func Setup(dbConfig DbConfig) error {
	log.Println("Connecting to MongoDB...")
	if dbConfig.Hosts == nil && dbConfig.HostURL == "" && dbConfig.DBName == "" {
		return errors.New("Invalid connection info. Missing host and db info")
	}

	var session *mgo.Session
	var err error
	if dbConfig.Hosts != nil && dbConfig.DBName != "" {
		mongoDBDialInfo := &mgo.DialInfo{
			Addrs:    dbConfig.Hosts,
			Timeout:  10 * time.Second,
			Database: dbConfig.DBName,
			Username: dbConfig.UserName,
			Password: dbConfig.Password,
		}
		session, err = mgo.DialWithInfo(mongoDBDialInfo)
	} else {
		session, err = mgo.DialWithTimeout(dbConfig.HostURL, 10*time.Second)
	}

	if err != nil {
		log.Printf("MongoDB connection failed : %s. Exiting the program.\n", err)
		return err
	}

	//starting with primary preferred, but individual query can change mode per copied session
	session.SetMode(mgo.Strong, true)
	log.Println("Connected to MongoDB successfully")

	/* Initialized database object with global session*/
	connectionMap[dbConfig.DBName] = Db{mainSession: session, Config: dbConfig}

	return nil
}
165585
func (c *mongoDBConnectionProducer) Connection(_ context.Context) (interface{}, error) {
	if !c.Initialized {
		return nil, connutil.ErrNotInitialized
	}

	if c.session != nil {
		if err := c.session.Ping(); err == nil {
			return c.session, nil
		}
		c.session.Close()
	}

	dialInfo, err := parseMongoURL(c.ConnectionURL)
	if err != nil {
		return nil, err
	}

	c.session, err = mgo.DialWithInfo(dialInfo)
	if err != nil {
		return nil, err
	}

	if c.safe != nil {
		c.session.SetSafe(c.safe)
	}

	c.session.SetSyncTimeout(1 * time.Minute)
	c.session.SetSocketTimeout(1 * time.Minute)

	return c.session, nil
}
550468
func (gm *serverMethod) setup(apiDef *raml.APIDefinition, r *raml.Resource, rd *resource.Resource, methodName string) error {
	gm.MethodName = strings.Title(serverMethodName(gm.Endpoint, gm.DisplayName, methodName, rd.Name))

	// setting middlewares
	middlewares := []string{}

	// security middlewares
	for _, v := range gm.SecuredBy {
		if !security.ValidateScheme(v.Name, apiDef) {
			continue
		}
		// oauth2 middleware
		m, err := getOauth2MwrHandler(v)
		if err != nil {
			return err
		}
		middlewares = append(middlewares, m)
	}

	gm.Middlewares = strings.Join(middlewares, ", ")

	return nil
}
919314
func SetUp(c *Config) *bot.Bot {
	config = c

	ircConn = ircevent.IRC(c.User, c.Nick)
	ircConn.RealName = c.RealName
	ircConn.Password = c.Password
	ircConn.UseTLS = c.UseTLS
	ircConn.TLSConfig = &tls.Config{
		ServerName: getServerName(c.Server),
	}
	ircConn.VerboseCallbackHandler = c.Debug

	b = bot.New(&bot.Handlers{
		Response: responseHandler,
	},
		&bot.Config{
			Protocol: protocol,
			Server:   c.Server,
		},
	)

	ircConn.AddCallback("001", onWelcome)
	ircConn.AddCallback("PRIVMSG", onPRIVMSG)
	ircConn.AddCallback("CTCP_ACTION", onCTCPACTION)

	return b
}
515653
func (conn *Connection) SetConfig(section string,
	option string, value string, auth Auth) error {
	url, err := buildUrl("_node/_local/_config", section, option)
	if err != nil {
		return err
	}
	body := strings.NewReader("\"" + value + "\"")
	resp, err := conn.request("PUT", url, body, nil, auth)
	if err == nil {
		resp.Body.Close()
	}
	return err
}
1130905
func Connect() (err error) {
	if config.GUnitTestingEnv {
		err = connectToDB(config.GAppName+"_test", config.GAppName+"_test", config.GAppName+"_test", "localhost")
	} else if _, ok := syscall.Getenv("DYNO"); ok {
		err = connectToDB(os.Getenv("DB_USER"), os.Getenv("DB_NAME"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"))
	} else if config.GDevEnv {
		err = connectToDB(config.GAppName, config.GAppName, config.GAppName, "db")
	}
	if err != nil {
		log.Panic("Database status: [Failed to connect]", err)
	}
	return
}
1155836
func (db *DB) putConn(dc *driverConn, err error) {
	db.mu.Lock()
	if !dc.inUse {
		if debugGetPut {
			fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
		}
		panic("sql: connection returned that was never out")
	}
	if debugGetPut {
		db.lastPut[dc] = stack()
	}
	dc.inUse = false

	for _, fn := range dc.onPut {
		fn()
	}
	dc.onPut = nil

	if err == driver.ErrBadConn {
		// Don't reuse bad connections.
		// Since the conn is considered bad and is being discarded, treat it
		// as closed. Don't decrement the open count here, finalClose will
		// take care of that.
		db.maybeOpenNewConnections()
		db.mu.Unlock()
		dc.Close()
		return
	}
	if putConnHook != nil {
		putConnHook(db, dc)
	}
	added := db.putConnDBLocked(dc, nil)
	db.mu.Unlock()

	if !added {
		dc.Close()
	}
}
313688
func Setup(allowPrivileged bool, privilegedSources PrivilegedSources, perConnectionBytesPerSec int64) {
	Initialize(Capabilities{
		AllowPrivileged:                        allowPrivileged,
		PrivilegedSources:                      privilegedSources,
		PerConnectionBandwidthLimitBytesPerSec: perConnectionBytesPerSec,
	})
}
456394
func setupNetwork(conn *libvirt.Connect, name string) error {
	n, err := conn.LookupNetworkByName(name)
	if err != nil {
		return errors.Wrapf(err, "checking network %s", name)
	}

	// always ensure autostart is set on the network
	autostart, err := n.GetAutostart()
	if err != nil {
		return errors.Wrapf(err, "checking network %s autostart", name)
	}
	if !autostart {
		if err := n.SetAutostart(true); err != nil {
			return errors.Wrapf(err, "setting autostart for network %s", name)
		}
	}

	// always ensure the network is started (active)
	active, err := n.IsActive()
	if err != nil {
		return errors.Wrapf(err, "checking network status for %s", name)
	}
	if !active {
		if err := n.Create(); err != nil {
			return errors.Wrapf(err, "starting network %s", name)
		}
	}

	return nil
}
1004210
func Configure() *Config {
	switch cfg.StorageType {
	case "memory":
		log.Println("Using in-memory storage")
		cfg.Storage = storage.CreateInMemory()
	case "mongodb":
		log.Println("Using MongoDB message storage")
		s := storage.CreateMongoDB(cfg.MongoURI, cfg.MongoDb, cfg.MongoColl)
		if s == nil {
			log.Println("MongoDB storage unavailable, reverting to in-memory storage")
			cfg.Storage = storage.CreateInMemory()
		} else {
			log.Println("Connected to MongoDB")
			cfg.Storage = s
		}
	case "maildir":
		log.Println("Using maildir message storage")
		s := storage.CreateMaildir(cfg.MaildirPath)
		cfg.Storage = s
	default:
		log.Fatalf("Invalid storage type %s", cfg.StorageType)
	}

	Jim.Configure(func(message string, args ...interface{}) {
		log.Printf(message, args...)
	})
	if cfg.InviteJim {
		cfg.Monkey = Jim
	}

	if len(cfg.OutgoingSMTPFile) > 0 {
		b, err := ioutil.ReadFile(cfg.OutgoingSMTPFile)
		if err != nil {
			log.Fatal(err)
		}
		var o map[string]*OutgoingSMTP
		err = json.Unmarshal(b, &o)
		if err != nil {
			log.Fatal(err)
		}
		cfg.OutgoingSMTP = o
	}

	return cfg
}
399868
func setupNetwork(config *initConfig) error {
	for _, config := range config.Networks {
		strategy, err := getStrategy(config.Type)
		if err != nil {
			return err
		}
		if err := strategy.initialize(config); err != nil {
			return err
		}
	}
	return nil
}
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
}
130411
func setup(c *caddy.Controller) error {
	configs, err := mimeParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Mime{Next: next, Configs: configs}
	})

	return nil
}
424916
func Init() {
	// Read configuration.
	var found bool
	if Driver, found = revel.Config.String("db.driver"); !found {
		revel.RevelLog.Fatal("db.driver not configured")
	}
	if Spec, found = revel.Config.String("db.spec"); !found {
		revel.RevelLog.Fatal("db.spec not configured")
	}

	// Open a connection.
	var err error
	Db, err = sql.Open(Driver, Spec)
	if err != nil {
		revel.RevelLog.Fatal("Open database connection error", "error", err, "driver", Driver, "spec", Spec)
	}

	revel.OnAppStop(func() {
		revel.RevelLog.Info("Closing the database (from module)")
		if err := Db.Close(); err != nil {
			revel.AppLog.Error("Failed to close the database", "error", err)
		}
	})
}
1339525
func (n *natsStreamingRequester) Setup() error {
	conn, err := stan.Connect("test-cluster", fmt.Sprintf("%s-%d", n.clientID, time.Now().UnixNano()), stan.NatsURL(n.url))
	if err != nil {
		return err
	}
	n.msgChan = make(chan []byte)
	sub, err := conn.Subscribe(n.subject, func(msg *stan.Msg) {
		n.msgChan <- msg.Data
	})
	if err != nil {
		conn.Close()
		return err
	}
	n.conn = conn
	n.sub = sub
	n.msg = make([]byte, n.payloadSize)
	for i := 0; i < n.payloadSize; i++ {
		n.msg[i] = 'A' + uint8(rand.Intn(26))
	}
	return nil
}
40792
func Setup(c config.Config) error {
	log.Info("storage: setting up storage module")

	deviceSessionTTL = c.NetworkServer.DeviceSessionTTL
	schedulerInterval = c.NetworkServer.Scheduler.SchedulerInterval

	log.Info("storage: setting up Redis connection pool")
	redisPool = &redis.Pool{
		MaxIdle:     10,
		IdleTimeout: c.Redis.IdleTimeout,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialURL(c.Redis.URL,
				redis.DialReadTimeout(redisDialReadTimeout),
				redis.DialWriteTimeout(redisDialWriteTimeout),
			)
			if err != nil {
				return nil, fmt.Errorf("redis connection error: %s", err)
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Now().Sub(t) < onBorrowPingInterval {
				return nil
			}

			_, err := c.Do("PING")
			if err != nil {
				return fmt.Errorf("ping redis error: %s", err)
			}
			return nil
		},
	}

	log.Info("storage: connecting to PostgreSQL")
	d, err := sqlx.Open("postgres", c.PostgreSQL.DSN)
	if err != nil {
		return errors.Wrap(err, "storage: PostgreSQL connection error")
	}
	for {
		if err := d.Ping(); err != nil {
			log.WithError(err).Warning("storage: ping PostgreSQL database error, will retry in 2s")
			time.Sleep(2 * time.Second)
		} else {
			break
		}
	}

	db = &DBLogger{d}

	if c.PostgreSQL.Automigrate {
		log.Info("storage: applying PostgreSQL data migrations")
		m := &migrate.AssetMigrationSource{
			Asset:    migrations.Asset,
			AssetDir: migrations.AssetDir,
			Dir:      "",
		}
		n, err := migrate.Exec(db.DB.DB, "postgres", m, migrate.Up)
		if err != nil {
			return errors.Wrap(err, "storage: applying PostgreSQL data migrations error")
		}
		log.WithField("count", n).Info("storage: PostgreSQL data migrations applied")
	}

	return nil
}
919645
func (db *Database) Connection() (*Connection, error) {
	db.mux.Lock()
	defer db.mux.Unlock()
	return newConnection(db)
}