-
Notifications
You must be signed in to change notification settings - Fork 6
/
nomad.go
322 lines (294 loc) · 8.05 KB
/
nomad.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
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"log"
"sync"
"time"
"github.com/hashicorp/nomad/api"
"github.com/ugorji/go/codec"
)
type NomadInfo map[string]*NomadTier
type TaskGroupMap map[string][]*api.AllocationListStub
type NomadTier struct {
Name string
Alias []string
Prefix []string
allocStubMap map[string][]*api.AllocationListStub
jobStubMap map[string]*api.JobListStub
jobMap map[string]*api.Job
nmap map[string]*api.NodeListStub
shaMap map[string]*AllocInfo
statsMap map[string]*api.AllocResourceUsage
deployMap map[string]*api.Deployment // key is deployment ID
sync.RWMutex
}
type NomadConfig struct {
Name string
URL string
Token string
Alias []string
Prefix []string
}
type AllocInfo struct {
Name string
ID string
Command string
Node *api.NodeListStub
DockerHost string
JobID string
Tier string
}
func stopJob(tier, jobid string) bool {
cfg := getNomadConfig()
info := cfg[tier]
c, _ := api.NewClient(&api.Config{Address: info.URL, SecretID: info.Token})
_, _, err := c.Jobs().Info(jobid, nil)
if err != nil {
log.Println(err)
return false
}
res, _, err := c.Jobs().Deregister(jobid, false, nil)
if err != nil {
log.Println(res, err)
return false
}
log.Println(res)
return true
}
func restartJob(tier, jobid string) bool {
cfg := getNomadConfig()
info := cfg[tier]
c, _ := api.NewClient(&api.Config{Address: info.URL, SecretID: info.Token})
job, _, err := c.Jobs().Info(jobid, nil)
if err != nil {
log.Println(err)
return false
}
res, _, err := c.Jobs().Deregister(jobid, false, nil)
if err != nil {
log.Println(res, err)
return false
}
stop := false
job.Stop = &stop
time.Sleep(time.Second * 5)
_, _, err = c.Jobs().Register(job, nil)
if err != nil {
log.Println(err)
return false
}
log.Println(res)
return true
}
func restartTaskGroup(tier, jobid string, group string) bool {
cfg := getNomadConfig()
info := cfg[tier]
c, _ := api.NewClient(&api.Config{Address: info.URL, SecretID: info.Token})
job, _, err := c.Jobs().Info(jobid, nil)
if err != nil {
log.Println(err)
return false
}
for _, tg := range job.TaskGroups {
if *tg.Name == group {
prev := tg.Count
tg.Count = new(int)
_, _, err := c.Jobs().Register(job, nil)
if err != nil {
log.Println(err)
return false
}
// set to previous value
tg.Count = prev
_, _, err = c.Jobs().Register(job, nil)
if err != nil {
log.Println(err)
return false
}
return true
}
}
log.Println(jobid, "/", group, "not found")
return false
}
func inspectJob(tier, jobid string) string {
var jsonHandlePretty = &codec.JsonHandle{
HTMLCharsAsIs: true,
Indent: 4,
}
cfg := getNomadConfig()
info := cfg[tier]
c, _ := api.NewClient(&api.Config{Address: info.URL, SecretID: info.Token})
job, _, err := c.Jobs().Info(jobid, nil)
if err != nil {
log.Println(err)
}
req := api.RegisterJobRequest{Job: job}
var buf bytes.Buffer
enc := codec.NewEncoder(&buf, jsonHandlePretty)
err = enc.Encode(req)
if err != nil {
log.Println(err)
}
return buf.String()
}
func getNomadInfo() NomadInfo {
i := make(NomadInfo)
cfg := getNomadConfig()
ntier := make(chan *NomadTier)
for tier, nc := range cfg {
go func(tier string, nc *NomadConfig) {
ntier <- getNomadTierInfo(tier, nc.URL, nc.Token, nc.Alias, nc.Prefix)
}(tier, nc)
}
for res := range ntier {
i[res.Name] = res
if len(i) == len(cfg) {
break
}
}
close(ntier)
n := &NomadTier{allocStubMap: make(map[string][]*api.AllocationListStub), jobStubMap: make(map[string]*api.JobListStub), jobMap: make(map[string]*api.Job), nmap: make(map[string]*api.NodeListStub), shaMap: make(map[string]*AllocInfo), statsMap: make(map[string]*api.AllocResourceUsage), deployMap: make(map[string]*api.Deployment)}
i["alles"] = n
i["alles"].Name = "alles"
for tier, _ := range cfg {
for k, v := range i[tier].allocStubMap {
i["alles"].allocStubMap[k] = v
}
for k, v := range i[tier].jobStubMap {
i["alles"].jobStubMap[k] = v
}
for k, v := range i[tier].jobMap {
i["alles"].jobMap[k] = v
}
for k, v := range i[tier].nmap {
i["alles"].nmap[k] = v
}
for k, v := range i[tier].shaMap {
i["alles"].shaMap[k] = v
}
for k, v := range i[tier].statsMap {
i["alles"].statsMap[k] = v
}
for k, v := range i[tier].deployMap {
i["alles"].deployMap[k] = v
}
}
return i
}
func getNomadTierInfo(tier, url, token string, alias []string, prefix []string) *NomadTier {
n := &NomadTier{Name: tier,
Alias: alias,
Prefix: prefix,
allocStubMap: make(map[string][]*api.AllocationListStub),
jobStubMap: make(map[string]*api.JobListStub),
jobMap: make(map[string]*api.Job),
nmap: make(map[string]*api.NodeListStub),
shaMap: make(map[string]*AllocInfo),
statsMap: make(map[string]*api.AllocResourceUsage),
deployMap: make(map[string]*api.Deployment)}
c, err := api.NewClient(&api.Config{Address: url, SecretID: token})
if err != nil {
log.Printf("getNomadTierInfo err: %s %#v\n", url, err.Error())
}
allocs, _, err := c.Allocations().List(nil)
if err != nil {
log.Printf("getNomadTierInfo allocs err: %s %#v\n", url, err.Error())
}
nodes, _, err := c.Nodes().List(nil)
if err != nil {
log.Printf("getNomadTierInfo nodes err: %s %#v\n", url, err.Error())
}
deploys, _, err := c.Deployments().List(nil)
if err != nil {
log.Printf("getNomadTierInfo deployments err: %s %#v\n", url, err.Error())
}
jobStubs, _, err := c.Jobs().List(nil)
if err != nil {
log.Printf("getNomadTierInfo jobs err: %s %#v\n", url, err.Error())
}
var wg sync.WaitGroup
for _, node := range nodes {
n.nmap[node.ID] = node
}
for _, jobStub := range jobStubs {
n.jobStubMap[jobStub.ID] = jobStub
if jobStub.Periodic {
j, _, _ := c.Jobs().Info(jobStub.ID, nil)
n.jobMap[jobStub.ID] = j
}
}
for _, deploy := range deploys {
n.deployMap[deploy.ID] = deploy
}
for _, alloc := range allocs {
if alloc.ClientStatus == "running" || alloc.ClientStatus == "pending" || alloc.ClientStatus == "failed" {
n.allocStubMap[alloc.JobID] = append(n.allocStubMap[alloc.JobID], alloc)
}
}
h := sha1.New()
for _, allocs := range n.allocStubMap {
for _, alloc := range allocs {
for k, _ := range alloc.TaskStates {
h.Write([]byte(k + alloc.ID))
hash := hex.EncodeToString(h.Sum(nil))[0:10]
n.shaMap[hash] = &AllocInfo{Name: k, ID: alloc.ID, Node: n.nmap[alloc.NodeID], JobID: alloc.JobID, Tier: tier}
h.Reset()
}
}
}
for _, allocs := range n.allocStubMap {
for _, alloc := range allocs {
wg.Add(1)
go func(alloc *api.AllocationListStub, n *NomadTier) {
realalloc, _, err := c.Allocations().Info(alloc.ID, nil)
if err != nil {
log.Println("realloc", err)
}
//log.Printf("NODE: %#v\n", n.nmap[alloc.NodeID])
//c, _ := api.NewClient(&api.Config{Address: "http://" + n.nmap[alloc.NodeID].HTTPAddr})
stats, err := c.Allocations().Stats(realalloc, nil)
if err != nil {
log.Println("stats", err)
}
n.Lock()
n.statsMap[alloc.ID] = stats
n.Unlock()
wg.Done()
}(alloc, n)
}
}
wg.Wait()
return n
}
func getTierFromJob(job string) string {
cfg := getNomadConfig()
for tier, info := range cfg {
if hasPrefix(job, info.Prefix) {
return tier
}
}
return "unset"
}
// formatTime formats the time to string based on RFC822
func formatTime(t time.Time) string {
if t.Unix() < 1 {
// It's more confusing to display the UNIX epoch or a zero value than nothing
return ""
}
// Return ISO_8601 time format GH-3806
return t.Format("2006-01-02T15:04:05Z07:00")
}
// formatUnixNanoTime is a helper for formatting time for output.
func formatUnixNanoTime(nano int64) string {
t := time.Unix(0, nano)
return formatTime(t)
}
// formatTimeDifference takes two times and determines their duration difference
// truncating to a passed unit.
// E.g. formatTimeDifference(first=1m22s33ms, second=1m28s55ms, time.Second) -> 6s
func formatTimeDifference(first, second time.Time, d time.Duration) string {
return second.Truncate(d).Sub(first.Truncate(d)).String()
}