1
0
mirror of https://github.com/shirou/gopsutil.git synced 2025-04-24 13:48:56 +08:00
shirou_gopsutil/disk/disk_unix.go

64 lines
1.5 KiB
Go
Raw Normal View History

// SPDX-License-Identifier: BSD-3-Clause
//go:build freebsd || linux || darwin
2014-04-18 16:34:47 +09:00
2014-12-30 22:09:05 +09:00
package disk
2014-04-18 16:34:47 +09:00
2017-12-31 15:25:49 +09:00
import (
"context"
"strconv"
2017-12-31 15:25:49 +09:00
"golang.org/x/sys/unix"
)
2014-04-18 16:34:47 +09:00
2017-12-31 15:25:49 +09:00
func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
stat := unix.Statfs_t{}
err := unix.Statfs(path, &stat)
2014-04-18 16:34:47 +09:00
if err != nil {
return nil, err
2014-04-18 16:34:47 +09:00
}
2014-10-10 12:09:36 +04:00
bsize := stat.Bsize
2014-04-18 16:34:47 +09:00
ret := &UsageStat{
Path: unescapeFstab(path),
Fstype: getFsType(stat),
2014-10-10 12:09:36 +04:00
Total: (uint64(stat.Blocks) * uint64(bsize)),
Free: (uint64(stat.Bavail) * uint64(bsize)),
2014-08-26 12:38:52 +04:00
InodesTotal: (uint64(stat.Files)),
2014-08-26 22:17:35 +09:00
InodesFree: (uint64(stat.Ffree)),
2014-04-18 16:34:47 +09:00
}
2022-08-29 15:44:23 +02:00
ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize)
if (ret.Used + ret.Free) == 0 {
ret.UsedPercent = 0
} else {
// 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
}
2014-04-18 16:34:47 +09:00
// if could not get InodesTotal, return empty
if ret.InodesTotal < ret.InodesFree {
return ret, nil
2017-02-01 23:05:29 +00:00
}
2014-08-26 12:38:52 +04:00
ret.InodesUsed = (ret.InodesTotal - ret.InodesFree)
2017-02-01 23:05:29 +00:00
if ret.InodesTotal == 0 {
ret.InodesUsedPercent = 0
} else {
ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0
}
2014-04-18 16:34:47 +09:00
return ret, nil
}
// 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
}