-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontroller.go
More file actions
676 lines (598 loc) · 18.9 KB
/
controller.go
File metadata and controls
676 lines (598 loc) · 18.9 KB
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
package controller
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/github/deployment-tracker/internal/metadata"
"github.com/github/deployment-tracker/pkg/deploymentrecord"
"github.com/github/deployment-tracker/pkg/dtmetrics"
"github.com/github/deployment-tracker/pkg/ociutil"
amcache "k8s.io/apimachinery/pkg/util/cache"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
const (
// EventCreated indicates that a pod has been created.
EventCreated = "CREATED"
// EventDeleted indicates that a pod has been deleted.
EventDeleted = "DELETED"
// unknownArtifactTTL is the TTL for cached 404 responses from the
// deployment record API. Once an artifact is known to be missing,
// we suppress further API calls for this duration.
unknownArtifactTTL = 1 * time.Hour
)
type ttlCache interface {
Get(k any) (any, bool)
Set(k any, v any, ttl time.Duration)
Delete(k any)
}
type deploymentRecordPoster interface {
PostOne(ctx context.Context, record *deploymentrecord.DeploymentRecord) error
}
type podMetadataAggregator interface {
BuildAggregatePodMetadata(ctx context.Context, obj *metav1.PartialObjectMetadata) *metadata.AggregatePodMetadata
}
// PodEvent represents a pod event to be processed.
type PodEvent struct {
Key string
EventType string
DeletedPod *corev1.Pod // Only populated for delete events
}
// Controller is the Kubernetes controller for tracking deployments.
type Controller struct {
clientset kubernetes.Interface
metadataAggregator podMetadataAggregator
podInformer cache.SharedIndexInformer
workqueue workqueue.TypedRateLimitingInterface[PodEvent]
apiClient deploymentRecordPoster
cfg *Config
// best effort cache to avoid redundant posts
// post requests are idempotent, so if this cache fails due to
// restarts or other events, nothing will break.
observedDeployments ttlCache
// best effort cache to suppress API calls for artifacts that
// returned a 404 (no artifact found). Keyed by image digest.
unknownArtifacts ttlCache
}
// New creates a new deployment tracker controller.
func New(clientset kubernetes.Interface, metadataAggregator podMetadataAggregator, namespace string, excludeNamespaces string, cfg *Config) (*Controller, error) {
// Create informer factory
factory := createInformerFactory(clientset, namespace, excludeNamespaces)
podInformer := factory.Core().V1().Pods().Informer()
// Create work queue with rate limiting
queue := workqueue.NewTypedRateLimitingQueue(
workqueue.DefaultTypedControllerRateLimiter[PodEvent](),
)
// Create API client with optional token
clientOpts := []deploymentrecord.ClientOption{}
if cfg.APIToken != "" {
clientOpts = append(clientOpts, deploymentrecord.WithAPIToken(cfg.APIToken))
}
if cfg.GHAppID != "" &&
cfg.GHInstallID != "" &&
(len(cfg.GHAppPrivateKey) > 0 || cfg.GHAppPrivateKeyPath != "") {
clientOpts = append(clientOpts, deploymentrecord.WithGHApp(
cfg.GHAppID,
cfg.GHInstallID,
cfg.GHAppPrivateKey,
cfg.GHAppPrivateKeyPath,
))
}
apiClient, err := deploymentrecord.NewClient(
cfg.BaseURL,
cfg.Organization,
clientOpts...,
)
if err != nil {
return nil, fmt.Errorf("failed to create API client: %w", err)
}
cntrl := &Controller{
clientset: clientset,
metadataAggregator: metadataAggregator,
podInformer: podInformer,
workqueue: queue,
apiClient: apiClient,
cfg: cfg,
observedDeployments: amcache.NewExpiring(),
unknownArtifacts: amcache.NewExpiring(),
}
// Add event handlers to the informer
_, err = podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
pod, ok := obj.(*corev1.Pod)
if !ok {
slog.Error("Invalid object returned",
"object", obj,
)
return
}
// Only process pods that are running and belong
// to a deployment
if pod.Status.Phase == corev1.PodRunning && getDeploymentName(pod) != "" {
key, err := cache.MetaNamespaceKeyFunc(obj)
// For our purposes, there are in practice
// no error event we care about, so don't
// bother with handling it.
if err == nil {
queue.Add(PodEvent{
Key: key,
EventType: EventCreated,
})
}
}
},
UpdateFunc: func(oldObj, newObj any) {
oldPod, ok := oldObj.(*corev1.Pod)
if !ok {
slog.Error("Invalid old object returned",
"object", oldObj,
)
return
}
newPod, ok := newObj.(*corev1.Pod)
if !ok {
slog.Error("Invalid new object returned",
"object", newObj,
)
return
}
// Skip if pod is being deleted or doesn't belong
// to a deployment
if newPod.DeletionTimestamp != nil || getDeploymentName(newPod) == "" {
return
}
// Only process if pod just became running.
// We need to process this as often when a container
// is created, the spec does not contain the digest
// so we need to wait for the status field to be
// populated from where we can get the digest.
if oldPod.Status.Phase != corev1.PodRunning &&
newPod.Status.Phase == corev1.PodRunning {
key, err := cache.MetaNamespaceKeyFunc(newObj)
// For our purposes, there are in practice
// no error event we care about, so don't
// bother with handling it.
if err == nil {
queue.Add(PodEvent{
Key: key,
EventType: EventCreated,
})
}
}
},
DeleteFunc: func(obj any) {
pod, ok := obj.(*corev1.Pod)
if !ok {
// Handle deleted final state unknown
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
pod, ok = tombstone.Obj.(*corev1.Pod)
if !ok {
return
}
}
// Only process pods that belong to a deployment
if getDeploymentName(pod) == "" {
return
}
key, err := cache.MetaNamespaceKeyFunc(obj)
// For our purposes, there are in practice
// no error event we care about, so don't
// bother with handling it.
if err == nil {
queue.Add(PodEvent{
Key: key,
EventType: EventDeleted,
DeletedPod: pod,
})
}
},
})
if err != nil {
return nil, fmt.Errorf("failed to add event handlers: %w", err)
}
return cntrl, nil
}
// Run starts the controller.
func (c *Controller) Run(ctx context.Context, workers int) error {
defer runtime.HandleCrash()
defer c.workqueue.ShutDown()
slog.Info("Starting pod informer")
// Start the informer
go c.podInformer.Run(ctx.Done())
// Wait for the cache to be synced
slog.Info("Waiting for informer cache to sync")
if !cache.WaitForCacheSync(ctx.Done(), c.podInformer.HasSynced) {
return errors.New("timed out waiting for caches to sync")
}
slog.Info("Starting workers",
"count", workers,
)
// Start workers
for i := 0; i < workers; i++ {
go wait.UntilWithContext(ctx, c.runWorker, time.Second)
}
slog.Info("Controller started")
<-ctx.Done()
slog.Info("Shutting down workers")
return nil
}
// runWorker runs a worker to process items from the work queue.
func (c *Controller) runWorker(ctx context.Context) {
for c.processNextItem(ctx) {
}
}
// processNextItem processes the next item from the work queue.
func (c *Controller) processNextItem(ctx context.Context) bool {
event, shutdown := c.workqueue.Get()
if shutdown {
return false
}
defer c.workqueue.Done(event)
start := time.Now()
err := c.processEvent(ctx, event)
dur := time.Since(start)
if err == nil {
dtmetrics.EventsProcessedOk.WithLabelValues(event.EventType).Inc()
dtmetrics.EventsProcessedTimer.WithLabelValues("ok").Observe(dur.Seconds())
c.workqueue.Forget(event)
return true
}
dtmetrics.EventsProcessedTimer.WithLabelValues("failed").Observe(dur.Seconds())
dtmetrics.EventsProcessedFailed.WithLabelValues(event.EventType).Inc()
// Requeue on error with rate limiting
slog.Error("Failed to process event, requeuing",
"event_key", event.Key,
"error", err,
)
c.workqueue.AddRateLimited(event)
return true
}
// processEvent processes a single pod event.
func (c *Controller) processEvent(ctx context.Context, event PodEvent) error {
var pod *corev1.Pod
if event.EventType == EventDeleted {
// For delete events, use the pod captured at deletion time
pod = event.DeletedPod
if pod == nil {
slog.Error("Delete event missing pod data",
"key", event.Key,
)
return nil
}
// Check if the parent deployment still exists
// If it does, this is just a scale-down event, skip it.
//
// If a deployment changes image versions, this will not
// fire delete/decommissioned events to the remote API.
// This is as intended, as the server will keep track of
// the (cluster unique) deployment name, and just update
// the referenced image digest to the newly observed (via
// the create event).
deploymentName := getDeploymentName(pod)
if deploymentName != "" && c.deploymentExists(ctx, pod.Namespace, deploymentName) {
slog.Debug("Deployment still exists, skipping pod delete (scale down)",
"namespace", pod.Namespace,
"deployment", deploymentName,
"pod", pod.Name,
)
return nil
}
} else {
// For create events, get the pod from the informer's cache
obj, exists, err := c.podInformer.GetIndexer().GetByKey(event.Key)
if err != nil {
slog.Error("Failed to get pod from cache",
"key", event.Key,
"error", err,
)
return nil
}
if !exists {
// Pod no longer exists in cache, skip processing
return nil
}
var ok bool
pod, ok = obj.(*corev1.Pod)
if !ok {
slog.Error("Invalid object type in cache",
"key", event.Key,
)
return nil
}
}
status := deploymentrecord.StatusDeployed
if event.EventType == EventDeleted {
status = deploymentrecord.StatusDecommissioned
}
var lastErr error
// Gather aggregate metadata for adds/updates
var aggPodMetadata *metadata.AggregatePodMetadata
if status != deploymentrecord.StatusDecommissioned {
aggPodMetadata = c.metadataAggregator.BuildAggregatePodMetadata(ctx, podToPartialMetadata(pod))
}
// Record info for each container in the pod
for _, container := range pod.Spec.Containers {
if err := c.recordContainer(ctx, pod, container, status, event.EventType, aggPodMetadata); err != nil {
lastErr = err
}
}
// Also record init containers
for _, container := range pod.Spec.InitContainers {
if err := c.recordContainer(ctx, pod, container, status, event.EventType, aggPodMetadata); err != nil {
lastErr = err
}
}
return lastErr
}
// deploymentExists checks if a deployment exists in the cluster.
func (c *Controller) deploymentExists(ctx context.Context, namespace, name string) bool {
_, err := c.clientset.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if k8serrors.IsNotFound(err) {
return false
}
// On error, assume it exists to be safe
// (avoid false decommissions)
slog.Warn("Failed to check if deployment exists, assuming it does",
"namespace", namespace,
"deployment", name,
"error", err,
)
return true
}
return true
}
// recordContainer records a single container's deployment info.
func (c *Controller) recordContainer(ctx context.Context, pod *corev1.Pod, container corev1.Container, status, eventType string, aggPodMetadata *metadata.AggregatePodMetadata) error {
var cacheKey string
dn := getARDeploymentName(pod, container, c.cfg.Template)
digest := getContainerDigest(pod, container.Name)
if dn == "" || digest == "" {
slog.Debug("Skipping container: missing deployment name or digest",
"namespace", pod.Namespace,
"pod", pod.Name,
"container", container.Name,
"deployment_name", dn,
"has_digest", digest != "",
)
return nil
}
// Check if we've already recorded this deployment
switch status {
case deploymentrecord.StatusDeployed:
cacheKey = getCacheKey(EventCreated, dn, digest)
if _, exists := c.observedDeployments.Get(cacheKey); exists {
slog.Debug("Deployment already observed, skipping post",
"deployment_name", dn,
"digest", digest,
)
return nil
}
case deploymentrecord.StatusDecommissioned:
cacheKey = getCacheKey(EventDeleted, dn, digest)
if _, exists := c.observedDeployments.Get(cacheKey); exists {
slog.Debug("Deployment already deleted, skipping post",
"deployment_name", dn,
"digest", digest,
)
return nil
}
default:
return fmt.Errorf("invalid status: %s", status)
}
// Check if this artifact was previously unknown (404 from the API)
if _, exists := c.unknownArtifacts.Get(digest); exists {
dtmetrics.PostDeploymentRecordUnknownArtifactCacheHit.Inc()
slog.Debug("Artifact previously returned 404, skipping post",
"deployment_name", dn,
"digest", digest,
)
return nil
}
// Extract image name and tag
imageName, version := ociutil.ExtractName(container.Image)
// Format runtime risks and tags
var runtimeRisks []deploymentrecord.RuntimeRisk
var tags map[string]string
if aggPodMetadata != nil {
for risk := range aggPodMetadata.RuntimeRisks {
runtimeRisks = append(runtimeRisks, risk)
}
slices.Sort(runtimeRisks)
tags = aggPodMetadata.Tags
}
// Create deployment record
record := deploymentrecord.NewDeploymentRecord(
imageName,
digest,
version,
c.cfg.LogicalEnvironment,
c.cfg.PhysicalEnvironment,
c.cfg.Cluster,
status,
dn,
runtimeRisks,
tags,
)
if err := c.apiClient.PostOne(ctx, record); err != nil {
// Return if no artifact is found and cache the digest
var noArtifactErr *deploymentrecord.NoArtifactError
if errors.As(err, &noArtifactErr) {
c.unknownArtifacts.Set(digest, true, unknownArtifactTTL)
slog.Info("No artifact found, digest cached as unknown",
"deployment_name", dn,
"digest", digest,
)
return nil
}
// Make sure to not retry on client error messages
var clientErr *deploymentrecord.ClientError
if errors.As(err, &clientErr) {
slog.Warn("Failed to post record",
"event_type", eventType,
"name", record.Name,
"deployment_name", record.DeploymentName,
"status", record.Status,
"digest", record.Digest,
"error", err,
)
return nil
}
slog.Error("Failed to post record",
"event_type", eventType,
"name", record.Name,
"deployment_name", record.DeploymentName,
"status", record.Status,
"digest", record.Digest,
"error", err,
)
return err
}
slog.Info("Posted record",
"event_type", eventType,
"name", record.Name,
"deployment_name", record.DeploymentName,
"status", record.Status,
"digest", record.Digest,
"runtime_risks", record.RuntimeRisks,
"tags", record.Tags,
)
// Update cache after successful post
switch status {
case deploymentrecord.StatusDeployed:
cacheKey = getCacheKey(EventCreated, dn, digest)
c.observedDeployments.Set(cacheKey, true, 2*time.Minute)
// If there was a previous delete event, remove that
cacheKey = getCacheKey(EventDeleted, dn, digest)
c.observedDeployments.Delete(cacheKey)
case deploymentrecord.StatusDecommissioned:
cacheKey = getCacheKey(EventDeleted, dn, digest)
c.observedDeployments.Set(cacheKey, true, 2*time.Minute)
// If there was a previous create event, remove that
cacheKey = getCacheKey(EventCreated, dn, digest)
c.observedDeployments.Delete(cacheKey)
default:
return fmt.Errorf("invalid status: %s", status)
}
return nil
}
func getCacheKey(ev, dn, digest string) string {
return ev + "||" + dn + "||" + digest
}
// createInformerFactory creates a shared informer factory with the given resync period.
// If excludeNamespaces is non-empty, it will exclude those namespaces from being watched.
// If namespace is non-empty, it will only watch that namespace.
func createInformerFactory(clientset kubernetes.Interface, namespace string, excludeNamespaces string) informers.SharedInformerFactory {
var factory informers.SharedInformerFactory
switch {
case namespace != "":
slog.Info("Namespace to watch",
"namespace",
namespace,
)
factory = informers.NewSharedInformerFactoryWithOptions(
clientset,
30*time.Second,
informers.WithNamespace(namespace),
)
case excludeNamespaces != "":
seenNamespaces := make(map[string]bool)
fieldSelectorParts := make([]string, 0)
for _, ns := range strings.Split(excludeNamespaces, ",") {
ns = strings.TrimSpace(ns)
if ns != "" && !seenNamespaces[ns] {
seenNamespaces[ns] = true
fieldSelectorParts = append(fieldSelectorParts, fmt.Sprintf("metadata.namespace!=%s", ns))
}
}
slog.Info("Excluding namespaces from watch",
"field_selector",
strings.Join(fieldSelectorParts, ","),
)
tweakListOptions := func(options *metav1.ListOptions) {
options.FieldSelector = strings.Join(fieldSelectorParts, ",")
}
factory = informers.NewSharedInformerFactoryWithOptions(
clientset,
30*time.Second,
informers.WithTweakListOptions(tweakListOptions),
)
default:
factory = informers.NewSharedInformerFactory(clientset,
30*time.Second,
)
}
return factory
}
// getARDeploymentName converts the pod's metadata into the correct format
// for the deployment name for the artifact registry (this is not the same
// as the K8s deployment's name!)
// The deployment name must unique within logical, physical environment and
// the cluster.
func getARDeploymentName(p *corev1.Pod, c corev1.Container, tmpl string) string {
res := tmpl
res = strings.ReplaceAll(res, TmplNS, p.Namespace)
res = strings.ReplaceAll(res, TmplDN, getDeploymentName(p))
res = strings.ReplaceAll(res, TmplCN, c.Name)
return res
}
// getContainerDigest extracts the image digest from the container status.
// The spec only contains the desired state, so any resolved digests must
// be pulled from the status field.
func getContainerDigest(pod *corev1.Pod, containerName string) string {
// Check regular container statuses
for _, status := range pod.Status.ContainerStatuses {
if status.Name == containerName {
return ociutil.ExtractDigest(status.ImageID)
}
}
// Check init container statuses
for _, status := range pod.Status.InitContainerStatuses {
if status.Name == containerName {
return ociutil.ExtractDigest(status.ImageID)
}
}
return ""
}
// getDeploymentName returns the deployment name for a pod, if it belongs
// to one.
func getDeploymentName(pod *corev1.Pod) string {
// Pods created by Deployments are owned by ReplicaSets
// The ReplicaSet name follows the pattern: <deployment-name>-<hash>
for _, owner := range pod.OwnerReferences {
if owner.Kind == "ReplicaSet" {
// Extract deployment name by removing the hash suffix
// ReplicaSet name format: <deployment-name>-<hash>
rsName := owner.Name
lastDash := strings.LastIndex(rsName, "-")
if lastDash > 0 {
return rsName[:lastDash]
}
return rsName
}
}
return ""
}
func podToPartialMetadata(pod *corev1.Pod) *metav1.PartialObjectMetadata {
return &metav1.PartialObjectMetadata{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Pod",
},
ObjectMeta: pod.ObjectMeta,
}
}