-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.go
74 lines (64 loc) · 1.82 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"os"
"path/filepath"
logrus "github.com/sirupsen/logrus"
bbolt "go.etcd.io/bbolt"
)
// setupDatabase initializes and returns a bbolt DB instance based on the
// provided configuration. It ensures the database directory exists,
// creates the database file if necessary, and configures the database with the
// specified settings.
func setupDatabase(config *Config) (*bbolt.DB, error) {
// Ensure the database directory exists.
_, err := os.Stat(config.Database.DatabaseDirPath)
if os.IsNotExist(err) {
err := os.Mkdir(
config.Database.DatabaseDirPath,
DatabaseDirPermissions,
)
if err != nil {
return nil, err
}
}
// Construct the full path to the database file.
dbFilePath := filepath.Join(
config.Database.DatabaseDirPath, config.Database.DatabaseFile,
)
// Open the database with a timeout.
options := &bbolt.Options{Timeout: config.Database.FileLockTimeout}
db, err := bbolt.Open(
dbFilePath, DatabaseFilePermissions, options,
)
if err != nil {
return nil, err
}
// Create the main bucket for mission control data if it doesn't exist.
err = db.Update(func(tx *bbolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(
[]byte(DatabaseBucketName),
)
if err != nil {
return err
}
return nil
})
if err != nil {
db.Close()
return nil, err
}
// Configure MaxBatchDelay and MaxBatchSize.
db.MaxBatchDelay = config.Database.MaxBatchDelay
db.MaxBatchSize = config.Database.MaxBatchSize
return db, nil
}
// cleanupDB closes the database connection and logs any errors encountered
// during the process. It exits the program with a status code of 1 if the
// database fails to close.
func cleanupDB(db *bbolt.DB) {
if err := db.Close(); err != nil {
logrus.Errorf("Failed to close database: %v"+"\n", err)
os.Exit(1)
}
logrus.Info("Database connection closed")
}