/
ccruntime_controller.go
960 lines (860 loc) · 31.8 KB
/
ccruntime_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
/*
Copyright 2021 CNCF.
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"
"fmt"
"strconv"
"strings"
"time"
"k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
nodeapi "k8s.io/api/node/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
ccv1beta1 "github.com/confidential-containers/operator/api/v1beta1"
)
// CcRuntimeReconciler reconciles a CcRuntime object
type CcRuntimeReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
ccRuntime *ccv1beta1.CcRuntime
Namespace string
}
//+kubebuilder:rbac:groups=confidentialcontainers.org,resources=ccruntimes,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=confidentialcontainers.org,resources=ccruntimes/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=confidentialcontainers.org,resources=ccruntimes/finalizers,verbs=update
//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get;list;watch;patch;update
//+kubebuilder:rbac:groups=apps,resources=daemonsets,verbs=get;list;watch;create;delete;update;patch
//+kubebuilder:rbac:groups=node.k8s.io,resources=runtimeclasses,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups="",resources=namespaces,verbs=get;update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the CcRuntime object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.9.2/pkg/reconcile
func (r *CcRuntimeReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log = log.FromContext(ctx)
_ = r.Log.WithValues("ccruntime", req.NamespacedName)
r.Log.Info("Reconciling CcRuntime in Kubernetes Cluster")
// Fetch the CcRuntime instance
r.ccRuntime = &ccv1beta1.CcRuntime{}
err := r.Client.Get(context.TODO(), req.NamespacedName, r.ccRuntime)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile 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.
return ctrl.Result{}, err
}
// Create the uninstall DaemonSet
ds := r.processDaemonset(UninstallOperation)
if err := controllerutil.SetControllerReference(r.ccRuntime, ds, r.Scheme); err != nil {
r.Log.Error(err, "Failed setting ControllerReference for uninstall DS")
return ctrl.Result{}, err
}
foundDs := &appsv1.DaemonSet{}
err = r.Client.Get(context.TODO(), types.NamespacedName{Name: ds.Name, Namespace: ds.Namespace}, foundDs)
if err != nil && errors.IsNotFound(err) {
r.Log.Info("Creating cleanup Daemonset", "ds.Namespace", ds.Namespace, "ds.Name", ds.Name)
err = r.Client.Create(context.TODO(), ds)
if err != nil {
return ctrl.Result{}, err
}
}
// Check if the CcRuntime instance is marked to be deleted, which is
// indicated by the deletion timestamp being set.
if r.ccRuntime.GetDeletionTimestamp() != nil {
r.Log.Info("ccRuntime instance marked deleted")
res, err := r.processCcRuntimeDeleteRequest()
if err != nil || res.Requeue {
return res, err
} else {
return ctrl.Result{}, nil
}
}
return r.processCcRuntimeInstallRequest()
}
func (r *CcRuntimeReconciler) getNodeClient() (v1.NodeInterface, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
nodeClient := clientset.CoreV1().Nodes()
return nodeClient, err
}
func (r *CcRuntimeReconciler) setCleanupNodeLabels() (ctrl.Result, error) {
var nodesList = &corev1.NodeList{}
nodesClient, err := r.getNodeClient()
if err != nil {
r.Log.Info("Couldn't get nodes client")
return ctrl.Result{}, err
}
listOpts := []client.ListOption{
client.MatchingLabels(r.ccRuntime.Spec.Config.InstallDoneLabel),
}
err = r.Client.List(context.TODO(), nodesList, listOpts...)
if err != nil {
r.Log.Info("failed to list nodes during uninstallation status update")
return ctrl.Result{}, err
}
installDoneLabel := make([]string, 0, len(r.ccRuntime.Spec.Config.InstallDoneLabel))
for key := range r.ccRuntime.Spec.Config.InstallDoneLabel {
installDoneLabel = append(installDoneLabel, key)
}
if len(installDoneLabel) > 1 {
return ctrl.Result{}, fmt.Errorf("installDoneLabel must only have one entry")
}
for _, node := range nodesList.Items {
for k, v := range node.GetLabels() {
if k == installDoneLabel[0] && v == "true" {
nodeLabels := node.GetLabels()
nodeLabels[k] = "cleanup"
node.SetLabels(nodeLabels)
break
}
}
_, err := nodesClient.Update(context.TODO(), &node, metav1.UpdateOptions{
TypeMeta: metav1.TypeMeta{},
DryRun: nil,
FieldManager: "",
})
if err != nil {
r.Log.Info("failed to update node labels")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) processCcRuntimeDeleteRequest() (ctrl.Result, error) {
var result = ctrl.Result{}
// Create the uninstall DaemonSet
ds := r.processDaemonset(UninstallOperation)
if err := controllerutil.SetControllerReference(r.ccRuntime, ds, r.Scheme); err != nil {
r.Log.Error(err, "Failed setting ControllerReference for uninstall DS")
return ctrl.Result{}, err
}
foundDs := &appsv1.DaemonSet{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: ds.Name, Namespace: ds.Namespace}, foundDs)
if err != nil && errors.IsNotFound(err) {
r.Log.Info("Creating cleanup Daemonset", "ds.Namespace", ds.Namespace, "ds.Name", ds.Name)
err = r.Client.Create(context.TODO(), ds)
}
if err != nil {
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
if contains(r.ccRuntime.GetFinalizers(), RuntimeConfigFinalizer) {
// Check for nodes with label set by install DS prestop hook.
// If no nodes exist then remove finalizer and reconcile
err, nodes := r.getNodesWithLabels(r.ccRuntime.Spec.Config.UninstallDoneLabel)
if err != nil {
r.Log.Error(err, "Error in getting list of nodes with uninstallDoneLabel")
return ctrl.Result{}, err
}
finishedNodes := len(nodes.Items)
if !allNodesDone(finishedNodes, r) {
result, err = r.setCleanupNodeLabels()
if err != nil {
r.Log.Error(err, "updating the cleanup labels on nodes failed")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, err
}
} else {
if r.ccRuntime.Spec.Config.PostUninstall.Image == "" {
controllerutil.RemoveFinalizer(r.ccRuntime, RuntimeConfigFinalizer)
} else if r.ccRuntime.Spec.Config.PostUninstall.Image != "" {
// FXIME: This should be treated in a better way, as just having the sleep
// here won't do us any good in the future.
//
// What's basically happening, and forcing us to do this, is the
// fact that the Uninstall and postUninstall daemonsets are being
// started at exactly the same time, leading to a race condition
// when changing the containerd configuration.
//
// When looking at the kata-containers payload code, we see that the
// the label is only set after containerd is successfully reconfigured,
// and looking at this function we see we shouldn't reach this part
// before the label is set. However, that's not what we're facing ...
time.Sleep(time.Second * 60)
result, err = handlePostUninstall(r)
if !result.Requeue {
controllerutil.RemoveFinalizer(r.ccRuntime, RuntimeConfigFinalizer)
result, err = r.updateCcRuntime()
if err != nil {
return result, err
}
result, err = r.deleteUninstallDaemonsets()
prepostLabels := map[string]string{}
if r.ccRuntime.Spec.Config.PreInstall.Image != "" {
prepostLabels[PreInstallDoneLabel[0]] = PreInstallDoneLabel[1]
}
if r.ccRuntime.Spec.Config.PostUninstall.Image != "" {
prepostLabels[PostUninstallDoneLabel[0]] = PostUninstallDoneLabel[1]
}
err, nodes := r.getNodesWithLabels(prepostLabels)
if err != nil {
r.Log.Error(err, "an error occured when getting the list of nodes from which we want to"+
"remove preinstall/postuninstall labels")
return ctrl.Result{}, err
}
postuninstalledNodes := len(nodes.Items)
if !allNodesDone(postuninstalledNodes, r) {
return ctrl.Result{Requeue: true}, nil
} else {
if postuninstalledNodes > 0 {
result, err = r.removeNodeLabels(nodes)
if err != nil {
r.Log.Error(err, "removing the labels from nodes failed")
return ctrl.Result{}, err
}
}
}
}
}
if err != nil {
return result, err
}
result, err = r.updateCcRuntime()
return result, err
}
result, err = r.updateUninstallationStatus(finishedNodes)
if err != nil {
r.Log.Info("Error from updateUninstallationStatus")
return result, err
}
result.Requeue = true
result.RequeueAfter = time.Second * 10
}
return result, err
}
func (r *CcRuntimeReconciler) updateCcRuntime() (ctrl.Result, error) {
err := r.Client.Update(context.TODO(), r.ccRuntime)
if err != nil {
r.Log.Error(err, "failed to update ccRuntime")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
return ctrl.Result{}, nil
}
func allNodesDone(finishedNodes int, r *CcRuntimeReconciler) bool {
return finishedNodes == r.ccRuntime.Status.TotalNodesCount
}
func (r *CcRuntimeReconciler) updateUninstallationStatus(finishedNodes int) (ctrl.Result, error) {
var doneNodes []string
err, cleanupNodes := r.getNodesWithLabels(r.ccRuntime.Spec.Config.UninstallDoneLabel)
if err != nil {
r.Log.Error(err, "Error in getting list of nodes with UninstallDoneLabel")
return ctrl.Result{}, err
}
// Update CR
r.ccRuntime.Status.UnInstallationStatus.Completed.CompletedNodesCount = finishedNodes
r.ccRuntime.Status.UnInstallationStatus.InProgress.InProgressNodesCount = r.ccRuntime.Status.TotalNodesCount - finishedNodes
for i := range cleanupNodes.Items {
doneNodes = append(doneNodes, cleanupNodes.Items[i].Name)
}
r.ccRuntime.Status.UnInstallationStatus.InProgress.BinariesUnInstalledNodesList = doneNodes
err = r.Client.Update(context.TODO(), r.ccRuntime)
if err != nil {
r.Log.Error(err, "failed to update ccRuntime with finalizer")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, err
}
return ctrl.Result{}, nil
}
func handlePostUninstall(r *CcRuntimeReconciler) (ctrl.Result, error) {
err, nodes := r.getNodesWithLabels(map[string]string{"cc-postuninstall/done": "true"})
if err != nil {
r.Log.Info("couldn't get nodes labeled with postuninstall done label")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
if r.ccRuntime.Spec.Config.PostUninstall.Image != "" &&
len(nodes.Items) < r.ccRuntime.Status.TotalNodesCount &&
r.ccRuntime.Status.TotalNodesCount > 0 {
postUninstallDs := r.makeHookDaemonset(PostUninstallOperation)
// get daemonset
res, err := r.handlePrePostDs(postUninstallDs, map[string]string{"cc-postuninstall/done": "true"})
if res.Requeue {
if err != nil {
r.Log.Info("error from handlePrePostDs")
}
}
return res, err
} else if len(nodes.Items) == r.ccRuntime.Status.TotalNodesCount {
return ctrl.Result{}, nil
}
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
func (r *CcRuntimeReconciler) processCcRuntimeInstallRequest() (ctrl.Result, error) {
nodesList := &corev1.NodeList{}
if r.ccRuntime.Spec.CcNodeSelector == nil {
r.ccRuntime.Spec.CcNodeSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{"node.kubernetes.io/worker": ""},
}
}
listOpts := []client.ListOption{
client.MatchingLabels(r.ccRuntime.Spec.CcNodeSelector.MatchLabels),
}
err := r.Client.List(context.TODO(), nodesList, listOpts...)
if err != nil {
return ctrl.Result{}, err
}
r.ccRuntime.Status.TotalNodesCount = len(nodesList.Items)
if r.ccRuntime.Status.TotalNodesCount == 0 {
return ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second},
fmt.Errorf("no suitable worker nodes found for runtime installation. Please make sure to label the nodes with labels specified in CcNodeSelector")
}
if r.ccRuntime.Spec.Config.PayloadImage == "" {
return ctrl.Result{Requeue: true, RequeueAfter: 15 * time.Second},
fmt.Errorf("PayloadImage must be specified to download the runtime binaries")
}
r.ccRuntime.Status.RuntimeName = r.ccRuntime.Spec.RuntimeName
err = r.Client.Status().Update(context.TODO(), r.ccRuntime)
if err != nil {
return ctrl.Result{}, err
}
// if ds exists, get all labels
err, nodes := r.getNodesWithLabels(map[string]string{"cc-preinstall/done": "true"})
if err != nil {
r.Log.Info("couldn't GET labelled nodes")
return ctrl.Result{}, err
}
if r.ccRuntime.Spec.Config.PreInstall.Image != "" &&
len(nodes.Items) < r.ccRuntime.Status.TotalNodesCount {
preInstallDs := r.makeHookDaemonset(PreInstallOperation)
r.Log.Info("ds = ", "daemonset", preInstallDs)
res, err := r.handlePrePostDs(preInstallDs, map[string]string{"cc-preinstall/done": "true"})
if res.Requeue {
r.Log.Info("requeue request from handlePrePostDs")
return res, err
}
}
// Don't create the daemonset if the runtime is already installed on the cluster nodes
if r.ccRuntime.Status.TotalNodesCount > 0 &&
r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesCount != r.ccRuntime.Status.TotalNodesCount {
ds := r.processDaemonset(InstallOperation)
// Set CcRuntime instance as the owner and controller
if err := controllerutil.SetControllerReference(r.ccRuntime, ds, r.Scheme); err != nil {
r.Log.Error(err, "Failed setting ControllerReference")
return ctrl.Result{}, err
}
foundDs := &appsv1.DaemonSet{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: ds.Name, Namespace: ds.Namespace}, foundDs)
if err != nil && errors.IsNotFound(err) {
r.Log.Info("Creating a new installation Daemonset", "ds.Namespace", ds.Namespace, "ds.Name", ds.Name)
err = r.Client.Create(context.TODO(), ds)
if err != nil {
return ctrl.Result{}, err
}
} else if err != nil {
return ctrl.Result{}, err
}
}
return r.monitorCcRuntimeInstallation()
}
/*
This creates DaemonSets for pre-install/post-uninstall unless it already exists.
We leave the DaemonSets running until the ccRuntime finalizer is called.
This way the running DaemonSet automatically applies changes when a new
node is added.
*/
func (r *CcRuntimeReconciler) handlePrePostDs(preInstallDs *appsv1.DaemonSet, doneLabel map[string]string) (
ctrl.Result, error,
) {
foundPreinstallDs := &appsv1.DaemonSet{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: preInstallDs.Name, Namespace: preInstallDs.Namespace}, foundPreinstallDs)
r.Log.Info("create preinstall/postuninstall DS", "DS", preInstallDs)
if err != nil && errors.IsNotFound(err) {
err = r.Client.Create(context.TODO(), preInstallDs)
if err != nil {
r.Log.Info("failed to create preinstall/postuninstall DS", "DS", preInstallDs)
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, nil
} else if err != nil {
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
// if ds exists, get all labels
err, nodes := r.getNodesWithLabels(doneLabel)
if err != nil {
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
if len(nodes.Items) < r.ccRuntime.Status.TotalNodesCount {
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) monitorCcRuntimeInstallation() (ctrl.Result, error) {
var (
err error
result ctrl.Result
)
// If the installation of the binaries is successful on all nodes, proceed with creating the runtime classes
if r.allNodesInstalled() {
// Update runtimeClass field
var runtimeClassNames []string
runtimeClasses := r.ccRuntime.Spec.Config.RuntimeClasses
for _, runtimeClass := range runtimeClasses {
foundRc := &nodeapi.RuntimeClass{}
err := r.Client.Get(context.TODO(), types.NamespacedName{Name: runtimeClass.Name}, foundRc)
if errors.IsNotFound(err) {
r.Log.Info("The runtime payload failed to create the runtime class", "runtimeClassName", runtimeClass.Name)
return ctrl.Result{}, err
}
runtimeClassNames = append(runtimeClassNames, runtimeClass.Name)
}
r.ccRuntime.Status.RuntimeClass = strings.Join(runtimeClassNames, ",")
// Add finalizer for this CR
if !contains(r.ccRuntime.GetFinalizers(), RuntimeConfigFinalizer) {
if err := r.addFinalizer(); err != nil {
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 10}, err
}
}
r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesCount = len(r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesList)
r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList = []string{}
r.ccRuntime.Status.InstallationStatus.InProgress.InProgressNodesCount = 0
}
err = r.Client.Status().Update(context.TODO(), r.ccRuntime)
if err != nil {
r.Log.Info("failed to update status while monitoring installation")
return ctrl.Result{}, err
}
nodesList, result, err := r.getAllNodes()
if err != nil {
return result, err
}
result, err = r.updateInstallationStatus(nodesList)
if err != nil {
return result, err
}
if r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesCount != r.ccRuntime.Status.TotalNodesCount {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) updateInstallationStatus(nodesList *corev1.NodeList) (ctrl.Result, error) {
r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList = []string{}
for _, node := range nodesList.Items {
r.ccRuntime.Status.InstallationStatus.InProgress.InProgressNodesCount = len(r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList)
for k, v := range node.GetLabels() {
doneLabel, exists := r.ccRuntime.Spec.Config.InstallDoneLabel[k]
if exists && v == doneLabel {
if !contains(r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesList, node.Name) {
r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesCount++
r.Log.Info("adding new node to completed list", "nodeName", node.Name)
r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesList =
append(r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesList, node.Name)
r.ccRuntime.Status.InstallationStatus.InProgress.InProgressNodesCount = len(r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList)
if !contains(r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList, node.Name) {
r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList =
append(r.ccRuntime.Status.InstallationStatus.InProgress.BinariesInstalledNodesList, node.Name)
}
}
}
}
err := r.Client.Status().Update(context.TODO(), r.ccRuntime)
if err != nil {
r.Log.Info("Updating status of completed nodes etc failed")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, err
}
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) getAllNodes() (*corev1.NodeList, ctrl.Result, error) {
nodesList := &corev1.NodeList{}
if r.ccRuntime.Spec.CcNodeSelector == nil {
r.ccRuntime.Spec.CcNodeSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{"node.kubernetes.io/worker": ""},
}
}
listOpts := []client.ListOption{
client.MatchingLabels(r.ccRuntime.Spec.CcNodeSelector.MatchLabels),
}
err := r.Client.List(context.TODO(), nodesList, listOpts...)
if err != nil {
r.Log.Info("listing the nodes failed while monitoring the installation")
return nil, ctrl.Result{}, err
}
return nodesList, ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) allNodesInstalled() bool {
return r.ccRuntime.Status.TotalNodesCount > 0 &&
r.ccRuntime.Status.InstallationStatus.Completed.CompletedNodesCount == r.ccRuntime.Status.TotalNodesCount
}
func (r *CcRuntimeReconciler) processDaemonset(operation DaemonOperation) *appsv1.DaemonSet {
runPrivileged := true
var runAsUser int64 = 0
dsName := "cc-operator-daemon-" + string(operation)
dsLabelSelectors := map[string]string{
"name": dsName,
}
var nodeSelector map[string]string
if r.ccRuntime.Spec.CcNodeSelector != nil && operation == InstallOperation {
nodeSelector = r.ccRuntime.Spec.CcNodeSelector.MatchLabels
} else if operation == UninstallOperation {
nodeSelector = r.ccRuntime.Spec.Config.UninstallDoneLabel
} else {
nodeSelector = map[string]string{
"node.kubernetes.io/worker": "",
}
}
var containerCommand []string
preStopHook := &corev1.Lifecycle{}
if operation == InstallOperation {
preStopHook = &corev1.Lifecycle{
PreStop: &corev1.LifecycleHandler{
Exec: &corev1.ExecAction{
Command: r.ccRuntime.Spec.Config.CleanupCmd,
},
},
}
containerCommand = r.ccRuntime.Spec.Config.InstallCmd
}
if operation == UninstallOperation {
containerCommand = r.ccRuntime.Spec.Config.UninstallCmd
}
var debug = strconv.FormatBool(r.ccRuntime.Spec.Config.Debug)
var defaultShim = ""
var createDefaultRuntimeClass = "false"
if strings.HasPrefix(r.ccRuntime.Spec.Config.DefaultRuntimeClassName, "kata-") {
// Remove the "kata-" prefix from DefaultRuntimeClassName
defaultShim = strings.TrimPrefix(r.ccRuntime.Spec.Config.DefaultRuntimeClassName, "kata-")
createDefaultRuntimeClass = "true"
}
var shims []string
var snapshotter_handler_mapping []string
for _, runtimeClass := range r.ccRuntime.Spec.Config.RuntimeClasses {
// Similarly to what's being done for the default shim, let's remove
// the "kata-" prefix from the runtime class names
shim := strings.TrimPrefix(runtimeClass.Name, "kata-")
shims = append(shims, shim)
if runtimeClass.Snapshotter != "" {
mapping := shim + ":" + runtimeClass.Snapshotter
snapshotter_handler_mapping = append(snapshotter_handler_mapping, mapping)
}
}
var envVars = []corev1.EnvVar{
{
Name: "NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "spec.nodeName",
},
},
},
{
Name: "DEBUG",
Value: debug,
},
{
Name: "DEFAULT_SHIM",
Value: defaultShim,
},
{
Name: "CREATE_DEFAULT_RUNTIMECLASS",
Value: createDefaultRuntimeClass,
},
{
Name: "CREATE_RUNTIMECLASSES",
Value: "true",
},
{
Name: "SHIMS",
Value: strings.Join(shims, " "),
},
{
Name: "SNAPSHOTTER_HANDLER_MAPPING",
Value: strings.Join(snapshotter_handler_mapping, ","),
},
}
envVars = append(envVars, r.ccRuntime.Spec.Config.EnvironmentVariables...)
return &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "DaemonSet",
},
ObjectMeta: metav1.ObjectMeta{
Name: dsName,
Namespace: r.Namespace,
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: dsLabelSelectors,
},
UpdateStrategy: appsv1.DaemonSetUpdateStrategy{
Type: "RollingUpdate",
RollingUpdate: &appsv1.RollingUpdateDaemonSet{
MaxUnavailable: &intstr.IntOrString{
Type: intstr.Int,
IntVal: 1,
},
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: dsLabelSelectors,
},
Spec: corev1.PodSpec{
ServiceAccountName: "cc-operator-controller-manager",
NodeSelector: nodeSelector,
HostPID: true,
Containers: []corev1.Container{
{
Name: "cc-runtime-install-pod",
Image: r.ccRuntime.Spec.Config.PayloadImage,
ImagePullPolicy: "Always",
Lifecycle: preStopHook,
SecurityContext: &corev1.SecurityContext{
// TODO - do we really need to run as root?
Privileged: &runPrivileged,
RunAsUser: &runAsUser,
},
Command: containerCommand,
Env: envVars,
VolumeMounts: r.ccRuntime.Spec.Config.InstallerVolumeMounts,
},
},
Volumes: r.ccRuntime.Spec.Config.InstallerVolumes,
},
},
},
}
}
func (r *CcRuntimeReconciler) addFinalizer() error {
r.Log.Info("Adding Finalizer for the RuntimeConfig")
controllerutil.AddFinalizer(r.ccRuntime, RuntimeConfigFinalizer)
// Update CR
err := r.Client.Update(context.TODO(), r.ccRuntime)
if err != nil {
r.Log.Error(err, "Failed to update ccRuntime with finalizer")
return err
}
return nil
}
// Get Nodes container specific labels
func (r *CcRuntimeReconciler) getNodesWithLabels(nodeLabels map[string]string) (error, *corev1.NodeList) {
nodes := &corev1.NodeList{}
labelSelector := labels.SelectorFromSet(nodeLabels)
listOpts := []client.ListOption{
client.MatchingLabelsSelector{Selector: labelSelector},
}
if err := r.Client.List(context.TODO(), nodes, listOpts...); err != nil {
r.Log.Error(err, "Getting list of nodes having specified labels failed")
return err, &corev1.NodeList{}
}
return nil, nodes
}
func (r *CcRuntimeReconciler) mapCcRuntimeToRequests(ctx context.Context, ccRuntimeObj client.Object) []reconcile.Request {
ccRuntimeList := &ccv1beta1.CcRuntimeList{}
err := r.Client.List(ctx, ccRuntimeList)
if err != nil {
return []reconcile.Request{}
}
reconcileRequests := make([]reconcile.Request, len(ccRuntimeList.Items))
for _, ccRuntime := range ccRuntimeList.Items {
reconcileRequests = append(reconcileRequests, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: ccRuntime.Name,
},
})
}
return reconcileRequests
}
// SetupWithManager sets up the controller with the Manager.
func (r *CcRuntimeReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&ccv1beta1.CcRuntime{}).
Watches(
&corev1.Node{},
handler.EnqueueRequestsFromMapFunc(r.mapCcRuntimeToRequests)).
Complete(r)
}
func (r *CcRuntimeReconciler) deleteUninstallDaemonsets() (ctrl.Result, error) {
ds := r.processDaemonset(UninstallOperation)
result, err := r.deleteDaemonset(ds)
if err != nil {
return result, err
}
ds = r.makeHookDaemonset(PostUninstallOperation)
result, err = r.deleteDaemonset(ds)
if err != nil {
return result, err
}
ds = r.makeHookDaemonset(PreInstallOperation)
result, err = r.deleteDaemonset(ds)
if err != nil {
return result, err
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) deleteDaemonset(ds *appsv1.DaemonSet) (ctrl.Result, error) {
err := r.Client.Delete(context.TODO(), ds)
if err != nil && !errors.IsNotFound(err) && !errors.IsGone(err) {
r.Log.Error(err, "Couldn't delete Daemonset ", "Name:", ds.Name)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *CcRuntimeReconciler) makeHookDaemonset(operation DaemonOperation) *appsv1.DaemonSet {
var (
runPrivileged = true
runAsUser int64 = 0
image = "" //nolint: ineffassign
dsName string
volumes []corev1.Volume
volumeMounts []corev1.VolumeMount
envVars = []corev1.EnvVar{
{
Name: "NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "spec.nodeName",
},
},
},
}
)
envVars = append(envVars, r.ccRuntime.Spec.Config.EnvironmentVariables...)
switch operation {
case PreInstallOperation:
dsName = "cc-operator-pre-install-daemon"
image = r.ccRuntime.Spec.Config.PreInstall.Image
volumeMounts = r.ccRuntime.Spec.Config.PreInstall.VolumeMounts
volumes = r.ccRuntime.Spec.Config.PreInstall.Volumes
envVars = append(envVars, r.ccRuntime.Spec.Config.PreInstall.EnvironmentVariables...)
case PostUninstallOperation:
dsName = "cc-operator-post-uninstall-daemon"
image = r.ccRuntime.Spec.Config.PostUninstall.Image
volumeMounts = r.ccRuntime.Spec.Config.PostUninstall.VolumeMounts
volumes = r.ccRuntime.Spec.Config.PostUninstall.Volumes
envVars = append(envVars, r.ccRuntime.Spec.Config.PostUninstall.EnvironmentVariables...)
default:
dsName = "invalid operation"
image = "invalid image"
volumeMounts = []corev1.VolumeMount{}
volumes = []corev1.Volume{}
envVars = []corev1.EnvVar{}
}
dsLabelSelectors := map[string]string{
"name": dsName,
}
var nodeSelector map[string]string
if r.ccRuntime.Spec.CcNodeSelector != nil {
nodeSelector = r.ccRuntime.Spec.CcNodeSelector.MatchLabels
} else {
nodeSelector = map[string]string{
"node.kubernetes.io/worker": "",
}
}
return &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "DaemonSet",
},
ObjectMeta: metav1.ObjectMeta{
Name: dsName,
Namespace: r.Namespace,
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: dsLabelSelectors,
},
UpdateStrategy: appsv1.DaemonSetUpdateStrategy{
Type: "RollingUpdate",
RollingUpdate: &appsv1.RollingUpdateDaemonSet{
MaxUnavailable: &intstr.IntOrString{
Type: intstr.Int,
IntVal: 1,
},
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: dsLabelSelectors,
},
Spec: corev1.PodSpec{
ServiceAccountName: "cc-operator-controller-manager",
NodeSelector: nodeSelector,
HostPID: true,
Containers: []corev1.Container{
{
Name: "cc-runtime-" + string(operation) + "-pod",
Image: image,
ImagePullPolicy: "Always",
SecurityContext: &corev1.SecurityContext{
Privileged: &runPrivileged,
RunAsUser: &runAsUser,
},
Command: []string{"/bin/sh", "-c", "/opt/confidential-containers-pre-install-artifacts/scripts/" + string(operation) + ".sh"},
Env: envVars,
VolumeMounts: volumeMounts,
},
},
Volumes: volumes,
},
},
},
}
}
func (r *CcRuntimeReconciler) removeNodeLabels(nodesList *corev1.NodeList) (ctrl.Result, error) {
nodesClient, err := r.getNodeClient()
if err != nil {
r.Log.Info("Couldn't get nodes client")
return ctrl.Result{}, err
}
for _, node := range nodesList.Items {
nodeLabels := node.GetLabels()
if val, ok := nodeLabels[PreInstallDoneLabel[0]]; ok && val == PreInstallDoneLabel[1] {
delete(nodeLabels, PreInstallDoneLabel[0])
}
if val, ok := nodeLabels[PostUninstallDoneLabel[0]]; ok && val == PostUninstallDoneLabel[1] {
delete(nodeLabels, PostUninstallDoneLabel[0])
}
if val, ok := nodeLabels[KataRuntimeLabel[0]]; ok && val == KataRuntimeLabel[1] {
delete(nodeLabels, KataRuntimeLabel[0])
}
node.SetLabels(nodeLabels)
_, err := nodesClient.Update(context.TODO(), &node, metav1.UpdateOptions{
TypeMeta: metav1.TypeMeta{},
DryRun: nil,
FieldManager: "",
})
if err != nil {
r.Log.Info("failed to update node labels")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}