-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
storage_unix.go
64 lines (56 loc) · 1.92 KB
/
storage_unix.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
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package fingerprint
import (
"fmt"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// diskFree inspects the filesystem for path and returns the volume name and
// the total and free bytes available on the file system.
func (f *StorageFingerprint) diskFree(path string) (volume string, total, free uint64, err error) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", 0, 0, fmt.Errorf("failed to determine absolute path for %s", path)
}
// Use -k to standardize the output values between darwin and linux
var dfArgs string
if runtime.GOOS == "linux" {
// df on linux needs the -P option to prevent linebreaks on long filesystem paths
dfArgs = "-kP"
} else {
dfArgs = "-k"
}
mountOutput, err := exec.Command("df", dfArgs, absPath).Output()
if err != nil {
return "", 0, 0, fmt.Errorf("failed to determine mount point for %s", absPath)
}
// Output looks something like:
// Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on
// /dev/disk1 487385240 423722532 63406708 87% 105994631 15851677 87% /
// [0] volume [1] capacity [2] SKIP [3] free
lines := strings.Split(string(mountOutput), "\n")
if len(lines) < 2 {
return "", 0, 0, fmt.Errorf("failed to parse `df` output; expected at least 2 lines")
}
fields := strings.Fields(lines[1])
if len(fields) < 4 {
return "", 0, 0, fmt.Errorf("failed to parse `df` output; expected at least 4 columns")
}
volume = fields[0]
total, err = strconv.ParseUint(fields[1], 10, 64)
if err != nil {
return "", 0, 0, fmt.Errorf("failed to parse storage.bytestotal size in kilobytes")
}
// convert to bytes
total *= 1024
free, err = strconv.ParseUint(fields[3], 10, 64)
if err != nil {
return "", 0, 0, fmt.Errorf("failed to parse storage.bytesfree size in kilobytes")
}
// convert to bytes
free *= 1024
return volume, total, free, nil
}