-
Notifications
You must be signed in to change notification settings - Fork 17
/
controller.go
286 lines (251 loc) · 7 KB
/
controller.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
package main
import (
"context"
"fmt"
"sync"
"time"
"k8s.io/client-go/kubernetes"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/tools/cache"
)
type ControllerOptions struct {
Namespaces []string
InclusionMatcher Matcher
ExclusionMatcher Matcher
SinceStart bool
Since *time.Time
}
type (
ContainerEnterFunc func(pod *v1.Pod, container *v1.Container, initialAddPhase bool) bool
ContainerExitFunc func(pod *v1.Pod, container *v1.Container)
ContainerErrorFunc func(pod *v1.Pod, container *v1.Container, err error)
)
type Callbacks struct {
OnEvent LogEventFunc
OnEnter ContainerEnterFunc
OnExit ContainerExitFunc
OnError ContainerErrorFunc
OnNothingDiscovered func()
}
type Controller struct {
ControllerOptions
client kubernetes.Interface
tailers map[string]*ContainerTailer
callbacks Callbacks
sync.Mutex
}
func NewController(client kubernetes.Interface, options ControllerOptions, callbacks Callbacks) *Controller {
return &Controller{
ControllerOptions: options,
client: client,
tailers: map[string]*ContainerTailer{},
callbacks: callbacks,
}
}
func (ctl *Controller) Run(ctx context.Context) error {
stopCh := make(chan struct{})
defer close(stopCh)
discoveredAny := false
for _, ns := range ctl.Namespaces {
podListWatcher := cache.NewListWatchFromClient(
ctl.client.CoreV1().RESTClient(), "pods", ns, fields.Everything())
obj, err := podListWatcher.List(metav1.ListOptions{})
if err != nil {
return fmt.Errorf("listing pods in %q: %w", ns, err)
}
switch t := obj.(type) {
case *v1.PodList:
for _, pod := range t.Items {
if ctl.onInitialAdd(&pod) {
discoveredAny = true
}
}
case *internalversion.List:
for _, item := range t.Items {
if pod, ok := item.(*v1.Pod); ok {
if ctl.onInitialAdd(pod) {
discoveredAny = true
}
}
}
default:
panic(fmt.Sprintf("unexpected return type %T when listing pods", obj))
}
_, informer := cache.NewIndexerInformer(
podListWatcher, &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
if pod, ok := obj.(*v1.Pod); ok {
ctl.onAdd(pod)
}
},
UpdateFunc: func(old interface{}, new interface{}) {
if pod, ok := new.(*v1.Pod); ok {
ctl.onUpdate(pod)
}
},
DeleteFunc: func(obj interface{}) {
if pod, ok := obj.(*v1.Pod); ok {
ctl.onDelete(pod)
}
},
}, cache.Indexers{})
go informer.Run(stopCh)
}
if !discoveredAny {
ctl.callbacks.OnNothingDiscovered()
}
<-ctx.Done()
return ctx.Err()
}
func (ctl *Controller) onInitialAdd(pod *v1.Pod) bool {
added := false
for _, container := range pod.Spec.InitContainers {
if ctl.shouldIncludeContainer(pod, &container) {
ctl.addContainer(pod, &container, true)
added = true
}
}
for _, container := range pod.Spec.Containers {
if ctl.shouldIncludeContainer(pod, &container) {
ctl.addContainer(pod, &container, true)
added = true
}
}
return added
}
func (ctl *Controller) onAdd(pod *v1.Pod) {
for _, container := range pod.Spec.InitContainers {
if ctl.shouldIncludeContainer(pod, &container) {
ctl.addContainer(pod, &container, false)
}
}
for _, container := range pod.Spec.Containers {
if ctl.shouldIncludeContainer(pod, &container) {
ctl.addContainer(pod, &container, false)
}
}
}
func (ctl *Controller) onUpdate(pod *v1.Pod) {
containers := pod.Spec.Containers
containerStatuses := allContainerStatusesForPod(pod)
for _, containerStatus := range containerStatuses {
var container *v1.Container
for i, c := range containers {
if c.Name == containerStatus.Name {
container = &containers[i]
break
}
}
if container == nil {
// Should be impossible; means there's a status for a container that isn't
// part of the spec
continue
}
if ctl.shouldIncludeContainer(pod, container) {
ctl.addContainer(pod, container, false)
} else {
ctl.deleteContainer(pod, container)
}
}
}
func (ctl *Controller) onDelete(pod *v1.Pod) {
for _, container := range pod.Spec.Containers {
ctl.deleteContainer(pod, &container)
}
}
func (ctl *Controller) shouldIncludeContainer(pod *v1.Pod, container *v1.Container) bool {
if !(pod.Status.Phase == v1.PodRunning || pod.Status.Phase == v1.PodPending) {
return false
}
running := false
for _, s := range allContainerStatusesForPod(pod) {
if s.Name == container.Name && (s.State.Waiting != nil || s.State.Terminated != nil ||
s.State.Running != nil) {
running = true
break
}
}
if !running {
return false
}
if ctl.ExclusionMatcher.Match(pod) {
return false
}
if !(ctl.InclusionMatcher.Match(pod) || ctl.InclusionMatcher.Match(container)) {
return false
}
return !ctl.ExclusionMatcher.Match(container)
}
func (ctl *Controller) addContainer(pod *v1.Pod, container *v1.Container, initialAdd bool) {
ctl.Lock()
defer ctl.Unlock()
key := buildKey(pod, container)
if _, ok := ctl.tailers[key]; ok {
return
}
if !ctl.callbacks.OnEnter(pod, container, initialAdd) {
return
}
fromTimestamp, ok := ctl.getStartTimestamp(pod, container, initialAdd)
if !ok {
return
}
targetPod, targetContainer := *pod, *container // Copy to avoid mutation
tailer := NewContainerTailer(ctl.client, targetPod, targetContainer,
ctl.callbacks.OnEvent, fromTimestamp)
ctl.tailers[key] = tailer
go func() {
tailer.Run(context.Background(), func(err error) {
ctl.callbacks.OnError(&targetPod, &targetContainer, err)
})
}()
}
func (ctl *Controller) deleteContainer(pod *v1.Pod, container *v1.Container) {
ctl.Lock()
defer ctl.Unlock()
key := buildKey(pod, container)
if tailer, ok := ctl.tailers[key]; ok {
delete(ctl.tailers, key)
tailer.Stop()
ctl.callbacks.OnExit(pod, container)
}
}
func (ctl *Controller) getStartTimestamp(pod *v1.Pod, container *v1.Container, initialAdd bool) (*time.Time, bool) {
switch {
case ctl.SinceStart:
return nil, true
case ctl.Since != nil:
return ctl.Since, true
case initialAdd:
// Don't show any history, but add a small amount of buffer to
// account for clock skew
now := time.Now().Add(time.Second * -5)
return &now, true
default:
var t *time.Time
for _, status := range allContainerStatusesForPod(pod) {
if status.Name == container.Name && status.State.Running != nil {
startTime := status.State.Running.StartedAt.Time
if t == nil || startTime.Before(*t) {
t = &startTime
}
}
}
if t == nil {
return nil, false
}
return t, true
}
}
func buildKey(pod *v1.Pod, container *v1.Container) string {
return fmt.Sprintf("%s/%s/%s", pod.Namespace, pod.Name, container.Name)
}
func allContainerStatusesForPod(pod *v1.Pod) []v1.ContainerStatus {
statuses := make([]v1.ContainerStatus, len(pod.Status.ContainerStatuses)+len(pod.Status.InitContainerStatuses))
return append(
append(statuses, pod.Status.InitContainerStatuses...),
pod.Status.ContainerStatuses...)
}