forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapped_device_path_resolver.go
92 lines (73 loc) · 2.26 KB
/
mapped_device_path_resolver.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
package devicepathresolver
import (
"os"
"path/filepath"
"strings"
"time"
boshsettings "github.com/cloudfoundry/bosh-agent/settings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type mappedDevicePathResolver struct {
diskWaitTimeout time.Duration
fs boshsys.FileSystem
}
func NewMappedDevicePathResolver(
diskWaitTimeout time.Duration,
fs boshsys.FileSystem,
) DevicePathResolver {
return mappedDevicePathResolver{fs: fs, diskWaitTimeout: diskWaitTimeout}
}
func (dpr mappedDevicePathResolver) GetRealDevicePath(diskSettings boshsettings.DiskSettings) (string, bool, error) {
stopAfter := time.Now().Add(dpr.diskWaitTimeout)
devicePath := diskSettings.Path
if len(devicePath) == 0 {
return "", false, bosherr.Error("Getting real device path: path is missing")
}
realPath, found, err := dpr.findPossibleDevice(devicePath)
if err != nil {
return "", false, bosherr.Errorf("Getting real device path: %s", err.Error())
}
for !found {
if time.Now().After(stopAfter) {
return "", true, bosherr.Errorf("Timed out getting real device path for %s", devicePath)
}
time.Sleep(100 * time.Millisecond)
realPath, found, err = dpr.findPossibleDevice(devicePath)
if err != nil {
return "", false, bosherr.Errorf("Getting real device path: %s", err.Error())
}
}
return realPath, false, nil
}
func (dpr mappedDevicePathResolver) findPossibleDevice(devicePath string) (string, bool, error) {
needsMapping := strings.HasPrefix(devicePath, "/dev/sd")
if needsMapping {
pathSuffix := strings.Split(devicePath, "/dev/sd")[1]
possiblePrefixes := []string{
"/dev/xvd", // Xen
"/dev/vd", // KVM
"/dev/sd",
}
for _, prefix := range possiblePrefixes {
path := prefix + pathSuffix
if dpr.fs.FileExists(path) {
return path, true, nil
}
}
} else if dpr.fs.FileExists(devicePath) {
stat, err := dpr.fs.Lstat(devicePath)
if err == nil && stat.Mode()&os.ModeSymlink == os.ModeSymlink {
link, err := dpr.fs.Readlink(devicePath)
if err != nil {
return "", false, err
}
if strings.Contains(link, "..") {
link = filepath.Join(devicePath, "..", link)
}
return filepath.Clean(link), true, nil
}
return devicePath, true, nil
}
return "", false, nil
}