forked from openshift/sandboxed-containers-operator
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathopenshift_controller.go
2361 lines (2016 loc) · 81.2 KB
/
openshift_controller.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
/*
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 controllers
import (
"context"
"encoding/json"
"fmt"
"os"
"reflect"
"time"
"github.com/confidential-containers/cloud-api-adaptor/peerpodconfig-ctrl/api/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/labels"
ignTypes "github.com/coreos/ignition/v2/config/v3_2/types"
"github.com/go-logr/logr"
secv1 "github.com/openshift/api/security/v1"
mcfgv1 "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1"
mcfgconsts "github.com/openshift/machine-config-operator/pkg/daemon/constants"
kataconfigurationv1 "github.com/openshift/sandboxed-containers-operator/api/v1"
"github.com/openshift/sandboxed-containers-operator/internal/featuregates"
corev1 "k8s.io/api/core/v1"
nodeapi "k8s.io/api/node/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/workqueue"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// blank assignment to verify that KataConfigOpenShiftReconciler implements reconcile.Reconciler
// var _ reconcile.Reconciler = &KataConfigOpenShiftReconciler{}
// KataConfigOpenShiftReconciler reconciles a KataConfig object
type KataConfigOpenShiftReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
kataConfig *kataconfigurationv1.KataConfig
FeatureGates *featuregates.FeatureGates
}
const (
OperatorNamespace = "openshift-sandboxed-containers-operator"
dashboard_configmap_name = "grafana-dashboard-sandboxed-containers"
dashboard_configmap_namespace = "openshift-config-managed"
container_runtime_config_name = "kata-crio-config"
extension_mc_name = "50-enable-sandboxed-containers-extension"
DEFAULT_PEER_PODS = "10"
peerpodConfigCrdName = "peerpodconfig-openshift"
peerpodsMachineConfigPathLocation = "/config/peerpods"
peerpodsCrioMachineConfig = "50-kata-remote"
peerpodsCrioMachineConfigYaml = "mc-50-crio-config.yaml"
peerpodsKataRemoteMachineConfig = "40-worker-kata-remote-config"
peerpodsKataRemoteMachineConfigYaml = "mc-40-kata-remote-config.yaml"
peerpodsRuntimeClassName = "kata-remote"
peerpodsRuntimeClassCpuOverhead = "0.25"
peerpodsRuntimeClassMemOverhead = "350Mi"
)
// +kubebuilder:rbac:groups=kataconfiguration.openshift.io,resources=kataconfigs;kataconfigs/finalizers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=kataconfiguration.openshift.io,resources=kataconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments;daemonsets;replicasets;statefulsets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=daemonsets/finalizers,resourceNames=manager-role,verbs=update
// +kubebuilder:rbac:groups=node.k8s.io,resources=runtimeclasses,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=config.openshift.io,resources=clusterversions,verbs=get
// +kubebuilder:rbac:groups="";machineconfiguration.openshift.io,resources=nodes;machineconfigs;machineconfigpools;containerruntimeconfigs;pods;services;services/finalizers;endpoints;persistentvolumeclaims;events;configmaps;secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=security.openshift.io,resources=securitycontextconstraints,verbs=use;get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=namespaces,verbs=get;update
// +kubebuilder:rbac:groups="",resources=nodes/status,verbs=patch
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpodconfigs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpodconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpodconfigs/finalizers,verbs=update
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpods/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=confidentialcontainers.org,resources=peerpods/finalizers,verbs=update
// +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=mutatingwebhookconfigurations,verbs=get;list;watch;create;update;delete
// +kubebuilder:rbac:groups=config.openshift.io,resources=infrastructures,verbs=get;list;watch
// +kubebuilder:rbac:groups="batch",resources=jobs,verbs=create;get;list;watch;delete
// +kubebuilder:rbac:groups="",resources=pods/log,verbs=get
func (r *KataConfigOpenShiftReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = r.Log.WithValues("kataconfig", req.NamespacedName)
r.Log.Info("Reconciling KataConfig in OpenShift Cluster")
// Fetch the KataConfig instance
r.kataConfig = &kataconfigurationv1.KataConfig{}
err := r.Client.Get(context.TODO(), req.NamespacedName, r.kataConfig)
if err != nil {
if k8serrors.IsNotFound(err) {
// Request object not found, could have been deleted after ctrl request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
r.Log.Error(err, "Cannot retrieve kataConfig")
return ctrl.Result{}, err
}
if r.FeatureGates.IsEnabled(ctx, "timeTravel") {
r.Log.Info("TimeTravel feature is enabled. Performing feature-specific logic...")
}
return func() (ctrl.Result, error) {
// k8s resource correctness checking on creation/modification
// isn't fully reliable for matchExpressions. Specifically,
// it doesn't catch an invalid value of matchExpressions.operator.
// With this work-around we check early if our kata node selector
// is workable and bail out before making any changes to the
// cluster if it turns out it isn't.
_, err := r.getKataConfigNodeSelectorAsSelector()
if err != nil {
r.Log.Info("Invalid KataConfig.spec.kataConfigPoolSelector - please fix your KataConfig", "err", err)
return ctrl.Result{}, nil
}
// Check if the KataConfig instance is marked to be deleted, which is
// indicated by the deletion timestamp being set. However, don't let
// uninstallation commence if another operation (installation, update)
// is underway.
if r.kataConfig.GetDeletionTimestamp() != nil && !r.isInstalling() && !r.isUpdating() {
res, err := r.processKataConfigDeleteRequest()
updateErr := r.Client.Status().Update(context.TODO(), r.kataConfig)
// The finalizer test is to get rid of the
// "Operation cannot be fulfilled [...] Precondition failed"
// error which happens when returning from a reconciliation that
// deleted our KataConfig by removing its finalizer. So if the
// finalizer is missing the actual KataConfig object is probably
// already gone from the cluster, hence the error.
if updateErr != nil && controllerutil.ContainsFinalizer(r.kataConfig, kataConfigFinalizer) {
r.Log.Info("Updating KataConfig failed", "err", updateErr)
return ctrl.Result{}, updateErr
}
return res, err
}
res, err := r.processKataConfigInstallRequest()
if err != nil {
return res, err
}
updateErr := r.Client.Status().Update(context.TODO(), r.kataConfig)
if updateErr != nil {
return ctrl.Result{}, updateErr
}
cMap := r.processDashboardConfigMap()
if cMap == nil {
r.Log.Info("failed to generate config map for metrics dashboard")
return ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second}, nil
}
foundCm := &corev1.ConfigMap{}
err = r.Client.Get(context.TODO(), types.NamespacedName{Name: cMap.Name, Namespace: cMap.Namespace}, foundCm)
if err != nil {
if k8serrors.IsNotFound(err) {
r.Log.Info("Installing metrics dashboard")
err = r.Client.Create(context.TODO(), cMap)
if err != nil {
r.Log.Error(err, "Error when creating the dashboard configmap")
res = ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second}
}
} else {
r.Log.Error(err, "could not get dashboard info, try again")
res = ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second}
}
}
err = r.processLogLevel(r.kataConfig.Spec.LogLevel)
if err != nil {
res = ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second}
}
return res, err
}()
}
func makeContainerRuntimeConfig(desiredLogLevel string, mcpSelector *metav1.LabelSelector) *mcfgv1.ContainerRuntimeConfig {
return &mcfgv1.ContainerRuntimeConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: "machineconfiguration.openshift.io/v1",
Kind: "ContainerRuntimeConfig",
},
ObjectMeta: metav1.ObjectMeta{
Name: container_runtime_config_name,
},
Spec: mcfgv1.ContainerRuntimeConfigSpec{
MachineConfigPoolSelector: mcpSelector,
ContainerRuntimeConfig: &mcfgv1.ContainerRuntimeConfiguration{
LogLevel: desiredLogLevel,
},
},
}
}
func (r *KataConfigOpenShiftReconciler) processLogLevel(desiredLogLevel string) error {
if desiredLogLevel == "" {
r.Log.Info("desired logLevel value is empty, setting to default ('info')")
desiredLogLevel = "info"
}
ctrRuntimeCfg := &mcfgv1.ContainerRuntimeConfig{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: container_runtime_config_name}, ctrRuntimeCfg)
if err != nil {
if !k8serrors.IsNotFound(err) {
r.Log.Error(err, "could not get ContainerRuntimeConfig, try again")
return err
}
r.Log.Info("no existing ContainerRuntimeConfig found")
if desiredLogLevel == "info" {
// if there's no ContainerRuntimeConfig - meaning that logLevel
// wasn't set yet and thus is at the default value in the cluster -
// *and* the desired value is the default one as well, there's
// nothing to do
r.Log.Info("current and desired logLevel values are both default, no action necessary")
return nil
}
machineConfigPoolSelectorLabels := map[string]string{"pools.operator.machineconfiguration.openshift.io/kata-oc": ""}
isConvergedCluster, err := r.checkConvergedCluster()
if isConvergedCluster && err == nil {
machineConfigPoolSelectorLabels = map[string]string{"pools.operator.machineconfiguration.openshift.io/master": ""}
}
machineConfigPoolSelector := &metav1.LabelSelector{
MatchLabels: machineConfigPoolSelectorLabels,
}
ctrRuntimeCfg = makeContainerRuntimeConfig(desiredLogLevel, machineConfigPoolSelector)
r.Log.Info("creating ContainerRuntimeConfig")
err = r.Client.Create(context.TODO(), ctrRuntimeCfg)
if err != nil {
r.Log.Error(err, "error creating ContainerRuntimeConfig")
return err
}
r.Log.Info("ContainerRuntimeConfig created successfully")
} else {
r.Log.Info("existing ContainerRuntimeConfig found")
if ctrRuntimeCfg.Spec.ContainerRuntimeConfig.LogLevel == desiredLogLevel {
r.Log.Info("existing ContainerRuntimeConfig is up-to-date, no action necessary")
return nil
}
// We only update LogLevel and don't touch MachineConfigPoolSelector
// as that shouldn't be necessary. It selects an MCP based only on
// whether the cluster is converged or not. Assuming that being
// converged is an immutable property of any given cluster, the initial
// choice of MachineConfigPoolSelector value should always be valid.
ctrRuntimeCfg.Spec.ContainerRuntimeConfig.LogLevel = desiredLogLevel
r.Log.Info("updating ContainerRuntimeConfig")
err = r.Client.Update(context.TODO(), ctrRuntimeCfg)
if err != nil {
r.Log.Error(err, "error updating ContainerRuntimeConfig")
return err
}
r.Log.Info("ContainerRuntimeConfig updated successfully")
}
return nil
}
func (r *KataConfigOpenShiftReconciler) removeLogLevel() error {
r.Log.Info("removing logLevel ContainerRuntimeConfig")
ctrRuntimeCfg := &mcfgv1.ContainerRuntimeConfig{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: container_runtime_config_name}, ctrRuntimeCfg)
if err != nil {
if k8serrors.IsNotFound(err) {
r.Log.Info("no logLevel ContainerRuntimeConfig found, nothing to do")
return nil
} else {
r.Log.Info("could not get ContainerRuntimeConfig", "err", err)
return err
}
}
err = r.Client.Delete(context.TODO(), ctrRuntimeCfg)
if err != nil {
r.Log.Info("error deleting ContainerRuntimeConfig", "err", err)
return err
}
r.Log.Info("logLevel ContainerRuntimeConfig deleted successfully")
return nil
}
func (r *KataConfigOpenShiftReconciler) processDaemonsetForMonitor() *appsv1.DaemonSet {
var (
runPrivileged = false
runUserID = int64(1001)
runGroupID = int64(1001)
)
kataMonitorImage := os.Getenv("RELATED_IMAGE_KATA_MONITOR")
if len(kataMonitorImage) == 0 {
// kata-monitor image URL is generally impossible to verify or sanitise,
// with the empty value being pretty much the only exception where it's
// fairly clear what good it is. If we can only detect a single one
// out of an infinite number of bad values, we choose not to return an
// error here (giving an impression that we can actually detect errors)
// but just log this incident and plow ahead.
r.Log.Info("RELATED_IMAGE_KATA_MONITOR env var is unset or empty, kata-monitor pods will not run")
}
r.Log.Info("Creating monitor DaemonSet with image file: \"" + kataMonitorImage + "\"")
dsName := "openshift-sandboxed-containers-monitor"
dsLabels := map[string]string{
"name": dsName,
}
nodeSelector := r.getNodeSelectorAsMap()
return &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "DaemonSet",
},
ObjectMeta: metav1.ObjectMeta{
Name: dsName,
Namespace: OperatorNamespace,
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: dsLabels,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: dsLabels,
},
Spec: corev1.PodSpec{
ServiceAccountName: "monitor",
NodeSelector: nodeSelector,
Tolerations: []corev1.Toleration{
{
Operator: corev1.TolerationOpExists,
},
},
Containers: []corev1.Container{
{
Name: "kata-monitor",
Image: kataMonitorImage,
ImagePullPolicy: "Always",
SecurityContext: &corev1.SecurityContext{
Privileged: &runPrivileged,
RunAsUser: &runUserID,
RunAsGroup: &runGroupID,
SELinuxOptions: &corev1.SELinuxOptions{
Type: "osc_monitor.process",
},
},
Command: []string{"/usr/bin/kata-monitor", "--listen-address=:8090", "--log-level=debug", "--runtime-endpoint=/run/crio/crio.sock"},
VolumeMounts: []corev1.VolumeMount{
{
Name: "crio-sock",
MountPath: "/run/crio/",
},
{
Name: "sbs",
MountPath: "/run/vc/sbs/",
}},
},
},
Volumes: []corev1.Volume{
{
Name: "crio-sock",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/run/crio/",
},
},
},
{
Name: "sbs",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/run/vc/sbs/",
},
},
},
},
},
},
},
}
}
func (r *KataConfigOpenShiftReconciler) processDashboardConfigMap() *corev1.ConfigMap {
r.Log.Info("Creating sandboxed containers dashboard in the OpenShift console")
cmLabels := map[string]string{
"console.openshift.io/dashboard": "true",
}
// retrieve content of the dashboard from our own namespace
foundCm := &corev1.ConfigMap{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: dashboard_configmap_name, Namespace: OperatorNamespace}, foundCm)
if err != nil {
r.Log.Error(err, "could not get dashboard data")
return nil
}
return &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "ConfigMap",
},
ObjectMeta: metav1.ObjectMeta{
Name: dashboard_configmap_name,
Namespace: dashboard_configmap_namespace,
Labels: cmLabels,
},
Data: foundCm.Data,
}
}
func (r *KataConfigOpenShiftReconciler) newMCPforCR() *mcfgv1.MachineConfigPool {
lsr := metav1.LabelSelectorRequirement{
Key: "machineconfiguration.openshift.io/role",
Operator: metav1.LabelSelectorOpIn,
Values: []string{"kata-oc", "worker"},
}
mcp := &mcfgv1.MachineConfigPool{
TypeMeta: metav1.TypeMeta{
APIVersion: "machineconfiguration.openshift.io/v1",
Kind: "MachineConfigPool",
},
ObjectMeta: metav1.ObjectMeta{
Name: "kata-oc",
Labels: map[string]string{
// This label is added to make it possible to form a label
// selector that selects this MCP. One use case is the
// ContainerRuntimeConfig resource which selects MCPs based
// on labels and is used to implement KataConfig.spec.logLevel
// handling.
"pools.operator.machineconfiguration.openshift.io/kata-oc": "",
},
},
Spec: mcfgv1.MachineConfigPoolSpec{
MachineConfigSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{lsr},
},
NodeSelector: r.getNodeSelectorAsLabelSelector(),
},
}
return mcp
}
func getExtensionName() string {
// RHCOS uses "sandboxed-containers" as thats resolved/translated in the machine-config-operator to "kata-containers"
// FCOS however does not get any translation in the machine-config-operator so we need to
// send in "kata-containers".
// Both are later send to rpm-ostree for installation.
//
// As RHCOS is rather special variant, use "kata-containers" by default, which also applies to FCOS
extension := os.Getenv("SANDBOXED_CONTAINERS_EXTENSION")
if len(extension) == 0 {
extension = "kata-containers"
}
return extension
}
func (r *KataConfigOpenShiftReconciler) newMCForCR(machinePool string) (*mcfgv1.MachineConfig, error) {
r.Log.Info("Creating MachineConfig for Custom Resource")
ic := ignTypes.Config{
Ignition: ignTypes.Ignition{
Version: "3.2.0",
},
}
icb, err := json.Marshal(ic)
if err != nil {
return nil, err
}
extension := getExtensionName()
mc := mcfgv1.MachineConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: "machineconfiguration.openshift.io/v1",
Kind: "MachineConfig",
},
ObjectMeta: metav1.ObjectMeta{
Name: extension_mc_name,
Labels: map[string]string{
"machineconfiguration.openshift.io/role": machinePool,
"app": r.kataConfig.Name,
},
Namespace: OperatorNamespace,
},
Spec: mcfgv1.MachineConfigSpec{
Extensions: []string{extension},
Config: runtime.RawExtension{
Raw: icb,
},
},
}
return &mc, nil
}
func (r *KataConfigOpenShiftReconciler) addFinalizer() error {
r.Log.Info("Adding Finalizer for the KataConfig")
controllerutil.AddFinalizer(r.kataConfig, kataConfigFinalizer)
// Update CR
err := r.Client.Update(context.TODO(), r.kataConfig)
if err != nil {
r.Log.Error(err, "Failed to update KataConfig with finalizer")
return err
}
return nil
}
func (r *KataConfigOpenShiftReconciler) removeFinalizer() error {
r.Log.Info("Removing finalizer from the KataConfig")
controllerutil.RemoveFinalizer(r.kataConfig, kataConfigFinalizer)
err := r.Client.Update(context.TODO(), r.kataConfig)
if err != nil {
r.Log.Error(err, "Unable to update KataConfig")
return err
}
return nil
}
func (r *KataConfigOpenShiftReconciler) listKataPods() error {
podList := &corev1.PodList{}
listOpts := []client.ListOption{
client.InNamespace(corev1.NamespaceAll),
}
if err := r.Client.List(context.TODO(), podList, listOpts...); err != nil {
return fmt.Errorf("failed to list kata pods: %v", err)
}
for _, pod := range podList.Items {
if pod.Spec.RuntimeClassName != nil {
if contains(r.kataConfig.Status.RuntimeClasses, *pod.Spec.RuntimeClassName) {
return fmt.Errorf("existing pods using \"%v\" RuntimeClass found. Please delete the pods manually for KataConfig deletion to proceed", *pod.Spec.RuntimeClassName)
}
}
}
return nil
}
//lint:ignore U1000 This method is unused, but let's keep it for now
func (r *KataConfigOpenShiftReconciler) kataOcExists() (bool, error) {
kataOcMcp := &mcfgv1.MachineConfigPool{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: "kata-oc"}, kataOcMcp)
if err != nil && k8serrors.IsNotFound(err) {
r.Log.Info("kata-oc MachineConfigPool not found")
return false, nil
} else if err != nil {
r.Log.Error(err, "Could not get the kata-oc MachineConfigPool")
return false, err
}
return true, nil
}
func (r *KataConfigOpenShiftReconciler) checkConvergedCluster() (bool, error) {
//Check if only master and worker MCP exists
//Worker machinecount should be 0
listOpts := []client.ListOption{}
mcpList := &mcfgv1.MachineConfigPoolList{}
err := r.Client.List(context.TODO(), mcpList, listOpts...)
if err != nil {
r.Log.Error(err, "Unable to get the list of MCPs")
return false, err
}
numMcp := len(mcpList.Items)
r.Log.Info("Number of MCPs", "numMcp", numMcp)
if numMcp == 2 {
for _, mcp := range mcpList.Items {
if mcp.Name == "worker" && mcp.Status.MachineCount == 0 {
r.Log.Info("Converged Cluster")
return true, nil
}
}
}
return false, nil
}
func (r *KataConfigOpenShiftReconciler) checkNodeEligibility() error {
r.Log.Info("Check Node Eligibility to run Kata containers")
// Check if node eligibility label exists
if r.kataConfig.Spec.EnablePeerPods {
r.Log.Info("enablePeerPods is true. Skipping since they are mutually exclusive.")
return nil
}
nodes, err := r.getNodesWithLabels(map[string]string{"feature.node.kubernetes.io/runtime.kata": "true"})
if err != nil {
r.Log.Error(err, "Error in getting list of nodes with label: feature.node.kubernetes.io/runtime.kata")
return err
}
if len(nodes.Items) == 0 {
err = fmt.Errorf("no Nodes with required labels found. Is NFD running?")
return err
}
return nil
}
func (r *KataConfigOpenShiftReconciler) getMcpName() (string, error) {
isConvergedCluster, err := r.checkConvergedCluster()
if err != nil {
r.Log.Info("Error trying to find out if cluster is converged", "err", err)
return "", err
}
if isConvergedCluster {
return "master", nil
} else {
return "kata-oc", nil
}
}
func (r *KataConfigOpenShiftReconciler) createScc() error {
scc := GetScc()
// Set Kataconfig r.kataConfig as the owner and controller
if err := controllerutil.SetControllerReference(r.kataConfig, scc, r.Scheme); err != nil {
return err
}
foundScc := &secv1.SecurityContextConstraints{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: scc.Name}, foundScc)
if err != nil {
if !k8serrors.IsNotFound(err) {
return err
}
r.Log.Info("Creating a new Scc", "scc.Name", scc.Name)
err = r.Client.Create(context.TODO(), scc)
if err != nil {
return err
}
}
return nil
}
func (r *KataConfigOpenShiftReconciler) createRuntimeClass(runtimeClassName string, cpuOverhead string, memoryOverhead string) error {
rc := func() *nodeapi.RuntimeClass {
rc := &nodeapi.RuntimeClass{
TypeMeta: metav1.TypeMeta{
APIVersion: "node.k8s.io/v1",
Kind: "RuntimeClass",
},
ObjectMeta: metav1.ObjectMeta{
Name: runtimeClassName,
},
Handler: runtimeClassName,
// Use same values for Pod Overhead as upstream kata-deploy using, see
// https://github.com/kata-containers/packaging/blob/f17450317563b6e4d6b1a71f0559360b37783e19/kata-deploy/k8s-1.18/kata-runtimeClasses.yaml#L7
Overhead: &nodeapi.Overhead{
PodFixed: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse(cpuOverhead),
corev1.ResourceMemory: resource.MustParse(memoryOverhead),
},
},
}
nodeSelector := r.getNodeSelectorAsMap()
rc.Scheduling = &nodeapi.Scheduling{
NodeSelector: nodeSelector,
}
r.Log.Info("RuntimeClass NodeSelector:", "nodeSelector", nodeSelector)
return rc
}()
// Set Kataconfig r.kataConfig as the owner and controller
if err := controllerutil.SetControllerReference(r.kataConfig, rc, r.Scheme); err != nil {
return err
}
foundRc := &nodeapi.RuntimeClass{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: rc.Name}, foundRc)
if err != nil {
if !k8serrors.IsNotFound(err) {
return err
}
r.Log.Info("Creating a new RuntimeClass", "rc.Name", rc.Name)
err = r.Client.Create(context.TODO(), rc)
if err != nil {
return err
}
}
if !contains(r.kataConfig.Status.RuntimeClasses, runtimeClassName) {
r.kataConfig.Status.RuntimeClasses = append(r.kataConfig.Status.RuntimeClasses, runtimeClassName)
}
return nil
}
// "KataConfigNodeSelector" in the names of the following couple of helper
// functions refers to the value of KataConfig.spec.kataConfigPoolSelector,
// i.e. the original selector supplied by the user of KataConfig.
func (r *KataConfigOpenShiftReconciler) getKataConfigNodeSelectorAsLabelSelector() *metav1.LabelSelector {
isConvergedCluster, err := r.checkConvergedCluster()
if err == nil && isConvergedCluster {
// master MCP cannot be customized
return &metav1.LabelSelector{MatchLabels: map[string]string{"node-role.kubernetes.io/master": ""}}
}
nodeSelector := &metav1.LabelSelector{}
if r.kataConfig.Spec.KataConfigPoolSelector != nil {
nodeSelector = r.kataConfig.Spec.KataConfigPoolSelector.DeepCopy()
}
if r.kataConfig.Spec.CheckNodeEligibility {
nodeSelector = metav1.AddLabelToSelector(nodeSelector, "feature.node.kubernetes.io/runtime.kata", "true")
}
r.Log.Info("getKataConfigNodeSelectorAsLabelSelector()", "selector", nodeSelector)
return nodeSelector
}
func (r *KataConfigOpenShiftReconciler) getKataConfigNodeSelectorAsSelector() (labels.Selector, error) {
selector, err := metav1.LabelSelectorAsSelector(r.getKataConfigNodeSelectorAsLabelSelector())
r.Log.Info("getKataConfigNodeSelectorAsSelector()", "selector", selector, "err", err)
return selector, err
}
// "NodeSelector" in the names of the following couple of helper
// functions refers to the selector we pass to resources we create that
// need to select kata-enabled nodes (currently the "kata-oc" MCP, the pod
// template in the monitor daemonset and the runtimeclass). It's guaranteed
// to be a simple map[string]string (AKA MatchLabels) which is good because the
// pod template's and runtimeclass' node selectors don't support
// MatchExpressions and thus cannot hold the full value of
// KataConfig.spec.kataConfigPoolSelector.
func (r *KataConfigOpenShiftReconciler) getNodeSelectorAsMap() map[string]string {
isConvergedCluster, err := r.checkConvergedCluster()
if err == nil && isConvergedCluster {
// master MCP cannot be customized
return map[string]string{"node-role.kubernetes.io/master": ""}
} else {
return map[string]string{"node-role.kubernetes.io/kata-oc": ""}
}
}
func (r *KataConfigOpenShiftReconciler) getNodeSelectorAsLabelSelector() *metav1.LabelSelector {
return &metav1.LabelSelector{MatchLabels: r.getNodeSelectorAsMap()}
}
func (r *KataConfigOpenShiftReconciler) isMcpUpdating(mcpName string) bool {
mcp := &mcfgv1.MachineConfigPool{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: mcpName}, mcp)
if err != nil {
r.Log.Info("Getting MachineConfigPool failed ", "machinePool", mcpName, "err", err)
return false
}
return mcfgv1.IsMachineConfigPoolConditionTrue(mcp.Status.Conditions, mcfgv1.MachineConfigPoolUpdating)
}
func (r *KataConfigOpenShiftReconciler) processKataConfigDeleteRequest() (ctrl.Result, error) {
r.Log.Info("KataConfig deletion in progress: ")
machinePool, err := r.getMcpName()
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: 15 * time.Second}, err
}
if contains(r.kataConfig.GetFinalizers(), kataConfigFinalizer) {
// Get the list of pods that might be running using kata runtime
err := r.listKataPods()
if err != nil {
r.setInProgressConditionToBlockedByExistingKataPods(err.Error())
updErr := r.Client.Status().Update(context.TODO(), r.kataConfig)
if updErr != nil {
return ctrl.Result{}, updErr
}
r.Log.Info("Kata PODs are present. Requeue for reconciliation ")
return ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second}, err
}
}
kataNodeSelector, err := r.getKataConfigNodeSelectorAsSelector()
if err != nil {
r.Log.Info("Couldn't get node selector for unlabelling nodes", "err", err)
return ctrl.Result{Requeue: true}, nil
}
labelingChanged, err := r.unlabelNodes(kataNodeSelector)
if err != nil {
if k8serrors.IsConflict(err) {
return ctrl.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
} else {
return ctrl.Result{Requeue: true}, nil
}
}
r.Log.Info("Making sure parent MCP is synced properly, SCNodeRole=" + machinePool)
r.setInProgressConditionToUninstalling()
mc, err := r.newMCForCR(machinePool)
if err != nil {
return ctrl.Result{}, err
}
var isMcDeleted bool
err = r.Client.Get(context.TODO(), types.NamespacedName{Name: mc.Name}, mc)
if err != nil && k8serrors.IsNotFound(err) {
isMcDeleted = true
} else if err != nil {
return ctrl.Result{}, err
}
if !isMcDeleted {
err = r.Client.Delete(context.TODO(), mc)
if err != nil {
// error during removing mc, don't block the uninstall. Just log the error and move on.
r.Log.Error(err, "Error found deleting machine config. If the machine config exists after installation it can be safely deleted manually.",
"mc", mc.Name)
}
}
isConvergedCluster, _ := r.checkConvergedCluster()
// Conditions to detect whether we need to wait for the MCO to start
// reconciliation differ based on whether the cluster is converged.
// If so then it's the fact we've just deleted the extension MC, if not
// then it's the node-role labeling change (if there's none it means
// we're deleting a KataConfig on a cluster where no nodes matched the
// kataConfigPoolSelector and thus there will be no change for the MCO
// to reconciliate).
if (isConvergedCluster && !isMcDeleted) || (!isConvergedCluster && labelingChanged) {
r.Log.Info("Starting to wait for MCO to start reconciliation")
r.kataConfig.Status.WaitingForMcoToStart = true
}
// When nodes migrate from a source pool to a target pool the source
// pool is drained immediately and the nodes then slowly join the target
// pool. Thus the operation duration is dominated by the target pool
// part and the target pool is what we need to watch to find out when
// the operation is finished. When uninstalling kata on a regular
// cluster nodes leave "kata-oc" to rejoin "worker" so "worker" is our
// target pool. On a converged cluster, nodes leave "master" to rejoin
// it so "master" is both source and target in this case.
targetPool := "worker"
if isConvergedCluster {
targetPool = "master"
}
isMcoUpdating := r.isMcpUpdating(targetPool)
if !isMcoUpdating && r.kataConfig.Status.WaitingForMcoToStart {
r.Log.Info("Waiting for MCO to start updating.")
// We don't requeue, an MCP going Updated->Updating will
// trigger reconciliation by itself thanks to our watching MCPs.
return reconcile.Result{}, nil
} else {
r.Log.Info("No need to wait for MCO to start updating.", "isMcoUpdating", isMcoUpdating, "Status.WaitingForMcoToStart", r.kataConfig.Status.WaitingForMcoToStart)
r.kataConfig.Status.WaitingForMcoToStart = false
}
err = r.updateStatus()
if err != nil {
r.Log.Info("Error updating KataConfig.status", "err", err)
}
if isMcoUpdating {
r.Log.Info("Waiting for MachineConfigPool to be fully updated", "machinePool", targetPool)
return reconcile.Result{}, nil
}
r.resetInProgressCondition()
if !isConvergedCluster {
r.Log.Info("Get()'ing MachineConfigPool to delete it", "machinePool", "kata-oc")
kataOcMcp := &mcfgv1.MachineConfigPool{}
err = r.Client.Get(context.TODO(), types.NamespacedName{Name: "kata-oc"}, kataOcMcp)
if err == nil {
r.Log.Info("Deleting MachineConfigPool ", "machinePool", "kata-oc")
err = r.Client.Delete(context.TODO(), kataOcMcp)
if err != nil {
r.Log.Error(err, "Unable to delete kata-oc MachineConfigPool")
return ctrl.Result{}, err
}
} else if k8serrors.IsNotFound(err) {
r.Log.Info("MachineConfigPool not found", "machinePool", "kata-oc")
} else {
r.Log.Error(err, "Unable to get MachineConfigPool ", "machinePool", "kata-oc")
return ctrl.Result{}, err
}
}
ds := r.processDaemonsetForMonitor()
err = r.Client.Delete(context.TODO(), ds)
if err != nil {
if k8serrors.IsNotFound(err) {
r.Log.Info("monitor daemonset was already deleted")
} else {
r.Log.Error(err, "error when deleting monitor Daemonset, try again")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 15}, err
}
}
if r.kataConfig.Spec.EnablePeerPods {
// We are explicitly ignoring any errors in peerpodconfig and related machineconfigs removal as
// these can be removed manually if needed and this is not in the critical path
// of operator functionality
_ = r.disablePeerPods()
// Handle podvm image deletion
status, err := ImageDelete(r.Client)
if status == RequeueNeeded && err == nil {
// Set the KataConfig status to PodVM Image Deleting
r.setInProgressConditionToPodVMImageDeleting()
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 15}, nil
} else if status == ImageDeletionFailed {
// Set the KataConfig status to PodVM Image Deletion Failed
r.setInProgressConditionToPodVMImageDeletionFailed()
return reconcile.Result{}, err
} else if status == ImageDeletionStatusUnknown {
// Set the KataConfig status to PodVM Image Deletion Status Unknown
r.setInProgressConditionToPodVMImageDeletionUnknown()
// Reconcile with error
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 15}, err
} else if err != nil {
// Reconcile with error
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 15}, err
}
// Set the KataConfig status to PodVM Image Deleted
r.setInProgressConditionToPodVMImageDeleted()
}
scc := GetScc()
err = r.Client.Delete(context.TODO(), scc)
if err != nil {
if k8serrors.IsNotFound(err) {
r.Log.Info("SCC was already deleted")
} else {
r.Log.Error(err, "error when deleting SCC, retrying")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 15}, err
}
}
err = r.removeLogLevel()
if err != nil {
return ctrl.Result{Requeue: true}, nil
}
r.Log.Info("Uninstallation completed. Proceeding with the KataConfig deletion")
if err = r.removeFinalizer(); err != nil {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
func (r *KataConfigOpenShiftReconciler) processKataConfigInstallRequest() (ctrl.Result, error) {
r.Log.Info("Kata installation in progress")