This repository has been archived by the owner on Jun 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
brokercell.go
426 lines (382 loc) · 18.9 KB
/
brokercell.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
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package brokercell
import (
"context"
"fmt"
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap"
channellisters "github.com/google/knative-gcp/pkg/client/listers/messaging/v1beta1"
hpav2beta2 "k8s.io/api/autoscaling/v2beta2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
appsv1listers "k8s.io/client-go/listers/apps/v1"
hpav2beta2listers "k8s.io/client-go/listers/autoscaling/v2beta2"
corev1listers "k8s.io/client-go/listers/core/v1"
"knative.dev/pkg/network"
pkgreconciler "knative.dev/pkg/reconciler"
intv1alpha1 "github.com/google/knative-gcp/pkg/apis/intevents/v1alpha1"
bcreconciler "github.com/google/knative-gcp/pkg/client/injection/reconciler/intevents/v1alpha1/brokercell"
brokerlisters "github.com/google/knative-gcp/pkg/client/listers/broker/v1"
"github.com/google/knative-gcp/pkg/logging"
"github.com/google/knative-gcp/pkg/reconciler"
"github.com/google/knative-gcp/pkg/reconciler/brokercell/resources"
reconcilerutils "github.com/google/knative-gcp/pkg/reconciler/utils"
"github.com/google/knative-gcp/pkg/utils/authcheck"
)
type envConfig struct {
IngressImage string `envconfig:"INGRESS_IMAGE" required:"true"`
FanoutImage string `envconfig:"FANOUT_IMAGE" required:"true"`
RetryImage string `envconfig:"RETRY_IMAGE" required:"true"`
ServiceAccountName string `envconfig:"SERVICE_ACCOUNT" default:"broker"`
IngressPort int `envconfig:"INGRESS_PORT" default:"8080"`
MetricsPort int `envconfig:"METRICS_PORT" default:"9090"`
InternalMetricsEnabled bool `envconfig:"INTERNAL_METRICS_ENABLED" default:"false"`
}
type listers struct {
brokerLister brokerlisters.BrokerLister
channelLister channellisters.ChannelLister
hpaLister hpav2beta2listers.HorizontalPodAutoscalerLister
triggerLister brokerlisters.TriggerLister
configMapLister corev1listers.ConfigMapLister
secretLister corev1listers.SecretLister
serviceAccountLister corev1listers.ServiceAccountLister
serviceLister corev1listers.ServiceLister
endpointsLister corev1listers.EndpointsLister
deploymentLister appsv1listers.DeploymentLister
podLister corev1listers.PodLister
}
// NewReconciler creates a new BrokerCell reconciler.
func NewReconciler(base *reconciler.Base, ls listers) (*Reconciler, error) {
var env envConfig
if err := envconfig.Process("BROKER_CELL", &env); err != nil {
return nil, err
}
svcRec := &reconcilerutils.ServiceReconciler{
KubeClient: base.KubeClientSet,
ServiceLister: ls.serviceLister,
EndpointsLister: ls.endpointsLister,
Recorder: base.Recorder,
}
deploymentRec := &reconcilerutils.DeploymentReconciler{
KubeClient: base.KubeClientSet,
Lister: ls.deploymentLister,
Recorder: base.Recorder,
}
cmRec := &reconcilerutils.ConfigMapReconciler{
KubeClient: base.KubeClientSet,
Lister: ls.configMapLister,
Recorder: base.Recorder,
}
r := &Reconciler{
Base: base,
env: env,
listers: ls,
svcRec: svcRec,
deploymentRec: deploymentRec,
cmRec: cmRec,
}
return r, nil
}
// Reconciler implements controller.Reconciler for BrokerCell resources.
type Reconciler struct {
*reconciler.Base
listers
svcRec *reconcilerutils.ServiceReconciler
deploymentRec *reconcilerutils.DeploymentReconciler
cmRec *reconcilerutils.ConfigMapReconciler
env envConfig
}
// Check that our Reconciler implements Interface
var _ bcreconciler.Interface = (*Reconciler)(nil)
// ReconcileKind implements Interface.ReconcileKind.
func (r *Reconciler) ReconcileKind(ctx context.Context, bc *intv1alpha1.BrokerCell) pkgreconciler.Event {
// Why are we doing GC here instead of in the broker controller?
// 1. It's tricky to handle concurrency in broker controller. Suppose you are deleting all
// brokers at the same time, hard to tell if the brokercell should be gc'ed.
// 2. It's also more reliable. If for some reason we didn't delete the brokercell in the broker
// controller when we should (due to race, missing event, bug, etc), and if all the brokers are
// deleted, then we don't have a chance to retry.
// TODO(https://github.com/google/knative-gcp/issues/1196) It's cleaner to make this a separate controller.
if r.shouldGC(ctx, bc) {
logging.FromContext(ctx).Info("Garbage collecting brokercell", zap.String("brokercell", bc.Name), zap.String("Namespace", bc.Namespace))
return r.delete(ctx, bc)
}
bc.Status.InitializeConditions()
// Reconcile broker targets configmap first so that data plane pods are guaranteed to have the configmap volume
// mount available.
if err := r.reconcileConfig(ctx, bc); err != nil {
return err
}
authType, err := authcheck.GetAuthTypeForBrokerCell(ctx, r.serviceAccountLister, r.secretLister, authcheck.AuthTypeArgs{
Namespace: bc.Namespace,
ServiceAccountName: authcheck.BrokerServiceAccountName,
Secret: authcheck.BrokerSecret,
})
if err != nil {
bc.Status.MarkIngressUnknown(authcheck.AuthenticationCheckUnknownReason, err.Error())
bc.Status.MarkFanoutUnknown(authcheck.AuthenticationCheckUnknownReason, err.Error())
bc.Status.MarkRetryUnknown(authcheck.AuthenticationCheckUnknownReason, err.Error())
logging.FromContext(ctx).Error("Error getting authType", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
return err
}
// Reconcile ingress deployment, HPA and service.
ingressArgs := r.makeIngressArgs(bc, authType)
ind, err := r.deploymentRec.ReconcileDeployment(ctx, bc, resources.MakeIngressDeployment(ingressArgs))
if err != nil {
logging.FromContext(ctx).Error("Failed to reconcile ingress deployment", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkIngressFailed("IngressDeploymentFailed", "Failed to reconcile ingress deployment: %v", err)
return err
}
ingressHPA := resources.MakeHorizontalPodAutoscaler(ind, r.makeIngressHPAArgs(bc))
if err := r.reconcileAutoscaling(ctx, bc, ingressHPA); err != nil {
logging.FromContext(ctx).Error("Failed to reconcile ingress HPA", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkIngressFailed("HorizontalPodAutoscalerFailed", "Failed to reconcile ingress HorizontalPodAutoscaler: %v", err)
return err
}
endpoints, err := r.svcRec.ReconcileService(ctx, bc, resources.MakeIngressService(ingressArgs))
if err != nil {
logging.FromContext(ctx).Error("Failed to reconcile ingress service", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkIngressFailed("IngressServiceFailed", "Failed to reconcile ingress service: %v", err)
return err
}
// If deployment has replicaUnavailable error, it potentially has authentication configuration issues.
if replicaAvailable := bc.Status.PropagateIngressAvailability(endpoints, ind); !replicaAvailable {
podList, err := authcheck.GetPodList(ctx, resources.GetLabelSelector(bc.Name, resources.IngressName), r.KubeClientSet, bc.Namespace)
if err != nil {
logging.FromContext(ctx).Error("Failed to propagate authentication check message from ingress component", zap.Error(err))
return err
}
if authenticationCheckMessage := authcheck.GetTerminationLogFromPodList(podList); authenticationCheckMessage != "" {
bc.Status.MarkIngressUnknown(authcheck.AuthenticationCheckUnknownReason, authenticationCheckMessage)
}
}
hostName := network.GetServiceHostname(endpoints.GetName(), endpoints.GetNamespace())
bc.Status.IngressTemplate = fmt.Sprintf("http://%s/{namespace}/{name}", hostName)
// Reconcile fanout deployment and HPA.
fd, err := r.deploymentRec.ReconcileDeployment(ctx, bc, resources.MakeFanoutDeployment(r.makeFanoutArgs(bc, authType)))
if err != nil {
logging.FromContext(ctx).Error("Failed to reconcile fanout deployment", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkFanoutFailed("FanoutDeploymentFailed", "Failed to reconcile fanout deployment: %v", err)
return err
}
fanoutHPA := resources.MakeHorizontalPodAutoscaler(fd, r.makeFanoutHPAArgs(bc))
if err := r.reconcileAutoscaling(ctx, bc, fanoutHPA); err != nil {
logging.FromContext(ctx).Error("Failed to reconcile fanout HPA", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkFanoutFailed("HorizontalPodAutoscalerFailed", "Failed to reconcile fanout HorizontalPodAutoscaler: %v", err)
return err
}
// If deployment has replicaUnavailable error, it potentially has authentication configuration issues.
if replicaAvailable := bc.Status.PropagateFanoutAvailability(fd); !replicaAvailable {
podList, err := authcheck.GetPodList(ctx, resources.GetLabelSelector(bc.Name, resources.FanoutName), r.KubeClientSet, bc.Namespace)
if err != nil {
logging.FromContext(ctx).Error("Failed to propagate authentication check message from fanout component", zap.Error(err))
return err
}
if authenticationCheckMessage := authcheck.GetTerminationLogFromPodList(podList); authenticationCheckMessage != "" {
bc.Status.MarkFanoutUnknown(authcheck.AuthenticationCheckUnknownReason, authenticationCheckMessage)
}
}
// Reconcile retry deployment and HPA.
rd, err := r.deploymentRec.ReconcileDeployment(ctx, bc, resources.MakeRetryDeployment(r.makeRetryArgs(bc, authType)))
if err != nil {
logging.FromContext(ctx).Error("Failed to reconcile retry deployment", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkRetryFailed("RetryDeploymentFailed", "Failed to reconcile retry deployment: %v", err)
return err
}
retryHPA := resources.MakeHorizontalPodAutoscaler(rd, r.makeRetryHPAArgs(bc))
if err := r.reconcileAutoscaling(ctx, bc, retryHPA); err != nil {
logging.FromContext(ctx).Error("Failed to reconcile retry HPA", zap.Any("namespace", bc.Namespace), zap.Any("name", bc.Name), zap.Error(err))
bc.Status.MarkRetryFailed("HorizontalPodAutoscalerFailed", "Failed to reconcile retry HorizontalPodAutoscaler: %v", err)
return err
}
// If deployment has replicaUnavailable error, it potentially has authentication configuration issues.
if replicaAvailable := bc.Status.PropagateRetryAvailability(rd); !replicaAvailable {
podList, err := authcheck.GetPodList(ctx, resources.GetLabelSelector(bc.Name, resources.RetryName), r.KubeClientSet, bc.Namespace)
if err != nil {
logging.FromContext(ctx).Error("Failed to propagate authentication check message from retry component", zap.Error(err))
return err
}
if authenticationCheckMessage := authcheck.GetTerminationLogFromPodList(podList); authenticationCheckMessage != "" {
bc.Status.MarkRetryUnknown(authcheck.AuthenticationCheckUnknownReason, authenticationCheckMessage)
}
}
bc.Status.ObservedGeneration = bc.Generation
return pkgreconciler.NewEvent(corev1.EventTypeNormal, "BrokerCellReconciled", "BrokerCell reconciled: \"%s/%s\"", bc.Namespace, bc.Name)
}
// shouldGC returns true if
// 1. the brokercell was automatically created by GCP broker controller (with annotation
// internal.events.cloud.google.com/creator: googlecloud), and
// 2. there is no brokers pointing to it
func (r *Reconciler) shouldGC(ctx context.Context, bc *intv1alpha1.BrokerCell) bool {
// TODO use the constants in #1132 once it's merged
// We only garbage collect brokercells that were automatically created by the GCP broker controller.
if bc.GetAnnotations()["internal.events.cloud.google.com/creator"] != "googlecloud" {
return false
}
// TODO(#866) Only select brokers that point to this brokercell by label selector once the
// webhook assigns the brokercell label, i.e.,
// r.brokerLister.List(labels.SelectorFromSet(map[string]string{"brokercell":bc.Name, "brokercellns":bc.Namespace}))
brokers, err := r.brokerLister.List(labels.Everything())
if err != nil {
logging.FromContext(ctx).Error("Failed to list brokers, skipping garbage collection logic", zap.String("brokercell", bc.Name), zap.String("Namespace", bc.Namespace))
return false
}
if len(brokers) > 0 {
// There are still Brokers using this BrokerCell, do not garbage collect it.
return false
}
// TODO(#866) Only select Channels that point to this brokercell by label selector once the
// webhook assigns the brokercell label, i.e.,
// r.brokerLister.List(labels.SelectorFromSet(map[string]string{"brokercell":bc.Name, "brokercellns":bc.Namespace}))
channels, err := r.channelLister.List(labels.Everything())
if err != nil {
logging.FromContext(ctx).Error("Failed to list Channels, skipping garbage collection logic", zap.String("brokercell", bc.Name), zap.String("Namespace", bc.Namespace))
return false
}
if len(channels) > 0 {
// There are still Channels using this BrokerCell, do not garbage collect it.
return false
}
return true
}
func (r *Reconciler) delete(ctx context.Context, bc *intv1alpha1.BrokerCell) pkgreconciler.Event {
if err := r.RunClientSet.InternalV1alpha1().BrokerCells(bc.Namespace).Delete(ctx, bc.Name, metav1.DeleteOptions{}); err != nil {
return fmt.Errorf("failed to garbage collect brokercell: %w", err)
}
return pkgreconciler.NewEvent(corev1.EventTypeNormal, "BrokerCellGarbageCollected", "BrokerCell garbage collected: \"%s/%s\"", bc.Namespace, bc.Name)
}
func (r *Reconciler) makeIngressArgs(bc *intv1alpha1.BrokerCell, authType authcheck.AuthType) resources.IngressArgs {
return resources.IngressArgs{
Args: resources.Args{
ComponentName: resources.IngressName,
BrokerCell: bc,
Image: r.env.IngressImage,
ServiceAccountName: r.env.ServiceAccountName,
MetricsPort: r.env.MetricsPort,
AllowIstioSidecar: true,
CPURequest: bc.Spec.Components.Ingress.CPURequest,
CPULimit: bc.Spec.Components.Ingress.CPULimit,
MemoryRequest: bc.Spec.Components.Ingress.MemoryRequest,
MemoryLimit: bc.Spec.Components.Ingress.MemoryLimit,
RolloutRestartTime: bc.GetAnnotations()[resources.IngressRestartTimeAnnotationKey],
AuthType: authType,
},
Port: r.env.IngressPort,
// TODO(#1804): remove this arg when enabling the feature by default.
EnableIngressFilter: getIngressFilteringEnabled(bc),
}
}
// TODO(#1804): remove this function when enabling the feature by default.
func getIngressFilteringEnabled(bc *intv1alpha1.BrokerCell) bool {
if val, ok := bc.GetAnnotations()[resources.IngressFilteringEnabledAnnotationKey]; ok {
return val == "true"
}
return false
}
func (r *Reconciler) makeIngressHPAArgs(bc *intv1alpha1.BrokerCell) resources.AutoscalingArgs {
return resources.AutoscalingArgs{
ComponentName: resources.IngressName,
BrokerCell: bc,
AvgCPUUtilization: bc.Spec.Components.Ingress.AvgCPUUtilization,
AvgMemoryUsage: bc.Spec.Components.Ingress.AvgMemoryUsage,
MaxReplicas: *bc.Spec.Components.Ingress.MaxReplicas,
MinReplicas: *bc.Spec.Components.Ingress.MinReplicas,
}
}
func (r *Reconciler) makeFanoutArgs(bc *intv1alpha1.BrokerCell, authType authcheck.AuthType) resources.FanoutArgs {
return resources.FanoutArgs{
Args: resources.Args{
ComponentName: resources.FanoutName,
BrokerCell: bc,
Image: r.env.FanoutImage,
ServiceAccountName: r.env.ServiceAccountName,
MetricsPort: r.env.MetricsPort,
AllowIstioSidecar: true,
CPURequest: bc.Spec.Components.Fanout.CPURequest,
CPULimit: bc.Spec.Components.Fanout.CPULimit,
MemoryRequest: bc.Spec.Components.Fanout.MemoryRequest,
MemoryLimit: bc.Spec.Components.Fanout.MemoryLimit,
RolloutRestartTime: bc.GetAnnotations()[resources.FanoutRestartTimeAnnotationKey],
AuthType: authType,
},
}
}
func (r *Reconciler) makeFanoutHPAArgs(bc *intv1alpha1.BrokerCell) resources.AutoscalingArgs {
return resources.AutoscalingArgs{
ComponentName: resources.FanoutName,
BrokerCell: bc,
AvgCPUUtilization: bc.Spec.Components.Fanout.AvgCPUUtilization,
AvgMemoryUsage: bc.Spec.Components.Fanout.AvgMemoryUsage,
MaxReplicas: *bc.Spec.Components.Fanout.MaxReplicas,
MinReplicas: *bc.Spec.Components.Fanout.MinReplicas,
}
}
func (r *Reconciler) makeRetryArgs(bc *intv1alpha1.BrokerCell, authType authcheck.AuthType) resources.RetryArgs {
return resources.RetryArgs{
Args: resources.Args{
ComponentName: resources.RetryName,
BrokerCell: bc,
Image: r.env.RetryImage,
ServiceAccountName: r.env.ServiceAccountName,
MetricsPort: r.env.MetricsPort,
AllowIstioSidecar: true,
CPURequest: bc.Spec.Components.Retry.CPURequest,
CPULimit: bc.Spec.Components.Retry.CPULimit,
MemoryRequest: bc.Spec.Components.Retry.MemoryRequest,
MemoryLimit: bc.Spec.Components.Retry.MemoryLimit,
RolloutRestartTime: bc.GetAnnotations()[resources.RetryRestartTimeAnnotationKey],
AuthType: authType,
},
}
}
func (r *Reconciler) makeRetryHPAArgs(bc *intv1alpha1.BrokerCell) resources.AutoscalingArgs {
return resources.AutoscalingArgs{
ComponentName: resources.RetryName,
BrokerCell: bc,
AvgCPUUtilization: bc.Spec.Components.Retry.AvgCPUUtilization,
AvgMemoryUsage: bc.Spec.Components.Retry.AvgMemoryUsage,
MaxReplicas: *bc.Spec.Components.Retry.MaxReplicas,
MinReplicas: *bc.Spec.Components.Retry.MinReplicas,
}
}
func (r *Reconciler) reconcileAutoscaling(ctx context.Context, bc *intv1alpha1.BrokerCell, desired *hpav2beta2.HorizontalPodAutoscaler) error {
existing, err := r.hpaLister.HorizontalPodAutoscalers(desired.Namespace).Get(desired.Name)
if apierrs.IsNotFound(err) {
existing, err = r.KubeClientSet.AutoscalingV2beta2().HorizontalPodAutoscalers(desired.Namespace).Create(ctx, desired, metav1.CreateOptions{})
if apierrs.IsAlreadyExists(err) {
return nil
}
if err == nil {
r.Recorder.Eventf(bc, corev1.EventTypeNormal, "HorizontalPodAutoscalerCreated", "Created HPA %s/%s", desired.Namespace, desired.Name)
}
return err
}
if err != nil {
return err
}
if !equality.Semantic.DeepDerivative(desired.Spec, existing.Spec) {
// Don't modify the informers copy.
copy := existing.DeepCopy()
copy.Spec = desired.Spec
_, err := r.KubeClientSet.AutoscalingV2beta2().HorizontalPodAutoscalers(copy.Namespace).Update(ctx, copy, metav1.UpdateOptions{})
if err == nil {
r.Recorder.Eventf(bc, corev1.EventTypeNormal, "HorizontalPodAutoscalerUpdated", "Updated HPA %s/%s", desired.Namespace, desired.Name)
}
return err
}
return nil
}