-
Notifications
You must be signed in to change notification settings - Fork 1
/
operator.go
524 lines (477 loc) · 14.8 KB
/
operator.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
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
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/cashapp/transflect/pkg/transflect"
"github.com/google/uuid"
"github.com/jpillora/backoff"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
istionet "istio.io/client-go/pkg/apis/networking/v1alpha3"
istio "istio.io/client-go/pkg/clientset/versioned/typed/networking/v1alpha3"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
informerv1 "k8s.io/client-go/informers/apps/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/util/homedir"
"k8s.io/client-go/util/workqueue"
)
const (
deploymentAnnotation = "transflect.cash.squareup.com/deployment"
excludeAnnotation = "transflect.cash.squareup.com/exclude-grpc-services"
httpPrefixAnnotation = "transflect.cash.squareup.com/http-path-prefix"
includeAnnotation = "transflect.cash.squareup.com/include-grpc-services"
portAnnotation = "transflect.cash.squareup.com/port"
replicasetAnnotation = "transflect.cash.squareup.com/replicaset"
versionAnnotation = "transflect.cash.squareup.com/version"
)
type operator struct {
k8s *kubernetes.Clientset
istio *istio.NetworkingV1alpha3Client
rsInformer informerv1.ReplicaSetInformer
deployInformer informerv1.DeploymentInformer
queue workqueue.RateLimitingInterface
stopper chan struct{}
stopLock sync.Mutex
wg sync.WaitGroup
// activeState records the deployment revision and its grpc port
// for which an EnvoyFilter has been created. The port is required
// to update the EnvoyFilter on port annotation change.
//
// activeState[deploymentKey] = { revision, grpcPort, /* other annotations */ }
activeState sync.Map
// deploymentLocker synchronises operations on a deployment
// so that no two updates for a single deployment can run concurrently.
deploymentLocker transflect.MutexMap
useIngress bool
plaintext bool
address string
version string
leaseNamespace string
leaseID string
httpPathPrefix string
}
type activeEntry struct {
revision int
// Annotations
grpcPort uint32
excludeServices string
includeServices string
httpPathPrefix string
}
func newOperator(cfg *config) (*operator, error) {
k8s, istio, err := getClientSets()
if err != nil {
return nil, err
}
leaseID := cfg.LeaseID
if leaseID == "" {
leaseID = uuid.New().String()
}
op := &operator{
k8s: k8s,
istio: istio,
useIngress: cfg.UseIngress,
plaintext: cfg.Plaintext,
address: cfg.Address,
version: "transflect-" + version,
leaseNamespace: cfg.LeaseNamespace,
leaseID: leaseID,
httpPathPrefix: cfg.HTTPPathPrefix,
}
return op, nil
}
// start is concerned with setting up leader-election. If the current
// process is chosen as leader, the main operator work is kicked off in
// startLeading.
func (o *operator) start(ctx context.Context) error {
// Run leader election
var err error
ctx, cancel := context.WithCancel(ctx)
callbacks := leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
log.Debug().Str("leaderID", o.leaseID).Msg("Starting to lead")
leaderGauge.Set(1)
if err = o.startLeading(ctx); err != nil { // kick off operator
// stop the operator before we release the lease lock
// with `cancel()` so two operators are not running at
// the same time.
o.stop()
cancel()
}
},
OnStoppedLeading: func() {
log.Debug().Str("leaderID", o.leaseID).Msg("Stop leading")
leaderGauge.Set(0)
o.stop()
},
OnNewLeader: func(newID string) {
log.Debug().Str("leaderID", o.leaseID).Str("newLeaderID", newID).Msg("New leader elected")
},
}
lock := o.newLock(o.leaseID)
leaderelection.RunOrDie(ctx, newElection(lock, callbacks))
return err
}
func (o *operator) startLeading(ctx context.Context) error {
o.stopper = make(chan struct{})
// Initialise activeState for existing transflect EnvoyFilters
// to determine if EnvoyFilter upsert should be processed.
if err := o.syncActive(ctx); err != nil {
return fmt.Errorf("cannot start operator: %w", err)
}
// Initialise informers and queue
informerFactory := informers.NewSharedInformerFactory(o.k8s, time.Second*30)
o.rsInformer = informerFactory.Apps().V1().ReplicaSets()
if err := o.rsInformer.Informer().SetWatchErrorHandler(watchErrorHandler); err != nil {
return errors.Wrap(err, "cannot add custom error handler to replicaset informer")
}
o.rsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: o.enqueue,
UpdateFunc: o.enqueueWithOld,
})
o.deployInformer = informerFactory.Apps().V1().Deployments()
if err := o.deployInformer.Informer().SetWatchErrorHandler(watchErrorHandler); err != nil {
return errors.Wrap(err, "cannot add custom error handler to deployment informer")
}
o.deployInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
DeleteFunc: o.cleanupDeployment,
})
o.queue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "replicasets")
log.Debug().Msg("Start leading: informer event handlers registered")
// Run workers and informers
o.runWorkers(ctx, 42)
go o.rsInformer.Informer().Run(o.stopper)
go o.deployInformer.Informer().Run(o.stopper)
<-o.stopper
// When run finishes e.g. because of signal calling o.stop():
log.Debug().Msg("Shutting down queue")
o.queue.ShutDown()
return nil
}
func (o *operator) enqueue(v interface{}) {
rs, ok := v.(*appsv1.ReplicaSet)
if !ok {
log.Error().Interface("object", v).Msg("Cannot convert object to Replicaset for enqueueing")
return
}
if !shouldEnqueue(rs) {
return
}
key, _ := cache.MetaNamespaceKeyFunc(rs)
o.queue.Add(key)
}
func (o *operator) enqueueWithOld(_, v interface{}) {
o.enqueue(v)
}
func shouldEnqueue(rs *appsv1.ReplicaSet) bool {
if rs.Status.ReadyReplicas == 0 {
return false
}
if _, ok := getDeploymentKey(rs); !ok {
log.Debug().Str("replica", rs.Name).Msg("Replicaset does not have deployment owner")
return false
}
return true
}
func (o *operator) runWorkers(ctx context.Context, cnt int) {
for i := 0; i < cnt; i++ {
o.wg.Add(1)
go o.runWorker(ctx)
}
}
func (o *operator) runWorker(ctx context.Context) {
for o.next(ctx) { // process next enqueued Replicaset
}
o.wg.Done()
}
func (o *operator) stop() {
o.stopLock.Lock()
defer o.stopLock.Unlock()
select {
case <-o.stopper:
return // stopper is already closed
default:
}
if o.stopper != nil {
close(o.stopper)
}
o.wg.Wait()
log.Debug().Msg("All workers have finished")
}
func (o *operator) next(ctx context.Context) bool {
key, shutdown := o.queue.Get()
if shutdown {
return false
}
defer o.queue.Done(key)
rsName, ok := key.(string)
if !ok {
log.Error().Interface("key", key).Msg("Invalid key type, expected string")
preprocessErrCounter.Inc()
return true
}
rs, err := o.getReplicaset(rsName)
if err != nil {
log.Error().Err(err).Msg("Cannot get next queued Replicaset")
preprocessErrCounter.Inc()
return true
}
deployKey, _ := getDeploymentKey(rs)
o.deploymentLocker.Lock(deployKey)
defer o.deploymentLocker.Unlock(deployKey)
if !o.shouldProcessReplicaset(rs, deployKey) {
ignoredCounter.Inc()
return true
}
if err := o.processReplicaset(ctx, rs, deployKey); err != nil {
log.Error().Err(err).Str("replica", rs.Name).Msg("Cannot process EnvoyFilter for Replicaset")
}
return true
}
func (o *operator) shouldProcessReplicaset(rs *appsv1.ReplicaSet, deployKey string) bool {
if rs.Status.ReadyReplicas == 0 {
return false
}
port := grpcPort(rs)
v, existing := o.activeState.Load(deployKey)
if existing { // EnvoyFilter for given deployment exists
active, _ := v.(activeEntry)
// Ignore candidate if we have an existing filter but the candidate is
// old or has not changed the port.
revision := deployRevision(rs)
if revision == 0 {
log.Error().Str("replica", rs.Name).Msg("Cannot get revision annotation for candidate evaluation")
return false
}
if revision < active.revision {
return false
}
// Potential race condition if not performed under deployment
// lock and port is changed several times in a short period of time.
if active == newActiveEntry(rs) {
return false
}
}
if !existing && port == 0 {
// No existing record, so nothing to do if not annotated
return false
}
// Upsert or delete EnvoyFilter for Replicaset
return true
}
func (o *operator) processReplicaset(ctx context.Context, rs *appsv1.ReplicaSet, deployKey string) error {
if grpcPort(rs) == 0 {
if err := o.deleteFilter(ctx, rs); err != nil {
processedCounter.WithLabelValues("error", "delete").Inc()
}
o.activeState.Delete(deployKey)
o.deploymentLocker.Remove(deployKey)
processedCounter.WithLabelValues("success", "delete").Inc()
return nil
}
if err := o.upsertFilter(ctx, rs); err != nil {
processedCounter.WithLabelValues("error", "upsert").Inc()
return err
}
active := newActiveEntry(rs)
o.activeState.Store(deployKey, active)
processedCounter.WithLabelValues("success", "upsert").Inc()
return nil
}
func grpcPort(rs *appsv1.ReplicaSet) uint32 {
return grpcPortStr(rs.Annotations[portAnnotation])
}
func grpcPortStr(s string) uint32 {
i, err := strconv.Atoi(s)
if err != nil || i < 0 || i > 65535 {
return 0
}
return uint32(i)
}
func deployRevision(rs *appsv1.ReplicaSet) int {
return deployRevisionStr(rs.Annotations["deployment.kubernetes.io/revision"])
}
func deployRevisionStr(s string) int {
i, err := strconv.Atoi(s)
if err != nil || i < 0 {
return 0
}
return i
}
func getDeploymentKey(rs *appsv1.ReplicaSet) (string, bool) {
d, ok := getDeployment(rs)
if !ok {
return "", false
}
if rs.Namespace == "" {
return d.Name, true
}
return rs.Namespace + "/" + d.Name, true
}
func getDeployment(rs *appsv1.ReplicaSet) (metav1.OwnerReference, bool) {
for _, owner := range rs.GetOwnerReferences() {
if owner.Kind == "Deployment" {
return owner, true
}
}
return metav1.OwnerReference{}, false
}
func (o *operator) getReplicaset(key string) (*appsv1.ReplicaSet, error) {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return nil, errors.Wrapf(err, "invalid key format")
}
rs, err := o.rsInformer.Lister().ReplicaSets(namespace).Get(name)
if err != nil {
return nil, errors.Wrapf(err, "cannot GET replicaset %s", name)
}
return rs, nil
}
func getClientSets() (*kubernetes.Clientset, *istio.NetworkingV1alpha3Client, error) {
cfg, err := getConfig()
if err != nil {
return nil, nil, errors.Wrap(err, "cannot get Kubernetes config")
}
k8s, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, nil, errors.Wrap(err, "cannot get Kubernetes ClientSet")
}
istioClient, err := istio.NewForConfig(cfg)
if err != nil {
return nil, nil, errors.Wrap(err, "cannot get Istio ClientSet")
}
return k8s, istioClient, nil
}
func getConfig() (*rest.Config, error) {
cfg, err := rest.InClusterConfig()
if err == nil {
return cfg, nil
}
if !errors.Is(err, rest.ErrNotInCluster) {
return nil, errors.Wrap(err, "cannot get kubeconfig")
}
// Not running in the cluster. Find KUBECONFIG
kc := os.Getenv("KUBECONFIG")
if kc == "" {
home := homedir.HomeDir()
if home == "" {
return nil, errors.New("cannot find kubeconfig. Set KUBECONFIG env var")
}
kc = filepath.Join(home, ".kube", "config")
}
kubeCfg, err := clientcmd.BuildConfigFromFlags("", kc)
if err != nil {
return nil, errors.Wrap(err, "cannot find kube config")
}
return kubeCfg, nil
}
func (o *operator) newLock(id string) *resourcelock.LeaseLock {
return &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: "transflect-leader",
Namespace: o.leaseNamespace,
},
Client: o.k8s.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: id,
},
}
}
func newElection(lock *resourcelock.LeaseLock, callbacks leaderelection.LeaderCallbacks) leaderelection.LeaderElectionConfig {
return leaderelection.LeaderElectionConfig{
Lock: lock,
ReleaseOnCancel: true,
LeaseDuration: 20 * time.Second,
RenewDeadline: 15 * time.Second,
RetryPeriod: 5 * time.Second,
Callbacks: callbacks,
}
}
func watchErrorHandler(_ *cache.Reflector, err error) {
log.Debug().Err(err).Msg("ListAndWatch dropped the connection with an error, back-off and retry")
}
func (o *operator) syncActive(ctx context.Context) error {
opts := metav1.ListOptions{
LabelSelector: "app=transflect",
Limit: 42,
}
activeCnt := 0
b := backoff.Backoff{Min: 2 * time.Second}
for {
list, err := o.istio.EnvoyFilters("").List(ctx, opts)
if err != nil {
if int(b.Attempt()) > 10 {
return fmt.Errorf("cannot list existing EnvoyFilters to sync active state, ran out of attempts")
}
time.Sleep(b.Duration())
continue
}
b.Reset()
for _, filter := range list.Items {
key, entry, err := getActiveEntry(filter)
if err != nil {
log.Error().Err(err).Str("envoyfilter", filter.Name).Msg("Cannot be synced")
continue
}
o.activeState.Store(key, entry)
activeCnt++
log.Debug().Str("deploymentKey", key).Int("revision", entry.revision).Uint32("port", entry.grpcPort).Msg("synced active state")
}
if opts.Continue == "" {
filtersGauge.Set(float64(activeCnt))
return nil
}
}
}
func getActiveEntry(filter istionet.EnvoyFilter) (string, activeEntry, error) {
a := filter.Annotations
key := a[deploymentAnnotation]
if key == "" {
return "", activeEntry{}, fmt.Errorf("cannot retrieve deployment key from existing EnvoyFilter")
}
port := grpcPortStr(filter.Annotations[portAnnotation])
if port == 0 {
return "", activeEntry{}, fmt.Errorf("cannot retrieve grpc port from existing EnvoyFilter")
}
revision := deployRevisionStr(filter.Annotations["deployment.kubernetes.io/revision"])
if revision == 0 {
return "", activeEntry{}, fmt.Errorf("cannot retrieve deployment revision from existing EnvoyFilter")
}
entry := activeEntry{grpcPort: port, revision: revision}
return key, entry, nil
}
func (o *operator) cleanupDeployment(v interface{}) {
d, ok := v.(*appsv1.Deployment)
if !ok {
log.Error().Interface("object", v).Msg("Cannot convert object to Deployment for cleanup")
return
}
key, err := cache.MetaNamespaceKeyFunc(d)
if err != nil {
log.Error().Err(err).Str("deployment", d.Name).Msg("Cannot create deployment Key, skip EnvoyFilter cleanup")
return
}
o.activeState.Delete(key)
o.deploymentLocker.Remove(key)
}
func newActiveEntry(rs *appsv1.ReplicaSet) activeEntry {
return activeEntry{
grpcPort: grpcPort(rs),
revision: deployRevision(rs),
excludeServices: rs.Annotations[excludeAnnotation],
includeServices: rs.Annotations[includeAnnotation],
httpPathPrefix: rs.Annotations[httpPrefixAnnotation],
}
}