-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathiscsi.go
More file actions
2563 lines (2182 loc) · 85.1 KB
/
Copy pathiscsi.go
File metadata and controls
2563 lines (2182 loc) · 85.1 KB
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 NetApp, Inc. All Rights Reserved.
package utils
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/cenkalti/backoff/v4"
. "github.com/netapp/trident/logging"
"github.com/netapp/trident/utils/errors"
)
const (
iSCSIErrNoObjsFound = 21
ISCSIErrLoginAuthFailed = 24
multipathDeviceDiscoveryTimeoutSecs = 90
temporaryMountDir = "/tmp_mnt"
volumeMountDir = "/vol_mnt"
unknownFstype = "<unknown>"
iscsiadmLoginTimeoutValue = 10
iscsiadmLoginTimeout = iscsiadmLoginTimeoutValue * time.Second
iscsiadmLoginRetryMax = "1"
iSCSISessionStateLoggedIn = "LOGGED_IN"
iSCSIMaxFlushWaitDuration = 6 * time.Minute
SessionInfoSource = "sessionSource"
SessionSourceNodeStage = "nodeStage"
SessionSourceTrackingInfo = "trackingInfo"
SessionSourceCurrentStatus = "currentStatus"
)
var (
// Exclusion list contains keywords if found in any Target IQN should not be considered for
// self-healing.
// solidfire: Exclude solidfire for now. Solidfire maintains a different handle 'Current Portal'
// which is not published or captured in VolumePublishInfo, current self-healing logic does not
// work for logout, login or scan as it is designed to work with published portal information.
iSCSISelfHealingExclusion = []string{"solidfire"}
IscsiUtils = NewIscsiReconcileUtils()
// Non-persistent map to maintain flush delays/errors if any, for device path(s).
iSCSIVolumeFlushExceptions = make(map[string]time.Time)
)
// AttachISCSIVolumeRetry attaches a volume with retry by invoking AttachISCSIVolume with backoff.
func AttachISCSIVolumeRetry(
ctx context.Context, name, mountpoint string, publishInfo *VolumePublishInfo, secrets map[string]string, timeout time.Duration,
) (int64, error) {
Logc(ctx).Debug(">>>> iscsi.AttachISCSIVolumeRetry")
defer Logc(ctx).Debug("<<<< iscsi.AttachISCSIVolumeRetry")
var err error
var mpathSize int64
if err = ISCSIPreChecks(ctx); err != nil {
return mpathSize, err
}
checkAttachISCSIVolume := func() error {
mpathSize, err = AttachISCSIVolume(ctx, name, mountpoint, publishInfo, secrets)
return err
}
attachNotify := func(err error, duration time.Duration) {
Logc(ctx).WithFields(LogFields{
"increment": duration,
"error": err,
}).Debug("Attach iSCSI volume is not complete, waiting.")
}
attachBackoff := backoff.NewExponentialBackOff()
attachBackoff.InitialInterval = 1 * time.Second
attachBackoff.Multiplier = 1.414 // approx sqrt(2)
attachBackoff.RandomizationFactor = 0.1
attachBackoff.MaxElapsedTime = timeout
err = backoff.RetryNotify(checkAttachISCSIVolume, attachBackoff, attachNotify)
return mpathSize, err
}
// AttachISCSIVolume attaches the volume to the local host.
// This method must be able to accomplish its task using only the publish information passed in.
// It may be assumed that this method always runs on the host to which the volume will be attached.
// If the mountpoint parameter is specified, the volume will be mounted to it.
// The device path is set on the in-out publishInfo parameter so that it may be mounted later instead.
// If multipath device size is found to be inconsistent with device size, then the correct size is returned.
func AttachISCSIVolume(ctx context.Context, name, mountpoint string, publishInfo *VolumePublishInfo,
secrets map[string]string,
) (int64, error) {
Logc(ctx).Debug(">>>> iscsi.AttachISCSIVolume")
defer Logc(ctx).Debug("<<<< iscsi.AttachISCSIVolume")
var err error
var mpathSize int64
lunID := int(publishInfo.IscsiLunNumber)
var portals []string
// IscsiTargetPortal is one of the ports on the target and IscsiPortals
// are rest of the target ports for establishing iSCSI session.
// If the target has multiple portals, then there will be multiple iSCSI sessions.
portals = append(portals, ensureHostportFormatted(publishInfo.IscsiTargetPortal))
for _, p := range publishInfo.IscsiPortals {
portals = append(portals, ensureHostportFormatted(p))
}
if publishInfo.IscsiInterface == "" {
publishInfo.IscsiInterface = "default"
}
Logc(ctx).WithFields(LogFields{
"volume": name,
"mountpoint": mountpoint,
"lunID": lunID,
"portals": portals,
"targetIQN": publishInfo.IscsiTargetIQN,
"iscsiInterface": publishInfo.IscsiInterface,
"fstype": publishInfo.FilesystemType,
}).Debug("Attaching iSCSI volume.")
if err = ISCSIPreChecks(ctx); err != nil {
return mpathSize, err
}
// Ensure we are logged into correct portals
pendingPortalsToLogin, loggedIn, err := portalsToLogin(ctx, publishInfo.IscsiTargetIQN, portals)
if err != nil {
return mpathSize, err
}
newLogin, err := EnsureISCSISessions(ctx, publishInfo, pendingPortalsToLogin)
if !loggedIn && !newLogin {
return mpathSize, err
}
// First attempt to fix invalid serials by rescanning them
err = handleInvalidSerials(ctx, lunID, publishInfo.IscsiTargetIQN, publishInfo.IscsiLunSerial, rescanOneLun)
if err != nil {
return mpathSize, err
}
// Then attempt to fix invalid serials by purging them (to be scanned
// again later)
err = handleInvalidSerials(ctx, lunID, publishInfo.IscsiTargetIQN, publishInfo.IscsiLunSerial, purgeOneLun)
if err != nil {
return mpathSize, err
}
// Scan the target and wait for the device(s) to appear
err = waitForDeviceScan(ctx, lunID, publishInfo.IscsiTargetIQN)
if err != nil {
Logc(ctx).Errorf("Could not find iSCSI device: %+v", err)
return mpathSize, err
}
// At this point if the serials are still invalid, give up so the
// caller can retry (invoking the remediation steps above in the
// process, if they haven't already been run).
failHandler := func(ctx context.Context, path string) error {
Logc(ctx).Error("Detected LUN serial number mismatch, attaching volume would risk data corruption, giving up")
return fmt.Errorf("LUN serial number mismatch, kernel has stale cached data")
}
err = handleInvalidSerials(ctx, lunID, publishInfo.IscsiTargetIQN, publishInfo.IscsiLunSerial, failHandler)
if err != nil {
return mpathSize, err
}
// Wait for multipath device i.e. /dev/dm-* for the given LUN
err = waitForMultipathDeviceForLUN(ctx, lunID, publishInfo.IscsiTargetIQN)
if err != nil {
return mpathSize, err
}
// Lookup all the SCSI device information
deviceInfo, err := getDeviceInfoForLUN(ctx, lunID, publishInfo.IscsiTargetIQN, false, false)
if err != nil {
return mpathSize, fmt.Errorf("error getting iSCSI device information: %v", err)
} else if deviceInfo == nil {
return mpathSize, fmt.Errorf("could not get iSCSI device information for LUN %d", lunID)
}
Logc(ctx).WithFields(LogFields{
"scsiLun": deviceInfo.LUN,
"multipathDevice": deviceInfo.MultipathDevice,
"devices": deviceInfo.Devices,
"iqn": deviceInfo.IQN,
}).Debug("Found device.")
// Make sure we use the proper device
deviceToUse := deviceInfo.Devices[0]
if deviceInfo.MultipathDevice != "" {
deviceToUse = deviceInfo.MultipathDevice
// To avoid LUN ID conflict with a ghost device below checks
// are necessary:
// Conflict 1: Due to race conditons, it is possible a ghost
// DM device is discovered instead of the actual
// DM device.
// Conflict 2: Some OS like RHEL displays the ghost device size
// instead of the actual LUN size.
//
// Below check ensures that the correct device with the correct
// size is being discovered.
// If LUN Serial Number exists, then compare it with DM
// device's UUID in sysfs
if err = verifyMultipathDeviceSerial(ctx, deviceToUse, publishInfo.IscsiLunSerial); err != nil {
return mpathSize, err
}
// Once the multipath device has been found, compare its size with
// the size of one of the devices, if it differs then mark it for
// resize after the staging.
correctMpathSize, mpathSizeCorrect, err := verifyMultipathDeviceSize(ctx, deviceToUse, deviceInfo.Devices[0])
if err != nil {
Logc(ctx).WithFields(LogFields{
"scsiLun": deviceInfo.LUN,
"multipathDevice": deviceInfo.MultipathDevice,
"device": deviceInfo.Devices[0],
"iqn": deviceInfo.IQN,
"err": err,
}).Error("Failed to verify multipath device size.")
return mpathSize, fmt.Errorf("failed to verify multipath device %s size", deviceInfo.MultipathDevice)
}
if !mpathSizeCorrect {
mpathSize = correctMpathSize
Logc(ctx).WithFields(LogFields{
"scsiLun": deviceInfo.LUN,
"multipathDevice": deviceInfo.MultipathDevice,
"device": deviceInfo.Devices[0],
"iqn": deviceInfo.IQN,
"mpathSize": mpathSize,
}).Error("Multipath device size does not match device size.")
}
} else {
return mpathSize, fmt.Errorf("could not find multipath device for LUN %d", lunID)
}
if deviceToUse == "" {
return mpathSize, fmt.Errorf("could not determine device to use for %v", name)
}
devicePath := "/dev/" + deviceToUse
if err := waitForDevice(ctx, devicePath); err != nil {
return mpathSize, fmt.Errorf("could not find device %v; %s", devicePath, err)
}
var isLUKSDevice, luksFormatted bool
if publishInfo.LUKSEncryption != "" {
isLUKSDevice, err = strconv.ParseBool(publishInfo.LUKSEncryption)
if err != nil {
return mpathSize, fmt.Errorf("could not parse LUKSEncryption into a bool, got %v",
publishInfo.LUKSEncryption)
}
}
if isLUKSDevice {
luksDevice, _ := NewLUKSDevice(devicePath, name)
luksFormatted, err = EnsureLUKSDeviceMappedOnHost(ctx, luksDevice, name, secrets)
if err != nil {
return mpathSize, err
}
devicePath = luksDevice.MappedDevicePath()
}
// Return the device in the publish info in case the mount will be done later
publishInfo.DevicePath = devicePath
if publishInfo.FilesystemType == fsRaw {
return mpathSize, nil
}
existingFstype, err := getDeviceFSType(ctx, devicePath)
if err != nil {
return mpathSize, err
}
if existingFstype == "" {
if !isLUKSDevice {
if unformatted, err := isDeviceUnformatted(ctx, devicePath); err != nil {
Logc(ctx).WithField("device",
devicePath).Errorf("Unable to identify if the device is unformatted; err: %v", err)
return mpathSize, err
} else if !unformatted {
Logc(ctx).WithField("device", devicePath).Errorf("Device is not unformatted; err: %v", err)
return mpathSize, fmt.Errorf("device %v is not unformatted", devicePath)
}
} else {
// We can safely assume if we just luksFormatted the device, we can also add a filesystem without dataloss
if !luksFormatted {
Logc(ctx).WithField("device",
devicePath).Errorf("Unable to identify if the luks device is empty; err: %v", err)
return mpathSize, err
}
}
Logc(ctx).WithFields(LogFields{"volume": name, "fstype": publishInfo.FilesystemType}).Debug("Formatting LUN.")
err := formatVolume(ctx, devicePath, publishInfo.FilesystemType)
if err != nil {
return mpathSize, fmt.Errorf("error formatting LUN %s, device %s: %v", name, deviceToUse, err)
}
} else if existingFstype != unknownFstype && existingFstype != publishInfo.FilesystemType {
Logc(ctx).WithFields(LogFields{
"volume": name,
"existingFstype": existingFstype,
"requestedFstype": publishInfo.FilesystemType,
}).Error("LUN already formatted with a different file system type.")
return mpathSize, fmt.Errorf("LUN %s, device %s already formatted with other filesystem: %s",
name, deviceToUse, existingFstype)
} else {
Logc(ctx).WithFields(LogFields{
"volume": name,
"fstype": deviceInfo.Filesystem,
}).Debug("LUN already formatted.")
}
// Attempt to resolve any filesystem inconsistencies that might be due to dirty node shutdowns, cloning
// in-use volumes, or creating volumes from snapshots taken from in-use volumes. This is only safe to do
// if a device is not mounted. The fsck command returns a non-zero exit code if filesystem errors are found,
// even if they are completely and automatically fixed, so we don't return any error here.
mounted, err := IsMounted(ctx, devicePath, "", "")
if err != nil {
return mpathSize, err
}
if !mounted {
err = repairVolume(ctx, devicePath, publishInfo.FilesystemType)
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
logFields := LogFields{
"volume": name,
"fstype": deviceInfo.Filesystem,
"device": devicePath,
}
if exitErr.ExitCode() == 1 {
Logc(ctx).WithFields(logFields).Info("Fixed filesystem errors")
} else {
logFields["exitCode"] = exitErr.ExitCode()
Logc(ctx).WithError(err).WithFields(logFields).Error("Failed to repair filesystem errors.")
}
}
}
}
// Optionally mount the device
if mountpoint != "" {
if err := MountDevice(ctx, devicePath, mountpoint, publishInfo.MountOptions, false); err != nil {
return mpathSize, fmt.Errorf("error mounting LUN %v, device %v, mountpoint %v; %s",
name, deviceToUse, mountpoint, err)
}
}
return mpathSize, nil
}
// GetInitiatorIqns returns parsed contents of /etc/iscsi/initiatorname.iscsi
func GetInitiatorIqns(ctx context.Context) ([]string, error) {
Logc(ctx).Debug(">>>> iscsi.GetInitiatorIqns")
defer Logc(ctx).Debug("<<<< iscsi.GetInitiatorIqns")
out, err := command.Execute(ctx, "cat", "/etc/iscsi/initiatorname.iscsi")
if err != nil {
Logc(ctx).WithField("Error", err).Warn("Could not read initiatorname.iscsi; perhaps iSCSI is not installed?")
return nil, err
}
return parseInitiatorIQNs(ctx, string(out)), nil
}
// parseInitiatorIQNs accepts the contents of /etc/iscsi/initiatorname.iscsi and returns the IQN(s).
func parseInitiatorIQNs(ctx context.Context, contents string) []string {
iqns := make([]string, 0)
lines := strings.Split(contents, "\n")
for _, line := range lines {
match := iqnRegex.FindStringSubmatch(line)
if match == nil {
continue
}
paramsMap := make(map[string]string)
for i, name := range iqnRegex.SubexpNames() {
if i > 0 && i <= len(match) {
paramsMap[name] = match[i]
}
}
if iqn, ok := paramsMap["iqn"]; ok {
iqns = append(iqns, iqn)
}
}
return iqns
}
// GetSysfsBlockDirsForLUN returns the list of directories in sysfs where the block devices should appear
// after the scan is successful. One directory is returned for each path in the host session map.
func (h *IscsiReconcileHelper) GetSysfsBlockDirsForLUN(lunID int, hostSessionMap map[int]int) []string {
paths := make([]string, 0)
for hostNumber, sessionNumber := range hostSessionMap {
p := fmt.Sprintf(
chrootPathPrefix+"/sys/class/scsi_host/host%d/device/session%d/iscsi_session/session%d/device/target%d:0:0/%d:0:0:%d",
hostNumber, sessionNumber, sessionNumber, hostNumber, hostNumber, lunID)
paths = append(paths, p)
}
return paths
}
// GetDevicesForLUN find the /dev/sd* device names for an iSCSI LUN.
func (h *IscsiReconcileHelper) GetDevicesForLUN(paths []string) ([]string, error) {
devices := make([]string, 0)
for _, p := range paths {
dirname := p + "/block"
exists, err := PathExists(dirname)
if !exists || err != nil {
continue
}
dirFd, err := os.Open(dirname)
if err != nil {
return nil, err
}
list, err := dirFd.Readdir(1)
dirFd.Close()
if err != nil {
return nil, err
}
if 0 == len(list) {
continue
}
devices = append(devices, list[0].Name())
}
return devices, nil
}
// GetMultipathDeviceUUID find the /sys/block/dmX/dm/uuid UUID that contains DM device serial in hex format.
func (h *IscsiReconcileHelper) GetMultipathDeviceUUID(multipathDevicePath string) (string, error) {
multipathDevice := strings.TrimPrefix(multipathDevicePath, "/dev/")
deviceUUIDPath := chrootPathPrefix + fmt.Sprintf("/sys/block/%s/dm/uuid", multipathDevice)
exists, err := PathExists(deviceUUIDPath)
if !exists || err != nil {
return "", errors.NotFoundError("multipath device '%s' UUID not found", multipathDevice)
}
UUID, err := os.ReadFile(deviceUUIDPath)
if err != nil {
return "", err
}
return string(UUID), nil
}
// GetMultipathDeviceDisks find the /sys/block/dmX/slaves/sdX disks.
func (h *IscsiReconcileHelper) GetMultipathDeviceDisks(ctx context.Context, multipathDevicePath string) ([]string,
error,
) {
devices := make([]string, 0)
multipathDevice := strings.TrimPrefix(multipathDevicePath, "/dev/")
diskPath := chrootPathPrefix + fmt.Sprintf("/sys/block/%s/slaves/", multipathDevice)
diskDirs, err := os.ReadDir(diskPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
Logc(ctx).Warningf("multipath device directory %s does not exist, device is already gone?", diskDirs)
return nil, nil
}
Logc(ctx).WithError(err).Errorf("Could not read %s", diskPath)
return nil, fmt.Errorf("failed to identify multipath device disks; unable to read %q :%w", diskPath, err)
}
for _, diskDir := range diskDirs {
contentName := diskDir.Name()
if !strings.HasPrefix(contentName, "sd") {
continue
}
devices = append(devices, contentName)
}
return devices, nil
}
// GetMultipathDeviceBySerial find DM device whose UUID /sys/block/dmX/dm/uuid contains serial in hex format.
func (h *IscsiReconcileHelper) GetMultipathDeviceBySerial(ctx context.Context, hexSerial string) (string, error) {
var (
sysPath = chrootPathPrefix + "/sys/block/"
multipathCMDTimeout = 10 * time.Second
)
blockDirs, err := os.ReadDir(sysPath)
if err != nil {
Logc(ctx).WithError(err).Errorf("Could not read %s", sysPath)
return "", fmt.Errorf("failed to find multipath device by serial; unable to read '%s'", sysPath)
}
for _, blockDir := range blockDirs {
dmDeviceName := blockDir.Name()
if !strings.HasPrefix(dmDeviceName, "dm-") {
continue
}
uuid, err := h.GetMultipathDeviceUUID(dmDeviceName)
if err != nil {
Logc(ctx).WithFields(LogFields{
"UUID": hexSerial,
"multipathDevice": dmDeviceName,
"err": err,
}).Error("Failed to get UUID of multipath device.")
continue
}
if !strings.Contains(uuid, hexSerial) {
continue
}
// Use 'multipath -l' and check the exit code. A success return
// indicates that it is a not a stale device. Noted that frequently
// running this in a busy environment may time out, and lead to a
// situation that the device is not properly discovered. But it will
// fail the following operations and retries next time.
if _, err := command.ExecuteWithTimeout(ctx, "multipath", multipathCMDTimeout, true, "-l", dmDeviceName); err != nil {
Logc(ctx).WithFields(LogFields{
"device": dmDeviceName,
}).WithError(err).Warn("Candidate is not a valid map known to multipathd, ignoring stale entry.")
continue
}
Logc(ctx).WithFields(LogFields{
"UUID": hexSerial,
"multipathDevice": dmDeviceName,
}).Debug("Found multipath device by UUID.")
return dmDeviceName, nil
}
return "", errors.NotFoundError("no multipath device found")
}
// GetMultipathDeviceForLUN is the most robust method to find a multipath device.
// It uses a three-factor check (serial, path liveness, LUN ID) to ensure the
// correct and active device is returned, filtering out any stale entries.
func (h *IscsiReconcileHelper) GetMultipathDeviceForLUN(ctx context.Context, hexSerial string, lunID int) (string, error) {
var (
sysPath = chrootPathPrefix + "/sys/block/"
lunIDString = strconv.Itoa(lunID)
fields = LogFields{
"lunID": lunID,
"lunSerial": hexSerial,
}
)
Logc(ctx).WithFields(fields).Debug(">>>> iscsi.GetMultipathDeviceForLUN")
defer Logc(ctx).WithFields(fields).Debug("<<<< iscsi.GetMultipathDeviceForLUN")
blockDirs, err := os.ReadDir(sysPath)
if err != nil {
Logc(ctx).WithError(err).WithFields(fields).Errorf("Could not read %s", sysPath)
return "", fmt.Errorf("failed to list block devices in %q", sysPath)
}
for _, blockDir := range blockDirs {
dmDeviceName := blockDir.Name()
if !strings.HasPrefix(dmDeviceName, "dm-") {
continue
}
// Check for a WWID match.
uuid, err := h.GetMultipathDeviceUUID(dmDeviceName)
if err != nil || !strings.Contains(uuid, hexSerial) {
// Not a match, or not a multipath device.
continue
}
// Perform checks whether it's a stale device by checking slaves.
Logc(ctx).WithFields(LogFields{
"serial": hexSerial,
"candidate": dmDeviceName,
"uuid": uuid,
}).Debug("Found candidate multipath device")
// A stale device should contain no slaves.
slavesPath := filepath.Join(sysPath, dmDeviceName, "slaves")
slaves, err := os.ReadDir(slavesPath)
if err != nil || len(slaves) == 0 {
Logc(ctx).WithFields(fields).Warnf("Candidate %s is a stale device with no paths, ignoring.", dmDeviceName)
continue
}
// Verify the LUN ID on an actual path using the 1st slave device info.
scsiDevicePath := filepath.Join(slavesPath, slaves[0].Name(), "device", "scsi_device")
scsiDeviceDirs, err := os.ReadDir(scsiDevicePath)
if err != nil || len(scsiDeviceDirs) == 0 {
Logc(ctx).WithFields(fields).WithError(err).Warnf("Could not read scsi_device %q info for candidate path %s.", scsiDevicePath, dmDeviceName)
continue
}
scsiDeviceAddress := scsiDeviceDirs[0].Name()
parts := strings.Split(scsiDeviceAddress, ":")
if len(parts) != 4 {
Logc(ctx).WithFields(fields).Warnf("Invalid SCSI device address %s.", scsiDeviceAddress)
continue
}
currentLunID := parts[3]
if currentLunID == lunIDString {
// All lun ID and serial match the multipath device.
Logc(ctx).WithFields(fields).Debugf("Successfully identified and verified multipath device %s.", dmDeviceName)
return dmDeviceName, nil
}
}
return "", errors.NotFoundError(fmt.Sprintf("no active multipath device found for serial %s and LUN ID %d", hexSerial, lunID))
}
// waitForDeviceScan scans all paths to a specific LUN and waits until all
// SCSI disk-by-path devices for that LUN are present on the host.
func waitForDeviceScan(ctx context.Context, lunID int, iSCSINodeName string) error {
fields := LogFields{
"lunID": lunID,
"iSCSINodeName": iSCSINodeName,
}
Logc(ctx).WithFields(fields).Debug(">>>> iscsi.waitForDeviceScan")
defer Logc(ctx).WithFields(fields).Debug("<<<< iscsi.waitForDeviceScan")
hostSessionMap := IscsiUtils.GetISCSIHostSessionMapForTarget(ctx, iSCSINodeName)
if len(hostSessionMap) == 0 {
return fmt.Errorf("no iSCSI hosts found for target %s", iSCSINodeName)
}
Logc(ctx).WithField("hostSessionMap", hostSessionMap).Debug("Built iSCSI host/session map.")
hosts := make([]int, 0)
for hostNumber := range hostSessionMap {
hosts = append(hosts, hostNumber)
}
if err := iSCSIScanTargetLUN(ctx, lunID, hosts); err != nil {
Logc(ctx).WithField("scanError", err).Error("Could not scan for new LUN.")
}
paths := IscsiUtils.GetSysfsBlockDirsForLUN(lunID, hostSessionMap)
Logc(ctx).Debugf("Scanning paths: %v", paths)
found := make([]string, 0)
allDevicesExist := true
// Check if all paths present, and return nil (success) if so
for _, p := range paths {
dirname := p + "/block"
exists, err := PathExists(dirname)
if !exists || err != nil {
// Set flag to false as device is missing
allDevicesExist = false
} else {
found = append(found, dirname)
Logc(ctx).Debugf("Paths found: %v", dirname)
}
}
if len(found) == 0 {
Logc(ctx).Warnf("Could not find any devices ")
// log info about current status of host when no devices are found
if _, err := command.Execute(ctx, "ls", "-al", "/dev"); err != nil {
Logc(ctx).Warnf("Could not run ls -al /dev: %v", err)
}
if _, err := command.Execute(ctx, "ls", "-al", devMapperRoot); err != nil {
Logc(ctx).Warnf("Could not run ls -al %s: %v", devMapperRoot, err)
}
if _, err := command.Execute(ctx, "ls", "-al", "/dev/disk/by-path"); err != nil {
Logc(ctx).Warnf("Could not run ls -al /dev/disk/by-path: %v", err)
}
if _, err := command.Execute(ctx, "lsscsi"); err != nil {
Logc(ctx).Warnf("Could not run lsscsi: %v", err)
}
if _, err := command.Execute(ctx, "lsscsi", "-t"); err != nil {
Logc(ctx).Warnf("Could not run lsscsi -t: %v", err)
}
if _, err := command.Execute(ctx, "free"); err != nil {
Logc(ctx).Warnf("Could not run free: %v", err)
}
return errors.New("no devices present yet")
}
if allDevicesExist {
// We have found all devices.
Logc(ctx).Debugf("All Paths found: %v", found)
} else {
// We have found some devices but not all.
Logc(ctx).Debugf("Some Paths found: %v", found)
}
return nil
}
// ISCSISupported returns true if iscsiadm is installed and in the PATH.
func ISCSISupported(ctx context.Context) bool {
Logc(ctx).Debug(">>>> iscsi.ISCSISupported")
defer Logc(ctx).Debug("<<<< iscsi.ISCSISupported")
// run the iscsiadm command to show version to check if iscsiadm is installed
_, err := execIscsiadmCommand(ctx, "-V")
if err != nil {
Logc(ctx).Debug("iscsiadm tools not found on this host.")
return false
}
return true
}
// ISCSIDiscoveryInfo contains information about discovered iSCSI targets.
type ISCSIDiscoveryInfo struct {
Portal string
PortalIP string
TargetName string
}
// iSCSIDiscovery uses the 'iscsiadm' command to perform discovery.
func iSCSIDiscovery(ctx context.Context, portal string) ([]ISCSIDiscoveryInfo, error) {
Logc(ctx).WithField("portal", portal).Debug(">>>> iscsi.iSCSIDiscovery")
defer Logc(ctx).Debug("<<<< iscsi.iSCSIDiscovery")
out, err := execIscsiadmCommand(ctx, "-m", "discovery", "-t", "sendtargets", "-p", portal)
if err != nil {
return nil, err
}
/*
iscsiadm -m discovery -t st -p 10.63.152.249:3260
10.63.152.249:3260,1 iqn.1992-08.com.netapp:2752.600a0980006074c20000000056b32c4d
10.63.152.250:3260,2 iqn.1992-08.com.netapp:2752.600a0980006074c20000000056b32c4d
a[0]==10.63.152.249:3260,1
a[1]==iqn.1992-08.com.netapp:2752.600a0980006074c20000000056b32c4d
For IPv6
[fd20:8b1e:b258:2000:f816:3eff:feec:2]:3260,1038 iqn.1992-08.com.netapp:sn.7894d7af053711ea88b100a0b886136a
a[0]==[fd20:8b1e:b258:2000:f816:3eff:feec:2]:3260,1038
a[1]==iqn.1992-08.com.netapp:sn.7894d7af053711ea88b100a0b886136a
*/
var discoveryInfo []ISCSIDiscoveryInfo
lines := strings.Split(string(out), "\n")
for _, l := range lines {
a := strings.Fields(l)
if len(a) >= 2 {
portalIP := ""
if IPv6Check(a[0]) {
// This is an IPv6 address
portalIP = strings.Split(a[0], "]")[0]
portalIP += "]"
} else {
portalIP = strings.Split(a[0], ":")[0]
}
discoveryInfo = append(discoveryInfo, ISCSIDiscoveryInfo{
Portal: a[0],
PortalIP: portalIP,
TargetName: a[1],
})
Logc(ctx).WithFields(LogFields{
"Portal": a[0],
"PortalIP": portalIP,
"TargetName": a[1],
}).Debug("Adding iSCSI discovery info.")
}
}
return discoveryInfo, nil
}
// ISCSISessionInfo contains information about iSCSI sessions.
type ISCSISessionInfo struct {
SID string
Portal string
PortalIP string
TargetName string
}
// getISCSISessionInfo parses output from 'iscsiadm -m session' and returns the parsed output.
func getISCSISessionInfo(ctx context.Context) ([]ISCSISessionInfo, error) {
Logc(ctx).Debug(">>>> iscsi.getISCSISessionInfo")
defer Logc(ctx).Debug("<<<< iscsi.getISCSISessionInfo")
out, err := execIscsiadmCommand(ctx, "-m", "session")
if err != nil {
exitErr, ok := err.(*exec.ExitError)
if ok && exitErr.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() == iSCSIErrNoObjsFound {
Logc(ctx).Debug("No iSCSI session found.")
return []ISCSISessionInfo{}, nil
} else {
Logc(ctx).WithField("error", err).Error("Problem checking iSCSI sessions.")
return nil, err
}
}
/*
# iscsiadm -m session
tcp: [3] 10.0.207.7:3260,1028 iqn.1992-08.com.netapp:sn.afbb1784f77411e582f8080027e22798:vs.3 (non-flash)
tcp: [4] 10.0.207.9:3260,1029 iqn.1992-08.com.netapp:sn.afbb1784f77411e582f8080027e22798:vs.3 (non-flash)
a[0]==tcp:
a[1]==[4]
a[2]==10.0.207.9:3260,1029
a[3]==iqn.1992-08.com.netapp:sn.afbb1784f77411e582f8080027e22798:vs.3
a[4]==(non-flash)
*/
var sessionInfo []ISCSISessionInfo
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
for _, l := range lines {
a := strings.Fields(l)
if len(a) > 3 {
sid := a[1]
sid = sid[1 : len(sid)-1]
portalIP := ""
if IPv6Check(a[2]) {
// This is an IPv6 address
portalIP = strings.Split(a[2], "]")[0]
portalIP += "]"
} else {
portalIP = strings.Split(a[2], ":")[0]
}
sessionInfo = append(sessionInfo, ISCSISessionInfo{
SID: sid,
Portal: a[2],
PortalIP: portalIP,
TargetName: a[3],
})
Logc(ctx).WithFields(LogFields{
"SID": sid,
"Portal": a[2],
"PortalIP": portalIP,
"TargetName": a[3],
}).Debug("Adding iSCSI session info.")
}
}
return sessionInfo, nil
}
// ISCSILogout logs out from the supplied target
func ISCSILogout(ctx context.Context, targetIQN, targetPortal string) error {
logFields := LogFields{
"targetIQN": targetIQN,
"targetPortal": targetPortal,
}
Logc(ctx).WithFields(logFields).Debug(">>>> iscsi.ISCSILogout")
defer Logc(ctx).WithFields(logFields).Debug("<<<< iscsi.ISCSILogout")
defer listAllISCSIDevices(ctx)
if _, err := execIscsiadmCommand(ctx, "-m", "node", "-T", targetIQN, "--portal", targetPortal, "-u"); err != nil {
Logc(ctx).WithField("error", err).Debug("Error during iSCSI logout.")
}
// We used to delete the iscsi "node" at this point but that could interfere with
// another iSCSI client (such as kubelet with and "iscsi" PV) attempting to use
// the same node.
listAllISCSIDevices(ctx)
return nil
}
// iSCSISessionExists checks to see if a session exists to the specified portal.
func iSCSISessionExists(ctx context.Context, portal string) (bool, error) {
Logc(ctx).Debug(">>>> iscsi.iSCSISessionExists")
defer Logc(ctx).Debug("<<<< iscsi.iSCSISessionExists")
sessionInfo, err := getISCSISessionInfo(ctx)
if err != nil {
Logc(ctx).WithField("error", err).Error("Problem checking iSCSI sessions.")
return false, err
}
for _, e := range sessionInfo {
if strings.Contains(e.PortalIP, portal) {
return true, nil
}
}
return false, nil
}
// iSCSISessionExistsToTargetIQN checks to see if a session exists to the specified target.
func iSCSISessionExistsToTargetIQN(ctx context.Context, targetIQN string) (bool, error) {
Logc(ctx).Debug(">>>> iscsi.iSCSISessionExistsToTargetIQN")
defer Logc(ctx).Debug("<<<< iscsi.iSCSISessionExistsToTargetIQN")
sessionInfo, err := getISCSISessionInfo(ctx)
if err != nil {
Logc(ctx).WithField("error", err).Error("Problem checking iSCSI sessions.")
return false, err
}
for _, e := range sessionInfo {
if e.TargetName == targetIQN {
return true, nil
}
}
return false, nil
}
// portalsToLogin checks to see if session to for all the specified portals exist for the specified
// target. If a session does not exist for a give portal it is added to list of portals that Trident
// needs to login to.
func portalsToLogin(ctx context.Context, targetIQN string, portals []string) ([]string, bool, error) {
logFields := LogFields{
"targetIQN": targetIQN,
"portals": portals,
}
Logc(ctx).WithFields(logFields).Debug(">>>> iscsi.portalsToLogin")
defer Logc(ctx).Debug("<<<< iscsi.portalsToLogin")
portalsInStaleState := make([]string, 0)
portalsNotLoggedIn := make([]string, len(portals))
copy(portalsNotLoggedIn, portals)
sessionInfo, err := getISCSISessionInfo(ctx)
if err != nil {
Logc(ctx).WithField("error", err).Error("Problem checking iSCSI sessions.")
return portalsNotLoggedIn, false, err
}
for _, e := range sessionInfo {
if e.TargetName == targetIQN {
// Portals (portalsNotLoggedIn) may/may not contain anything after ":", so instead of matching complete
// portal value (with e.Portal), check if e.Portal's IP address matches portal's IP address
matchFunc := func(main, val string) bool {
mainIpAddress := parseHostportIP(main)
valIpAddress := parseHostportIP(val)
return mainIpAddress == valIpAddress
}
lenBeforeCheck := len(portalsNotLoggedIn)
portalsNotLoggedIn = RemoveStringFromSliceConditionally(portalsNotLoggedIn, e.Portal, matchFunc)
lenAfterCheck := len(portalsNotLoggedIn)
// If the portal is logged in ensure it is not stale
if lenBeforeCheck != lenAfterCheck {
if IsISCSISessionStale(ctx, e.SID) {
portalsInStaleState = append(portalsInStaleState, e.Portal)
}
}
}
}
if len(portals) == len(portalsInStaleState) {
return nil, false, fmt.Errorf("no new session to establish and existing session(s) might be in unhealthy state")
}
loggedIn := len(portals) != (len(portalsNotLoggedIn) + len(portalsInStaleState))
return portalsNotLoggedIn, loggedIn, nil
}
// formatPortal returns the iSCSI portal string, appending a port number if one isn't
// already present, and also appending a target portal group tag if one is not present
func formatPortal(portal string) string {
if portalPortPattern.MatchString(portal) {
return portal
} else {
return portal + ":3260"
}
}
// iSCSIScanTargetLUN scans a single LUN or all the LUNs on an iSCSI target to discover it.
// If all the LUNs are to be scanned please pass -1 for lunID.
func iSCSIScanTargetLUN(ctx context.Context, lunID int, hosts []int) error {
fields := LogFields{"hosts": hosts, "lunID": lunID}
Logc(ctx).WithFields(fields).Debug(">>>> iscsi.iSCSIScanTargetLUN")
defer Logc(ctx).WithFields(fields).Debug("<<<< iscsi.iSCSIScanTargetLUN")
var (
f *os.File
err error