forked from stolostron/backplane-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
387 lines (332 loc) · 13.3 KB
/
main.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
// Copyright Contributors to the Open Cluster Management project
/*
Copyright 2021.
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.
*/
//go:generate go run pkg/templates/rbac.go
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
operatorsapiv2 "github.com/operator-framework/api/pkg/operators/v2"
backplanev1 "github.com/stolostron/backplane-operator/api/v1"
"github.com/stolostron/backplane-operator/controllers"
renderer "github.com/stolostron/backplane-operator/pkg/rendering"
"github.com/stolostron/backplane-operator/pkg/status"
"github.com/stolostron/backplane-operator/pkg/utils"
"github.com/stolostron/backplane-operator/pkg/version"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clustermanager "open-cluster-management.io/api/operator/v1"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
hiveconfig "github.com/openshift/hive/apis/hive/v1"
rbacv1 "k8s.io/api/rbac/v1"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/util/retry"
"go.uber.org/zap/zapcore"
admissionregistration "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
apixv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/webhook"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
//+kubebuilder:scaffold:imports
)
const (
crdName = "multiclusterengines.multicluster.openshift.io"
crdsDir = "pkg/templates/crds"
NoCacheEnv = "DISABLE_CLIENT_CACHE"
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
if _, exists := os.LookupEnv("OPERATOR_VERSION"); !exists {
panic("OPERATOR_VERSION not defined")
}
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(backplanev1.AddToScheme(scheme))
utilruntime.Must(apiregistrationv1.AddToScheme(scheme))
utilruntime.Must(operatorsapiv2.AddToScheme(scheme))
utilruntime.Must(admissionregistration.AddToScheme(scheme))
utilruntime.Must(apixv1.AddToScheme(scheme))
utilruntime.Must(hiveconfig.AddToScheme(scheme))
utilruntime.Must(clustermanager.AddToScheme(scheme))
utilruntime.Must(monitoringv1.AddToScheme(scheme))
utilruntime.Must(configv1.AddToScheme(scheme))
utilruntime.Must(operatorv1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
var leaseDuration time.Duration
var renewDeadline time.Duration
var retryPeriod time.Duration
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", true,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.DurationVar(&leaseDuration, "leader-election-lease-duration", 137*time.Second, ""+
"The duration that non-leader candidates will wait after observing a leadership "+
"renewal until attempting to acquire leadership of a led but unrenewed leader "+
"slot. This is effectively the maximum duration that a leader can be stopped "+
"before it is replaced by another candidate. This is only applicable if leader "+
"election is enabled.")
flag.DurationVar(&renewDeadline, "leader-election-renew-deadline", 107*time.Second, ""+
"The interval between attempts by the acting master to renew a leadership slot "+
"before it stops leading. This must be less than or equal to the lease duration. "+
"This is only applicable if leader election is enabled.")
flag.DurationVar(&retryPeriod, "leader-election-retry-period", 26*time.Second, ""+
"The duration the clients should wait between attempting acquisition and renewal "+
"of a leadership. This is only applicable if leader election is enabled.")
opts := zap.Options{
Development: true,
TimeEncoder: zapcore.ISO8601TimeEncoder,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
ctrl.Log.WithName("Backplane Operator version").Info(fmt.Sprintf("%#v", version.Get()))
mgrOptions := ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "797f9276.open-cluster-management.io",
WebhookServer: &webhook.Server{TLSMinVersion: "1.2"},
LeaseDuration: &leaseDuration,
RenewDeadline: &renewDeadline,
RetryPeriod: &retryPeriod,
// LeaderElectionNamespace: "backplane-operator-system", // Ensure this is commented out. Uncomment only for running operator locally.
}
setupLog.Info("Disabling Operator Client Cache for high-memory resources")
mgrOptions.ClientDisableCacheFor = []client.Object{
&corev1.Secret{},
&rbacv1.ClusterRole{},
&rbacv1.ClusterRoleBinding{},
&rbacv1.RoleBinding{},
&corev1.ConfigMap{},
&corev1.ServiceAccount{},
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), mgrOptions)
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
// use uncached client for setup before manager starts
uncachedClient, err := client.New(ctrl.GetConfigOrDie(), client.Options{
Scheme: mgr.GetScheme(),
})
if err != nil {
setupLog.Error(err, "unable to create uncached client")
os.Exit(1)
}
// Force OperatorCondition Upgradeable to False
//
// We have to at least default the condition to False or
// OLM will use the Readiness condition via our readiness probe instead:
// https://olm.operatorframework.io/docs/advanced-tasks/communicating-operator-conditions-to-olm/#setting-defaults
//
// We want to force it to False to ensure that the final decision about whether
// the operator can be upgraded stays within the mce controller.
setupLog.Info("Setting OperatorCondition.")
upgradeableCondition, err := utils.NewOperatorCondition(uncachedClient, operatorsapiv2.Upgradeable)
ctx := context.Background()
if err != nil {
setupLog.Error(err, "Cannot create the Upgradeable Operator Condition")
os.Exit(1)
}
err = upgradeableCondition.Set(ctx, metav1.ConditionFalse, utils.UpgradeableInitReason, utils.UpgradeableInitMessage)
if err != nil {
setupLog.Error(err, "unable to create set operator condition upgradable to false")
os.Exit(1)
}
if err = (&controllers.MultiClusterEngineReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
StatusManager: &status.StatusTracker{Client: mgr.GetClient()},
UpgradeableCond: upgradeableCondition,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "MultiClusterEngine")
os.Exit(1)
}
// Render CRD templates
crdsDir := crdsDir
crds, errs := renderer.RenderCRDs(crdsDir)
if len(errs) > 0 {
for _, err := range errs {
setupLog.Info(err.Error())
}
os.Exit(1)
}
// udpate CRDs with retry
for i := range crds {
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
crd := crds[i]
e := ensureCRD(context.TODO(), uncachedClient, crd)
return e
})
if retryErr != nil {
setupLog.Error(err, "unable to ensure CRD exists in alloted time. Failing.")
os.Exit(1)
}
}
if os.Getenv("ENABLE_WEBHOOKS") != "false" {
// https://book.kubebuilder.io/cronjob-tutorial/running.html#running-webhooks-locally, https://book.kubebuilder.io/multiversion-tutorial/webhooks.html#and-maingo
if err = ensureWebhooks(uncachedClient); err != nil {
setupLog.Error(err, "unable to ensure webhook", "webhook", "MultiClusterEngine")
os.Exit(1)
}
if err = (&backplanev1.MultiClusterEngine{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "MultiClusterEngine")
os.Exit(1)
}
}
//+kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
multiclusterengineList := &backplanev1.MultiClusterEngineList{}
err = uncachedClient.List(context.TODO(), multiclusterengineList)
if err != nil {
setupLog.Error(err, "Could not set List multicluster engines")
os.Exit(1)
}
if len(multiclusterengineList.Items) == 0 {
err = upgradeableCondition.Set(ctx, metav1.ConditionTrue, utils.UpgradeableAllowReason, utils.UpgradeableAllowMessage)
if err != nil {
setupLog.Error(err, "Could not set Operator Condition")
os.Exit(1)
}
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
func ensureCRD(ctx context.Context, c client.Client, crd *unstructured.Unstructured) error {
existingCRD := &unstructured.Unstructured{}
existingCRD.SetGroupVersionKind(crd.GroupVersionKind())
err := c.Get(ctx, types.NamespacedName{Name: crd.GetName()}, existingCRD)
if err != nil && errors.IsNotFound(err) {
// CRD not found. Create and return
setupLog.Info(fmt.Sprintf("creating CRD '%s'", crd.GetName()))
err = c.Create(ctx, crd)
if err != nil {
return fmt.Errorf("error creating CRD '%s': %w", crd.GetName(), err)
}
} else if err != nil {
return fmt.Errorf("error getting CRD '%s': %w", crd.GetName(), err)
} else if err == nil {
// CRD already exists. Update and return
if utils.AnnotationPresent(utils.AnnotationMCEIgnore, existingCRD) {
setupLog.Info(fmt.Sprintf("CRD '%s' has ignore label. Skipping update.", crd.GetName()))
return nil
}
crd.SetResourceVersion(existingCRD.GetResourceVersion())
setupLog.Info(fmt.Sprintf("updating CRD '%s'", crd.GetName()))
err = c.Update(ctx, crd)
if err != nil {
return fmt.Errorf("error updating CRD '%s': %w", crd.GetName(), err)
}
}
return nil
}
func ensureWebhooks(k8sClient client.Client) error {
ctx := context.Background()
deploymentNamespace, ok := os.LookupEnv("POD_NAMESPACE")
if !ok {
setupLog.Info("Failing due to being unable to locate webhook service namespace")
os.Exit(1)
}
validatingWebhook := backplanev1.ValidatingWebhook(deploymentNamespace)
maxAttempts := 10
for i := 0; i < maxAttempts; i++ {
setupLog.Info("Applying ValidatingWebhookConfiguration")
// Get reference to MCE CRD to set as owner of the webhook
// This way if the CRD is deleted the webhook will be removed with it
crdKey := types.NamespacedName{Name: crdName}
owner := &apixv1.CustomResourceDefinition{}
if err := k8sClient.Get(context.TODO(), crdKey, owner); err != nil {
setupLog.Error(err, "Failed to get MCE CRD")
time.Sleep(5 * time.Second)
continue
}
validatingWebhook.SetOwnerReferences([]metav1.OwnerReference{
{
APIVersion: "apiextensions.k8s.io/v1",
Kind: "CustomResourceDefinition",
Name: owner.Name,
UID: owner.UID,
},
})
existingWebhook := &admissionregistration.ValidatingWebhookConfiguration{}
existingWebhook.SetGroupVersionKind(schema.GroupVersionKind{
Group: "admissionregistration.k8s.io",
Version: "v1",
Kind: "ValidatingWebhookConfiguration",
})
err := k8sClient.Get(ctx, types.NamespacedName{Name: validatingWebhook.GetName()}, existingWebhook)
if err != nil && errors.IsNotFound(err) {
// Webhook not found. Create and return
err = k8sClient.Create(ctx, validatingWebhook)
if err != nil {
setupLog.Error(err, "Error creating validatingwebhookconfiguration")
time.Sleep(5 * time.Second)
continue
}
return nil
} else if err != nil {
setupLog.Error(err, "Error getting validatingwebhookconfiguration")
time.Sleep(5 * time.Second)
continue
} else if err == nil {
// Webhook already exists. Update and return
setupLog.Info("Updating existing validatingwebhookconfiguration")
existingWebhook.Webhooks = validatingWebhook.Webhooks
err = k8sClient.Update(ctx, existingWebhook)
if err != nil {
setupLog.Error(err, "Error updating validatingwebhookconfiguration")
time.Sleep(5 * time.Second)
continue
}
return nil
}
}
return fmt.Errorf("unable to ensure validatingwebhook exists in allotted time")
}