-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
supervisor.go
1432 lines (1199 loc) · 42.6 KB
/
supervisor.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 The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package supervisor
import (
"bytes"
"context"
"crypto/tls"
_ "embed"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"text/template"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/knadh/koanf/maps"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/rawbytes"
"github.com/knadh/koanf/v2"
"github.com/open-telemetry/opamp-go/client"
"github.com/open-telemetry/opamp-go/client/types"
"github.com/open-telemetry/opamp-go/protobufs"
"github.com/open-telemetry/opamp-go/server"
serverTypes "github.com/open-telemetry/opamp-go/server/types"
"go.opentelemetry.io/collector/config/configopaque"
"go.opentelemetry.io/collector/config/configtls"
semconv "go.opentelemetry.io/collector/semconv/v1.21.0"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
"github.com/open-telemetry/opentelemetry-collector-contrib/cmd/opampsupervisor/supervisor/commander"
"github.com/open-telemetry/opentelemetry-collector-contrib/cmd/opampsupervisor/supervisor/config"
"github.com/open-telemetry/opentelemetry-collector-contrib/cmd/opampsupervisor/supervisor/healthchecker"
)
var (
//go:embed templates/nooppipeline.yaml
noopPipelineTpl string
//go:embed templates/extraconfig.yaml
extraConfigTpl string
//go:embed templates/opampextension.yaml
opampextensionTpl string
//go:embed templates/owntelemetry.yaml
ownTelemetryTpl string
lastRecvRemoteConfigFile = "last_recv_remote_config.dat"
lastRecvOwnMetricsConfigFile = "last_recv_own_metrics_config.dat"
)
const (
persistentStateFileName = "persistent_state.yaml"
agentConfigFileName = "effective.yaml"
)
const maxBufferedCustomMessages = 10
type configState struct {
// Supervisor-assembled config to be given to the Collector.
mergedConfig string
// true if the server provided configmap was empty
configMapIsEmpty bool
}
func (c *configState) equal(other *configState) bool {
return other.mergedConfig == c.mergedConfig && other.configMapIsEmpty == c.configMapIsEmpty
}
// Supervisor implements supervising of OpenTelemetry Collector and uses OpAMPClient
// to work with an OpAMP Server.
type Supervisor struct {
logger *zap.Logger
pidProvider pidProvider
// Commander that starts/stops the Agent process.
commander *commander.Commander
startedAt time.Time
healthCheckTicker *backoff.Ticker
healthChecker *healthchecker.HTTPHealthChecker
lastHealthCheckErr error
// Supervisor's own config.
config config.Supervisor
agentDescription *atomic.Value
// Supervisor's persistent state
persistentState *persistentState
noopPipelineTemplate *template.Template
opampextensionTemplate *template.Template
extraConfigTemplate *template.Template
ownTelemetryTemplate *template.Template
agentConn *atomic.Value
// A config section to be added to the Collector's config to fetch its own metrics.
// TODO: store this persistently so that when starting we can compose the effective
// config correctly.
// https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/21078
agentConfigOwnMetricsSection *atomic.Value
// agentHealthCheckEndpoint is the endpoint the Collector's health check extension
// will listen on for health check requests from the Supervisor.
agentHealthCheckEndpoint string
// Internal config state for agent use. See the configState struct for more details.
cfgState *atomic.Value
// Final effective config of the Collector.
effectiveConfig *atomic.Value
// Last received remote config.
remoteConfig *protobufs.AgentRemoteConfig
// A channel to indicate there is a new config to apply.
hasNewConfig chan struct{}
// configApplyTimeout is the maximum time to wait for the agent to apply a new config.
// After this time passes without the agent reporting health as OK, the agent is considered unhealthy.
configApplyTimeout time.Duration
// lastHealthFromClient is the last health status of the agent received from the client.
lastHealthFromClient *protobufs.ComponentHealth
// lastHealth is the last health status of the agent.
lastHealth *protobufs.ComponentHealth
// The OpAMP client to connect to the OpAMP Server.
opampClient client.OpAMPClient
doneChan chan struct{}
agentWG sync.WaitGroup
customMessageToServer chan *protobufs.CustomMessage
customMessageWG sync.WaitGroup
// agentHasStarted is true if the agent has started.
agentHasStarted bool
// agentStartHealthCheckAttempts is the number of health check attempts made by the agent since it started.
agentStartHealthCheckAttempts int
// agentRestarting is true if the agent is restarting.
agentRestarting atomic.Bool
// The OpAMP server to communicate with the Collector's OpAMP extension
opampServer server.OpAMPServer
opampServerPort int
}
func NewSupervisor(logger *zap.Logger, cfg config.Supervisor) (*Supervisor, error) {
s := &Supervisor{
logger: logger,
pidProvider: defaultPIDProvider{},
hasNewConfig: make(chan struct{}, 1),
agentConfigOwnMetricsSection: &atomic.Value{},
cfgState: &atomic.Value{},
effectiveConfig: &atomic.Value{},
agentDescription: &atomic.Value{},
doneChan: make(chan struct{}),
customMessageToServer: make(chan *protobufs.CustomMessage, maxBufferedCustomMessages),
agentConn: &atomic.Value{},
}
if err := s.createTemplates(); err != nil {
return nil, err
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("error validating config: %w", err)
}
s.config = cfg
if err := os.MkdirAll(s.config.Storage.Directory, 0700); err != nil {
return nil, fmt.Errorf("error creating storage dir: %w", err)
}
s.configApplyTimeout = s.config.Agent.ConfigApplyTimeout
return s, nil
}
func (s *Supervisor) Start() error {
var err error
s.persistentState, err = loadOrCreatePersistentState(s.persistentStateFilePath())
if err != nil {
return err
}
if err = s.getBootstrapInfo(); err != nil {
return fmt.Errorf("could not get bootstrap info from the Collector: %w", err)
}
healthCheckPort := s.config.Agent.HealthCheckPort
if healthCheckPort == 0 {
healthCheckPort, err = s.findRandomPort()
if err != nil {
return fmt.Errorf("could not find port for health check: %w", err)
}
}
s.agentHealthCheckEndpoint = fmt.Sprintf("localhost:%d", healthCheckPort)
s.logger.Info("Supervisor starting",
zap.String("id", s.persistentState.InstanceID.String()))
err = s.loadAndWriteInitialMergedConfig()
if err != nil {
return fmt.Errorf("failed loading initial config: %w", err)
}
if err = s.startOpAMP(); err != nil {
return fmt.Errorf("cannot start OpAMP client: %w", err)
}
s.commander, err = commander.NewCommander(
s.logger,
s.config.Storage.Directory,
s.config.Agent,
"--config", s.agentConfigFilePath(),
)
if err != nil {
return err
}
s.startHealthCheckTicker()
s.agentWG.Add(1)
go func() {
defer s.agentWG.Done()
s.runAgentProcess()
}()
s.customMessageWG.Add(1)
go func() {
defer s.customMessageWG.Done()
s.forwardCustomMessagesToServerLoop()
}()
return nil
}
func (s *Supervisor) createTemplates() error {
var err error
if s.noopPipelineTemplate, err = template.New("nooppipeline").Parse(noopPipelineTpl); err != nil {
return err
}
if s.extraConfigTemplate, err = template.New("extraconfig").Parse(extraConfigTpl); err != nil {
return err
}
if s.opampextensionTemplate, err = template.New("opampextension").Parse(opampextensionTpl); err != nil {
return err
}
if s.ownTelemetryTemplate, err = template.New("owntelemetry").Parse(ownTelemetryTpl); err != nil {
return err
}
return nil
}
// getBootstrapInfo obtains the Collector's agent description by
// starting a Collector with a specific config that only starts
// an OpAMP extension, obtains the agent description, then
// shuts down the Collector. This only needs to happen
// once per Collector binary.
func (s *Supervisor) getBootstrapInfo() (err error) {
s.opampServerPort, err = s.getSupervisorOpAMPServerPort()
if err != nil {
return err
}
bootstrapConfig, err := s.composeNoopConfig()
if err != nil {
return err
}
err = os.WriteFile(s.agentConfigFilePath(), bootstrapConfig, 0600)
if err != nil {
return fmt.Errorf("failed to write agent config: %w", err)
}
srv := server.New(newLoggerFromZap(s.logger))
done := make(chan error, 1)
var connected atomic.Bool
// Start a one-shot server to get the Collector's agent description
// using the Collector's OpAMP extension.
err = srv.Start(flattenedSettings{
endpoint: fmt.Sprintf("localhost:%d", s.opampServerPort),
onConnectingFunc: func(_ *http.Request) (bool, int) {
connected.Store(true)
return true, http.StatusOK
},
onMessageFunc: func(_ serverTypes.Connection, message *protobufs.AgentToServer) {
if message.AgentDescription != nil {
instanceIDSeen := false
s.setAgentDescription(message.AgentDescription)
identAttr := message.AgentDescription.IdentifyingAttributes
for _, attr := range identAttr {
if attr.Key == semconv.AttributeServiceInstanceID {
// TODO: Consider whether to attempt restarting the Collector.
// https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/29864
if attr.Value.GetStringValue() != s.persistentState.InstanceID.String() {
done <- fmt.Errorf(
"the Collector's instance ID (%s) does not match with the instance ID set by the Supervisor (%s)",
attr.Value.GetStringValue(),
s.persistentState.InstanceID.String())
return
}
instanceIDSeen = true
}
}
if !instanceIDSeen {
done <- errors.New("the Collector did not specify an instance ID in its AgentDescription message")
return
}
done <- nil
}
},
}.toServerSettings())
if err != nil {
return err
}
defer func() {
if stopErr := srv.Stop(context.Background()); stopErr != nil {
err = errors.Join(err, fmt.Errorf("error when stopping the opamp server: %w", stopErr))
}
}()
cmd, err := commander.NewCommander(
s.logger,
s.config.Storage.Directory,
s.config.Agent,
"--config", s.agentConfigFilePath(),
)
if err != nil {
return err
}
if err = cmd.Start(context.Background()); err != nil {
return err
}
defer func() {
if stopErr := cmd.Stop(context.Background()); stopErr != nil {
err = errors.Join(err, fmt.Errorf("error when stopping the collector: %w", stopErr))
}
}()
select {
case <-time.After(s.config.Agent.BootstrapTimeout):
if connected.Load() {
return errors.New("collector connected but never responded with an AgentDescription message")
} else {
return errors.New("collector's OpAMP client never connected to the Supervisor")
}
case err = <-done:
return err
}
}
func (s *Supervisor) startOpAMP() error {
if err := s.startOpAMPClient(); err != nil {
return err
}
if err := s.startOpAMPServer(); err != nil {
return err
}
return nil
}
func (s *Supervisor) startOpAMPClient() error {
s.opampClient = client.NewWebSocket(newLoggerFromZap(s.logger))
// determine if we need to load a TLS config or not
var tlsConfig *tls.Config
parsedURL, err := url.Parse(s.config.Server.Endpoint)
if err != nil {
return fmt.Errorf("parse server endpoint: %w", err)
}
if parsedURL.Scheme == "wss" || parsedURL.Scheme == "https" {
tlsConfig, err = s.config.Server.TLSSetting.LoadTLSConfig(context.Background())
if err != nil {
return err
}
}
s.logger.Debug("Connecting to OpAMP server...", zap.String("endpoint", s.config.Server.Endpoint), zap.Any("headers", s.config.Server.Headers))
settings := types.StartSettings{
OpAMPServerURL: s.config.Server.Endpoint,
Header: s.config.Server.Headers,
TLSConfig: tlsConfig,
InstanceUid: types.InstanceUid(s.persistentState.InstanceID),
Callbacks: types.CallbacksStruct{
OnConnectFunc: func(_ context.Context) {
s.logger.Debug("Connected to the server.")
},
OnConnectFailedFunc: func(_ context.Context, err error) {
s.logger.Error("Failed to connect to the server", zap.Error(err))
},
OnErrorFunc: func(_ context.Context, err *protobufs.ServerErrorResponse) {
s.logger.Error("Server returned an error response", zap.String("message", err.ErrorMessage))
},
OnMessageFunc: s.onMessage,
OnOpampConnectionSettingsFunc: func(ctx context.Context, settings *protobufs.OpAMPConnectionSettings) error {
//nolint:errcheck
go s.onOpampConnectionSettings(ctx, settings)
return nil
},
OnCommandFunc: func(_ context.Context, command *protobufs.ServerToAgentCommand) error {
cmdType := command.GetType()
if *cmdType.Enum() == protobufs.CommandType_CommandType_Restart {
return s.handleRestartCommand()
}
return nil
},
SaveRemoteConfigStatusFunc: func(_ context.Context, _ *protobufs.RemoteConfigStatus) {
// TODO: https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/21079
},
GetEffectiveConfigFunc: func(_ context.Context) (*protobufs.EffectiveConfig, error) {
return s.createEffectiveConfigMsg(), nil
},
},
Capabilities: s.config.Capabilities.SupportedCapabilities(),
}
ad := s.agentDescription.Load().(*protobufs.AgentDescription)
if err = s.opampClient.SetAgentDescription(ad); err != nil {
return err
}
if err = s.opampClient.SetHealth(&protobufs.ComponentHealth{Healthy: false}); err != nil {
return err
}
s.logger.Debug("Starting OpAMP client...")
if err = s.opampClient.Start(context.Background(), settings); err != nil {
return err
}
s.logger.Debug("OpAMP client started.")
return nil
}
// startOpAMPServer starts an OpAMP server that will communicate
// with an OpAMP extension running inside a Collector to receive
// data from inside the Collector. The internal server's lifetime is not
// matched to the Collector's process, but may be restarted
// depending on information received by the Supervisor from the remote
// OpAMP server.
func (s *Supervisor) startOpAMPServer() error {
s.opampServer = server.New(newLoggerFromZap(s.logger))
var err error
s.opampServerPort, err = s.getSupervisorOpAMPServerPort()
if err != nil {
return err
}
s.logger.Debug("Starting OpAMP server...")
connected := &atomic.Bool{}
err = s.opampServer.Start(flattenedSettings{
endpoint: fmt.Sprintf("localhost:%d", s.opampServerPort),
onConnectingFunc: func(_ *http.Request) (bool, int) {
// Only allow one agent to be connected the this server at a time.
alreadyConnected := connected.Swap(true)
return !alreadyConnected, http.StatusConflict
},
onMessageFunc: s.handleAgentOpAMPMessage,
onConnectionCloseFunc: func(_ serverTypes.Connection) {
connected.Store(false)
},
}.toServerSettings())
if err != nil {
return err
}
s.logger.Debug("OpAMP server started.")
return nil
}
func (s *Supervisor) handleAgentOpAMPMessage(conn serverTypes.Connection, message *protobufs.AgentToServer) {
s.agentConn.Store(conn)
s.logger.Debug("Received OpAMP message from the agent")
if message.AgentDescription != nil {
s.setAgentDescription(message.AgentDescription)
}
if message.EffectiveConfig != nil {
if cfg, ok := message.EffectiveConfig.GetConfigMap().GetConfigMap()[""]; ok {
s.logger.Debug("Received effective config from agent")
s.effectiveConfig.Store(string(cfg.Body))
err := s.opampClient.UpdateEffectiveConfig(context.Background())
if err != nil {
s.logger.Error("The OpAMP client failed to update the effective config", zap.Error(err))
}
} else {
s.logger.Error("Got effective config message, but the instance config was not present. Ignoring effective config.")
}
}
// Proxy client capabilities to server
if message.CustomCapabilities != nil {
err := s.opampClient.SetCustomCapabilities(message.CustomCapabilities)
if err != nil {
s.logger.Error("Failed to send custom capabilities to OpAMP server")
}
}
// Proxy agent custom messages to server
if message.CustomMessage != nil {
select {
case s.customMessageToServer <- message.CustomMessage:
default:
s.logger.Warn(
"Buffer full, skipping forwarding custom message to server",
zap.String("capability", message.CustomMessage.Capability),
zap.String("type", message.CustomMessage.Type),
)
}
}
if message.Health != nil {
s.logger.Debug("Received health status from agent", zap.Bool("healthy", message.Health.Healthy))
s.lastHealthFromClient = message.Health
}
}
func (s *Supervisor) forwardCustomMessagesToServerLoop() {
for {
select {
case cm := <-s.customMessageToServer:
for {
sendingChan, err := s.opampClient.SendCustomMessage(cm)
switch {
case errors.Is(err, types.ErrCustomMessagePending):
s.logger.Debug("Custom message pending, waiting to send...")
<-sendingChan
continue
case err == nil: // OK
s.logger.Debug("Custom message forwarded to server.")
default:
s.logger.Error("Failed to send custom message to OpAMP server")
}
break
}
case <-s.doneChan:
return
}
}
}
// setAgentDescription sets the agent description, merging in any user-specified attributes from the supervisor configuration.
func (s *Supervisor) setAgentDescription(ad *protobufs.AgentDescription) {
ad.IdentifyingAttributes = applyKeyValueOverrides(s.config.Agent.Description.IdentifyingAttributes, ad.IdentifyingAttributes)
ad.NonIdentifyingAttributes = applyKeyValueOverrides(s.config.Agent.Description.NonIdentifyingAttributes, ad.NonIdentifyingAttributes)
s.agentDescription.Store(ad)
}
// applyKeyValueOverrides merges the overrides map into the array of key value pairs.
// If a key from overrides already exists in the array of key value pairs, it is overwritten by the value from the overrides map.
// An array of KeyValue pair is returned, with each key value pair having a distinct key.
func applyKeyValueOverrides(overrides map[string]string, orig []*protobufs.KeyValue) []*protobufs.KeyValue {
kvMap := make(map[string]*protobufs.KeyValue, len(orig)+len(overrides))
for _, kv := range orig {
kvMap[kv.Key] = kv
}
for k, v := range overrides {
kvMap[k] = &protobufs.KeyValue{
Key: k,
Value: &protobufs.AnyValue{
Value: &protobufs.AnyValue_StringValue{
StringValue: v,
},
},
}
}
// Sort keys for stable output, makes it easier to test.
keys := make([]string, 0, len(kvMap))
for k := range kvMap {
keys = append(keys, k)
}
sort.Strings(keys)
kvOut := make([]*protobufs.KeyValue, 0, len(kvMap))
for _, k := range keys {
v := kvMap[k]
kvOut = append(kvOut, v)
}
return kvOut
}
func (s *Supervisor) stopOpAMPClient() error {
s.logger.Debug("Stopping OpAMP client...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := s.opampClient.Stop(ctx)
// TODO(srikanthccv): remove context.DeadlineExceeded after https://github.com/open-telemetry/opamp-go/pull/213
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
return err
}
s.logger.Debug("OpAMP client stopped.")
return nil
}
func (s *Supervisor) getHeadersFromSettings(protoHeaders *protobufs.Headers) http.Header {
headers := make(http.Header)
for _, header := range protoHeaders.Headers {
headers.Add(header.Key, header.Value)
}
return headers
}
func (s *Supervisor) onOpampConnectionSettings(_ context.Context, settings *protobufs.OpAMPConnectionSettings) error {
if settings == nil {
s.logger.Debug("Received ConnectionSettings request with nil settings")
return nil
}
newServerConfig := config.OpAMPServer{}
if settings.DestinationEndpoint != "" {
newServerConfig.Endpoint = settings.DestinationEndpoint
}
if settings.Headers != nil {
newServerConfig.Headers = s.getHeadersFromSettings(settings.Headers)
}
if settings.Certificate != nil {
if len(settings.Certificate.CaPublicKey) != 0 {
newServerConfig.TLSSetting.CAPem = configopaque.String(settings.Certificate.CaPublicKey)
}
if len(settings.Certificate.PublicKey) != 0 {
newServerConfig.TLSSetting.CertPem = configopaque.String(settings.Certificate.PublicKey)
}
if len(settings.Certificate.PrivateKey) != 0 {
newServerConfig.TLSSetting.KeyPem = configopaque.String(settings.Certificate.PrivateKey)
}
} else {
newServerConfig.TLSSetting = configtls.ClientConfig{Insecure: true}
}
if err := newServerConfig.Validate(); err != nil {
s.logger.Error("New OpAMP settings resulted in invalid configuration", zap.Error(err))
return err
}
if err := s.stopOpAMPClient(); err != nil {
s.logger.Error("Cannot stop the OpAMP client", zap.Error(err))
return err
}
// take a copy of the current OpAMP server config
oldServerConfig := s.config.Server
// update the OpAMP server config
s.config.Server = newServerConfig
if err := s.startOpAMPClient(); err != nil {
s.logger.Error("Cannot connect to the OpAMP server using the new settings", zap.Error(err))
// revert the OpAMP server config
s.config.Server = oldServerConfig
// start the OpAMP client with the old settings
if err := s.startOpAMPClient(); err != nil {
s.logger.Error("Cannot reconnect to the OpAMP server after restoring old settings", zap.Error(err))
return err
}
}
return nil
}
func (s *Supervisor) composeNoopPipeline() ([]byte, error) {
var cfg bytes.Buffer
err := s.noopPipelineTemplate.Execute(&cfg, map[string]any{
"InstanceUid": s.persistentState.InstanceID.String(),
"SupervisorPort": s.opampServerPort,
})
if err != nil {
return nil, err
}
return cfg.Bytes(), nil
}
func (s *Supervisor) composeNoopConfig() ([]byte, error) {
var k = koanf.New("::")
cfg, err := s.composeNoopPipeline()
if err != nil {
return nil, err
}
if err = k.Load(rawbytes.Provider(cfg), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return nil, err
}
if err = k.Load(rawbytes.Provider(s.composeOpAMPExtensionConfig()), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return nil, err
}
return k.Marshal(yaml.Parser())
}
func (s *Supervisor) composeExtraLocalConfig() []byte {
var cfg bytes.Buffer
resourceAttrs := map[string]string{}
ad := s.agentDescription.Load().(*protobufs.AgentDescription)
for _, attr := range ad.IdentifyingAttributes {
resourceAttrs[attr.Key] = attr.Value.GetStringValue()
}
for _, attr := range ad.NonIdentifyingAttributes {
resourceAttrs[attr.Key] = attr.Value.GetStringValue()
}
tplVars := map[string]any{
"Healthcheck": s.agentHealthCheckEndpoint,
"ResourceAttributes": resourceAttrs,
"SupervisorPort": s.opampServerPort,
}
err := s.extraConfigTemplate.Execute(
&cfg,
tplVars,
)
if err != nil {
s.logger.Error("Could not compose local config", zap.Error(err))
return nil
}
return cfg.Bytes()
}
func (s *Supervisor) composeOpAMPExtensionConfig() []byte {
orphanPollInterval := 5 * time.Second
if s.config.Agent.OrphanDetectionInterval > 0 {
orphanPollInterval = s.config.Agent.OrphanDetectionInterval
}
var cfg bytes.Buffer
tplVars := map[string]any{
"InstanceUid": s.persistentState.InstanceID.String(),
"SupervisorPort": s.opampServerPort,
"PID": s.pidProvider.PID(),
"PPIDPollInterval": orphanPollInterval,
}
err := s.opampextensionTemplate.Execute(
&cfg,
tplVars,
)
if err != nil {
s.logger.Error("Could not compose local config", zap.Error(err))
return nil
}
return cfg.Bytes()
}
func (s *Supervisor) loadAndWriteInitialMergedConfig() error {
var lastRecvRemoteConfig, lastRecvOwnMetricsConfig []byte
var err error
if s.config.Capabilities.AcceptsRemoteConfig {
// Try to load the last received remote config if it exists.
lastRecvRemoteConfig, err = os.ReadFile(filepath.Join(s.config.Storage.Directory, lastRecvRemoteConfigFile))
if err == nil {
config := &protobufs.AgentRemoteConfig{}
err = proto.Unmarshal(lastRecvRemoteConfig, config)
if err != nil {
s.logger.Error("Cannot parse last received remote config", zap.Error(err))
} else {
s.remoteConfig = config
}
} else {
s.logger.Error("error while reading last received config", zap.Error(err))
}
} else {
s.logger.Debug("Remote config is not supported, will not attempt to load config from fil")
}
if s.config.Capabilities.ReportsOwnMetrics {
// Try to load the last received own metrics config if it exists.
lastRecvOwnMetricsConfig, err = os.ReadFile(filepath.Join(s.config.Storage.Directory, lastRecvOwnMetricsConfigFile))
if err == nil {
set := &protobufs.TelemetryConnectionSettings{}
err = proto.Unmarshal(lastRecvOwnMetricsConfig, set)
if err != nil {
s.logger.Error("Cannot parse last received own metrics config", zap.Error(err))
} else {
s.setupOwnMetrics(context.Background(), set)
}
}
} else {
s.logger.Debug("Own metrics is not supported, will not attempt to load config from file")
}
_, err = s.composeMergedConfig(s.remoteConfig)
if err != nil {
return fmt.Errorf("could not compose initial merged config: %w", err)
}
// write the initial merged config to disk
cfgState := s.cfgState.Load().(*configState)
if err := os.WriteFile(s.agentConfigFilePath(), []byte(cfgState.mergedConfig), 0600); err != nil {
s.logger.Error("Failed to write agent config.", zap.Error(err))
}
return nil
}
// createEffectiveConfigMsg create an EffectiveConfig with the content of the
// current effective config.
func (s *Supervisor) createEffectiveConfigMsg() *protobufs.EffectiveConfig {
cfgStr, ok := s.effectiveConfig.Load().(string)
if !ok {
cfgState, ok := s.cfgState.Load().(*configState)
if !ok {
cfgStr = ""
} else {
cfgStr = cfgState.mergedConfig
}
}
cfg := &protobufs.EffectiveConfig{
ConfigMap: &protobufs.AgentConfigMap{
ConfigMap: map[string]*protobufs.AgentConfigFile{
"": {Body: []byte(cfgStr)},
},
},
}
return cfg
}
func (s *Supervisor) setupOwnMetrics(_ context.Context, settings *protobufs.TelemetryConnectionSettings) (configChanged bool) {
var cfg bytes.Buffer
if settings.DestinationEndpoint == "" {
// No destination. Disable metric collection.
s.logger.Debug("Disabling own metrics pipeline in the config")
} else {
s.logger.Debug("Enabling own metrics pipeline in the config")
port, err := s.findRandomPort()
if err != nil {
s.logger.Error("Could not setup own metrics", zap.Error(err))
return
}
err = s.ownTelemetryTemplate.Execute(
&cfg,
map[string]any{
"PrometheusPort": port,
"MetricsEndpoint": settings.DestinationEndpoint,
},
)
if err != nil {
s.logger.Error("Could not setup own metrics", zap.Error(err))
return
}
}
s.agentConfigOwnMetricsSection.Store(cfg.String())
// Need to recalculate the Agent config so that the metric config is included in it.
configChanged, err := s.composeMergedConfig(s.remoteConfig)
if err != nil {
s.logger.Error("Error composing merged config for own metrics. Ignoring agent self metrics config", zap.Error(err))
return
}
return configChanged
}
// composeMergedConfig composes the merged config from multiple sources:
// 1) the remote config from OpAMP Server
// 2) the own metrics config section
// 3) the local override config that is hard-coded in the Supervisor.
func (s *Supervisor) composeMergedConfig(config *protobufs.AgentRemoteConfig) (configChanged bool, err error) {
var k = koanf.New("::")
configMapIsEmpty := len(config.GetConfig().GetConfigMap()) == 0
if !configMapIsEmpty {
c := config.GetConfig()
// Sort to make sure the order of merging is stable.
var names []string
for name := range c.ConfigMap {
if name == "" {
// skip instance config
continue
}
names = append(names, name)
}
sort.Strings(names)
// Append instance config as the last item.
names = append(names, "")
// Merge received configs.
for _, name := range names {
item := c.ConfigMap[name]
if item == nil {
continue
}
var k2 = koanf.New("::")
err = k2.Load(rawbytes.Provider(item.Body), yaml.Parser())
if err != nil {
return false, fmt.Errorf("cannot parse config named %s: %w", name, err)
}
err = k.Merge(k2)
if err != nil {
return false, fmt.Errorf("cannot merge config named %s: %w", name, err)
}
}
} else {
// Add noop pipeline
var noopConfig []byte
noopConfig, err = s.composeNoopPipeline()
if err != nil {
return false, fmt.Errorf("could not compose noop pipeline: %w", err)
}
if err = k.Load(rawbytes.Provider(noopConfig), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return false, fmt.Errorf("could not merge noop pipeline: %w", err)
}
}
// Merge own metrics config.
ownMetricsCfg, ok := s.agentConfigOwnMetricsSection.Load().(string)
if ok {
if err = k.Load(rawbytes.Provider([]byte(ownMetricsCfg)), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return false, err
}
}
// Merge local config last since it has the highest precedence.
if err = k.Load(rawbytes.Provider(s.composeExtraLocalConfig()), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return false, err
}
if err = k.Load(rawbytes.Provider(s.composeOpAMPExtensionConfig()), yaml.Parser(), koanf.WithMergeFunc(configMergeFunc)); err != nil {
return false, err
}
// The merged final result is our new merged config.
newMergedConfigBytes, err := k.Marshal(yaml.Parser())
if err != nil {
return false, err
}
// Check if supervisor's merged config is changed.
newConfigState := &configState{
mergedConfig: string(newMergedConfigBytes),
configMapIsEmpty: configMapIsEmpty,
}
configChanged = false
oldConfigState := s.cfgState.Swap(newConfigState)
if oldConfigState == nil || !oldConfigState.(*configState).equal(newConfigState) {
s.logger.Debug("Merged config changed.")
configChanged = true
}
return configChanged, nil
}
func (s *Supervisor) handleRestartCommand() error {
s.agentRestarting.Store(true)
defer s.agentRestarting.Store(false)
s.logger.Debug("Received restart command")
err := s.commander.Restart(context.Background())
if err != nil {
s.logger.Error("Could not restart agent process", zap.Error(err))
}
return err