-
Notifications
You must be signed in to change notification settings - Fork 2
/
files.go
129 lines (108 loc) · 2.31 KB
/
files.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
package main
import (
"encoding/json"
"io/ioutil"
"strings"
"time"
)
// TriggerType describes what sorts of trigger are supported
type TriggerType int
const (
Post TriggerType = iota
Manual
Periodic
)
func (t *TriggerType) UnmarshalJSON(data []byte) error {
switch strings.ToLower(string(data)) {
case "\"post\"":
*t = Post
case "\"manual\"":
*t = Manual
case "\"periodic\"":
*t = Periodic
default:
*t = Manual // emit diagnostic?
}
return nil
}
func (t TriggerType) String() string {
switch t {
case Post:
return "Post"
case Manual:
return "Manual"
case Periodic:
return "Periodic"
}
return "(unknown)"
}
// Duration wraps time.Duration to allow some custom formatters to
// be applied.
type Duration time.Duration
func (d Duration) MarshalText() ([]byte, error) {
return []byte(time.Duration(d).String()), nil
}
func (d Duration) String() string {
return time.Duration(d).String()
}
func (d *Duration) UnmarshalText(val []byte) error {
if len(val) == 0 {
return nil
}
duration, err := time.ParseDuration(string(val))
if err != nil {
return err
}
*d = Duration(duration)
return nil
}
type ConfigFile struct {
ServerConfig Config
Watches map[string]WatchDogConfig
}
type Config struct {
ListenAddress string
StateFile string
ExecArgs []string
}
func loadConfig(file string) (ConfigFile, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return ConfigFile{}, err
}
myConfig := ConfigFile{
ServerConfig: Config{
ListenAddress: "127.0.0.1:8080",
ExecArgs: []string{"/bin/bash", "-c"},
},
}
if err := json.Unmarshal(data, &myConfig); err != nil {
return ConfigFile{}, err
}
return myConfig, nil
}
type StatusFile map[string]WatchDogStatus
func loadStatus(file string) (StatusFile, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return StatusFile{}, err
}
var myStatus StatusFile
if err := json.Unmarshal(data, &myStatus); err != nil {
return StatusFile{}, err
}
return myStatus, nil
}
func saveStatus(file string, statuses []*Watch) error {
myStatus := make(StatusFile)
for _, s := range statuses {
if s.Endpoint != "" && !s.LastSeen().IsZero() {
myStatus[s.Endpoint] = s.Status()
}
}
f, err := json.MarshalIndent(myStatus, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(file, f, 0644)
}