fork/gdu

git clone https://git.julia.blue/fork/gdu

Quet Zalfeat(analyze): add SQLite analyzer and some assorted changes (#484)da638da

master
2.1 KiB97 linesraw
1//go:build freebsd || darwin
2
3package device
4
5import (
6	"bufio"
7	"bytes"
8	"errors"
9	"io"
10	"os/exec"
11	"regexp"
12	"strings"
13
14	"golang.org/x/sys/unix"
15)
16
17// BSDDevicesInfoGetter returns info for Darwin devices
18type BSDDevicesInfoGetter struct {
19	MountCmd string
20}
21
22// Getter is current instance of DevicesInfoGetter
23var Getter DevicesInfoGetter = BSDDevicesInfoGetter{MountCmd: "/sbin/mount"}
24
25// GetMounts returns all mounted filesystems from output of /sbin/mount
26func (t BSDDevicesInfoGetter) GetMounts() (devices Devices, err error) {
27	var out []byte
28	out, err = exec.Command(t.MountCmd).Output()
29	if err != nil {
30		return nil, err
31	}
32
33	rdr := bytes.NewReader(out)
34
35	return readMountOutput(rdr)
36}
37
38// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall)
39func (t BSDDevicesInfoGetter) GetDevicesInfo() (devices Devices, err error) {
40	var mounts Devices
41	mounts, err = t.GetMounts()
42	if err != nil {
43		return nil, err
44	}
45
46	return processMounts(mounts, false)
47}
48
49func readMountOutput(rdr io.Reader) (mounts Devices, err error) {
50	scanner := bufio.NewScanner(rdr)
51	for scanner.Scan() {
52		line := scanner.Text()
53
54		re := regexp.MustCompile(`^(.*) on (/.*) \(([^)]+)\)$`)
55		parts := re.FindAllStringSubmatch(line, -1)
56
57		if len(parts) < 1 {
58			return nil, errors.New("cannot parse mount output")
59		}
60
61		fstype := strings.TrimSpace(strings.Split(parts[0][3], ",")[0])
62
63		device := &Device{
64			Name:       parts[0][1],
65			MountPoint: parts[0][2],
66			Fstype:     fstype,
67		}
68		mounts = append(mounts, device)
69	}
70
71	if err := scanner.Err(); err != nil {
72		return nil, err
73	}
74
75	return mounts, nil
76}
77
78func processMounts(mounts Devices, ignoreErrors bool) (devices Devices, err error) {
79	for _, mount := range mounts {
80		if !strings.HasPrefix(mount.Name, "/dev") && mount.Fstype != "zfs" {
81			continue
82		}
83
84		info := &unix.Statfs_t{}
85		err := unix.Statfs(mount.MountPoint, info)
86		if err != nil && !ignoreErrors {
87			return nil, err
88		}
89
90		mount.Size = int64(info.Bsize) * int64(info.Blocks)
91		mount.Free = int64(info.Bsize) * int64(info.Bavail)
92
93		devices = append(devices, mount)
94	}
95
96	return devices, nil
97}