forked from blind-oracle/dnstap-bgp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
68 lines (54 loc) · 1.11 KB
/
db.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
package main
import (
"bytes"
"encoding/gob"
"net"
bolt "github.com/etcd-io/bbolt"
)
type db struct {
h *bolt.DB
b []byte
}
func newDB(path string) (d *db, err error) {
d = &db{
b: []byte("ipcache"),
}
if d.h, err = bolt.Open(path, 0666, nil); err != nil {
return
}
err = d.h.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(d.b)
return err
})
return
}
func (d *db) add(e *cacheEntry) (err error) {
var b bytes.Buffer
if err = gob.NewEncoder(&b).Encode(e); err != nil {
return
}
return d.h.Update(func(tx *bolt.Tx) error {
return tx.Bucket(d.b).Put(e.IP, b.Bytes())
})
}
func (d *db) del(ip net.IP) (err error) {
return d.h.Update(func(tx *bolt.Tx) error {
return tx.Bucket(d.b).Delete(ip)
})
}
func (d *db) fetchAll() (es []*cacheEntry, err error) {
err = d.h.View(func(tx *bolt.Tx) error {
return tx.Bucket(d.b).ForEach(func(k, v []byte) (err error) {
e := &cacheEntry{}
if err = gob.NewDecoder(bytes.NewBuffer(v)).Decode(e); err != nil {
return
}
es = append(es, e)
return nil
})
})
return
}
func (d *db) close() error {
return d.h.Close()
}