-
Notifications
You must be signed in to change notification settings - Fork 282
/
Copy pathutil.go
2079 lines (1813 loc) · 75.3 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"
"net/http"
"reflect"
"regexp"
"sort"
"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/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
runtimecache "sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
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"
)
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"
// 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"
// AnnVddkExtraArgs references a ConfigMap that holds arguments to pass directly to the VDDK library
AnnVddkExtraArgs = AnnAPIGroup + "/storage.pod.vddk.extraargs"
// AnnRequiresScratch provides a const for our PVC requiring scratch annotation
AnnRequiresScratch = AnnAPIGroup + "/storage.import.requiresScratch"
// AnnRequiresDirectIO provides a const for our PVC requiring direct io annotation (due to OOMs we need to try qemu cache=none)
AnnRequiresDirectIO = AnnAPIGroup + "/storage.import.requiresDirectIo"
// OOMKilledReason provides a value that container runtimes must return in the reason field for an OOMKilled container
OOMKilledReason = "OOMKilled"
// 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 = AnnAPIGroup + "/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"
// AnnDefaultVirtStorageClass is the annotation indicating that a storage class is the default one for virtualization purposes
AnnDefaultVirtStorageClass = "storageclass.kubevirt.io/is-default-virt-class"
// AnnDefaultSnapshotClass is the annotation indicating that a snapshot class is the default one
AnnDefaultSnapshotClass = "snapshot.storage.kubernetes.io/is-default-class"
// AnnSourceVolumeMode is the volume mode of the source PVC specified as an annotation on snapshots
AnnSourceVolumeMode = AnnAPIGroup + "/storage.import.sourceVolumeMode"
// 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"
// AnnPodSidecarInjectionIstio is used for enabling/disabling Pod istio/AspenMesh sidecar injection
AnnPodSidecarInjectionIstio = "sidecar.istio.io/inject"
// AnnPodSidecarInjectionIstioDefault is the default value passed for AnnPodSidecarInjection
AnnPodSidecarInjectionIstioDefault = "false"
// AnnPodSidecarInjectionLinkerd is used to enable/disable linkerd sidecar injection
AnnPodSidecarInjectionLinkerd = "linkerd.io/inject"
// AnnPodSidecarInjectionLinkerdDefault is the default value passed for AnnPodSidecarInjectionLinkerd
AnnPodSidecarInjectionLinkerdDefault = "disabled"
// 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 = AnnAPIGroup + "/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"
// VolumeSnapshotClassSelected reports that a VolumeSnapshotClass was selected
VolumeSnapshotClassSelected = "VolumeSnapshotClassSelected"
// MessageStorageProfileVolumeSnapshotClassSelected reports that a VolumeSnapshotClass was selected according to StorageProfile
MessageStorageProfileVolumeSnapshotClassSelected = "VolumeSnapshotClass selected according to StorageProfile"
// MessageDefaultVolumeSnapshotClassSelected reports that the default VolumeSnapshotClass was selected
MessageDefaultVolumeSnapshotClassSelected = "Default VolumeSnapshotClass selected"
// MessageFirstVolumeSnapshotClassSelected reports that the first VolumeSnapshotClass was selected
MessageFirstVolumeSnapshotClassSelected = "First VolumeSnapshotClass selected"
// 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"
// LabelDynamicCredentialSupport specifies if the OS supports updating credentials at runtime.
//nolint:gosec // These are not credentials
LabelDynamicCredentialSupport = "kubevirt.io/dynamic-credentials-support"
// LabelExcludeFromVeleroBackup provides a const to indicate whether an object should be excluded from velero backup
LabelExcludeFromVeleroBackup = "velero.io/exclude-from-backup"
// ProgressDone this means we are DONE
ProgressDone = "100.0%"
// AnnEventSourceKind is the source kind that should be related to events
AnnEventSourceKind = AnnAPIGroup + "/events.source.kind"
// AnnEventSource is the source that should be related to events (namespace/name)
AnnEventSource = AnnAPIGroup + "/events.source"
// AnnAllowClaimAdoption is the annotation that allows a claim to be adopted by a DataVolume
AnnAllowClaimAdoption = AnnAPIGroup + "/allowClaimAdoption"
// AnnCdiCustomizeComponentHash annotation is a hash of all customizations that live under spec.CustomizeComponents
AnnCdiCustomizeComponentHash = AnnAPIGroup + "/customizer-identifier"
// AnnCreatedForDataVolume stores the UID of the datavolume that the PVC was created for
AnnCreatedForDataVolume = AnnAPIGroup + "/createdForDataVolume"
)
// 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
// DefaultInstanceTypeLabels is a list of currently supported default instance type labels
DefaultInstanceTypeLabels = []string{
LabelDefaultInstancetype,
LabelDefaultInstancetypeKind,
LabelDefaultPreference,
LabelDefaultPreferenceKind,
}
apiServerKeyOnce sync.Once
apiServerKey *rsa.PrivateKey
// allowedAnnotations is a list of annotations
// that can be propagated from the pvc/dv to a pod
allowedAnnotations = map[string]string{
AnnPodNetwork: "",
AnnPodSidecarInjectionIstio: AnnPodSidecarInjectionIstioDefault,
AnnPodSidecarInjectionLinkerd: AnnPodSidecarInjectionLinkerdDefault,
AnnPriorityClassName: "",
AnnPodMultusDefaultNetwork: "",
}
validLabelsMatch = regexp.MustCompile(`^([\w.]+\.kubevirt.io|kubevirt.io)/[\w-]+$`)
)
// 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
}
// MultiTokenValidator is a token validator that can validate both short and long tokens
type MultiTokenValidator struct {
ShortTokenValidator token.Validator
LongTokenValidator token.Validator
}
// ValidatePVC validates a PVC
func (mtv *MultiTokenValidator) ValidatePVC(source, target *corev1.PersistentVolumeClaim) error {
tok, v := mtv.getTokenAndValidator(target)
return ValidateCloneTokenPVC(tok, v, source, target)
}
// ValidatePopulator valades a token for a populator
func (mtv *MultiTokenValidator) ValidatePopulator(vcs *cdiv1.VolumeCloneSource, pvc *corev1.PersistentVolumeClaim) error {
if vcs.Namespace == pvc.Namespace {
return nil
}
tok, v := mtv.getTokenAndValidator(pvc)
tokenData, err := v.Validate(tok)
if err != nil {
return errors.Wrap(err, "error verifying token")
}
var tokenResourceName string
switch vcs.Spec.Source.Kind {
case "PersistentVolumeClaim":
tokenResourceName = "persistentvolumeclaims"
case "VolumeSnapshot":
tokenResourceName = "volumesnapshots"
}
srcName := vcs.Spec.Source.Name
return validateTokenData(tokenData, vcs.Namespace, srcName, pvc.Namespace, pvc.Name, string(pvc.UID), tokenResourceName)
}
func (mtv *MultiTokenValidator) getTokenAndValidator(pvc *corev1.PersistentVolumeClaim) (string, token.Validator) {
v := mtv.LongTokenValidator
tok, ok := pvc.Annotations[AnnExtendedCloneToken]
if !ok {
// if token doesn't exist, no prob for same namespace
tok = pvc.Annotations[AnnCloneToken]
v = mtv.ShortTokenValidator
}
return tok, v
}
// NewMultiTokenValidator returns a new multi token validator
func NewMultiTokenValidator(key *rsa.PublicKey) *MultiTokenValidator {
return &MultiTokenValidator{
ShortTokenValidator: NewCloneTokenValidator(common.CloneTokenIssuer, key),
LongTokenValidator: NewCloneTokenValidator(common.ExtendedCloneTokenIssuer, key),
}
}
// 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)
}
// IsDataVolumeUsingDefaultStorageClass checks if the DataVolume is using the default StorageClass
func IsDataVolumeUsingDefaultStorageClass(dv *cdiv1.DataVolume) bool {
return GetStorageClassFromDVSpec(dv) == nil
}
// GetStorageClassFromDVSpec returns the StorageClassName from DataVolume PVC or Storage spec
func GetStorageClassFromDVSpec(dv *cdiv1.DataVolume) *string {
if dv.Spec.PVC != nil {
return dv.Spec.PVC.StorageClassName
}
if dv.Spec.Storage != nil {
return dv.Spec.Storage.StorageClassName
}
return nil
}
// getStorageClassByName looks up the storage class based on the name.
// If name is nil, it performs fallback to default according to the provided content type
// If no storage class is found, returns nil
func getStorageClassByName(ctx context.Context, client client.Client, name *string, contentType cdiv1.DataVolumeContentType) (*storagev1.StorageClass, error) {
if name == nil {
return getFallbackStorageClass(ctx, client, contentType)
}
// look up storage class by name
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
}
// GetStorageClassByNameWithK8sFallback looks up the storage class based on the name
// If name is nil, it looks for the default k8s storage class storageclass.kubernetes.io/is-default-class
// If no storage class is found, returns nil
func GetStorageClassByNameWithK8sFallback(ctx context.Context, client client.Client, name *string) (*storagev1.StorageClass, error) {
return getStorageClassByName(ctx, client, name, cdiv1.DataVolumeArchive)
}
// GetStorageClassByNameWithVirtFallback looks up the storage class based on the name
// If name is nil, it looks for the following, in this order:
// default kubevirt storage class (if the caller is interested) storageclass.kubevirt.io/is-default-class
// default k8s storage class storageclass.kubernetes.io/is-default-class
// If no storage class is found, returns nil
func GetStorageClassByNameWithVirtFallback(ctx context.Context, client client.Client, name *string, contentType cdiv1.DataVolumeContentType) (*storagev1.StorageClass, error) {
return getStorageClassByName(ctx, client, name, contentType)
}
// getFallbackStorageClass looks for a default virt/k8s storage class according to the content type
// If no storage class is found, returns nil
func getFallbackStorageClass(ctx context.Context, client client.Client, contentType cdiv1.DataVolumeContentType) (*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")
}
if GetContentType(contentType) == cdiv1.DataVolumeKubeVirt {
if virtSc := GetPlatformDefaultStorageClass(storageClasses, AnnDefaultVirtStorageClass); virtSc != nil {
return virtSc, nil
}
}
return GetPlatformDefaultStorageClass(storageClasses, AnnDefaultStorageClass), nil
}
// GetPlatformDefaultStorageClass returns the default storage class according to the provided annotation or nil if none found
func GetPlatformDefaultStorageClass(storageClasses *storagev1.StorageClassList, defaultAnnotationKey string) *storagev1.StorageClass {
defaultClasses := []storagev1.StorageClass{}
for _, storageClass := range storageClasses.Items {
if storageClass.Annotations[defaultAnnotationKey] == "true" {
defaultClasses = append(defaultClasses, storageClass)
}
}
if len(defaultClasses) == 0 {
return nil
}
// Primary sort by creation timestamp, newest first
// Secondary sort by class name, ascending order
// Follows k8s behavior
// https://github.com/kubernetes/kubernetes/blob/731068288e112c8b5af70f676296cc44661e84f4/pkg/volume/util/storageclass.go#L58-L59
sort.Slice(defaultClasses, func(i, j int) bool {
if defaultClasses[i].CreationTimestamp.UnixNano() == defaultClasses[j].CreationTimestamp.UnixNano() {
return defaultClasses[i].Name < defaultClasses[j].Name
}
return defaultClasses[i].CreationTimestamp.UnixNano() > defaultClasses[j].CreationTimestamp.UnixNano()
})
if len(defaultClasses) > 1 {
klog.V(3).Infof("%d default StorageClasses were found, choosing: %s", len(defaultClasses), defaultClasses[0].Name)
}
return &defaultClasses[0]
}
// GetFilesystemOverheadForStorageClass determines the filesystem overhead defined in CDIConfig for the storageClass.
func GetFilesystemOverheadForStorageClass(ctx context.Context, client client.Client, storageClassName *string) (cdiv1.Percent, error) {
if storageClassName != nil && *storageClassName == "" {
klog.V(3).Info("No storage class name passed")
return "0", nil
}
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 := GetStorageClassByNameWithK8sFallback(ctx, client, storageClassName)
if err != nil || targetStorageClass == nil {
klog.V(3).Info("Storage class", storageClassName, "not found, trying default storage class")
targetStorageClass, err = GetStorageClassByNameWithK8sFallback(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
}
// GetImportPodRestartPolicy gets the current import pod restart policy from cdi config
func GetImportPodRestartPolicy(client client.Client) (corev1.RestartPolicy, 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 "", err
}
return cdiconfig.Status.ImportPodRestartPolicy, 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
}
// GetPodFromPvc determines the pod associated with the pvc passed in.
func GetPodFromPvc(c client.Client, namespace string, pvc *corev1.PersistentVolumeClaim) (*corev1.Pod, error) {
l, _ := labels.Parse(common.PrometheusLabelKey)
pods := &corev1.PodList{}
listOptions := client.ListOptions{
LabelSelector: l,
}
if err := c.List(context.TODO(), pods, &listOptions); err != nil {
return nil, err
}
pvcUID := pvc.GetUID()
for _, pod := range pods.Items {
if ShouldIgnorePod(&pod, pvc) {
continue
}
for _, or := range pod.OwnerReferences {
if or.UID == pvcUID {
return &pod, nil
}
}
// TODO: check this
val, exists := pod.Labels[CloneUniqueID]
if exists && val == string(pvcUID)+common.ClonerSourcePodNameSuffix {
return &pod, nil
}
}
return nil, errors.Errorf("Unable to find pod owned by UID: %s, in namespace: %s", string(pvcUID), namespace)
}
// 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
}
}
for _, vm := range c.VolumeDevices {
if vm.Name == volume.Name {
// Node level rw mount and container can't mount block device ro
onlyReadOnly = false
}
}
}
if onlyReadOnly {
// no rw mounts
addPod = false
}
} else {
// all mounts must be ro
addPod = false
}
if strings.HasSuffix(pod.Name, common.ClonerSourcePodNameSuffix) && pod.Labels != nil &&
pod.Labels[common.CDIComponentLabel] == common.ClonerSourcePodName {
// Host assisted clone source pod only reads from source
// But some drivers disallow mounting a block PVC ReadOnly
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
}
if len(crList.Items) == 0 {
return nil, nil
}
if len(crList.Items) == 1 {
return &crList.Items[0], nil
}
var activeResources []cdiv1.CDI
for _, cr := range crList.Items {
if cr.Status.Phase != sdkapi.PhaseError {
activeResources = append(activeResources, cr)
}
}
if len(activeResources) != 1 {
return nil, fmt.Errorf("invalid number of active CDI resources: %d", len(activeResources))
}
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 returns 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
}
// ImmediateBindingRequested returns if an object has the ImmediateBinding annotation
func ImmediateBindingRequested(obj metav1.Object) bool {
_, isImmediateBindingRequested := obj.GetAnnotations()[AnnImmediateBinding]
return isImmediateBindingRequested
}
// 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.GetAnnotations()[AnnRequiresDirectIO] == "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 := GetCloneSourceInfo(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
}
// IsSnapshotValidForClone returns an error if the passed snapshot is not valid for cloning
func IsSnapshotValidForClone(sourceSnapshot *snapshotv1.VolumeSnapshot) error {
if sourceSnapshot.Status == nil {
return fmt.Errorf("no status on source snapshot yet")
}
if !IsSnapshotReady(sourceSnapshot) {
klog.V(3).Info("snapshot not ReadyToUse, while we allow this, probably going to be an issue going forward", "namespace", sourceSnapshot.Namespace, "name", sourceSnapshot.Name)
}
if sourceSnapshot.Status.Error != nil {
errMessage := "no details"
if msg := sourceSnapshot.Status.Error.Message; msg != nil {
errMessage = *msg
}
return fmt.Errorf("snapshot in error state with msg: %s", errMessage)
}
if sourceSnapshot.Spec.VolumeSnapshotClassName == nil ||
*sourceSnapshot.Spec.VolumeSnapshotClassName == "" {
return fmt.Errorf("snapshot %s/%s does not have volume snap class populated, can't clone", sourceSnapshot.Name, sourceSnapshot.Namespace)
}
return nil