// Initialize the database from revel.Config
671
func InitDb(dbResult *DbGorp) error {
	params := DbInfo{}
	params.DbDriver = revel.Config.StringDefault("db.driver", "sqlite3")
	params.DbHost = revel.Config.StringDefault("db.host", "localhost")
	if params.DbDriver == "sqlite3" && params.DbHost == "localhost" {
		params.DbHost = "/tmp/app.db"
	}
	params.DbUser = revel.Config.StringDefault("db.user", "default")
	params.DbPassword = revel.Config.StringDefault("db.password", "")
	params.DbName = revel.Config.StringDefault("db.name", "default")
	params.DbConnection = revel.Config.StringDefault("db.connection", "")
	params.DbSchema = revel.Config.StringDefault("db.schema", "")
	dbResult.Info = &params

	return dbResult.InitDb(true)
}
95449
func (s *configsService) Config(db *gorm.DB, app *App) (*Config, error) {
	r, err := releasesFind(db, ReleasesQuery{App: app})
	if err != nil {
		if err == gorm.RecordNotFound {
			// It's possible to have config without releases, this handles that.
			c, err := configsFind(db, ConfigsQuery{App: app})
			if err != nil {
				if err == gorm.RecordNotFound {
					// Return an empty config.
					return &Config{
						AppID: app.ID,
						App:   app,
						Vars:  make(Vars),
					}, nil
				}
				return nil, err
			}

			return c, nil
		}

		return nil, err
	}

	return r.Config, nil
}
744909
func (c *Controller) Begin() revel.Result {
	c.Db = gorp.Db
	txn, err := gorp.Db.Begin()
	if err != nil {
		panic(err.Error() + " Failed to establish database connection with " + c.Db.Info.DbConnection)
	}
	c.Txn = txn
	return nil
}
1035589
func (c *mongoDBConnectionProducer) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) {
	c.Lock()
	defer c.Unlock()

	c.RawConfig = conf

	err := mapstructure.WeakDecode(conf, c)
	if err != nil {
		return nil, err
	}

	if len(c.ConnectionURL) == 0 {
		return nil, fmt.Errorf("connection_url cannot be empty")
	}

	c.ConnectionURL = dbutil.QueryHelper(c.ConnectionURL, map[string]string{
		"username": c.Username,
		"password": c.Password,
	})

	if c.WriteConcern != "" {
		input := c.WriteConcern

		// Try to base64 decode the input. If successful, consider the decoded
		// value as input.
		inputBytes, err := base64.StdEncoding.DecodeString(input)
		if err == nil {
			input = string(inputBytes)
		}

		concern := &mgo.Safe{}
		err = json.Unmarshal([]byte(input), concern)
		if err != nil {
			return nil, errwrap.Wrapf("error mashalling write_concern: {{err}}", err)
		}

		// Guard against empty, non-nil mgo.Safe object; we don't want to pass that
		// into mgo.SetSafe in Connection().
		if (mgo.Safe{} == *concern) {
			return nil, fmt.Errorf("provided write_concern values did not map to any mgo.Safe fields")
		}
		c.safe = concern
	}

	// Set initialized to true at this point since all fields are set,
	// and the connection can be established at a later time.
	c.Initialized = true

	if verifyConnection {
		if _, err := c.Connection(ctx); err != nil {
			return nil, errwrap.Wrapf("error verifying connection: {{err}}", err)
		}

		if err := c.session.Ping(); err != nil {
			return nil, errwrap.Wrapf("error verifying connection: {{err}}", err)
		}
	}

	return conf, nil
}
488674
func New(cfg ...service.Config) *Database {
	db := &Database{redis: service.New(cfg...)}
	db.redis.Connect()
	_, err := db.redis.PingPong()
	if err != nil {
		log.Fatal(err)
		return nil
	}
	runtime.SetFinalizer(db, closeDB)
	return db
}
956397
func (c *ConnWriter) Init(config map[string]interface{}) error {
	conf, err := json.Marshal(config)
	if err != nil {
		return err
	}
	return json.Unmarshal(conf, c)
}
719280
func Init() {
	dbMutex.Lock()
	defer dbMutex.Unlock()

	if initialized {
		return
	}

	DBUrl = url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DbAddr,
		Path:     config.Constants.DbDatabase,
		RawQuery: "sslmode=disable",
	}

	logrus.Info("Connecting to DB on ", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DbUsername, config.Constants.DbPassword)

	var err error
	DB, err = gorm.Open("postgres", DBUrl.String())
	//	DB, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		logrus.Fatal(err.Error())
	}

	DB.SetLogger(logrus.StandardLogger())

	logrus.Info("Connected!")
	initialized = true
}
570475
func Open(dbPath string, modifiers ...OptionModifier) (*DB, error) {
	path := filepath.Join(dbPath, dbName)

	if !fileExists(path) {
		if err := createChannelDB(dbPath); err != nil {
			return nil, err
		}
	}

	opts := DefaultOptions()
	for _, modifier := range modifiers {
		modifier(&opts)
	}

	bdb, err := bbolt.Open(path, dbFilePermission, nil)
	if err != nil {
		return nil, err
	}

	chanDB := &DB{
		DB:     bdb,
		dbPath: dbPath,
	}
	chanDB.graph = newChannelGraph(
		chanDB, opts.RejectCacheSize, opts.ChannelCacheSize,
	)

	// Synchronize the version of database and apply migrations if needed.
	if err := chanDB.syncVersions(dbVersions); err != nil {
		bdb.Close()
		return nil, err
	}

	return chanDB, nil
}
1325349
func (s *Storage) Init() error {
	dbPath = s.config.Stat.LevelDB.Path
	return nil
}
1036797
func init() {
	DefaultCallback.Update().Register("gorm:assign_updating_attributes", assignUpdatingAttributesCallback)
	DefaultCallback.Update().Register("gorm:begin_transaction", beginTransactionCallback)
	DefaultCallback.Update().Register("gorm:before_update", beforeUpdateCallback)
	DefaultCallback.Update().Register("gorm:save_before_associations", saveBeforeAssociationsCallback)
	DefaultCallback.Update().Register("gorm:update_time_stamp", updateTimeStampForUpdateCallback)
	DefaultCallback.Update().Register("gorm:update", updateCallback)
	DefaultCallback.Update().Register("gorm:save_after_associations", saveAfterAssociationsCallback)
	DefaultCallback.Update().Register("gorm:after_update", afterUpdateCallback)
	DefaultCallback.Update().Register("gorm:commit_or_rollback_transaction", commitOrRollbackTransactionCallback)
}
1076498
func (db *MemDB) initialize() error {
	root := db.getRoot()
	for tName, tableSchema := range db.schema.Tables {
		for iName := range tableSchema.Indexes {
			index := iradix.New()
			path := indexPath(tName, iName)
			root, _, _ = root.Insert(path, index)
		}
	}
	db.root = unsafe.Pointer(root)
	return nil
}
253354
func Init() {
	if *ldapAuthConfigFile == "" && *ldapAuthConfigString == "" {
		log.Infof("Not configuring AuthServerLdap because mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are empty")
		return
	}
	if *ldapAuthConfigFile != "" && *ldapAuthConfigString != "" {
		log.Infof("Both mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are non-empty, can only use one.")
		return
	}
	if *ldapAuthMethod != mysql.MysqlClearPassword && *ldapAuthMethod != mysql.MysqlDialog {
		log.Exitf("Invalid mysql_ldap_auth_method value: only support mysql_clear_password or dialog")
	}
	ldapAuthServer := &AuthServerLdap{
		Client:       &ClientImpl{},
		ServerConfig: ServerConfig{},
		Method:       *ldapAuthMethod,
	}

	data := []byte(*ldapAuthConfigString)
	if *ldapAuthConfigFile != "" {
		var err error
		data, err = ioutil.ReadFile(*ldapAuthConfigFile)
		if err != nil {
			log.Exitf("Failed to read mysql_ldap_auth_config_file: %v", err)
		}
	}
	if err := json.Unmarshal(data, ldapAuthServer); err != nil {
		log.Exitf("Error parsing AuthServerLdap config: %v", err)
	}
	mysql.RegisterAuthServerImpl("ldap", ldapAuthServer)
}
1101078
func (a *Airport) init(config interface{}, doneChan chan struct{}) (err error) {
	a.log.Info("Airport redis example. If you need more info about what is happening, run example with -debug=true")

	rand.Seed(time.Now().UnixNano())

	printHeaders()
	setupFlightStatusFormat()

	// prepare client to connect to the redis DB
	a.client, err = redis.ConfigToClient(config)
	if err != nil {
		return fmt.Errorf("failed to create redis client: %v", err)
	}
	a.connection, err = redis.NewBytesConnection(a.client, a.log)
	if err != nil {
		return fmt.Errorf("failed to create connection from redis client: %v", err)
	}

	// prepare all the brokers and watchers in order to simulate airport
	a.arrivalBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.arrivalPrefix)
	a.arrivalWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.arrivalPrefix)

	a.departureBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.departurePrefix)
	a.departureWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.departurePrefix)

	a.hangarBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.hangarPrefix)
	a.hangarWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.hangarPrefix)

	a.cleanUp(false)

	// start watchers
	a.arrivalChan = make(chan datasync.ProtoWatchResp, flightSlots)
	if err := a.arrivalWatcher.Watch(keyval.ToChanProto(a.arrivalChan), nil, ""); err != nil {
		return fmt.Errorf("failed to start 'arrival' watcher: %v", err)
	}
	a.departureChan = make(chan datasync.ProtoWatchResp, flightSlots)
	if err := a.departureWatcher.Watch(keyval.ToChanProto(a.departureChan), nil, ""); err != nil {
		return fmt.Errorf("failed to start 'departure' watcher: %v", err)
	}
	a.hangarChan = make(chan datasync.ProtoWatchResp, hangarSlots)
	if err := a.hangarWatcher.Watch(keyval.ToChanProto(a.hangarChan), nil, ""); err != nil {
		return fmt.Errorf("failed to start 'hangar' watcher: %v", err)
	}
	a.runwayChan = make(chan flight.Info, flightSlots)

	return nil
}
1163044
func (db *database) Init(config *Config, logger *log.Logger) bool {
	db.mu.Lock()
	defer db.mu.Unlock()
	db.setError(errors.New("not intialized"))
	db.config = config
	db.log = logger
	if db.config.DBPath == "" {
		db.log.Printf("no database file specified")
		db.setError(errors.New("no database loaded"))
		return false
	}
	dbf, err := loadDatabase(db.config.DBPath)
	if err != nil {
		db.log.Printf("load failure: %v", err)
		db.setError(err)
		return false
	}
	// Validate that the database threat list stored on disk is not too stale.
	if db.isStale(dbf.Time) {
		db.log.Printf("database loaded is stale")
		db.ml.Lock()
		defer db.ml.Unlock()
		db.setStale()
		return false
	}
	// Validate that the database threat list stored on disk is at least a
	// superset of the specified configuration.
	tfuNew := make(threatsForUpdate)
	for _, td := range db.config.ThreatLists {
		if row, ok := dbf.Table[td]; ok {
			tfuNew[td] = row
		} else {
			db.log.Printf("database configuration mismatch, missing %v", td)
			db.setError(errors.New("database configuration mismatch"))
			return false
		}
	}
	db.tfu = tfuNew
	db.generateThreatsForLookups(dbf.Time)
	return true
}
948271
func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err error) {
	// First, clear the generated files (to avoid them messing with ProcessSource).
	cleanSource(paths, "tmp", "routes")

	sourceInfo, err := parser.ProcessSource(paths)
	if err != nil {
		return
	}

	// Add the db.import to the import paths.
	if dbImportPath, found := paths.Config.String("db.import"); found {
		sourceInfo.InitImportPaths = append(sourceInfo.InitImportPaths, strings.Split(dbImportPath, ",")...)
	}

	// Sort controllers so that file generation is reproducible
	controllers := sourceInfo.ControllerSpecs()
	sort.Stable(ByString(controllers))

	// Generate two source files.
	templateArgs := map[string]interface{}{
		"ImportPath":     paths.ImportPath,
		"Controllers":    controllers,
		"ValidationKeys": sourceInfo.ValidationKeys,
		"ImportPaths":    calcImportAliases(sourceInfo),
		"TestSuites":     sourceInfo.TestSuites(),
	}

	// Generate code for the main, run and routes file.
	// The run file allows external programs to launch and run the application
	// without being the main thread
	cleanSource(paths, "tmp", "routes")

	if err = genSource(paths, "tmp", "main.go", RevelMainTemplate, templateArgs); err != nil {
		return
	}
	if err = genSource(paths, filepath.Join("tmp", "run"), "run.go", RevelRunTemplate, templateArgs); err != nil {
		return
	}
	if err = genSource(paths, "routes", "routes.go", RevelRoutesTemplate, templateArgs); err != nil {
		return
	}

	// Read build config.
	buildTags := paths.Config.StringDefault("build.tags", "")

	// Build the user program (all code under app).
	// It relies on the user having "go" installed.
	goPath, err := exec.LookPath("go")
	if err != nil {
		utils.Logger.Fatal("Go executable not found in PATH.")
	}

	// Detect if deps tool should be used (is there a vendor folder ?)
	useVendor := utils.DirExists(filepath.Join(paths.BasePath, "vendor"))
	basePath := paths.BasePath
	for !useVendor {
		basePath = filepath.Dir(basePath)
		found := false
		// Check to see if we are still in the GOPATH
		for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
			if strings.HasPrefix(basePath, gopath) {
				found = true
				break
			}
		}
		if !found {
			break
		} else {
			useVendor = utils.DirExists(filepath.Join(basePath, "vendor"))
		}
	}

	pkg, err := build.Default.Import(paths.ImportPath, "", build.FindOnly)
	if err != nil {
		return
	}

	// Binary path is a combination of $GOBIN/revel.d directory, app's import path and its name.
	binName := filepath.Join(pkg.BinDir, "revel.d", paths.ImportPath, filepath.Base(paths.BasePath))

	// Change binary path for Windows build
	goos := runtime.GOOS
	if goosEnv := os.Getenv("GOOS"); goosEnv != "" {
		goos = goosEnv
	}
	if goos == "windows" {
		binName += ".exe"
	}

	gotten := make(map[string]struct{})
	contains := func(s []string, e string) bool {
		for _, a := range s {
			if a == e {
				return true
			}
		}
		return false
	}

	for {
		appVersion := getAppVersion(paths)

		buildTime := time.Now().UTC().Format(time.RFC3339)
		versionLinkerFlags := fmt.Sprintf("-X %s/app.AppVersion=%s -X %s/app.BuildTime=%s",
			paths.ImportPath, appVersion, paths.ImportPath, buildTime)

		// Append any build flags specified, they will override existing flags
		flags := []string{}
		if len(c.BuildFlags) == 0 {
			flags = []string{
				"build",
				"-i",
				"-ldflags", versionLinkerFlags,
				"-tags", buildTags,
				"-o", binName}
		} else {
			if !contains(c.BuildFlags, "build") {
				flags = []string{"build"}
			}
			flags = append(flags, c.BuildFlags...)
			if !contains(flags, "-ldflags") {
				flags = append(flags, "-ldflags", versionLinkerFlags)
			}
			if !contains(flags, "-tags") {
				flags = append(flags, "-tags", buildTags)
			}
			if !contains(flags, "-o") {
				flags = append(flags, "-o", binName)
			}
		}

		// Add in build flags
		flags = append(flags, c.BuildFlags...)

		// This is Go main path
		gopath := c.GoPath
		for _, o := range paths.ModulePathMap {
			gopath += string(filepath.ListSeparator) + o
		}

		// Note: It's not applicable for filepath.* usage
		flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))

		buildCmd := exec.Command(goPath, flags...)
		buildCmd.Env = append(os.Environ(),
			"GOPATH="+gopath,
		)
		utils.CmdInit(buildCmd, c.AppPath)
		utils.Logger.Info("Exec:", "args", buildCmd.Args)
		output, err := buildCmd.CombinedOutput()

		// If the build succeeded, we're done.
		if err == nil {
			utils.Logger.Info("Build successful continuing")
			return NewApp(binName, paths), nil
		}

		// Since there was an error, capture the output in case we need to report it
		stOutput := string(output)

		// See if it was an import error that we can go get.
		matches := importErrorPattern.FindAllStringSubmatch(stOutput, -1)
		utils.Logger.Info("Build failed checking for missing imports", "message", stOutput, "missing_imports", len(matches))
		if matches == nil {
			utils.Logger.Info("Build failed no missing imports", "message", stOutput)
			return nil, newCompileError(paths, output)
		}
		utils.Logger.Warn("Detected missing packages, importing them", "packages", len(matches))
		for _, match := range matches {
			// Ensure we haven't already tried to go get it.
			pkgName := match[1]
			utils.Logger.Info("Trying to import ", "package", pkgName)
			if _, alreadyTried := gotten[pkgName]; alreadyTried {
				utils.Logger.Error("Failed to import ", "package", pkgName)
				return nil, newCompileError(paths, output)
			}
			gotten[pkgName] = struct{}{}
			if err := c.PackageResolver(pkgName); err != nil {
				utils.Logger.Error("Unable to resolve package", "package", pkgName, "error", err)
				return nil, newCompileError(paths, []byte(err.Error()))
			}
		}

		// Success getting the import, attempt to build again.
	}

	// TODO remove this unreachable code and document it
	utils.Logger.Fatal("Not reachable")
	return nil, nil
}
491417
func Open(driver, config string) shimmie.Store {
	db := openDB(driver, config)
	return &datastore{db}
}
1248144
func (p *Process) initPrimaryDB() error {
	logger := p.Logger.New("fn", "initPrimaryDB")
	logger.Info("initializing primary database")

	dsn := &DSN{
		Host:    "127.0.0.1:" + p.Port,
		User:    "root",
		Timeout: p.OpTimeout,
	}

	db, err := sql.Open("mysql", dsn.String())
	if err != nil {
		logger.Error("error acquiring connection", "err", err)
		return err
	}
	defer db.Close()

	if _, err := db.Exec(fmt.Sprintf(`CREATE USER 'flynn'@'%%' IDENTIFIED BY '%s'`, p.Password)); err != nil && MySQLErrorNumber(err) != 1396 {
		logger.Error("error creating database user", "err", err)
		return err
	}
	if _, err := db.Exec(`GRANT ALL ON *.* TO 'flynn'@'%' WITH GRANT OPTION`); err != nil {
		logger.Error("error granting privileges", "err", err)
		return err
	}
	if _, err := db.Exec(`INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so'`); err != nil && MySQLErrorNumber(err) != 1968 {
		logger.Error("error installing rpl_semi_sync_master", "err", err)
		return err
	}
	if _, err := db.Exec(`FLUSH PRIVILEGES`); err != nil {
		logger.Error("error flushing privileges", "err", err)
		return err
	}

	// If we are running in Singleton mode we don't need to setup replication
	if p.Singleton {
		return nil
	}
	// Enable semi-sync replication on the master.
	master_variables := map[string]string{
		"rpl_semi_sync_master_wait_point":    "AFTER_SYNC",
		"rpl_semi_sync_master_timeout":       "18446744073709551615",
		"rpl_semi_sync_master_enabled":       "1",
		"rpl_semi_sync_master_wait_no_slave": "1",
	}

	for v, val := range master_variables {
		if _, err := db.Exec(fmt.Sprintf(`SET GLOBAL %s = %s`, v, val)); err != nil {
			logger.Error("error setting system variable", "var", v, "val", val, "err", err)
			return err
		}
	}

	return nil
}