-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathconfig.go
116 lines (101 loc) · 2.59 KB
/
config.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
package config
import (
"bufio"
"encoding/json"
"io/ioutil"
"os"
"path"
"github.com/burke/zeus/go/filemonitor"
"github.com/burke/zeus/go/processtree"
"github.com/burke/zeus/go/zerror"
)
type config struct {
Command string
Plan interface{}
Items map[string]string
}
// BuildProcessTree builds the process tree.
func BuildProcessTree(configFile string, monitor filemonitor.FileMonitor) *processtree.ProcessTree {
conf := parseConfig(configFile)
tree := &processtree.ProcessTree{}
tree.SlavesByName = make(map[string]*processtree.SlaveNode)
tree.StateChanged = make(chan bool, 16)
tree.ExecCommand = conf.Command
plan, ok := conf.Plan.(map[string]interface{})
if !ok {
zerror.ErrorConfigFileInvalidFormat()
}
iteratePlan(tree, plan, monitor, nil)
return tree
}
func iteratePlan(
tree *processtree.ProcessTree,
plan map[string]interface{},
monitor filemonitor.FileMonitor,
parent *processtree.SlaveNode,
) {
for name, v := range plan {
if subPlan, ok := v.(map[string]interface{}); ok {
newNode := tree.NewSlaveNode(name, parent, monitor)
if parent == nil {
tree.Root = newNode
} else {
parent.Slaves = append(parent.Slaves, newNode)
}
iteratePlan(tree, subPlan, monitor, newNode)
} else {
var newNode *processtree.CommandNode
if aliases, ok := v.([]interface{}); ok {
strs := make([]string, len(aliases))
for i, alias := range aliases {
strs[i] = alias.(string)
}
newNode = tree.NewCommandNode(name, strs, parent)
} else if v == nil {
newNode = tree.NewCommandNode(name, nil, parent)
} else {
zerror.ErrorConfigFileInvalidFormat()
}
parent.Commands = append(parent.Commands, newNode)
}
}
}
func defaultConfigPath() string {
binaryPath := os.Args[0]
gemDir := path.Dir(path.Dir(binaryPath))
jsonpath := path.Join(gemDir, "examples/zeus.json")
return jsonpath
}
func readConfigFileOrDefault(configFile string) ([]byte, error) {
contents, err := readFile(configFile)
if err != nil {
switch err.(type) {
case *os.PathError:
return readFile(defaultConfigPath())
default:
return contents, err
}
}
return contents, err
}
func parseConfig(configFile string) (c config) {
var conf config
contents, err := readConfigFileOrDefault(configFile)
if err != nil {
zerror.ErrorConfigFileInvalidJSON()
}
err = json.Unmarshal(contents, &conf)
if err != nil {
zerror.ErrorConfigFileInvalidJSON()
}
return conf
}
func readFile(path string) (contents []byte, err error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
reader := bufio.NewReader(file)
contents, err = ioutil.ReadAll(reader)
return
}