/
util.go
5670 lines (5215 loc) · 214 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 2021 The Kubernetes 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 e2e
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
cnstypes "github.com/vmware/govmomi/cns/types"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
vim25types "github.com/vmware/govmomi/vim25/types"
"golang.org/x/crypto/ssh"
"gopkg.in/yaml.v2"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"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/runtime/schema"
pkgtypes "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubectl/pkg/drain"
"k8s.io/kubectl/pkg/util/podutils"
"k8s.io/kubernetes/test/e2e/framework"
fdep "k8s.io/kubernetes/test/e2e/framework/deployment"
"k8s.io/kubernetes/test/e2e/framework/manifest"
fnodes "k8s.io/kubernetes/test/e2e/framework/node"
fpod "k8s.io/kubernetes/test/e2e/framework/pod"
fpv "k8s.io/kubernetes/test/e2e/framework/pv"
fssh "k8s.io/kubernetes/test/e2e/framework/ssh"
fss "k8s.io/kubernetes/test/e2e/framework/statefulset"
snapc "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1"
snapclient "github.com/kubernetes-csi/external-snapshotter/client/v4/clientset/versioned"
cnsoperatorv1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator"
cnsfileaccessconfigv1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator/cnsfileaccessconfig/v1alpha1"
cnsnodevmattachmentv1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator/cnsnodevmattachment/v1alpha1"
cnsregistervolumev1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator/cnsregistervolume/v1alpha1"
cnsvolumemetadatav1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator/cnsvolumemetadata/v1alpha1"
k8s "sigs.k8s.io/vsphere-csi-driver/v2/pkg/kubernetes"
)
var (
defaultCluster *object.ClusterComputeResource
svcClient clientset.Interface
svcNamespace string
vsanHealthClient *VsanClient
clusterComputeResource []*object.ClusterComputeResource
hosts []*object.HostSystem
defaultDatastore *object.Datastore
restConfig *rest.Config
pvclaims []*v1.PersistentVolumeClaim
pvclaimsToDelete []*v1.PersistentVolumeClaim
pvZone string
pvRegion string
)
type TKGCluster struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace"`
ResourceVersion string `yaml:"resourceVersion"`
SelfLink string `yaml:"selfLink"`
UID string `yaml:"uid"`
} `yaml:"metadata"`
Spec struct {
Distribution struct {
FullVersion string `yaml:"fullVersion"`
Version string `yaml:"version"`
} `yaml:"distribution"`
Settings struct {
Network struct {
Cni struct {
Name string `yaml:"name"`
} `yaml:"cni"`
Pods struct {
CidrBlocks []string `yaml:"cidrBlocks"`
} `yaml:"pods"`
ServiceDomain string `yaml:"serviceDomain"`
Services struct {
CidrBlocks []string `yaml:"cidrBlocks"`
} `yaml:"services"`
} `yaml:"network"`
} `yaml:"settings"`
Topology struct {
ControlPlane struct {
Class string `yaml:"class"`
Count int `yaml:"count"`
StorageClass string `yaml:"storageClass"`
} `yaml:"controlPlane"`
Workers struct {
Class string `yaml:"class"`
Count int `yaml:"count"`
StorageClass string `yaml:"storageClass"`
} `yaml:"workers"`
} `yaml:"topology"`
} `yaml:"spec"`
Status struct {
Addons struct {
Authsvc struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"authsvc"`
Cloudprovider struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"cloudprovider"`
Cni struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"cni"`
Csi struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"csi"`
DNS struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"dns"`
MetricsServer struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Reason string `yaml:"reason"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
} `yaml:"metrics-server"`
Proxy struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"proxy"`
Psp struct {
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
} `yaml:"conditions"`
Name string `yaml:"name"`
Status string `yaml:"status"`
Version string `yaml:"version"`
} `yaml:"psp"`
} `yaml:"addons"`
ClusterAPIStatus struct {
APIEndpoints []struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"apiEndpoints"`
} `yaml:"clusterApiStatus"`
Conditions []struct {
LastTransitionTime time.Time `yaml:"lastTransitionTime"`
Status string `yaml:"status"`
Type string `yaml:"type"`
Message string `yaml:"message,omitempty"`
Reason string `yaml:"reason,omitempty"`
} `yaml:"conditions"`
Phase string `yaml:"phase"`
} `yaml:"status"`
}
type VMImages struct {
APIVersion string `json:"apiVersion"`
Items []struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata struct {
Annotations struct {
VmoperatorVmwareComContentLibraryVersion string `json:"vmoperator.vmware.com/content-library-version"`
VmwareSystemCompatibilityoffering string `json:"vmware-system.compatibilityoffering"`
VmwareSystemGuestKubernetesAddonsAntrea string `json:"vmware-system.guest.kubernetes.addons.antrea"`
VmwareSystemGuestKubernetesAddonsAuthsvc string `json:"vmware-system.guest.kubernetes.addons.authsvc"`
VmwareSystemGuestKubernetesAddonsCalico string `json:"vmware-system.guest.kubernetes.addons.calico"`
VmwareSystemGuestKubernetesAddonsPvcsi string `json:"vmware-system.guest.kubernetes.addons.pvcsi"`
VmwareSystemGuestKubernetesAddonsVmwareGC string `json:"vmware-system.guest.kubernetes.addons.vmware-guest-cluster"`
VmwareSystemGuestKubernetesImageVersion string `json:"vmware-system.guest.kubernetes.distribution.image.version"`
} `json:"annotations"`
CreationTimestamp time.Time `json:"creationTimestamp"`
Generation int `json:"generation"`
ManagedFields []struct {
APIVersion string `json:"apiVersion"`
FieldsType string `json:"fieldsType"`
FieldsV1 struct {
FMetadata struct {
FAnnotations struct {
NAMING_FAILED struct {
} `json:"."`
FVmoperatorVmwareComContentLibraryVersion struct {
} `json:"f:vmoperator.vmware.com/content-library-version"`
FVmwareSystemCompatibilityoffering struct {
} `json:"f:vmware-system.compatibilityoffering"`
FVmwareSystemGuestKubernetesAddonsAntrea struct {
} `json:"f:vmware-system.guest.kubernetes.addons.antrea"`
FVmwareSystemGuestKubernetesAddonsAuthsvc struct {
} `json:"f:vmware-system.guest.kubernetes.addons.authsvc"`
FVmwareSystemGuestKubernetesAddonsCalico struct {
} `json:"f:vmware-system.guest.kubernetes.addons.calico"`
FVmwareSystemGuestKubernetesAddonsPvcsi struct {
} `json:"f:vmware-system.guest.kubernetes.addons.pvcsi"`
FVmwareSystemGuestKubernetesAddonsVmwareGC struct {
} `json:"f:vmware-system.guest.kubernetes.addons.vmware-guest-cluster"`
FVmwareSystemGuestKubernetesImageVersion struct {
} `json:"f:vmware-system.guest.kubernetes.distribution.image.version"`
} `json:"f:annotations"`
} `json:"f:metadata"`
FSpec struct {
NAMING_FAILED struct {
} `json:"."`
FHwVersion struct {
} `json:"f:hwVersion"`
FImageSourceType struct {
} `json:"f:imageSourceType"`
FOsInfo struct {
NAMING_FAILED struct {
} `json:"."`
FType struct {
} `json:"f:type"`
} `json:"f:osInfo"`
FProductInfo struct {
NAMING_FAILED struct {
} `json:"."`
FFullVersion struct {
} `json:"f:fullVersion"`
FProduct struct {
} `json:"f:product"`
FVendor struct {
} `json:"f:vendor"`
FVersion struct {
} `json:"f:version"`
} `json:"f:productInfo"`
FType struct {
} `json:"f:type"`
} `json:"f:spec"`
FStatus struct {
NAMING_FAILED struct {
} `json:"."`
FConditions struct {
} `json:"f:conditions"`
FImageSupported struct {
} `json:"f:imageSupported"`
FInternalID struct {
} `json:"f:internalId"`
FUUID struct {
} `json:"f:uuid"`
} `json:"f:status"`
} `json:"fieldsV1"`
Manager string `json:"manager"`
Operation string `json:"operation"`
Time time.Time `json:"time"`
} `json:"managedFields"`
Name string `json:"name"`
OwnerReferences []struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Name string `json:"name"`
UID string `json:"uid"`
} `json:"ownerReferences"`
ResourceVersion string `json:"resourceVersion"`
SelfLink string `json:"selfLink"`
UID string `json:"uid"`
} `json:"metadata"`
Spec struct {
HwVersion int `json:"hwVersion"`
ImageSourceType string `json:"imageSourceType"`
OsInfo struct {
Type string `json:"type"`
} `json:"osInfo"`
ProductInfo struct {
FullVersion string `json:"fullVersion"`
Product string `json:"product"`
Vendor string `json:"vendor"`
Version string `json:"version"`
} `json:"productInfo"`
Type string `json:"type"`
} `json:"spec"`
Status struct {
Conditions []struct {
LastTransitionTime time.Time `json:"lastTransitionTime"`
Status string `json:"status"`
Type string `json:"type"`
} `json:"conditions"`
ImageSupported bool `json:"imageSupported"`
InternalID string `json:"internalId"`
UUID string `json:"uuid"`
} `json:"status"`
} `json:"items"`
Kind string `json:"kind"`
Metadata struct {
Continue string `json:"continue"`
ResourceVersion string `json:"resourceVersion"`
SelfLink string `json:"selfLink"`
} `json:"metadata"`
}
type AuthToken struct {
IDToken string `json:"id_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
type CertRotate struct {
UserID string `json:"user_id"`
UserName string `json:"user_name"`
Created time.Time `json:"created"`
Version int `json:"version"`
ID string `json:"id"`
UpdatedByUserID string `json:"updated_by_user_id"`
UpdatedByUserName string `json:"updated_by_user_name"`
Updated time.Time `json:"updated"`
Status string `json:"status"`
ResourceID string `json:"resource_id"`
ResourceType string `json:"resource_type"`
StartResourceEntityVersion interface{} `json:"start_resource_entity_version"`
EndResourceEntityVersion interface{} `json:"end_resource_entity_version"`
ParentTaskID interface{} `json:"parent_task_id"`
SubStatus string `json:"sub_status"`
TaskType string `json:"task_type"`
ErrorMessage interface{} `json:"error_message"`
CustomerErrorMessage interface{} `json:"customer_error_message"`
LocalizedErrorMessage interface{} `json:"localized_error_message"`
StartTime time.Time `json:"start_time"`
EndTime interface{} `json:"end_time"`
Retries int `json:"retries"`
TaskVersion string `json:"task_version"`
ProgressPercent int `json:"progress_percent"`
EstimatedRemainingMinutes int `json:"estimated_remaining_minutes"`
TaskProgressPhases interface{} `json:"task_progress_phases"`
ServiceErrors []interface{} `json:"service_errors"`
Params struct {
CertType struct {
CertType string `json:"cert_type"`
CertificateToDelete interface{} `json:"certificate_to_delete"`
CertificateToSave interface{} `json:"certificate_to_save"`
ValidDays interface{} `json:"valid_days"`
Version interface{} `json:"version"`
CertificateConfig interface{} `json:"certificate_config"`
} `json:"certType"`
} `json:"params"`
OrgType string `json:"org_type"`
CorrelationID interface{} `json:"correlation_id"`
PhaseInProgress string `json:"phase_in_progress"`
OrgID string `json:"org_id"`
}
type GetTaskTstatus struct {
UserID string `json:"user_id"`
UserName string `json:"user_name"`
Created time.Time `json:"created"`
Version int `json:"version"`
ID string `json:"id"`
UpdatedByUserID string `json:"updated_by_user_id"`
UpdatedByUserName string `json:"updated_by_user_name"`
Updated time.Time `json:"updated"`
Status string `json:"status"`
ResourceID string `json:"resource_id"`
ResourceType string `json:"resource_type"`
StartResourceEntityVersion interface{} `json:"start_resource_entity_version"`
EndResourceEntityVersion interface{} `json:"end_resource_entity_version"`
ParentTaskID interface{} `json:"parent_task_id"`
SubStatus string `json:"sub_status"`
TaskType string `json:"task_type"`
ErrorMessage interface{} `json:"error_message"`
CustomerErrorMessage interface{} `json:"customer_error_message"`
LocalizedErrorMessage interface{} `json:"localized_error_message"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Retries int `json:"retries"`
TaskVersion string `json:"task_version"`
ProgressPercent int `json:"progress_percent"`
EstimatedRemainingMinutes int `json:"estimated_remaining_minutes"`
TaskProgressPhases interface{} `json:"task_progress_phases"`
ServiceErrors []interface{} `json:"service_errors"`
Params struct {
CertType struct {
CertType string `json:"cert_type"`
CertificateToDelete []struct {
Entity string `json:"entity"`
SerialNum string `json:"serial_num"`
Fingerprint string `json:"fingerprint"`
Certificate string `json:"certificate"`
} `json:"certificate_to_delete"`
CertificateToSave []struct {
Entity string `json:"entity"`
SerialNum string `json:"serial_num"`
Fingerprint string `json:"fingerprint"`
Certificate string `json:"certificate"`
} `json:"certificate_to_save"`
} `json:"certType"`
} `json:"params"`
OrgType string `json:"org_type"`
CorrelationID interface{} `json:"correlation_id"`
PhaseInProgress string `json:"phase_in_progress"`
OrgID string `json:"org_id"`
}
// getVSphereStorageClassSpec returns Storage Class Spec with supplied storage
// class parameters.
func getVSphereStorageClassSpec(scName string, scParameters map[string]string,
allowedTopologies []v1.TopologySelectorLabelRequirement, scReclaimPolicy v1.PersistentVolumeReclaimPolicy,
bindingMode storagev1.VolumeBindingMode, allowVolumeExpansion bool) *storagev1.StorageClass {
if bindingMode == "" {
bindingMode = storagev1.VolumeBindingImmediate
}
var sc = &storagev1.StorageClass{
TypeMeta: metav1.TypeMeta{
Kind: "StorageClass",
},
ObjectMeta: metav1.ObjectMeta{
GenerateName: "sc-",
},
Provisioner: e2evSphereCSIDriverName,
VolumeBindingMode: &bindingMode,
AllowVolumeExpansion: &allowVolumeExpansion,
}
// If scName is specified, use that name, else auto-generate storage class
// name.
if scName != "" {
if supervisorCluster {
sc.ObjectMeta.Name = scName
} else {
sc.ObjectMeta = metav1.ObjectMeta{
Name: scName,
}
}
}
if scParameters != nil {
sc.Parameters = scParameters
}
if allowedTopologies != nil {
sc.AllowedTopologies = []v1.TopologySelectorTerm{
{
MatchLabelExpressions: allowedTopologies,
},
}
}
if scReclaimPolicy != "" {
sc.ReclaimPolicy = &scReclaimPolicy
}
return sc
}
// getPvFromClaim returns PersistentVolume for requested claim.
func getPvFromClaim(client clientset.Interface, namespace string, claimName string) *v1.PersistentVolume {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
pvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, claimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pv, err := client.CoreV1().PersistentVolumes().Get(ctx, pvclaim.Spec.VolumeName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return pv
}
// getNodeUUID returns Node VM UUID for requested node.
func getNodeUUID(ctx context.Context, client clientset.Interface, nodeName string) string {
vmUUID := ""
if isCsiFssEnabled(ctx, client, GetAndExpectStringEnvVar(envCSINamespace), useCsiNodeID) {
csiNode, err := client.StorageV1().CSINodes().Get(ctx, nodeName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
csiDriverFound := false
for _, driver := range csiNode.Spec.Drivers {
if driver.Name == e2evSphereCSIDriverName {
csiDriverFound = true
vmUUID = driver.NodeID
}
}
gomega.Expect(csiDriverFound).To(gomega.BeTrue(), "CSI driver not found in CSI node %s", nodeName)
} else {
node, err := client.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
vmUUID = strings.TrimPrefix(node.Spec.ProviderID, providerPrefix)
gomega.Expect(vmUUID).NotTo(gomega.BeEmpty())
}
ginkgo.By(fmt.Sprintf("VM UUID is: %s for node: %s", vmUUID, nodeName))
return vmUUID
}
// getVMUUIDFromNodeName returns the vmUUID for a given node vm and datacenter.
func getVMUUIDFromNodeName(nodeName string) (string, error) {
var datacenters []string
finder := find.NewFinder(e2eVSphere.Client.Client, false)
cfg, err := getConfig()
gomega.Expect(err).NotTo(gomega.HaveOccurred())
dcList := strings.Split(cfg.Global.Datacenters, ",")
for _, dc := range dcList {
dcName := strings.TrimSpace(dc)
if dcName != "" {
datacenters = append(datacenters, dcName)
}
}
var vm *object.VirtualMachine
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for _, dc := range datacenters {
dataCenter, err := finder.Datacenter(ctx, dc)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
finder := find.NewFinder(dataCenter.Client(), false)
finder.SetDatacenter(dataCenter)
vm, err = finder.VirtualMachine(ctx, nodeName)
if err != nil {
continue
}
vmUUID := vm.UUID(ctx)
gomega.Expect(vmUUID).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintf("VM UUID is: %s for node: %s", vmUUID, nodeName))
return vmUUID, nil
}
return "", err
}
// verifyVolumeMetadataInCNS verifies container volume metadata is matching the
// one is CNS cache.
func verifyVolumeMetadataInCNS(vs *vSphere, volumeID string,
PersistentVolumeClaimName string, PersistentVolumeName string,
PodName string, Labels ...vim25types.KeyValue) error {
queryResult, err := vs.queryCNSVolumeWithResult(volumeID)
if err != nil {
return err
}
gomega.Expect(queryResult.Volumes).ShouldNot(gomega.BeEmpty())
if len(queryResult.Volumes) != 1 || queryResult.Volumes[0].VolumeId.Id != volumeID {
return fmt.Errorf("failed to query cns volume %s", volumeID)
}
for _, metadata := range queryResult.Volumes[0].Metadata.EntityMetadata {
kubernetesMetadata := metadata.(*cnstypes.CnsKubernetesEntityMetadata)
if kubernetesMetadata.EntityType == "POD" && kubernetesMetadata.EntityName != PodName {
return fmt.Errorf("entity Pod with name %s not found for volume %s", PodName, volumeID)
} else if kubernetesMetadata.EntityType == "PERSISTENT_VOLUME" &&
kubernetesMetadata.EntityName != PersistentVolumeName {
return fmt.Errorf("entity PV with name %s not found for volume %s", PersistentVolumeName, volumeID)
} else if kubernetesMetadata.EntityType == "PERSISTENT_VOLUME_CLAIM" &&
kubernetesMetadata.EntityName != PersistentVolumeClaimName {
return fmt.Errorf("entity PVC with name %s not found for volume %s", PersistentVolumeClaimName, volumeID)
}
}
labelMap := make(map[string]string)
for _, e := range queryResult.Volumes[0].Metadata.EntityMetadata {
if e == nil {
continue
}
if e.GetCnsEntityMetadata().Labels == nil {
continue
}
for _, al := range e.GetCnsEntityMetadata().Labels {
// These are the actual labels in the provisioned PV. Populate them
// in the label map.
labelMap[al.Key] = al.Value
}
for _, el := range Labels {
// Traverse through the slice of expected labels and see if all of them
// are present in the label map.
if val, ok := labelMap[el.Key]; ok {
gomega.Expect(el.Value == val).To(gomega.BeTrue(),
fmt.Sprintf("Actual label Value of the statically provisioned PV is %s but expected is %s",
val, el.Value))
} else {
return fmt.Errorf("label(%s:%s) is expected in the provisioned PV but its not found", el.Key, el.Value)
}
}
}
ginkgo.By(fmt.Sprintf("successfully verified metadata of the volume %q", volumeID))
return nil
}
// getVirtualDeviceByDiskID gets the virtual device by diskID.
func getVirtualDeviceByDiskID(ctx context.Context, vm *object.VirtualMachine,
diskID string) (vim25types.BaseVirtualDevice, error) {
vmname, err := vm.Common.ObjectName(ctx)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
vmDevices, err := vm.Device(ctx)
if err != nil {
framework.Logf("failed to get the devices for VM: %q. err: %+v", vmname, err)
return nil, err
}
for _, device := range vmDevices {
if vmDevices.TypeName(device) == "VirtualDisk" {
if virtualDisk, ok := device.(*vim25types.VirtualDisk); ok {
if virtualDisk.VDiskId != nil && virtualDisk.VDiskId.Id == diskID {
framework.Logf("Found FCDID %q attached to VM %q", diskID, vmname)
return device, nil
}
}
}
}
framework.Logf("failed to find FCDID %q attached to VM %q", diskID, vmname)
return nil, nil
}
// getPersistentVolumeClaimSpecWithStorageClass return the PersistentVolumeClaim
// spec with specified storage class.
func getPersistentVolumeClaimSpecWithStorageClass(namespace string, ds string, storageclass *storagev1.StorageClass,
pvclaimlabels map[string]string, accessMode v1.PersistentVolumeAccessMode) *v1.PersistentVolumeClaim {
disksize := diskSize
if ds != "" {
disksize = ds
}
if accessMode == "" {
// If accessMode is not specified, set the default accessMode.
accessMode = v1.ReadWriteOnce
}
claim := &v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "pvc-",
Namespace: namespace,
},
Spec: v1.PersistentVolumeClaimSpec{
AccessModes: []v1.PersistentVolumeAccessMode{
accessMode,
},
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): resource.MustParse(disksize),
},
},
StorageClassName: &(storageclass.Name),
},
}
if pvclaimlabels != nil {
claim.Labels = pvclaimlabels
}
return claim
}
// getPersistentVolumeClaimSpecWithoutStorageClass return the PersistentVolumeClaim
// spec without passing the storage class.
func getPersistentVolumeClaimSpecWithoutStorageClass(namespace string, ds string,
pvclaimlabels map[string]string, accessMode v1.PersistentVolumeAccessMode) *v1.PersistentVolumeClaim {
disksize := diskSize
if ds != "" {
disksize = ds
}
if accessMode == "" {
// If accessMode is not specified, set the default accessMode.
accessMode = v1.ReadWriteOnce
}
claim := &v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "pvc-",
Namespace: namespace,
},
Spec: v1.PersistentVolumeClaimSpec{
AccessModes: []v1.PersistentVolumeAccessMode{
accessMode,
},
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): resource.MustParse(disksize),
},
},
},
}
if pvclaimlabels != nil {
claim.Labels = pvclaimlabels
}
return claim
}
// createPVCAndStorageClass helps creates a storage class with specified name,
// storageclass parameters and PVC using storage class.
func createPVCAndStorageClass(client clientset.Interface, pvcnamespace string,
pvclaimlabels map[string]string, scParameters map[string]string, ds string,
allowedTopologies []v1.TopologySelectorLabelRequirement, bindingMode storagev1.VolumeBindingMode,
allowVolumeExpansion bool, accessMode v1.PersistentVolumeAccessMode,
names ...string) (*storagev1.StorageClass, *v1.PersistentVolumeClaim, error) {
scName := ""
if len(names) > 0 {
scName = names[0]
}
storageclass, err := createStorageClass(client, scParameters,
allowedTopologies, "", bindingMode, allowVolumeExpansion, scName)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim, err := createPVC(client, pvcnamespace, pvclaimlabels, ds, storageclass, accessMode)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return storageclass, pvclaim, err
}
// createStorageClass helps creates a storage class with specified name,
// storageclass parameters.
func createStorageClass(client clientset.Interface, scParameters map[string]string,
allowedTopologies []v1.TopologySelectorLabelRequirement,
scReclaimPolicy v1.PersistentVolumeReclaimPolicy, bindingMode storagev1.VolumeBindingMode,
allowVolumeExpansion bool, scName string) (*storagev1.StorageClass, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var storageclass *storagev1.StorageClass
var err error
isStorageClassPresent := false
ginkgo.By(fmt.Sprintf("Creating StorageClass %s with scParameters: %+v and allowedTopologies: %+v "+
"and ReclaimPolicy: %+v and allowVolumeExpansion: %t",
scName, scParameters, allowedTopologies, scReclaimPolicy, allowVolumeExpansion))
if supervisorCluster {
storageclass, err = client.StorageV1().StorageClasses().Get(ctx, scName, metav1.GetOptions{})
if !apierrors.IsNotFound(err) {
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
if storageclass != nil && err == nil {
isStorageClassPresent = true
}
}
if !isStorageClassPresent {
storageclass, err = client.StorageV1().StorageClasses().Create(ctx, getVSphereStorageClassSpec(scName,
scParameters, allowedTopologies, scReclaimPolicy, bindingMode, allowVolumeExpansion), metav1.CreateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred(), fmt.Sprintf("Failed to create storage class with err: %v", err))
}
return storageclass, err
}
// updateSCtoDefault updates the given SC to default
func updateSCtoDefault(ctx context.Context, client clientset.Interface, scName, isDefault string) error {
sc, err := client.StorageV1().StorageClasses().Get(ctx, scName, metav1.GetOptions{})
if err != nil {
framework.Failf("Failed to get storage class %s from cluster, err=%+v", sc.Name, err)
return err
}
patch := map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]string{
"storageclass.kubernetes.io/is-default-class": isDefault,
},
},
}
patchBytes, err := json.Marshal(patch)
if err != nil {
framework.Failf("Failed to marshal patch(%s): %s", patch, err)
return err
}
// Patch the storage class with the updated annotation.
updatedSC, err := client.StorageV1().StorageClasses().Patch(ctx,
scName, "application/merge-patch+json", patchBytes, metav1.PatchOptions{})
if err != nil {
framework.Failf("Failed to patch the storage class object with isDefault. Err = %+v", err)
return err
}
framework.Logf("Successfully updated annotations of storage class '%s' to:\n%v", scName, updatedSC.Annotations)
return nil
}
// createPVC helps creates pvc with given namespace and labels using given
// storage class.
func createPVC(client clientset.Interface, pvcnamespace string, pvclaimlabels map[string]string, ds string,
storageclass *storagev1.StorageClass, accessMode v1.PersistentVolumeAccessMode) (*v1.PersistentVolumeClaim, error) {
pvcspec := getPersistentVolumeClaimSpecWithStorageClass(pvcnamespace, ds, storageclass, pvclaimlabels, accessMode)
ginkgo.By(fmt.Sprintf("Creating PVC using the Storage Class %s with disk size %s and labels: %+v accessMode: %+v",
storageclass.Name, ds, pvclaimlabels, accessMode))
pvclaim, err := fpv.CreatePVC(client, pvcnamespace, pvcspec)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), fmt.Sprintf("Failed to create pvc with err: %v", err))
framework.Logf("PVC created: %v in namespace: %v", pvclaim.Name, pvcnamespace)
return pvclaim, err
}
// createPVC helps creates pvc with given namespace and labels using given
// storage class.
func scaleCreatePVC(client clientset.Interface, pvcnamespace string, pvclaimlabels map[string]string, ds string,
storageclass *storagev1.StorageClass, accessMode v1.PersistentVolumeAccessMode, wg *sync.WaitGroup) {
defer wg.Done()
pvcspec := getPersistentVolumeClaimSpecWithStorageClass(pvcnamespace, ds, storageclass, pvclaimlabels, accessMode)
ginkgo.By(fmt.Sprintf("Creating PVC using the Storage Class %s with disk size %s and labels: %+v accessMode: %+v",
storageclass.Name, ds, pvclaimlabels, accessMode))
pvclaim, err := fpv.CreatePVC(client, pvcnamespace, pvcspec)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), fmt.Sprintf("Failed to create pvc with err: %v", err))
pvclaims = append(pvclaims, pvclaim)
}
// scaleCreateDeletePVC helps create and delete pvc with given namespace and
// labels, using given storage class (envWorkerPerRoutine * envNumberOfGoRoutines)
// times. Create and Delete PVC happens synchronously. PVC is picked randomly
// for deletion.
func scaleCreateDeletePVC(client clientset.Interface, pvcnamespace string, pvclaimlabels map[string]string,
ds string, storageclass *storagev1.StorageClass, accessMode v1.PersistentVolumeAccessMode,
wg *sync.WaitGroup, lock *sync.Mutex, worker int) {
ctx, cancel := context.WithCancel(context.Background())
var totalPVCDeleted int = 0
defer cancel()
defer wg.Done()
for index := 1; index <= worker; index++ {
pvcspec := getPersistentVolumeClaimSpecWithStorageClass(pvcnamespace, ds, storageclass, pvclaimlabels, accessMode)
ginkgo.By(fmt.Sprintf("Creating PVC using the Storage Class %s with disk size %s and labels: %+v accessMode: %+v",
storageclass.Name, ds, pvclaimlabels, accessMode))
pvclaim, err := fpv.CreatePVC(client, pvcnamespace, pvcspec)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), fmt.Sprintf("Failed to create pvc with err: %v", err))
lock.Lock()
pvclaims = append(pvclaims, pvclaim)
pvclaimToDelete := randomPickPVC()
lock.Unlock()
// Check if volume is present or not.
pvclaimToDelete, err = client.CoreV1().PersistentVolumeClaims(pvclaimToDelete.Namespace).Get(
ctx, pvclaimToDelete.Name, metav1.GetOptions{})
if err == nil {
// Waiting for PVC to be bound.
pvclaimsToDelete := append(pvclaimsToDelete, pvclaimToDelete)
_, err = fpv.WaitForPVClaimBoundPhase(client, pvclaimsToDelete, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
err = fpv.DeletePersistentVolumeClaim(client, pvclaimToDelete.Name, pvcnamespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
totalPVCDeleted++
}
}
framework.Logf("Total number of deleted PVCs %v", totalPVCDeleted)
}
// randomPickPVC returns randomly picked PVC from list of PVCs.
func randomPickPVC() *v1.PersistentVolumeClaim {
index := rand.Intn(len(pvclaims))
pvclaims[len(pvclaims)-1], pvclaims[index] = pvclaims[index], pvclaims[len(pvclaims)-1]
pvclaimToDelete := pvclaims[len(pvclaims)-1]
pvclaims = pvclaims[:len(pvclaims)-1]
framework.Logf("pvc to delete %v", pvclaimToDelete.Name)
return pvclaimToDelete
}
// createStatefulSetWithOneReplica helps create a stateful set with one replica.
func createStatefulSetWithOneReplica(client clientset.Interface, manifestPath string,
namespace string) (*appsv1.StatefulSet, *v1.Service) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mkpath := func(file string) string {
return filepath.Join(manifestPath, file)
}
statefulSet, err := manifest.StatefulSetFromManifest(mkpath("statefulset.yaml"), namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
service, err := manifest.SvcFromManifest(mkpath("service.yaml"))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
service, err = client.CoreV1().Services(namespace).Create(ctx, service, metav1.CreateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
*statefulSet.Spec.Replicas = 1
_, err = client.AppsV1().StatefulSets(namespace).Create(ctx, statefulSet, metav1.CreateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return statefulSet, service
}
// updateDeploymentReplicawithWait helps to update the replica for a deployment
// with wait.
func updateDeploymentReplicawithWait(client clientset.Interface, count int32, name string, namespace string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var deployment *appsv1.Deployment
var err error
waitErr := wait.Poll(healthStatusPollInterval, healthStatusPollTimeout, func() (bool, error) {
deployment, err = client.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if err != nil {
return false, nil
}
*deployment.Spec.Replicas = count
ginkgo.By("Waiting for update operation on deployment to take effect")
deployment, err = client.AppsV1().Deployments(namespace).Update(ctx, deployment, metav1.UpdateOptions{})
if err != nil {
return false, err
}
err = fdep.WaitForDeploymentComplete(client, deployment)
if err != nil {
return false, err
}
return true, nil
})
return waitErr
}
// updateDeploymentReplica helps to update the replica for a deployment.
func updateDeploymentReplica(client clientset.Interface,
count int32, name string, namespace string) *appsv1.Deployment {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
deployment, err := client.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
*deployment.Spec.Replicas = count
deployment, err = client.AppsV1().Deployments(namespace).Update(ctx, deployment, metav1.UpdateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
err = fdep.WaitForDeploymentComplete(client, deployment)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return deployment
}
// bringDownCsiController helps to bring the csi controller pod down.
// Default namespace used here is csiSystemNamespace.
func bringDownCsiController(Client clientset.Interface, namespace ...string) {
if len(namespace) == 0 {
updateDeploymentReplica(Client, 0, vSphereCSIControllerPodNamePrefix, csiSystemNamespace)
} else {
updateDeploymentReplica(Client, 0, vSphereCSIControllerPodNamePrefix, namespace[0])
}
ginkgo.By("Controller is down")
}
// bringDownTKGController helps to bring the TKG control manager pod down.
// Its taks svc client as input.
func bringDownTKGController(Client clientset.Interface) {
updateDeploymentReplica(Client, 0, vsphereControllerManager, vsphereTKGSystemNamespace)
ginkgo.By("TKGControllManager replica is set to 0")
}