-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataStore.go
96 lines (84 loc) · 1.81 KB
/
dataStore.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
func getDataStore(dConfig *dataStoreConfig, zms *map[string]*zoneManager) dataStore {
switch dConfig.Mode {
case "yaml":
return newYamlDataStore(dConfig.Path, zms)
}
return nil
}
type dataStore interface {
setZone(zoneName string, data *zoneStoreData) error
getZone(zoneName string) (*zoneStoreData, error)
save() error
load() error
}
type storeData struct {
Zones map[string]zoneStoreData `yaml:"zones"`
}
type zoneStoreData struct {
Serial uint32 `yaml:"serial"`
Origin string `yaml:"origin"`
Tree *dnsTree `yaml:"tree"`
}
func newYamlDataStore(path string, zms *map[string]*zoneManager) dataStore {
yd := &yamlDataStore{
path: path,
}
err := yd.load()
if err != nil {
zoneData := map[string]zoneStoreData{}
for _, zm := range *zms {
zoneData[zm.ZoneConfig.Suffix] = zoneStoreData{}
}
yd.data = &storeData{
Zones: zoneData,
}
}
return yd
}
type yamlDataStore struct {
path string
data *storeData
}
func (yd *yamlDataStore) setZone(zoneName string, data *zoneStoreData) error {
_, ok := yd.data.Zones[zoneName]
if ok {
yd.data.Zones[zoneName] = *data
return yd.save()
}
return fmt.Errorf("not found")
}
func (yd *yamlDataStore) getZone(zoneName string) (*zoneStoreData, error) {
zoneData, ok := yd.data.Zones[zoneName]
if ok {
return &zoneData, nil
}
return nil, fmt.Errorf("not found")
}
func (yd *yamlDataStore) save() error {
y, err := yaml.Marshal(yd.data)
if err != nil {
return err
}
if err := ioutil.WriteFile(yd.path, y, 0644); err != nil {
return err
}
return nil
}
func (yd *yamlDataStore) load() error {
data := &storeData{}
buf, err := ioutil.ReadFile(yd.path)
if err != nil {
return err
}
if err := yaml.Unmarshal(buf, data); err != nil {
return err
}
yd.data = data
return nil
}