// initBolt initializes the backing bolt db, checking that the metadata schema
// version matches what we expect
964506
func (db *DB) initBolt(path string) (bool, error) {
	var err error
	db.db, err = bolt.Open(path, 0600, nil)
	if err != nil {
		return false, err
	}

	return db.checkMeta()
}
221637
func (p *PartitionedMemoryIdx) Init() error {
	for _, m := range p.Partition {
		err := m.Init()
		if err != nil {
			return err
		}
	}
	return nil
}
952324
func (s *BoltStateDB) Upgrade() error {
	// Check to see if the underlying DB needs upgrading.
	upgrade, err := NeedsUpgrade(s.db.BoltDB())
	if err != nil {
		return err
	}
	if !upgrade {
		// No upgrade needed!
		return nil
	}

	// Upgraded needed. Backup the boltdb first.
	backupFileName := filepath.Join(s.stateDir, "state.db.backup")
	if err := backupDB(s.db.BoltDB(), backupFileName); err != nil {
		return fmt.Errorf("error backing up state db: %v", err)
	}

	// Perform the upgrade
	if err := s.db.Update(func(tx *boltdd.Tx) error {
		if err := UpgradeAllocs(s.logger, tx); err != nil {
			return err
		}

		// Add standard metadata
		if err := addMeta(tx.BoltTx()); err != nil {
			return err
		}

		// Write the time the upgrade was done
		bkt, err := tx.CreateBucketIfNotExists(metaBucketName)
		if err != nil {
			return err
		}
		return bkt.Put(metaUpgradedKey, time.Now().Format(time.RFC3339))
	}); err != nil {
		return err
	}

	s.logger.Info("successfully upgraded state")
	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)
		}
	})
}
552981
func init() {
	DefaultCallback.Delete().Register("gorm:begin_transaction", beginTransactionCallback)
	DefaultCallback.Delete().Register("gorm:before_delete", beforeDeleteCallback)
	DefaultCallback.Delete().Register("gorm:delete", deleteCallback)
	DefaultCallback.Delete().Register("gorm:after_delete", afterDeleteCallback)
	DefaultCallback.Delete().Register("gorm:commit_or_rollback_transaction", commitOrRollbackTransactionCallback)
}
1006342
func (builder *MultiOrganizationBuilder) Build(db chronograf.OrganizationsStore) (*multistore.OrganizationsStore, error) {
	// These organization are those handled from a directory
	files := filestore.NewOrganizations(builder.Path, builder.Logger)
	// Acts as a front-end to both the bolt org and filesystem orgs.
	// The idea here is that these stores form a hierarchy in which each is tried sequentially until
	// the operation has success.  So, the database is preferred over filesystem
	orgs := &multistore.OrganizationsStore{
		Stores: []chronograf.OrganizationsStore{
			db,
			files,
		},
	}

	return orgs, nil
}
763585
func InitDB(dbInfo *DBInfo, shutdown func()) (*DB, error) {
	dbPath, err := filepath.Abs(dbInfo.FileName)
	if err != nil {
		return nil, err
	}

	// Ensures target DB-file has a parent folder
	parent := filepath.Dir(dbPath)
	err = os.MkdirAll(parent, 0755)
	if err != nil {
		return nil, err
	}

	// "shared-cache" mode has multiple connections share a single data and
	// schema cache. _busy_timeout helps prevent SQLITE_BUSY ("database is
	// locked") errors by sleeping for a certain amount of time when the
	// database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html.
	dbPath = dbPath + "?cache=shared&_busy_timeout=" + DBBusyTimeout
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil || db == nil {
		return nil, err
	}

	// Historically, SQLite did not handle concurrent writes internally,
	// necessitating a limitation of just 1 open connecton. With a busy_timeout
	// set, this is less important. With go-sqlite 1.10, this is not needed at
	// all since the library started compiling sqlite3 for
	// thread-safe/"serialized" operation (SQLITE_THREADSAFE=1). For details,
	// see https://sqlite.org/threadsafe.html and
	// https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized.
	// The change to go-sqlite3 is
	// github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e
	//
	// db.SetMaxOpenConns(1)

	// These are db-wide settings that persist for the entire session.
	_, err = db.Exec(SetCacheSizeSQL)
	if err != nil {
		log.Error("Error setting SQLite Cache size")
		return nil, err
	}
	_, err = db.Exec(SetSynchrounousOffSQL)
	if err != nil {
		log.Error("Error setting SQLite synchrounous off")
		return nil, err
	}

	rawCreateBlockSummaryStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	size INTEGER,
      	diff FLOAT,
      	sdiff FLOAT,
      	time INTEGER,
      	poolsize INTEGER,
      	poolval FLOAT,
      	poolavg FLOAT,
      	winners TEXT,
      	is_mainchain BOOL,
      	is_valid BOOL
    	);`

	createBlockSummaryStmt := fmt.Sprintf(rawCreateBlockSummaryStmt, TableNameSummaries)

	_, err = db.Exec(createBlockSummaryStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createBlockSummaryStmt)
		return nil, err
	}

	rawCreateStakeInfoExtendedStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	num_tickets INTEGER,
      	fee_min FLOAT, fee_max FLOAT, fee_mean FLOAT,
      	fee_med FLOAT, fee_std FLOAT,
      	sdiff FLOAT, window_num INTEGER, window_ind INTEGER,
      	pool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT,
      	winners TEXT
    	);`

	createStakeInfoExtendedStmt := fmt.Sprintf(rawCreateStakeInfoExtendedStmt, TableNameStakeInfo)

	_, err = db.Exec(createStakeInfoExtendedStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createStakeInfoExtendedStmt)
		return nil, err
	}

	if err = db.Ping(); err != nil {
		return nil, err
	}

	dataBase, err := NewDB(db, shutdown)
	if err != nil {
		return nil, err
	}

	// Table creation string are used in JustifyTableStructures
	// Eventually won't be needed.
	dataBase.rawCreateBlockSummaryStmt = rawCreateBlockSummaryStmt
	dataBase.rawCreateStakeInfoExtendedStmt = rawCreateStakeInfoExtendedStmt
	if err = dataBase.JustifyTableStructures(dbInfo); err != nil {
		return nil, err
	}

	return dataBase, err
}
626919
func (s *Stack) init() error {
	// Create a new LevelDB Iterator.
	iter := s.db.NewIterator(nil, nil)
	defer iter.Release()

	// Set stack head to the last item.
	if iter.Last() {
		s.head = keyToID(iter.Key())
	}

	// Set stack tail to the first item.
	if iter.First() {
		s.tail = keyToID(iter.Key()) - 1
	}

	return iter.Error()
}
586817
func (b *stdBackend) init() {
	b.etmData = make(map[string]*stdMeasuringPoint)
	b.ssvData = make(map[string]*stdStaySetVariable)
	b.dsrData = make(map[string]DynamicStatusRetriever)
}
855400
func (tx *Tx) init(db *DB) {
	tx.db = db
	tx.pages = nil

	// Copy the meta page since it can be changed by the writer.
	tx.meta = &meta{}
	db.meta().copy(tx.meta)

	// Copy over the root bucket.
	tx.root = newBucket(tx)
	tx.root.bucket = &bucket{}
	*tx.root.bucket = tx.meta.root

	// Increment the transaction id and add a page cache for writable transactions.
	if tx.writable {
		tx.pages = make(map[pgid]*page)
		tx.meta.txid += txid(1)
	}
}
1181572
func (d *MasterDaemon) Init() {
	// set cluster mode
	err := master.SetClusterMode(d.ClusterMode)
	if err != nil {
		log.Fatalf("Failed to set cluster-mode %q. Error: %s", d.ClusterMode, err)
	}

	// initialize state driver
	d.stateDriver, err = utils.NewStateDriver(d.ClusterStoreDriver, &core.InstanceInfo{DbURL: d.ClusterStoreURL})
	if err != nil {
		log.Fatalf("Failed to init state-store: driver %q, URLs %q. Error: %s", d.ClusterStoreDriver, d.ClusterStoreURL, err)
	}

	// Initialize resource manager
	d.resmgr, err = resources.NewStateResourceManager(d.stateDriver)
	if err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	// Create an objdb client
	d.objdbClient, err = objdb.InitClient(d.ClusterStoreDriver, []string{d.ClusterStoreURL})
	if err != nil {
		log.Fatalf("Error connecting to state store: driver %q, URLs %q. Err: %v", d.ClusterStoreDriver, d.ClusterStoreURL, err)
	}
}
597741
func InitOnce(homeDir, mobileSharedHome, logFile, runModeStr string,
	accessGroupOverride bool, dnsNSFetcher ExternalDNSNSFetcher, nvh NativeVideoHelper) {
	startOnce.Do(func() {
		if err := Init(homeDir, mobileSharedHome, logFile, runModeStr, accessGroupOverride, dnsNSFetcher, nvh); err != nil {
			kbCtx.Log.Errorf("Init error: %s", err)
		}
	})
}
365712
func init() {
	if os.Getenv("SEC51_KEYPATH") != "" {
		keyPath = os.Getenv("SEC51_KEYPATH")
	} else {
		keyPath = "keys"
	}

	keysFolderPrefixFormat = filepath.Join(keyPath, "%s")
	testKeysFolderPrefixFormat = filepath.Join(testKeyPath, "%s")
	if err := createBaseKeyFolder(keyPath); err != nil {
		log.Println(err)
	}
}
1018406
func (s *Store) Init(btlPolicy pvtdatapolicy.BTLPolicy) {
	s.pvtdataStore.Init(btlPolicy)
}
157303
func (c *HeightHintCache) initBuckets() error {
	return c.db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(spendHintBucket)
		if err != nil {
			return err
		}

		_, err = tx.CreateBucketIfNotExists(confirmHintBucket)
		return err
	})
}
385801
func newPooledBoltConn(connStr string, driver DriverPool) (*boltConn, error) {

	c := createBoltConn(connStr)
	c.poolDriver = driver

	return c, nil
}
985950
func Init(params map[string]string) (volume.VolumeDriver, error) {
	nbdInit()

	inst := &driver{
		IODriver: volume.IONotSupported,
		StoreEnumerator: common.NewDefaultStoreEnumerator(Name,
			kvdb.Instance()),
		StatsDriver:        volume.StatsNotSupported,
		QuiesceDriver:      volume.QuiesceNotSupported,
		CredsDriver:        volume.CredsNotSupported,
		CloudBackupDriver:  volume.CloudBackupNotSupported,
		CloudMigrateDriver: volume.CloudMigrateNotSupported,
	}
	inst.buseDevices = make(map[string]*buseDev)
	if err := os.MkdirAll(BuseMountPath, 0744); err != nil {
		return nil, err
	}
	volumeInfo, err := inst.StoreEnumerator.Enumerate(
		&api.VolumeLocator{},
		nil,
	)
	if err == nil {
		for _, info := range volumeInfo {
			if info.Status == api.VolumeStatus_VOLUME_STATUS_NONE {
				info.Status = api.VolumeStatus_VOLUME_STATUS_UP
				inst.UpdateVol(info)
			}
		}
	} else {
		logrus.Println("Could not enumerate Volumes, ", err)
	}

	inst.cl = &clusterListener{}
	c, err := clustermanager.Inst()
	if err != nil {
		logrus.Println("BUSE initializing in single node mode")
	} else {
		logrus.Println("BUSE initializing in clustered mode")
		c.AddEventListener(inst.cl)
	}

	logrus.Println("BUSE initialized and driver mounted at: ", BuseMountPath)
	return inst, nil
}