summaryrefslogtreecommitdiff
path: root/vendor/github.com/lufia/plan9stats/host.go
blob: a3921c0e3692a72adae9f9d705d8948cd7369f7e (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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package stats

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var (
	delim = []byte{' '}
)

// Host represents host status.
type Host struct {
	Sysname    string
	Storages   []*Storage
	Interfaces []*Interface
}

// MemStats represents the memory statistics.
type MemStats struct {
	Total       int64 // total memory in byte
	PageSize    int64 // a page size in byte
	KernelPages int64
	UserPages   Gauge
	SwapPages   Gauge

	Malloced Gauge // kernel malloced data in byte
	Graphics Gauge // kernel graphics data in byte
}

// Gauge is used/available gauge.
type Gauge struct {
	Used  int64
	Avail int64
}

func (g Gauge) Free() int64 {
	return g.Avail - g.Used
}

// ReadMemStats reads memory statistics from /dev/swap.
func ReadMemStats(ctx context.Context, opts ...Option) (*MemStats, error) {
	cfg := newConfig(opts...)
	swap := filepath.Join(cfg.rootdir, "/dev/swap")
	f, err := os.Open(swap)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var stat MemStats
	m := map[string]interface{}{
		"memory":        &stat.Total,
		"pagesize":      &stat.PageSize,
		"kernel":        &stat.KernelPages,
		"user":          &stat.UserPages,
		"swap":          &stat.SwapPages,
		"kernel malloc": &stat.Malloced,
		"kernel draw":   &stat.Graphics,
	}
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		fields := bytes.SplitN(scanner.Bytes(), delim, 2)
		if len(fields) < 2 {
			continue
		}
		switch key := string(fields[1]); key {
		case "memory", "pagesize", "kernel":
			v := m[key].(*int64)
			n, err := strconv.ParseInt(string(fields[0]), 10, 64)
			if err != nil {
				return nil, err
			}
			*v = n
		case "user", "swap", "kernel malloc", "kernel draw":
			v := m[key].(*Gauge)
			if err := parseGauge(string(fields[0]), v); err != nil {
				return nil, err
			}
		}
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return &stat, nil
}

func parseGauge(s string, r *Gauge) error {
	a := strings.SplitN(s, "/", 2)
	if len(a) != 2 {
		return fmt.Errorf("can't parse ratio: %s", s)
	}
	var p intParser
	u := p.ParseInt64(a[0], 10)
	n := p.ParseInt64(a[1], 10)
	if err := p.Err(); err != nil {
		return err
	}
	r.Used = u
	r.Avail = n
	return nil
}

type Interface struct {
	Name string
	Addr string
}

const (
	numEther = 8  // see ether(3)
	numIpifc = 16 // see ip(3)
)

// ReadInterfaces reads network interfaces from etherN.
func ReadInterfaces(ctx context.Context, opts ...Option) ([]*Interface, error) {
	cfg := newConfig(opts...)
	var a []*Interface
	for i := 0; i < numEther; i++ {
		p, err := readInterface(cfg.rootdir, i)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return nil, err
		}
		a = append(a, p)
	}
	return a, nil
}

func readInterface(netroot string, i int) (*Interface, error) {
	ether := fmt.Sprintf("ether%d", i)
	dir := filepath.Join(netroot, ether)
	info, err := os.Stat(dir)
	if err != nil {
		return nil, err
	}
	if !info.IsDir() {
		return nil, fmt.Errorf("%s: is not directory", dir)
	}

	addr, err := ioutil.ReadFile(filepath.Join(dir, "addr"))
	if err != nil {
		return nil, err
	}
	return &Interface{
		Name: ether,
		Addr: string(addr),
	}, nil
}

var (
	netdirs = []string{"/net", "/net.alt"}
)

// ReadHost reads host status.
func ReadHost(ctx context.Context, opts ...Option) (*Host, error) {
	cfg := newConfig(opts...)
	var h Host
	name, err := readSysname(cfg.rootdir)
	if err != nil {
		return nil, err
	}
	h.Sysname = name

	a, err := ReadStorages(ctx, opts...)
	if err != nil {
		return nil, err
	}
	h.Storages = a

	for _, s := range netdirs {
		netroot := filepath.Join(cfg.rootdir, s)
		ifaces, err := ReadInterfaces(ctx, WithRootDir(netroot))
		if err != nil {
			return nil, err
		}
		h.Interfaces = append(h.Interfaces, ifaces...)
	}
	return &h, nil
}

func readSysname(rootdir string) (string, error) {
	file := filepath.Join(rootdir, "/dev/sysname")
	b, err := ioutil.ReadFile(file)
	if err != nil {
		return "", err
	}
	return string(bytes.TrimSpace(b)), nil
}

type IPStats struct {
	ID      int    // number of interface in ipifc dir
	Device  string // associated physical device
	MTU     int    // max transfer unit
	Sendra6 uint8  // on == send router adv
	Recvra6 uint8  // on == recv router adv

	Pktin  int64 // packets read
	Pktout int64 // packets written
	Errin  int64 // read errors
	Errout int64 // write errors
}

type Iplifc struct {
	IP            net.IP
	Mask          net.IPMask
	Net           net.IP // ip & mask
	PerfLifetime  int64  // preferred lifetime
	ValidLifetime int64  // valid lifetime
}

type Ipv6rp struct {
	// TODO(lufia): see ip(2)
}