-
Notifications
You must be signed in to change notification settings - Fork 45
/
restore.go
286 lines (264 loc) · 6.89 KB
/
restore.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
"bytes"
"encoding/gob"
"fmt"
"io/ioutil"
"os"
"sync"
"time"
"github.com/subutai-io/p2p/lib"
yaml "gopkg.in/yaml.v2"
)
// Restore represents dump/restore subsystem for instances
// This class keeps a list of so-called "save entries", which is
// a binding for instance information
// Restore system saves entries in a YAML-formatted save file, specified
// as an argument on daemon launch using `--save`
type Restore struct {
entries []saveEntry
filepath string
lock sync.RWMutex
active bool
}
// saveEntry is a YAML binding for data save file
type saveEntry struct {
IP string `yaml:"ip"`
Mac string `yaml:"mac"`
Dev string `yaml:"dev"`
Hash string `yaml:"hash"`
Keyfile string `yaml:"keyfile"`
Key string `yaml:"key"`
TTL string `yaml:"ttl"`
LastSuccess string `yaml:"last_success"`
Enabled bool
}
// init will initialize restore subsystem by checking if
// file exists and can be modified
func (r *Restore) init(filepath string) error {
if filepath == "" {
r.active = false
return nil
}
file, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
return err
}
file.Close()
r.filepath = filepath
r.active = true
return nil
}
// save will write dump of entries into a save file
func (r *Restore) save() error {
if r.filepath == "" {
return nil
}
r.lock.Lock()
file, err := os.OpenFile(r.filepath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
if err != nil {
r.lock.Unlock()
return err
}
data, err := r.encode()
if err != nil {
r.lock.Unlock()
return err
}
ptp.Log(ptp.Info, "Saving instances")
_, err = file.Write(data)
if err != nil {
r.lock.Unlock()
return err
}
r.lock.Unlock()
return nil
}
// load will read save file and unmarshal saved entries
func (r *Restore) load() error {
if r.filepath == "" {
return nil
}
r.lock.Lock()
data, err := ioutil.ReadFile(r.filepath)
if err != nil {
r.lock.Unlock()
return err
}
r.lock.Unlock()
data = bytes.Trim(data, "\x00") // TODO: add more security to this
if len(data) == 0 {
return nil
}
if string(data[0]) == "-" || string(data[0]) == "[" {
r.decode(data)
return nil
}
// TODO: This code is deprecated and must be removed in version 9
return r.decodeInstances(data)
}
// addInstance will create new save file entry from instance
func (r *Restore) addInstance(inst *P2PInstance) error {
ls, _ := inst.Args.LastSuccess.MarshalText()
return r.addEntry(saveEntry{
IP: inst.Args.IP,
Mac: inst.Args.Mac,
Dev: inst.Args.Dev,
Hash: inst.Args.Hash,
Keyfile: inst.Args.Keyfile,
Key: inst.Args.Key,
TTL: inst.Args.TTL,
LastSuccess: string(ls),
Enabled: true,
})
}
// addEntry will create new save entry if it's unique by hash
func (r *Restore) addEntry(entry saveEntry) error {
r.lock.Lock()
defer r.lock.Unlock()
for _, e := range r.entries {
if e.Hash == entry.Hash {
return fmt.Errorf("Instance %s already in list of saved entries", entry.Hash)
}
}
r.entries = append(r.entries, entry)
return nil
}
func (r *Restore) removeEntry(hash string) error {
r.lock.Lock()
defer r.lock.Unlock()
for i, e := range r.entries {
if e.Hash == hash {
r.entries = append(r.entries[:i], r.entries[i+1:]...)
return nil
}
}
return fmt.Errorf("Can't delete save entry: %s not found", hash)
}
func (r *Restore) bumpInstance(hash string) error {
r.lock.Lock()
defer r.lock.Unlock()
for i, e := range r.entries {
if e.Hash == hash {
ls, _ := time.Now().MarshalText()
r.entries[i].LastSuccess = string(ls)
r.entries[i].Enabled = true
return nil
}
}
return fmt.Errorf("Can't update last success date for the instance: %s", hash)
}
func (r *Restore) disableStaleInstances(inst *P2PInstance) error {
r.lock.RLock()
defer r.lock.RUnlock()
for i, e := range r.entries {
var t time.Time
err := t.UnmarshalText([]byte(e.LastSuccess))
if err != nil {
ptp.Log(ptp.Error, "Failed to unmarshal date for save file entry %s. Disabling it", e.Hash)
r.entries[i].Enabled = false
continue
}
if time.Since(t) > time.Duration(time.Hour*24*20) {
ptp.Log(ptp.Warning, "Instance %s was active more than 20 days ago", e.Hash)
r.entries[i].Enabled = false
}
}
return nil
}
// encode will generate YAML
func (r *Restore) encode() ([]byte, error) {
if len(r.entries) == 0 {
return nil, nil
}
var data []saveEntry
for _, e := range r.entries {
if e.Enabled {
data = append(data, e)
}
}
output, err := yaml.Marshal(data)
if err != nil {
return nil, err
}
return output, nil
}
// decode will accept YAML and generate a slice of RunArgs
func (r *Restore) decode(data []byte) error {
var saved []saveEntry
err := yaml.Unmarshal(data, &saved)
if err != nil {
return err
}
r.lock.Lock()
r.entries = saved
r.lock.Unlock()
return nil
}
// decodeInstances is an obsolet variant of instances unmarshal
// TODO: Remove in version 10
func (r *Restore) decodeInstances(data []byte) error {
if len(data) == 0 {
return nil
}
var args []saveEntry
b := bytes.Buffer{}
b.Write(data)
d := gob.NewDecoder(&b)
err := d.Decode(&args)
if err != nil {
blocksOfInstancesOld := bytes.Split(data, bytes.NewBufferString("|~|").Bytes())
blocksOfInstances := bytes.Split(data, bytes.NewBufferString("|||").Bytes())
if len(blocksOfInstancesOld) == len(blocksOfInstances) {
if len(blocksOfInstancesOld) != 1 || len(blocksOfInstances) != 1 {
return fmt.Errorf("Unexpected error in decoding process")
}
} else {
if len(blocksOfInstancesOld) > len(blocksOfInstances) {
blocksOfInstances = blocksOfInstancesOld
}
}
for _, str := range blocksOfInstances {
blocksOfArguments := bytes.Split(str, bytes.NewBufferString("~").Bytes())
if len(blocksOfArguments) != 10 {
return fmt.Errorf("Couldn't decode the instances")
}
var item saveEntry
item.IP = string(blocksOfArguments[0])
item.Mac = string(blocksOfArguments[1])
item.Dev = string(blocksOfArguments[2])
item.Hash = string(blocksOfArguments[3])
//item.Dht = string(blocksOfArguments[4])
item.Keyfile = string(blocksOfArguments[5])
item.Key = string(blocksOfArguments[6])
item.TTL = string(blocksOfArguments[7])
// Force this env to be nor marked as failed
item.Enabled = true
ls, _ := time.Now().MarshalText()
item.LastSuccess = string(ls)
//item.Fwd = false
// if string(blocksOfArguments[8]) == "1" {
// item.Fwd = true
// }
//item.Port, err = strconv.Atoi(string(blocksOfArguments[9]))
// if err != nil {
// return fmt.Errorf("Couldn't decode the Port: %v", err)
// }
args = append(args, item)
}
}
r.lock.Lock()
ptp.Log(ptp.Info, "Decoded %d entries from the old format", len(args))
r.entries = args
r.lock.Unlock()
return nil
}
// get will return slice of entries
func (r *Restore) get() []saveEntry {
r.lock.Lock()
defer r.lock.Unlock()
return r.entries
}
func (r *Restore) isActive() bool {
return r.active
}