-
Notifications
You must be signed in to change notification settings - Fork 408
/
sync.go
2217 lines (1982 loc) · 84.3 KB
/
sync.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
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package operator
import (
"bytes"
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"net"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"time"
configclientscheme "github.com/openshift/client-go/config/clientset/versioned/scheme"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
kubeErrs "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/jsonmergepatch"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
configv1 "github.com/openshift/api/config/v1"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
mcfgv1alpha1 "github.com/openshift/api/machineconfiguration/v1alpha1"
v1alpha1 "github.com/openshift/api/machineconfiguration/v1alpha1"
opv1 "github.com/openshift/api/operator/v1"
features "github.com/openshift/api/features"
mcoac "github.com/openshift/client-go/operator/applyconfigurations/operator/v1"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
"github.com/openshift/library-go/pkg/operator/resource/resourceread"
mcoResourceApply "github.com/openshift/machine-config-operator/lib/resourceapply"
mcoResourceRead "github.com/openshift/machine-config-operator/lib/resourceread"
"github.com/openshift/machine-config-operator/pkg/apihelpers"
"github.com/openshift/machine-config-operator/pkg/controller/build"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
templatectrl "github.com/openshift/machine-config-operator/pkg/controller/template"
daemonconsts "github.com/openshift/machine-config-operator/pkg/daemon/constants"
"github.com/openshift/machine-config-operator/pkg/helpers"
"github.com/openshift/machine-config-operator/pkg/server"
"github.com/openshift/machine-config-operator/pkg/upgrademonitor"
"github.com/openshift/machine-config-operator/pkg/version"
autoscalingv1 "k8s.io/api/autoscaling/v1"
)
const (
requiredForUpgradeMachineConfigPoolLabelKey = "operator.machineconfiguration.openshift.io/required-for-upgrade"
)
var platformsRequiringCloudConf = sets.NewString(
string(configv1.AzurePlatformType),
string(configv1.GCPPlatformType),
string(configv1.OpenStackPlatformType),
string(configv1.VSpherePlatformType),
)
type manifestPaths struct {
clusterRoles []string
roleBindings []string
clusterRoleBindings []string
serviceAccounts []string
secrets []string
configMaps []string
roles []string
validatingAdmissionPolicies []string
validatingAdmissionPolicyBindings []string
}
const (
// Machine Config Controller manifest paths
mccClusterRoleManifestPath = "manifests/machineconfigcontroller/clusterrole.yaml"
mccEventsClusterRoleManifestPath = "manifests/machineconfigcontroller/events-clusterrole.yaml"
mccEventsRoleBindingDefaultManifestPath = "manifests/machineconfigcontroller/events-rolebinding-default.yaml"
mccEventsRoleBindingTargetManifestPath = "manifests/machineconfigcontroller/events-rolebinding-target.yaml"
mccClusterRoleBindingManifestPath = "manifests/machineconfigcontroller/clusterrolebinding.yaml"
mccServiceAccountManifestPath = "manifests/machineconfigcontroller/sa.yaml"
mccKubeRbacProxyConfigMapPath = "manifests/machineconfigcontroller/kube-rbac-proxy-config.yaml"
mccKubeRbacProxyPrometheusRolePath = "manifests/machineconfigcontroller/prometheus-rbac.yaml"
mccKubeRbacProxyPrometheusRoleBindingPath = "manifests/machineconfigcontroller/prometheus-rolebinding-target.yaml"
mccMachineConfigurationGuardsValidatingAdmissionPolicyPath = "manifests/machineconfigcontroller/machineconfiguration-guards-validatingadmissionpolicy.yaml"
mccMachineConfigurationGuardsValidatingAdmissionPolicyBindingPath = "manifests/machineconfigcontroller/machineconfiguration-guards-validatingadmissionpolicybinding.yaml"
mccMachineConfigPoolSelectorValidatingAdmissionPolicyPath = "manifests/machineconfigcontroller/custom-machine-config-pool-selector-validatingadmissionpolicy.yaml"
mccMachineConfigPoolSelectorValidatingAdmissionPolicyBindingPath = "manifests/machineconfigcontroller/custom-machine-config-pool-selector-validatingadmissionpolicybinding.yaml"
mccUpdateBootImagesValidatingAdmissionPolicyPath = "manifests/machineconfigcontroller/update-bootimages-validatingadmissionpolicy.yaml"
mccUpdateBootImagesValidatingAdmissionPolicyBindingPath = "manifests/machineconfigcontroller/update-bootimages-validatingadmissionpolicybinding.yaml"
// Machine OS Builder manifest paths
mobClusterRoleManifestPath = "manifests/machineosbuilder/clusterrole.yaml"
mobEventsClusterRoleManifestPath = "manifests/machineosbuilder/events-clusterrole.yaml"
mobEventsRoleBindingDefaultManifestPath = "manifests/machineosbuilder/events-rolebinding-default.yaml"
mobEventsRoleBindingTargetManifestPath = "manifests/machineosbuilder/events-rolebinding-target.yaml"
mobClusterRoleBindingServiceAccountManifestPath = "manifests/machineosbuilder/clusterrolebinding-service-account.yaml"
mobClusterRolebindingAnyUIDManifestPath = "manifests/machineosbuilder/clusterrolebinding-anyuid.yaml"
mobServiceAccountManifestPath = "manifests/machineosbuilder/sa.yaml"
// Machine Config Daemon manifest paths
mcdClusterRoleManifestPath = "manifests/machineconfigdaemon/clusterrole.yaml"
mcdEventsClusterRoleManifestPath = "manifests/machineconfigdaemon/events-clusterrole.yaml"
mcdEventsRoleBindingDefaultManifestPath = "manifests/machineconfigdaemon/events-rolebinding-default.yaml"
mcdEventsRoleBindingTargetManifestPath = "manifests/machineconfigdaemon/events-rolebinding-target.yaml"
mcdClusterRoleBindingManifestPath = "manifests/machineconfigdaemon/clusterrolebinding.yaml"
mcdServiceAccountManifestPath = "manifests/machineconfigdaemon/sa.yaml"
mcdDaemonsetManifestPath = "manifests/machineconfigdaemon/daemonset.yaml"
mcdKubeRbacProxyConfigMapPath = "manifests/machineconfigdaemon/kube-rbac-proxy-config.yaml"
mcdKubeRbacProxyPrometheusRolePath = "manifests/machineconfigdaemon/prometheus-rbac.yaml"
mcdKubeRbacProxyPrometheusRoleBindingPath = "manifests/machineconfigdaemon/prometheus-rolebinding-target.yaml"
mcdRolePath = "manifests/machineconfigdaemon/role.yaml"
mcdRoleBindingPath = "manifests/machineconfigdaemon/rolebinding.yaml"
mcdMCNGuardValidatingAdmissionPolicyPath = "manifests/machineconfigdaemon/mcn-guards-validatingadmissionpolicy.yaml"
mcdMCNGuardValidatingAdmissionPolicyBindingPath = "manifests/machineconfigdaemon/mcn-guards-validatingadmissionpolicybinding.yaml"
// Machine Config Server manifest paths
mcsClusterRoleManifestPath = "manifests/machineconfigserver/clusterrole.yaml"
mcsClusterRoleBindingManifestPath = "manifests/machineconfigserver/clusterrolebinding.yaml"
mcsCSRBootstrapRoleBindingManifestPath = "manifests/machineconfigserver/csr-bootstrap-role-binding.yaml"
mcsCSRRenewalRoleBindingManifestPath = "manifests/machineconfigserver/csr-renewal-role-binding.yaml"
mcsServiceAccountManifestPath = "manifests/machineconfigserver/sa.yaml"
mcsNodeBootstrapperServiceAccountManifestPath = "manifests/machineconfigserver/node-bootstrapper-sa.yaml"
mcsNodeBootstrapperTokenManifestPath = "manifests/machineconfigserver/node-bootstrapper-token.yaml"
mcsDaemonsetManifestPath = "manifests/machineconfigserver/daemonset.yaml"
// Machine OS puller manifest paths
mopRoleBindingManifestPath = "manifests/machine-os-puller/rolebinding.yaml"
mopServiceAccountManifestPath = "manifests/machine-os-puller/sa.yaml"
)
type syncFunc struct {
name string
fn func(config *renderConfig, co *configv1.ClusterOperator) error
}
type syncError struct {
task string
err error
}
func (optr *Operator) syncAll(syncFuncs []syncFunc) error {
co, err := optr.fetchClusterOperator()
if err != nil {
return err
}
// Deepcopy the cluster operator object. Pass it through each of the sync functions below. Some of the sync functions
// will modify the object status as needed. This will be then used to perform a "batch" update to the object at the end of this
// function. This helps minimize API calls.
//
// Note: syncRequiredMachineConfigPools(one of the syncFuncs) will update the object prior to the batch update
// For syncRequiredMachineConfigPools, this is because the operator may be rolling out a new
// MachineConfig and may get "stuck" in the polling block within that function until all required pools are done updating.
// By updating within syncRequiredMachineConfigPools, the operator is able to provide faster updates during the progression
// of the pool update.
updatedCO := co.DeepCopy()
optr.syncProgressingStatus(updatedCO)
var syncErr syncError
for _, sf := range syncFuncs {
startTime := time.Now()
syncErr = syncError{
task: sf.name,
err: sf.fn(optr.renderConfig, updatedCO),
}
if optr.inClusterBringup {
klog.Infof("[init mode] synced %s in %v", sf.name, time.Since(startTime))
}
if syncErr.err != nil {
// Keep rendering controllerconfig if the daemon sync fails so (among other things)
// our certificates don't expire.
// https://bugzilla.redhat.com/show_bug.cgi?id=2034883
if sf.name == "MachineConfigDaemon" {
if err := optr.safetySyncControllerConfig(optr.renderConfig); err != nil {
// we don't want this error to supersede the actual error
// it's just "oh also, we tried to save you, but that didn't work either"
klog.Errorf("Error performing safety controllerconfig sync: %v", err)
}
}
break
}
}
optr.syncDegradedStatus(updatedCO, syncErr)
optr.syncAvailableStatus(updatedCO)
optr.syncVersion(updatedCO)
optr.syncRelatedObjects(updatedCO)
syncUpgradeableStatusErr := optr.syncUpgradeableStatus(updatedCO)
syncClusterFleetEvaluationErr := optr.syncClusterFleetEvaluation(updatedCO)
// Batch update the Cluster Operator Status. This update will cause a resource conflict if
// syncRequiredMachineConfigPools has done an update prior to this. In such a case,
// updateClusterOperatorStatus will refetch the Cluster Operator object before updating the new status.
if _, err := optr.updateClusterOperatorStatus(co, &updatedCO.Status, nil); err != nil {
return fmt.Errorf("error updating cluster operator status: %w", err)
}
// Handle these errors after as CO status updates should have priority over this
if syncUpgradeableStatusErr != nil {
return fmt.Errorf("error syncingUpgradeableStatus: %w", syncUpgradeableStatusErr)
}
if syncClusterFleetEvaluationErr != nil {
return fmt.Errorf("error updating cluster operator status: %w", syncClusterFleetEvaluationErr)
}
if err := optr.syncMetrics(); err != nil {
return fmt.Errorf("error syncing metrics: %w", err)
}
if optr.inClusterBringup && syncErr.err == nil {
klog.Infof("Initialization complete")
optr.inClusterBringup = false
}
return syncErr.err
}
// Return true if kube-cloud-config ConfigMap is required.
func isKubeCloudConfigCMRequired(infra *configv1.Infrastructure) bool {
return infra.Spec.CloudConfig.Name != "" || isCloudConfRequired(infra)
}
// Return true if the platform requires a cloud.conf.
func isCloudConfRequired(infra *configv1.Infrastructure) bool {
if infra.Status.PlatformStatus == nil {
return false
}
return platformsRequiringCloudConf.Has(string(infra.Status.PlatformStatus.Type))
}
// Sync cloud config on supported platform from cloud.conf available in openshift-config-managed/kube-cloud-config ConfigMap.
func (optr *Operator) syncCloudConfig(spec *mcfgv1.ControllerConfigSpec, infra *configv1.Infrastructure) error {
cm, err := optr.clusterCmLister.ConfigMaps("openshift-config-managed").Get("kube-cloud-config")
if err != nil {
if apierrors.IsNotFound(err) {
if isKubeCloudConfigCMRequired(infra) {
// Return error only if the kube-cloud-config ConfigMap is required, otherwise proceeds further.
return fmt.Errorf("%s/%s configmap is required on platform %s but not found: %w",
"openshift-config-managed", "kube-cloud-config", infra.Status.PlatformStatus.Type, err)
}
return nil
}
return err
}
// Read cloud.conf from openshift-config-managed/kube-cloud-config ConfigMap.
cc, err := getCloudConfigFromConfigMap(cm, "cloud.conf")
if err != nil {
if isCloudConfRequired(infra) {
// Return error only if cloud.conf is required, otherwise proceeds further.
return fmt.Errorf("%s/%s configmap must have the %s key on platform %s but not found",
"openshift-config-managed", "kube-cloud-config", "cloud.conf", infra.Status.PlatformStatus.Type)
}
} else {
spec.CloudProviderConfig = cc
}
caCert, err := getCAsFromConfigMap(cm, "ca-bundle.pem")
if err == nil {
spec.CloudProviderCAData = caCert
}
return nil
}
//nolint:gocyclo
func (optr *Operator) syncRenderConfig(_ *renderConfig, _ *configv1.ClusterOperator) error {
if optr.inClusterBringup {
klog.V(4).Info("Starting inClusterBringup informers cache sync")
// sync now our own informers after having installed the CRDs
if !cache.WaitForCacheSync(optr.stopCh, optr.ccListerSynced) {
return fmt.Errorf("failed to sync caches for informers")
}
klog.V(4).Info("Finished inClusterBringup informers cache sync")
}
// sync up the images used by operands.
imgsRaw, err := os.ReadFile(optr.imagesFile)
if err != nil {
return err
}
imgs, err := ctrlcommon.ParseImagesFromBytes(imgsRaw)
if err != nil {
return err
}
optrVersion, _ := optr.vStore.Get("operator")
if imgs.ReleaseVersion != optrVersion {
return fmt.Errorf("refusing to read images.json version %q, operator version %q", imgs.ReleaseVersion, optrVersion)
}
// handle image registry certificates.
// parse these, add them to ctrlcfgspec and then handle these in the daemon write to disk function
cfg, err := optr.imgLister.Get("cluster")
if err != nil {
return err
}
imgRegistryUsrData := []mcfgv1.ImageRegistryBundle{}
if cfg.Spec.AdditionalTrustedCA.Name != "" {
cm, err := optr.clusterCmLister.ConfigMaps("openshift-config").Get(cfg.Spec.AdditionalTrustedCA.Name)
if err != nil {
klog.Warningf("could not find configmap specified in image.config.openshift.io/cluster with the name %s", cfg.Spec.AdditionalTrustedCA.Name)
} else {
newKeys := sets.StringKeySet(cm.Data).List()
newBinaryKeys := sets.StringKeySet(cm.BinaryData).List()
for _, key := range newKeys {
raw, err := base64.StdEncoding.DecodeString(cm.Data[key])
if err != nil {
imgRegistryUsrData = append(imgRegistryUsrData, mcfgv1.ImageRegistryBundle{
File: key,
Data: []byte(cm.Data[key]),
})
} else {
imgRegistryUsrData = append(imgRegistryUsrData, mcfgv1.ImageRegistryBundle{
File: key,
Data: raw,
})
}
}
for _, key := range newBinaryKeys {
imgRegistryUsrData = append(imgRegistryUsrData, mcfgv1.ImageRegistryBundle{
File: key,
Data: cm.BinaryData[key],
})
}
}
}
imgRegistryData := []mcfgv1.ImageRegistryBundle{}
cm, err := optr.clusterCmLister.ConfigMaps("openshift-config-managed").Get("image-registry-ca")
if err == nil {
newKeys := sets.StringKeySet(cm.Data).List()
newBinaryKeys := sets.StringKeySet(cm.BinaryData).List()
for _, key := range newKeys {
raw, err := base64.StdEncoding.DecodeString(cm.Data[key])
if err != nil {
imgRegistryData = append(imgRegistryData, mcfgv1.ImageRegistryBundle{
File: key,
Data: []byte(cm.Data[key]),
})
} else {
imgRegistryData = append(imgRegistryData, mcfgv1.ImageRegistryBundle{
File: key,
Data: raw,
})
}
}
for _, key := range newBinaryKeys {
imgRegistryData = append(imgRegistryData, mcfgv1.ImageRegistryBundle{
File: key,
Data: cm.BinaryData[key],
})
}
}
mergedData := append([]mcfgv1.ImageRegistryBundle{}, append(imgRegistryData, imgRegistryUsrData...)...)
caData := make(map[string]string, len(mergedData))
for _, CA := range mergedData {
caData[CA.File] = string(CA.Data)
}
cm, err = optr.clusterCmLister.ConfigMaps("openshift-config-managed").Get("merged-trusted-image-registry-ca")
if err != nil && !apierrors.IsNotFound(err) {
return err
}
cmAnnotations := make(map[string]string)
cmAnnotations["openshift.io/description"] = "Created and managed by the machine-config-operator"
if err != nil && apierrors.IsNotFound(err) {
klog.Infof("creating merged-trusted-image-registry-ca")
_, err = optr.kubeClient.CoreV1().ConfigMaps("openshift-config-managed").Create(
context.TODO(),
&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "merged-trusted-image-registry-ca",
Annotations: cmAnnotations,
},
Data: caData,
},
metav1.CreateOptions{},
)
if err != nil {
return err
}
} else {
cmMarshal, err := json.Marshal(cm)
if err != nil {
return err
}
newCM := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "merged-trusted-image-registry-ca",
Annotations: cmAnnotations,
},
Data: caData,
}
newCMMarshal, err := json.Marshal(newCM)
if err != nil {
return err
}
// check for deletedData
stillExists := false
for file, data := range cm.Data {
stillExists = false
// for each file in the configmap
// does it match ANY of the new files? if not, it is deleted.
for newfile, newdata := range caData {
if newfile == file && newdata == data {
stillExists = true
}
}
if !stillExists {
break
}
}
// check for newData
for file, data := range caData {
equal := false
for oldfile, olddata := range cm.Data {
if file == oldfile && data == olddata {
equal = true
}
}
if !equal || (!stillExists && len(cm.Data) > 0) {
klog.Info("Detecting changes in merged-trusted-image-registry-ca, creating patch")
if !equal {
klog.Infof("Diff is between file %s and its data %s which are new", file, data)
}
patchBytes, err := jsonmergepatch.CreateThreeWayJSONMergePatch(cmMarshal, newCMMarshal, cmMarshal)
klog.Infof("JSONPATCH: \n %s", string(patchBytes))
if err != nil {
return err
}
_, err = optr.kubeClient.CoreV1().ConfigMaps("openshift-config-managed").Patch(context.TODO(), "merged-trusted-image-registry-ca", types.MergePatchType, patchBytes, metav1.PatchOptions{})
if err != nil {
return fmt.Errorf("Could not patch merged-trusted-image-registry-ca with data %s: %w", string(patchBytes), err)
}
break
}
}
}
// sync up CAs
rootCA, err := optr.getCAsFromConfigMap("kube-system", "root-ca", "ca.crt")
if err != nil {
return err
}
bootstrapComplete := false
_, err = optr.clusterCmLister.ConfigMaps("kube-system").Get("bootstrap")
switch {
case err == nil:
bootstrapComplete = true
case apierrors.IsNotFound(err):
bootstrapComplete = false
case err != nil:
return err
default:
panic("math broke")
}
var kubeAPIServerServingCABytes []byte
var internalRegistryPullSecret []byte
// We only want to switch to the proper certificate bundle *after* we've generated our first controllerconfig.
// we need to make sure we generate a rendered-config that matches the "day 1" config that our nodes bootstrapped with and
// if bootstrapComplete happens while inClusterBringup == true, that matching MachineConfig will never get rendered and
// our pools will degrade (because the machine-config-daemon checks for it).
// See: https://issues.redhat.com/browse/OCPBUGS-5888
if bootstrapComplete && !optr.inClusterBringup {
// This is the ca-bundle published by the kube-apiserver that is used terminate client-certificates in the kube cluster.
// If the kubelet has a flag to check the in-cluster published ca bundle, that would be ideal.
kubeAPIServerServingCABytes, err = optr.getCAsFromConfigMap("openshift-config-managed", "kube-apiserver-client-ca", "ca-bundle.crt")
if err != nil {
return err
}
// Fetch the merged image registry pull secret file. The hope is that, by doing this after cluster bringup, an additional
// roll of machineconfig can be avoided. This can be moved to the controller once certs are removed from machine configs
// https://github.com/openshift/machine-config-operator/pull/3787
internalRegistryPullSecret, err = optr.getImageRegistryPullSecrets()
if err != nil {
klog.Errorf("Merging registry secrets failed with: %s", err)
return err
}
} else {
// this else block exists to find a way to match the rendering hash of the machineconfig that the installer creates.
// it seems that if the MCO cannot find an existing machineconfig, the operator and machines perma-wedge and it cannot
// install a new machineconfig. This is an unfortunate behavior that should be fixed eventually, but we need the kubelet
// to be able to trust the monitoring stack and this, combined with the no-reboot behavior, is enough to get us unstuck.
// as described by the name this is essentially static, but it no worse than what was here before. Since changes disrupt workloads
// and since must perfectly match what the installer creates, this is effectively frozen in time.
initialKubeAPIServerServingCABytes, err := optr.getCAsFromConfigMap("openshift-config", "initial-kube-apiserver-server-ca", "ca-bundle.crt")
if err != nil {
return err
}
// Fetch the following configmap and merge into the the initial CA. The CA is the same for the first year, and will rotate
// automatically afterwards.
kubeAPIServerServingCABytes, err = optr.getCAsFromConfigMap("openshift-kube-apiserver-operator", "kube-apiserver-to-kubelet-client-ca", "ca-bundle.crt")
if err != nil {
kubeAPIServerServingCABytes = initialKubeAPIServerServingCABytes
} else {
kubeAPIServerServingCABytes = mergeCertWithCABundle(initialKubeAPIServerServingCABytes, kubeAPIServerServingCABytes, "kube-apiserver-to-kubelet-signer")
}
// Blank out image registry pull secret if cluster is still in bringup
internalRegistryPullSecret = nil
}
bundle := make([]byte, 0)
bundle = append(bundle, rootCA...)
// sync up os image url
// TODO: this should probably be part of the imgs
oscontainer, osextensionscontainer, err := optr.getOsImageURLs(optr.namespace)
if err != nil {
return err
}
imgs.BaseOSContainerImage = oscontainer
imgs.BaseOSExtensionsContainerImage = osextensionscontainer
// sync up the ControllerConfigSpec
infra, network, proxy, dns, apiServer, err := optr.getGlobalConfig()
if err != nil {
return err
}
spec, err := createDiscoveredControllerConfigSpec(infra, network, proxy, dns)
if err != nil {
return err
}
var trustBundle []byte
certPool := x509.NewCertPool()
// this is the generic trusted bundle for things like self-signed registries.
additionalTrustBundle, err := optr.getCAsFromConfigMap("openshift-config", "user-ca-bundle", "ca-bundle.crt")
if err != nil && !apierrors.IsNotFound(err) {
return err
}
if len(additionalTrustBundle) > 0 {
if !certPool.AppendCertsFromPEM(additionalTrustBundle) {
return fmt.Errorf("configmap %s/%s doesn't have a valid PEM bundle", "openshift-config", "user-ca-bundle")
}
trustBundle = append(trustBundle, additionalTrustBundle...)
}
// this is the trusted bundle specific for proxy things and can differ from the generic one above.
if proxy != nil && proxy.Spec.TrustedCA.Name != "" && proxy.Spec.TrustedCA.Name != "user-ca-bundle" {
proxyTrustBundle, err := optr.getCAsFromConfigMap("openshift-config", proxy.Spec.TrustedCA.Name, "ca-bundle.crt")
if err != nil {
return err
}
if len(proxyTrustBundle) > 0 {
if !certPool.AppendCertsFromPEM(proxyTrustBundle) {
return fmt.Errorf("configmap %s/%s doesn't have a valid PEM bundle", "openshift-config", proxy.Spec.TrustedCA.Name)
}
trustBundle = append(trustBundle, proxyTrustBundle...)
}
}
spec.AdditionalTrustBundle = trustBundle
if err := optr.syncCloudConfig(spec, infra); err != nil {
return err
}
spec.KubeAPIServerServingCAData = kubeAPIServerServingCABytes
spec.RootCAData = bundle
spec.ImageRegistryBundleData = imgRegistryData
spec.ImageRegistryBundleUserData = imgRegistryUsrData
spec.PullSecret = &corev1.ObjectReference{Namespace: "openshift-config", Name: "pull-secret"}
spec.InternalRegistryPullSecret = internalRegistryPullSecret
spec.BaseOSContainerImage = imgs.BaseOSContainerImage
spec.BaseOSExtensionsContainerImage = imgs.BaseOSExtensionsContainerImage
spec.Images = map[string]string{
templatectrl.MachineConfigOperatorKey: imgs.MachineConfigOperator,
templatectrl.APIServerWatcherKey: imgs.MachineConfigOperator,
templatectrl.InfraImageKey: imgs.InfraImage,
templatectrl.KeepalivedKey: imgs.Keepalived,
templatectrl.CorednsKey: imgs.Coredns,
templatectrl.HaproxyKey: imgs.Haproxy,
templatectrl.BaremetalRuntimeCfgKey: imgs.BaremetalRuntimeCfg,
templatectrl.KubeRbacProxyKey: imgs.KubeRbacProxy,
}
ignitionHost, err := getIgnitionHost(&infra.Status)
if err != nil {
return err
}
pointerConfig, err := ctrlcommon.PointerConfig(ignitionHost, rootCA)
if err != nil {
return err
}
pointerConfigData, err := json.Marshal(pointerConfig)
if err != nil {
return err
}
isOnClusterBuildEnabled, err := optr.isOnClusterBuildFeatureGateEnabled()
if err != nil {
return err
}
if isOnClusterBuildEnabled {
moscs, err := optr.getAndValidateMachineOSConfigs()
if err != nil {
return err
}
// create renderConfig
optr.renderConfig = getRenderConfig(optr.namespace, string(kubeAPIServerServingCABytes), spec, &imgs.RenderConfigImages, infra.Status.APIServerInternalURL, pointerConfigData, moscs, apiServer)
} else {
optr.renderConfig = getRenderConfig(optr.namespace, string(kubeAPIServerServingCABytes), spec, &imgs.RenderConfigImages, infra.Status.APIServerInternalURL, pointerConfigData, nil, apiServer)
}
return nil
}
func getIgnitionHost(infraStatus *configv1.InfrastructureStatus) (string, error) {
internalURL := infraStatus.APIServerInternalURL
internalURLParsed, err := url.Parse(internalURL)
if err != nil {
return "", err
}
securePortStr := strconv.Itoa(server.SecurePort)
ignitionHost := fmt.Sprintf("%s:%s", internalURLParsed.Hostname(), securePortStr)
if infraStatus.PlatformStatus != nil {
switch infraStatus.PlatformStatus.Type {
case configv1.BareMetalPlatformType:
ignitionHost = net.JoinHostPort(infraStatus.PlatformStatus.BareMetal.APIServerInternalIPs[0], securePortStr)
case configv1.OpenStackPlatformType:
ignitionHost = net.JoinHostPort(infraStatus.PlatformStatus.OpenStack.APIServerInternalIPs[0], securePortStr)
case configv1.OvirtPlatformType:
ignitionHost = net.JoinHostPort(infraStatus.PlatformStatus.Ovirt.APIServerInternalIPs[0], securePortStr)
case configv1.VSpherePlatformType:
if infraStatus.PlatformStatus.VSphere != nil {
if len(infraStatus.PlatformStatus.VSphere.APIServerInternalIPs) > 0 {
ignitionHost = net.JoinHostPort(infraStatus.PlatformStatus.VSphere.APIServerInternalIPs[0], securePortStr)
}
}
}
}
return ignitionHost, nil
}
func (optr *Operator) syncMachineConfigPools(config *renderConfig, _ *configv1.ClusterOperator) error {
mcps := []string{
"manifests/master.machineconfigpool.yaml",
"manifests/worker.machineconfigpool.yaml",
}
for _, mcp := range mcps {
mcpBytes, err := renderAsset(config, mcp)
if err != nil {
return err
}
p := mcoResourceRead.ReadMachineConfigPoolV1OrDie(mcpBytes)
_, _, err = mcoResourceApply.ApplyMachineConfigPool(optr.client.MachineconfigurationV1(), p)
if err != nil {
return err
}
}
userDataTemplatePath := "manifests/userdata_secret.yaml"
pools, err := optr.mcpLister.List(labels.Everything())
if err != nil {
return err
}
// base64.StdEncoding.EncodeToString
for _, pool := range pools {
pointerConfigAsset := newAssetRenderer("pointer-config")
pointerConfigAsset.templateData = config.PointerConfig
pointerConfigData, err := pointerConfigAsset.render(struct{ Role string }{pool.Name})
if err != nil {
return err
}
userDataAsset := newAssetRenderer(userDataTemplatePath)
if err := userDataAsset.read(); err != nil {
return err
}
userDataAsset.addTemplateFuncs()
userdataBytes, err := userDataAsset.render(struct{ Role, PointerConfig string }{
pool.Name,
base64.StdEncoding.EncodeToString(pointerConfigData),
})
if err != nil {
return err
}
p := resourceread.ReadSecretV1OrDie(userdataBytes)
// Work around https://github.com/kubernetes/kubernetes/issues/3030 and https://github.com/kubernetes/kubernetes/issues/80609
pool.APIVersion = mcfgv1.GroupVersion.String()
pool.Kind = "MachineConfigPool"
p.ObjectMeta.OwnerReferences = []metav1.OwnerReference{
{
APIVersion: pool.APIVersion,
Kind: pool.Kind,
Name: pool.ObjectMeta.Name,
UID: pool.ObjectMeta.UID,
},
}
_, _, err = resourceapply.ApplySecret(context.TODO(), optr.kubeClient.CoreV1(), optr.libgoRecorder, p)
if err != nil {
return err
}
}
return nil
}
// we need to mimic this
func (optr *Operator) syncMachineConfigNodes(_ *renderConfig, _ *configv1.ClusterOperator) error {
fg, err := optr.fgAccessor.CurrentFeatureGates()
if err != nil {
klog.Errorf("Could not get fg: %v", err)
return err
}
if !fg.Enabled(features.FeatureGateMachineConfigNodes) {
return nil
}
nodes, err := optr.nodeLister.List(labels.Everything())
if err != nil {
return err
}
nodeMap := make(map[string]*corev1.Node, len(nodes))
for _, node := range nodes {
nodeMap[node.Name] = node
}
mcns, err := optr.client.MachineconfigurationV1alpha1().MachineConfigNodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return err
}
for _, node := range nodes {
if node.Status.Phase == corev1.NodePending || node.Status.Phase == corev1.NodePhase("Provisioning") {
continue
}
var pool string
var ok bool
if _, ok = node.Labels["node-role.kubernetes.io/worker"]; ok {
pool = "worker"
} else if _, ok = node.Labels["node-role.kubernetes.io/master"]; ok {
pool = "master"
}
newMCS := &v1alpha1.MachineConfigNode{
Spec: v1alpha1.MachineConfigNodeSpec{
Node: v1alpha1.MCOObjectReference{
Name: node.Name,
},
Pool: v1alpha1.MCOObjectReference{
Name: pool,
},
ConfigVersion: v1alpha1.MachineConfigNodeSpecMachineConfigVersion{
Desired: upgrademonitor.NotYetSet,
},
},
TypeMeta: metav1.TypeMeta{
Kind: "MachineConfigNode",
APIVersion: "machineconfiguration.openshift.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: node.Name,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "v1",
Name: node.ObjectMeta.Name,
Kind: "Node",
UID: node.ObjectMeta.UID,
},
},
},
}
mcsBytes, err := json.Marshal(newMCS)
if err != nil {
klog.Errorf("error rendering asset for MachineConfigNode %v", err)
return err
}
p := mcoResourceRead.ReadMachineConfigNodeV1OrDie(mcsBytes)
mcn, _, err := mcoResourceApply.ApplyMachineConfigNode(optr.client.MachineconfigurationV1alpha1(), p)
if err != nil {
return err
}
// if this is the first time we are applying the MCN and the node is ready, set the config version probably
if mcn.Spec.ConfigVersion.Desired == upgrademonitor.NotYetSet {
err = upgrademonitor.GenerateAndApplyMachineConfigNodeSpec(optr.fgAccessor, pool, node, optr.client)
if err != nil {
klog.Errorf("Error making MCN spec for Update Compatible: %v", err)
}
}
}
if mcns != nil {
for _, mcn := range mcns.Items {
if _, ok := nodeMap[mcn.Name]; !ok {
klog.Infof("Node %s has been removed, deleting associated MCN", mcn.Name)
optr.client.MachineconfigurationV1alpha1().MachineConfigNodes().Delete(context.TODO(), mcn.Name, metav1.DeleteOptions{})
}
}
}
return nil
}
func isApplyManifestErrorRetriable(err error) bool {
// Retry on brief rpc errors
// See https://issues.redhat.com/browse/OCPBUGS-24228 for more information.
// String compare isn't great, but could not find a good error type for this in the standard libraries
if strings.Contains(err.Error(), "rpc error") {
return true
}
// Retry on resource conflict errors, i.e "the object has been modified; please apply your changes to the latest version and try again"
// See last few comments on https://issues.redhat.com/browse/OCPBUGS-9108 for more information
if apierrors.IsConflict(err) {
return true
}
// Add any other errors to be added to the retry here.
klog.Infof("Skipping retry in ApplyManifests for error: %s", err)
return false
}
//nolint:gocyclo
func (optr *Operator) applyManifests(config *renderConfig, paths manifestPaths) error {
// Retry in case this is a short lived, transient issue.
// This does an exponential retry, up to 5 times before it eventually times out and causing a degrade.
return retry.OnError(retry.DefaultRetry, isApplyManifestErrorRetriable, func() error {
for _, path := range paths.clusterRoles {
crBytes, err := renderAsset(config, path)
if err != nil {
return err
}
cr := resourceread.ReadClusterRoleV1OrDie(crBytes)
_, _, err = resourceapply.ApplyClusterRole(context.TODO(), optr.kubeClient.RbacV1(), optr.libgoRecorder, cr)
if err != nil {
return err
}
}
for _, path := range paths.roles {
rBytes, err := renderAsset(config, path)
if err != nil {
return err
}
r := resourceread.ReadRoleV1OrDie(rBytes)
_, _, err = resourceapply.ApplyRole(context.TODO(), optr.kubeClient.RbacV1(), optr.libgoRecorder, r)
if err != nil {
return err
}
}
for _, path := range paths.roleBindings {
rbBytes, err := renderAsset(config, path)
if err != nil {
return err
}
rb := resourceread.ReadRoleBindingV1OrDie(rbBytes)
_, _, err = resourceapply.ApplyRoleBinding(context.TODO(), optr.kubeClient.RbacV1(), optr.libgoRecorder, rb)
if err != nil {
return err
}
}
for _, path := range paths.clusterRoleBindings {
crbBytes, err := renderAsset(config, path)
if err != nil {
return err
}
crb := resourceread.ReadClusterRoleBindingV1OrDie(crbBytes)
_, _, err = resourceapply.ApplyClusterRoleBinding(context.TODO(), optr.kubeClient.RbacV1(), optr.libgoRecorder, crb)
if err != nil {
return err
}
}
for _, path := range paths.serviceAccounts {
saBytes, err := renderAsset(config, path)
if err != nil {
return err
}
sa := resourceread.ReadServiceAccountV1OrDie(saBytes)
_, _, err = resourceapply.ApplyServiceAccount(context.TODO(), optr.kubeClient.CoreV1(), optr.libgoRecorder, sa)
if err != nil {
return err
}
}
for _, path := range paths.secrets {
sBytes, err := renderAsset(config, path)
if err != nil {
return err
}
s := resourceread.ReadSecretV1OrDie(sBytes)
_, _, err = resourceapply.ApplySecret(context.TODO(), optr.kubeClient.CoreV1(), optr.libgoRecorder, s)
if err != nil {
return err
}
}
for _, path := range paths.configMaps {
cmBytes, err := renderAsset(config, path)
if err != nil {
return err
}
cm := resourceread.ReadConfigMapV1OrDie(cmBytes)
_, _, err = resourceapply.ApplyConfigMap(context.TODO(), optr.kubeClient.CoreV1(), optr.libgoRecorder, cm)
if err != nil {
return err
}
}
fg, err := optr.fgAccessor.CurrentFeatureGates()
if err != nil {
return fmt.Errorf("could not get feature gates: %w", err)
}
if fg == nil {
return fmt.Errorf("received nil feature gates")
}
// Only sync validatingadmissionpolicy manifests if ValidatingAdmissionPolicy feature gate is enabled
if fg.Enabled(features.FeatureGateValidatingAdmissionPolicy) {
// These new apply functions have a resource cache in case there are duplicate CRs
noCache := resourceapply.NewResourceCache()
for _, path := range paths.validatingAdmissionPolicies {
vapBytes, err := renderAsset(config, path)
if err != nil {
return err
}
vap := resourceread.ReadValidatingAdmissionPolicyV1beta1OrDie(vapBytes)
_, _, err = resourceapply.ApplyValidatingAdmissionPolicyV1beta1(context.TODO(), optr.kubeClient.AdmissionregistrationV1beta1(), optr.libgoRecorder, vap, noCache)
if err != nil {
return err
}
}
for _, path := range paths.validatingAdmissionPolicyBindings {
vapbBytes, err := renderAsset(config, path)
if err != nil {
return err
}
vapb := resourceread.ReadValidatingAdmissionPolicyBindingV1beta1OrDie(vapbBytes)
_, _, err = resourceapply.ApplyValidatingAdmissionPolicyBindingV1beta1(context.TODO(), optr.kubeClient.AdmissionregistrationV1beta1(), optr.libgoRecorder, vapb, noCache)
if err != nil {
return err
}
}
}
return nil
})
}
// safetySyncControllerConfig is a special case render of the controllerconfig that we run when
// we need to keep syncing controllerconfig, but something (like daemon sync failing) is preventing
// us from getting to the actual controller sync
func (optr *Operator) safetySyncControllerConfig(config *renderConfig) error {
klog.Infof("Performing safety controllerconfig sync")
// If we have an existing controllerconfig, we might be able to keep rendering
existingCc, err := optr.ccLister.Get(ctrlcommon.ControllerConfigName)
if err != nil {
return err
}
// If there is an existing config, but we didn't render it (e.g. we are in the middle of an upgrade)
// we can't render a new one here, it won't succeed because the existing controller won't touch it
// and we'll time out waiting.
if existingCc.Annotations[daemonconsts.GeneratedByVersionAnnotationKey] != version.Raw {
return fmt.Errorf("Our version (%s) differs from controllerconfig (%s), can't do 'safety' controllerconfig sync until controller is updated", version.Raw, existingCc.Annotations[daemonconsts.GeneratedByVersionAnnotationKey])
}
// If we made it here, we should be able to sync controllerconfig, and the existing controller should handle it
return optr.syncControllerConfig(config)
}
// syncControllerConfig is NOT meant to be called as a separate 'top level" sync in syncAll,
// it is meant to be called as part of syncMachineConfigController because it will only succeed if