-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathboltdb.go
More file actions
76 lines (62 loc) · 1.31 KB
/
boltdb.go
File metadata and controls
76 lines (62 loc) · 1.31 KB
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
75
76
package boltdb
import (
"fmt"
"os"
"path/filepath"
"sync"
"github.com/aquasecurity/postee/v2/log"
bolt "go.etcd.io/bbolt"
)
const (
DEFAULT_PATH = "/server/database/webhooks.db"
)
type BoltDb struct {
mu sync.Mutex
DbPath string
db *bolt.DB
}
func NewBoltDb(paths ...string) (*BoltDb, error) {
dbPath := DEFAULT_PATH
if len(paths) > 0 {
if paths[0] != "" {
dbPath = paths[0]
}
}
log.Logger.Infof("Open Bolt DB at %s", dbPath)
dbConn, err := open(dbPath)
if err != nil {
return nil, fmt.Errorf("failed to open bolt DB file: (%s) %w", dbPath, err)
}
return &BoltDb{
db: dbConn,
DbPath: dbPath,
}, nil
}
func open(path string) (*bolt.DB, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
err = os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
return nil, err
}
}
return bolt.Open(path, 0666, nil)
}
func (boltDb *BoltDb) ChangeDbPath(newPath string) error {
boltDb.mu.Lock()
defer boltDb.mu.Unlock()
boltDb.DbPath = newPath
if boltDb.db != nil {
boltDb.db.Close()
}
dbConn, err := bolt.Open(newPath, 0666, nil)
if err != nil {
return fmt.Errorf("failed to open bolt DB file: (%s) %w", newPath, err)
}
boltDb.db = dbConn
return nil
}
func (boltDb *BoltDb) Close() error {
boltDb.mu.Lock()
defer boltDb.mu.Unlock()
return boltDb.db.Close()
}