-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathcoordinator.go
1679 lines (1484 loc) · 56.7 KB
/
coordinator.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package coordinator
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync/atomic"
"time"
"go.elastic.co/apm/v2"
"gopkg.in/yaml.v2"
"github.com/elastic/elastic-agent-client/v7/pkg/client"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/info"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/reexec"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/details"
"github.com/elastic/elastic-agent/internal/pkg/agent/configuration"
"github.com/elastic/elastic-agent/internal/pkg/agent/transpiler"
"github.com/elastic/elastic-agent/internal/pkg/capabilities"
"github.com/elastic/elastic-agent/internal/pkg/config"
"github.com/elastic/elastic-agent/internal/pkg/diagnostics"
"github.com/elastic/elastic-agent/internal/pkg/fleetapi"
"github.com/elastic/elastic-agent/internal/pkg/fleetapi/acker"
"github.com/elastic/elastic-agent/pkg/component"
"github.com/elastic/elastic-agent/pkg/component/runtime"
agentclient "github.com/elastic/elastic-agent/pkg/control/v2/client"
"github.com/elastic/elastic-agent/pkg/control/v2/cproto"
"github.com/elastic/elastic-agent/pkg/core/logger"
"github.com/elastic/elastic-agent/pkg/features"
"github.com/elastic/elastic-agent/pkg/limits"
"github.com/elastic/elastic-agent/pkg/utils/broadcaster"
)
// ErrNotUpgradable error is returned when upgrade cannot be performed.
var ErrNotUpgradable = errors.New(
"cannot be upgraded; must be installed with install sub-command and " +
"running under control of the systems supervisor")
// ErrUpgradeInProgress error is returned if two or more upgrades are
// attempted at the same time.
var ErrUpgradeInProgress = errors.New("upgrade already in progress")
// ReExecManager provides an interface to perform re-execution of the entire agent.
type ReExecManager interface {
ReExec(callback reexec.ShutdownCallbackFn, argOverrides ...string)
}
// UpgradeManager provides an interface to perform the upgrade action for the agent.
type UpgradeManager interface {
// Upgradeable returns true if can be upgraded.
Upgradeable() bool
// Reload reloads the configuration for the upgrade manager.
Reload(rawConfig *config.Config) error
// Upgrade upgrades running agent.
Upgrade(ctx context.Context, version string, sourceURI string, action *fleetapi.ActionUpgrade, details *details.Details, skipVerifyOverride bool, skipDefaultPgp bool, pgpBytes ...string) (_ reexec.ShutdownCallbackFn, err error)
// Ack is used on startup to check if the agent has upgraded and needs to send an ack for the action
Ack(ctx context.Context, acker acker.Acker) error
// MarkerWatcher returns a watcher for the upgrade marker.
MarkerWatcher() upgrade.MarkerWatcher
}
// MonitorManager provides an interface to perform the monitoring action for the agent.
type MonitorManager interface {
// Enabled when configured to collect metrics/logs.
Enabled() bool
// Reload reloads the configuration for the upgrade manager.
Reload(rawConfig *config.Config) error
// MonitoringConfig injects monitoring configuration into resolved ast tree.
// args:
// - the existing config policy
// - a list of the expected running components
// - a map of component IDs to binary names
// - a map of component IDs to the PIDs of the running components.
MonitoringConfig(map[string]interface{}, []component.Component, map[string]string, map[string]uint64) (map[string]interface{}, error)
}
// Runner provides interface to run a manager and receive running errors.
type Runner interface {
// Run runs the manager.
Run(context.Context) error
// Errors returns the channel to listen to errors on.
//
// A manager should send a nil error to clear its previous error when it should no longer report as an error.
Errors() <-chan error
}
// RuntimeManager provides an interface to run and update the runtime.
type RuntimeManager interface {
Runner
// Update updates the current components model.
Update(model component.Model)
// PerformAction executes an action on a unit.
PerformAction(ctx context.Context, comp component.Component, unit component.Unit, name string, params map[string]interface{}) (map[string]interface{}, error)
// SubscribeAll provides an interface to watch for changes in all components.
SubscribeAll(context.Context) *runtime.SubscriptionAll
// PerformDiagnostics executes the diagnostic action for the provided units. If no units are provided then
// it performs diagnostics for all current units.
PerformDiagnostics(context.Context, ...runtime.ComponentUnitDiagnosticRequest) []runtime.ComponentUnitDiagnostic
// PerformComponentDiagnostics executes the diagnostic action for the provided components. If no components are provided,
// then it performs the diagnostics for all current units.
PerformComponentDiagnostics(ctx context.Context, additionalMetrics []cproto.AdditionalDiagnosticRequest, req ...component.Component) ([]runtime.ComponentDiagnostic, error)
}
// ConfigChange provides an interface for receiving a new configuration.
//
// Ack must be called if the configuration change was accepted and Fail should be called if it fails to be accepted.
type ConfigChange interface {
// Config returns the configuration for this change.
Config() *config.Config
// Ack marks the configuration change as accepted.
Ack() error
// Fail marks the configuration change as failed.
Fail(err error)
}
// ErrorReporter provides an interface for any manager that is handled by the coordinator to report errors.
type ErrorReporter interface{}
// ConfigManager provides an interface to run and watch for configuration changes.
type ConfigManager interface {
Runner
// ActionErrors returns the error channel for actions.
// May return errors for fleet managed agents.
// Will always be empty for standalone agents.
ActionErrors() <-chan error
// Watch returns the chanel to watch for configuration changes.
Watch() <-chan ConfigChange
}
// VarsManager provides an interface to run and watch for variable changes.
type VarsManager interface {
Runner
// Watch returns the chanel to watch for variable changes.
Watch() <-chan []*transpiler.Vars
}
// ComponentsModifier is a function that takes the computed components model and modifies it before
// passing it into the components runtime manager.
type ComponentsModifier func(comps []component.Component, cfg map[string]interface{}) ([]component.Component, error)
// managerShutdownTimeout is how long the coordinator will wait during shutdown
// to receive termination states from its managers.
const managerShutdownTimeout = time.Second * 5
type configReloader interface {
Reload(*config.Config) error
}
// Coordinator manages the entire state of the Elastic Agent.
//
// All configuration changes, update variables, and upgrade actions are managed and controlled by the coordinator.
type Coordinator struct {
logger *logger.Logger
agentInfo info.Agent
isManaged bool
cfg *configuration.Configuration
specs component.RuntimeSpecs
reexecMgr ReExecManager
upgradeMgr UpgradeManager
monitorMgr MonitorManager
monitoringServerReloader configReloader
runtimeMgr RuntimeManager
configMgr ConfigManager
varsMgr VarsManager
caps capabilities.Capabilities
modifiers []ComponentsModifier
// The current state of the Coordinator. This value and its subfields are
// safe to read directly from within the main Coordinator goroutine.
// Changes are also safe but must set the stateNeedsRefresh flag to ensure
// an update is broadcast at the end of the current iteration (so it is
// recommended to make changes via helper funtions like setCoordinatorState,
// setFleetState, etc). Changes that need to broadcast immediately without
// waiting for the end of the iteration can call stateRefresh() directly,
// but this should be rare.
//
// state should never be directly read or written outside the Coordinator
// goroutine. Callers who need to access or modify the state should use the
// public accessors like State(), SetLogLevel(), etc.
state State
stateBroadcaster *broadcaster.Broadcaster[State]
// If you get a race detector error while accessing this field, it probably
// means you're calling private Coordinator methods from outside the
// Coordinator goroutine.
stateNeedsRefresh bool
// overrideState is used during the update process to report the overall
// upgrade progress instead of the Coordinator's baseline internal state.
overrideState *coordinatorOverrideState
// overrideStateChan forwards override states from the publicly accessible
// SetOverrideState helper to the Coordinator goroutine.
overrideStateChan chan *coordinatorOverrideState
// upgradeDetailsChan forwards upgrade details from the publicly accessible
// SetUpgradeDetails helper to the Coordinator goroutine.
upgradeDetailsChan chan *details.Details
// loglevelCh forwards log level changes from the public API (SetLogLevel)
// to the run loop in Coordinator's main goroutine.
logLevelCh chan logp.Level
// managerChans collects the channels used to receive updates from the
// various managers. Coordinator reads from all of them during the run loop.
// Tests can safely override these before calling Coordinator.Run, or in
// between calls to Coordinator.runLoopIteration when testing synchronously.
// Tests can send to these channels to simulate manager updates.
managerChans managerChans
// Top-level errors reported by managers / actions. These will be folded
// into the reported state before broadcasting -- State() will report
// agentclient.Failed if one of these is set, even if the underlying
// coordinator state is agentclient.Healthy.
// Errors from the runtime manager report policy update failures and are
// stored in runtimeUpdateErr below.
configMgrErr error
actionsErr error
varsMgrErr error
// Errors resulting from different possible failure modes when setting a
// new policy. Right now there are three different stages where a policy
// update can fail:
// - in generateAST, converting the policy to an AST
// - in process, converting the AST and vars into a full component model
// - while applying the final component model in the runtime manager
// (reported asynchronously via the runtime manager error channel)
//
// The plan is to improve our preprocessing so we can always detect
// failures immediately https://github.com/elastic/elastic-agent/issues/2887.
// For now, we track three distinct errors for those three failure types,
// and merge them into a readable error in generateReportableState.
configErr error
componentGenErr error
runtimeUpdateErr error
// The raw policy before spec lookup or variable substitution
ast *transpiler.AST
// The current variables
vars []*transpiler.Vars
// The policy after spec and variable substitution
derivedConfig map[string]interface{}
// The final component model generated from ast and vars (this is the same
// value that is sent to the runtime manager).
componentModel []component.Component
// Disabled for 8.8.0 release in order to limit the surface
// https://github.com/elastic/security-team/issues/6501
// mx sync.RWMutex
// protection protection.Config
// a sync channel that can be called by other components to check if the main coordinator
// loop in runLoopIteration() is active and listening.
// Should only be interacted with via CoordinatorActive() or runLoopIteration()
heartbeatChan chan struct{}
// if a component (mostly endpoint) has a new PID, we need to update
// the monitoring components so they have a PID to monitor
// however, if endpoint is in some kind of restart loop,
// we could DOS the config system. Instead,
// run a ticker that checks to see if we have a new PID.
componentPIDTicker *time.Ticker
componentPidRequiresUpdate *atomic.Bool
}
// The channels Coordinator reads to receive updates from the various managers.
type managerChans struct {
// runtimeManagerUpdate is not read-only because it is owned internally
// and written to by watchRuntimeComponents in a helper goroutine after
// receiving updates from the raw runtime manager channel.
runtimeManagerUpdate chan runtime.ComponentComponentState
runtimeManagerError <-chan error
configManagerUpdate <-chan ConfigChange
configManagerError <-chan error
actionsError <-chan error
varsManagerUpdate <-chan []*transpiler.Vars
varsManagerError <-chan error
upgradeMarkerUpdate <-chan upgrade.UpdateMarker
}
// diffCheck is a container used by checkAndLogUpdate()
type diffCheck struct {
inNew bool
inLast bool
updated bool
}
// UpdateStats reports the diff of a component update.
// This is primarily used as a log message, and exported in case it's needed elsewhere.
type UpdateStats struct {
Components UpdateComponentChange `json:"components"`
Outputs UpdateComponentChange `json:"outputs"`
}
// UpdateComponentChange reports stats for changes to a particular part of a config.
type UpdateComponentChange struct {
Added []string `json:"added,omitempty"`
Removed []string `json:"removed,omitempty"`
Updated []string `json:"updated,omitempty"`
Count int `json:"count,omitempty"`
}
// New creates a new coordinator.
func New(logger *logger.Logger, cfg *configuration.Configuration, logLevel logp.Level, agentInfo info.Agent, specs component.RuntimeSpecs, reexecMgr ReExecManager, upgradeMgr UpgradeManager, runtimeMgr RuntimeManager, configMgr ConfigManager, varsMgr VarsManager, caps capabilities.Capabilities, monitorMgr MonitorManager, isManaged bool, modifiers ...ComponentsModifier) *Coordinator {
var fleetState cproto.State
var fleetMessage string
if !isManaged {
// default enum value is STARTING which is confusing for standalone
fleetState = agentclient.Stopped
fleetMessage = "Not enrolled into Fleet"
}
state := State{
State: agentclient.Starting,
Message: "Starting",
FleetState: fleetState,
FleetMessage: fleetMessage,
LogLevel: logLevel,
}
c := &Coordinator{
logger: logger,
cfg: cfg,
agentInfo: agentInfo,
isManaged: isManaged,
specs: specs,
reexecMgr: reexecMgr,
upgradeMgr: upgradeMgr,
monitorMgr: monitorMgr,
runtimeMgr: runtimeMgr,
configMgr: configMgr,
varsMgr: varsMgr,
caps: caps,
modifiers: modifiers,
state: state,
// Note: the uses of a buffered input channel in our broadcaster (the
// third parameter to broadcaster.New) means that it is possible for
// immediately adjacent writes/reads not to match, e.g.:
//
// stateBroadcaster.Set(newState)
// reportedState := stateBroadcaster.Get() // may not match newState
//
// We accept this intentionally to make sure Coordinator itself blocks
// as rarely as possible. Within Coordinator's goroutine, we can always
// get the latest synchronized value by reading the state struct directly,
// so this only affects external callers, and we accept that some of those
// might be behind by a scheduler interrupt or so.
//
// If this ever changes and we decide we need absolute causal
// synchronization in the subscriber API, just set the input buffer to 0.
stateBroadcaster: broadcaster.New(state, 64, 32),
logLevelCh: make(chan logp.Level),
overrideStateChan: make(chan *coordinatorOverrideState),
upgradeDetailsChan: make(chan *details.Details),
heartbeatChan: make(chan struct{}),
componentPIDTicker: time.NewTicker(time.Second * 30),
componentPidRequiresUpdate: &atomic.Bool{},
}
// Setup communication channels for any non-nil components. This pattern
// lets us transparently accept nil managers / simulated events during
// unit testing.
if runtimeMgr != nil {
// The runtime manager's update channel is a special case: unlike the
// other channels, we create it directly instead of reading it from the
// manager. Once Coordinator.runner starts, it calls watchRuntimeComponents
// in a helper goroutine, which subscribes directly to the runtime manager.
// It then scans and logs any changes before forwarding the update
// unmodified to this channel to merge with Coordinator.state. This is just
// to keep the work of scanning and logging the component changes off the
// main Coordinator goroutine.
// Tests want to simulate a component state update can send directly to
// this channel, as long as they aren't specifically testing the logging
// behavior in watchRuntimeComponents.
c.managerChans.runtimeManagerUpdate = make(chan runtime.ComponentComponentState)
c.managerChans.runtimeManagerError = runtimeMgr.Errors()
}
if configMgr != nil {
c.managerChans.configManagerUpdate = configMgr.Watch()
c.managerChans.configManagerError = configMgr.Errors()
c.managerChans.actionsError = configMgr.ActionErrors()
}
if varsMgr != nil {
c.managerChans.varsManagerUpdate = varsMgr.Watch()
c.managerChans.varsManagerError = varsMgr.Errors()
}
if upgradeMgr != nil && upgradeMgr.MarkerWatcher() != nil {
c.managerChans.upgradeMarkerUpdate = upgradeMgr.MarkerWatcher().Watch()
}
return c
}
// State returns the current state for the coordinator. It might be a state
// behind the actual state. See broadcaster.New for details.
// Called by external goroutines.
func (c *Coordinator) State() State {
return c.stateBroadcaster.Get()
}
// IsActive is a blocking method that waits for a channel response
// from the coordinator loop. This can be used to as a basic health check,
// as we'll timeout and return false if the coordinator run loop doesn't
// respond to our channel.
func (c *Coordinator) IsActive(timeout time.Duration) bool {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
select {
case <-c.heartbeatChan:
return true
case <-ctx.Done():
return false
}
}
func (c *Coordinator) RegisterMonitoringServer(s configReloader) {
c.monitoringServerReloader = s
}
// StateSubscribe returns a channel that reports changes in Coordinator state.
//
// bufferLen specifies how many state changes should be queued in addition to
// the most recent one. If bufferLen is 0, reads on the channel always return
// the current state. Otherwise, multiple changes that occur between reads
// will accumulate up to bufferLen. If the most recent state has already been
// read, reads on the channel will block until the next state change.
//
// The returned channel always returns at least one value, and will keep
// returning changes until its context is cancelled or the Coordinator shuts
// down. After Coordinator shutdown, the channel will continue returning
// pending changes until the subscriber reads the final one, when the channel
// will be closed. On context cancel, the channel is closed immediately.
//
// This is safe to call from external goroutines, and subscriber behavior can
// never block Coordinator -- see the broadcaster package for detailed
// performance guarantees.
func (c *Coordinator) StateSubscribe(ctx context.Context, bufferLen int) chan State {
return c.stateBroadcaster.Subscribe(ctx, bufferLen)
}
// Disabled for 8.8.0 release in order to limit the surface
// https://github.com/elastic/security-team/issues/6501
// // Protection returns the current agent protection configuration
// // This is needed to be able to access the protection configuration for actions validation
// func (c *Coordinator) Protection() protection.Config {
// c.mx.RLock()
// defer c.mx.RUnlock()
// return c.protection
// }
// // setProtection sets protection configuration
// func (c *Coordinator) setProtection(protectionConfig protection.Config) {
// c.mx.Lock()
// c.protection = protectionConfig
// c.mx.Unlock()
// }
// ReExec performs the re-execution.
// Called from external goroutines.
func (c *Coordinator) ReExec(callback reexec.ShutdownCallbackFn, argOverrides ...string) {
// override the overall state to stopping until the re-execution is complete
c.SetOverrideState(agentclient.Stopping, "Re-executing")
c.reexecMgr.ReExec(callback, argOverrides...)
}
// Upgrade runs the upgrade process.
// Called from external goroutines.
func (c *Coordinator) Upgrade(ctx context.Context, version string, sourceURI string, action *fleetapi.ActionUpgrade, skipVerifyOverride bool, skipDefaultPgp bool, pgpBytes ...string) error {
// early check outside of upgrader before overriding the state
if !c.upgradeMgr.Upgradeable() {
return ErrNotUpgradable
}
// early check capabilities to ensure this upgrade actions is allowed
if c.caps != nil {
if !c.caps.AllowUpgrade(version, sourceURI) {
return ErrNotUpgradable
}
}
// A previous upgrade may be cancelled and needs some time to
// run the callback to clear the state
var err error
for i := 0; i < 5; i++ {
s := c.State()
if s.State != agentclient.Upgrading {
err = nil
break
}
err = ErrUpgradeInProgress
time.Sleep(1 * time.Second)
}
if err != nil {
return err
}
// override the overall state to upgrading until the re-execution is complete
c.SetOverrideState(agentclient.Upgrading, fmt.Sprintf("Upgrading to version %s", version))
// initialize upgrade details
actionID := ""
if action != nil {
actionID = action.ActionID
}
det := details.NewDetails(version, details.StateRequested, actionID)
det.RegisterObserver(c.SetUpgradeDetails)
cb, err := c.upgradeMgr.Upgrade(ctx, version, sourceURI, action, det, skipVerifyOverride, skipDefaultPgp, pgpBytes...)
if err != nil {
c.ClearOverrideState()
det.Fail(err)
return err
}
if cb != nil {
det.SetState(details.StateRestarting)
c.ReExec(cb)
}
return nil
}
func (c *Coordinator) logUpgradeDetails(details *details.Details) {
c.logger.Infow("updated upgrade details", "upgrade_details", details)
}
// AckUpgrade is the method used on startup to ack a previously successful upgrade action.
// Called from external goroutines.
func (c *Coordinator) AckUpgrade(ctx context.Context, acker acker.Acker) error {
return c.upgradeMgr.Ack(ctx, acker)
}
// PerformAction executes an action on a unit.
// Called from external goroutines.
func (c *Coordinator) PerformAction(ctx context.Context, comp component.Component, unit component.Unit, name string, params map[string]interface{}) (map[string]interface{}, error) {
return c.runtimeMgr.PerformAction(ctx, comp, unit, name, params)
}
// PerformDiagnostics executes the diagnostic action for the provided units. If no units are provided then
// it performs diagnostics for all current units.
// Called from external goroutines.
func (c *Coordinator) PerformDiagnostics(ctx context.Context, req ...runtime.ComponentUnitDiagnosticRequest) []runtime.ComponentUnitDiagnostic {
return c.runtimeMgr.PerformDiagnostics(ctx, req...)
}
// PerformComponentDiagnostics executes the diagnostic action for the provided components.
func (c *Coordinator) PerformComponentDiagnostics(ctx context.Context, additionalMetrics []cproto.AdditionalDiagnosticRequest, req ...component.Component) ([]runtime.ComponentDiagnostic, error) {
return c.runtimeMgr.PerformComponentDiagnostics(ctx, additionalMetrics, req...)
}
// SetLogLevel changes the entire log level for the running Elastic Agent.
// Called from external goroutines.
func (c *Coordinator) SetLogLevel(ctx context.Context, lvl *logp.Level) error {
if lvl == nil {
return fmt.Errorf("logp.Level passed to Coordinator.SetLogLevel() must be not nil")
}
select {
case <-ctx.Done():
return ctx.Err()
case c.logLevelCh <- *lvl:
// set global once the level change has been taken by the channel
logger.SetLevel(*lvl)
return nil
}
}
// watchRuntimeComponents listens for state updates from the runtime
// manager, logs them, and forwards them to CoordinatorState.
// Runs in its own goroutine created in Coordinator.Run.
func (c *Coordinator) watchRuntimeComponents(ctx context.Context) {
state := make(map[string]runtime.ComponentState)
var subChan <-chan runtime.ComponentComponentState
// A real Coordinator will always have a runtime manager, but unit tests
// may not initialize all managers -- in that case we leave subChan nil,
// and just idle until Coordinator shuts down.
if c.runtimeMgr != nil {
subChan = c.runtimeMgr.SubscribeAll(ctx).Ch()
}
for {
select {
case <-ctx.Done():
return
case s := <-subChan:
oldState, ok := state[s.Component.ID]
if !ok {
componentLog := coordinatorComponentLog{
ID: s.Component.ID,
State: s.State.State.String(),
}
logBasedOnState(c.logger, s.State.State, fmt.Sprintf("Spawned new component %s: %s", s.Component.ID, s.State.Message), "component", componentLog)
for ui, us := range s.State.Units {
unitLog := coordinatorUnitLog{
ID: ui.UnitID,
Type: ui.UnitType.String(),
State: us.State.String(),
}
logBasedOnState(c.logger, us.State, fmt.Sprintf("Spawned new unit %s: %s", ui.UnitID, us.Message), "component", componentLog, "unit", unitLog)
}
} else {
componentLog := coordinatorComponentLog{
ID: s.Component.ID,
State: s.State.State.String(),
}
if oldState.State != s.State.State {
cl := coordinatorComponentLog{
ID: s.Component.ID,
State: s.State.State.String(),
OldState: oldState.State.String(),
}
logBasedOnState(c.logger, s.State.State, fmt.Sprintf("Component state changed %s (%s->%s): %s", s.Component.ID, oldState.State.String(), s.State.State.String(), s.State.Message), "component", cl)
}
for ui, us := range s.State.Units {
oldUS, ok := oldState.Units[ui]
if !ok {
unitLog := coordinatorUnitLog{
ID: ui.UnitID,
Type: ui.UnitType.String(),
State: us.State.String(),
}
logBasedOnState(c.logger, us.State, fmt.Sprintf("Spawned new unit %s: %s", ui.UnitID, us.Message), "component", componentLog, "unit", unitLog)
} else if oldUS.State != us.State {
unitLog := coordinatorUnitLog{
ID: ui.UnitID,
Type: ui.UnitType.String(),
State: us.State.String(),
OldState: oldUS.State.String(),
}
logBasedOnState(c.logger, us.State, fmt.Sprintf("Unit state changed %s (%s->%s): %s", ui.UnitID, oldUS.State.String(), us.State.String(), us.Message), "component", componentLog, "unit", unitLog)
}
}
}
state[s.Component.ID] = s.State
if s.State.State == client.UnitStateStopped {
delete(state, s.Component.ID)
}
// Forward the final changes back to Coordinator, unless our context
// has ended.
select {
case c.managerChans.runtimeManagerUpdate <- s:
case <-ctx.Done():
return
}
}
}
}
// Run runs the Coordinator. Must be called on the Coordinator's main goroutine.
//
// The RuntimeManager, ConfigManager and VarsManager that is passed into NewCoordinator are also ran and lifecycle controlled by the Run.
//
// If any of the three managers fail, the Coordinator will shut down and
// Run will return an error.
func (c *Coordinator) Run(ctx context.Context) error {
// log all changes in the state of the runtime and update the coordinator state
watchCtx, watchCanceller := context.WithCancel(ctx)
defer watchCanceller()
go c.watchRuntimeComponents(watchCtx)
// Close the state broadcaster on finish, but leave it running in the
// background until all subscribers have read the final values or their
// context ends, so test listeners and such can collect Coordinator's
// shutdown state.
defer close(c.stateBroadcaster.InputChan)
if c.varsMgr != nil {
c.setCoordinatorState(agentclient.Starting, "Waiting for initial configuration and composable variables")
} else {
// vars not initialized, go directly to running
c.setCoordinatorState(agentclient.Healthy, "Running")
}
// The usual state refresh happens in the main run loop in Coordinator.runner,
// so before/after the runner call we need to trigger state change broadcasts
// manually with refreshState.
c.refreshState()
err := c.runner(ctx)
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
c.setCoordinatorState(agentclient.Stopped, "Requested to be stopped")
c.setFleetState(agentclient.Stopped, "Requested to be stopped")
} else {
var message string
if err != nil {
message = fmt.Sprintf("Fatal coordinator error: %v", err.Error())
} else {
// runner should always return a non-nil error, but if it doesn't,
// report it.
message = "Coordinator terminated with unknown error (runner returned nil)"
}
c.setCoordinatorState(agentclient.Failed, message)
c.setFleetState(agentclient.Stopped, message)
}
// Broadcast the final state in case anyone is still listening
c.refreshState()
return err
}
// DiagnosticHooks returns diagnostic hooks that can be connected to the control server to provide diagnostic
// information about the state of the Elastic Agent.
// Called by external goroutines.
func (c *Coordinator) DiagnosticHooks() diagnostics.Hooks {
return diagnostics.Hooks{
{
Name: "agent-info",
Filename: "agent-info.yaml",
Description: "current state of the agent information of the running Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
output := struct {
AgentID string `yaml:"agent_id"`
Headers map[string]string `yaml:"headers"`
LogLevel string `yaml:"log_level"`
Snapshot bool `yaml:"snapshot"`
Version string `yaml:"version"`
Unprivileged bool `yaml:"unprivileged"`
}{
AgentID: c.agentInfo.AgentID(),
Headers: c.agentInfo.Headers(),
LogLevel: c.agentInfo.LogLevel(),
Snapshot: c.agentInfo.Snapshot(),
Version: c.agentInfo.Version(),
Unprivileged: c.agentInfo.Unprivileged(),
}
o, err := yaml.Marshal(output)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "local-config",
Filename: "local-config.yaml",
Description: "current local configuration of the running Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
if c.cfg == nil {
return []byte("error: failed no local configuration")
}
o, err := yaml.Marshal(c.cfg)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "pre-config",
Filename: "pre-config.yaml",
Description: "current pre-configuration of the running Elastic Agent before variable substitution",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
if c.ast == nil {
return []byte("error: failed no configuration by the coordinator")
}
cfg, err := c.ast.Map()
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
o, err := yaml.Marshal(cfg)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "variables",
Filename: "variables.yaml",
Description: "current variable contexts of the running Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
if c.vars == nil {
return []byte("error: failed no variables by the coordinator")
}
vars := make([]map[string]interface{}, 0, len(c.vars))
for _, v := range c.vars {
m, err := v.Map()
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
vars = append(vars, m)
}
o, err := yaml.Marshal(struct {
Variables []map[string]interface{} `yaml:"variables"`
}{
Variables: vars,
})
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "computed-config",
Filename: "computed-config.yaml",
Description: "current computed configuration of the running Elastic Agent after variable substitution",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
cfg := c.derivedConfig
o, err := yaml.Marshal(cfg)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "components-expected",
Filename: "components-expected.yaml",
Description: "current expected components model of the running Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
comps := c.componentModel
o, err := yaml.Marshal(struct {
Components []component.Component `yaml:"components"`
}{
Components: comps,
})
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "components-actual",
Filename: "components-actual.yaml",
Description: "actual components model of the running Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
components := c.State().Components
componentConfigs := make([]component.Component, len(components))
for i := 0; i < len(components); i++ {
componentConfigs[i] = components[i].Component
}
o, err := yaml.Marshal(struct {
Components []component.Component `yaml:"components"`
}{
Components: componentConfigs,
})
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
{
Name: "state",
Filename: "state.yaml",
Description: "current state of running components by the Elastic Agent",
ContentType: "application/yaml",
Hook: func(_ context.Context) []byte {
type StateComponentOutput struct {
ID string `yaml:"id"`
State runtime.ComponentState `yaml:"state"`
}
type StateHookOutput struct {
State agentclient.State `yaml:"state"`
Message string `yaml:"message"`
FleetState agentclient.State `yaml:"fleet_state"`
FleetMessage string `yaml:"fleet_message"`
LogLevel logp.Level `yaml:"log_level"`
Components []StateComponentOutput `yaml:"components"`
UpgradeDetails *details.Details `yaml:"upgrade_details,omitempty"`
}
getState := func(c *Coordinator) (State, []StateComponentOutput) {
s := c.State()
compStates := make([]StateComponentOutput, len(s.Components))
for i, comp := range s.Components {
compStates[i] = StateComponentOutput{
ID: comp.Component.ID,
State: comp.State,
}
}
return s, compStates
}
// c.State() may return a stale state (up to 1 version behind)
// due to potential delays in state updates.
// If the state is HEALTH but `version_info` is missing, it
// indicates staleness.
// In this case, the state is re-fetched to obtain the latest
// information. After the second fetch, no more checks are
// performed and the state is returned as is.
var s State
var compStates []StateComponentOutput
outerLoop:
for i := 0; i < 5; i++ {
s, compStates = getState(c)
for _, cs := range compStates {
if cs.State.State == client.UnitStateHealthy &&
cs.State.VersionInfo.BuildHash != "" &&
cs.State.VersionInfo.Meta["commit"] != "" {
break outerLoop
}
}
time.Sleep(50 * time.Millisecond)
}
output := StateHookOutput{
State: s.State,
Message: s.Message,
FleetState: s.FleetState,
FleetMessage: s.FleetMessage,
LogLevel: s.LogLevel,
Components: compStates,
UpgradeDetails: s.UpgradeDetails,
}
o, err := yaml.Marshal(output)
if err != nil {
return []byte(fmt.Sprintf("error: %q", err))
}
return o
},
},
}
}
// runner performs the actual work of running all the managers.
// Called on the main Coordinator goroutine, from Coordinator.Run.
//
// if one of the managers terminates the others are also stopped and then the whole runner returns
func (c *Coordinator) runner(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer c.componentPIDTicker.Stop()
// We run nil checks before starting the various managers so that unit tests
// only have to initialize / mock the specific components they're testing.
// If a manager is nil, we prebuffer its return channel with nil also so
// handleCoordinatorDone doesn't block waiting for its result on shutdown.
// In a live agent, the manager fields are never nil.
runtimeErrCh := make(chan error, 1)
if c.runtimeMgr != nil {
go func() {
err := c.runtimeMgr.Run(ctx)
cancel()
runtimeErrCh <- err
}()
} else {
runtimeErrCh <- nil
}
configErrCh := make(chan error, 1)
if c.configMgr != nil {
go func() {
err := c.configMgr.Run(ctx)
cancel()
configErrCh <- err
}()
} else {
configErrCh <- nil
}
varsErrCh := make(chan error, 1)
if c.varsMgr != nil {