-
Notifications
You must be signed in to change notification settings - Fork 0
/
namespace.go
459 lines (369 loc) · 12.6 KB
/
namespace.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
package watcher
import (
"context"
"errors"
"fmt"
"sync"
"time"
mc "github.com/massix/chaos-monkey/internal/apis/clientset/versioned"
"github.com/massix/chaos-monkey/internal/configuration"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/record"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
type NamespaceWatcher struct {
typedcorev1.NamespaceInterface
record.EventRecorderLogger
Logrus logrus.FieldLogger
Client kubernetes.Interface
CmcClient mc.Interface
MetricsClient metricsv.Interface
Mutex *sync.Mutex
CrdWatchers map[string]Watcher
metrics *nwMetrics
RootNamespace string
Behavior configuration.Behavior
CleanupTimeout time.Duration
WatcherTimeout time.Duration
Running bool
}
// Close implements Watcher.
func (n *NamespaceWatcher) Close() error {
n.metrics.unregister()
return nil
}
// Metrics for the NamespaceWatcher component
type nwMetrics struct {
// Total number of events handled
addedEvents prometheus.Counter
modifiedEvents prometheus.Counter
deletedEvents prometheus.Counter
// Total number of restarts handled
restarts prometheus.Counter
// Total number of CMCs spawned
cmcSpawned prometheus.Counter
// Total number of *active* CMCs
cmcActive prometheus.Gauge
// How long it took to handle an event
eventDuration prometheus.Histogram
}
func (nw *nwMetrics) unregister() {
prometheus.Unregister(nw.addedEvents)
prometheus.Unregister(nw.modifiedEvents)
prometheus.Unregister(nw.deletedEvents)
prometheus.Unregister(nw.restarts)
prometheus.Unregister(nw.cmcSpawned)
prometheus.Unregister(nw.cmcActive)
prometheus.Unregister(nw.eventDuration)
}
var _ = (Watcher)((*NamespaceWatcher)(nil))
func newNwMetrics(rootNamespace, behavior string) *nwMetrics {
return &nwMetrics{
addedEvents: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "chaos_monkey",
Name: "events",
Subsystem: "nswatcher",
Help: "Total number of events handled",
ConstLabels: map[string]string{"event_type": "add", "root_namespace": rootNamespace, "behavior": behavior},
}),
modifiedEvents: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "chaos_monkey",
Name: "events",
Subsystem: "nswatcher",
Help: "Total number of events handled",
ConstLabels: map[string]string{"event_type": "modify", "root_namespace": rootNamespace, "behavior": behavior},
}),
deletedEvents: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "chaos_monkey",
Name: "events",
Subsystem: "nswatcher",
Help: "Total number of events handled",
ConstLabels: map[string]string{"event_type": "delete", "root_namespace": rootNamespace, "behavior": behavior},
}),
restarts: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "chaos_monkey",
Name: "restarts",
Subsystem: "nswatcher",
Help: "Total number of restarts handled",
ConstLabels: map[string]string{"root_namespace": rootNamespace, "behavior": behavior},
}),
cmcSpawned: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "chaos_monkey",
Name: "cmc_spawned",
Subsystem: "nswatcher",
Help: "Total number of CMCs spawned",
ConstLabels: map[string]string{"root_namespace": rootNamespace, "behavior": behavior},
}),
cmcActive: promauto.NewGauge(prometheus.GaugeOpts{
Namespace: "chaos_monkey",
Name: "cmc_active",
Subsystem: "nswatcher",
Help: "Current active CMC Watchers",
ConstLabels: map[string]string{"root_namespace": rootNamespace, "behavior": behavior},
}),
eventDuration: promauto.NewHistogram(prometheus.HistogramOpts{
Namespace: "chaos_monkey",
Name: "event_duration",
Subsystem: "nswatcher",
Help: "How long it took to handle an event (calculated in microseconds)",
ConstLabels: map[string]string{"root_namespace": rootNamespace, "behavior": behavior},
Buckets: []float64{0, 5, 10, 20, 50, 100, 500, 1000, 1500, 2000},
}),
}
}
func NewNamespaceWatcher(clientset kubernetes.Interface, cmcClientset mc.Interface, metricsClient metricsv.Interface, recorder record.EventRecorderLogger, rootNamespace string, behavior configuration.Behavior) *NamespaceWatcher {
logrus.Infof("Creating new namespace watcher for namespace %s", rootNamespace)
if clientset == nil {
panic("Clientset cannot be nil")
}
// Build my own recorder
if recorder == nil {
broadcaster := record.NewBroadcaster()
broadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: clientset.CoreV1().Events("")})
recorder = broadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "chaos-monkey"})
}
conf := configuration.FromEnvironment()
return &NamespaceWatcher{
NamespaceInterface: clientset.CoreV1().Namespaces(),
EventRecorderLogger: recorder,
Logrus: logrus.WithFields(logrus.Fields{"component": "NamespaceWatcher", "rootNamespace": rootNamespace}),
CrdWatchers: map[string]Watcher{},
Mutex: &sync.Mutex{},
metrics: newNwMetrics(rootNamespace, string(behavior)),
CleanupTimeout: 1 * time.Minute,
RootNamespace: rootNamespace,
Behavior: behavior,
Running: false,
Client: clientset,
CmcClient: cmcClientset,
MetricsClient: metricsClient,
WatcherTimeout: conf.Timeouts.Namespace,
}
}
// IsRunning implements Watcher.
func (n *NamespaceWatcher) IsRunning() bool {
n.Mutex.Lock()
defer n.Mutex.Unlock()
return n.Running
}
func (n *NamespaceWatcher) IsNamespaceAllowed(namespace *corev1.Namespace) bool {
label, ok := namespace.ObjectMeta.Labels[configuration.NamespaceLabel]
// We allow all and there is no label
if n.Behavior == configuration.BehaviorAllowAll && !ok {
return true
}
// We deny all and there is no label
if n.Behavior == configuration.BehaviorDenyAll && !ok {
return false
}
// We deny all by default, the label is a whitelist (only if its value is "true")
if n.Behavior == configuration.BehaviorDenyAll {
return label == "true"
}
// We allow all by default, everything will let it through, except for "false"
if n.Behavior == configuration.BehaviorAllowAll {
return label != "false"
}
// We should never arrive here
return false
}
// Start implements Watcher.
func (n *NamespaceWatcher) Start(ctx context.Context) error {
var err error
var wg sync.WaitGroup
defer n.Close()
n.Logrus.Infof("Starting watcher, timeout: %s, behavior: %s", n.WatcherTimeout, n.Behavior)
timeoutSeconds := int64(n.WatcherTimeout.Seconds())
w, err := n.Watch(ctx, v1.ListOptions{
Watch: true,
TimeoutSeconds: &timeoutSeconds,
})
if err != nil {
return err
}
defer w.Stop()
n.setRunning(true)
for n.IsRunning() {
select {
case evt, ok := <-w.ResultChan():
if !ok {
n.Logrus.Warn("Watcher chan closed, resetting everything")
w, err = n.restartWatch(ctx, &wg)
if err != nil {
n.Logrus.Errorf("Error while restarting watcher: %s", err)
_ = n.Stop()
}
n.metrics.restarts.Inc()
// Reset the number of active CMCs
n.metrics.cmcActive.Set(0)
break
}
requestStart := time.Now().UnixMicro()
ns := evt.Object.(*corev1.Namespace)
switch evt.Type {
case "", watch.Error:
n.Logrus.Errorf("Received empty event or error from watcher: %+v", evt)
err = errors.New("Empty event or error from namespace watcher")
_ = n.Stop()
case watch.Added:
if !n.IsNamespaceAllowed(ns) {
logrus.Infof("Not creating watcher for %s", ns.Name)
continue
}
n.Logrus.Infof("Adding watcher for namespace %s", ns.Name)
if err := n.addWatcher(ns.Name); err != nil {
logrus.Errorf("Error while trying to add CRD watcher: %s", err)
continue
}
n.Logrus.Debug("All is good! Sending event.")
n.startCrdWatcher(ctx, ns.Name, &wg)
n.Eventf(ns, "Normal", "Added", "CRD Watcher added for %s", ns.Name)
n.metrics.addedEvents.Inc()
case watch.Modified:
n.Logrus.Infof("Eventually modifying watcher for %s", ns.Name)
if n.IsNamespaceAllowed(ns) {
if err := n.addWatcher(ns.Name); err != nil {
n.Logrus.Warnf("Error while trying to add CRD watcher: %s", err)
} else {
n.Logrus.Infof("Starting newly created watcher for %s", ns.Name)
n.startCrdWatcher(ctx, ns.Name, &wg)
}
} else {
if err := n.removeWatcher(ns.Name); err != nil {
n.Logrus.Warnf("Error while trying to remove CRD watcher: %s", err)
}
}
n.metrics.modifiedEvents.Inc()
case watch.Deleted:
n.Logrus.Infof("Deleting watcher for namespace %s", ns.Name)
if err := n.removeWatcher(ns.Name); err != nil {
n.Logrus.Warnf("Error while trying to remove CRD watcher: %s", err)
}
n.Logrus.Debug("All is good! Sending event.")
n.metrics.deletedEvents.Inc()
n.Eventf(ns, "Normal", "Deleted", "CRD Watcher deleted for %s", ns.Name)
}
requestEnd := time.Now().UnixMicro()
n.metrics.eventDuration.Observe(float64(requestEnd - requestStart))
case <-ctx.Done():
n.Logrus.Info("Context cancelled")
_ = n.Stop()
case <-time.After(n.CleanupTimeout):
n.Logrus.Debug("Cleaning up...")
n.cleanUp()
}
}
n.Logrus.Info("Namespace watcher stopped, cleaning up...")
n.Mutex.Lock()
for ns, crd := range n.CrdWatchers {
n.Logrus.Infof("Stopping watcher for namespace %s", ns)
if err := crd.Stop(); err != nil {
n.Logrus.Warnf("Error while trying to stop CRD watcher: %s", err)
}
delete(n.CrdWatchers, ns)
}
n.Mutex.Unlock()
n.Logrus.Info("Waiting for all CRD Watchers to finish")
wg.Wait()
n.Logrus.Debug("Unregistering Prometheus metrics")
return err
}
// Stop implements Watcher.
func (n *NamespaceWatcher) Stop() error {
n.Mutex.Lock()
defer n.Mutex.Unlock()
n.Logrus.Debugf("Stopping namespace watcher for %s", n.RootNamespace)
n.Running = false
return nil
}
// Internal methods
func (n *NamespaceWatcher) addWatcher(namespace string) error {
n.Mutex.Lock()
defer n.Mutex.Unlock()
if _, ok := n.CrdWatchers[namespace]; ok {
return fmt.Errorf("Watcher for namespace %s already exists", namespace)
}
n.CrdWatchers[namespace] = DefaultCrdFactory(n.Client, n.CmcClient, n.MetricsClient, nil, namespace)
return nil
}
func (n *NamespaceWatcher) removeWatcher(namespace string) error {
n.Mutex.Lock()
defer n.Mutex.Unlock()
var err error
if w, ok := n.CrdWatchers[namespace]; ok {
err = w.Stop()
delete(n.CrdWatchers, namespace)
n.metrics.cmcActive.Dec()
} else {
err = fmt.Errorf("Watcher for namespace %s does not exist", namespace)
}
return err
}
func (n *NamespaceWatcher) cleanUp() {
n.Mutex.Lock()
defer n.Mutex.Unlock()
for ns, w := range n.CrdWatchers {
if !w.IsRunning() {
n.Logrus.Infof("Cleaning up watcher for namespace %s", ns)
if err := w.Stop(); err != nil {
n.Logrus.Warnf("Error while trying to remove CRD watcher: %s", err)
}
delete(n.CrdWatchers, ns)
}
}
}
func (n *NamespaceWatcher) setRunning(v bool) {
n.Mutex.Lock()
defer n.Mutex.Unlock()
n.Running = v
}
func (n *NamespaceWatcher) startCrdWatcher(ctx context.Context, namespace string, wg *sync.WaitGroup) {
n.Mutex.Lock()
defer n.Mutex.Unlock()
wg.Add(1)
watcher := n.CrdWatchers[namespace]
go func() {
defer wg.Done()
n.Logrus.Debugf("Starting CRD Watcher for namespace %s", namespace)
if watcher == nil {
n.Logrus.Warnf("No watcher found for namespace %s", namespace)
return
}
if err := watcher.Start(ctx); err != nil {
n.Logrus.Errorf("Error while starting CRD Watcher for namespace %s", namespace)
}
}()
n.metrics.cmcActive.Inc()
n.metrics.cmcSpawned.Inc()
}
func (n *NamespaceWatcher) restartWatch(ctx context.Context, wg *sync.WaitGroup) (watch.Interface, error) {
n.Mutex.Lock()
defer n.Mutex.Unlock()
n.Logrus.Info("Preparing for restart: cleaning all the CRD Watchers")
// Stop all the running watches
for k, w := range n.CrdWatchers {
n.Logrus.Debugf("Cleaning %s", k)
if err := w.Stop(); err != nil {
logrus.Warnf("Error while stopping CRD Watcher for %s: %s", k, err)
}
delete(n.CrdWatchers, k)
}
// Wait for all the CRD Watchers to be stopped
n.Logrus.Info("Waiting for all CRD Watchers to finish...")
wg.Wait()
n.Logrus.Infof("Restarting watcher with timeout: %s", n.WatcherTimeout)
// Now recreate a new watch interface
timeoutSeconds := int64(n.WatcherTimeout.Seconds())
return n.Watch(ctx, v1.ListOptions{
Watch: true,
TimeoutSeconds: &timeoutSeconds,
})
}