-
Notifications
You must be signed in to change notification settings - Fork 297
/
main.go
424 lines (378 loc) · 17 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
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
/*
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"
"fmt"
cmdutil "github.com/openshift/hypershift/cmd/util"
"github.com/openshift/hypershift/support/globalconfig"
"os"
"strings"
"time"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/go-logr/logr"
operatorv1 "github.com/openshift/api/operator/v1"
hyperapi "github.com/openshift/hypershift/api"
hyperv1 "github.com/openshift/hypershift/api/v1beta1"
awsutil "github.com/openshift/hypershift/cmd/infra/aws/util"
"github.com/openshift/hypershift/hypershift-operator/controllers/hostedcluster"
"github.com/openshift/hypershift/hypershift-operator/controllers/nodepool"
"github.com/openshift/hypershift/hypershift-operator/controllers/platform/aws"
"github.com/openshift/hypershift/hypershift-operator/controllers/proxy"
"github.com/openshift/hypershift/hypershift-operator/controllers/supportedversion"
"github.com/openshift/hypershift/hypershift-operator/controllers/uwmtelemetry"
"github.com/openshift/hypershift/pkg/version"
"github.com/openshift/hypershift/support/capabilities"
"github.com/openshift/hypershift/support/metrics"
"github.com/openshift/hypershift/support/releaseinfo"
"github.com/openshift/hypershift/support/upsert"
"github.com/openshift/hypershift/support/util"
hyperutil "github.com/openshift/hypershift/support/util"
"github.com/spf13/cobra"
"go.uber.org/zap/zapcore"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
crclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
func main() {
cmd := &cobra.Command{
Use: "hypershift-operator",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
os.Exit(1)
},
}
cmd.Version = version.String()
cmd.AddCommand(NewStartCommand())
if err := cmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
type StartOptions struct {
Namespace string
DeploymentName string
PodName string
MetricsAddr string
CertDir string
EnableOCPClusterMonitoring bool
EnableCIDebugOutput bool
ControlPlaneOperatorImage string
RegistryOverrides map[string]string
PrivatePlatform string
OIDCStorageProviderS3BucketName string
OIDCStorageProviderS3Region string
OIDCStorageProviderS3Credentials string
EnableUWMTelemetryRemoteWrite bool
}
func NewStartCommand() *cobra.Command {
ctrl.SetLogger(zap.New(zap.UseDevMode(true), zap.JSONEncoder(func(o *zapcore.EncoderConfig) {
o.EncodeTime = zapcore.RFC3339TimeEncoder
})))
cmd := &cobra.Command{
Use: "run",
Short: "Runs the Hypershift operator",
}
opts := StartOptions{
Namespace: "hypershift",
DeploymentName: "operator",
MetricsAddr: "0",
CertDir: "",
ControlPlaneOperatorImage: "",
RegistryOverrides: map[string]string{},
PrivatePlatform: string(hyperv1.NonePlatform),
OIDCStorageProviderS3Region: "",
OIDCStorageProviderS3Credentials: "",
}
cmd.Flags().StringVar(&opts.Namespace, "namespace", opts.Namespace, "The namespace this operator lives in")
cmd.Flags().StringVar(&opts.DeploymentName, "deployment-name", opts.DeploymentName, "Legacy flag, does nothing. Use --pod-name instead.")
cmd.Flags().StringVar(&opts.PodName, "pod-name", opts.PodName, "The name of the pod the operator runs in")
cmd.Flags().StringVar(&opts.MetricsAddr, "metrics-addr", opts.MetricsAddr, "The address the metric endpoint binds to.")
cmd.Flags().StringVar(&opts.CertDir, "cert-dir", opts.CertDir, "Path to the serving key and cert for manager")
cmd.Flags().StringVar(&opts.ControlPlaneOperatorImage, "control-plane-operator-image", opts.ControlPlaneOperatorImage, "A control plane operator image to use (defaults to match this operator if running in a deployment)")
cmd.Flags().BoolVar(&opts.EnableOCPClusterMonitoring, "enable-ocp-cluster-monitoring", opts.EnableOCPClusterMonitoring, "Development-only option that will make your OCP cluster unsupported: If the cluster Prometheus should be configured to scrape metrics")
cmd.Flags().BoolVar(&opts.EnableCIDebugOutput, "enable-ci-debug-output", false, "If extra CI debug output should be enabled")
cmd.Flags().StringToStringVar(&opts.RegistryOverrides, "registry-overrides", map[string]string{}, "registry-overrides contains the source registry string as a key and the destination registry string as value. Images before being applied are scanned for the source registry string and if found the string is replaced with the destination registry string. Format is: sr1=dr1,sr2=dr2")
cmd.Flags().StringVar(&opts.PrivatePlatform, "private-platform", opts.PrivatePlatform, "Platform on which private clusters are supported by this operator (supports \"AWS\" or \"None\")")
cmd.Flags().StringVar(&opts.OIDCStorageProviderS3BucketName, "oidc-storage-provider-s3-bucket-name", "", "Name of the bucket in which to store the clusters OIDC discovery information. Required for AWS guest clusters")
cmd.Flags().StringVar(&opts.OIDCStorageProviderS3Region, "oidc-storage-provider-s3-region", opts.OIDCStorageProviderS3Region, "Region in which the OIDC bucket is located. Required for AWS guest clusters")
cmd.Flags().StringVar(&opts.OIDCStorageProviderS3Credentials, "oidc-storage-provider-s3-credentials", opts.OIDCStorageProviderS3Credentials, "Location of the credentials file for the OIDC bucket. Required for AWS guest clusters.")
cmd.Flags().BoolVar(&opts.EnableUWMTelemetryRemoteWrite, "enable-uwm-telemetry-remote-write", opts.EnableUWMTelemetryRemoteWrite, "If true, enables a controller that ensures user workload monitoring is enabled and that it is configured to remote write telemetry metrics from control planes")
cmd.Run = func(cmd *cobra.Command, args []string) {
ctx, cancel := context.WithCancel(ctrl.SetupSignalHandler())
defer cancel()
if err := run(ctx, &opts, ctrl.Log.WithName("setup")); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
return cmd
}
func run(ctx context.Context, opts *StartOptions, log logr.Logger) error {
log.Info("Starting hypershift-operator-manager", "version", version.String())
restConfig := ctrl.GetConfigOrDie()
restConfig.UserAgent = "hypershift-operator-manager"
leaseDuration := time.Second * 60
renewDeadline := time.Second * 40
retryPeriod := time.Second * 15
mgr, err := ctrl.NewManager(restConfig, ctrl.Options{
Scheme: hyperapi.Scheme,
MetricsBindAddress: opts.MetricsAddr,
Port: 9443,
CertDir: opts.CertDir,
LeaderElection: true,
LeaderElectionID: "hypershift-operator-leader-elect",
LeaderElectionResourceLock: "leases",
LeaderElectionReleaseOnCancel: true,
LeaderElectionNamespace: opts.Namespace,
LeaseDuration: &leaseDuration,
RenewDeadline: &renewDeadline,
RetryPeriod: &retryPeriod,
})
if err != nil {
return fmt.Errorf("unable to start manager: %w", err)
}
kubeDiscoveryClient, err := discovery.NewDiscoveryClientForConfig(mgr.GetConfig())
if err != nil {
return fmt.Errorf("unable to create discovery client: %w", err)
}
mgmtClusterCaps, err := capabilities.DetectManagementClusterCapabilities(kubeDiscoveryClient)
if err != nil {
return fmt.Errorf("unable to detect cluster capabilities: %w", err)
}
lookupOperatorImage := func(userSpecifiedImage string) (string, error) {
if len(userSpecifiedImage) > 0 {
log.Info("using image from arguments", "image", userSpecifiedImage)
return userSpecifiedImage, nil
}
me := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: opts.Namespace, Name: opts.PodName}}
if err := mgr.GetAPIReader().Get(ctx, crclient.ObjectKeyFromObject(me), me); err != nil {
return "", fmt.Errorf("failed to get operator pod %s: %w", crclient.ObjectKeyFromObject(me), err)
}
// Use the container status to make sure we get the sha256 reference rather than a potentially
// floating tag.
for _, container := range me.Status.ContainerStatuses {
// TODO: could use downward API for this too, overkill?
if container.Name == "operator" {
return strings.TrimPrefix(container.ImageID, "docker-pullable://"), nil
}
}
return "", fmt.Errorf("couldn't locate operator container on deployment")
}
var operatorImage string
if err := wait.PollImmediate(5*time.Second, 30*time.Second, func() (bool, error) {
operatorImage, err = lookupOperatorImage(opts.ControlPlaneOperatorImage)
if err != nil {
return false, err
}
// Apparently this is occasionally set to an empty string
if operatorImage == "" {
log.Info("operator image is empty, retrying")
return false, nil
}
return true, nil
}); err != nil {
if err != nil {
return fmt.Errorf("failed to find operator image: %w", err)
}
}
log.Info("using hosted control plane operator image", "operator-image", operatorImage)
createOrUpdate := upsert.New(opts.EnableCIDebugOutput)
metricsSet, err := metrics.MetricsSetFromEnv()
if err != nil {
return err
}
log.Info("Using metrics set", "set", metricsSet.String())
// Convert RegistryOverrides flag to a map of string-to-slice of strings
registryOverrides := util.ConvertRegistryOverrideFlagDataType(opts.RegistryOverrides)
// Populate RegistryOverrides with ICSP from management cluster if no value is passed in the RegistryOverrides flag
if len(registryOverrides) == 0 {
client, err := cmdutil.GetClient()
if err != nil {
return err
}
registryOverrides, err = populateRegistryOverrides(ctx, client)
if err != nil {
return err
}
}
hostedClusterReconciler := &hostedcluster.HostedClusterReconciler{
Client: mgr.GetClient(),
ManagementClusterCapabilities: mgmtClusterCaps,
HypershiftOperatorImage: operatorImage,
ReleaseProvider: &releaseinfo.RegistryMirrorProviderDecorator{
Delegate: &releaseinfo.CachedProvider{
Inner: &releaseinfo.RegistryClientProvider{},
Cache: map[string]*releaseinfo.ReleaseImage{},
},
RegistryOverrides: registryOverrides,
},
EnableOCPClusterMonitoring: opts.EnableOCPClusterMonitoring,
EnableCIDebugOutput: opts.EnableCIDebugOutput,
ImageMetadataProvider: &util.RegistryClientImageMetadataProvider{},
MetricsSet: metricsSet,
}
if opts.OIDCStorageProviderS3BucketName != "" {
awsSession := awsutil.NewSession("hypershift-operator-oidc-bucket", opts.OIDCStorageProviderS3Credentials, "", "", opts.OIDCStorageProviderS3Region)
awsConfig := awsutil.NewConfig()
s3Client := s3.New(awsSession, awsConfig)
hostedClusterReconciler.S3Client = s3Client
hostedClusterReconciler.OIDCStorageProviderS3BucketName = opts.OIDCStorageProviderS3BucketName
}
if err := hostedClusterReconciler.SetupWithManager(mgr, createOrUpdate); err != nil {
return fmt.Errorf("unable to create controller: %w", err)
}
if opts.CertDir != "" {
if err := hostedcluster.SetupWebhookWithManager(mgr); err != nil {
return fmt.Errorf("unable to create webhook: %w", err)
}
}
// Since we dropped the validation webhook server we need to ensure this resource doesn't exist
// otherwise it will intercept kas requests and fail.
// TODO (alberto): dropped in 4.14.
validatingWebhookConfiguration := &admissionregistrationv1.ValidatingWebhookConfiguration{
TypeMeta: metav1.TypeMeta{
Kind: "ValidatingWebhookConfiguration",
APIVersion: admissionregistrationv1.SchemeGroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Namespace: opts.Namespace,
Name: hyperv1.GroupVersion.Group,
},
}
if err := mgr.GetClient().Delete(ctx, validatingWebhookConfiguration); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
}
if err := (&nodepool.NodePoolReconciler{
Client: mgr.GetClient(),
ReleaseProvider: &releaseinfo.RegistryMirrorProviderDecorator{
Delegate: &releaseinfo.CachedProvider{
Inner: &releaseinfo.RegistryClientProvider{},
Cache: map[string]*releaseinfo.ReleaseImage{},
},
RegistryOverrides: registryOverrides,
},
CreateOrUpdateProvider: createOrUpdate,
HypershiftOperatorImage: operatorImage,
ImageMetadataProvider: &util.RegistryClientImageMetadataProvider{},
}).SetupWithManager(mgr); err != nil {
return fmt.Errorf("unable to create controller: %w", err)
}
if mgmtClusterCaps.Has(capabilities.CapabilityProxy) {
if err := proxy.Setup(mgr, opts.Namespace, opts.DeploymentName); err != nil {
return fmt.Errorf("failed to set up the proxy controller: %w", err)
}
}
// Start platform-specific controllers
switch hyperv1.PlatformType(opts.PrivatePlatform) {
case hyperv1.AWSPlatform:
if err := (&aws.AWSEndpointServiceReconciler{
Client: mgr.GetClient(),
CreateOrUpdateProvider: createOrUpdate,
}).SetupWithManager(mgr); err != nil {
return fmt.Errorf("unable to create controller: %w", err)
}
}
// Start controller to manage supported versions configmap
if err := (supportedversion.New(mgr.GetClient(), createOrUpdate, opts.Namespace).
SetupWithManager(mgr)); err != nil {
return fmt.Errorf("unable to create supported version controller: %w", err)
}
// If enabled, start controller to ensure UWM stack is enabled and configured
// to remote write telemetry metrics
if opts.EnableUWMTelemetryRemoteWrite {
if err := (&uwmtelemetry.Reconciler{
Namespace: opts.Namespace,
Client: mgr.GetClient(),
CreateOrUpdateProvider: createOrUpdate,
}).SetupWithManager(mgr); err != nil {
return fmt.Errorf("unable to create uwm telemetry controller: %w", err)
}
}
// The mgr and therefore the cache is not started yet, thus we have to construct a client that
// directly reads from the api.
apiReadingClient, err := crclient.NewDelegatingClient(crclient.NewDelegatingClientInput{
CacheReader: mgr.GetAPIReader(),
Client: mgr.GetClient(),
})
if err != nil {
return fmt.Errorf("failed to construct api reading client: %w", err)
}
// If it exsists, block default ingress controller from admitting HCP private routes
ic := &operatorv1.IngressController{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
Namespace: "openshift-ingress-operator",
},
}
if err := apiReadingClient.Get(ctx, types.NamespacedName{Namespace: ic.Namespace, Name: ic.Name}, ic); err == nil {
if _, err := controllerutil.CreateOrUpdate(ctx, apiReadingClient, ic, func() error {
if ic.Spec.RouteSelector == nil {
ic.Spec.RouteSelector = &metav1.LabelSelector{}
}
if ic.Spec.RouteSelector.MatchExpressions == nil {
ic.Spec.RouteSelector.MatchExpressions = []metav1.LabelSelectorRequirement{}
}
for _, requirement := range ic.Spec.RouteSelector.MatchExpressions {
if requirement.Key != hyperutil.HCPRouteLabel {
continue
}
requirement.Operator = metav1.LabelSelectorOpDoesNotExist
return nil
}
ic.Spec.RouteSelector.MatchExpressions = append(ic.Spec.RouteSelector.MatchExpressions, metav1.LabelSelectorRequirement{
Key: hyperutil.HCPRouteLabel,
Operator: metav1.LabelSelectorOpDoesNotExist,
})
return nil
}); err != nil {
return fmt.Errorf("failed to reconcile default ingress controller: %w", err)
}
log.Info("reconciled default ingress controller")
}
if err := setupMetrics(mgr); err != nil {
return fmt.Errorf("failed to setup metrics: %w", err)
}
// Start the controllers
log.Info("starting manager")
return mgr.Start(ctx)
}
// populateRegistryOverrides returns a map of registry overrides from the management cluster
func populateRegistryOverrides(ctx context.Context, client crclient.Client) (map[string][]string, error) {
var icspMapping = make(map[string][]string)
var listOfICSP = globalconfig.ImageContentSourcePolicyList()
err := client.List(ctx, listOfICSP)
if err != nil {
return nil, err
}
// For each ICSP, map the source with each of its mirrors
for _, item := range listOfICSP.Items {
for _, registryDigestMirror := range item.Spec.RepositoryDigestMirrors {
source := registryDigestMirror.Source
for n := range registryDigestMirror.Mirrors {
icspMapping[source] = append(icspMapping[source], registryDigestMirror.Mirrors[n])
}
}
}
return icspMapping, nil
}