2018-10-17 20:20:35 +00:00
|
|
|
// +build freebsd linux darwin
|
|
|
|
|
|
|
|
package disk
|
|
|
|
|
2018-10-19 18:33:23 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"strconv"
|
2018-10-17 20:20:35 +00:00
|
|
|
|
2018-10-19 18:33:23 +00:00
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
2020-07-01 12:47:56 +00:00
|
|
|
// Usage returns a file system usage. path is a filesystem path such
|
2018-10-19 18:33:23 +00:00
|
|
|
// as "/", not device file path like "/dev/vda1". If you want to use
|
|
|
|
// a return value of disk.Partitions, use "Mountpoint" not "Device".
|
2018-10-17 20:20:35 +00:00
|
|
|
func Usage(path string) (*UsageStat, error) {
|
2018-10-19 18:33:23 +00:00
|
|
|
return UsageWithContext(context.Background(), path)
|
|
|
|
}
|
|
|
|
|
|
|
|
func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
|
|
|
|
stat := unix.Statfs_t{}
|
|
|
|
err := unix.Statfs(path, &stat)
|
2018-10-17 20:20:35 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
bsize := stat.Bsize
|
|
|
|
|
|
|
|
ret := &UsageStat{
|
2018-10-19 18:33:23 +00:00
|
|
|
Path: unescapeFstab(path),
|
2018-10-17 20:20:35 +00:00
|
|
|
Fstype: getFsType(stat),
|
|
|
|
Total: (uint64(stat.Blocks) * uint64(bsize)),
|
|
|
|
Free: (uint64(stat.Bavail) * uint64(bsize)),
|
|
|
|
InodesTotal: (uint64(stat.Files)),
|
|
|
|
InodesFree: (uint64(stat.Ffree)),
|
|
|
|
}
|
|
|
|
|
|
|
|
// if could not get InodesTotal, return empty
|
|
|
|
if ret.InodesTotal < ret.InodesFree {
|
|
|
|
return ret, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
ret.InodesUsed = (ret.InodesTotal - ret.InodesFree)
|
|
|
|
ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize)
|
|
|
|
|
|
|
|
if ret.InodesTotal == 0 {
|
|
|
|
ret.InodesUsedPercent = 0
|
|
|
|
} else {
|
|
|
|
ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0
|
|
|
|
}
|
|
|
|
|
2018-10-19 18:33:23 +00:00
|
|
|
if (ret.Used + ret.Free) == 0 {
|
2018-10-17 20:20:35 +00:00
|
|
|
ret.UsedPercent = 0
|
|
|
|
} else {
|
2018-10-19 18:33:23 +00:00
|
|
|
// We don't use ret.Total to calculate percent.
|
|
|
|
// see https://github.com/shirou/gopsutil/issues/562
|
|
|
|
ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0
|
2018-10-17 20:20:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|
2018-10-19 18:33:23 +00:00
|
|
|
|
|
|
|
// Unescape escaped octal chars (like space 040, ampersand 046 and backslash 134) to their real value in fstab fields issue#555
|
|
|
|
func unescapeFstab(path string) string {
|
|
|
|
escaped, err := strconv.Unquote(`"` + path + `"`)
|
|
|
|
if err != nil {
|
|
|
|
return path
|
|
|
|
}
|
|
|
|
return escaped
|
|
|
|
}
|