forked from operator-framework/operator-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
660 lines (590 loc) · 26.5 KB
/
main.go
File metadata and controls
660 lines (590 loc) · 26.5 KB
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/*
Copyright 2022.
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 main
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/containers/image/v5/types"
"github.com/spf13/cobra"
rbacv1 "k8s.io/api/rbac/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsv1client "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1"
k8slabels "k8s.io/apimachinery/pkg/labels"
k8stypes "k8s.io/apimachinery/pkg/types"
apimachineryrand "k8s.io/apimachinery/pkg/util/rand"
"k8s.io/client-go/discovery"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
"pkg.package-operator.run/boxcutter/machinery"
"pkg.package-operator.run/boxcutter/managedcache"
"pkg.package-operator.run/boxcutter/ownerhandling"
"pkg.package-operator.run/boxcutter/validation"
ctrl "sigs.k8s.io/controller-runtime"
crcache "sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/certwatcher"
"sigs.k8s.io/controller-runtime/pkg/client"
crcontroller "sigs.k8s.io/controller-runtime/pkg/controller"
crfinalizer "sigs.k8s.io/controller-runtime/pkg/finalizer"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
helmclient "github.com/operator-framework/helm-operator-plugins/pkg/client"
ocv1 "github.com/operator-framework/operator-controller/api/v1"
"github.com/operator-framework/operator-controller/internal/operator-controller/action"
"github.com/operator-framework/operator-controller/internal/operator-controller/applier"
"github.com/operator-framework/operator-controller/internal/operator-controller/authentication"
"github.com/operator-framework/operator-controller/internal/operator-controller/authorization"
"github.com/operator-framework/operator-controller/internal/operator-controller/catalogmetadata/cache"
catalogclient "github.com/operator-framework/operator-controller/internal/operator-controller/catalogmetadata/client"
"github.com/operator-framework/operator-controller/internal/operator-controller/contentmanager"
"github.com/operator-framework/operator-controller/internal/operator-controller/controllers"
"github.com/operator-framework/operator-controller/internal/operator-controller/features"
"github.com/operator-framework/operator-controller/internal/operator-controller/finalizers"
"github.com/operator-framework/operator-controller/internal/operator-controller/resolve"
"github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/convert"
"github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/preflights/crdupgradesafety"
"github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/render"
"github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/render/certproviders"
"github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/render/registryv1"
"github.com/operator-framework/operator-controller/internal/operator-controller/scheme"
sharedcontrollers "github.com/operator-framework/operator-controller/internal/shared/controllers"
fsutil "github.com/operator-framework/operator-controller/internal/shared/util/fs"
httputil "github.com/operator-framework/operator-controller/internal/shared/util/http"
imageutil "github.com/operator-framework/operator-controller/internal/shared/util/image"
"github.com/operator-framework/operator-controller/internal/shared/util/pullsecretcache"
sautil "github.com/operator-framework/operator-controller/internal/shared/util/sa"
"github.com/operator-framework/operator-controller/internal/shared/version"
)
var (
setupLog = ctrl.Log.WithName("setup")
defaultSystemNamespace = "olmv1-system"
certWatcher *certwatcher.CertWatcher
cfg = &config{}
)
type config struct {
metricsAddr string
pprofAddr string
certFile string
keyFile string
enableLeaderElection bool
probeAddr string
cachePath string
systemNamespace string
catalogdCasDir string
pullCasDir string
globalPullSecret string
}
const authFilePrefix = "operator-controller-global-pull-secrets"
// podNamespace checks whether the controller is running in a Pod vs.
// being run locally by inspecting the namespace file that gets mounted
// automatically for Pods at runtime. If that file doesn't exist, then
// return defaultSystemNamespace.
func podNamespace() string {
namespace, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
return defaultSystemNamespace
}
return string(namespace)
}
var operatorControllerCmd = &cobra.Command{
Use: "operator-controller",
Short: "operator-controller is the central component of Operator Lifecycle Manager (OLM) v1",
RunE: func(cmd *cobra.Command, args []string) error {
if err := validateMetricsFlags(); err != nil {
return err
}
return run()
},
}
var versionCommand = &cobra.Command{
Use: "version",
Short: "Prints operator-controller version information",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(version.String())
},
}
func init() {
//create flagset, the collection of flags for this command
flags := operatorControllerCmd.Flags()
flags.StringVar(&cfg.metricsAddr, "metrics-bind-address", "", "The address for the metrics endpoint. Requires tls-cert and tls-key. (Default: ':8443')")
flags.StringVar(&cfg.pprofAddr, "pprof-bind-address", "0", "The address the pprof endpoint binds to. an empty string or 0 disables pprof")
flags.StringVar(&cfg.probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flags.StringVar(&cfg.catalogdCasDir, "catalogd-cas-dir", "", "The directory of TLS certificate authorities to use for verifying HTTPS connections to the Catalogd web service.")
flags.StringVar(&cfg.pullCasDir, "pull-cas-dir", "", "The directory of TLS certificate authorities to use for verifying HTTPS connections to image registries.")
flags.StringVar(&cfg.certFile, "tls-cert", "", "The certificate file used for the metrics server. Required to enable the metrics server. Requires tls-key.")
flags.StringVar(&cfg.keyFile, "tls-key", "", "The key file used for the metrics server. Required to enable the metrics server. Requires tls-cert")
flags.BoolVar(&cfg.enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flags.StringVar(&cfg.cachePath, "cache-path", "/var/cache", "The local directory path used for filesystem based caching")
flags.StringVar(&cfg.systemNamespace, "system-namespace", "", "Configures the namespace that gets used to deploy system resources.")
flags.StringVar(&cfg.globalPullSecret, "global-pull-secret", "", "The <namespace>/<name> of the global pull secret that is going to be used to pull bundle images.")
//adds version sub command
operatorControllerCmd.AddCommand(versionCommand)
//add klog flags to flagset
klog.InitFlags(flag.CommandLine)
flags.AddGoFlagSet(flag.CommandLine)
//add feature gate flags to flagset
features.OperatorControllerFeatureGate.AddFlag(flags)
ctrl.SetLogger(klog.NewKlogr())
}
func validateMetricsFlags() error {
if (cfg.certFile != "" && cfg.keyFile == "") || (cfg.certFile == "" && cfg.keyFile != "") {
setupLog.Error(errors.New("missing TLS configuration"),
"tls-cert and tls-key flags must be used together",
"certFile", cfg.certFile, "keyFile", cfg.keyFile)
return fmt.Errorf("unable to configure TLS certificates: tls-cert and tls-key flags must be used together")
}
if cfg.metricsAddr != "" && cfg.certFile == "" && cfg.keyFile == "" {
setupLog.Error(errors.New("invalid metrics configuration"),
"metrics-bind-address requires tls-cert and tls-key flags to be set",
"metricsAddr", cfg.metricsAddr, "certFile", cfg.certFile, "keyFile", cfg.keyFile)
return fmt.Errorf("metrics-bind-address requires tls-cert and tls-key flags to be set")
}
if cfg.certFile != "" && cfg.keyFile != "" && cfg.metricsAddr == "" {
cfg.metricsAddr = ":8443"
}
return nil
}
func run() error {
setupLog.Info("starting up the controller", "version info", version.String())
// log feature gate status after parsing flags and setting up logger
features.LogFeatureGateStates(setupLog, features.OperatorControllerFeatureGate)
authFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("%s-%s.json", authFilePrefix, apimachineryrand.String(8)))
var globalPullSecretKey *k8stypes.NamespacedName
if cfg.globalPullSecret != "" {
secretParts := strings.Split(cfg.globalPullSecret, "/")
if len(secretParts) != 2 {
err := fmt.Errorf("incorrect number of components")
setupLog.Error(err, "Value of global-pull-secret should be of the format <namespace>/<name>")
return err
}
globalPullSecretKey = &k8stypes.NamespacedName{Name: secretParts[1], Namespace: secretParts[0]}
}
if cfg.systemNamespace == "" {
cfg.systemNamespace = podNamespace()
}
setupLog.Info("set up manager")
cacheOptions := crcache.Options{
ByObject: map[client.Object]crcache.ByObject{
&ocv1.ClusterExtension{}: {Label: k8slabels.Everything()},
&ocv1.ClusterCatalog{}: {Label: k8slabels.Everything()},
&rbacv1.ClusterRole{}: {Label: k8slabels.Everything()},
&rbacv1.ClusterRoleBinding{}: {Label: k8slabels.Everything()},
&rbacv1.Role{}: {Namespaces: map[string]crcache.Config{}, Label: k8slabels.Everything()},
&rbacv1.RoleBinding{}: {Namespaces: map[string]crcache.Config{}, Label: k8slabels.Everything()},
},
DefaultNamespaces: map[string]crcache.Config{
cfg.systemNamespace: {LabelSelector: k8slabels.Everything()},
},
DefaultLabelSelector: k8slabels.Nothing(),
}
if features.OperatorControllerFeatureGate.Enabled(features.BoxcutterRuntime) {
cacheOptions.ByObject[&ocv1.ClusterExtensionRevision{}] = crcache.ByObject{
Label: k8slabels.Everything(),
}
}
saKey, err := sautil.GetServiceAccount()
if err != nil {
setupLog.Error(err, "Failed to extract serviceaccount from JWT")
return err
}
setupLog.Info("Successfully extracted serviceaccount from JWT", "serviceaccount",
fmt.Sprintf("%s/%s", saKey.Namespace, saKey.Name))
err = pullsecretcache.SetupPullSecretCache(&cacheOptions, globalPullSecretKey, saKey)
if err != nil {
setupLog.Error(err, "Unable to setup pull-secret cache")
return err
}
metricsServerOptions := server.Options{}
if len(cfg.certFile) > 0 && len(cfg.keyFile) > 0 {
setupLog.Info("Starting metrics server with TLS enabled", "addr", cfg.metricsAddr, "tls-cert", cfg.certFile, "tls-key", cfg.keyFile)
metricsServerOptions.BindAddress = cfg.metricsAddr
metricsServerOptions.SecureServing = true
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
// If the certificate files change, the watcher will reload them.
var err error
certWatcher, err = certwatcher.New(cfg.certFile, cfg.keyFile)
if err != nil {
setupLog.Error(err, "Failed to initialize certificate watcher")
return err
}
metricsServerOptions.TLSOpts = append(metricsServerOptions.TLSOpts, func(config *tls.Config) {
config.GetCertificate = certWatcher.GetCertificate
// If the enable-http2 flag is false (the default), http/2 should be disabled
// due to its vulnerabilities. More specifically, disabling http/2 will
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
// Rapid Reset CVEs. For more information see:
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
// - https://github.com/advisories/GHSA-4374-p667-p6c8
// Besides, those CVEs are solved already; the solution is still insufficient, and we need to mitigate
// the risks. More info https://github.com/golang/go/issues/63417
config.NextProtos = []string{"http/1.1"}
})
} else {
// Note that the metrics server is not serving if the BindAddress is set to "0".
// Therefore, the metrics server is disabled by default. It is only enabled
// if certFile and keyFile are provided. The intention is not allowing the metrics
// be served with the default self-signed certificate generated by controller-runtime.
metricsServerOptions.BindAddress = "0"
setupLog.Info("WARNING: Metrics Server is disabled. " +
"Metrics will not be served since the TLS certificate and key file are not provided.")
}
restConfig := ctrl.GetConfigOrDie()
mgr, err := ctrl.NewManager(restConfig, ctrl.Options{
Scheme: scheme.Scheme,
Metrics: metricsServerOptions,
PprofBindAddress: cfg.pprofAddr,
HealthProbeBindAddress: cfg.probeAddr,
LeaderElection: cfg.enableLeaderElection,
LeaderElectionID: "9c4404e7.operatorframework.io",
LeaderElectionReleaseOnCancel: true,
// Recommended Leader Election values
// https://github.com/openshift/enhancements/blob/61581dcd985130357d6e4b0e72b87ee35394bf6e/CONVENTIONS.md#handling-kube-apiserver-disruption
LeaseDuration: ptr.To(137 * time.Second),
RenewDeadline: ptr.To(107 * time.Second),
RetryPeriod: ptr.To(26 * time.Second),
Cache: cacheOptions,
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
// when the Manager ends. This requires the binary to immediately end when the
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
// speeds up voluntary leader transitions as the new leader don't have to wait
// LeaseDuration time first.
//
// In the default scaffold provided, the program ends immediately after
// the manager stops, so would be fine to enable this option. However,
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
return err
}
certPoolWatcher, err := httputil.NewCertPoolWatcher(cfg.catalogdCasDir, ctrl.Log.WithName("cert-pool"))
if err != nil {
setupLog.Error(err, "unable to create CA certificate pool")
return err
}
if certWatcher != nil {
setupLog.Info("Adding certificate watcher to manager")
if err := mgr.Add(certWatcher); err != nil {
setupLog.Error(err, "unable to add certificate watcher to manager")
return err
}
}
if err := fsutil.EnsureEmptyDirectory(cfg.cachePath, 0700); err != nil {
setupLog.Error(err, "unable to ensure empty cache directory")
return err
}
imageCache := imageutil.BundleCache(filepath.Join(cfg.cachePath, "unpack"))
imagePuller := &imageutil.ContainersImagePuller{
SourceCtxFunc: func(ctx context.Context) (*types.SystemContext, error) {
srcContext := &types.SystemContext{
DockerCertPath: cfg.pullCasDir,
OCICertPath: cfg.pullCasDir,
}
logger := log.FromContext(ctx)
if _, err := os.Stat(authFilePath); err == nil {
logger.Info("using available authentication information for pulling image")
srcContext.AuthFilePath = authFilePath
} else if os.IsNotExist(err) {
logger.Info("no authentication information found for pulling image, proceeding without auth")
} else {
return nil, fmt.Errorf("could not stat auth file, error: %w", err)
}
return srcContext, nil
},
}
clusterExtensionFinalizers := crfinalizer.NewFinalizers()
if err := clusterExtensionFinalizers.Register(controllers.ClusterExtensionCleanupUnpackCacheFinalizer, finalizers.FinalizerFunc(func(ctx context.Context, obj client.Object) (crfinalizer.Result, error) {
return crfinalizer.Result{}, imageCache.Delete(ctx, obj.GetName())
})); err != nil {
setupLog.Error(err, "unable to register finalizer", "finalizerKey", controllers.ClusterExtensionCleanupUnpackCacheFinalizer)
return err
}
cl := mgr.GetClient()
catalogsCachePath := filepath.Join(cfg.cachePath, "catalogs")
if err := os.MkdirAll(catalogsCachePath, 0700); err != nil {
setupLog.Error(err, "unable to create catalogs cache directory")
return err
}
catalogClientBackend := cache.NewFilesystemCache(catalogsCachePath)
catalogClient := catalogclient.New(catalogClientBackend, func() (*http.Client, error) {
return httputil.BuildHTTPClient(certPoolWatcher)
})
resolver := &resolve.CatalogResolver{
WalkCatalogsFunc: resolve.CatalogWalker(
func(ctx context.Context, option ...client.ListOption) ([]ocv1.ClusterCatalog, error) {
var catalogs ocv1.ClusterCatalogList
if err := cl.List(ctx, &catalogs, option...); err != nil {
return nil, err
}
return catalogs.Items, nil
},
catalogClient.GetPackage,
),
Validations: []resolve.ValidationFunc{
resolve.NoDependencyValidation,
},
}
aeClient, err := apiextensionsv1client.NewForConfig(mgr.GetConfig())
if err != nil {
setupLog.Error(err, "unable to create apiextensions client")
return err
}
preflights := []applier.Preflight{
crdupgradesafety.NewPreflight(aeClient.CustomResourceDefinitions()),
}
var ctrlBuilderOpts []controllers.ControllerBuilderOption
if features.OperatorControllerFeatureGate.Enabled(features.BoxcutterRuntime) {
ctrlBuilderOpts = append(ctrlBuilderOpts, controllers.WithOwns(&ocv1.ClusterExtensionRevision{}))
}
ceReconciler := &controllers.ClusterExtensionReconciler{
Client: cl,
Resolver: resolver,
ImageCache: imageCache,
ImagePuller: imagePuller,
Finalizers: clusterExtensionFinalizers,
}
ceController, err := ceReconciler.SetupWithManager(mgr, ctrlBuilderOpts...)
if err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ClusterExtension")
return err
}
if features.OperatorControllerFeatureGate.Enabled(features.BoxcutterRuntime) {
err = setupBoxcutter(mgr, ceReconciler, preflights)
} else {
err = setupHelm(mgr, ceReconciler, preflights, ceController, clusterExtensionFinalizers)
}
if err != nil {
setupLog.Error(err, "unable to setup lifecycler")
return err
}
if err = (&controllers.ClusterCatalogReconciler{
Client: cl,
CatalogCache: catalogClientBackend,
CatalogCachePopulator: catalogClient,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ClusterCatalog")
return err
}
setupLog.Info("creating SecretSyncer controller for watching secret", "Secret", cfg.globalPullSecret)
err = (&sharedcontrollers.PullSecretReconciler{
Client: mgr.GetClient(),
AuthFilePath: authFilePath,
SecretKey: globalPullSecretKey,
ServiceAccountKey: saKey,
}).SetupWithManager(mgr)
if err != nil {
setupLog.Error(err, "unable to create controller", "controller", "SecretSyncer")
return err
}
//+kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
return err
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
return err
}
setupLog.Info("starting manager")
ctx := ctrl.SetupSignalHandler()
if err := mgr.Start(ctx); err != nil {
setupLog.Error(err, "problem running manager")
return err
}
if err := os.Remove(authFilePath); err != nil {
setupLog.Error(err, "failed to cleanup temporary auth file")
return err
}
return nil
}
func getCertificateProvider() render.CertificateProvider {
if features.OperatorControllerFeatureGate.Enabled(features.WebhookProviderCertManager) {
return certproviders.CertManagerCertificateProvider{}
} else if features.OperatorControllerFeatureGate.Enabled(features.WebhookProviderOpenshiftServiceCA) {
return certproviders.OpenshiftServiceCaCertificateProvider{}
}
return nil
}
func setupBoxcutter(mgr manager.Manager, ceReconciler *controllers.ClusterExtensionReconciler, preflights []applier.Preflight) error {
certProvider := getCertificateProvider()
coreClient, err := corev1client.NewForConfig(mgr.GetConfig())
if err != nil {
return fmt.Errorf("unable to create core client: %w", err)
}
cfgGetter, err := helmclient.NewActionConfigGetter(mgr.GetConfig(), mgr.GetRESTMapper(),
helmclient.StorageDriverMapper(action.ChunkedStorageDriverMapper(coreClient, mgr.GetAPIReader(), cfg.systemNamespace)),
helmclient.ClientNamespaceMapper(func(obj client.Object) (string, error) {
ext := obj.(*ocv1.ClusterExtension)
return ext.Spec.Namespace, nil
}),
)
if err != nil {
return fmt.Errorf("unable to create helm action config getter: %w", err)
}
acg, err := action.NewWrappedActionClientGetter(cfgGetter,
helmclient.WithFailureRollbacks(false),
)
if err != nil {
return fmt.Errorf("unable to create helm action client getter: %w", err)
}
// TODO: add support for preflight checks
// TODO: better scheme handling - which types do we want to support?
_ = apiextensionsv1.AddToScheme(mgr.GetScheme())
rg := &applier.SimpleRevisionGenerator{
Scheme: mgr.GetScheme(),
BundleRenderer: &applier.RegistryV1BundleRenderer{
BundleRenderer: registryv1.Renderer,
CertificateProvider: certProvider,
},
}
ceReconciler.Applier = &applier.Boxcutter{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
RevisionGenerator: rg,
Preflights: preflights,
}
ceReconciler.RevisionStatesGetter = &controllers.BoxcutterRevisionStatesGetter{Reader: mgr.GetClient()}
ceReconciler.StorageMigrator = &applier.BoxcutterStorageMigrator{
Client: mgr.GetClient(),
ActionClientGetter: acg,
RevisionGenerator: rg,
}
// Boxcutter
const (
boxcutterSystemPrefixFieldOwner = "olm.operatorframework.io"
)
discoveryClient, err := discovery.NewDiscoveryClientForConfig(mgr.GetConfig())
if err != nil {
return fmt.Errorf("unable to create discovery client: %w", err)
}
trackingCache, err := managedcache.NewTrackingCache(
ctrl.Log.WithName("trackingCache"),
mgr.GetConfig(),
crcache.Options{
Scheme: mgr.GetScheme(), Mapper: mgr.GetRESTMapper(),
},
)
if err != nil {
return fmt.Errorf("unable to create boxcutter tracking cache: %v", err)
}
if err := mgr.Add(trackingCache); err != nil {
return fmt.Errorf("unable to add tracking cache to manager: %v", err)
}
if err = (&controllers.ClusterExtensionRevisionReconciler{
Client: mgr.GetClient(),
RevisionEngine: machinery.NewRevisionEngine(
machinery.NewPhaseEngine(
machinery.NewObjectEngine(
mgr.GetScheme(), trackingCache, mgr.GetClient(),
ownerhandling.NewNative(mgr.GetScheme()),
machinery.NewComparator(ownerhandling.NewNative(mgr.GetScheme()), discoveryClient, mgr.GetScheme(), boxcutterSystemPrefixFieldOwner),
boxcutterSystemPrefixFieldOwner, boxcutterSystemPrefixFieldOwner,
),
validation.NewClusterPhaseValidator(mgr.GetRESTMapper(), mgr.GetClient()),
),
validation.NewRevisionValidator(), mgr.GetClient(),
),
TrackingCache: trackingCache,
}).SetupWithManager(mgr); err != nil {
return fmt.Errorf("unable to setup ClusterExtensionRevision controller: %w", err)
}
return nil
}
func setupHelm(
mgr manager.Manager,
ceReconciler *controllers.ClusterExtensionReconciler,
preflights []applier.Preflight,
ceController crcontroller.Controller,
clusterExtensionFinalizers crfinalizer.Registerer,
) error {
coreClient, err := corev1client.NewForConfig(mgr.GetConfig())
if err != nil {
return fmt.Errorf("unable to create core client: %w", err)
}
tokenGetter := authentication.NewTokenGetter(coreClient, authentication.WithExpirationDuration(1*time.Hour))
clientRestConfigMapper := action.ServiceAccountRestConfigMapper(tokenGetter)
if features.OperatorControllerFeatureGate.Enabled(features.SyntheticPermissions) {
clientRestConfigMapper = action.SyntheticUserRestConfigMapper(clientRestConfigMapper)
}
cfgGetter, err := helmclient.NewActionConfigGetter(mgr.GetConfig(), mgr.GetRESTMapper(),
helmclient.StorageDriverMapper(action.ChunkedStorageDriverMapper(coreClient, mgr.GetAPIReader(), cfg.systemNamespace)),
helmclient.ClientNamespaceMapper(func(obj client.Object) (string, error) {
ext := obj.(*ocv1.ClusterExtension)
return ext.Spec.Namespace, nil
}),
helmclient.ClientRestConfigMapper(clientRestConfigMapper),
)
if err != nil {
return fmt.Errorf("unable to create helm action config getter: %w", err)
}
acg, err := action.NewWrappedActionClientGetter(cfgGetter,
helmclient.WithFailureRollbacks(false),
)
if err != nil {
return fmt.Errorf("unable to create helm action client getter: %w", err)
}
// determine if PreAuthorizer should be enabled based on feature gate
var preAuth authorization.PreAuthorizer
if features.OperatorControllerFeatureGate.Enabled(features.PreflightPermissions) {
preAuth = authorization.NewRBACPreAuthorizer(mgr.GetClient())
}
cm := contentmanager.NewManager(clientRestConfigMapper, mgr.GetConfig(), mgr.GetRESTMapper())
err = clusterExtensionFinalizers.Register(controllers.ClusterExtensionCleanupContentManagerCacheFinalizer, finalizers.FinalizerFunc(func(ctx context.Context, obj client.Object) (crfinalizer.Result, error) {
ext := obj.(*ocv1.ClusterExtension)
err := cm.Delete(ext)
return crfinalizer.Result{}, err
}))
if err != nil {
setupLog.Error(err, "unable to register content manager cleanup finalizer")
return err
}
certProvider := getCertificateProvider()
// now initialize the helmApplier, assigning the potentially nil preAuth
ceReconciler.Applier = &applier.Helm{
ActionClientGetter: acg,
Preflights: preflights,
BundleToHelmChartConverter: &convert.BundleToHelmChartConverter{
BundleRenderer: registryv1.Renderer,
CertificateProvider: certProvider,
IsWebhookSupportEnabled: certProvider != nil,
},
HelmReleaseToObjectsConverter: &applier.HelmReleaseToObjectsConverter{},
PreAuthorizer: preAuth,
Watcher: ceController,
Manager: cm,
}
ceReconciler.RevisionStatesGetter = &controllers.HelmRevisionStatesGetter{ActionClientGetter: acg}
return nil
}
func main() {
if err := operatorControllerCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}