-
Notifications
You must be signed in to change notification settings - Fork 137
/
nodeserver_test.go
1060 lines (981 loc) · 31.9 KB
/
nodeserver_test.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 2020 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 smb
import (
"context"
"encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"github.com/kubernetes-csi/csi-driver-smb/test/utils/testutil"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
mount "k8s.io/mount-utils"
"k8s.io/utils/exec"
)
func matchFlakyWindowsError(mainError error, substr string) bool {
var errorMessage string
if mainError == nil {
errorMessage = ""
} else {
errorMessage = mainError.Error()
}
return strings.Contains(errorMessage, substr)
}
func TestNodeStageVolume(t *testing.T) {
stdVolCap := csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{},
},
}
mountGroupVolCap := csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{
VolumeMountGroup: "1000",
},
},
}
mountGroupWithModesVolCap := csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{
VolumeMountGroup: "1000",
MountFlags: []string{"file_mode=0111", "dir_mode=0111"},
},
},
}
errorMountSensSource := testutil.GetWorkDirPath("error_mount_sens_source", t)
smbFile := testutil.GetWorkDirPath("smb.go", t)
sourceTest := testutil.GetWorkDirPath("source_test", t)
testSource := "\\\\hostname\\share\\test"
volContext := map[string]string{
sourceField: testSource,
}
volContextWithMetadata := map[string]string{
sourceField: testSource,
pvcNameKey: "pvcname",
pvcNamespaceKey: "pvcnamespace",
pvNameKey: "pvname",
}
secrets := map[string]string{
usernameField: "test_username",
passwordField: "test_password",
domainField: "test_doamin",
}
tests := []struct {
desc string
setup func(*Driver)
req *csi.NodeStageVolumeRequest
expectedErr testutil.TestError
cleanup func(*Driver)
// use this field only when Windows
// gives flaky error messages due
// to CSI proxy
// This field holds the base error message
// that is common amongst all other flaky
// error messages
flakyWindowsErrorMessage string
skipOnWindows bool
}{
{
desc: "[Error] Volume ID missing",
req: &csi.NodeStageVolumeRequest{},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume ID missing in request"),
},
},
{
desc: "[Error] Volume capabilities missing",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1"},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume capability not provided"),
},
},
{
desc: "[Error] Stage target path missing",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1", VolumeCapability: &stdVolCap},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Staging target not provided"),
},
},
{
desc: "[Error] Source field is missing in context",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1", StagingTargetPath: sourceTest,
VolumeCapability: &stdVolCap},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "source field is missing, current context: map[]"),
},
},
{
desc: "[Error] Not a Directory",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: smbFile,
VolumeCapability: &stdVolCap,
VolumeContext: volContext,
Secrets: secrets},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.Internal, fmt.Sprintf("MkdirAll %s failed with error: mkdir %s: not a directory", smbFile, smbFile)),
WindowsError: status.Error(codes.Internal, fmt.Sprintf("Could not mount target %s: mkdir %s: The system cannot find the path specified.", smbFile, smbFile)),
},
},
{
desc: "[Error] Volume operation in progress",
setup: func(d *Driver) {
d.volumeLocks.TryAcquire(fmt.Sprintf("%s-%s", "vol_1", sourceTest))
},
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1", StagingTargetPath: sourceTest,
VolumeCapability: &stdVolCap,
VolumeContext: volContext,
Secrets: secrets},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.Aborted, fmt.Sprintf(volumeOperationAlreadyExistsFmt, "vol_1")),
},
cleanup: func(d *Driver) {
d.volumeLocks.Release(fmt.Sprintf("%s-%s", "vol_1", sourceTest))
},
},
{
desc: "[Error] Failed SMB mount mocked by MountSensitive",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: errorMountSensSource,
VolumeCapability: &stdVolCap,
VolumeContext: volContext,
Secrets: secrets},
skipOnWindows: true,
flakyWindowsErrorMessage: fmt.Sprintf("rpc error: code = Internal desc = volume(vol_1##) mount \"%s\" on %#v failed "+
"with NewSmbGlobalMapping(%s, %s) failed with error: rpc error: code = Unknown desc = NewSmbGlobalMapping failed.",
strings.Replace(testSource, "\\", "\\\\", -1), errorMountSensSource, testSource, errorMountSensSource),
expectedErr: testutil.TestError{
DefaultError: status.Errorf(codes.Internal,
"volume(vol_1##) mount \"%s\" on \"%s\" failed with fake "+
"MountSensitive: target error",
strings.Replace(testSource, "\\", "\\\\", -1), errorMountSensSource),
},
},
{
desc: "[Success] Valid request",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: sourceTest,
VolumeCapability: &stdVolCap,
VolumeContext: volContext,
Secrets: secrets},
skipOnWindows: true,
flakyWindowsErrorMessage: fmt.Sprintf("rpc error: code = Internal desc = volume(vol_1##) mount \"%s\" on %#v failed with "+
"NewSmbGlobalMapping(%s, %s) failed with error: rpc error: code = Unknown desc = NewSmbGlobalMapping failed.",
strings.Replace(testSource, "\\", "\\\\", -1), sourceTest, testSource, sourceTest),
expectedErr: testutil.TestError{},
},
{
desc: "[Success] Valid request with pv/pvc metadata",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: sourceTest,
VolumeCapability: &stdVolCap,
VolumeContext: volContextWithMetadata,
Secrets: secrets},
skipOnWindows: true,
flakyWindowsErrorMessage: fmt.Sprintf("rpc error: code = Internal desc = volume(vol_1##) mount \"%s\" on %#v failed with "+
"NewSmbGlobalMapping(%s, %s) failed with error: rpc error: code = Unknown desc = NewSmbGlobalMapping failed.",
strings.Replace(testSource, "\\", "\\\\", -1), sourceTest, testSource, sourceTest),
expectedErr: testutil.TestError{},
},
{
desc: "[Success] Valid request with VolumeMountGroup",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: sourceTest,
VolumeCapability: &mountGroupVolCap,
VolumeContext: volContext,
Secrets: secrets},
skipOnWindows: true,
flakyWindowsErrorMessage: fmt.Sprintf("rpc error: code = Internal desc = volume(vol_1##) mount \"%s\" on %#v failed with "+
"NewSmbGlobalMapping(%s, %s) failed with error: rpc error: code = Unknown desc = NewSmbGlobalMapping failed.",
strings.Replace(testSource, "\\", "\\\\", -1), sourceTest, testSource, sourceTest),
expectedErr: testutil.TestError{},
},
{
desc: "[Success] Valid request with VolumeMountGroup and file/dir modes",
req: &csi.NodeStageVolumeRequest{VolumeId: "vol_1##", StagingTargetPath: sourceTest,
VolumeCapability: &mountGroupWithModesVolCap,
VolumeContext: volContext,
Secrets: secrets},
skipOnWindows: true,
flakyWindowsErrorMessage: fmt.Sprintf("rpc error: code = Internal desc = volume(vol_1##) mount \"%s\" on %#v failed with "+
"NewSmbGlobalMapping(%s, %s) failed with error: rpc error: code = Unknown desc = NewSmbGlobalMapping failed.",
strings.Replace(testSource, "\\", "\\\\", -1), sourceTest, testSource, sourceTest),
expectedErr: testutil.TestError{},
},
}
// Setup
d := NewFakeDriver()
for _, test := range tests {
if test.skipOnWindows && runtime.GOOS == "windows" {
continue
}
mounter, err := NewFakeMounter()
if err != nil {
t.Fatalf("failed to get fake mounter: %v", err)
}
d.mounter = mounter
if test.setup != nil {
test.setup(d)
}
_, err = d.NodeStageVolume(context.Background(), test.req)
// separate assertion for flaky error messages
if test.flakyWindowsErrorMessage != "" && runtime.GOOS == "windows" {
if !matchFlakyWindowsError(err, test.flakyWindowsErrorMessage) {
t.Errorf("test case: %s, \nUnexpected error: %v\nExpected error: %v", test.desc, err, test.flakyWindowsErrorMessage)
}
} else {
if !testutil.AssertError(&test.expectedErr, err) {
t.Errorf("test case: %s, \nUnexpected error: %v\nExpected error: %v", test.desc, err, test.expectedErr.GetExpectedError())
}
}
if test.cleanup != nil {
test.cleanup(d)
}
}
// Clean up
err := os.RemoveAll(sourceTest)
assert.NoError(t, err)
err = os.RemoveAll(errorMountSensSource)
assert.NoError(t, err)
}
func TestNodeGetInfo(t *testing.T) {
d := NewFakeDriver()
// Test valid request
req := csi.NodeGetInfoRequest{}
resp, err := d.NodeGetInfo(context.Background(), &req)
assert.NoError(t, err)
assert.Equal(t, resp.GetNodeId(), fakeNodeID)
}
func TestNodeGetCapabilities(t *testing.T) {
d := NewFakeDriver()
capType := &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME,
},
}
capList := []*csi.NodeServiceCapability{{
Type: capType,
}}
d.NSCap = capList
// Test valid request
req := csi.NodeGetCapabilitiesRequest{}
resp, err := d.NodeGetCapabilities(context.Background(), &req)
assert.NotNil(t, resp)
assert.Equal(t, resp.Capabilities[0].GetType(), capType)
assert.NoError(t, err)
}
func TestNodeExpandVolume(t *testing.T) {
d := NewFakeDriver()
req := csi.NodeExpandVolumeRequest{}
resp, err := d.NodeExpandVolume(context.Background(), &req)
assert.Nil(t, resp)
if !reflect.DeepEqual(err, status.Error(codes.Unimplemented, "")) {
t.Errorf("Unexpected error: %v", err)
}
}
func TestNodePublishVolume(t *testing.T) {
volumeCap := csi.VolumeCapability_AccessMode{Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER}
errorMountSource := testutil.GetWorkDirPath("error_mount_source", t)
alreadyMountedTarget := testutil.GetWorkDirPath("false_is_likely_exist_target", t)
smbFile := testutil.GetWorkDirPath("smb.go", t)
sourceTest := testutil.GetWorkDirPath("source_test", t)
targetTest := testutil.GetWorkDirPath("target_test", t)
tests := []struct {
desc string
setup func(*Driver)
req *csi.NodePublishVolumeRequest
skipOnWindows bool
expectedErr testutil.TestError
cleanup func(*Driver)
}{
{
desc: "[Error] Volume capabilities missing",
req: &csi.NodePublishVolumeRequest{},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume capability missing in request"),
},
},
{
desc: "[Error] Volume ID missing",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap}},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume ID missing in request"),
},
},
{
desc: "[Error] Target path missing",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1"},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Target path not provided"),
},
},
{
desc: "[Error] Stage target path missing",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: targetTest},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Staging target not provided"),
},
},
{
desc: "[Error] Not a directory",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: smbFile,
StagingTargetPath: sourceTest,
Readonly: true},
expectedErr: testutil.TestError{
DefaultError: status.Errorf(codes.Internal, "Could not mount target \"%s\": mkdir %s: not a directory", smbFile, smbFile),
WindowsError: status.Errorf(codes.Internal, "Could not mount target %#v: mkdir %s: The system cannot find the path specified.", smbFile, smbFile),
},
},
{
desc: "[Error] Mount error mocked by Mount",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: targetTest,
StagingTargetPath: errorMountSource,
Readonly: true},
// todo: This test does not return any error on windows
// Once the issue is figured out, we'll remove this field
skipOnWindows: true,
expectedErr: testutil.TestError{
DefaultError: status.Errorf(codes.Internal, "Could not mount \"%s\" at \"%s\": fake Mount: source error", errorMountSource, targetTest),
},
},
{
desc: "[Success] Valid request read only",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: targetTest,
StagingTargetPath: sourceTest,
Readonly: true},
expectedErr: testutil.TestError{},
},
{
desc: "[Success] Valid request already mounted",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: alreadyMountedTarget,
StagingTargetPath: sourceTest,
Readonly: true},
expectedErr: testutil.TestError{},
},
{
desc: "[Success] Valid request",
req: &csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: targetTest,
StagingTargetPath: sourceTest,
Readonly: true},
expectedErr: testutil.TestError{},
},
}
// Setup
_ = makeDir(alreadyMountedTarget)
d := NewFakeDriver()
mounter, err := NewFakeMounter()
if err != nil {
t.Fatalf("failed to get fake mounter: %v", err)
}
d.mounter = mounter
for _, test := range tests {
if !(test.skipOnWindows && runtime.GOOS == "windows") {
if test.setup != nil {
test.setup(d)
}
_, err := d.NodePublishVolume(context.Background(), test.req)
if !testutil.AssertError(&test.expectedErr, err) {
t.Errorf("test case: %s, \nUnexpected error: %v\nExpected error: %v", test.desc, err, test.expectedErr.GetExpectedError())
}
if test.cleanup != nil {
test.cleanup(d)
}
}
}
// Clean up
err = os.RemoveAll(targetTest)
assert.NoError(t, err)
err = os.RemoveAll(alreadyMountedTarget)
assert.NoError(t, err)
}
func TestNodeUnpublishVolume(t *testing.T) {
errorTarget := testutil.GetWorkDirPath("error_is_likely_target", t)
targetFile := testutil.GetWorkDirPath("abc.go", t)
targetTest := testutil.GetWorkDirPath("target_test", t)
tests := []struct {
desc string
setup func(*Driver)
req *csi.NodeUnpublishVolumeRequest
expectedErr testutil.TestError
skipOnWindows bool
cleanup func(*Driver)
}{
{
desc: "[Error] Volume ID missing",
req: &csi.NodeUnpublishVolumeRequest{TargetPath: targetTest},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume ID missing in request"),
},
},
{
desc: "[Error] Target missing",
req: &csi.NodeUnpublishVolumeRequest{VolumeId: "vol_1"},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Target path missing in request"),
},
},
{
desc: "[Success] Valid request",
req: &csi.NodeUnpublishVolumeRequest{TargetPath: targetFile, VolumeId: "vol_1"},
expectedErr: testutil.TestError{},
},
}
// Setup
_ = makeDir(errorTarget)
d := NewFakeDriver()
mounter, err := NewFakeMounter()
if err != nil {
t.Fatalf("failed to get fake mounter: %v", err)
}
d.mounter = mounter
for _, test := range tests {
if !(test.skipOnWindows && runtime.GOOS == "windows") {
if test.setup != nil {
test.setup(d)
}
_, err := d.NodeUnpublishVolume(context.Background(), test.req)
if !testutil.AssertError(&test.expectedErr, err) {
t.Errorf("test case: %s, \nUnexpected error: %v\nExpected error: %v", test.desc, err, test.expectedErr.GetExpectedError())
}
if test.cleanup != nil {
test.cleanup(d)
}
}
}
// Clean up
err = os.RemoveAll(errorTarget)
assert.NoError(t, err)
}
func TestNodeUnstageVolume(t *testing.T) {
errorTarget := testutil.GetWorkDirPath("error_is_likely_target", t)
targetFile := testutil.GetWorkDirPath("abc.go", t)
targetTest := testutil.GetWorkDirPath("target_test", t)
tests := []struct {
desc string
setup func(*Driver)
req *csi.NodeUnstageVolumeRequest
skipOnWindows bool
expectedErr testutil.TestError
cleanup func(*Driver)
}{
{
desc: "[Error] Volume ID missing",
req: &csi.NodeUnstageVolumeRequest{StagingTargetPath: targetTest},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Volume ID missing in request"),
},
},
{
desc: "[Error] Target missing",
req: &csi.NodeUnstageVolumeRequest{VolumeId: "vol_1"},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.InvalidArgument, "Staging target not provided"),
},
},
{
desc: "[Error] Volume operation in progress",
setup: func(d *Driver) {
d.volumeLocks.TryAcquire(fmt.Sprintf("%s-%s", "vol_1", targetFile))
},
req: &csi.NodeUnstageVolumeRequest{StagingTargetPath: targetFile, VolumeId: "vol_1"},
expectedErr: testutil.TestError{
DefaultError: status.Error(codes.Aborted, fmt.Sprintf(volumeOperationAlreadyExistsFmt, "vol_1")),
},
cleanup: func(d *Driver) {
d.volumeLocks.Release(fmt.Sprintf("%s-%s", "vol_1", targetFile))
},
},
{
desc: "[Success] Valid request",
req: &csi.NodeUnstageVolumeRequest{StagingTargetPath: targetFile, VolumeId: "vol_1"},
expectedErr: testutil.TestError{},
},
}
// Setup
_ = makeDir(errorTarget)
d := NewFakeDriver()
mounter, err := NewFakeMounter()
if err != nil {
t.Fatalf("failed to get fake mounter: %v", err)
}
d.mounter = mounter
for _, test := range tests {
if !(test.skipOnWindows && runtime.GOOS == "windows") {
if test.setup != nil {
test.setup(d)
}
_, err := d.NodeUnstageVolume(context.Background(), test.req)
if !testutil.AssertError(&test.expectedErr, err) {
t.Errorf("test case: %s, \nUnexpected error: %v\nExpected error: %v", test.desc, err, test.expectedErr.GetExpectedError())
}
if test.cleanup != nil {
test.cleanup(d)
}
}
}
// Clean up
err = os.RemoveAll(errorTarget)
assert.NoError(t, err)
}
func TestEnsureMountPoint(t *testing.T) {
errorTarget := "./error_is_likely_target"
alreadyExistTarget := "./false_is_likely_exist_target"
falseTarget := "./false_is_likely_target"
smbFile := "./smb.go"
targetTest := "./target_test"
tests := []struct {
desc string
target string
expectedErr error
}{
{
desc: "[Error] Mocked by IsLikelyNotMountPoint",
target: errorTarget,
expectedErr: fmt.Errorf("fake IsLikelyNotMountPoint: fake error"),
},
{
desc: "[Error] Error opening file",
target: falseTarget,
expectedErr: &os.PathError{Op: "open", Path: "./false_is_likely_target", Err: syscall.ENOENT},
},
{
desc: "[Error] Not a directory",
target: smbFile,
expectedErr: &os.PathError{Op: "mkdir", Path: "./smb.go", Err: syscall.ENOTDIR},
},
{
desc: "[Success] Successful run",
target: targetTest,
expectedErr: nil,
},
{
desc: "[Success] Already existing mount",
target: alreadyExistTarget,
expectedErr: nil,
},
}
// Setup
_ = makeDir(alreadyExistTarget)
d := NewFakeDriver()
fakeMounter := &fakeMounter{}
d.mounter = &mount.SafeFormatAndMount{
Interface: fakeMounter,
}
for _, test := range tests {
_, err := d.ensureMountPoint(test.target)
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("test case: %s, Unexpected error: %v", test.desc, err)
}
}
// Clean up
err := os.RemoveAll(alreadyExistTarget)
assert.NoError(t, err)
err = os.RemoveAll(targetTest)
assert.NoError(t, err)
}
func TestMakeDir(t *testing.T) {
targetTest := "./target_test"
//Successfully create directory
err := makeDir(targetTest)
assert.NoError(t, err)
//Failed case
err = makeDir("./smb.go")
var e *os.PathError
if !errors.As(err, &e) {
t.Errorf("Unexpected Error: %v", err)
}
// Remove the directory created
err = os.RemoveAll(targetTest)
assert.NoError(t, err)
}
func TestNodeGetVolumeStats(t *testing.T) {
nonexistedPath := "/not/a/real/directory"
fakePath := "/tmp/fake-volume-path"
tests := []struct {
desc string
req *csi.NodeGetVolumeStatsRequest
expectedErr error
}{
{
desc: "[Error] Volume ID missing",
req: &csi.NodeGetVolumeStatsRequest{VolumePath: fakePath},
expectedErr: status.Error(codes.InvalidArgument, "NodeGetVolumeStats volume ID was empty"),
},
{
desc: "[Error] VolumePath missing",
req: &csi.NodeGetVolumeStatsRequest{VolumeId: "vol_1"},
expectedErr: status.Error(codes.InvalidArgument, "NodeGetVolumeStats volume path was empty"),
},
{
desc: "[Error] Incorrect volume path",
req: &csi.NodeGetVolumeStatsRequest{VolumePath: nonexistedPath, VolumeId: "vol_1"},
expectedErr: status.Errorf(codes.NotFound, "path /not/a/real/directory does not exist"),
},
{
desc: "[Success] Standard success",
req: &csi.NodeGetVolumeStatsRequest{VolumePath: fakePath, VolumeId: "vol_1"},
expectedErr: nil,
},
}
// Setup
_ = makeDir(fakePath)
d := NewFakeDriver()
for _, test := range tests {
_, err := d.NodeGetVolumeStats(context.Background(), test.req)
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("desc: %v, expected error: %v, actual error: %v", test.desc, test.expectedErr, err)
}
}
// Clean up
err := os.RemoveAll(fakePath)
assert.NoError(t, err)
}
func TestCheckGidPresentInMountFlags(t *testing.T) {
tests := []struct {
desc string
MountFlags []string
result bool
}{
{
desc: "[Success] Gid present in mount flags",
MountFlags: []string{"gid=3000"},
result: true,
},
{
desc: "[Success] Gid not present in mount flags",
MountFlags: []string{},
result: false,
},
}
for _, test := range tests {
gIDPresent := checkGidPresentInMountFlags(test.MountFlags)
if gIDPresent != test.result {
t.Errorf("[%s]: Expected result : %t, Actual result: %t", test.desc, test.result, gIDPresent)
}
}
}
func TestVolumeKerberosCacheName(t *testing.T) {
tests := []struct {
name string
}{
{
name: "s", // short name
},
{
name: "Volume Handle##unique suffix",
},
{
name: "Volume With Spaces and Slashes // and symbols that produce /+ after base64 ???????~~~~~~~~",
},
}
for _, test := range tests {
fileName := volumeKerberosCacheName(test.name)
if strings.Contains(fileName, "/") || strings.Contains(fileName, "+") {
t.Errorf("[%s]: Expected result should not contain / or +, Actual result: %s", test.name, fileName)
}
}
}
func TestHasKerberosMountOption(t *testing.T) {
tests := []struct {
desc string
MountFlags []string
result bool
}{
{
desc: "[Success] Sec kerberos present in mount flags",
MountFlags: []string{"sec=krb5"},
result: true,
},
{
desc: "[Success] Sec kerberos present in mount flags",
MountFlags: []string{"sec=krb5i"},
result: true,
},
{
desc: "[Success] Sec kerberos not present in mount flags",
MountFlags: []string{},
result: false,
},
{
desc: "[Success] Sec kerberos not present in mount flags",
MountFlags: []string{"sec=ntlm"},
result: false,
},
}
for _, test := range tests {
securityIsKerberos := hasKerberosMountOption(test.MountFlags)
if securityIsKerberos != test.result {
t.Errorf("[%s]: Expected result : %t, Actual result: %t", test.desc, test.result, securityIsKerberos)
}
}
}
func TestGetCredUID(t *testing.T) {
_, convertErr := strconv.Atoi("foo")
tests := []struct {
desc string
MountFlags []string
result int
expectedErr error
}{
{
desc: "[Success] Got correct credUID",
MountFlags: []string{"cruid=1000"},
result: 1000,
expectedErr: nil,
},
{
desc: "[Success] Got correct credUID",
MountFlags: []string{"cruid=0"},
result: 0,
expectedErr: nil,
},
{
desc: "[Error] Got error when no CredUID",
MountFlags: []string{},
result: -1,
expectedErr: fmt.Errorf("Can't find credUid in mount flags"),
},
{
desc: "[Error] Got error when CredUID is not an int",
MountFlags: []string{"cruid=foo"},
result: 0,
expectedErr: convertErr,
},
}
for _, test := range tests {
credUID, err := getCredUID(test.MountFlags)
if credUID != test.result {
t.Errorf("[%s]: Expected result : %d, Actual result: %d", test.desc, test.result, credUID)
}
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("[%s]: Expected error : %v, Actual error: %v", test.desc, test.expectedErr, err)
}
}
}
func TestGetKerberosCache(t *testing.T) {
ticket := []byte{'G', 'O', 'L', 'A', 'N', 'G'}
base64Ticket := base64.StdEncoding.EncodeToString(ticket)
credUID := 1000
krb5CacheDirectory := "/var/lib/kubelet/kerberos/"
krb5Prefix := "krb5cc_"
goodFileName := fmt.Sprintf("%s%s%d", krb5CacheDirectory, krb5Prefix, credUID)
krb5CcacheName := "krb5cc_1000"
_, base64DecError := base64.StdEncoding.DecodeString("123")
tests := []struct {
desc string
credUID int
secrets map[string]string
expectedFileName string
expectedContent []byte
expectedErr error
}{
{
desc: "[Success] Got correct filename and content",
credUID: 1000,
secrets: map[string]string{
krb5CcacheName: base64Ticket,
},
expectedFileName: goodFileName,
expectedContent: ticket,
expectedErr: nil,
},
{
desc: "[Error] Throw error if credUID mismatch",
credUID: 1001,
secrets: map[string]string{
krb5CcacheName: base64Ticket,
},
expectedFileName: "",
expectedContent: nil,
expectedErr: status.Error(codes.InvalidArgument, fmt.Sprintf("Empty kerberos cache in key %s", "krb5cc_1001")),
},
{
desc: "[Error] Throw error if ticket is empty in secret",
credUID: 1000,
secrets: map[string]string{
krb5CcacheName: "",
},
expectedFileName: "",
expectedContent: nil,
expectedErr: status.Error(codes.InvalidArgument, fmt.Sprintf("Empty kerberos cache in key %s", krb5CcacheName)),
},
{
desc: "[Error] Throw error if ticket is invalid base64",
credUID: 1000,
secrets: map[string]string{
krb5CcacheName: "123",
},
expectedFileName: "",
expectedContent: nil,
expectedErr: status.Error(codes.InvalidArgument, fmt.Sprintf("Malformed kerberos cache in key %s, expected to be in base64 form: %v", krb5CcacheName, base64DecError)),
},
}
for _, test := range tests {
fileName, content, err := getKerberosCache(krb5CacheDirectory, krb5Prefix, test.credUID, test.secrets)
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("[%s]: Expected error : %v, Actual error: %v", test.desc, test.expectedErr, err)
} else {
if fileName != test.expectedFileName {
t.Errorf("[%s]: Expected filename : %s, Actual result: %s", test.desc, test.expectedFileName, fileName)
}
if !reflect.DeepEqual(content, test.expectedContent) {
t.Errorf("[%s]: Expected content : %s, Actual content: %s", test.desc, test.expectedContent, content)
}
}
}
}
func TestNodePublishVolumeIdempotentMount(t *testing.T) {
if runtime.GOOS == "windows" || os.Getuid() != 0 {
return
}
sourceTest := "./sourcetest"
err := makeDir(sourceTest)
assert.NoError(t, err)
targetTest := "./targettest"
err = makeDir(targetTest)
assert.NoError(t, err)
d := NewFakeDriver()
d.mounter = &mount.SafeFormatAndMount{
Interface: mount.New(""),
Exec: exec.New(),
}
volumeCap := csi.VolumeCapability_AccessMode{Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER}
req := csi.NodePublishVolumeRequest{VolumeCapability: &csi.VolumeCapability{AccessMode: &volumeCap},
VolumeId: "vol_1",
TargetPath: targetTest,
StagingTargetPath: sourceTest,
Readonly: true}
_, err = d.NodePublishVolume(context.Background(), &req)
assert.NoError(t, err)
_, err = d.NodePublishVolume(context.Background(), &req)
assert.NoError(t, err)
// ensure the target not be mounted twice
targetAbs, err := filepath.Abs(targetTest)
assert.NoError(t, err)
mountList, err := d.mounter.List()
assert.NoError(t, err)
mountPointNum := 0
for _, mountPoint := range mountList {
if mountPoint.Path == targetAbs {
mountPointNum++
}
}
assert.Equal(t, 1, mountPointNum)
err = d.mounter.Unmount(targetTest)
assert.NoError(t, err)
_ = d.mounter.Unmount(targetTest)
err = os.RemoveAll(sourceTest)
assert.NoError(t, err)
err = os.RemoveAll(targetTest)
assert.NoError(t, err)
}
func TestEnableGroupRWX(t *testing.T) {
tests := []struct {
value string
expectedValue string
}{
{
value: "qwerty",
expectedValue: "qwerty",
},
{
value: "0111",
expectedValue: "0171",
},
}
for _, test := range tests {
mode := enableGroupRWX(test.value)
assert.Equal(t, test.expectedValue, mode)
}
}
func TestRaiseGroupRWXInMountFlags(t *testing.T) {
tests := []struct {
mountFlags []string
flag string
expectedResult bool
mountFlagsUpdated bool
expectedMountFlags []string