summaryrefslogtreecommitdiffstats
path: root/widgets/mem_freebsd.go
blob: f3dd983b2e31f21e7572333de50901e1908f8f12 (plain)
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
package widgets

import (
	"fmt"
	"log"
	"os/exec"
	"strconv"
	"strings"

	"github.com/cjbassi/gotop/utils"
)

func convert(s []string) (MemoryInfo, error) {
	total, err := strconv.ParseUint(s[0], 10, 64)
	if err != nil {
		return MemoryInfo{}, fmt.Errorf("int converion failed %v", err)
	}

	used, err := strconv.ParseUint(s[1], 10, 64)
	if err != nil {
		return MemoryInfo{}, fmt.Errorf("int converion failed %v", err)
	}

	percentage, err := strconv.ParseFloat(strings.TrimSuffix(s[2], "%"), 64)
	if err != nil {
		return MemoryInfo{}, fmt.Errorf("float converion failed %v", err)
	}

	return MemoryInfo{
		Total:       total * utils.KB,
		Used:        used * utils.KB,
		UsedPercent: percentage,
	}, nil
}

func gatherSwapInfo() (MemoryInfo, error) {
	cmd := "swapinfo -k|sed -n '1!p'|awk '{print $2,$3,$5}'"
	output, err := exec.Command("sh", "-c", cmd).Output()
	if err != nil {
		if err != nil {
			return MemoryInfo{}, fmt.Errorf("command failed %v", err)
		}
	}

	ss := strings.Split(strings.TrimSuffix(string(output), "\n"), " ")

	return convert(ss)
}

func (self *MemWidget) updateSwapMemory() {
	swapMemory, err := gatherSwapInfo()
	if err != nil {
		log.Printf("failed to get swap memory info from gopsutil: %v", err)
	} else {
		self.renderMemInfo("Swap", MemoryInfo{
			Total:       swapMemory.Total,
			Used:        swapMemory.Used,
			UsedPercent: swapMemory.UsedPercent,
		})
	}
}