File: dev_linux.go

package info (click to toggle)
gdu 5.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 624 kB
  • sloc: makefile: 122
file content (104 lines) | stat: -rw-r--r-- 2,245 bytes parent folder | download | duplicates (2)
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
95
96
97
98
99
100
101
102
103
104
package device

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"

	"golang.org/x/sys/unix"
)

// LinuxDevicesInfoGetter returns info for Linux devices
type LinuxDevicesInfoGetter struct {
	MountsPath string
}

// Getter is current instance of DevicesInfoGetter
var Getter DevicesInfoGetter = LinuxDevicesInfoGetter{MountsPath: "/proc/mounts"}

// GetMounts returns all mounted filesystems from /proc/mounts
func (t LinuxDevicesInfoGetter) GetMounts() (Devices, error) {
	file, err := os.Open(t.MountsPath)
	if err != nil {
		return nil, err
	}

	devices, err := readMountsFile(file)
	if err != nil {
		if cerr := file.Close(); cerr != nil {
			return nil, fmt.Errorf("%w; %s", err, cerr)
		}
		return nil, err
	}
	if err := file.Close(); err != nil {
		return nil, err
	}
	return devices, nil
}

// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall)
func (t LinuxDevicesInfoGetter) GetDevicesInfo() (Devices, error) {
	mounts, err := t.GetMounts()
	if err != nil {
		return nil, err
	}

	return processMounts(mounts, false)
}

func readMountsFile(file io.Reader) (Devices, error) {
	mounts := Devices{}

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.Fields(line)

		device := &Device{
			Name:       parts[0],
			MountPoint: unescapeString(parts[1]),
			Fstype:     parts[2],
		}
		mounts = append(mounts, device)
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return mounts, nil
}

func processMounts(mounts Devices, ignoreErrors bool) (Devices, error) {
	devices := Devices{}

	for _, mount := range mounts {
		if strings.Contains(mount.MountPoint, "/snap/") {
			continue
		}

		if strings.HasPrefix(mount.Name, "/dev") ||
			mount.Fstype == "zfs" ||
			mount.Fstype == "nfs" ||
			mount.Fstype == "nfs4" {
			info := &unix.Statfs_t{}
			err := unix.Statfs(mount.MountPoint, info)
			if err != nil && !ignoreErrors {
				return nil, err
			}

			mount.Size = int64(info.Bsize) * int64(info.Blocks)
			mount.Free = int64(info.Bsize) * int64(info.Bavail)

			devices = append(devices, mount)
		}
	}

	return devices, nil
}

func unescapeString(str string) string {
	return strings.ReplaceAll(str, "\\040", " ")
}