-
Notifications
You must be signed in to change notification settings - Fork 1
/
agent.go
918 lines (807 loc) · 31.7 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
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
package agent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/datawire/ambassador-agent/pkg/api/agent"
"github.com/datawire/dlib/dlog"
"github.com/datawire/k8sapi/pkg/k8sapi"
envoyMetrics "github.com/emissary-ingress/emissary/v3/pkg/api/envoy/service/metrics/v3"
diagnosticsTypes "github.com/emissary-ingress/emissary/v3/pkg/diagnostics/v1"
"github.com/emissary-ingress/emissary/v3/pkg/kates"
snapshotTypes "github.com/emissary-ingress/emissary/v3/pkg/snapshot/v1"
"github.com/pkg/errors"
io_prometheus_client "github.com/prometheus/client_model/go"
"google.golang.org/grpc/peer"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes"
// load all auth plugins
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
const defaultMinReportPeriod = 30 * time.Second
const cloudConnectTokenKey = "CLOUD_CONNECT_TOKEN"
type Comm interface {
Close() error
Report(context.Context, *agent.Snapshot, string) error
ReportCommandResult(context.Context, *agent.CommandResult, string) error
Directives() <-chan *agent.Directive
StreamMetrics(context.Context, *agent.StreamMetricsMessage, string) error
StreamDiagnostics(context.Context, *agent.Diagnostics, string) error
}
type atomicBool struct {
mutex sync.Mutex
value bool
}
func (ab *atomicBool) Value() bool {
ab.mutex.Lock()
defer ab.mutex.Unlock()
return ab.value
}
func (ab *atomicBool) Set(v bool) {
ab.mutex.Lock()
defer ab.mutex.Unlock()
ab.value = v
}
// Agent is the component that talks to the DCP Director, which is a cloud
// service run by Datawire.
type Agent struct {
// Connectivity to the Director
comm Comm
connInfo *ConnInfo
agentID *agent.Identity
newDirective <-chan *agent.Directive
ambassadorAPIKeyMutex sync.Mutex
ambassadorAPIKey string
directiveHandler DirectiveHandler
// store what the initial value was in the env var so we can set the ambassadorAPIKey value
// (^^Above) if the configmap and/or secret get deleted.
ambassadorAPIKeyEnvVarValue string
connAddress string
// State managed by the director via the retriever
reportingStopped bool // Did the director say don't report?
minReportPeriod time.Duration // How often can we Report?
lastDirectiveID string
// The state of reporting
reportToSend *agent.Snapshot // Report that's ready to send
reportRunning atomicBool // Is a report being sent right now?
reportComplete chan error // Report() finished with this error
// apiDocsStore holds OpenAPI documents from cluster Mappings
apiDocsStore *APIDocsStore
// rolloutStore holds Argo Rollouts state from cluster
rolloutStore *RolloutStore
// applicationStore holds Argo Applications state from cluster
applicationStore *ApplicationStore
// config map/secret information
// agent namespace is... the namespace the agent is running in.
// but more importantly, it's the namespace that the config resource lives in (which is
// either a ConfigMap or Secret)
agentNamespace string
// Name of the k8s ConfigMap or Secret the CLOUD_CONNECT_TOKEN exists on. We're supporting
// both Secrets and ConfigMaps here because it is likely in an enterprise cluster, the RBAC
// for secrets is locked down to Ops folks only, and we want to make it easy for regular ol'
// engineers to give this whole service catalog thing a go
agentCloudResourceConfigName string
// Field selector for the k8s resources that the agent watches
agentWatchFieldSelector string
namespacesToWatch []string
// A mutex related to the metrics endpoint action, to avoid concurrent (and useless) pushes.
metricsRelayMutex sync.Mutex
// Timestamp to keep in memory to Prevent from making too many requests to the Ambassador
// Cloud API.
metricsBackoffUntil time.Time
// Used to accumulate metrics for a same timestamp before pushing them to the cloud.
aggregatedMetrics map[string][]*io_prometheus_client.MetricFamily
// Extra headers to inject into RPC requests to ambassador cloud.
rpcExtraHeaders []string
// Diagnostics reporting
reportDiagnosticsAllowed bool // Allow agent to fetch diagnostics and report to cloud
diagnosticsReportingStopped bool // Director stopped diagnostics reporting
// minDiagnosticsReportPeriod time.Duration // How frequently do we collect diagnostics
// The state of diagnostic reporting
diagnosticsReportRunning atomicBool // Is a report being sent right now?
diagnosticsReportComplete chan error // Report() finished with this error
// Stand-alone config
emissaryPresent bool // if not installed by emissary, generate snapshots
clusterId string // cluster id used in generated snapshots
// k8sapi watchers
clientset *kubernetes.Clientset
configWatchers *ConfigWatchers
coreWatchers *CoreWatchers
ambassadorWatcher *AmbassadorWatcher
siWatcher *SIWatcher
}
// New returns a new Agent.
func NewAgent(
ctx context.Context,
directiveHandler DirectiveHandler,
rolloutsGetterFactory rolloutsGetterFactory,
secretsGetterFactory secretsGetterFactory,
clientset *kubernetes.Clientset,
agentNamespace string,
) *Agent {
reportPeriodFromEnv := os.Getenv("AGENT_REPORTING_PERIOD")
var reportPeriod time.Duration
if reportPeriodFromEnv != "" {
var err error
reportPeriod, err = time.ParseDuration(reportPeriodFromEnv)
if err != nil {
reportPeriod = defaultMinReportPeriod
} else {
reportPeriod = MaxDuration(defaultMinReportPeriod, reportPeriod)
}
} else {
reportPeriod = defaultMinReportPeriod
}
if directiveHandler == nil {
directiveHandler = &BasicDirectiveHandler{
DefaultMinReportPeriod: defaultMinReportPeriod,
rolloutsGetterFactory: rolloutsGetterFactory,
secretsGetterFactory: secretsGetterFactory,
}
}
var rpcExtraHeaders = make([]string, 0)
if os.Getenv("RPC_INTERCEPT_HEADER_KEY") != "" &&
os.Getenv("RPC_INTERCEPT_HEADER_VALUE") != "" {
rpcExtraHeaders = append(
rpcExtraHeaders,
os.Getenv("RPC_INTERCEPT_HEADER_KEY"),
os.Getenv("RPC_INTERCEPT_HEADER_VALUE"),
)
}
namespacesToWatch := strings.Split(os.Getenv("NAMESPACES_TO_WATCH"), " ")
if len(namespacesToWatch) == 0 {
namespacesToWatch = append(namespacesToWatch, "")
}
return &Agent{
minReportPeriod: reportPeriod,
reportComplete: make(chan error),
ambassadorAPIKey: os.Getenv(cloudConnectTokenKey),
// store this same value in a different variable, so that if ambassadorAPIKey gets
// changed by some other configuration, we know what to change it back to. See
// comment on the struct for more detail
ambassadorAPIKeyEnvVarValue: os.Getenv(cloudConnectTokenKey),
connAddress: os.Getenv("RPC_CONNECTION_ADDRESS"),
agentNamespace: agentNamespace,
agentCloudResourceConfigName: getEnvWithDefault("AGENT_CONFIG_RESOURCE_NAME", "ambassador-agent-cloud-token"),
directiveHandler: directiveHandler,
reportRunning: atomicBool{value: false},
agentWatchFieldSelector: getEnvWithDefault("AGENT_WATCH_FIELD_SELECTOR", "metadata.namespace!=kube-system"),
metricsBackoffUntil: time.Now().Add(defaultMinReportPeriod),
rpcExtraHeaders: rpcExtraHeaders,
aggregatedMetrics: map[string][]*io_prometheus_client.MetricFamily{},
namespacesToWatch: namespacesToWatch,
// k8sapi watchers
clientset: clientset,
coreWatchers: NewCoreWatchers(clientset, namespacesToWatch),
configWatchers: NewConfigWatchers(clientset, agentNamespace),
ambassadorWatcher: NewAmbassadorWatcher(clientset, agentNamespace),
siWatcher: NewSIWatcher(ctx, clientset, namespacesToWatch),
// TODO add other watchers
}
}
func (a *Agent) StopReporting(ctx context.Context) {
dlog.Debugf(ctx, "stop reporting: %t -> true", a.reportingStopped)
a.reportingStopped = true
}
func (a *Agent) StartReporting(ctx context.Context) {
dlog.Debugf(ctx, "stop reporting: %t -> false", a.reportingStopped)
a.reportingStopped = false
}
func (a *Agent) SetMinReportPeriod(ctx context.Context, dur time.Duration) {
dlog.Debugf(ctx, "minimum report period %s -> %s", a.minReportPeriod, dur)
a.minReportPeriod = dur
}
func (a *Agent) SetLastDirectiveID(ctx context.Context, id string) {
dlog.Debugf(ctx, "setting last directive ID %s", id)
a.lastDirectiveID = id
}
func (a *Agent) SetReportDiagnosticsAllowed(reportDiagnosticsAllowed bool) {
dlog.Debugf(context.Background(), "setting reporting diagnostics to cloud to: %t", reportDiagnosticsAllowed)
a.reportDiagnosticsAllowed = reportDiagnosticsAllowed
}
func getAmbSnapshotInfo(url string) (*snapshotTypes.Snapshot, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
return nil, errors.New(fmt.Sprintf("Cannot fetch snapshot from url: %s. "+
"Response failed with status code: %d", url, resp.StatusCode))
}
defer resp.Body.Close()
rawSnapshot, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ret := &snapshotTypes.Snapshot{}
err = json.Unmarshal(rawSnapshot, ret)
return ret, err
}
func getAmbDiagnosticsInfo(url string) (*diagnosticsTypes.Diagnostics, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
return nil, errors.New(fmt.Sprintf("Cannot fetch diagnostics from url: %s. "+
"Response failed with status code: %d", url, resp.StatusCode))
}
defer resp.Body.Close()
rawDiagnosticsSnapshot, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ret := &diagnosticsTypes.Diagnostics{}
err = json.Unmarshal(rawDiagnosticsSnapshot, ret)
return ret, err
}
func parseAmbassadorAdminHost(rawurl string) (string, error) {
url, err := url.Parse(rawurl)
if err != nil {
return "", err
}
return url.Hostname(), nil
}
func getAPIKeyValue(configValue string, configHadValue bool) string {
if configHadValue {
return configValue
}
return ""
}
// Handle change to the ambassadorAPIKey that we auth to the agent with
// in order of importance: secret > configmap > environment variable
// so if a secret exists, read from that. then, check if a config map exists, and read the value
// from that. If neither a secret or a configmap exists, use the value from the environment that we
// stored on startup.
func (a *Agent) handleAPIKeyConfigChange(ctx context.Context) {
// reset the connection so we use a new api key (or break the connection if the api key was
// unset). The agent will reset the connection the next time it tries to send a report
resetComm := func(newKey string, oldKey string, a *Agent) {
if newKey != oldKey {
a.ClearComm()
}
}
prevKey := a.ambassadorAPIKey
// first, check if we have a secret, since we want that value to take if we
// can get it.
// there _should_ only be one secret here, but we're going to loop and check that the object
// meta matches what we expect
if secrets, err := a.configWatchers.secretWatcher.List(ctx); err == nil {
for _, secret := range secrets {
if secret.GetName() == a.agentCloudResourceConfigName && secret.GetNamespace() == a.agentNamespace {
connTokenBytes, ok := secret.Data[cloudConnectTokenKey]
connToken := string(connTokenBytes)
dlog.Infof(ctx, "Setting cloud connect token from secret")
a.ambassadorAPIKey = getAPIKeyValue(connToken, ok)
resetComm(a.ambassadorAPIKey, prevKey, a)
return
}
}
} else {
dlog.Warnf(ctx, "Unable to list secrets for cloud connect token: %v", err)
}
// then, if we don't have a secret, we check for a config map
// there _should_ only be one config here, but we're going to loop and check that the object
// meta matches what we expect
if cms, err := a.configWatchers.mapsWatcher.List(ctx); err == nil {
for _, cm := range cms {
if cm.GetName() == a.agentCloudResourceConfigName && cm.GetNamespace() == a.agentNamespace {
connTokenBytes, ok := cm.Data[cloudConnectTokenKey]
connToken := string(connTokenBytes)
dlog.Infof(ctx, "Setting cloud connect token from configmap")
a.ambassadorAPIKey = getAPIKeyValue(connToken, ok)
resetComm(a.ambassadorAPIKey, prevKey, a)
return
}
}
} else {
dlog.Warnf(ctx, "Unable to list configmaps for cloud connect token: %v", err)
}
// so if we got here, we know something changed, but a config map
// nor a secret exist, which means they never existed or they got
// deleted. in this case, we fall back to the env var (which is
// likely empty, so in that case, that is basically equivelant to
// turning the agent "off")
dlog.Infof(ctx, "Setting cloud connect token from environment")
a.ambassadorAPIKeyMutex.Lock()
defer a.ambassadorAPIKeyMutex.Unlock()
a.ambassadorAPIKey = a.ambassadorAPIKeyEnvVarValue
if a.ambassadorAPIKeyEnvVarValue == "" {
dlog.Errorf(ctx, "Unable to get cloud connect token. This agent will do nothing.")
}
resetComm(a.ambassadorAPIKey, prevKey, a)
}
// Watch is the work performed by the main goroutine for the Agent. It processes
// Watt/Diag snapshots, reports to the Director, and executes directives from
// the Director.
func (a *Agent) Watch(ctx context.Context, snapshotURL, diagnosticsURL string) error {
dlog.Info(ctx, "Agent is running...")
a.configWatchers.EnsureStarted(ctx)
// TODO wait for config sync
a.waitForAPIKey(ctx)
a.coreWatchers.EnsureStarted(ctx)
// TODO wait for amb sync
a.ambassadorWatcher.EnsureStarted(ctx)
a.handleAPIKeyConfigChange(ctx)
// The following is kates that im not sure we can replicate with k8sapi as it currently exists
// leaving it in for now
client, err := kates.NewClient(kates.ClientConfig{})
if err != nil {
return err
}
ns := kates.NamespaceAll
dc := NewDynamicClient(client.DynamicInterface(), NewK8sInformer)
rolloutGvr, _ := schema.ParseResourceArg("rollouts.v1alpha1.argoproj.io")
rolloutCallback := dc.WatchGeneric(ctx, ns, rolloutGvr)
applicationGvr, _ := schema.ParseResourceArg("applications.v1alpha1.argoproj.io")
applicationCallback := dc.WatchGeneric(ctx, ns, applicationGvr)
return a.watch(ctx, snapshotURL, diagnosticsURL, rolloutCallback, applicationCallback)
}
func (a *Agent) waitForAPIKey(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ch := k8sapi.Subscribe(ctx, a.configWatchers.cond)
a.handleAPIKeyConfigChange(ctx)
// wait until the user installs an api key
for a.ambassadorAPIKey == "" {
select {
case <-ctx.Done():
return
case <-ch:
a.handleAPIKeyConfigChange(ctx)
case <-time.After(1 * time.Minute):
dlog.Debugf(ctx, "Still waiting for api key")
}
}
}
func (a *Agent) watch(ctx context.Context, snapshotURL, diagnosticsURL string, rolloutCallback <-chan *GenericCallback, applicationCallback <-chan *GenericCallback) error {
ambHost, err := parseAmbassadorAdminHost(snapshotURL)
if err != nil {
// if we can't parse the host out of the url we won't be able to talk to ambassador
// anyway
return err
}
configCh := k8sapi.Subscribe(ctx, a.configWatchers.cond)
ambCh := k8sapi.Subscribe(ctx, a.ambassadorWatcher.cond)
a.apiDocsStore = NewAPIDocsStore()
applicationStore := NewApplicationStore()
rolloutStore := NewRolloutStore()
dlog.Info(ctx, "Beginning to watch and report resources to ambassador cloud")
for {
// Wait for an event
select {
case <-ctx.Done():
return nil
// just hardcode it so we wake every 1 second and check if we're ready to report
// intentionally not waiting for agent.minReportPeriod seconds because then we may
// never report if a bunch of directives keep coming in or pods change a
// bunch
case <-time.After(1 * time.Second):
// just a ticker, this will fallthru to the snapshot getting thing
case <-configCh:
a.handleAPIKeyConfigChange(ctx)
case <-ambCh:
a.handleAmbassadorEndpointChange(ctx)
case callback, ok := <-rolloutCallback:
if ok {
dlog.Debugf(ctx, "argo rollout callback: %v", callback.EventType)
a.rolloutStore, err = rolloutStore.FromCallback(callback)
if err != nil {
dlog.Warnf(ctx, "Error processing rollout callback: %s", err)
}
}
case callback, ok := <-applicationCallback:
if ok {
dlog.Debugf(ctx, "argo application callback: %v", callback.EventType)
a.applicationStore, err = applicationStore.FromCallback(callback)
if err != nil {
dlog.Warnf(ctx, "Error processing application callback: %s", err)
}
}
case directive := <-a.newDirective:
a.directiveHandler.HandleDirective(ctx, a, directive)
}
// only ask ambassador for a snapshot if we're actually going to report it.
// if reportRunning is true, that means we're still in the quiet period
// after sending a report.
// if emissary is the owner, do all the things
if !a.reportingStopped && !a.reportRunning.Value() {
// if emissary is present, get initial snapshot from emissary
// otherwise, create it
var snapshot *snapshotTypes.Snapshot
if a.emissaryPresent {
snapshot, err = getAmbSnapshotInfo(snapshotURL)
if err != nil {
dlog.Warnf(ctx, "Error getting snapshot from ambassador %+v", err)
}
} else {
if a.clusterId == "" {
ns := "default"
if len(a.namespacesToWatch) > 0 && a.namespacesToWatch[0] != "" {
ns = a.agentNamespace
}
a.clusterId = GetClusterID(ctx, a.clientset, ns) // get cluster id for ambMeta
}
snapshot = &snapshotTypes.Snapshot{
AmbassadorMeta: &snapshotTypes.AmbassadorMetaInfo{
ClusterID: a.clusterId,
},
Kubernetes: &snapshotTypes.KubernetesSnapshot{},
}
}
dlog.Debug(ctx, "Received snapshot in agent")
if err = a.ProcessSnapshot(ctx, snapshot, ambHost); err != nil {
dlog.Warnf(ctx, "error processing snapshot: %+v", err)
}
}
a.MaybeReportSnapshot(ctx)
if !a.diagnosticsReportingStopped && !a.diagnosticsReportRunning.Value() && a.reportDiagnosticsAllowed && a.emissaryPresent {
diagnostics, err := getAmbDiagnosticsInfo(diagnosticsURL)
if err != nil {
dlog.Warnf(ctx, "Error getting diagnostics from ambassador %+v", err)
}
dlog.Debug(ctx, "Received diagnostics in agent")
agentDiagnostics, err := a.ProcessDiagnostics(ctx, diagnostics, ambHost)
if err != nil {
dlog.Warnf(ctx, "error processing diagnostics: %+v", err)
}
a.ReportDiagnostics(ctx, agentDiagnostics)
}
}
}
func (a *Agent) handleAmbassadorEndpointChange(ctx context.Context) {
if endpoints, err := a.ambassadorWatcher.endpointWatcher.List(ctx); err == nil {
for _, endpoint := range endpoints {
if endpoint.Name == "ambassador-admin" {
a.emissaryPresent = true
a.siWatcher.Cancel()
return
}
}
} else {
dlog.Warnf(ctx, "Unable to watch for ambassador-admin service, will act as though standalone: %v", err)
}
a.emissaryPresent = false
a.siWatcher.EnsureStarted(ctx)
}
func (a *Agent) MaybeReportSnapshot(ctx context.Context) {
dlog.Debugf(ctx, "Trying to send snapshot")
if a.ambassadorAPIKey == "" {
dlog.Error(ctx, "CLOUD_CONNECT_TOKEN not set in the environment, not reporting snapshot")
return
}
if a.reportingStopped || a.reportRunning.Value() || (a.reportToSend == nil) {
// Don't report if the Director told us to stop reporting, if we are
// already sending a report or waiting for the minimum time between
// reports, or if there is nothing new to report right now.
dlog.Debugf(ctx, "Not reporting snapshot [reporting stopped = %t] [report running = %t] [report to send is nil = %t]", a.reportingStopped, a.reportRunning.Value(), (a.reportToSend == nil))
return
}
// It's time to send a report
if a.comm == nil {
// The communications channel to the DCP was not yet created or was
// closed above, due to a change in identity, or close elsewhere, due to
// a change in endpoint configuration.
newComm, err := NewComm(
ctx, a.connInfo, a.agentID, a.ambassadorAPIKey, a.rpcExtraHeaders)
if err != nil {
dlog.Warnf(ctx, "Failed to dial the DCP: %v", err)
dlog.Warn(ctx, "DCP functionality disabled until next retry")
return
}
a.comm = newComm
a.newDirective = a.comm.Directives()
}
a.reportRunning.Set(true) // Cleared when the report completes
// Send a report. This is an RPC, i.e. it can block, so we do this in a
// goroutine. Sleep after send so we don't need to keep track of
// whether/when it's okay to send the next report.
go func(ctx context.Context, report *agent.Snapshot, delay time.Duration) {
var err error
defer func() {
if err != nil {
dlog.Warnf(ctx, "failed to report: %+v", err)
}
dlog.Debugf(ctx, "Finished sending snapshot report, sleeping for %s", delay.String())
time.Sleep(delay)
a.reportRunning.Set(false)
// make the write non blocking
select {
case a.reportComplete <- err:
// cool we sent something
default:
// do nothing if nobody is listening
}
}()
a.ambassadorAPIKeyMutex.Lock()
apikey := a.ambassadorAPIKey
a.ambassadorAPIKeyMutex.Unlock()
err = a.comm.Report(ctx, report, apikey)
}(ctx, a.reportToSend, a.minReportPeriod)
// Update state variables
a.reportToSend = nil // Set when a snapshot yields a fresh report
}
// ReportDiagnostics ...
func (a *Agent) ReportDiagnostics(ctx context.Context, agentDiagnostics *agent.Diagnostics) {
if a.ambassadorAPIKey == "" {
dlog.Debugf(ctx, "CLOUD_CONNECT_TOKEN not set in the environment, not reporting diagnostics")
return
}
if a.diagnosticsReportingStopped || a.diagnosticsReportRunning.Value() || (agentDiagnostics == nil) {
// Don't report if the Director told us to stop reporting, if we are
// already sending a report or waiting for the minimum time between
// reports, or if there is nothing new to report right now.
dlog.Debugf(ctx, "Not reporting diagnostics [reporting stopped = %t] [report running = %t] [report to send is nil = %t]", a.diagnosticsReportingStopped, a.diagnosticsReportRunning.Value(), agentDiagnostics == nil)
return
}
// It's time to send a report
if a.comm == nil {
// The communications channel to the DCP was not yet created or was
// closed above, due to a change in identity, or close elsewhere, due to
// a change in endpoint configuration.
newComm, err := NewComm(
ctx, a.connInfo, a.agentID, a.ambassadorAPIKey, a.rpcExtraHeaders)
if err != nil {
dlog.Warnf(ctx, "Failed to dial the DCP: %v", err)
dlog.Warn(ctx, "DCP functionality disabled until next retry")
return
}
a.comm = newComm
a.newDirective = a.comm.Directives()
}
a.diagnosticsReportRunning.Set(true) // Cleared when the diagnostics report completes
// Send a diagnostics report. This is an RPC, i.e. it can block, so we do this in a
// goroutine. Sleep after send, so we don't need to keep track of
// whether/when it's okay to send the next report.
go func(ctx context.Context, diagnosticsReport *agent.Diagnostics, delay time.Duration) {
var err error
defer func() {
if err != nil {
dlog.Warnf(ctx, "failed to do diagnostics report: %+v", err)
}
dlog.Debugf(ctx, "Finished sending diagnostics report, sleeping for %s", delay.String())
time.Sleep(delay)
a.diagnosticsReportRunning.Set(false)
// make the write non blocking
select {
case a.diagnosticsReportComplete <- err:
// cool we sent something
default:
// do nothing if nobody is listening
}
}()
a.ambassadorAPIKeyMutex.Lock()
apikey := a.ambassadorAPIKey
a.ambassadorAPIKeyMutex.Unlock()
err = a.comm.StreamDiagnostics(ctx, diagnosticsReport, apikey)
}(ctx, agentDiagnostics, a.minReportPeriod) // minReportPeriod is the one set for snapshots
}
// ProcessSnapshot turns a Watt/Diag Snapshot into a report that the agent can
// send to the Director. If the new report is semantically different from the
// prior one sent, then the Agent's state is updated to indicate that reporting
// should occur once again.
func (a *Agent) ProcessSnapshot(ctx context.Context, snapshot *snapshotTypes.Snapshot, ambHost string) error {
if snapshot == nil || snapshot.AmbassadorMeta == nil {
dlog.Warn(ctx, "No metadata discovered for snapshot, not reporting.")
return nil
}
agentID := GetIdentity(snapshot.AmbassadorMeta, ambHost)
if agentID == nil {
dlog.Warnf(ctx, "Could not parse identity info out of snapshot, not sending snapshot")
return nil
}
a.agentID = agentID
newConnInfo, err := connInfoFromAddress(a.connAddress)
if err != nil {
// The user has attempted to turn on the Agent (otherwise GetIdentity
// would have returned nil), but there's a problem with the connection
// configuration. Rather than processing the entire snapshot and then
// failing to send the resulting report, let's just fail now. The user
// will see the error in the logs and correct the configuration.
return err
}
if a.connInfo == nil || *newConnInfo != *a.connInfo {
// The configuration for the Director endpoint has changed: either this
// is the first snapshot or the user changed the value.
//
// Close any existing communications channel so that we can create
// a new one with the new endpoint.
a.ClearComm()
// Save the new endpoint information.
a.connInfo = newConnInfo
}
if snapshot.Kubernetes != nil {
if snapshot.Kubernetes.Pods, err = a.coreWatchers.podWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find pods: %v", err)
}
dlog.Debugf(ctx, "Found %d pods", len(snapshot.Kubernetes.Pods))
if snapshot.Kubernetes.ConfigMaps, err = a.coreWatchers.mapsWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find configmaps: %v", err)
}
dlog.Debugf(ctx, "Found %d configMaps", len(snapshot.Kubernetes.ConfigMaps))
if snapshot.Kubernetes.Deployments, err = a.coreWatchers.deployWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find deployments: %v", err)
}
dlog.Debugf(ctx, "Found %d Deployments", len(snapshot.Kubernetes.Deployments))
if snapshot.Kubernetes.Endpoints, err = a.coreWatchers.endpointWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find endpoints: %v", err)
}
dlog.Debugf(ctx, "Found %d Endpoints", len(snapshot.Kubernetes.Endpoints))
if !a.emissaryPresent {
if snapshot.Kubernetes.Services, err = a.siWatcher.serviceWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find services: %v", err)
}
dlog.Debugf(ctx, "Found %d services", len(snapshot.Kubernetes.Services))
if ingresses, err := a.siWatcher.ingressWatchers.List(ctx); err != nil {
dlog.Errorf(ctx, "Unable to find ingresses: %v", err)
} else {
snapshot.Kubernetes.Ingresses = []*snapshotTypes.Ingress{}
for _, ing := range ingresses {
snapshot.Kubernetes.Ingresses = append(snapshot.Kubernetes.Ingresses, &snapshotTypes.Ingress{Ingress: *ing})
}
}
dlog.Debugf(ctx, "Found %d ingresses", len(snapshot.Kubernetes.Ingresses))
}
if a.rolloutStore != nil {
snapshot.Kubernetes.ArgoRollouts = a.rolloutStore.StateOfWorld()
dlog.Debugf(ctx, "Found %d argo rollouts", len(snapshot.Kubernetes.ArgoRollouts))
}
if a.applicationStore != nil {
snapshot.Kubernetes.ArgoApplications = a.applicationStore.StateOfWorld()
dlog.Debugf(ctx, "Found %d argo applications", len(snapshot.Kubernetes.ArgoApplications))
}
if a.apiDocsStore != nil {
a.apiDocsStore.ProcessSnapshot(ctx, snapshot)
snapshot.APIDocs = a.apiDocsStore.StateOfWorld()
dlog.Debugf(ctx, "Found %d api docs", len(snapshot.APIDocs))
}
}
if err = snapshot.Sanitize(); err != nil {
dlog.Errorf(ctx, "Error sanitizing snapshot: %v", err)
return err
}
rawJsonSnapshot, err := json.Marshal(snapshot)
if err != nil {
dlog.Errorf(ctx, "Error marshalling snapshot: %v", err)
return err
}
report := &agent.Snapshot{
Identity: agentID,
RawSnapshot: rawJsonSnapshot,
ContentType: snapshotTypes.ContentTypeJSON,
ApiVersion: snapshotTypes.ApiVersion,
SnapshotTs: timestamppb.Now(),
}
a.reportToSend = report
dlog.Debugf(ctx, "Will send a snapshot for %s", agentID)
return nil
}
// ProcessDiagnostics translates ambassadors diagnostics into streamable agent diagnostics
func (a *Agent) ProcessDiagnostics(ctx context.Context, diagnostics *diagnosticsTypes.Diagnostics,
ambHost string) (*agent.Diagnostics, error) {
if diagnostics == nil {
dlog.Warn(ctx, "No diagnostics found, not reporting.")
return nil, nil
}
if diagnostics.System == nil {
dlog.Warn(ctx, "Missing System information from diagnostics, not reporting.")
return nil, nil
}
agentID := GetIdentityFromDiagnostics(diagnostics.System, ambHost)
if agentID == nil {
dlog.Warn(ctx, "Could not parse identity info out of diagnostics, not sending.")
return nil, nil
}
a.agentID = agentID
newConnInfo, err := connInfoFromAddress(a.connAddress)
if err != nil {
// The user has attempted to turn on the Agent (otherwise GetIdentity
// would have returned nil), but there's a problem with the connection
// configuration. Rather than processing the entire snapshot and then
// failing to send the resulting report, let's just fail now. The user
// will see the error in the logs and correct the configuration.
return nil, err
}
if a.connInfo == nil || *newConnInfo != *a.connInfo {
// The configuration for the Director endpoint has changed: either this
// is the first snapshot or the user changed the value.
//
// Close any existing communications channel so that we can create
// a new one with the new endpoint.
a.ClearComm()
// Save the new endpoint information.
a.connInfo = newConnInfo
}
rawJsonDiagnostics, err := json.Marshal(diagnostics)
if err != nil {
return nil, err
}
diagnosticsReport := &agent.Diagnostics{
Identity: agentID,
RawDiagnostics: rawJsonDiagnostics,
ContentType: diagnosticsTypes.ContentTypeJSON,
ApiVersion: diagnosticsTypes.ApiVersion,
SnapshotTs: timestamppb.Now(),
}
return diagnosticsReport, nil
}
var allowedMetricsSuffixes = []string{"upstream_rq_total", "upstream_rq_time", "upstream_rq_5xx"}
// MetricsRelayHandler is invoked as a callback when the agent receive metrics from Envoy (sink).
func (a *Agent) MetricsRelayHandler(
ctx context.Context,
in *envoyMetrics.StreamMetricsMessage,
) {
metrics := in.GetEnvoyMetrics()
if a.comm != nil && !a.reportingStopped {
p, ok := peer.FromContext(ctx)
if !ok {
dlog.Warnf(ctx, "peer not found in context")
return
}
a.ambassadorAPIKeyMutex.Lock()
apikey := a.ambassadorAPIKey
a.ambassadorAPIKeyMutex.Unlock()
newMetrics := make([]*io_prometheus_client.MetricFamily, 0, len(metrics))
for _, metricFamily := range metrics {
for _, suffix := range allowedMetricsSuffixes {
if strings.HasSuffix(metricFamily.GetName(), suffix) {
newMetrics = append(newMetrics, metricFamily)
break
}
}
}
instanceID := p.Addr.String()
a.metricsRelayMutex.Lock()
defer a.metricsRelayMutex.Unlock()
// Collect metrics until next report.
if time.Now().Before(a.metricsBackoffUntil) {
dlog.Infof(ctx, "Append %d metric(s) to stack from %s",
len(newMetrics), instanceID,
)
a.aggregatedMetrics[instanceID] = newMetrics
return
}
// Otherwise, we reached a new batch of metric, send everything.
outMessage := &agent.StreamMetricsMessage{
Identity: a.agentID,
EnvoyMetrics: []*io_prometheus_client.MetricFamily{},
}
for key, instanceMetrics := range a.aggregatedMetrics {
outMessage.EnvoyMetrics = append(outMessage.EnvoyMetrics, instanceMetrics...)
delete(a.aggregatedMetrics, key)
}
if relayedMetricCount := len(outMessage.GetEnvoyMetrics()); relayedMetricCount > 0 {
dlog.Infof(ctx, "Relaying %d metric(s)", relayedMetricCount)
if err := a.comm.StreamMetrics(ctx, outMessage, apikey); err != nil {
dlog.Errorf(ctx, "error streaming metric(s): %+v", err)
}
}
// Configure next push.
a.metricsBackoffUntil = time.Now().Add(defaultMinReportPeriod)
dlog.Infof(ctx, "Next metrics relay scheduled for %s",
a.metricsBackoffUntil.UTC().String())
}
}
// ClearComm ends the current connection to the Director, if it exists, thereby
// forcing a new connection to be created when needed.
func (a *Agent) ClearComm() {
if a.comm != nil {
a.comm.Close()
a.comm = nil
}
}
// MaxDuration returns the greater of two durations.
func MaxDuration(a, b time.Duration) time.Duration {
if a > b {
return a
}
return b
}