-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpod_tracker.go
271 lines (223 loc) · 8.17 KB
/
pod_tracker.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
// SPDX-License-Identifier: Apache-2.0
package kubernetes
import (
"context"
"fmt"
"sync"
"time"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
kubeinformers "k8s.io/client-go/informers"
informers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
)
// containerTracker contains useful signals that are managed by the podTracker.
type containerTracker struct {
// Name is the name of the container
Name string
// terminatedOnce ensures that the Terminated channel only gets closed once.
terminatedOnce sync.Once
// Terminated will be closed once the container reaches a terminal state.
Terminated chan struct{}
// TODO: collect streaming logs here before TailContainer is called
}
// podTracker contains Informers used to watch and synchronize local k8s caches.
// This is similar to a typical Kubernetes controller (eg like k8s.io/sample-controller.Controller).
type podTracker struct {
// https://pkg.go.dev/github.com/sirupsen/logrus#Entry
Logger *logrus.Entry
// TrackedPod is the Namespace/Name of the tracked pod
TrackedPod string
// informerFactory is used to create Informers and Listers
informerFactory kubeinformers.SharedInformerFactory
// informerDone is a function used to stop the informerFactory
informerDone context.CancelFunc
// podInformer watches the given pod, caches the results, and makes them available in podLister
podInformer informers.PodInformer
// PodLister helps list Pods. All objects returned here must be treated as read-only.
PodLister listers.PodLister
// PodSynced is a function that can be used to determine if an informer has synced.
// This is useful for determining if caches have synced.
PodSynced cache.InformerSynced
// Containers maps the container name to a containerTracker
Containers map[string]*containerTracker
// Ready signals when the PodTracker is done with setup and ready to Start.
Ready chan struct{}
}
// HandlePodAdd is an AddFunc for cache.ResourceEventHandlerFuncs for Pods.
func (p *podTracker) HandlePodAdd(newObj interface{}) {
newPod := p.getTrackedPod(newObj)
if newPod == nil {
// not valid or not our tracked pod
return
}
p.Logger.Tracef("handling pod add event for %s", p.TrackedPod)
p.inspectContainerStatuses(newPod)
}
// HandlePodUpdate is an UpdateFunc for cache.ResourceEventHandlerFuncs for Pods.
func (p *podTracker) HandlePodUpdate(oldObj, newObj interface{}) {
oldPod := p.getTrackedPod(oldObj)
newPod := p.getTrackedPod(newObj)
if oldPod == nil || newPod == nil {
// not valid or not our tracked pod
return
}
// if we need to optimize and avoid the resync update events, we can do this:
//if newPod.ResourceVersion == oldPod.ResourceVersion {
// // Periodic resync will send update events for all known Pods
// // If ResourceVersion is the same we have to look harder for Status changes
// if newPod.Status.Phase == oldPod.Status.Phase && newPod.Status.Size() == oldPod.Status.Size() {
// return
// }
//}
p.Logger.Tracef("handling pod update event for %s", p.TrackedPod)
p.inspectContainerStatuses(newPod)
}
// HandlePodDelete is an DeleteFunc for cache.ResourceEventHandlerFuncs for Pods.
func (p *podTracker) HandlePodDelete(oldObj interface{}) {
oldPod := p.getTrackedPod(oldObj)
if oldPod == nil {
// not valid or not our tracked pod
return
}
p.Logger.Tracef("handling pod delete event for %s", p.TrackedPod)
p.inspectContainerStatuses(oldPod)
}
// getTrackedPod tries to convert the obj into a Pod and makes sure it is the tracked Pod.
// This should only be used by the funcs of cache.ResourceEventHandlerFuncs.
func (p *podTracker) getTrackedPod(obj interface{}) *v1.Pod {
var (
pod *v1.Pod
ok bool
)
if pod, ok = obj.(*v1.Pod); !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
p.Logger.Errorf("error decoding pod, invalid type")
return nil
}
pod, ok = tombstone.Obj.(*v1.Pod)
if !ok {
p.Logger.Errorf("error decoding pod tombstone, invalid type")
return nil
}
}
trackedPod := pod.GetNamespace() + "/" + pod.GetName()
if trackedPod != p.TrackedPod {
p.Logger.Errorf("error got unexpected pod: %s", trackedPod)
return nil
}
return pod
}
// Start kicks off the API calls to start populating the cache.
// There is no need to run this in a separate goroutine (ie go podTracker.Start(ctx)).
func (p *podTracker) Start(ctx context.Context) {
p.Logger.Tracef("starting PodTracker for pod %s", p.TrackedPod)
informerCtx, done := context.WithCancel(ctx)
p.informerDone = done
// Start method is non-blocking and runs all registered informers in a dedicated goroutine.
p.informerFactory.Start(informerCtx.Done())
}
// Stop shuts down any informers (e.g. stop watching APIs).
func (p *podTracker) Stop() {
p.Logger.Tracef("stopping PodTracker for pod %s", p.TrackedPod)
if p.informerDone != nil {
p.informerDone()
}
}
// TrackContainers creates a containerTracker for each container.
func (p *podTracker) TrackContainers(containers []v1.Container) {
p.Logger.Tracef("tracking %d more containers for pod %s", len(containers), p.TrackedPod)
if p.Containers == nil {
p.Containers = map[string]*containerTracker{}
}
for _, ctn := range containers {
p.Containers[ctn.Name] = &containerTracker{
Name: ctn.Name,
Terminated: make(chan struct{}),
}
}
}
// newPodTracker initializes a podTracker with a given clientset for a given pod.
func newPodTracker(log *logrus.Entry, clientset kubernetes.Interface, pod *v1.Pod, defaultResync time.Duration) (*podTracker, error) {
if pod == nil {
return nil, fmt.Errorf("newPodTracker expected a pod, got nil")
}
trackedPod := pod.ObjectMeta.Namespace + "/" + pod.ObjectMeta.Name
if pod.ObjectMeta.Name == "" || pod.ObjectMeta.Namespace == "" {
return nil, fmt.Errorf("newPodTracker expects pod to have Name and Namespace, got %s", trackedPod)
}
log.Tracef("creating PodTracker for pod %s", trackedPod)
// create label selector for watching the pod
selector, err := labels.NewRequirement(
"pipeline",
selection.Equals,
[]string{fields.EscapeValue(pod.ObjectMeta.Name)},
)
if err != nil {
return nil, err
}
// create filtered Informer factory which is commonly used for k8s controllers
informerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(
clientset,
defaultResync,
kubeinformers.WithNamespace(pod.ObjectMeta.Namespace),
kubeinformers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = selector.String()
}),
)
podInformer := informerFactory.Core().V1().Pods()
// initialize podTracker
tracker := podTracker{
Logger: log,
TrackedPod: trackedPod,
informerFactory: informerFactory,
podInformer: podInformer,
PodLister: podInformer.Lister(),
PodSynced: podInformer.Informer().HasSynced,
Ready: make(chan struct{}),
}
// register event handler funcs in podInformer
podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: tracker.HandlePodAdd,
UpdateFunc: tracker.HandlePodUpdate,
DeleteFunc: tracker.HandlePodDelete,
})
return &tracker, nil
}
// mockPodTracker returns a new podTracker with the given pod pre-loaded in the cache.
func mockPodTracker(log *logrus.Entry, clientset kubernetes.Interface, pod *v1.Pod) (*podTracker, error) {
// Make sure test pods are valid before passing to PodTracker (ie support &v1.Pod{}).
if pod.ObjectMeta.Name == "" {
pod.ObjectMeta.Name = "test-pod"
}
if pod.ObjectMeta.Namespace == "" {
pod.ObjectMeta.Namespace = "test"
}
tracker, err := newPodTracker(log, clientset, pod, 0*time.Second)
if err != nil {
return nil, err
}
err = tracker.setupMockFor(pod)
if err != nil {
return nil, err
}
return tracker, err
}
// setupMockFor initializes the podTracker's internal caches with the given pod.
func (p *podTracker) setupMockFor(pod *v1.Pod) error {
// init containerTrackers as well
p.TrackContainers(pod.Spec.Containers)
// pre-populate the podInformer cache
err := p.podInformer.Informer().GetIndexer().Add(pod)
if err != nil {
return err
}
return nil
}