-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathclient.go
1036 lines (919 loc) · 29.7 KB
/
client.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 kube // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sattributesprocessor/internal/kube"
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
"go.opentelemetry.io/collector/featuregate"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
apps_v1 "k8s.io/api/apps/v1"
api_v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sattributesprocessor/internal/observability"
)
// Upgrade to StageStable in v0.92.0
var enableRFC3339Timestamp = featuregate.GlobalRegistry().MustRegister(
"k8sattr.rfc3339",
featuregate.StageBeta,
featuregate.WithRegisterDescription("When enabled, uses RFC3339 format for k8s.pod.start_time value"),
featuregate.WithRegisterFromVersion("v0.82.0"),
)
// WatchClient is the main interface provided by this package to a kubernetes cluster.
type WatchClient struct {
m sync.RWMutex
deleteMut sync.Mutex
logger *zap.Logger
kc kubernetes.Interface
informer cache.SharedInformer
namespaceInformer cache.SharedInformer
nodeInformer cache.SharedInformer
replicasetInformer cache.SharedInformer
replicasetRegex *regexp.Regexp
cronJobRegex *regexp.Regexp
deleteQueue []deleteRequest
stopCh chan struct{}
// A map containing Pod related data, used to associate them with resources.
// Key can be either an IP address or Pod UID
Pods map[PodIdentifier]*Pod
Rules ExtractionRules
Filters Filters
Associations []Association
Exclude Excludes
// A map containing Namespace related data, used to associate them with resources.
// Key is namespace name
Namespaces map[string]*Namespace
// A map containing Node related data, used to associate them with resources.
// Key is node name
Nodes map[string]*Node
// A map containing ReplicaSets related data, used to associate them with resources.
// Key is replicaset uid
ReplicaSets map[string]*ReplicaSet
}
// Extract replicaset name from the pod name. Pod name is created using
// format: [deployment-name]-[Random-String-For-ReplicaSet]
var rRegex = regexp.MustCompile(`^(.*)-[0-9a-zA-Z]+$`)
// Extract CronJob name from the Job name. Job name is created using
// format: [cronjob-name]-[time-hash-int]
var cronJobRegex = regexp.MustCompile(`^(.*)-[0-9]+$`)
// New initializes a new k8s Client.
func New(logger *zap.Logger, apiCfg k8sconfig.APIConfig, rules ExtractionRules, filters Filters, associations []Association, exclude Excludes, newClientSet APIClientsetProvider, newInformer InformerProvider, newNamespaceInformer InformerProviderNamespace, newReplicaSetInformer InformerProviderReplicaSet) (Client, error) {
c := &WatchClient{
logger: logger,
Rules: rules,
Filters: filters,
Associations: associations,
Exclude: exclude,
replicasetRegex: rRegex,
cronJobRegex: cronJobRegex,
stopCh: make(chan struct{}),
}
go c.deleteLoop(time.Second*30, defaultPodDeleteGracePeriod)
c.Pods = map[PodIdentifier]*Pod{}
c.Namespaces = map[string]*Namespace{}
c.Nodes = map[string]*Node{}
c.ReplicaSets = map[string]*ReplicaSet{}
if newClientSet == nil {
newClientSet = k8sconfig.MakeClient
}
kc, err := newClientSet(apiCfg)
if err != nil {
return nil, err
}
c.kc = kc
labelSelector, fieldSelector, err := selectorsFromFilters(c.Filters)
if err != nil {
return nil, err
}
logger.Info(
"k8s filtering",
zap.String("labelSelector", labelSelector.String()),
zap.String("fieldSelector", fieldSelector.String()),
)
if newInformer == nil {
newInformer = newSharedInformer
}
if newNamespaceInformer == nil {
// if rules to extract metadata from namespace is configured use namespace shared informer containing
// all namespaces including kube-system which contains cluster uid information (kube-system-uid)
if c.extractNamespaceLabelsAnnotations() {
newNamespaceInformer = newNamespaceSharedInformer
} else {
// use kube-system shared informer to only watch kube-system namespace
// reducing overhead of watching all the namespaces
newNamespaceInformer = newKubeSystemSharedInformer
}
}
c.informer = newInformer(c.kc, c.Filters.Namespace, labelSelector, fieldSelector)
err = c.informer.SetTransform(
func(object any) (any, error) {
originalPod, success := object.(*api_v1.Pod)
if !success { // means this is a cache.DeletedFinalStateUnknown, in which case we do nothing
return object, nil
}
return removeUnnecessaryPodData(originalPod, c.Rules), nil
},
)
if err != nil {
return nil, err
}
c.namespaceInformer = newNamespaceInformer(c.kc)
if rules.DeploymentName || rules.DeploymentUID {
if newReplicaSetInformer == nil {
newReplicaSetInformer = newReplicaSetSharedInformer
}
c.replicasetInformer = newReplicaSetInformer(c.kc, c.Filters.Namespace)
err = c.replicasetInformer.SetTransform(
func(object any) (any, error) {
originalReplicaset, success := object.(*apps_v1.ReplicaSet)
if !success { // means this is a cache.DeletedFinalStateUnknown, in which case we do nothing
return object, nil
}
return removeUnnecessaryReplicaSetData(originalReplicaset), nil
},
)
if err != nil {
return nil, err
}
}
if c.extractNodeLabelsAnnotations() {
c.nodeInformer = newNodeSharedInformer(c.kc, c.Filters.Node)
}
return c, err
}
// Start registers pod event handlers and starts watching the kubernetes cluster for pod changes.
func (c *WatchClient) Start() {
_, err := c.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handlePodAdd,
UpdateFunc: c.handlePodUpdate,
DeleteFunc: c.handlePodDelete,
})
if err != nil {
c.logger.Error("error adding event handler to pod informer", zap.Error(err))
}
go c.informer.Run(c.stopCh)
_, err = c.namespaceInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handleNamespaceAdd,
UpdateFunc: c.handleNamespaceUpdate,
DeleteFunc: c.handleNamespaceDelete,
})
if err != nil {
c.logger.Error("error adding event handler to namespace informer", zap.Error(err))
}
go c.namespaceInformer.Run(c.stopCh)
if c.Rules.DeploymentName || c.Rules.DeploymentUID {
_, err = c.replicasetInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handleReplicaSetAdd,
UpdateFunc: c.handleReplicaSetUpdate,
DeleteFunc: c.handleReplicaSetDelete,
})
if err != nil {
c.logger.Error("error adding event handler to replicaset informer", zap.Error(err))
}
go c.replicasetInformer.Run(c.stopCh)
}
if c.nodeInformer != nil {
_, err = c.nodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handleNodeAdd,
UpdateFunc: c.handleNodeUpdate,
DeleteFunc: c.handleNodeDelete,
})
if err != nil {
c.logger.Error("error adding event handler to node informer", zap.Error(err))
}
go c.nodeInformer.Run(c.stopCh)
}
}
// Stop signals the the k8s watcher/informer to stop watching for new events.
func (c *WatchClient) Stop() {
close(c.stopCh)
}
func (c *WatchClient) handlePodAdd(obj any) {
observability.RecordPodAdded()
if pod, ok := obj.(*api_v1.Pod); ok {
c.addOrUpdatePod(pod)
} else {
c.logger.Error("object received was not of type api_v1.Pod", zap.Any("received", obj))
}
podTableSize := len(c.Pods)
observability.RecordPodTableSize(int64(podTableSize))
}
func (c *WatchClient) handlePodUpdate(_, newPod any) {
observability.RecordPodUpdated()
if pod, ok := newPod.(*api_v1.Pod); ok {
// TODO: update or remove based on whether container is ready/unready?.
c.addOrUpdatePod(pod)
} else {
c.logger.Error("object received was not of type api_v1.Pod", zap.Any("received", newPod))
}
podTableSize := len(c.Pods)
observability.RecordPodTableSize(int64(podTableSize))
}
func (c *WatchClient) handlePodDelete(obj any) {
observability.RecordPodDeleted()
if pod, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Pod); ok {
c.forgetPod(pod)
} else {
c.logger.Error("object received was not of type api_v1.Pod", zap.Any("received", obj))
}
podTableSize := len(c.Pods)
observability.RecordPodTableSize(int64(podTableSize))
}
func (c *WatchClient) handleNamespaceAdd(obj any) {
observability.RecordNamespaceAdded()
if namespace, ok := obj.(*api_v1.Namespace); ok {
c.addOrUpdateNamespace(namespace)
} else {
c.logger.Error("object received was not of type api_v1.Namespace", zap.Any("received", obj))
}
}
func (c *WatchClient) handleNamespaceUpdate(_, newNamespace any) {
observability.RecordNamespaceUpdated()
if namespace, ok := newNamespace.(*api_v1.Namespace); ok {
c.addOrUpdateNamespace(namespace)
} else {
c.logger.Error("object received was not of type api_v1.Namespace", zap.Any("received", newNamespace))
}
}
func (c *WatchClient) handleNamespaceDelete(obj any) {
observability.RecordNamespaceDeleted()
if namespace, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Namespace); ok {
c.m.Lock()
if ns, ok := c.Namespaces[namespace.Name]; ok {
// When a namespace is deleted all the pods(and other k8s objects in that namespace) in that namespace are deleted before it.
// So we wont have any spans that might need namespace annotations and labels.
// Thats why we dont need an implementation for deleteQueue and gracePeriod for namespaces.
delete(c.Namespaces, ns.Name)
}
c.m.Unlock()
} else {
c.logger.Error("object received was not of type api_v1.Namespace", zap.Any("received", obj))
}
}
func (c *WatchClient) handleNodeAdd(obj any) {
observability.RecordNodeAdded()
if node, ok := obj.(*api_v1.Node); ok {
c.addOrUpdateNode(node)
} else {
c.logger.Error("object received was not of type api_v1.Node", zap.Any("received", obj))
}
}
func (c *WatchClient) handleNodeUpdate(_, newNode any) {
observability.RecordNodeUpdated()
if node, ok := newNode.(*api_v1.Node); ok {
c.addOrUpdateNode(node)
} else {
c.logger.Error("object received was not of type api_v1.Node", zap.Any("received", newNode))
}
}
func (c *WatchClient) handleNodeDelete(obj any) {
observability.RecordNodeDeleted()
if node, ok := ignoreDeletedFinalStateUnknown(obj).(*api_v1.Node); ok {
c.m.Lock()
if n, ok := c.Nodes[node.Name]; ok {
delete(c.Nodes, n.Name)
}
c.m.Unlock()
} else {
c.logger.Error("object received was not of type api_v1.Node", zap.Any("received", obj))
}
}
func (c *WatchClient) deleteLoop(interval time.Duration, gracePeriod time.Duration) {
// This loop runs after N seconds and deletes pods from cache.
// It iterates over the delete queue and deletes all that aren't
// in the grace period anymore.
for {
select {
case <-time.After(interval):
var cutoff int
now := time.Now()
c.deleteMut.Lock()
for i, d := range c.deleteQueue {
if d.ts.Add(gracePeriod).After(now) {
break
}
cutoff = i + 1
}
toDelete := c.deleteQueue[:cutoff]
c.deleteQueue = c.deleteQueue[cutoff:]
c.deleteMut.Unlock()
c.m.Lock()
for _, d := range toDelete {
if p, ok := c.Pods[d.id]; ok {
// Sanity check: make sure we are deleting the same pod
// and the underlying state (ip<>pod mapping) has not changed.
if p.Name == d.podName {
delete(c.Pods, d.id)
}
}
}
podTableSize := len(c.Pods)
observability.RecordPodTableSize(int64(podTableSize))
c.m.Unlock()
case <-c.stopCh:
return
}
}
}
// GetPod takes an IP address or Pod UID and returns the pod the identifier is associated with.
func (c *WatchClient) GetPod(identifier PodIdentifier) (*Pod, bool) {
c.m.RLock()
pod, ok := c.Pods[identifier]
c.m.RUnlock()
if ok {
if pod.Ignore {
return nil, false
}
return pod, ok
}
observability.RecordIPLookupMiss()
return nil, false
}
// GetNamespace takes a namespace and returns the namespace object the namespace is associated with.
func (c *WatchClient) GetNamespace(namespace string) (*Namespace, bool) {
c.m.RLock()
ns, ok := c.Namespaces[namespace]
c.m.RUnlock()
if ok {
return ns, ok
}
return nil, false
}
// GetNode takes a node name and returns the node object the node name is associated with.
func (c *WatchClient) GetNode(nodeName string) (*Node, bool) {
c.m.RLock()
node, ok := c.Nodes[nodeName]
c.m.RUnlock()
if ok {
return node, ok
}
return nil, false
}
func (c *WatchClient) extractPodAttributes(pod *api_v1.Pod) map[string]string {
tags := map[string]string{}
if c.Rules.PodName {
tags[conventions.AttributeK8SPodName] = pod.Name
}
if c.Rules.PodHostName {
tags[tagHostName] = pod.Spec.Hostname
}
if c.Rules.Namespace {
tags[conventions.AttributeK8SNamespaceName] = pod.GetNamespace()
}
if c.Rules.StartTime {
ts := pod.GetCreationTimestamp()
if !ts.IsZero() {
if enableRFC3339Timestamp.IsEnabled() {
if rfc3339ts, err := ts.MarshalText(); err != nil {
c.logger.Error("failed to unmarshal pod creation timestamp", zap.Error(err))
} else {
tags[tagStartTime] = string(rfc3339ts)
}
} else {
tags[tagStartTime] = ts.String()
}
}
}
if c.Rules.PodUID {
uid := pod.GetUID()
tags[conventions.AttributeK8SPodUID] = string(uid)
}
if c.Rules.ReplicaSetID || c.Rules.ReplicaSetName ||
c.Rules.DaemonSetUID || c.Rules.DaemonSetName ||
c.Rules.JobUID || c.Rules.JobName ||
c.Rules.StatefulSetUID || c.Rules.StatefulSetName ||
c.Rules.DeploymentName || c.Rules.DeploymentUID ||
c.Rules.CronJobName {
for _, ref := range pod.OwnerReferences {
switch ref.Kind {
case "ReplicaSet":
if c.Rules.ReplicaSetID {
tags[conventions.AttributeK8SReplicaSetUID] = string(ref.UID)
}
if c.Rules.ReplicaSetName {
tags[conventions.AttributeK8SReplicaSetName] = ref.Name
}
if c.Rules.DeploymentName {
if replicaset, ok := c.getReplicaSet(string(ref.UID)); ok {
if replicaset.Deployment.Name != "" {
tags[conventions.AttributeK8SDeploymentName] = replicaset.Deployment.Name
}
}
}
if c.Rules.DeploymentUID {
if replicaset, ok := c.getReplicaSet(string(ref.UID)); ok {
if replicaset.Deployment.Name != "" {
tags[conventions.AttributeK8SDeploymentUID] = replicaset.Deployment.UID
}
}
}
case "DaemonSet":
if c.Rules.DaemonSetUID {
tags[conventions.AttributeK8SDaemonSetUID] = string(ref.UID)
}
if c.Rules.DaemonSetName {
tags[conventions.AttributeK8SDaemonSetName] = ref.Name
}
case "StatefulSet":
if c.Rules.StatefulSetUID {
tags[conventions.AttributeK8SStatefulSetUID] = string(ref.UID)
}
if c.Rules.StatefulSetName {
tags[conventions.AttributeK8SStatefulSetName] = ref.Name
}
case "Job":
if c.Rules.CronJobName {
parts := c.cronJobRegex.FindStringSubmatch(ref.Name)
if len(parts) == 2 {
tags[conventions.AttributeK8SCronJobName] = parts[1]
}
}
if c.Rules.JobUID {
tags[conventions.AttributeK8SJobUID] = string(ref.UID)
}
if c.Rules.JobName {
tags[conventions.AttributeK8SJobName] = ref.Name
}
}
}
}
if c.Rules.Node {
tags[tagNodeName] = pod.Spec.NodeName
}
if c.Rules.ClusterUID {
if val, ok := c.Namespaces["kube-system"]; ok {
tags[tagClusterUID] = val.NamespaceUID
} else {
c.logger.Debug("unable to find kube-system namespace, cluster uid will not be available")
}
}
for _, r := range c.Rules.Labels {
r.extractFromPodMetadata(pod.Labels, tags, "k8s.pod.labels.%s")
}
for _, r := range c.Rules.Annotations {
r.extractFromPodMetadata(pod.Annotations, tags, "k8s.pod.annotations.%s")
}
return tags
}
// This function removes all data from the Pod except what is required by extraction rules and pod association
func removeUnnecessaryPodData(pod *api_v1.Pod, rules ExtractionRules) *api_v1.Pod {
// name, namespace, uid, start time and ip are needed for identifying Pods
// there's room to optimize this further, it's kept this way for simplicity
transformedPod := api_v1.Pod{
ObjectMeta: meta_v1.ObjectMeta{
Name: pod.GetName(),
Namespace: pod.GetNamespace(),
UID: pod.GetUID(),
},
Status: api_v1.PodStatus{
PodIP: pod.Status.PodIP,
StartTime: pod.Status.StartTime,
},
Spec: api_v1.PodSpec{
HostNetwork: pod.Spec.HostNetwork,
},
}
if rules.StartTime {
transformedPod.SetCreationTimestamp(pod.GetCreationTimestamp())
}
if rules.PodUID {
transformedPod.SetUID(pod.GetUID())
}
if rules.Node {
transformedPod.Spec.NodeName = pod.Spec.NodeName
}
if rules.PodHostName {
transformedPod.Spec.Hostname = pod.Spec.Hostname
}
if needContainerAttributes(rules) {
for _, containerStatus := range pod.Status.ContainerStatuses {
transformedPod.Status.ContainerStatuses = append(
transformedPod.Status.ContainerStatuses,
api_v1.ContainerStatus{
Name: containerStatus.Name,
ContainerID: containerStatus.ContainerID,
RestartCount: containerStatus.RestartCount,
},
)
}
for _, containerStatus := range pod.Status.InitContainerStatuses {
transformedPod.Status.InitContainerStatuses = append(
transformedPod.Status.InitContainerStatuses,
api_v1.ContainerStatus{
Name: containerStatus.Name,
ContainerID: containerStatus.ContainerID,
RestartCount: containerStatus.RestartCount,
},
)
}
removeUnnecessaryContainerData := func(c api_v1.Container) api_v1.Container {
transformedContainer := api_v1.Container{}
transformedContainer.Name = c.Name // we always need the name, it's used for identification
if rules.ContainerImageName || rules.ContainerImageTag {
transformedContainer.Image = c.Image
}
return transformedContainer
}
for _, container := range pod.Spec.Containers {
transformedPod.Spec.Containers = append(
transformedPod.Spec.Containers, removeUnnecessaryContainerData(container),
)
}
for _, container := range pod.Spec.InitContainers {
transformedPod.Spec.InitContainers = append(
transformedPod.Spec.InitContainers, removeUnnecessaryContainerData(container),
)
}
}
if len(rules.Labels) > 0 {
transformedPod.Labels = pod.Labels
}
if len(rules.Annotations) > 0 {
transformedPod.Annotations = pod.Annotations
}
if rules.IncludesOwnerMetadata() {
transformedPod.SetOwnerReferences(pod.GetOwnerReferences())
}
return &transformedPod
}
func (c *WatchClient) extractPodContainersAttributes(pod *api_v1.Pod) PodContainers {
containers := PodContainers{
ByID: map[string]*Container{},
ByName: map[string]*Container{},
}
if !needContainerAttributes(c.Rules) {
return containers
}
if c.Rules.ContainerImageName || c.Rules.ContainerImageTag {
for _, spec := range append(pod.Spec.Containers, pod.Spec.InitContainers...) {
container := &Container{}
nameTagSep := strings.LastIndex(spec.Image, ":")
if c.Rules.ContainerImageName {
if nameTagSep > 0 {
container.ImageName = spec.Image[:nameTagSep]
} else {
container.ImageName = spec.Image
}
}
if c.Rules.ContainerImageTag && nameTagSep > 0 {
container.ImageTag = spec.Image[nameTagSep+1:]
}
containers.ByName[spec.Name] = container
}
}
for _, apiStatus := range append(pod.Status.ContainerStatuses, pod.Status.InitContainerStatuses...) {
container, ok := containers.ByName[apiStatus.Name]
if !ok {
container = &Container{}
containers.ByName[apiStatus.Name] = container
}
if c.Rules.ContainerName {
container.Name = apiStatus.Name
}
containerID := apiStatus.ContainerID
// Remove container runtime prefix
parts := strings.Split(containerID, "://")
if len(parts) == 2 {
containerID = parts[1]
}
containers.ByID[containerID] = container
if c.Rules.ContainerID {
if container.Statuses == nil {
container.Statuses = map[int]ContainerStatus{}
}
container.Statuses[int(apiStatus.RestartCount)] = ContainerStatus{containerID}
}
}
return containers
}
func (c *WatchClient) extractNamespaceAttributes(namespace *api_v1.Namespace) map[string]string {
tags := map[string]string{}
for _, r := range c.Rules.Labels {
r.extractFromNamespaceMetadata(namespace.Labels, tags, "k8s.namespace.labels.%s")
}
for _, r := range c.Rules.Annotations {
r.extractFromNamespaceMetadata(namespace.Annotations, tags, "k8s.namespace.annotations.%s")
}
return tags
}
func (c *WatchClient) extractNodeAttributes(node *api_v1.Node) map[string]string {
tags := map[string]string{}
for _, r := range c.Rules.Labels {
r.extractFromNodeMetadata(node.Labels, tags, "k8s.node.labels.%s")
}
for _, r := range c.Rules.Annotations {
r.extractFromNodeMetadata(node.Annotations, tags, "k8s.node.annotations.%s")
}
return tags
}
func (c *WatchClient) podFromAPI(pod *api_v1.Pod) *Pod {
newPod := &Pod{
Name: pod.Name,
Namespace: pod.GetNamespace(),
NodeName: pod.Spec.NodeName,
Address: pod.Status.PodIP,
HostNetwork: pod.Spec.HostNetwork,
PodUID: string(pod.UID),
StartTime: pod.Status.StartTime,
}
if c.shouldIgnorePod(pod) {
newPod.Ignore = true
} else {
newPod.Attributes = c.extractPodAttributes(pod)
if needContainerAttributes(c.Rules) {
newPod.Containers = c.extractPodContainersAttributes(pod)
}
}
return newPod
}
// getIdentifiersFromAssoc returns list of PodIdentifiers for given pod
func (c *WatchClient) getIdentifiersFromAssoc(pod *Pod) []PodIdentifier {
var ids []PodIdentifier
for _, assoc := range c.Associations {
ret := PodIdentifier{}
skip := false
for i, source := range assoc.Sources {
// If association configured to take IP address from connection
switch {
case source.From == ConnectionSource:
if pod.Address == "" {
skip = true
break
}
// Host network mode is not supported right now with IP based
// tagging as all pods in host network get same IP addresses.
// Such pods are very rare and usually are used to monitor or control
// host traffic (e.g, linkerd, flannel) instead of service business needs.
if pod.HostNetwork {
skip = true
break
}
ret[i] = PodIdentifierAttributeFromSource(source, pod.Address)
case source.From == ResourceSource:
attr := ""
switch source.Name {
case conventions.AttributeK8SNamespaceName:
attr = pod.Namespace
case conventions.AttributeK8SPodName:
attr = pod.Name
case conventions.AttributeK8SPodUID:
attr = pod.PodUID
case conventions.AttributeHostName:
attr = pod.Address
// k8s.pod.ip is set by passthrough mode
case K8sIPLabelName:
attr = pod.Address
default:
if v, ok := pod.Attributes[source.Name]; ok {
attr = v
}
}
if attr == "" {
skip = true
break
}
ret[i] = PodIdentifierAttributeFromSource(source, attr)
}
}
if !skip {
ids = append(ids, ret)
}
}
// Ensure backward compatibility
if pod.PodUID != "" {
ids = append(ids, PodIdentifier{
PodIdentifierAttributeFromResourceAttribute(conventions.AttributeK8SPodUID, pod.PodUID),
})
}
if pod.Address != "" && !pod.HostNetwork {
ids = append(ids, PodIdentifier{
PodIdentifierAttributeFromConnection(pod.Address),
})
// k8s.pod.ip is set by passthrough mode
ids = append(ids, PodIdentifier{
PodIdentifierAttributeFromResourceAttribute(K8sIPLabelName, pod.Address),
})
}
return ids
}
func (c *WatchClient) addOrUpdatePod(pod *api_v1.Pod) {
newPod := c.podFromAPI(pod)
c.m.Lock()
defer c.m.Unlock()
for _, id := range c.getIdentifiersFromAssoc(newPod) {
// compare initial scheduled timestamp for existing pod and new pod with same identifier
// and only replace old pod if scheduled time of new pod is newer or equal.
// This should fix the case where scheduler has assigned the same attributes (like IP address)
// to a new pod but update event for the old pod came in later.
if p, ok := c.Pods[id]; ok {
if pod.Status.StartTime.Before(p.StartTime) {
continue
}
}
c.Pods[id] = newPod
}
}
func (c *WatchClient) forgetPod(pod *api_v1.Pod) {
podToRemove := c.podFromAPI(pod)
for _, id := range c.getIdentifiersFromAssoc(podToRemove) {
p, ok := c.GetPod(id)
if ok && p.Name == pod.Name {
c.appendDeleteQueue(id, pod.Name)
}
}
}
func (c *WatchClient) appendDeleteQueue(podID PodIdentifier, podName string) {
c.deleteMut.Lock()
c.deleteQueue = append(c.deleteQueue, deleteRequest{
id: podID,
podName: podName,
ts: time.Now(),
})
c.deleteMut.Unlock()
}
func (c *WatchClient) shouldIgnorePod(pod *api_v1.Pod) bool {
// Check if user requested the pod to be ignored through annotations
if v, ok := pod.Annotations[ignoreAnnotation]; ok {
if strings.ToLower(strings.TrimSpace(v)) == "true" {
return true
}
}
// Check if user requested the pod to be ignored through configuration
for _, excludedPod := range c.Exclude.Pods {
if excludedPod.Name.MatchString(pod.Name) {
return true
}
}
return false
}
func selectorsFromFilters(filters Filters) (labels.Selector, fields.Selector, error) {
labelSelector := labels.Everything()
for _, f := range filters.Labels {
r, err := labels.NewRequirement(f.Key, f.Op, []string{f.Value})
if err != nil {
return nil, nil, err
}
labelSelector = labelSelector.Add(*r)
}
var selectors []fields.Selector
for _, f := range filters.Fields {
switch f.Op {
case selection.Equals:
selectors = append(selectors, fields.OneTermEqualSelector(f.Key, f.Value))
case selection.NotEquals:
selectors = append(selectors, fields.OneTermNotEqualSelector(f.Key, f.Value))
case selection.DoesNotExist, selection.DoubleEquals, selection.In, selection.NotIn, selection.Exists, selection.GreaterThan, selection.LessThan:
fallthrough
default:
return nil, nil, fmt.Errorf("field filters don't support operator: '%s'", f.Op)
}
}
if filters.Node != "" {
selectors = append(selectors, fields.OneTermEqualSelector(podNodeField, filters.Node))
}
return labelSelector, fields.AndSelectors(selectors...), nil
}
func (c *WatchClient) addOrUpdateNamespace(namespace *api_v1.Namespace) {
newNamespace := &Namespace{
Name: namespace.Name,
NamespaceUID: string(namespace.UID),
StartTime: namespace.GetCreationTimestamp(),
}
newNamespace.Attributes = c.extractNamespaceAttributes(namespace)
c.m.Lock()
if namespace.Name != "" {
c.Namespaces[namespace.Name] = newNamespace
}
c.m.Unlock()
}
func (c *WatchClient) extractNamespaceLabelsAnnotations() bool {
for _, r := range c.Rules.Labels {
if r.From == MetadataFromNamespace {
return true
}
}
for _, r := range c.Rules.Annotations {
if r.From == MetadataFromNamespace {
return true
}
}
return false
}
func (c *WatchClient) extractNodeLabelsAnnotations() bool {
for _, r := range c.Rules.Labels {
if r.From == MetadataFromNode {
return true
}
}
for _, r := range c.Rules.Annotations {
if r.From == MetadataFromNode {
return true
}
}
return false
}
func (c *WatchClient) addOrUpdateNode(node *api_v1.Node) {
newNode := &Node{
Name: node.Name,
NodeUID: string(node.UID),
}
newNode.Attributes = c.extractNodeAttributes(node)
c.m.Lock()
if node.Name != "" {
c.Nodes[node.Name] = newNode
}
c.m.Unlock()
}
func needContainerAttributes(rules ExtractionRules) bool {
return rules.ContainerImageName ||
rules.ContainerName ||
rules.ContainerImageTag ||
rules.ContainerID
}
func (c *WatchClient) handleReplicaSetAdd(obj any) {
observability.RecordReplicaSetAdded()
if replicaset, ok := obj.(*apps_v1.ReplicaSet); ok {
c.addOrUpdateReplicaSet(replicaset)
} else {
c.logger.Error("object received was not of type apps_v1.ReplicaSet", zap.Any("received", obj))
}
}
func (c *WatchClient) handleReplicaSetUpdate(_, newRS any) {
observability.RecordReplicaSetUpdated()
if replicaset, ok := newRS.(*apps_v1.ReplicaSet); ok {
c.addOrUpdateReplicaSet(replicaset)
} else {
c.logger.Error("object received was not of type apps_v1.ReplicaSet", zap.Any("received", newRS))
}
}
func (c *WatchClient) handleReplicaSetDelete(obj any) {
observability.RecordReplicaSetDeleted()
if replicaset, ok := ignoreDeletedFinalStateUnknown(obj).(*apps_v1.ReplicaSet); ok {
c.m.Lock()
key := string(replicaset.UID)
delete(c.ReplicaSets, key)
c.m.Unlock()
} else {
c.logger.Error("object received was not of type apps_v1.ReplicaSet", zap.Any("received", obj))
}
}
func (c *WatchClient) addOrUpdateReplicaSet(replicaset *apps_v1.ReplicaSet) {
newReplicaSet := &ReplicaSet{
Name: replicaset.Name,
Namespace: replicaset.Namespace,
UID: string(replicaset.UID),
}
for _, ownerReference := range replicaset.OwnerReferences {
if ownerReference.Kind == "Deployment" && ownerReference.Controller != nil && *ownerReference.Controller {
newReplicaSet.Deployment = Deployment{
Name: ownerReference.Name,
UID: string(ownerReference.UID),
}
break
}
}
c.m.Lock()
if replicaset.UID != "" {
c.ReplicaSets[string(replicaset.UID)] = newReplicaSet