forked from cnosdb/cnosdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
73 lines (60 loc) · 1.15 KB
/
node.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
package cnosdb
import (
"encoding/json"
"os"
"path/filepath"
)
const (
nodeFile = "node.json"
)
type Node struct {
path string
ID uint64
Peers []string
}
// LoadNode will load the node information from disk if present
func LoadNode(path, fileName string) (*Node, error) {
nodeFile := nodeFile
if fileName != "" {
nodeFile = fileName
}
n := &Node{
path: path,
}
f, err := os.Open(filepath.Join(path, nodeFile))
if err != nil {
return nil, err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(n); err != nil {
return nil, err
}
return n, nil
}
// NewNode will return a new node
func NewNode(path string) *Node {
return &Node{
path: path,
}
}
// Save will save the node file to disk and replace the existing one if present
func (n *Node) Save(fileName string) error {
nodeFile := nodeFile
if fileName != "" {
nodeFile = fileName
}
file := filepath.Join(n.path, nodeFile)
tmpFile := file + "tmp"
f, err := os.Create(tmpFile)
if err != nil {
return err
}
if err = json.NewEncoder(f).Encode(n); err != nil {
f.Close()
return err
}
if err = f.Close(); nil != err {
return err
}
return os.Rename(tmpFile, file)
}