-
Notifications
You must be signed in to change notification settings - Fork 115
/
linux_formatter.go
94 lines (80 loc) · 2.48 KB
/
linux_formatter.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
package disk
import (
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
"regexp"
"strings"
)
type linuxFormatter struct {
runner boshsys.CmdRunner
fs boshsys.FileSystem
}
func NewLinuxFormatter(runner boshsys.CmdRunner, fs boshsys.FileSystem) Formatter {
return linuxFormatter{
runner: runner,
fs: fs,
}
}
func (f linuxFormatter) Format(partitionPath string, fsType FileSystemType) (err error) {
existingFsType, err := f.getPartitionFormatType(partitionPath)
if err != nil {
return bosherr.WrapError(err, "Checking filesystem format of partition")
}
if fsType == FileSystemSwap {
if existingFsType == FileSystemSwap {
return
}
// swap is not user-configured, so we're not concerned about reformatting
} else if existingFsType == FileSystemExt4 || existingFsType == FileSystemXFS {
// never reformat if it is already formatted in a supported format
return
}
switch fsType {
case FileSystemSwap:
_, _, _, err = f.runner.RunCommand("mkswap", partitionPath)
if err != nil {
err = bosherr.WrapError(err, "Shelling out to mkswap")
}
case FileSystemExt4:
err = f.makeFileSystemExt4(partitionPath)
if err != nil {
if strings.Contains(err.Error(), "apparently in use by the system") {
err = f.makeFileSystemExt4(partitionPath)
}
}
if err != nil {
err = bosherr.WrapError(err, "Shelling out to mke2fs")
}
case FileSystemXFS:
_, _, _, err = f.runner.RunCommand("mkfs.xfs", partitionPath)
if err != nil {
err = bosherr.WrapError(err, "Shelling out to mkfs.xfs")
}
}
return
}
func (f linuxFormatter) makeFileSystemExt4(partitionPath string) error {
var err error
if f.fs.FileExists("/sys/fs/ext4/features/lazy_itable_init") {
_, _, _, err = f.runner.RunCommand("mke2fs", "-t", string(FileSystemExt4), "-j", "-E", "lazy_itable_init=1", partitionPath)
} else {
_, _, _, err = f.runner.RunCommand("mke2fs", "-t", string(FileSystemExt4), "-j", partitionPath)
}
return err
}
func (f linuxFormatter) getPartitionFormatType(partitionPath string) (FileSystemType, error) {
stdout, stderr, exitStatus, err := f.runner.RunCommand("blkid", "-p", partitionPath)
if err != nil {
if exitStatus == 2 && stderr == "" {
// in that case we expect the device not to have any file system
return "", nil
}
return "", err
}
re := regexp.MustCompile(" TYPE=\"([^\"]+)\"")
match := re.FindStringSubmatch(stdout)
if nil == match {
return "", nil
}
return FileSystemType(match[1]), nil
}