This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
configmanager.go
336 lines (301 loc) · 7.89 KB
/
configmanager.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright (c) 2012 VMware, Inc.
package gonit
import (
"fmt"
"github.com/xushiwei/goyaml"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
// TODO:
// - Global interval for collecting resources.
// - Throw an error if the interval * MAX_DATA_TO_STORE < a rule's duration e.g.
// if interval is 1s and MAX_DATA_TO_STORE = 120 and someone wants 3
// minutes duration in a rule.
type ConfigManager struct {
ProcessGroups map[string]*ProcessGroup
Settings *Settings
}
type Settings struct {
AlertTransport string
SocketFile string
RpcServerUrl string
PollInterval int
Daemon *Process
}
type ProcessGroup struct {
Name string
Events map[string]*Event
Processes map[string]*Process
}
type Event struct {
Name string
Description string
Rule string
Duration string
Interval string
}
type Action struct {
Name string
Events []string
}
type Process struct {
Name string
Pidfile string
Start string
Stop string
Restart string
Gid string
Uid string
Stdout string
Stderr string
Env []string
Dir string
Detached bool
Description string
DependsOn []string
Actions map[string][]string
MonitorMode string
}
const (
CONFIG_FILE_POSTFIX = "-gonit.yml"
SETTINGS_FILENAME = "gonit.yml"
UNIX_SOCKET_TRANSPORT = "unix_socket"
MONITOR_MODE_ACTIVE = "active"
MONITOR_MODE_PASSIVE = "passive"
MONITOR_MODE_MANUAL = "manual"
)
const (
DEFAULT_ALERT_TRANSPORT = "none"
)
// Given an action string name, returns the events associated with it.
func (pg *ProcessGroup) EventByName(eventName string) *Event {
event, has_key := pg.Events[eventName]
if has_key {
return event
}
return nil
}
// Given a process name, returns the Process and whether it exists.
func (pg *ProcessGroup) processFromName(name string) (*Process, bool) {
serv, hasKey := pg.Processes[name]
return serv, hasKey
}
// For some of the maps, we want the map key name to be inside of the object so
// that it's easier to access.
func (c *ConfigManager) fillInNames() {
for groupName, processGroup := range c.ProcessGroups {
processGroup.Name = groupName
for name, process := range processGroup.Processes {
process.Name = name
processGroup.Processes[name] = process
}
for name, event := range processGroup.Events {
event.Name = name
processGroup.Events[name] = event
}
c.ProcessGroups[groupName] = processGroup
}
}
// Parses a config file into a ProcessGroup.
func (c *ConfigManager) parseConfigFile(path string) (*ProcessGroup, error) {
processGroup := &ProcessGroup{}
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if err := goyaml.Unmarshal(b, processGroup); err != nil {
return nil, err
}
log.Printf("Loaded config file '%+v'\n", path)
return processGroup, nil
}
// Parses a settings file into a Settings struct.
func (c *ConfigManager) parseSettingsFile(path string) (*Settings, error) {
settings := &Settings{}
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if err := goyaml.Unmarshal(b, settings); err != nil {
return nil, err
}
log.Printf("Loaded settings file: '%+v'\n", path)
return settings, nil
}
// Given a filename, removes -gonit.yml.
func getGroupName(filename string) string {
// -10 because of "-gonit.yml"
return filename[:len(filename)-10]
}
// Parses a directory for gonit files.
func (c *ConfigManager) parseDir(dirPath string) error {
dir, err := os.Open(dirPath)
if err != nil {
return err
}
defer dir.Close()
dirNames, err := dir.Readdirnames(-1)
if err != nil {
return err
}
for _, filename := range dirNames {
if err := c.parseFile(filepath.Join(dirPath, filename)); err != nil {
return err
}
}
return nil
}
// Applies default global settings if some options haven't been specified.
func (c *ConfigManager) ApplyDefaultSettings() {
if c.Settings == nil {
c.Settings = &Settings{}
}
settings := c.Settings
if settings.AlertTransport == "" {
settings.AlertTransport = DEFAULT_ALERT_TRANSPORT
}
if settings.Daemon == nil {
settings.Daemon = &Process{}
}
daemon := settings.Daemon
if daemon.Dir == "" {
daemon.Dir = os.Getenv("HOME")
}
if daemon.Name == "" {
daemon.Name = filepath.Base(os.Args[0])
}
if daemon.Pidfile == "" {
defaultPath := "." + daemon.Name + ".pid"
daemon.Pidfile = filepath.Join(daemon.Dir, defaultPath)
}
if settings.RpcServerUrl == "" {
defaultPath := "." + daemon.Name + ".sock"
settings.RpcServerUrl = filepath.Join(daemon.Dir, defaultPath)
}
}
// Parses a file.
func (c *ConfigManager) parseFile(path string) error {
_, filename := filepath.Split(path)
var err error
if filename == SETTINGS_FILENAME {
if c.Settings, err = c.parseSettingsFile(path); err != nil {
return err
}
} else if strings.HasSuffix(filename, CONFIG_FILE_POSTFIX) {
groupName := getGroupName(filename)
c.ProcessGroups[groupName], err = c.parseConfigFile(path)
if err != nil {
return err
}
}
return nil
}
// Main function to call, parses a path for gonit config file(s).
func (c *ConfigManager) Parse(paths ...string) error {
c.ProcessGroups = map[string]*ProcessGroup{}
for _, path := range paths {
fileInfo, err := os.Stat(path)
if err != nil {
return fmt.Errorf("Error stating path '%+v'.\n", path)
}
if fileInfo.IsDir() {
if err = c.parseDir(path); err != nil {
return err
}
} else {
if err := c.parseFile(path); err != nil {
return err
}
}
c.fillInNames()
}
if c.Settings == nil {
log.Printf("No settings found, using defaults.")
}
c.ApplyDefaultSettings()
c.applyDefaultConfigOpts()
if err := c.validate(); err != nil {
return err
}
return nil
}
func (c *ConfigManager) applyDefaultMonitorMode() {
for _, pg := range c.ProcessGroups {
for _, process := range pg.Processes {
if process.MonitorMode == "" {
process.MonitorMode = MONITOR_MODE_ACTIVE
}
}
}
}
func (c *ConfigManager) applyDefaultConfigOpts() {
c.applyDefaultMonitorMode()
}
// Validates that certain fields exist in the config file.
func (pg ProcessGroup) validateRequiredFieldsExist() error {
for name, process := range pg.Processes {
if process.Name == "" || process.Description == "" ||
process.Pidfile == "" || process.Start == "" {
return fmt.Errorf("%v must have name, description, pidfile and start.",
name)
}
}
for name, event := range pg.Events {
if event.Name == "" || event.Description == "" || event.Rule == "" {
return fmt.Errorf("%v must have name, description, rule, and "+
"actions.", name)
}
}
return nil
}
// Validates various links in a config.
func (pg *ProcessGroup) validateLinks() error {
// TODO: Validate the event links.
for _, process := range pg.Processes {
for _, dependsOnName := range process.DependsOn {
if _, hasKey := pg.processFromName(dependsOnName); hasKey == false {
return fmt.Errorf("Process %v has an unknown dependson '%v'.",
process.Name, dependsOnName)
}
}
}
return nil
}
// Valitades settings.
func (s *Settings) validate() error {
if s.AlertTransport == UNIX_SOCKET_TRANSPORT && s.SocketFile == "" {
return fmt.Errorf("Settings uses '%v' alerts transport, but has no socket"+
" file.", UNIX_SOCKET_TRANSPORT)
}
return nil
}
// Validates a process group config.
func (c *ConfigManager) validate() error {
if len(c.ProcessGroups) == 0 {
return fmt.Errorf("A configuration file (*-gonit.yml) must be provided.")
}
for _, pg := range c.ProcessGroups {
if err := pg.validateRequiredFieldsExist(); err != nil {
return err
}
if err := pg.validateLinks(); err != nil {
return err
}
}
if err := c.Settings.validate(); err != nil {
return err
}
return nil
}
func (p *Process) IsMonitoringModeActive() bool {
return p.MonitorMode == MONITOR_MODE_ACTIVE
}
func (p *Process) IsMonitoringModePassive() bool {
return p.MonitorMode == MONITOR_MODE_PASSIVE
}
func (p *Process) IsMonitoringModeManual() bool {
return p.MonitorMode == MONITOR_MODE_MANUAL
}