forked from open-telemetry/opentelemetry-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
676 lines (606 loc) · 25.2 KB
/
main.go
File metadata and controls
676 lines (606 loc) · 25.2 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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"net"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
cmv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
configv1 "github.com/openshift/api/config/v1"
routev1 "github.com/openshift/api/route/v1"
openshifttls "github.com/openshift/controller-runtime-common/pkg/tls"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
colfeaturegate "go.opentelemetry.io/collector/featuregate"
"go.uber.org/zap/zapcore"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"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/manager"
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
otelv1alpha1 "github.com/open-telemetry/opentelemetry-operator/apis/v1alpha1"
otelv1beta1 "github.com/open-telemetry/opentelemetry-operator/apis/v1beta1"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/certmanager"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/collector"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/opampbridge"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/openshift"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/prometheus"
"github.com/open-telemetry/opentelemetry-operator/internal/autodetect/targetallocator"
"github.com/open-telemetry/opentelemetry-operator/internal/components"
"github.com/open-telemetry/opentelemetry-operator/internal/config"
"github.com/open-telemetry/opentelemetry-operator/internal/controllers"
"github.com/open-telemetry/opentelemetry-operator/internal/fips"
"github.com/open-telemetry/opentelemetry-operator/internal/instrumentation"
instrumentationupgrade "github.com/open-telemetry/opentelemetry-operator/internal/instrumentation/upgrade"
collectorManifests "github.com/open-telemetry/opentelemetry-operator/internal/manifests/collector"
openshiftDashboards "github.com/open-telemetry/opentelemetry-operator/internal/openshift/dashboards"
operatormetrics "github.com/open-telemetry/opentelemetry-operator/internal/operator-metrics"
"github.com/open-telemetry/opentelemetry-operator/internal/operatornetworkpolicy"
"github.com/open-telemetry/opentelemetry-operator/internal/rbac"
"github.com/open-telemetry/opentelemetry-operator/internal/version"
wh "github.com/open-telemetry/opentelemetry-operator/internal/webhook"
"github.com/open-telemetry/opentelemetry-operator/internal/webhook/podmutation"
"github.com/open-telemetry/opentelemetry-operator/pkg/featuregate"
"github.com/open-telemetry/opentelemetry-operator/pkg/sidecar"
)
var (
scheme = k8sruntime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(otelv1alpha1.AddToScheme(scheme))
utilruntime.Must(otelv1beta1.AddToScheme(scheme))
utilruntime.Must(networkingv1.AddToScheme(scheme))
utilruntime.Must(configv1.AddToScheme(scheme))
// +kubebuilder:scaffold:scheme
}
func main() {
cfg := config.New()
cliFlags := config.CreateCLIParser(cfg)
// registers any flags that underlying libraries might use
opts := zap.Options{}
var zapFlagSet flag.FlagSet
opts.BindFlags(&zapFlagSet)
cliFlags.AddGoFlagSet(&zapFlagSet)
featureGates := featuregate.Flags(colfeaturegate.GlobalRegistry())
cliFlags.AddGoFlagSet(featureGates)
var configFile string
cliFlags.StringVar(&configFile, "config-file", "", "Path to config file")
if err := cliFlags.Parse(os.Args[1:]); err != nil {
panic(err)
}
err := cfg.Apply(configFile)
if err != nil {
fmt.Printf("configuration error: %v\n", err)
os.Exit(1)
}
opts.EncoderConfigOptions = append(opts.EncoderConfigOptions, func(ec *zapcore.EncoderConfig) {
ec.MessageKey = cfg.Zap.MessageKey
ec.LevelKey = cfg.Zap.LevelKey
ec.TimeKey = cfg.Zap.TimeKey
if cfg.Zap.LevelFormat == "lowercase" {
ec.EncodeLevel = zapcore.LowercaseLevelEncoder
} else {
ec.EncodeLevel = zapcore.CapitalLevelEncoder
}
})
logger := zap.New(zap.UseFlagOptions(&opts))
ctrl.SetLogger(logger)
configLog := ctrl.Log.WithName("config")
v := version.Get()
logger.Info("Starting the OpenTelemetry Operator",
"opentelemetry-operator", v.Operator,
"build-date", v.BuildDate,
"go-version", v.Go,
"go-arch", runtime.GOARCH,
"go-os", runtime.GOOS,
"feature-gates", featureGates.Lookup(featuregate.FeatureGatesFlag).Value.String(),
"config", cfg.ToStringMap(),
)
restConfig := ctrl.GetConfigOrDie()
var namespaces map[string]cache.Config
watchNamespace, found := os.LookupEnv("WATCH_NAMESPACE")
if found {
setupLog.Info("watching namespace(s)", "namespaces", watchNamespace)
namespaces = map[string]cache.Config{}
for ns := range strings.SplitSeq(watchNamespace, ",") {
namespaces[ns] = cache.Config{}
}
} else {
setupLog.Info("the env var WATCH_NAMESPACE isn't set, watching all namespaces")
}
// see https://github.com/openshift/library-go/blob/4362aa519714a4b62b00ab8318197ba2bba51cb7/pkg/config/leaderelection/leaderelection.go#L104
leaseDuration := time.Second * 137
renewDeadline := time.Second * 107
retryPeriod := time.Second * 26
optionsTlSOptsFuncs := []func(*tls.Config){
func(config *tls.Config) {
if err = cfg.TLS.ApplyTLSConfig(config); err != nil {
setupLog.Error(err, "error setting up TLS")
}
},
}
var initialTLSProfileSpec configv1.TLSProfileSpec
// Fetch TLS profile from the cluster if enabled
if cfg.TLS.UseClusterProfile {
// Create a temporary client for TLS profile fetch (before the manager is created).
// The TLS profile should be set before the manager starts.
tempClient, errClient := client.New(restConfig, client.Options{Scheme: scheme})
if errClient != nil {
setupLog.Error(errClient, "unable to create temporary client for TLS profile fetch")
os.Exit(1)
}
// Fetch initial TLS profile using controller-runtime-common
initialTLSProfileSpec, err = openshifttls.FetchAPIServerTLSProfile(context.Background(), tempClient)
if err != nil {
setupLog.Error(err, "unable to get TLS profile from cluster")
os.Exit(1)
}
// Convert to TLS options function for operator's own TLS (webhooks, metrics)
tlsConfigFunc, unsupportedCiphers := openshifttls.NewTLSConfigFromProfile(initialTLSProfileSpec)
if len(unsupportedCiphers) > 0 {
setupLog.Info("some TLS ciphers from cluster profile are not supported by Go", "unsupportedCiphers", unsupportedCiphers)
}
// Add cluster profile to the TLS funcs, it will override the statically provided config.
optionsTlSOptsFuncs = append(optionsTlSOptsFuncs, tlsConfigFunc)
}
if cfg.TLS.ConfigureOperands {
tlsCfg := &tls.Config{}
for _, t := range optionsTlSOptsFuncs {
t(tlsCfg)
}
cfg.Internal.OperandTLSProfile = components.NewStaticTLSProfile(tlsCfg.MinVersion, tlsCfg.CipherSuites)
}
// Configure metrics server options
metricsOptions := metricsserver.Options{
BindAddress: cfg.MetricsAddr,
}
if cfg.MetricsSecure {
metricsOptions.SecureServing = true
metricsOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
metricsOptions.TLSOpts = optionsTlSOptsFuncs
if cfg.MetricsTLSCertFile != "" && cfg.MetricsTLSKeyFile != "" {
metricsOptions.CertDir = filepath.Dir(cfg.MetricsTLSCertFile)
metricsOptions.CertName = filepath.Base(cfg.MetricsTLSCertFile)
metricsOptions.KeyName = filepath.Base(cfg.MetricsTLSKeyFile)
}
}
mgrOptions := ctrl.Options{
Scheme: scheme,
Metrics: metricsOptions,
HealthProbeBindAddress: cfg.ProbeAddr,
LeaderElection: cfg.EnableLeaderElection,
LeaderElectionID: "9f7554c3.opentelemetry.io",
LeaderElectionReleaseOnCancel: true,
LeaseDuration: &leaseDuration,
RenewDeadline: &renewDeadline,
RetryPeriod: &retryPeriod,
PprofBindAddress: cfg.PprofAddr,
WebhookServer: webhook.NewServer(webhook.Options{
Port: cfg.WebhookPort,
TLSOpts: optionsTlSOptsFuncs,
}),
Cache: cache.Options{
DefaultNamespaces: namespaces,
},
}
mgr, err := ctrl.NewManager(restConfig, mgrOptions)
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
clientset, err := kubernetes.NewForConfig(mgr.GetConfig())
if err != nil {
setupLog.Error(err, "failed to create kubernetes clientset")
}
// Discover Kubernetes API server info from EndpointSlices for network policies
if err = discoverKubeAPIServer(context.Background(), clientset, &cfg); err != nil {
setupLog.Info("Failed to discover Kubernetes API server from EndpointSlice", "error", err)
}
// Create a cancellable context for graceful shutdown on TLS profile change
signalCtx := ctrl.SetupSignalHandler()
ctx, cancel := context.WithCancel(signalCtx)
defer cancel()
// Setup TLS profile watcher for graceful restart on TLS profile change.
// When the cluster's TLS security profile changes (e.g., from Intermediate to Modern),
// the watcher detects this and cancels the context, triggering a graceful shutdown.
// The operator pod will restart and apply the new TLS settings to webhooks, metrics,
// and operand configurations. This approach is recommended by OpenShift because:
// 1. TLS profile changes are cluster-level security policy changes
// 2. All connections (existing and new) should use the new profile uniformly
// 3. It avoids complexity of hot-reloading TLS config on existing connections
if cfg.TLS.UseClusterProfile {
watcher := &openshifttls.SecurityProfileWatcher{
Client: mgr.GetClient(),
InitialTLSProfileSpec: initialTLSProfileSpec,
OnProfileChange: func(_ context.Context, _, _ configv1.TLSProfileSpec) {
setupLog.Info("TLS security profile changed, triggering graceful restart")
cancel()
},
}
if err = watcher.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to setup TLS profile watcher")
os.Exit(1)
}
}
// Apply feature gates from Config if set (could be from file or env vars)
// This must be done before checking feature gates like EnableOperatorNetworkPolicy
if cfg.FeatureGates != "" {
configLog.Info("Applying feature gates from configuration", "gates", cfg.FeatureGates)
if err = featuregate.ApplyFeatureGateOverrides(cfg.FeatureGates); err != nil {
setupLog.Error(err, "failed to apply feature gate overrides")
os.Exit(1)
}
}
if cfg.OpenshiftCreateDashboard {
dashErr := mgr.Add(openshiftDashboards.NewDashboardManagement(clientset))
if dashErr != nil {
setupLog.Error(dashErr, "failed to create the OpenShift dashboards")
}
}
if featuregate.EnableOperatorNetworkPolicy.IsEnabled() {
errNetworkPolicy := enableOperatorNetworkPolicy(cfg, clientset, mgr)
if errNetworkPolicy != nil {
setupLog.Error(errNetworkPolicy, "failed to create the Operator network policies")
os.Exit(1)
}
}
reviewer := rbac.NewReviewer(clientset)
// builds the operator's configuration
ad, err := autodetect.New(restConfig, reviewer)
if err != nil {
setupLog.Error(err, "failed to setup auto-detect routine")
os.Exit(1)
}
if err = autodetect.ApplyAutoDetect(ad, &cfg, configLog); err != nil {
setupLog.Error(err, "failed to autodetect config variables")
}
// Only add these to the scheme if they are available
if cfg.PrometheusCRAvailability == prometheus.Available {
setupLog.Info("Prometheus CRDs are installed, adding to scheme.")
utilruntime.Must(monitoringv1.AddToScheme(scheme))
} else {
setupLog.Info("Prometheus CRDs are not installed, skipping adding to scheme.")
}
if cfg.OpenShiftRoutesAvailability == openshift.RoutesAvailable {
setupLog.Info("Openshift CRDs are installed, adding to scheme.")
utilruntime.Must(routev1.Install(scheme))
} else {
setupLog.Info("Openshift CRDs are not installed, skipping adding to scheme.")
}
if cfg.CertManagerAvailability == certmanager.Available {
setupLog.Info("Cert-Manager is available to the operator, adding to scheme.")
utilruntime.Must(cmv1.AddToScheme(scheme))
if featuregate.EnableTargetAllocatorMTLS.IsEnabled() {
setupLog.Info("Securing the connection between the target allocator and the collector")
}
} else {
setupLog.Info("Cert-Manager is not available to the operator, skipping adding to scheme.")
}
if cfg.CollectorAvailability == collector.Available {
setupLog.Info("OpenTelemetryCollectorCRDSs are available to the operator")
} else {
setupLog.Info("OpenTelemetryCollectorCRDSs are not available to the operator")
if !cfg.IgnoreMissingCollectorCRDs {
setupLog.Error(errors.New("missing OpenTelemetryCollector CRDs"), "The OpenTelemetryCollector CRDs are not present in the cluster. Set ignore_missing_collector_crds to true or install the CRDs in the cluster.")
os.Exit(1)
}
}
setupLog.Info("Native sidecar", "enabled", cfg.Internal.NativeSidecarSupport)
if cfg.AnnotationsFilter != nil {
for _, basePattern := range cfg.AnnotationsFilter {
_, compileErr := regexp.Compile(basePattern)
if compileErr != nil {
setupLog.Error(compileErr, "could not compile the regexp pattern for Annotations filter")
}
}
}
if cfg.LabelsFilter != nil {
for _, basePattern := range cfg.LabelsFilter {
_, compileErr := regexp.Compile(basePattern)
if compileErr != nil {
setupLog.Error(compileErr, "could not compile the regexp pattern for Labels filter")
}
}
}
err = addDependencies(ctx, mgr, cfg)
if err != nil {
setupLog.Error(err, "failed to add/run bootstrap dependencies to the controller manager")
os.Exit(1)
}
var collectorReconciler *controllers.OpenTelemetryCollectorReconciler
if cfg.CollectorAvailability == collector.Available {
collectorReconciler = controllers.NewReconciler(controllers.Params{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("OpenTelemetryCollector"),
Scheme: mgr.GetScheme(),
Config: cfg,
Recorder: mgr.GetEventRecorderFor("opentelemetry-operator"),
Reviewer: reviewer,
Version: v,
})
if err = collectorReconciler.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "OpenTelemetryCollector")
os.Exit(1)
}
}
if cfg.TargetAllocatorAvailability == targetallocator.Available {
if err = controllers.NewTargetAllocatorReconciler(
mgr.GetClient(),
mgr.GetScheme(),
mgr.GetEventRecorderFor("targetallocator"),
cfg,
ctrl.Log.WithName("controllers").WithName("TargetAllocator"),
).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "TargetAllocator")
os.Exit(1)
}
}
if cfg.OpAmpBridgeAvailability == opampbridge.Available {
if err = controllers.NewOpAMPBridgeReconciler(controllers.OpAMPBridgeReconcilerParams{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("OpAMPBridge"),
Scheme: mgr.GetScheme(),
Config: cfg,
Recorder: mgr.GetEventRecorderFor("opamp-bridge"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "OpAMPBridge")
os.Exit(1)
}
}
if featuregate.EnableClusterObservability.IsEnabled() {
setupLog.Info("ClusterObservability feature is enabled")
if err = controllers.NewClusterObservabilityReconciler(controllers.ClusterObservabilityReconcilerParams{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("ClusterObservability"),
Scheme: mgr.GetScheme(),
Config: cfg,
Recorder: mgr.GetEventRecorderFor("cluster-observability"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ClusterObservability")
os.Exit(1)
}
} else {
setupLog.Info("ClusterObservability feature is disabled")
}
if cfg.PrometheusCRAvailability == prometheus.Available && cfg.CreateServiceMonitorOperatorMetrics {
operatorMetrics, opError := operatormetrics.NewOperatorMetrics(mgr.GetConfig(), scheme, ctrl.Log.WithName("operator-metrics-sm"))
if opError != nil {
setupLog.Error(opError, "Failed to create the operator metrics SM")
}
err = mgr.Add(operatorMetrics)
if err != nil {
setupLog.Error(err, "Failed to add the operator metrics SM")
}
}
if cfg.EnableWebhooks {
var crdMetrics *otelv1beta1.Metrics
if cfg.EnableCRMetrics {
meterProvider, metricsErr := otelv1beta1.BootstrapMetrics()
if metricsErr != nil {
setupLog.Error(metricsErr, "Error bootstrapping CRD metrics")
}
crdMetrics, err = otelv1beta1.NewMetrics(meterProvider, ctx, mgr.GetAPIReader())
if err != nil {
setupLog.Error(err, "Error init CRD metrics")
}
}
if cfg.CollectorAvailability == collector.Available {
bv := func(ctx context.Context, collector otelv1beta1.OpenTelemetryCollector) admission.Warnings {
var warnings admission.Warnings
params, newErr := collectorReconciler.GetParams(ctx, collector)
if err != nil {
warnings = append(warnings, newErr.Error())
return warnings
}
params.ErrorAsWarning = true
_, newErr = collectorManifests.Build(params)
if newErr != nil {
warnings = append(warnings, newErr.Error())
return warnings
}
return warnings
}
var fipsCheck fips.FIPSCheck
if ad.FIPSEnabled(ctx) {
receivers, exporters, processors, extensions := parseFipsFlag(cfg.FipsDisabledComponents)
logger.Info("Fips disabled components", "receivers", receivers, "exporters", exporters, "processors", processors, "extensions", extensions)
fipsCheck = fips.NewFipsCheck(receivers, exporters, processors, extensions)
}
// TLS defaults for operands are now applied at reconciliation time (ConfigMap generation)
// via cfg.Internal.OperandTLSProfile, which was set earlier in this function.
// This ensures collectors automatically get updated TLS settings when the operator
// restarts after a cluster TLS profile change.
if err = wh.SetupCollectorWebhook(mgr, cfg, reviewer, crdMetrics, bv, fipsCheck); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "OpenTelemetryCollector")
os.Exit(1)
}
}
if cfg.TargetAllocatorAvailability == targetallocator.Available {
if err = wh.SetupTargetAllocatorWebhook(mgr, cfg, reviewer); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "TargetAllocator")
os.Exit(1)
}
}
if err = wh.SetupInstrumentationWebhook(mgr, cfg); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "Instrumentation")
os.Exit(1)
}
decoder := admission.NewDecoder(mgr.GetScheme())
mgr.GetWebhookServer().Register("/mutate-v1-pod", &webhook.Admission{
Handler: podmutation.NewWebhookHandler(cfg, ctrl.Log.WithName("pod-webhook"), decoder, mgr.GetClient(),
[]podmutation.PodMutator{
sidecar.NewMutator(logger, cfg, mgr.GetClient()),
instrumentation.NewMutator(logger, mgr.GetClient(), mgr.GetEventRecorderFor("opentelemetry-operator"), cfg),
}),
})
if cfg.OpAmpBridgeAvailability == opampbridge.Available {
if err = wh.SetupOpAMPBridgeWebhook(mgr, cfg); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "OpAMPBridge")
os.Exit(1)
}
}
} else {
ctrl.Log.Info("Webhooks are disabled, operator is running an unsupported mode", "ENABLE_WEBHOOKS", "false")
}
// +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)
}
if cfg.EnableWebhooks {
if err := mgr.AddReadyzCheck("webhook", mgr.GetWebhookServer().StartedChecker()); err != nil {
setupLog.Error(err, "unable to set up webhook ready check")
os.Exit(1)
}
}
setupLog.Info("starting manager")
// NOTE: We enable LeaderElectionReleaseOnCancel, and to be safe we need to exit right after the manager does
if err := mgr.Start(ctx); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
func discoverKubeAPIServer(ctx context.Context, clientset kubernetes.Interface, cfg *config.Config) error {
endpointSlices, err := clientset.DiscoveryV1().EndpointSlices("default").List(ctx, metav1.ListOptions{
LabelSelector: "kubernetes.io/service-name=kubernetes",
})
if err != nil {
return fmt.Errorf("failed to list kubernetes EndpointSlices: %w", err)
}
if len(endpointSlices.Items) == 0 {
return errors.New("no EndpointSlice found for kubernetes service in default namespace")
}
for _, endpointSlice := range endpointSlices.Items {
// Extract port
for _, p := range endpointSlice.Ports {
if p.Port != nil && p.Name != nil && *p.Name == "https" {
cfg.Internal.KubeAPIServerPort = *p.Port
break
}
}
// Extract IPs from endpoints
for _, endpoint := range endpointSlice.Endpoints {
cfg.Internal.KubeAPIServerIPs = append(cfg.Internal.KubeAPIServerIPs, endpoint.Addresses...)
}
}
if cfg.Internal.KubeAPIServerPort == 0 {
return errors.New("no https port found in kubernetes EndpointSlice")
}
if len(cfg.Internal.KubeAPIServerIPs) == 0 {
return errors.New("no endpoint IPs found in kubernetes EndpointSlice")
}
setupLog.Info("Discovered Kubernetes API server", "port", cfg.Internal.KubeAPIServerPort, "ips", cfg.Internal.KubeAPIServerIPs)
return nil
}
func enableOperatorNetworkPolicy(cfg config.Config, clientset kubernetes.Interface, mgr ctrl.Manager) error {
operatorNamespace := os.Getenv("NAMESPACE")
if operatorNamespace == "" {
return errors.New("NAMESPACE environment variable is not set, it is rquired for the Operator Network Policy to work")
}
// Check if API server info was discovered
if cfg.Internal.KubeAPIServerPort == 0 || len(cfg.Internal.KubeAPIServerIPs) == 0 {
return errors.New("Kubernetes API server info not discovered from EndpointSlice") //nolint:staticcheck // ST1005
}
var policyOpts []operatornetworkpolicy.Option
policyOpts = append(policyOpts, operatornetworkpolicy.WithOperatorNamespace(operatorNamespace))
policyOpts = append(policyOpts, operatornetworkpolicy.WithAPIServerPort(cfg.Internal.KubeAPIServerPort))
policyOpts = append(policyOpts, operatornetworkpolicy.WithAPIServerIPs(cfg.Internal.KubeAPIServerIPs))
if cfg.OpenShiftRoutesAvailability == openshift.RoutesAvailable {
policyOpts = append(policyOpts, operatornetworkpolicy.WithAPISererPodLabelSelector(&metav1.LabelSelector{
MatchLabels: map[string]string{
"apiserver": "true",
},
}))
policyOpts = append(policyOpts, operatornetworkpolicy.WithAPISererNamespaceLabelSelector(&metav1.LabelSelector{
MatchLabels: map[string]string{
"kubernetes.io/metadata.name": "openshift-kube-apiserver",
},
}))
}
if cfg.EnableWebhooks {
//nolint:gosec // disable G115
policyOpts = append(policyOpts, operatornetworkpolicy.WithWebhookPort(int32(cfg.WebhookPort)))
}
if cfg.MetricsAddr != "" {
_, portStr, errParse := net.SplitHostPort(cfg.MetricsAddr)
if errParse != nil {
return fmt.Errorf("failed to parse port from metrics address: %w", errParse)
}
metricsPort, errParse := strconv.ParseInt(portStr, 10, 32)
if errParse != nil {
return fmt.Errorf("failed to parse port for the metrics address :%w", errParse)
}
policyOpts = append(policyOpts, operatornetworkpolicy.WithMetricsPort(int32(metricsPort)))
}
operatorNetworkPoliciesErr := mgr.Add(operatornetworkpolicy.NewOperatorNetworkPolicy(clientset, mgr.GetScheme(), policyOpts...))
if operatorNetworkPoliciesErr != nil {
return fmt.Errorf("failed to create the Operator network policies: %w", operatorNetworkPoliciesErr)
}
return nil
}
func addDependencies(_ context.Context, mgr ctrl.Manager, cfg config.Config) error {
// adds the upgrade mechanism to be executed once the manager is ready
err := mgr.Add(manager.RunnableFunc(func(c context.Context) error {
u := instrumentationupgrade.NewInstrumentationUpgrade(
mgr.GetClient(),
ctrl.Log.WithName("instrumentation-upgrade"),
mgr.GetEventRecorderFor("opentelemetry-operator"),
cfg,
)
return u.ManagedInstances(c)
}))
if err != nil {
return fmt.Errorf("failed to upgrade Instrumentation instances: %w", err)
}
return nil
}
func parseFipsFlag(fipsFlag string) (receivers, exporters, processors, extensions []string) {
split := strings.SplitSeq(fipsFlag, ",")
for val := range split {
val = strings.TrimSpace(val)
typeAndName := strings.Split(val, ".")
if len(typeAndName) == 2 {
componentType := typeAndName[0]
name := typeAndName[1]
switch componentType {
case "receiver":
receivers = append(receivers, name)
case "exporter":
exporters = append(exporters, name)
case "processor":
processors = append(processors, name)
case "extension":
extensions = append(extensions, name)
}
}
}
return receivers, exporters, processors, extensions
}