-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontroller.go
More file actions
322 lines (274 loc) · 8.45 KB
/
controller.go
File metadata and controls
322 lines (274 loc) · 8.45 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
package controller
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/github/deployment-tracker/pkg/deploymentrecord"
"github.com/github/deployment-tracker/pkg/image"
corev1 "k8s.io/api/core/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"
)
// PodEvent represents a pod event to be processed.
type PodEvent struct {
Key string
EventType string
Pod *corev1.Pod
}
// Controller is the Kubernetes controller for tracking deployments.
type Controller struct {
clientset kubernetes.Interface
podInformer cache.SharedIndexInformer
workqueue workqueue.TypedRateLimitingInterface[PodEvent]
apiClient *deploymentrecord.Client
cfg *Config
}
// New creates a new deployment tracker controller.
func New(clientset kubernetes.Interface, namespace string, cfg *Config) *Controller {
// Create informer factory
var factory informers.SharedInformerFactory
if namespace == "" {
factory = informers.NewSharedInformerFactory(clientset, 30*time.Second)
} else {
factory = informers.NewSharedInformerFactoryWithOptions(
clientset,
30*time.Second,
informers.WithNamespace(namespace),
)
}
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))
}
apiClient := deploymentrecord.NewClient(cfg.BaseURL, cfg.Org, clientOpts...)
cntrl := &Controller{
clientset: clientset,
podInformer: podInformer,
workqueue: queue,
apiClient: apiClient,
cfg: cfg,
}
// Add event handlers to the informer
_, err := podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
pod, ok := obj.(*corev1.Pod)
if !ok {
fmt.Printf("error: invalid object returned: %+v\n",
obj)
return
}
// Only process pods that are running
if pod.Status.Phase == corev1.PodRunning {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(PodEvent{Key: key, EventType: "CREATED", Pod: pod.DeepCopy()})
}
}
},
UpdateFunc: func(oldObj, newObj any) {
oldPod, ok := oldObj.(*corev1.Pod)
if !ok {
fmt.Printf("error: invalid object returned: %+v\n",
oldObj)
return
}
newPod, ok := newObj.(*corev1.Pod)
if !ok {
fmt.Printf("error: invalid object returned: %+v\n",
newObj)
return
}
// Skip if pod is being deleted
if newPod.DeletionTimestamp != nil {
return
}
// Only process if pod just became running
if oldPod.Status.Phase != corev1.PodRunning && newPod.Status.Phase == corev1.PodRunning {
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err == nil {
queue.Add(PodEvent{Key: key, EventType: "CREATED", Pod: newPod.DeepCopy()})
}
}
},
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
}
}
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(PodEvent{Key: key, EventType: "DELETED", Pod: pod.DeepCopy()})
}
},
})
if err != nil {
fmt.Printf("ERROR: failed to add event handlers: %s\n", err)
}
return cntrl
}
// Run starts the controller.
func (c *Controller) Run(ctx context.Context, workers int) error {
defer runtime.HandleCrash()
defer c.workqueue.ShutDown()
fmt.Println("Starting pod informer")
// Start the informer
go c.podInformer.Run(ctx.Done())
// Wait for the cache to be synced
fmt.Println("Waiting for informer cache to sync")
if !cache.WaitForCacheSync(ctx.Done(), c.podInformer.HasSynced) {
return errors.New("timed out waiting for caches to sync")
}
fmt.Printf("Starting %d workers\n", workers)
// Start workers
for i := 0; i < workers; i++ {
go wait.UntilWithContext(ctx, c.runWorker, time.Second)
}
fmt.Println("Controller started")
<-ctx.Done()
fmt.Println("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)
err := c.processEvent(ctx, event)
if err == nil {
c.workqueue.Forget(event)
return true
}
// Requeue on error with rate limiting
fmt.Printf("Error processing %s: %v, requeuing\n", event.Key, err)
c.workqueue.AddRateLimited(event)
return true
}
// processEvent processes a single pod event.
func (c *Controller) processEvent(ctx context.Context, event PodEvent) error {
timestamp := time.Now().Format(time.RFC3339)
pod := event.Pod
if pod == nil {
return nil
}
status := deploymentrecord.StatusDeployed
if event.EventType == "DELETED" {
status = deploymentrecord.StatusDecommissioned
}
var lastErr error
// Record info for each container in the pod
for _, container := range pod.Spec.Containers {
if err := c.recordContainer(ctx, pod, container, status, event.EventType, timestamp); err != nil {
lastErr = err
}
}
// Also record init containers
for _, container := range pod.Spec.InitContainers {
if err := c.recordContainer(ctx, pod, container, status, event.EventType, timestamp); err != nil {
lastErr = err
}
}
return lastErr
}
// recordContainer records a single container's deployment info.
func (c *Controller) recordContainer(ctx context.Context, pod *corev1.Pod, container corev1.Container, status, eventType, timestamp string) error {
dn := getARDeploymentName(pod, container, c.cfg.Template)
digest := getContainerDigest(pod, container.Name)
if dn == "" || digest == "" {
return nil
}
// Extract image name and tag
imageName, version := image.ExtractName(container.Image)
// Create deployment record
record := deploymentrecord.NewDeploymentRecord(
imageName,
digest,
version,
c.cfg.LogicalEnvironment,
c.cfg.PhysicalEnvironment,
c.cfg.Cluster,
status,
dn,
)
if err := c.apiClient.PostOne(ctx, record); err != nil {
fmt.Printf("[%s] FAILED %s name=%s deployment_name=%s error=%v\n",
timestamp, eventType, record.Name, record.DeploymentName, err)
return err
}
fmt.Printf("[%s] OK %s name=%s deployment_name=%s digest=%s status=%s\n",
timestamp, eventType, record.Name, record.DeploymentName, record.Digest, record.Status)
return nil
}
// 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.
func getContainerDigest(pod *corev1.Pod, containerName string) string {
// Check regular container statuses
for _, status := range pod.Status.ContainerStatuses {
if status.Name == containerName {
return image.ExtractDigest(status.ImageID)
}
}
// Check init container statuses
for _, status := range pod.Status.InitContainerStatuses {
if status.Name == containerName {
return image.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 ""
}