-
Notifications
You must be signed in to change notification settings - Fork 254
/
util.go
1759 lines (1538 loc) · 62 KB
/
util.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 The CDI Authors.
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 common
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"fmt"
"io"
"math"
"net/http"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-logr/logr"
snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v6/apis/volumesnapshot/v1"
ocpconfigv1 "github.com/openshift/api/config/v1"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
k8serrors "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/sets"
"k8s.io/client-go/tools/record"
"k8s.io/klog/v2"
"k8s.io/utils/pointer"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
cdiv1utils "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1/utils"
"kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme"
"kubevirt.io/containerized-data-importer/pkg/common"
featuregates "kubevirt.io/containerized-data-importer/pkg/feature-gates"
"kubevirt.io/containerized-data-importer/pkg/token"
"kubevirt.io/containerized-data-importer/pkg/util"
sdkapi "kubevirt.io/controller-lifecycle-operator-sdk/api"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
const (
// DataVolName provides a const to use for creating volumes in pod specs
DataVolName = "cdi-data-vol"
// ScratchVolName provides a const to use for creating scratch pvc volumes in pod specs
ScratchVolName = "cdi-scratch-vol"
// AnnAPIGroup is the APIGroup for CDI
AnnAPIGroup = "cdi.kubevirt.io"
// AnnCreatedBy is a pod annotation indicating if the pod was created by the PVC
AnnCreatedBy = AnnAPIGroup + "/storage.createdByController"
// AnnPodPhase is a PVC annotation indicating the related pod progress (phase)
AnnPodPhase = AnnAPIGroup + "/storage.pod.phase"
// AnnPodReady tells whether the pod is ready
AnnPodReady = AnnAPIGroup + "/storage.pod.ready"
// AnnPodRestarts is a PVC annotation that tells how many times a related pod was restarted
AnnPodRestarts = AnnAPIGroup + "/storage.pod.restarts"
// AnnPopulatedFor is a PVC annotation telling the datavolume controller that the PVC is already populated
AnnPopulatedFor = AnnAPIGroup + "/storage.populatedFor"
// AnnPrePopulated is a PVC annotation telling the datavolume controller that the PVC is already populated
AnnPrePopulated = AnnAPIGroup + "/storage.prePopulated"
// AnnPriorityClassName is PVC annotation to indicate the priority class name for importer, cloner and uploader pod
AnnPriorityClassName = AnnAPIGroup + "/storage.pod.priorityclassname"
// AnnExternalPopulation annotation marks a PVC as "externally populated", allowing the import-controller to skip it
AnnExternalPopulation = AnnAPIGroup + "/externalPopulation"
// AnnDeleteAfterCompletion is PVC annotation for deleting DV after completion
AnnDeleteAfterCompletion = AnnAPIGroup + "/storage.deleteAfterCompletion"
// AnnPodRetainAfterCompletion is PVC annotation for retaining transfer pods after completion
AnnPodRetainAfterCompletion = AnnAPIGroup + "/storage.pod.retainAfterCompletion"
// AnnPreviousCheckpoint provides a const to indicate the previous snapshot for a multistage import
AnnPreviousCheckpoint = AnnAPIGroup + "/storage.checkpoint.previous"
// AnnCurrentCheckpoint provides a const to indicate the current snapshot for a multistage import
AnnCurrentCheckpoint = AnnAPIGroup + "/storage.checkpoint.current"
// AnnFinalCheckpoint provides a const to indicate whether the current checkpoint is the last one
AnnFinalCheckpoint = AnnAPIGroup + "/storage.checkpoint.final"
// AnnCheckpointsCopied is a prefix for recording which checkpoints have already been copied
AnnCheckpointsCopied = AnnAPIGroup + "/storage.checkpoint.copied"
// AnnCurrentPodID keeps track of the latest pod servicing this PVC
AnnCurrentPodID = AnnAPIGroup + "/storage.checkpoint.pod.id"
// AnnMultiStageImportDone marks a multi-stage import as totally finished
AnnMultiStageImportDone = AnnAPIGroup + "/storage.checkpoint.done"
// AnnPopulatorProgress is a standard annotation that can be used progress reporting
AnnPopulatorProgress = AnnAPIGroup + "/storage.populator.progress"
// AnnPreallocationRequested provides a const to indicate whether preallocation should be performed on the PV
AnnPreallocationRequested = AnnAPIGroup + "/storage.preallocation.requested"
// AnnPreallocationApplied provides a const for PVC preallocation annotation
AnnPreallocationApplied = AnnAPIGroup + "/storage.preallocation"
// AnnRunningCondition provides a const for the running condition
AnnRunningCondition = AnnAPIGroup + "/storage.condition.running"
// AnnRunningConditionMessage provides a const for the running condition
AnnRunningConditionMessage = AnnAPIGroup + "/storage.condition.running.message"
// AnnRunningConditionReason provides a const for the running condition
AnnRunningConditionReason = AnnAPIGroup + "/storage.condition.running.reason"
// AnnBoundCondition provides a const for the running condition
AnnBoundCondition = AnnAPIGroup + "/storage.condition.bound"
// AnnBoundConditionMessage provides a const for the running condition
AnnBoundConditionMessage = AnnAPIGroup + "/storage.condition.bound.message"
// AnnBoundConditionReason provides a const for the running condition
AnnBoundConditionReason = AnnAPIGroup + "/storage.condition.bound.reason"
// AnnSourceRunningCondition provides a const for the running condition
AnnSourceRunningCondition = AnnAPIGroup + "/storage.condition.source.running"
// AnnSourceRunningConditionMessage provides a const for the running condition
AnnSourceRunningConditionMessage = AnnAPIGroup + "/storage.condition.source.running.message"
// AnnSourceRunningConditionReason provides a const for the running condition
AnnSourceRunningConditionReason = AnnAPIGroup + "/storage.condition.source.running.reason"
// AnnVddkVersion shows the last VDDK library version used by a DV's importer pod
AnnVddkVersion = AnnAPIGroup + "/storage.pod.vddk.version"
// AnnVddkHostConnection shows the last ESX host that serviced a DV's importer pod
AnnVddkHostConnection = AnnAPIGroup + "/storage.pod.vddk.host"
// AnnVddkInitImageURL saves a per-DV VDDK image URL on the PVC
AnnVddkInitImageURL = AnnAPIGroup + "/storage.pod.vddk.initimageurl"
// AnnRequiresScratch provides a const for our PVC requires scratch annotation
AnnRequiresScratch = AnnAPIGroup + "/storage.import.requiresScratch"
// AnnContentType provides a const for the PVC content-type
AnnContentType = AnnAPIGroup + "/storage.contentType"
// AnnSource provide a const for our PVC import source annotation
AnnSource = AnnAPIGroup + "/storage.import.source"
// AnnEndpoint provides a const for our PVC endpoint annotation
AnnEndpoint = AnnAPIGroup + "/storage.import.endpoint"
// AnnSecret provides a const for our PVC secretName annotation
AnnSecret = AnnAPIGroup + "/storage.import.secretName"
// AnnCertConfigMap is the name of a configmap containing tls certs
AnnCertConfigMap = AnnAPIGroup + "/storage.import.certConfigMap"
// AnnRegistryImportMethod provides a const for registry import method annotation
AnnRegistryImportMethod = AnnAPIGroup + "/storage.import.registryImportMethod"
// AnnRegistryImageStream provides a const for registry image stream annotation
AnnRegistryImageStream = AnnAPIGroup + "/storage.import.registryImageStream"
// AnnImportPod provides a const for our PVC importPodName annotation
AnnImportPod = AnnAPIGroup + "/storage.import.importPodName"
// AnnDiskID provides a const for our PVC diskId annotation
AnnDiskID = AnnAPIGroup + "/storage.import.diskId"
// AnnUUID provides a const for our PVC uuid annotation
AnnUUID = AnnAPIGroup + "/storage.import.uuid"
// AnnBackingFile provides a const for our PVC backing file annotation
AnnBackingFile = AnnAPIGroup + "/storage.import.backingFile"
// AnnThumbprint provides a const for our PVC backing thumbprint annotation
AnnThumbprint = AnnAPIGroup + "/storage.import.vddk.thumbprint"
// AnnExtraHeaders provides a const for our PVC extraHeaders annotation
AnnExtraHeaders = AnnAPIGroup + "/storage.import.extraHeaders"
// AnnSecretExtraHeaders provides a const for our PVC secretExtraHeaders annotation
AnnSecretExtraHeaders = AnnAPIGroup + "/storage.import.secretExtraHeaders"
// AnnCloneToken is the annotation containing the clone token
AnnCloneToken = AnnAPIGroup + "/storage.clone.token"
// AnnExtendedCloneToken is the annotation containing the long term clone token
AnnExtendedCloneToken = AnnAPIGroup + "/storage.extended.clone.token"
// AnnPermissiveClone annotation allows the clone-controller to skip the clone size validation
AnnPermissiveClone = AnnAPIGroup + "/permissiveClone"
// AnnOwnerUID annotation has the owner UID
AnnOwnerUID = AnnAPIGroup + "/ownerUID"
// AnnCloneType is the comuuted/requested clone type
AnnCloneType = AnnAPIGroup + "/cloneType"
// AnnCloneSourcePod name of the source clone pod
AnnCloneSourcePod = "cdi.kubevirt.io/storage.sourceClonePodName"
// AnnUploadRequest marks that a PVC should be made available for upload
AnnUploadRequest = AnnAPIGroup + "/storage.upload.target"
// AnnCheckStaticVolume checks if a statically allocated PV exists before creating the target PVC.
// If so, PVC is still created but population is skipped
AnnCheckStaticVolume = AnnAPIGroup + "/storage.checkStaticVolume"
// AnnPersistentVolumeList is an annotation storing a list of PV names
AnnPersistentVolumeList = AnnAPIGroup + "/storage.persistentVolumeList"
// AnnPopulatorKind annotation is added to a PVC' to specify the population kind, so it's later
// checked by the common populator watches.
AnnPopulatorKind = AnnAPIGroup + "/storage.populator.kind"
//AnnUsePopulator annotation indicates if the datavolume population will use populators
AnnUsePopulator = AnnAPIGroup + "/storage.usePopulator"
//AnnDefaultStorageClass is the annotation indicating that a storage class is the default one.
AnnDefaultStorageClass = "storageclass.kubernetes.io/is-default-class"
// AnnOpenShiftImageLookup is the annotation for OpenShift image stream lookup
AnnOpenShiftImageLookup = "alpha.image.policy.openshift.io/resolve-names"
// AnnCloneRequest sets our expected annotation for a CloneRequest
AnnCloneRequest = "k8s.io/CloneRequest"
// AnnCloneOf is used to indicate that cloning was complete
AnnCloneOf = "k8s.io/CloneOf"
// AnnPodNetwork is used for specifying Pod Network
AnnPodNetwork = "k8s.v1.cni.cncf.io/networks"
// AnnPodMultusDefaultNetwork is used for specifying default Pod Network
AnnPodMultusDefaultNetwork = "v1.multus-cni.io/default-network"
// AnnPodSidecarInjection is used for enabling/disabling Pod istio/AspenMesh sidecar injection
AnnPodSidecarInjection = "sidecar.istio.io/inject"
// AnnPodSidecarInjectionDefault is the default value passed for AnnPodSidecarInjection
AnnPodSidecarInjectionDefault = "false"
// AnnImmediateBinding provides a const to indicate whether immediate binding should be performed on the PV (overrides global config)
AnnImmediateBinding = AnnAPIGroup + "/storage.bind.immediate.requested"
// AnnSelectedNode annotation is added to a PVC that has been triggered by scheduler to
// be dynamically provisioned. Its value is the name of the selected node.
AnnSelectedNode = "volume.kubernetes.io/selected-node"
// CloneUniqueID is used as a special label to be used when we search for the pod
CloneUniqueID = "cdi.kubevirt.io/storage.clone.cloneUniqeId"
// CloneSourceInUse is reason for event created when clone source pvc is in use
CloneSourceInUse = "CloneSourceInUse"
// CloneComplete message
CloneComplete = "Clone Complete"
cloneTokenLeeway = 10 * time.Second
// Default value for preallocation option if not defined in DV or CDIConfig
defaultPreallocation = false
// ErrStartingPod provides a const to indicate that a pod wasn't able to start without providing sensitive information (reason)
ErrStartingPod = "ErrStartingPod"
// MessageErrStartingPod provides a const to indicate that a pod wasn't able to start without providing sensitive information (message)
MessageErrStartingPod = "Error starting pod '%s': For more information, request access to cdi-deploy logs from your sysadmin"
// ErrClaimNotValid provides a const to indicate a claim is not valid
ErrClaimNotValid = "ErrClaimNotValid"
// ErrExceededQuota provides a const to indicate the claim has exceeded the quota
ErrExceededQuota = "ErrExceededQuota"
// ErrIncompatiblePVC provides a const to indicate a clone is not possible due to an incompatible PVC
ErrIncompatiblePVC = "ErrIncompatiblePVC"
// SourceHTTP is the source type HTTP, if unspecified or invalid, it defaults to SourceHTTP
SourceHTTP = "http"
// SourceS3 is the source type S3
SourceS3 = "s3"
// SourceGCS is the source type GCS
SourceGCS = "gcs"
// SourceGlance is the source type of glance
SourceGlance = "glance"
// SourceNone means there is no source.
SourceNone = "none"
// SourceRegistry is the source type of Registry
SourceRegistry = "registry"
// SourceImageio is the source type ovirt-imageio
SourceImageio = "imageio"
// SourceVDDK is the source type of VDDK
SourceVDDK = "vddk"
// ClaimLost reason const
ClaimLost = "ClaimLost"
// NotFound reason const
NotFound = "NotFound"
// LabelDefaultInstancetype provides a default VirtualMachine{ClusterInstancetype,Instancetype} that can be used by a VirtualMachine booting from a given PVC
LabelDefaultInstancetype = "instancetype.kubevirt.io/default-instancetype"
// LabelDefaultInstancetypeKind provides a default kind of either VirtualMachineClusterInstancetype or VirtualMachineInstancetype
LabelDefaultInstancetypeKind = "instancetype.kubevirt.io/default-instancetype-kind"
// LabelDefaultPreference provides a default VirtualMachine{ClusterPreference,Preference} that can be used by a VirtualMachine booting from a given PVC
LabelDefaultPreference = "instancetype.kubevirt.io/default-preference"
// LabelDefaultPreferenceKind provides a default kind of either VirtualMachineClusterPreference or VirtualMachinePreference
LabelDefaultPreferenceKind = "instancetype.kubevirt.io/default-preference-kind"
// ProgressDone this means we are DONE
ProgressDone = "100.0%"
)
// Size-detection pod error codes
const (
NoErr int = iota
ErrBadArguments
ErrInvalidFile
ErrInvalidPath
ErrBadTermFile
ErrUnknown
)
var (
// BlockMode is raw block device mode
BlockMode = corev1.PersistentVolumeBlock
// FilesystemMode is filesystem device mode
FilesystemMode = corev1.PersistentVolumeFilesystem
apiServerKeyOnce sync.Once
apiServerKey *rsa.PrivateKey
)
// FakeValidator is a fake token validator
type FakeValidator struct {
Match string
Operation token.Operation
Name string
Namespace string
Resource metav1.GroupVersionResource
Params map[string]string
}
// Validate is a fake token validation
func (v *FakeValidator) Validate(value string) (*token.Payload, error) {
if value != v.Match {
return nil, fmt.Errorf("token does not match expected")
}
resource := metav1.GroupVersionResource{
Resource: "persistentvolumeclaims",
}
return &token.Payload{
Name: v.Name,
Namespace: v.Namespace,
Operation: token.OperationClone,
Resource: resource,
Params: v.Params,
}, nil
}
// NewCloneTokenValidator returns a new token validator
func NewCloneTokenValidator(issuer string, key *rsa.PublicKey) token.Validator {
return token.NewValidator(issuer, key, cloneTokenLeeway)
}
// GetRequestedImageSize returns the PVC requested size
func GetRequestedImageSize(pvc *corev1.PersistentVolumeClaim) (string, error) {
pvcSize, found := pvc.Spec.Resources.Requests[corev1.ResourceStorage]
if !found {
return "", errors.Errorf("storage request is missing in pvc \"%s/%s\"", pvc.Namespace, pvc.Name)
}
return pvcSize.String(), nil
}
// GetVolumeMode returns the volumeMode from PVC handling default empty value
func GetVolumeMode(pvc *corev1.PersistentVolumeClaim) corev1.PersistentVolumeMode {
return util.ResolveVolumeMode(pvc.Spec.VolumeMode)
}
// GetStorageClassByName looks up the storage class based on the name. If no storage class is found returns nil
func GetStorageClassByName(ctx context.Context, client client.Client, name *string) (*storagev1.StorageClass, error) {
// look up storage class by name
if name != nil {
storageClass := &storagev1.StorageClass{}
if err := client.Get(ctx, types.NamespacedName{Name: *name}, storageClass); err != nil {
if k8serrors.IsNotFound(err) {
return nil, nil
}
klog.V(3).Info("Unable to retrieve storage class", "storage class name", *name)
return nil, errors.Errorf("unable to retrieve storage class %s", *name)
}
return storageClass, nil
}
// No storage class found, just return nil for storage class and let caller deal with it.
return GetDefaultStorageClass(ctx, client)
}
// GetDefaultStorageClass returns the default storage class or nil if none found
func GetDefaultStorageClass(ctx context.Context, client client.Client) (*storagev1.StorageClass, error) {
storageClasses := &storagev1.StorageClassList{}
if err := client.List(ctx, storageClasses); err != nil {
klog.V(3).Info("Unable to retrieve available storage classes")
return nil, errors.New("unable to retrieve storage classes")
}
for _, storageClass := range storageClasses.Items {
if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" {
return &storageClass, nil
}
}
return nil, nil
}
// GetFilesystemOverheadForStorageClass determines the filesystem overhead defined in CDIConfig for the storageClass.
func GetFilesystemOverheadForStorageClass(ctx context.Context, client client.Client, storageClassName *string) (cdiv1.Percent, error) {
cdiConfig := &cdiv1.CDIConfig{}
if err := client.Get(ctx, types.NamespacedName{Name: common.ConfigName}, cdiConfig); err != nil {
if k8serrors.IsNotFound(err) {
klog.V(1).Info("CDIConfig does not exist, pod will not start until it does")
return "0", nil
}
return "0", err
}
targetStorageClass, err := GetStorageClassByName(ctx, client, storageClassName)
if err != nil || targetStorageClass == nil {
klog.V(3).Info("Storage class", storageClassName, "not found, trying default storage class")
targetStorageClass, err = GetStorageClassByName(ctx, client, nil)
if err != nil {
klog.V(3).Info("No default storage class found, continuing with global overhead")
return cdiConfig.Status.FilesystemOverhead.Global, nil
}
}
if cdiConfig.Status.FilesystemOverhead == nil {
klog.Errorf("CDIConfig filesystemOverhead used before config controller ran reconcile. Hopefully this only happens during unit testing.")
return "0", nil
}
if targetStorageClass == nil {
klog.V(3).Info("Storage class", storageClassName, "not found, continuing with global overhead")
return cdiConfig.Status.FilesystemOverhead.Global, nil
}
klog.V(3).Info("target storage class for overhead", targetStorageClass.GetName())
perStorageConfig := cdiConfig.Status.FilesystemOverhead.StorageClass
storageClassOverhead, found := perStorageConfig[targetStorageClass.GetName()]
if found {
return storageClassOverhead, nil
}
return cdiConfig.Status.FilesystemOverhead.Global, nil
}
// GetDefaultPodResourceRequirements gets default pod resource requirements from cdi config status
func GetDefaultPodResourceRequirements(client client.Client) (*corev1.ResourceRequirements, error) {
cdiconfig := &cdiv1.CDIConfig{}
if err := client.Get(context.TODO(), types.NamespacedName{Name: common.ConfigName}, cdiconfig); err != nil {
klog.Errorf("Unable to find CDI configuration, %v\n", err)
return nil, err
}
return cdiconfig.Status.DefaultPodResourceRequirements, nil
}
// GetImagePullSecrets gets the imagePullSecrets needed to pull images from the cdi config
func GetImagePullSecrets(client client.Client) ([]corev1.LocalObjectReference, error) {
cdiconfig := &cdiv1.CDIConfig{}
if err := client.Get(context.TODO(), types.NamespacedName{Name: common.ConfigName}, cdiconfig); err != nil {
klog.Errorf("Unable to find CDI configuration, %v\n", err)
return nil, err
}
return cdiconfig.Status.ImagePullSecrets, nil
}
// AddVolumeDevices returns VolumeDevice slice with one block device for pods using PV with block volume mode
func AddVolumeDevices() []corev1.VolumeDevice {
volumeDevices := []corev1.VolumeDevice{
{
Name: DataVolName,
DevicePath: common.WriteBlockPath,
},
}
return volumeDevices
}
// GetPodsUsingPVCs returns Pods currently using PVCs
func GetPodsUsingPVCs(ctx context.Context, c client.Client, namespace string, names sets.Set[string], allowReadOnly bool) ([]corev1.Pod, error) {
pl := &corev1.PodList{}
// hopefully using cached client here
err := c.List(ctx, pl, &client.ListOptions{Namespace: namespace})
if err != nil {
return nil, err
}
var pods []corev1.Pod
for _, pod := range pl.Items {
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
continue
}
for _, volume := range pod.Spec.Volumes {
if volume.VolumeSource.PersistentVolumeClaim != nil &&
names.Has(volume.PersistentVolumeClaim.ClaimName) {
addPod := true
if allowReadOnly {
if !volume.VolumeSource.PersistentVolumeClaim.ReadOnly {
onlyReadOnly := true
for _, c := range pod.Spec.Containers {
for _, vm := range c.VolumeMounts {
if vm.Name == volume.Name && !vm.ReadOnly {
onlyReadOnly = false
}
}
}
if onlyReadOnly {
// no rw mounts
addPod = false
}
} else {
// all mounts must be ro
addPod = false
}
}
if addPod {
pods = append(pods, pod)
break
}
}
}
}
return pods, nil
}
// GetWorkloadNodePlacement extracts the workload-specific nodeplacement values from the CDI CR
func GetWorkloadNodePlacement(ctx context.Context, c client.Client) (*sdkapi.NodePlacement, error) {
cr, err := GetActiveCDI(ctx, c)
if err != nil {
return nil, err
}
if cr == nil {
return nil, fmt.Errorf("no active CDI")
}
return &cr.Spec.Workloads, nil
}
// GetActiveCDI returns the active CDI CR
func GetActiveCDI(ctx context.Context, c client.Client) (*cdiv1.CDI, error) {
crList := &cdiv1.CDIList{}
if err := c.List(ctx, crList, &client.ListOptions{}); err != nil {
return nil, err
}
var activeResources []cdiv1.CDI
for _, cr := range crList.Items {
if cr.Status.Phase != sdkapi.PhaseError {
activeResources = append(activeResources, cr)
}
}
if len(activeResources) == 0 {
return nil, nil
}
if len(activeResources) > 1 {
return nil, fmt.Errorf("number of active CDI CRs > 1")
}
return &activeResources[0], nil
}
// IsPopulated returns if the passed in PVC has been populated according to the rules outlined in pkg/apis/core/<version>/utils.go
func IsPopulated(pvc *corev1.PersistentVolumeClaim, c client.Client) (bool, error) {
return cdiv1utils.IsPopulated(pvc, func(name, namespace string) (*cdiv1.DataVolume, error) {
dv := &cdiv1.DataVolume{}
err := c.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, dv)
return dv, err
})
}
// GetPreallocation retuns the preallocation setting for the specified object (DV or VolumeImportSource), falling back to StorageClass and global setting (in this order)
func GetPreallocation(ctx context.Context, client client.Client, preallocation *bool) bool {
// First, the DV's preallocation
if preallocation != nil {
return *preallocation
}
cdiconfig := &cdiv1.CDIConfig{}
if err := client.Get(context.TODO(), types.NamespacedName{Name: common.ConfigName}, cdiconfig); err != nil {
klog.Errorf("Unable to find CDI configuration, %v\n", err)
return defaultPreallocation
}
return cdiconfig.Status.Preallocation
}
// GetPriorityClass gets PVC priority class
func GetPriorityClass(pvc *corev1.PersistentVolumeClaim) string {
anno := pvc.GetAnnotations()
return anno[AnnPriorityClassName]
}
// ShouldDeletePod returns whether the PVC workload pod should be deleted
func ShouldDeletePod(pvc *corev1.PersistentVolumeClaim) bool {
return pvc.GetAnnotations()[AnnPodRetainAfterCompletion] != "true" || pvc.GetAnnotations()[AnnRequiresScratch] == "true" || pvc.DeletionTimestamp != nil
}
// AddFinalizer adds a finalizer to a resource
func AddFinalizer(obj metav1.Object, name string) {
if HasFinalizer(obj, name) {
return
}
obj.SetFinalizers(append(obj.GetFinalizers(), name))
}
// RemoveFinalizer removes a finalizer from a resource
func RemoveFinalizer(obj metav1.Object, name string) {
if !HasFinalizer(obj, name) {
return
}
var finalizers []string
for _, f := range obj.GetFinalizers() {
if f != name {
finalizers = append(finalizers, f)
}
}
obj.SetFinalizers(finalizers)
}
// HasFinalizer returns true if a resource has a specific finalizer
func HasFinalizer(object metav1.Object, value string) bool {
for _, f := range object.GetFinalizers() {
if f == value {
return true
}
}
return false
}
// ValidateCloneTokenPVC validates clone token for source and target PVCs
func ValidateCloneTokenPVC(t string, v token.Validator, source, target *corev1.PersistentVolumeClaim) error {
if source.Namespace == target.Namespace {
return nil
}
tokenData, err := v.Validate(t)
if err != nil {
return errors.Wrap(err, "error verifying token")
}
tokenResourceName := getTokenResourceNamePvc(source)
srcName := getSourceNamePvc(source)
return validateTokenData(tokenData, source.Namespace, srcName, target.Namespace, target.Name, string(target.UID), tokenResourceName)
}
// ValidateCloneTokenDV validates clone token for DV
func ValidateCloneTokenDV(validator token.Validator, dv *cdiv1.DataVolume) error {
sourceName, sourceNamespace := GetCloneSourceNameAndNamespace(dv)
if sourceNamespace == "" || sourceNamespace == dv.Namespace {
return nil
}
tok, ok := dv.Annotations[AnnCloneToken]
if !ok {
return errors.New("clone token missing")
}
tokenData, err := validator.Validate(tok)
if err != nil {
return errors.Wrap(err, "error verifying token")
}
tokenResourceName := getTokenResourceNameDataVolume(dv.Spec.Source)
if tokenResourceName == "" {
return errors.New("token resource name empty, can't verify properly")
}
return validateTokenData(tokenData, sourceNamespace, sourceName, dv.Namespace, dv.Name, "", tokenResourceName)
}
func getTokenResourceNameDataVolume(source *cdiv1.DataVolumeSource) string {
if source.PVC != nil {
return "persistentvolumeclaims"
} else if source.Snapshot != nil {
return "volumesnapshots"
}
return ""
}
func getTokenResourceNamePvc(sourcePvc *corev1.PersistentVolumeClaim) string {
if v, ok := sourcePvc.Labels[common.CDIComponentLabel]; ok && v == common.CloneFromSnapshotFallbackPVCCDILabel {
return "volumesnapshots"
}
return "persistentvolumeclaims"
}
func getSourceNamePvc(sourcePvc *corev1.PersistentVolumeClaim) string {
if v, ok := sourcePvc.Labels[common.CDIComponentLabel]; ok && v == common.CloneFromSnapshotFallbackPVCCDILabel {
if sourcePvc.Spec.DataSourceRef != nil {
return sourcePvc.Spec.DataSourceRef.Name
}
}
return sourcePvc.Name
}
func validateTokenData(tokenData *token.Payload, srcNamespace, srcName, targetNamespace, targetName, targetUID, tokenResourceName string) error {
uid := tokenData.Params["uid"]
if tokenData.Operation != token.OperationClone ||
tokenData.Name != srcName ||
tokenData.Namespace != srcNamespace ||
tokenData.Resource.Resource != tokenResourceName ||
tokenData.Params["targetNamespace"] != targetNamespace ||
tokenData.Params["targetName"] != targetName ||
(uid != "" && uid != targetUID) {
return errors.New("invalid token")
}
return nil
}
// validateContentTypes compares the content type of a clone DV against its source PVC's one
func validateContentTypes(sourcePVC *corev1.PersistentVolumeClaim, spec *cdiv1.DataVolumeSpec) (bool, cdiv1.DataVolumeContentType, cdiv1.DataVolumeContentType) {
sourceContentType := cdiv1.DataVolumeContentType(GetPVCContentType(sourcePVC))
targetContentType := spec.ContentType
if targetContentType == "" {
targetContentType = cdiv1.DataVolumeKubeVirt
}
return sourceContentType == targetContentType, sourceContentType, targetContentType
}
// ValidateClone compares a clone spec against its source PVC to validate its creation
func ValidateClone(sourcePVC *corev1.PersistentVolumeClaim, spec *cdiv1.DataVolumeSpec) error {
var targetResources corev1.ResourceRequirements
valid, sourceContentType, targetContentType := validateContentTypes(sourcePVC, spec)
if !valid {
msg := fmt.Sprintf("Source contentType (%s) and target contentType (%s) do not match", sourceContentType, targetContentType)
return errors.New(msg)
}
isSizelessClone := false
explicitPvcRequest := spec.PVC != nil
if explicitPvcRequest {
targetResources = spec.PVC.Resources
} else {
targetResources = spec.Storage.Resources
// The storage size in the target DV can be empty
// when cloning using the 'Storage' API
if _, ok := targetResources.Requests[corev1.ResourceStorage]; !ok {
isSizelessClone = true
}
}
// TODO: Spec.Storage API needs a better more complex check to validate clone size - to account for fsOverhead
// simple size comparison will not work here
if (!isSizelessClone && GetVolumeMode(sourcePVC) == corev1.PersistentVolumeBlock) || explicitPvcRequest {
if err := ValidateRequestedCloneSize(sourcePVC.Spec.Resources, targetResources); err != nil {
return err
}
}
return nil
}
// ValidateSnapshotClone compares a snapshot clone spec against its source snapshot to validate its creation
func ValidateSnapshotClone(sourceSnapshot *snapshotv1.VolumeSnapshot, spec *cdiv1.DataVolumeSpec) error {
var sourceResources, targetResources corev1.ResourceRequirements
if sourceSnapshot.Status == nil {
return fmt.Errorf("no status on source snapshot, not possible to proceed")
}
size := sourceSnapshot.Status.RestoreSize
restoreSizeAvailable := size != nil && size.Sign() > 0
if restoreSizeAvailable {
sourceResources.Requests = corev1.ResourceList{corev1.ResourceStorage: *size}
}
isSizelessClone := false
explicitPvcRequest := spec.PVC != nil
if explicitPvcRequest {
targetResources = spec.PVC.Resources
} else {
targetResources = spec.Storage.Resources
if _, ok := targetResources.Requests["storage"]; !ok {
isSizelessClone = true
}
}
if !isSizelessClone && restoreSizeAvailable {
// Sizes available, make sure user picked something bigger than minimal
if err := ValidateRequestedCloneSize(sourceResources, targetResources); err != nil {
return err
}
} else if isSizelessClone && !restoreSizeAvailable {
return fmt.Errorf("size not specified by user/provisioner, can't tell how much needed for restore")
}
return nil
}
// AddAnnotation adds an annotation to an object
func AddAnnotation(obj metav1.Object, key, value string) {
if obj.GetAnnotations() == nil {
obj.SetAnnotations(make(map[string]string))
}
obj.GetAnnotations()[key] = value
}
// AddLabel adds a label to an object
func AddLabel(obj metav1.Object, key, value string) {
if obj.GetLabels() == nil {
obj.SetLabels(make(map[string]string))
}
obj.GetLabels()[key] = value
}
// HandleFailedPod handles pod-creation errors and updates the pod's PVC without providing sensitive information
func HandleFailedPod(err error, podName string, pvc *corev1.PersistentVolumeClaim, recorder record.EventRecorder, c client.Client) error {
if err == nil {
return nil
}
// Generic reason and msg to avoid providing sensitive information
reason := ErrStartingPod
msg := fmt.Sprintf(MessageErrStartingPod, podName)
// Error handling to fine-tune the event with pertinent info
if ErrQuotaExceeded(err) {
reason = ErrExceededQuota
}
recorder.Event(pvc, corev1.EventTypeWarning, reason, msg)
if isCloneSourcePod := CreateCloneSourcePodName(pvc) == podName; isCloneSourcePod {
AddAnnotation(pvc, AnnSourceRunningCondition, "false")
AddAnnotation(pvc, AnnSourceRunningConditionReason, reason)
AddAnnotation(pvc, AnnSourceRunningConditionMessage, msg)
} else {
AddAnnotation(pvc, AnnRunningCondition, "false")
AddAnnotation(pvc, AnnRunningConditionReason, reason)
AddAnnotation(pvc, AnnRunningConditionMessage, msg)
}
AddAnnotation(pvc, AnnPodPhase, string(corev1.PodFailed))
if err := c.Update(context.TODO(), pvc); err != nil {
return err
}
return err
}
// GetSource returns the source string which determines the type of source. If no source or invalid source found, default to http
func GetSource(pvc *corev1.PersistentVolumeClaim) string {
source, found := pvc.Annotations[AnnSource]
if !found {
source = ""
}
switch source {
case
SourceHTTP,
SourceS3,
SourceGCS,
SourceGlance,
SourceNone,
SourceRegistry,
SourceImageio,
SourceVDDK:
default:
source = SourceHTTP
}
return source
}
// GetEndpoint returns the endpoint string which contains the full path URI of the target object to be copied.
func GetEndpoint(pvc *corev1.PersistentVolumeClaim) (string, error) {
ep, found := pvc.Annotations[AnnEndpoint]
if !found || ep == "" {
verb := "empty"
if !found {
verb = "missing"
}
return ep, errors.Errorf("annotation %q in pvc \"%s/%s\" is %s\n", AnnEndpoint, pvc.Namespace, pvc.Name, verb)
}
return ep, nil
}
// AddImportVolumeMounts is being called for pods using PV with filesystem volume mode
func AddImportVolumeMounts() []corev1.VolumeMount {
volumeMounts := []corev1.VolumeMount{
{
Name: DataVolName,
MountPath: common.ImporterDataDir,
},
}
return volumeMounts
}
// ValidateRequestedCloneSize validates the clone size requirements on block
func ValidateRequestedCloneSize(sourceResources corev1.ResourceRequirements, targetResources corev1.ResourceRequirements) error {
sourceRequest, hasSource := sourceResources.Requests[corev1.ResourceStorage]
targetRequest, hasTarget := targetResources.Requests[corev1.ResourceStorage]
if !hasSource || !hasTarget {
return errors.New("source/target missing storage resource requests")
}
// Verify that the target PVC size is equal or larger than the source.
if sourceRequest.Value() > targetRequest.Value() {
return errors.New("target resources requests storage size is smaller than the source")
}
return nil
}
// CreateCloneSourcePodName creates clone source pod name
func CreateCloneSourcePodName(targetPvc *corev1.PersistentVolumeClaim) string {
return string(targetPvc.GetUID()) + common.ClonerSourcePodNameSuffix
}
// IsPVCComplete returns true if a PVC is in 'Succeeded' phase, false if not
func IsPVCComplete(pvc *corev1.PersistentVolumeClaim) bool {
if pvc != nil {
phase, exists := pvc.ObjectMeta.Annotations[AnnPodPhase]
return exists && (phase == string(corev1.PodSucceeded))
}
return false
}
// SetRestrictedSecurityContext sets the pod security params to be compatible with restricted PSA
func SetRestrictedSecurityContext(podSpec *corev1.PodSpec) {
hasVolumeMounts := false
for _, containers := range [][]corev1.Container{podSpec.InitContainers, podSpec.Containers} {
for i := range containers {
container := &containers[i]
if container.SecurityContext == nil {
container.SecurityContext = &corev1.SecurityContext{}
}
container.SecurityContext.Capabilities = &corev1.Capabilities{
Drop: []corev1.Capability{
"ALL",
},
}
container.SecurityContext.SeccompProfile = &corev1.SeccompProfile{
Type: corev1.SeccompProfileTypeRuntimeDefault,
}
container.SecurityContext.AllowPrivilegeEscalation = pointer.Bool(false)
container.SecurityContext.RunAsNonRoot = pointer.Bool(true)
container.SecurityContext.RunAsUser = pointer.Int64(common.QemuSubGid)
if len(container.VolumeMounts) > 0 {
hasVolumeMounts = true
}
}
}
if hasVolumeMounts {
if podSpec.SecurityContext == nil {
podSpec.SecurityContext = &corev1.PodSecurityContext{}
}
podSpec.SecurityContext.FSGroup = pointer.Int64(common.QemuSubGid)
}
}
// SetNodeNameIfPopulator sets NodeName in a pod spec when the PVC is being handled by a CDI volume populator
func SetNodeNameIfPopulator(pvc *corev1.PersistentVolumeClaim, podSpec *corev1.PodSpec) {
_, isPopulator := pvc.Annotations[AnnPopulatorKind]
nodeName := pvc.Annotations[AnnSelectedNode]
if isPopulator && nodeName != "" {
podSpec.NodeName = nodeName
}
}
// CreatePvc creates PVC
func CreatePvc(name, ns string, annotations, labels map[string]string) *corev1.PersistentVolumeClaim {
return CreatePvcInStorageClass(name, ns, nil, annotations, labels, corev1.ClaimBound)
}
// CreatePvcInStorageClass creates PVC with storgae class
func CreatePvcInStorageClass(name, ns string, storageClassName *string, annotations, labels map[string]string, phase corev1.PersistentVolumeClaimPhase) *corev1.PersistentVolumeClaim {
pvc := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
Annotations: annotations,
Labels: labels,
UID: types.UID(ns + "-" + name),
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadOnlyMany, corev1.ReadWriteOnce},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("1G"),
},
},
StorageClassName: storageClassName,
},
Status: corev1.PersistentVolumeClaimStatus{
Phase: phase,
},
}
pvc.Status.Capacity = pvc.Spec.Resources.Requests.DeepCopy()
return pvc
}
// GetAPIServerKey returns API server RSA key
func GetAPIServerKey() *rsa.PrivateKey {
apiServerKeyOnce.Do(func() {
apiServerKey, _ = rsa.GenerateKey(rand.Reader, 2048)