-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathservice_unit_test.go
688 lines (653 loc) · 17.2 KB
/
service_unit_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
/*
Copyright © 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
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 service
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"os"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
csi "github.com/container-storage-interface/spec/lib/go/csi"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
const (
numOfCylindersForDefaultSize = 547
)
var (
s service
mockedExitStatus = 0
mockedStdout string
debugUnitTest = false
)
var (
counters = [60]int{}
testwg sync.WaitGroup
)
func incrementCounter(identifier string, num int) {
lockNumber := RequestLock(identifier, "")
timeToSleep := rand.Intn(1010-500) + 500 // #nosec G404
time.Sleep(time.Duration(timeToSleep) * time.Microsecond)
if debugUnitTest {
fmt.Printf("Sleeping for :%d microseconds\n", timeToSleep)
}
counters[num]++
ReleaseLock(identifier, "", lockNumber)
testwg.Done()
}
// TestReleaseLockWOAcquiring tries to release a lock that
// was never acquired.
func TestReleaseLockWOAcquiring(_ *testing.T) {
LockRequestHandler()
CleanupMapEntries(10 * time.Millisecond)
ReleaseLock("nonExistentLock", "", 0)
}
// TestReleasingOtherLock tries to release a lock that it didn't acquire
func TestReleasingOtherLock(_ *testing.T) {
LockRequestHandler()
CleanupMapEntries(10 * time.Millisecond)
lockNumber := RequestLock("new_lock", "")
ReleaseLock("new_lock", "", lockNumber+1)
ReleaseLock("new_lock", "", lockNumber)
}
var lockCounter int
func incrementLockCounter() {
lockNumber := RequestLock("identifier", "")
defer ReleaseLock("identifier", "", lockNumber)
lockCounter++
}
func TestLockCounter(t *testing.T) {
LockRequestHandler()
CleanupMapEntries(10 * time.Millisecond)
for i := 0; i < 500; i++ {
// Acquire and release the lock in same goroutine
incrementLockCounter()
}
if lockCounter != 500 {
t.Errorf("Expected lock counter to be 500 but found: %d", lockCounter)
}
}
func TestLocks(t *testing.T) {
LockRequestHandler()
CleanupMapEntries(10 * time.Millisecond)
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
for i := 0; i < 60; i++ {
testwg.Add(1)
sgname := "sg" + strconv.Itoa(i)
go incrementCounter(sgname, i)
}
testwg.Wait()
// Check if all the counters were updated properly
for _, counter := range counters {
if counter != 6 {
t.Errorf("expected counter to be %d but found %d", 6, counter)
}
}
}
func TestGetVolSize(t *testing.T) {
tests := []struct {
cr *csi.CapacityRange
numOfCylinders int
}{
{
// not requesting any range should result in a default size
cr: &csi.CapacityRange{
RequiredBytes: 0,
LimitBytes: 0,
},
numOfCylinders: numOfCylindersForDefaultSize,
},
{
// requesting a minimum below the MinVolumeSizeBytes
cr: &csi.CapacityRange{
RequiredBytes: MinVolumeSizeBytes - 1,
LimitBytes: 0,
},
numOfCylinders: 0,
},
{
// requesting a negative required bytes
cr: &csi.CapacityRange{
RequiredBytes: -1,
LimitBytes: 0,
},
numOfCylinders: 0,
},
{
// requesting a negative limit bytes
cr: &csi.CapacityRange{
RequiredBytes: 0,
LimitBytes: -1,
},
numOfCylinders: 0,
},
{
// not requesting a minimum but setting a limit below
// the minimum size should result in an error
cr: &csi.CapacityRange{
RequiredBytes: 0,
LimitBytes: MinVolumeSizeBytes - 1,
},
numOfCylinders: 0,
},
{
// requesting same sizes for minimum and maximum
// which can be serviced
cr: &csi.CapacityRange{
RequiredBytes: MinVolumeSizeBytes,
LimitBytes: MinVolumeSizeBytes,
},
numOfCylinders: 26,
},
{
// requesting size of 50 MB which is the advertised
// minimum volume size
cr: &csi.CapacityRange{
RequiredBytes: 50 * 1024 * 1024,
LimitBytes: 0,
},
numOfCylinders: 27,
},
{
// requesting same sizes for minimum and maximum
// which can't be serviced
cr: &csi.CapacityRange{
RequiredBytes: DefaultVolumeSizeBytes,
LimitBytes: DefaultVolumeSizeBytes,
},
numOfCylinders: 0,
},
{
// requesting volume size of 1 TB
cr: &csi.CapacityRange{
RequiredBytes: 1099511627776, // 1* 1024 * 1024 * 1024 * 1024
LimitBytes: 0,
},
numOfCylinders: 559241,
},
{
// requesting volume of MaxVolumeSizeBytes
cr: &csi.CapacityRange{
RequiredBytes: MaxVolumeSizeBytes,
LimitBytes: 0,
},
numOfCylinders: 35791395,
},
{
// requesting volume size of more than 1 TB
cr: &csi.CapacityRange{
RequiredBytes: MaxVolumeSizeBytes + 1,
LimitBytes: 0,
},
numOfCylinders: 0,
},
}
for _, tt := range tests {
tt := tt
t.Run("", func(st *testing.T) {
st.Parallel()
s := &service{}
num, err := s.validateVolSize(context.Background(), tt.cr, "", "", s.adminClient)
if tt.numOfCylinders == 0 {
// error is expected
assert.Error(st, err)
} else {
assert.EqualValues(st, tt.numOfCylinders, num)
}
})
}
}
func TestVolumeIdentifier(t *testing.T) {
volumePrefix := s.getClusterPrefix()
devID := "12345"
volumeName := "Vol-Name"
symID := "123456789012"
csiDeviceID := s.createCSIVolumeID(volumePrefix, volumeName, symID, devID)
volumeNameT, symIDT, devIDT, _, _, err := s.parseCsiID(csiDeviceID)
if err != nil {
t.Error()
t.Error(err.Error())
}
volumeName = fmt.Sprintf("csi-%s-%s", volumePrefix, volumeName)
if volumeNameT != volumeName ||
symIDT != symID || devIDT != devID {
t.Error("createCSIVolumeID and parseCsiID doesn't match")
}
// Test for empty device id
_, _, _, _, _, err = s.parseCsiID("")
if err == nil {
t.Error("Expected an error while parsing empty ID but recieved success")
}
// Test for malformed device id
malformedCSIDeviceID := "Vol1-Test"
volumeNameT, symIDT, devIDT, _, _, err = s.parseCsiID(malformedCSIDeviceID)
if err == nil {
t.Error("Expected an error while parsing malformed ID but recieved success")
}
malformedCSIDeviceID = "-vol1-Test"
_, _, _, _, _, err = s.parseCsiID(malformedCSIDeviceID)
if err == nil {
t.Error("Expected an error while parsing malformed ID but recieved success")
}
}
func TestMetroCSIDeviceID(t *testing.T) {
volumePrefix := s.getClusterPrefix()
devID := "12345"
volumeName := "Vol-Name"
symID := "123456789012"
remoteDevID := "98765"
remoteSymID := "000000000012"
volumeName = fmt.Sprintf("csi-%s-%s", volumePrefix, volumeName)
csiDeviceID := fmt.Sprintf("%s-%s:%s-%s:%s", volumeName, symID, remoteSymID, devID, remoteDevID)
volumeNameT, symIDT, devIDT, remSymIDT, remoteDevIDT, err := s.parseCsiID(csiDeviceID)
if err != nil {
t.Error()
t.Error(err.Error())
}
if volumeNameT != volumeName ||
symIDT != symID || devIDT != devID || remoteDevIDT != remoteDevID || remSymIDT != remoteSymID {
t.Error("createCSIVolumeID and parseCsiID doesn't match")
}
}
func TestStringSliceComparison(t *testing.T) {
valA := []string{"a", "b", "c"}
valB := []string{"c", "b", "a"}
valC := []string{"a", "b"}
valD := []string{"a", "b", "d"}
if !stringSlicesEqual(valA, valB) {
t.Error("Could not validate that reversed slices are equal")
}
if stringSlicesEqual(valA, valC) {
t.Error("Could not validate that slices of different sizes are different")
}
if stringSlicesEqual(valA, valD) {
t.Error("Could not validate that slices of different content are different")
}
}
func TestStringSliceRegexMatcher(t *testing.T) {
slice1 := []string{"aaa", "bbb", "abbba"}
matches := stringSliceRegexMatcher(slice1, ".*bbb.*")
if len(matches) != 2 {
t.Errorf("Expected 2 matches got %d: %s", len(matches), matches)
}
// Test using bad regex
matches = stringSliceRegexMatcher(slice1, "[a*")
if len(matches) != 0 {
t.Errorf("Expected 2 matches got %d: %s", len(matches), matches)
}
}
func TestExecCommandHelper(_ *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
fmt.Printf("Mocked stdout: %s", os.Getenv("STDOUT"))
fmt.Fprintf(os.Stdout, os.Getenv("STDOUT"))
i, _ := strconv.Atoi(os.Getenv("EXIT_STATUS"))
os.Exit(i)
}
func TestAppendIfMissing(t *testing.T) {
testStrings := []string{"Test1", "Test2", "Test3"}
testStrings = appendIfMissing(testStrings, "Test1")
count := 0
for _, str := range testStrings {
if str == "Test1" {
count++
}
}
if count != 1 {
t.Errorf("Expected no more than one occurence of string Test1 in slice but found %d", count)
}
count = 0
testStrings = appendIfMissing(testStrings, "Test4")
for _, str := range testStrings {
if str == "Test4" {
count++
}
}
if count != 1 {
t.Errorf("Expected no more than one occurence of string Test4 in slice but found %d", count)
}
}
func TestTruncateString(t *testing.T) {
stringToBeTruncated := "abcdefghijklmnopqrstuvwxyz"
// Set maxLength to an even number
truncatedString := truncateString(stringToBeTruncated, 10)
if truncatedString != "abcdevwxyz" {
t.Error("Truncated string doesn't match the expected string")
}
// Set maxLength to an odd number
truncatedString = truncateString(stringToBeTruncated, 11)
if truncatedString != "abcdeuvwxyz" {
t.Error("Truncated string doesn't match the expected string")
}
}
func TestFibreChannelSplitInitiatorID(t *testing.T) {
director, port, initiator, err := splitFibreChannelInitiatorID("FA-2A:6:0x1000000000000000")
if director != "FA-2A" {
t.Errorf("Expected director FA-2A got %s", director)
}
if port != "FA-2A:6" {
t.Errorf("Expected port FA-2A:6 got %s", port)
}
if initiator != "0x1000000000000000" {
t.Errorf("Expected initiator 0x1000000000000000 got %s", initiator)
}
_, _, _, err = splitFibreChannelInitiatorID("meaningless string")
if err == nil {
t.Errorf("Expected error but got none")
}
}
func TestPending(t *testing.T) {
tests := []struct {
npending int
maxpending int
differentIDs bool
errormsg string
}{
{
npending: 2,
maxpending: 1,
differentIDs: true,
errormsg: "overload",
},
{
npending: 4,
maxpending: 5,
differentIDs: true,
errormsg: "none",
},
{
npending: 2,
maxpending: 5,
differentIDs: false,
errormsg: "pending",
},
{
npending: 0,
maxpending: 1,
differentIDs: false,
errormsg: "none",
},
}
for _, test := range tests {
pendState := &pendingState{
maxPending: test.maxpending,
}
for i := 0; i < test.npending; i++ {
id := strconv.Itoa(i)
if test.differentIDs == false {
id = "same"
}
var vid volumeIDType
vid = volumeIDType(id)
err := vid.checkAndUpdatePendingState(pendState)
if debugUnitTest {
fmt.Printf("test %v err %v\n", test, err)
}
if i+1 == test.npending {
if test.errormsg == "none" {
if err != nil {
t.Error("Expected no error but got: " + err.Error())
}
} else {
if err != nil && !strings.Contains(err.Error(), test.errormsg) {
t.Error("Didn't get expected error: " + test.errormsg)
}
}
}
}
for i := 0; i <= test.maxpending; i++ {
id := strconv.Itoa(i)
if test.differentIDs == false {
id = "same"
}
var vid volumeIDType
vid = volumeIDType(id)
vid.clearPending(pendState)
}
}
}
func TestGobrickInitialization(t *testing.T) {
iscsiConnectorPrev := s.iscsiConnector
s.iscsiConnector = nil
s.initISCSIConnector("/")
if s.iscsiConnector == nil {
t.Error("Expected s.iscsiConnector to be initialized")
}
s.iscsiConnector = iscsiConnectorPrev
fcConnectorPrev := s.fcConnector
s.fcConnector = nil
s.initFCConnector("/")
if s.fcConnector == nil {
t.Error("Expected s.fcConnector to be initialized")
}
s.fcConnector = fcConnectorPrev
}
func TestSetGetLogFields(t *testing.T) {
fields := log.Fields{
"RequestID": "123",
"DeviceID": "12345",
}
ctx := setLogFields(nil, fields)
fields = getLogFields(ctx)
if fields["RequestID"] == nil {
t.Error("Expected fields.CSIRequestID to be initialized")
}
fields = getLogFields(nil)
if fields == nil {
t.Error("Expected fields to be initialized")
}
fields = getLogFields(context.Background())
if fields == nil {
t.Error("Expected fields to be initialized")
}
}
func TestEsnureISCSIDaemonIsStarted(t *testing.T) {
s.dBusConn = &mockDbusConnection{}
// Return a ListUnit mock response without ISCSId unit
mockgosystemdInducedErrors.ListUnitISCSIDNotPresentError = true
errMsg := fmt.Sprintf("failed to find iscsid.service. Going to panic")
assert.PanicsWithError(t, errMsg, func() { s.ensureISCSIDaemonStarted() })
mockgosystemdReset()
s.dBusConn = &mockDbusConnection{}
// Set the Daemon to inactive in mock response
mockgosystemdInducedErrors.ISCSIDInactiveError = true
mockgosystemdInducedErrors.StartUnitMaskedError = true
errMsg = fmt.Sprintf("mock - unit is masked - failed to start the unit")
assert.PanicsWithError(t, errMsg, func() { s.ensureISCSIDaemonStarted() })
}
func TestGetLocalMAC(t *testing.T) {
orderedIfs := []net.Interface{
{
Index: 1,
MTU: 65536,
Name: "lo",
HardwareAddr: nil,
Flags: 0x25,
},
{
Index: 2,
MTU: 1500,
Name: "ens192",
HardwareAddr: net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5},
Flags: 0x33,
},
{
Index: 5,
MTU: 1450,
Name: "vxlan.calico",
HardwareAddr: net.HardwareAddr{0x6, 0x7, 0x8, 0x9, 0xa, 0xb},
Flags: 0x33,
},
{
Index: 8,
MTU: 1450,
Name: "cali1d87cc7ab3f",
HardwareAddr: net.HardwareAddr{0xee, 0xee, 0xee, 0xee, 0xee, 0xee},
Flags: 0x33,
},
{
Index: 13,
MTU: 1450,
Name: "cali06df89a6f82",
HardwareAddr: net.HardwareAddr{0xee, 0xee, 0xee, 0xee, 0xee, 0xee},
Flags: 0x33,
},
}
unorderedIfs := []net.Interface{
{
Index: 257,
MTU: 1450,
Name: "cali24aa7dc293b",
HardwareAddr: net.HardwareAddr{0xee, 0xee, 0xee, 0xee, 0xee, 0xee},
Flags: 0x33,
},
{
Index: 1,
MTU: 65536,
Name: "lo",
HardwareAddr: nil,
Flags: 0x25,
},
{
Index: 2,
MTU: 1500,
Name: "ens192",
HardwareAddr: net.HardwareAddr{0x10, 0x11, 0x12, 0x13, 0x14, 0x15},
Flags: 0x33,
},
{
Index: 259,
MTU: 1450,
Name: "cali1d87cc7ab3f",
HardwareAddr: net.HardwareAddr{0xee, 0xee, 0xee, 0xee, 0xee, 0xee},
Flags: 0x33,
},
{
Index: 7,
MTU: 1450,
Name: "vxlan.calico",
HardwareAddr: net.HardwareAddr{0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b},
Flags: 0x33,
},
{
Index: 11,
MTU: 1450,
Name: "calibbe3ea81e70",
HardwareAddr: net.HardwareAddr{0xee, 0xee, 0xee, 0xee, 0xee, 0xee},
Flags: 0x33,
},
}
onlyLoIfs := []net.Interface{
{
Index: 1,
MTU: 65536,
Name: "lo",
HardwareAddr: nil,
Flags: 0x25,
},
}
tests := []struct {
expected string
expectErr bool
ifaceFunc func() ([]net.Interface, error)
ifaceExcludeFilter *regexp.Regexp
testName string
}{
{
testName: "basic ordered IFs test",
expectErr: false,
expected: "00:01:02:03:04:05",
ifaceFunc: func() ([]net.Interface, error) {
return orderedIfs, nil
},
ifaceExcludeFilter: nil,
},
{
testName: "basic unordered IFs test",
expectErr: false,
expected: "ee:ee:ee:ee:ee:ee",
ifaceFunc: func() ([]net.Interface, error) {
return unorderedIfs, nil
},
ifaceExcludeFilter: nil,
},
{
testName: "expected error from only lo",
expectErr: true,
ifaceFunc: func() ([]net.Interface, error) {
return onlyLoIfs, nil
},
ifaceExcludeFilter: nil,
},
{
testName: "expected error from error in ifaceFunc",
expectErr: true,
ifaceFunc: func() ([]net.Interface, error) {
return []net.Interface{}, errors.New("kaboom")
},
ifaceExcludeFilter: nil,
},
{
testName: "exclude cali interfaces",
expectErr: false,
expected: "10:11:12:13:14:15",
ifaceFunc: func() ([]net.Interface, error) {
return unorderedIfs, nil
},
ifaceExcludeFilter: regexp.MustCompile("^cali.+"),
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
returnedIf, err := getLocalMAC(tt.ifaceFunc, tt.ifaceExcludeFilter)
if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expected, returnedIf)
}
})
}
}