forked from vuvuzela/vuvuzela
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersist.go
87 lines (70 loc) · 1.92 KB
/
persist.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
// Copyright 2017 David Lazar. All rights reserved.
// Use of this source code is governed by the GNU AGPL
// license that can be found in the LICENSE file.
package vuvuzela
import (
"encoding/json"
"io/ioutil"
"vuvuzela.io/alpenhorn/config"
"vuvuzela.io/alpenhorn/errors"
"vuvuzela.io/internal/ioutil2"
"vuvuzela.io/vuvuzela/convo"
)
type persistedState struct {
ConvoConfig *config.SignedConfig
}
func (c *Client) persistLocked() error {
st := &persistedState{
ConvoConfig: c.convoConfig,
}
data, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
return ioutil2.WriteFileAtomic(c.PersistPath, data, 0600)
}
// LoadClient loads a client from persisted state at the given path.
// You should set the client's KeywheelPersistPath before connecting.
func LoadClient(clientPersistPath string) (*Client, error) {
clientData, err := ioutil.ReadFile(clientPersistPath)
if err != nil {
return nil, err
}
st := new(persistedState)
err = json.Unmarshal(clientData, st)
if err != nil {
return nil, err
}
c := &Client{
PersistPath: clientPersistPath,
}
c.loadStateLocked(st)
return c, nil
}
func (c *Client) loadStateLocked(st *persistedState) {
c.convoConfig = st.ConvoConfig
c.convoConfigHash = st.ConvoConfig.Hash()
}
// Persist writes the client's state to disk. The client persists
// itself automatically, so Persist is only needed when creating
// a new client.
func (c *Client) Persist() error {
c.mu.Lock()
err := c.persistLocked()
c.mu.Unlock()
return err
}
func (c *Client) Bootstrap(startingConvoConfig *config.SignedConfig) error {
if err := startingConvoConfig.Validate(); err != nil {
return err
}
_, ok := startingConvoConfig.Inner.(*convo.ConvoConfig)
if !ok {
return errors.New("unexpected inner config type: %T", startingConvoConfig.Inner)
}
c.mu.Lock()
defer c.mu.Unlock()
c.convoConfig = startingConvoConfig
c.convoConfigHash = startingConvoConfig.Hash()
return nil
}