/
virtualmachine_controller.go
1812 lines (1636 loc) · 63.7 KB
/
virtualmachine_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
/*
Copyright 2022.
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 (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"reflect"
"strconv"
"time"
nadapiv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
"golang.org/x/crypto/ssh"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"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/apimachinery/pkg/util/intstr"
"k8s.io/apiserver/pkg/storage/names"
"k8s.io/client-go/tools/record"
vmv1 "github.com/neondatabase/autoscaling/neonvm/apis/neonvm/v1"
"github.com/neondatabase/autoscaling/neonvm/controllers/buildtag"
"github.com/neondatabase/autoscaling/neonvm/pkg/ipam"
"github.com/neondatabase/autoscaling/pkg/api"
"github.com/neondatabase/autoscaling/pkg/util/patch"
)
const (
virtualmachineFinalizer = "vm.neon.tech/finalizer"
)
// Definitions to manage status conditions
const (
// typeAvailableVirtualMachine represents the status of the Deployment reconciliation
typeAvailableVirtualMachine = "Available"
// typeDegradedVirtualMachine represents the status used when the custom resource is deleted and the finalizer operations are must to occur.
typeDegradedVirtualMachine = "Degraded"
)
const (
minSupportedRunnerVersion api.RunnerProtoVersion = api.RunnerProtoV1
maxSupportedRunnerVersion api.RunnerProtoVersion = api.RunnerProtoV1
)
// VirtualMachineReconciler reconciles a VirtualMachine object
type VirtualMachineReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
Config *ReconcilerConfig
Metrics ReconcilerMetrics `exhaustruct:"optional"`
}
// The following markers are used to generate the rules permissions (RBAC) on config/rbac using controller-gen
// when controller-gen (used by 'make generate') is executed.
// To know more about markers see: https://book.kubebuilder.io/reference/markers.html
//+kubebuilder:rbac:groups=vm.neon.tech,resources=virtualmachines,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=vm.neon.tech,resources=virtualmachines/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=vm.neon.tech,resources=virtualmachines/finalizers,verbs=update
//+kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
//+kubebuilder:rbac:groups=core,resources=nodes,verbs=list
//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=pods/status,verbs=get;list;watch
//+kubebuilder:rbac:groups=vm.neon.tech,resources=ippools,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=vm.neon.tech,resources=ippools/finalizers,verbs=update
//+kubebuilder:rbac:groups=k8s.cni.cncf.io,resources=network-attachment-definitions,verbs=get;list;watch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// It is essential for the controller's reconciliation loop to be idempotent. By following the Operator
// pattern you will create Controllers which provide a reconcile function
// responsible for synchronizing resources until the desired state is reached on the cluster.
// Breaking this recommendation goes against the design principles of controller-runtime.
// and may lead to unforeseen consequences such as resources becoming stuck and requiring manual intervention.
// For further info:
// - About Operator Pattern: https://kubernetes.io/docs/concepts/extend-kubernetes/operator/
// - About Controllers: https://kubernetes.io/docs/concepts/architecture/controller/
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.13.0/pkg/reconcile
func (r *VirtualMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
var virtualmachine vmv1.VirtualMachine
if err := r.Get(ctx, req.NamespacedName, &virtualmachine); err != nil {
// Error reading the object - requeue the request.
if notfound := client.IgnoreNotFound(err); notfound == nil {
log.Info("virtualmachine resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
log.Error(err, "Unable to fetch VirtualMachine")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// examine DeletionTimestamp to determine if object is under deletion
if virtualmachine.ObjectMeta.DeletionTimestamp.IsZero() {
// The object is not being deleted, so if it does not have our finalizer,
// then lets add the finalizer and update the object. This is equivalent
// registering our finalizer.
if !controllerutil.ContainsFinalizer(&virtualmachine, virtualmachineFinalizer) {
log.Info("Adding Finalizer for VirtualMachine")
if ok := controllerutil.AddFinalizer(&virtualmachine, virtualmachineFinalizer); !ok {
log.Info("Failed to add finalizer from VirtualMachine")
return ctrl.Result{Requeue: true}, nil
}
if err := r.tryUpdateVM(ctx, &virtualmachine); err != nil {
log.Error(err, "Failed to update status about adding finalizer to VirtualMachine")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
} else {
// The object is being deleted
if controllerutil.ContainsFinalizer(&virtualmachine, virtualmachineFinalizer) {
// our finalizer is present, so lets handle any external dependency
log.Info("Performing Finalizer Operations for VirtualMachine before delete it")
r.doFinalizerOperationsForVirtualMachine(ctx, &virtualmachine)
// remove our finalizer from the list and update it.
log.Info("Removing Finalizer for VirtualMachine after successfully perform the operations")
if ok := controllerutil.RemoveFinalizer(&virtualmachine, virtualmachineFinalizer); !ok {
log.Info("Failed to remove finalizer from VirtualMachine")
return ctrl.Result{Requeue: true}, nil
}
if err := r.tryUpdateVM(ctx, &virtualmachine); err != nil {
log.Error(err, "Failed to update status about removing finalizer from VirtualMachine")
return ctrl.Result{}, err
}
}
// Stop reconciliation as the item is being deleted
return ctrl.Result{}, nil
}
statusBefore := virtualmachine.Status.DeepCopy()
if err := r.doReconcile(ctx, &virtualmachine); err != nil {
r.Recorder.Eventf(&virtualmachine, corev1.EventTypeWarning, "Failed",
"Failed to reconcile (%s): %s", virtualmachine.Name, err)
return ctrl.Result{}, err
}
// If the status changed, try to update the object
if !DeepEqual(statusBefore, virtualmachine.Status) {
if err := r.Status().Update(ctx, &virtualmachine); err != nil {
log.Error(err, "Failed to update VirtualMachine status after reconcile loop",
"virtualmachine", virtualmachine.Name)
return ctrl.Result{}, err
}
}
return ctrl.Result{RequeueAfter: time.Second}, nil
}
// doFinalizerOperationsForVirtualMachine will perform the required operations before delete the CR.
func (r *VirtualMachineReconciler) doFinalizerOperationsForVirtualMachine(ctx context.Context, virtualmachine *vmv1.VirtualMachine) {
// Note: It is not recommended to use finalizers with the purpose of delete resources which are
// created and managed in the reconciliation. These ones, such as the Pod created on this reconcile,
// are defined as depended of the custom resource. See that we use the method ctrl.SetControllerReference.
// to set the ownerRef which means that the Deployment will be deleted by the Kubernetes API.
// More info: https://kubernetes.io/docs/tasks/administer-cluster/use-cascading-deletion/
log := log.FromContext(ctx)
// The following implementation will raise an event
r.Recorder.Event(virtualmachine, "Warning", "Deleting",
fmt.Sprintf("Custom Resource %s is being deleted from the namespace %s",
virtualmachine.Name,
virtualmachine.Namespace))
// Release overlay IP address
if virtualmachine.Spec.ExtraNetwork != nil {
// Create IPAM object
nadName, err := nadIpamName()
if err != nil {
// ignore error
log.Error(err, "ignored error")
return
}
nadNamespace, err := nadIpamNamespace()
if err != nil {
// ignore error
log.Error(err, "ignored error")
return
}
ipam, err := ipam.New(ctx, nadName, nadNamespace)
if err != nil {
// ignore error
log.Error(err, "ignored error")
return
}
defer ipam.Close()
ip, err := ipam.ReleaseIP(ctx, virtualmachine.Name, virtualmachine.Namespace)
if err != nil {
// ignore error
log.Error(err, "fail to release IP, error ignored")
return
}
message := fmt.Sprintf("Released IP %s", ip.String())
log.Info(message)
r.Recorder.Event(virtualmachine, "Normal", "OverlayNet", message)
}
}
func getRunnerVersion(pod *corev1.Pod) (api.RunnerProtoVersion, error) {
val, ok := pod.Labels[vmv1.RunnerPodVersionLabel]
if !ok {
return api.RunnerProtoVersion(0), nil
}
uintVal, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return 0, fmt.Errorf("failed to parse label value as integer: %w", err)
}
return api.RunnerProtoVersion(uintVal), nil
}
func runnerVersionIsSupported(version api.RunnerProtoVersion) bool {
return version >= minSupportedRunnerVersion && version <= maxSupportedRunnerVersion
}
func (r *VirtualMachineReconciler) updateVMStatusCPU(
ctx context.Context,
virtualmachine *vmv1.VirtualMachine,
vmRunner *corev1.Pod,
qmpPluggedCPUs uint32,
cgroupUsage *api.VCPUCgroup,
) {
log := log.FromContext(ctx)
// We expect:
// - vm.Status.CPUs = cgroupUsage.VCPUs
// - vm.Status.CPUs.RoundUp() == qmpPluggedCPUs
// Otherwise, we update the status.
var currentCPUUsage vmv1.MilliCPU
if cgroupUsage != nil {
if cgroupUsage.VCPUs.RoundedUp() != qmpPluggedCPUs {
// This is not expected but it's fine. We only report the
// mismatch here and will resolve it in the next reconcile
// iteration loops by comparing these values to spec CPU use
// and moving to the scaling phase.
log.Error(nil, "Mismatch in the number of VM's plugged CPUs and runner pod's cgroup vCPUs",
"VirtualMachine", virtualmachine.Name,
"Runner Pod", vmRunner.Name,
"plugged CPUs", qmpPluggedCPUs,
"cgroup vCPUs", cgroupUsage.VCPUs)
}
currentCPUUsage = min(cgroupUsage.VCPUs, vmv1.MilliCPU(1000*qmpPluggedCPUs))
} else {
currentCPUUsage = vmv1.MilliCPU(1000 * qmpPluggedCPUs)
}
if virtualmachine.Status.CPUs == nil || *virtualmachine.Status.CPUs != currentCPUUsage {
virtualmachine.Status.CPUs = ¤tCPUUsage
r.Recorder.Event(virtualmachine, "Normal", "CpuInfo",
fmt.Sprintf("VirtualMachine %s uses %v cpu cores",
virtualmachine.Name,
virtualmachine.Status.CPUs))
}
}
func (r *VirtualMachineReconciler) updateVMStatusMemory(
virtualmachine *vmv1.VirtualMachine,
qmpMemorySize *resource.Quantity,
) {
if virtualmachine.Status.MemorySize == nil || !qmpMemorySize.Equal(*virtualmachine.Status.MemorySize) {
virtualmachine.Status.MemorySize = qmpMemorySize
r.Recorder.Event(virtualmachine, "Normal", "MemoryInfo",
fmt.Sprintf("VirtualMachine %s uses %v memory",
virtualmachine.Name,
virtualmachine.Status.MemorySize))
}
}
func (r *VirtualMachineReconciler) doReconcile(ctx context.Context, virtualmachine *vmv1.VirtualMachine) error {
log := log.FromContext(ctx)
// Let's check and just set the condition status as Unknown when no status are available
if virtualmachine.Status.Conditions == nil || len(virtualmachine.Status.Conditions) == 0 {
// set Unknown condition status for AvailableVirtualMachine
meta.SetStatusCondition(&virtualmachine.Status.Conditions, metav1.Condition{Type: typeAvailableVirtualMachine, Status: metav1.ConditionUnknown, Reason: "Reconciling", Message: "Starting reconciliation"})
}
// NB: .Spec.EnableSSH guaranteed non-nil because the k8s API server sets the default for us.
enableSSH := *virtualmachine.Spec.EnableSSH
// Generate ssh secret name
if enableSSH && len(virtualmachine.Status.SSHSecretName) == 0 {
virtualmachine.Status.SSHSecretName = fmt.Sprintf("ssh-neonvm-%s", virtualmachine.Name)
}
// Generate runner pod name
if len(virtualmachine.Status.PodName) == 0 {
virtualmachine.Status.PodName = names.SimpleNameGenerator.GenerateName(fmt.Sprintf("%s-", virtualmachine.Name))
// Update the .Status on API Server to avoid creating multiple pods for a single VM
// See https://github.com/neondatabase/autoscaling/issues/794 for the context
if err := r.Status().Update(ctx, virtualmachine); err != nil {
return fmt.Errorf("Failed to update VirtualMachine status: %w", err)
}
}
switch virtualmachine.Status.Phase {
case "":
// Acquire overlay IP address
if virtualmachine.Spec.ExtraNetwork != nil &&
virtualmachine.Spec.ExtraNetwork.Enable &&
len(virtualmachine.Status.ExtraNetIP) == 0 {
// Create IPAM object
nadName, err := nadIpamName()
if err != nil {
return err
}
nadNamespace, err := nadIpamNamespace()
if err != nil {
return err
}
ipam, err := ipam.New(ctx, nadName, nadNamespace)
if err != nil {
log.Error(err, "failed to create IPAM")
return err
}
defer ipam.Close()
ip, err := ipam.AcquireIP(ctx, virtualmachine.Name, virtualmachine.Namespace)
if err != nil {
log.Error(err, "fail to acquire IP")
return err
}
message := fmt.Sprintf("Acquired IP %s for overlay network interface", ip.String())
log.Info(message)
virtualmachine.Status.ExtraNetIP = ip.IP.String()
virtualmachine.Status.ExtraNetMask = fmt.Sprintf("%d.%d.%d.%d", ip.Mask[0], ip.Mask[1], ip.Mask[2], ip.Mask[3])
r.Recorder.Event(virtualmachine, "Normal", "OverlayNet", message)
}
// VirtualMachine just created, change Phase to "Pending"
virtualmachine.Status.Phase = vmv1.VmPending
case vmv1.VmPending:
// Check if the runner pod already exists, if not create a new one
vmRunner := &corev1.Pod{}
err := r.Get(ctx, types.NamespacedName{Name: virtualmachine.Status.PodName, Namespace: virtualmachine.Namespace}, vmRunner)
if err != nil && apierrors.IsNotFound(err) {
var sshSecret *corev1.Secret
if enableSSH {
// Check if the ssh secret already exists, if not create a new one
sshSecret = &corev1.Secret{}
err := r.Get(ctx, types.NamespacedName{
Name: virtualmachine.Status.SSHSecretName,
Namespace: virtualmachine.Namespace,
}, sshSecret)
if err != nil && apierrors.IsNotFound(err) {
// Define a new ssh secret
sshSecret, err = r.sshSecretForVirtualMachine(virtualmachine)
if err != nil {
log.Error(err, "Failed to define new SSH Secret for VirtualMachine")
return err
}
log.Info("Creating a new SSH Secret", "Secret.Namespace", sshSecret.Namespace, "Secret.Name", sshSecret.Name)
if err = r.Create(ctx, sshSecret); err != nil {
log.Error(err, "Failed to create new SSH secret", "Secret.Namespace", sshSecret.Namespace, "Secret.Name", sshSecret.Name)
return err
}
log.Info("SSH Secret was created", "Secret.Namespace", sshSecret.Namespace, "Secret.Name", sshSecret.Name)
} else if err != nil {
log.Error(err, "Failed to get SSH Secret")
return err
}
}
// Define a new pod
pod, err := r.podForVirtualMachine(virtualmachine, sshSecret)
if err != nil {
log.Error(err, "Failed to define new Pod resource for VirtualMachine")
return err
}
log.Info("Creating a new Pod", "Pod.Namespace", pod.Namespace, "Pod.Name", pod.Name)
if err = r.Create(ctx, pod); err != nil {
log.Error(err, "Failed to create new Pod", "Pod.Namespace", pod.Namespace, "Pod.Name", pod.Name)
return err
}
log.Info("Runner Pod was created", "Pod.Namespace", pod.Namespace, "Pod.Name", pod.Name)
msg := fmt.Sprintf("VirtualMachine %s created, Pod %s", virtualmachine.Name, pod.Name)
if sshSecret != nil {
msg = fmt.Sprintf("%s, SSH Secret %s", msg, sshSecret.Name)
}
r.Recorder.Event(virtualmachine, "Normal", "Created", msg)
if !virtualmachine.HasRestarted() {
d := pod.CreationTimestamp.Time.Sub(virtualmachine.CreationTimestamp.Time)
r.Metrics.vmCreationToRunnerCreationTime.Observe(d.Seconds())
}
} else if err != nil {
log.Error(err, "Failed to get vm-runner Pod")
return err
}
// runner pod found, check phase
switch runnerStatus(vmRunner) {
case runnerRunning:
virtualmachine.Status.PodIP = vmRunner.Status.PodIP
virtualmachine.Status.Phase = vmv1.VmRunning
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) created successfully", virtualmachine.Status.PodName, virtualmachine.Name)})
{
// Calculating VM startup latency metrics
now := time.Now()
d := now.Sub(vmRunner.CreationTimestamp.Time)
r.Metrics.runnerCreationToVMRunningTime.Observe(d.Seconds())
if !virtualmachine.HasRestarted() {
d := now.Sub(virtualmachine.CreationTimestamp.Time)
r.Metrics.vmCreationToVMRunningTime.Observe(d.Seconds())
log.Info("VM creation to VM running time", "duration(sec)", d.Seconds())
}
}
case runnerSucceeded:
virtualmachine.Status.Phase = vmv1.VmSucceeded
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionFalse,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) succeeded", virtualmachine.Status.PodName, virtualmachine.Name)})
case runnerFailed:
virtualmachine.Status.Phase = vmv1.VmFailed
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeDegradedVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) failed", virtualmachine.Status.PodName, virtualmachine.Name)})
case runnerUnknown:
virtualmachine.Status.Phase = vmv1.VmPending
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionUnknown,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) in Unknown phase", virtualmachine.Status.PodName, virtualmachine.Name)})
default:
// do nothing
}
case vmv1.VmRunning:
// Check if the runner pod exists
vmRunner := &corev1.Pod{}
err := r.Get(ctx, types.NamespacedName{Name: virtualmachine.Status.PodName, Namespace: virtualmachine.Namespace}, vmRunner)
if err != nil && apierrors.IsNotFound(err) {
// lost runner pod for running VirtualMachine ?
r.Recorder.Event(virtualmachine, "Warning", "NotFound",
fmt.Sprintf("runner pod %s not found",
virtualmachine.Status.PodName))
virtualmachine.Status.Phase = vmv1.VmFailed
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeDegradedVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) not found", virtualmachine.Status.PodName, virtualmachine.Name)})
} else if err != nil {
log.Error(err, "Failed to get runner Pod")
return err
}
// Update the metadata (including "usage" annotation) before anything else, so that it
// will be correctly set even if the rest of the reconcile operation fails.
if err := updatePodMetadataIfNecessary(ctx, r.Client, virtualmachine, vmRunner); err != nil {
log.Error(err, "Failed to sync pod labels and annotations", "VirtualMachine", virtualmachine.Name)
}
// runner pod found, check/update phase now
switch runnerStatus(vmRunner) {
case runnerRunning:
// update status by IP of runner pod
virtualmachine.Status.PodIP = vmRunner.Status.PodIP
// update phase
virtualmachine.Status.Phase = vmv1.VmRunning
// update Node name where runner working
virtualmachine.Status.Node = vmRunner.Spec.NodeName
runnerVersion, err := getRunnerVersion(vmRunner)
if err != nil {
log.Error(err, "Failed to get runner version of VM runner pod", "VirtualMachine", virtualmachine.Name)
return err
}
if !runnerVersionIsSupported(runnerVersion) {
err := fmt.Errorf("runner version %v is not supported", runnerVersion)
log.Error(err, "VM runner pod has unsupported version", "VirtualMachine", virtualmachine.Name)
return err
}
// get CPU details from QEMU
cpuSlotsPlugged, _, err := QmpGetCpus(QmpAddr(virtualmachine))
if err != nil {
log.Error(err, "Failed to get CPU details from VirtualMachine", "VirtualMachine", virtualmachine.Name)
return err
}
pluggedCPU := uint32(len(cpuSlotsPlugged))
// get cgroups CPU details from runner pod
cgroupUsage, err := getRunnerCgroup(ctx, virtualmachine)
if err != nil {
log.Error(err, "Failed to get CPU details from runner", "VirtualMachine", virtualmachine.Name)
return err
}
// update status by CPUs used in the VM
r.updateVMStatusCPU(ctx, virtualmachine, vmRunner, pluggedCPU, cgroupUsage)
// get Memory details from hypervisor and update VM status
memorySize, err := QmpGetMemorySize(QmpAddr(virtualmachine))
if err != nil {
log.Error(err, "Failed to get Memory details from VirtualMachine", "VirtualMachine", virtualmachine.Name)
return err
}
// update status by memory sizes used in the VM
r.updateVMStatusMemory(virtualmachine, memorySize)
// check if need hotplug/unplug CPU or memory
// compare guest spec and count of plugged
specUseCPU := virtualmachine.Spec.Guest.CPUs.Use
scaleCgroupCPU := *specUseCPU != cgroupUsage.VCPUs
scaleQemuCPU := specUseCPU.RoundedUp() != pluggedCPU
if scaleCgroupCPU || scaleQemuCPU {
log.Info("VM goes into scaling mode, CPU count needs to be changed",
"CPUs on runner pod cgroup", cgroupUsage.VCPUs,
"CPUs on board", pluggedCPU,
"CPUs in spec", virtualmachine.Spec.Guest.CPUs.Use)
virtualmachine.Status.Phase = vmv1.VmScaling
}
memorySizeFromSpec := resource.NewQuantity(int64(*virtualmachine.Spec.Guest.MemorySlots.Use)*virtualmachine.Spec.Guest.MemorySlotSize.Value(), resource.BinarySI)
if !memorySize.Equal(*memorySizeFromSpec) {
log.Info("VM goes into scale mode, need to resize Memory",
"Memory on board", memorySize,
"Memory in spec", memorySizeFromSpec)
virtualmachine.Status.Phase = vmv1.VmScaling
}
case runnerSucceeded:
virtualmachine.Status.Phase = vmv1.VmSucceeded
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionFalse,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) succeeded", virtualmachine.Status.PodName, virtualmachine.Name)})
case runnerFailed:
virtualmachine.Status.Phase = vmv1.VmFailed
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeDegradedVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) failed", virtualmachine.Status.PodName, virtualmachine.Name)})
case runnerUnknown:
virtualmachine.Status.Phase = vmv1.VmPending
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionUnknown,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) in Unknown phase", virtualmachine.Status.PodName, virtualmachine.Name)})
default:
// do nothing
}
case vmv1.VmScaling:
// Check that runner pod is still ok
vmRunner := &corev1.Pod{}
err := r.Get(ctx, types.NamespacedName{Name: virtualmachine.Status.PodName, Namespace: virtualmachine.Namespace}, vmRunner)
if err != nil && apierrors.IsNotFound(err) {
// lost runner pod for running VirtualMachine ?
r.Recorder.Event(virtualmachine, "Warning", "NotFound",
fmt.Sprintf("runner pod %s not found",
virtualmachine.Status.PodName))
virtualmachine.Status.Phase = vmv1.VmFailed
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeDegradedVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) not found", virtualmachine.Status.PodName, virtualmachine.Name)})
} else if err != nil {
log.Error(err, "Failed to get runner Pod")
return err
}
// Update the metadata (including "usage" annotation) before anything else, so that it
// will be correctly set even if the rest of the reconcile operation fails.
if err := updatePodMetadataIfNecessary(ctx, r.Client, virtualmachine, vmRunner); err != nil {
log.Error(err, "Failed to sync pod labels and annotations", "VirtualMachine", virtualmachine.Name)
}
// runner pod found, check that it's still up:
switch runnerStatus(vmRunner) {
case runnerSucceeded:
virtualmachine.Status.Phase = vmv1.VmSucceeded
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionFalse,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) succeeded", virtualmachine.Status.PodName, virtualmachine.Name)})
return nil
case runnerFailed:
virtualmachine.Status.Phase = vmv1.VmFailed
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeDegradedVirtualMachine,
Status: metav1.ConditionTrue,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) failed", virtualmachine.Status.PodName, virtualmachine.Name)})
return nil
case runnerUnknown:
virtualmachine.Status.Phase = vmv1.VmPending
meta.SetStatusCondition(&virtualmachine.Status.Conditions,
metav1.Condition{Type: typeAvailableVirtualMachine,
Status: metav1.ConditionUnknown,
Reason: "Reconciling",
Message: fmt.Sprintf("Pod (%s) for VirtualMachine (%s) in Unknown phase", virtualmachine.Status.PodName, virtualmachine.Name)})
return nil
default:
// do nothing
}
runnerVersion, err := getRunnerVersion(vmRunner)
if err != nil {
log.Error(err, "Failed to get runner version of VM runner pod", "VirtualMachine", virtualmachine.Name)
return err
}
if !runnerVersionIsSupported(runnerVersion) {
err := fmt.Errorf("runner version %v is not supported", runnerVersion)
log.Error(err, "VM runner pod has unsupported version", "VirtualMachine", virtualmachine.Name)
return err
}
cpuScaled := false
ramScaled := false
// do hotplug/unplug CPU
// firstly get current state from QEMU
cpuSlotsPlugged, _, err := QmpGetCpus(QmpAddr(virtualmachine))
if err != nil {
log.Error(err, "Failed to get CPU details from VirtualMachine", "VirtualMachine", virtualmachine.Name)
return err
}
specCPU := virtualmachine.Spec.Guest.CPUs.Use
pluggedCPU := uint32(len(cpuSlotsPlugged))
cgroupUsage, err := getRunnerCgroup(ctx, virtualmachine)
if err != nil {
log.Error(err, "Failed to get CPU details from runner", "VirtualMachine", virtualmachine.Name)
return err
}
// compare guest spec to count of plugged and runner pod cgroups
if specCPU.RoundedUp() > pluggedCPU {
// going to plug one CPU
log.Info("Plug one more CPU into VM")
if err := QmpPlugCpu(QmpAddr(virtualmachine)); err != nil {
return err
}
r.Recorder.Event(virtualmachine, "Normal", "ScaleUp",
fmt.Sprintf("One more CPU was plugged into VM %s",
virtualmachine.Name))
} else if specCPU.RoundedUp() < pluggedCPU {
// going to unplug one CPU
log.Info("Unplug one CPU from VM")
if err := QmpUnplugCpu(QmpAddr(virtualmachine)); err != nil {
return err
}
r.Recorder.Event(virtualmachine, "Normal", "ScaleDown",
fmt.Sprintf("One CPU was unplugged from VM %s",
virtualmachine.Name))
} else if *specCPU != cgroupUsage.VCPUs {
log.Info("Update runner pod cgroups", "runner", cgroupUsage.VCPUs, "spec", *specCPU)
if err := setRunnerCgroup(ctx, virtualmachine, *specCPU); err != nil {
return err
}
reason := "ScaleDown"
if *specCPU > cgroupUsage.VCPUs {
reason = "ScaleUp"
}
r.Recorder.Event(virtualmachine, "Normal", reason,
fmt.Sprintf("Runner pod cgroups was updated on VM %s",
virtualmachine.Name))
} else {
// seems already plugged correctly
cpuScaled = true
}
// do hotplug/unplug Memory
memSlotsMin := *virtualmachine.Spec.Guest.MemorySlots.Min
targetSlotCount := int(*virtualmachine.Spec.Guest.MemorySlots.Use - memSlotsMin)
realSlots, err := QmpSetMemorySlots(ctx, virtualmachine, targetSlotCount, r.Recorder)
if realSlots < 0 {
return err
}
if realSlots != int(targetSlotCount) {
log.Info("Couldn't achieve desired memory slot count, will modify .spec.guest.memorySlots.use instead", "details", err)
// firstly re-fetch VM
if err := r.Get(ctx, types.NamespacedName{Name: virtualmachine.Name, Namespace: virtualmachine.Namespace}, virtualmachine); err != nil {
log.Error(err, "Unable to re-fetch VirtualMachine")
return err
}
memorySlotsUseInSpec := *virtualmachine.Spec.Guest.MemorySlots.Use
memoryPluggedSlots := memSlotsMin + int32(realSlots)
*virtualmachine.Spec.Guest.MemorySlots.Use = memoryPluggedSlots
if err := r.tryUpdateVM(ctx, virtualmachine); err != nil {
log.Error(err, "Failed to update .spec.guest.memorySlots.use",
"old value", memorySlotsUseInSpec,
"new value", memoryPluggedSlots)
return err
}
} else {
ramScaled = true
}
// set VM phase to running if everything scaled
if cpuScaled && ramScaled {
// update status by CPUs used in the VM
r.updateVMStatusCPU(ctx, virtualmachine, vmRunner, pluggedCPU, cgroupUsage)
// get Memory details from hypervisor and update VM status
memorySize, err := QmpGetMemorySize(QmpAddr(virtualmachine))
if err != nil {
log.Error(err, "Failed to get Memory details from VirtualMachine", "VirtualMachine", virtualmachine.Name)
return err
}
// update status by memory sizes used in the VM
r.updateVMStatusMemory(virtualmachine, memorySize)
virtualmachine.Status.Phase = vmv1.VmRunning
}
case vmv1.VmSucceeded, vmv1.VmFailed:
// Always delete runner pod. Otherwise, we could end up with one container succeeded/failed
// but the other one still running (meaning that the pod still ends up Running).
vmRunner := &corev1.Pod{}
err := r.Get(ctx, types.NamespacedName{Name: virtualmachine.Status.PodName, Namespace: virtualmachine.Namespace}, vmRunner)
if err == nil {
// delete current runner
if err := r.deleteRunnerPodIfEnabled(ctx, virtualmachine, vmRunner); err != nil {
return err
}
} else if !apierrors.IsNotFound(err) {
return err
}
// We must keep the VM status the same until we know the neonvm-runner container has been
// terminated, otherwise we could end up starting a new runner pod while the VM in the old
// one is still running.
//
// Note that this is required because 'VmSucceeded' and 'VmFailed' are true if *at least
// one* container inside the runner pod has finished; the VM itself may still be running.
if apierrors.IsNotFound(err) || runnerContainerStopped(vmRunner) {
// NB: Cleanup() leaves status .Phase and .RestartCount (+ some others) but unsets other fields.
virtualmachine.Cleanup()
var shouldRestart bool
switch virtualmachine.Spec.RestartPolicy {
case vmv1.RestartPolicyAlways:
shouldRestart = true
case vmv1.RestartPolicyOnFailure:
shouldRestart = virtualmachine.Status.Phase == vmv1.VmFailed
case vmv1.RestartPolicyNever:
shouldRestart = false
}
if shouldRestart {
log.Info("Restarting VM runner pod", "VM.Phase", virtualmachine.Status.Phase, "RestartPolicy", virtualmachine.Spec.RestartPolicy)
virtualmachine.Status.Phase = vmv1.VmPending // reset to trigger restart
virtualmachine.Status.RestartCount += 1 // increment restart count
r.Metrics.vmRestartCounts.Inc()
}
// TODO for RestartPolicyNever: implement TTL or do nothing
}
default:
// do nothing
}
return nil
}
type runnerStatusKind string
const (
runnerUnknown runnerStatusKind = "Unknown"
runnerPending runnerStatusKind = "Pending"
runnerRunning runnerStatusKind = "Running"
runnerFailed runnerStatusKind = "Failed"
runnerSucceeded runnerStatusKind = "Succeeded"
)
// runnerStatus returns a description of the status of the VM inside the runner pod.
//
// This is *similar* to the value of pod.Status.Phase, but takes into consideration the statuses of
// the individual containers within the pod. This is because Kubernetes sets the pod phase to Failed
// or Succeeded only if *all* pods have exited, whereas we'd like to consider the VM to be Failed or
// Succeeded if *any* pod has exited.
//
// The full set of outputs is:
//
// - runnerUnknown, if pod.Status.Phase is Unknown
// - runnerPending, if pod.Status.Phase is "" or Pending
// - runnerRunning, if pod.Status.Phase is Running, and no containers have exited
// - runnerFailed, if pod.Status.Phase is Failed, or if any container has failed, or if any
// container other than neonvm-runner has exited
// - runnerSucceeded, if pod.Status.Phase is Succeeded, or if neonvm-runner has exited
// successfully
func runnerStatus(pod *corev1.Pod) runnerStatusKind {
switch pod.Status.Phase {
case "", corev1.PodPending:
return runnerPending
case corev1.PodSucceeded:
return runnerSucceeded
case corev1.PodFailed:
return runnerFailed
case corev1.PodUnknown:
return runnerUnknown
// See comment above for context on this logic
case corev1.PodRunning:
nonRunnerContainerSucceeded := false
runnerContainerSucceeded := false
for _, stat := range pod.Status.ContainerStatuses {
if stat.State.Terminated != nil {
failed := stat.State.Terminated.ExitCode != 0
isRunner := stat.Name == "neonvm-runner"
if failed {
// return that the "runner" has failed if any container has.
return runnerFailed
} else /* succeeded */ {
if isRunner {
// neonvm-runner succeeded. We'll return runnerSucceeded if no other
// container has failed.
runnerContainerSucceeded = true
} else {
// Other container has succeeded. We'll return runnerSucceeded if
// neonvm-runner has succeeded, but runnerFailed if this exited while
// neonvm-runner is still going.
nonRunnerContainerSucceeded = true
}
}
}
}
if runnerContainerSucceeded {
return runnerSucceeded
} else if nonRunnerContainerSucceeded {
return runnerFailed
} else {
return runnerRunning
}
default:
panic(fmt.Errorf("unknown pod phase: %q", pod.Status.Phase))
}
}
// runnerContainerStopped returns true iff the neonvm-runner container has exited.
//
// The guarantee is simple: It is only safe to start a new runner pod for a VM if
// runnerContainerStopped returns true (otherwise, we may end up with >1 instance of the same VM).
func runnerContainerStopped(pod *corev1.Pod) bool {
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
return true
}
for _, stat := range pod.Status.ContainerStatuses {
if stat.Name == "neonvm-runner" {
return stat.State.Terminated != nil
}
}
return false
}
// deleteRunnerPodIfEnabled deletes the runner pod if buildtag.NeverDeleteRunnerPods is false, and
// then emits an event and log line about what it did, whether it actually deleted the runner pod.
func (r *VirtualMachineReconciler) deleteRunnerPodIfEnabled(
ctx context.Context,
virtualmachine *vmv1.VirtualMachine,
runner *corev1.Pod,
) error {
log := log.FromContext(ctx)
var msg, eventReason string
if buildtag.NeverDeleteRunnerPods {
msg = fmt.Sprintf("VM runner pod deletion was skipped due to '%s' build tag", buildtag.TagnameNeverDeleteRunnerPods)
eventReason = "DeleteSkipped"
} else {
// delete current runner
if err := r.Delete(ctx, runner); err != nil {
return err
}
msg = "VM runner pod was deleted"
eventReason = "Deleted"
}
log.Info(msg, "Pod.Namespace", runner.Namespace, "Pod.Name", runner.Name)
r.Recorder.Event(virtualmachine, "Normal", eventReason, fmt.Sprintf("%s: %s", msg, runner.Name))
return nil
}
// updates the values of the runner pod's labels and annotations so that they are exactly equal to
// the set of labels/annotations we expect - minus some that are ignored.
//
// The reason we also need to delete unrecognized labels/annotations is so that if a
// label/annotation on the VM itself is deleted, we can accurately reflect that in the pod.
func updatePodMetadataIfNecessary(ctx context.Context, c client.Client, vm *vmv1.VirtualMachine, runnerPod *corev1.Pod) error {
log := log.FromContext(ctx)
var patches []patch.Operation
metaSpecs := []struct {
metaField string
expected map[string]string
actual map[string]string
ignoreExtra map[string]bool // use bool here so `if ignoreExtra[key] { ... }` works
}{
{
metaField: "labels",
expected: labelsForVirtualMachine(vm, nil), // don't include runner version
actual: runnerPod.Labels,
ignoreExtra: map[string]bool{
// Don't override the runner pod version - we need to keep it around without
// changing it; otherwise it's not useful!
vmv1.RunnerPodVersionLabel: true,
},
},
{
metaField: "annotations",
expected: annotationsForVirtualMachine(vm),
actual: runnerPod.Annotations,
ignoreExtra: map[string]bool{
"k8s.v1.cni.cncf.io/networks": true,
"k8s.v1.cni.cncf.io/network-status": true,
"k8s.v1.cni.cncf.io/networks-status": true,
},
},
}
var removedMessageParts []string
for _, spec := range metaSpecs {
// Add/update the entries we're expecting to be there
for k, e := range spec.expected {
if a, ok := spec.actual[k]; !ok || e != a {
patches = append(patches, patch.Operation{
// From RFC 6902 (JSON patch):
//
// > The "add" operation performs one of the following functions, depending upon
// > what the target location references:
// >
// > [ ... ]
// >
// > * If the target location specifies an object member that does not already
// > exist, a new member is added to the object.
// > * If the target location specifies an object member that does exist, that
// > member's value is replaced.
//
// So: if the value is missing we'll add it. And if it's different, we'll replace it.
Op: patch.OpAdd,
Path: fmt.Sprintf("/metadata/%s/%s", spec.metaField, patch.PathEscape(k)),
Value: e,
})
}
}
// Remove the entries we aren't expecting to be there
var removed []string