/
agent.go
528 lines (441 loc) · 14.4 KB
/
agent.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package backplane
import (
"context"
"encoding/json"
"math/rand"
"strings"
"time"
"github.com/choria-io/go-choria/choria"
"github.com/choria-io/go-choria/server/agents"
"github.com/choria-io/mcorpc-agent-provider/mcorpc"
"github.com/choria-io/mcorpc-agent-provider/mcorpc/ddl/agent"
)
// Pausable is a service that can be paused
type Pausable interface {
// Pause should pause operations within your app immediately
Pause()
// Resume should resume operations within your app immediately
Resume()
// Flip should invert the pause state in an atomic manner
Flip()
// Should report the pause state
Paused() bool
}
// HealthCheckable describes a application that can be checked using the backplane
type HealthCheckable interface {
// HealthCheck should return as its result a struct that can be JSON converted
HealthCheck() (result interface{}, ok bool)
}
// Stopable describes an application that can be stopped using the backplane
type Stopable interface {
// Shutdown will be called after some delay and should exit the application
Shutdown()
}
// LogLevel is a valid log level
type LogLevel int8
const (
_ = iota
// DebugLevel is developer level debugging information
DebugLevel LogLevel = iota
// InfoLevel is end user informative information
InfoLevel
// WarnLevel is end user warning information
WarnLevel
// CriticalLevel is end user critical information
CriticalLevel
)
// LogLevelSetable describes an application that can have its log levels adjusted at runtime
type LogLevelSetable interface {
SetLogLevel(LogLevel)
GetLogLevel() LogLevel
}
// HealthReply is the reply from the health action
type HealthReply struct {
Result json.RawMessage `json:"result"`
Healthy bool `json:"healthy"`
}
// ShutdownReply is the reply from the shutdown action
type ShutdownReply struct {
Delay string `json:"delay"`
}
// InfoReply is the reply from the info action
type InfoReply struct {
BackplaneVersion string `json:"backplane_version"`
Version string `json:"version"`
Paused bool `json:"paused"`
Facts interface{} `json:"facts"`
Healthy bool `json:"healthy"`
LogLevel string `json:"loglevel"`
HealthFeature bool `json:"healthcheck_feature"`
PauseFeature bool `json:"pause_feature"`
ShutdownFeature bool `json:"shutdown_feature"`
FactsFeature bool `json:"facts_feature"`
LogLevelFeature bool `json:"loglevel_feature"`
}
// PausableReply is the reply format expected from Pausable actions
type PausableReply struct {
Paused bool `json:"paused"`
}
// PingReply is the reply format from the ping action
type PingReply struct {
Version string `json:"version"`
}
// LogLevelReply is the reply format from the log level actions
type LogLevelReply struct {
Level string `json:"level"`
}
func (m *Management) startAgents(ctx context.Context) (err error) {
md := AgentMetadata()
agent := mcorpc.New(md.Name, md, m.cfg.fw, m.log.WithField("agent", md.Name))
if m.cfg.pausable != nil {
agent.MustRegisterAction("pause", m.fullAction(m.pauseAction))
agent.MustRegisterAction("resume", m.fullAction(m.resumeAction))
agent.MustRegisterAction("flip", m.fullAction(m.flipAction))
}
if m.cfg.stopable != nil {
agent.MustRegisterAction("shutdown", m.fullAction(m.shutdownAction))
}
if m.cfg.healthcheckable != nil {
agent.MustRegisterAction("health", m.roAction(m.healthAction))
}
if m.cfg.logsetable != nil {
agent.MustRegisterAction("debuglvl", m.fullAction(m.debugLevelAction))
agent.MustRegisterAction("infolvl", m.fullAction(m.infoLevelAction))
agent.MustRegisterAction("warnlvl", m.fullAction(m.warnLevelAction))
agent.MustRegisterAction("critlvl", m.fullAction(m.critLevelAction))
}
agent.MustRegisterAction("info", m.roAction(m.infoAction))
agent.MustRegisterAction("ping", m.roAction(m.pingAction))
return m.cserver.RegisterAgent(ctx, md.Name, agent)
}
func (m *Management) roAction(a mcorpc.Action) mcorpc.Action {
return func(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
if !m.cfg.auth.ROAllowed(req.CallerID) {
reply.Statuscode = mcorpc.Aborted
reply.Statusmsg = "You are not authorized to call this agent or action."
return
}
m.mu.Lock()
defer m.mu.Unlock()
a(ctx, req, reply, agent, conn)
}
}
func (m *Management) fullAction(a mcorpc.Action) mcorpc.Action {
return func(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
if !m.cfg.auth.FullAllowed(req.CallerID) {
reply.Statuscode = mcorpc.Aborted
reply.Statusmsg = "You are not authorized to call this agent or action."
return
}
m.mu.Lock()
defer m.mu.Unlock()
a(ctx, req, reply, agent, conn)
}
}
func (m *Management) debugLevelAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.logsetable.SetLogLevel(DebugLevel)
reply.Data = &LogLevelReply{
Level: "debug",
}
}
func (m *Management) infoLevelAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.logsetable.SetLogLevel(InfoLevel)
reply.Data = &LogLevelReply{
Level: "info",
}
}
func (m *Management) warnLevelAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.logsetable.SetLogLevel(WarnLevel)
reply.Data = &LogLevelReply{
Level: "warning",
}
}
func (m *Management) critLevelAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.logsetable.SetLogLevel(CriticalLevel)
reply.Data = &LogLevelReply{
Level: "critical",
}
}
func (m *Management) pingAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
reply.Data = &PingReply{
Version: agent.Metadata().Version,
}
}
func (m *Management) healthAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
r, ok := m.cfg.healthcheckable.HealthCheck()
j, err := json.Marshal(r)
if err != nil {
j = []byte(`{"error":"could not JSON encode result"}`)
}
reply.Data = &HealthReply{
Healthy: ok,
Result: json.RawMessage(j),
}
}
func (m *Management) shutdownAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
delay := time.Duration(rand.Intn(int(m.cfg.maxStopDelay))) + time.Second
r := func(d time.Duration) {
time.Sleep(d)
agent.Log.Warnf("Shutting down after shutdown action invoked by the backplane")
m.cfg.stopable.Shutdown()
}
agent.Log.Warnf("Scheduling shutdown after %s delay", delay)
go r(delay)
reply.Data = ShutdownReply{
Delay: delay.String(),
}
}
func (m *Management) pauseAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.pausable.Pause()
m.pinfo(reply)
}
func (m *Management) resumeAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.pausable.Resume()
m.pinfo(reply)
}
func (m *Management) flipAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
m.cfg.pausable.Flip()
m.pinfo(reply)
}
func (m *Management) infoAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, agent *mcorpc.Agent, conn choria.ConnectorInfo) {
info := &InfoReply{
BackplaneVersion: agent.Metadata().Version,
Version: "unknown",
LogLevel: "unknown",
}
if m.cfg.infosource != nil {
info.Version = m.cfg.infosource.Version()
info.Facts = m.cfg.infosource.FactData()
info.FactsFeature = true
}
if m.cfg.healthcheckable != nil {
_, info.Healthy = m.cfg.healthcheckable.HealthCheck()
info.HealthFeature = true
}
if m.cfg.pausable != nil {
info.Paused = m.cfg.pausable.Paused()
info.PauseFeature = true
}
if m.cfg.stopable != nil {
info.ShutdownFeature = true
}
if m.cfg.logsetable != nil {
switch m.cfg.logsetable.GetLogLevel() {
case DebugLevel:
info.LogLevel = "debug"
case InfoLevel:
info.LogLevel = "info"
case WarnLevel:
info.LogLevel = "warning"
case CriticalLevel:
info.LogLevel = "critical"
default:
info.LogLevel = "unknown"
}
info.LogLevelFeature = true
}
reply.Data = info
}
func (m *Management) pinfo(r *mcorpc.Reply) {
r.Data = &PausableReply{
Paused: m.cfg.pausable.Paused(),
}
}
// AgentMetadata returns the agent metadata
func AgentMetadata() *agents.Metadata {
return &agents.Metadata{
Name: "backplane",
Description: "Choria Management Backplane",
Author: "R.I.Pienaar <rip@devco.net>",
Version: Version,
License: "Apache-2.0",
URL: "https://choria.io",
Timeout: 10,
}
}
// AgentDDL creates a DDL for the agent
func AgentDDL() *agent.DDL {
ddl := &agent.DDL{
Metadata: AgentMetadata(),
Actions: []*agent.Action{},
Schema: "https://choria.io/schemas/mcorpc/ddl/v1/agent.json",
}
act := &agent.Action{
Name: "ping",
Description: "Backplane communications test",
Display: "failed",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"version": &agent.ActionOutputItem{
Description: "The version of the Choria Backplane system in use",
DisplayAs: "Choria Backplane",
Type: "string",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["version"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
act = &agent.Action{
Name: "info",
Description: "Information about the managed service",
Display: "always",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"backplane_version": &agent.ActionOutputItem{
Description: "The version of the Choria Backplane system in use",
DisplayAs: "Choria Backplane",
Type: "string",
},
"version": &agent.ActionOutputItem{
Description: "Service Version",
DisplayAs: "Version",
Type: "string",
},
"healthy": &agent.ActionOutputItem{
Description: "Health Status",
DisplayAs: "Healthy",
Type: "boolean",
},
"loglevel": &agent.ActionOutputItem{
Description: "Active log level",
DisplayAs: "Log Level",
Type: "string",
},
"healthcheck_feature": &agent.ActionOutputItem{
Description: "If the HealthCheckable interface is used",
DisplayAs: "Health Feature",
Type: "boolean",
},
"pause_feature": &agent.ActionOutputItem{
Description: "If the Pausable interface is used",
DisplayAs: "Circuit Breaker Feature",
Type: "boolean",
},
"shutdown_feature": &agent.ActionOutputItem{
Description: "If the Stopable interface is used",
DisplayAs: "Shutdown Feature",
Type: "boolean",
},
"facts_feature": &agent.ActionOutputItem{
Description: "If the InfoSource interface is used",
DisplayAs: "Facts Feature",
Type: "boolean",
},
"loglevel_feature": &agent.ActionOutputItem{
Description: "If the LogLevelSetable interface is used",
DisplayAs: "Log Level Feature",
Type: "boolean",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["version"]`),
},
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["paused"]`),
},
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["healthy"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
act = &agent.Action{
Name: "shutdown",
Description: "Terminates the managed service",
Display: "failed",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"delay": &agent.ActionOutputItem{
Description: "How long after running the action the shutdown will be initiated",
DisplayAs: "Delay",
Type: "string",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["delay"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
act = &agent.Action{
Name: "health",
Description: "Checks the health of the managed service",
Display: "failed",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"result": &agent.ActionOutputItem{
Description: "The result from the check method",
DisplayAs: "Result",
Type: "string",
},
"healthy": &agent.ActionOutputItem{
Description: "Status indicator for the checked service",
DisplayAs: "Healthy",
Type: "boolean",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["healthy"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
for _, action := range strings.Fields("pause resume flip") {
act = &agent.Action{
Name: action,
Description: action,
Display: "always",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"paused": &agent.ActionOutputItem{
Description: "Circuit Breaker pause state",
DisplayAs: "Paused",
Type: "boolean",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["paused"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
}
for _, action := range strings.Fields("debuglvl infolvl warnlvl critlvl") {
act = &agent.Action{
Name: action,
Description: action,
Display: "always",
Input: make(map[string]*agent.ActionInputItem),
Output: map[string]*agent.ActionOutputItem{
"level": &agent.ActionOutputItem{
Description: "Log level that was activated",
DisplayAs: "Log Level",
Type: "string",
},
},
Aggregation: []agent.ActionAggregateItem{
agent.ActionAggregateItem{
Function: "summary",
Arguments: json.RawMessage(`["level"]`),
},
},
}
ddl.Actions = append(ddl.Actions, act)
}
return ddl
}