forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
67 lines (58 loc) · 1.16 KB
/
service.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
package storage
import (
"log"
"os"
"path"
"sync"
"github.com/boltdb/bolt"
"github.com/pkg/errors"
)
type Service struct {
dbpath string
boltdb *bolt.DB
stores map[string]Interface
mu sync.Mutex
logger *log.Logger
}
func NewService(conf Config, l *log.Logger) *Service {
return &Service{
dbpath: conf.BoltDBPath,
logger: l,
stores: make(map[string]Interface),
}
}
func (s *Service) Open() error {
s.mu.Lock()
defer s.mu.Unlock()
err := os.MkdirAll(path.Dir(s.dbpath), 0755)
if err != nil {
return errors.Wrapf(err, "mkdir dirs %q", s.dbpath)
}
db, err := bolt.Open(s.dbpath, 0600, nil)
if err != nil {
return errors.Wrapf(err, "open boltdb @ %q", s.dbpath)
}
s.boltdb = db
return nil
}
func (s *Service) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.boltdb != nil {
return s.boltdb.Close()
}
return nil
}
// Return a namespaced store.
// Calling Store with the same namespace returns the same Store.
func (s *Service) Store(name string) Interface {
s.mu.Lock()
defer s.mu.Unlock()
if store, ok := s.stores[name]; ok {
return store
} else {
store = NewBolt(s.boltdb, name)
s.stores[name] = store
return store
}
}