NASutils Knowledge BaseUnofficialPolski

Go · projectA NAS summary on screen and as JSON

This Go program gathers the state of the NAS once and prints it in one of two forms. The screen form has a section each for the CPU, memory, data volumes and network ports, with bars. With -json it prints the same facts as JSON, which a script, a web page or a monitoring tool can read.

Programming on the NAS › Go in 30 lessons

 NAS summary                                                          TBS-h574TX

 CPU ─────────────────────────────────────────────────────────────────────────
  12th Gen Intel Core i5-1235U, 10 cores, 12 logical processors
  Load 1.17 0.90 0.88   █░░░░░░░░░░░░░░░░░░░ 9 % of the logical processors
  Up for 1 d 13 h 10 min   temperature 53 °C

 Memory ──────────────────────────────────────────────────────────────────────
  ███████░░░░░░░░░░░░░  36 %   5.6 GiB of 15.4 GiB in use, 9.8 GiB available

 Volumes ─────────────────────────────────────────────────────────────────────
  CACHEDEV1_DATA  ██████░░░░░░░░░░░░░░░░░░░░░░░░  21 %   281.8 GiB of 1327.1 GiB
  CACHEDEV2_DATA  ████░░░░░░░░░░░░░░░░░░░░░░░░░░  14 %   177.1 GiB of 1232.3 GiB

 Network ports ───────────────────────────────────────────────────────────────
  eth0   received   51.4 GiB   sent   10.2 GiB
  eth1   received    0.0 GiB   sent    0.0 GiB
The screen form: 10 cores and 12 logical processors at 9 % load, 53 °C, 36 % of the memory in use, two data volumes and the bytes of eth0 and eth1.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/go/stats.go

stats.go Download stats.go

// stats.go: a summary of the NAS in one screen: CPU, temperatures, memory, data volumes and network ports.
// With -json it prints the same facts as JSON, for a script or another program.
// Build and run it: go build stats.go && ./stats [-json]   (PROC and DF may point it at sample files)
package main

import (
	"cmp"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

// The facts, as structs; the json tags name the fields of the JSON form.
type CPU struct {
	Name    string    `json:"name"`
	Cores   int       `json:"cores"`
	Logical int       `json:"logical_processors"`
	Load    []float64 `json:"load"`                    // the averages of 1, 5 and 15 minutes
	TempC   int       `json:"temperature_c,omitempty"` // omitempty: left out when getsysinfo is missing
}

type Volume struct {
	Name    string `json:"name"`
	SizeKiB int64  `json:"size_kib"`
	UsedKiB int64  `json:"used_kib"`
	UsedPct int    `json:"used_percent"`
}

type Port struct {
	Name    string `json:"name"`
	RxBytes int64  `json:"received_bytes"`
	TxBytes int64  `json:"sent_bytes"`
}

type Summary struct {
	Model     string   `json:"model,omitempty"`
	UptimeS   int      `json:"uptime_seconds"`
	CPU       CPU      `json:"cpu"`
	MemoryKiB int64    `json:"memory_kib"`
	AvailKiB  int64    `json:"memory_available_kib"`
	Volumes   []Volume `json:"volumes"`
	Ports     []Port   `json:"ports"`
}

func read(name string) string {
	b, _ := os.ReadFile(cmp.Or(os.Getenv("PROC"), "/proc") + "/" + name)
	return string(b)
}

func num(s string) int64 { n, _ := strconv.ParseInt(strings.TrimSuffix(s, "%"), 10, 64); return n }
func collect() Summary {
	var s Summary
	model, _ := exec.Command("getsysinfo", "model").Output()
	s.Model = strings.TrimSpace(string(model))
	fmt.Sscanf(read("uptime"), "%d", &s.UptimeS)
	cores, physical := map[string]bool{}, ""
	for _, l := range strings.Split(read("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		k, v = strings.TrimSpace(k), strings.TrimSpace(v)
		switch {
		case k == "processor":
			s.CPU.Logical++
		case k == "model name" && s.CPU.Name == "":
			s.CPU.Name = strings.NewReplacer("(R)", "", "(TM)", "", " CPU", "").Replace(v)
		case k == "physical id":
			physical = v
		case k == "core id":
			cores[physical+"-"+v] = true
		}
	}
	s.CPU.Cores = len(cores)
	for _, f := range strings.Fields(read("loadavg"))[:3] {
		x, _ := strconv.ParseFloat(f, 64)
		s.CPU.Load = append(s.CPU.Load, x)
	}
	if t, err := exec.Command("getsysinfo", "cputmp").Output(); err == nil {
		fmt.Sscanf(string(t), "%d", &s.CPU.TempC) // "53 C/127 F"
	}
	for _, l := range strings.Split(read("meminfo"), "\n") {
		if f := strings.Fields(l); len(f) > 1 && f[0] == "MemTotal:" {
			s.MemoryKiB = num(f[1])
		} else if len(f) > 1 && f[0] == "MemAvailable:" {
			s.AvailKiB = num(f[1])
		}
	}
	out, err := os.ReadFile(os.Getenv("DF"))
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	for _, l := range strings.Split(string(out), "\n") {
		if f := strings.Fields(l); len(f) > 5 && strings.HasPrefix(f[5], "/share/") && strings.Count(f[5], "/") == 2 {
			s.Volumes = append(s.Volumes, Volume{strings.TrimPrefix(f[5], "/share/"), num(f[1]), num(f[2]), int(num(f[4]))})
		}
	}
	for _, l := range strings.Split(read("net/dev"), "\n") {
		name, rest, ok := strings.Cut(l, ":")
		if f := strings.Fields(rest); ok && strings.HasPrefix(strings.TrimSpace(name), "eth") && len(f) > 8 {
			s.Ports = append(s.Ports, Port{strings.TrimSpace(name), num(f[0]), num(f[8])})
		}
	}
	return s
}

const amber, green, red, dim, bold, reset = "\033[38;5;214m", "\033[32m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"

// bar fills pct percent of width: green up to 69 %, amber up to 89 %, red from 90 %.
func bar(pct, width int) string {
	c := green
	if pct >= 70 {
		c = amber
	}
	if pct >= 90 {
		c = red
	}
	return c + strings.Repeat("█", pct*width/100) + dim + strings.Repeat("░", width-pct*width/100) + reset
}

func gib(kib int64) string { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) }
func head(title string) {
	fmt.Printf("\n %s%s%s %s%s\n", bold+amber, title, reset+amber, strings.Repeat("─", 76-len([]rune(title))), reset)
}

func main() {
	asJSON := flag.Bool("json", false, "print the facts as JSON")
	flag.Parse()
	s := collect()
	if *asJSON {
		e := json.NewEncoder(os.Stdout)
		e.SetIndent("", "  ")
		e.Encode(s)
		return
	}
	fmt.Printf("%s %-40s%39s%s\n", "\033[1;30;48;5;214m", "NAS summary", s.Model, reset)
	head("CPU")
	fmt.Printf("  %s%s%s, %d cores, %d logical processors\n", bold, s.CPU.Name, reset, s.CPU.Cores, s.CPU.Logical)
	pct := int(s.CPU.Load[0] * 100 / float64(s.CPU.Logical))
	fmt.Printf("  Load %.2f %.2f %.2f   %s %d %% of the logical processors\n", s.CPU.Load[0], s.CPU.Load[1], s.CPU.Load[2], bar(pct, 20), pct)
	fmt.Printf("  Up for %d d %d h %d min", s.UptimeS/86400, s.UptimeS%86400/3600, s.UptimeS%3600/60)
	if s.CPU.TempC > 0 {
		fmt.Printf("   temperature %s%d °C%s", green, s.CPU.TempC, reset)
	}
	fmt.Println()
	head("Memory")
	used := s.MemoryKiB - s.AvailKiB
	fmt.Printf("  %s %3d %%   %s of %s in use, %s%s%s available\n", bar(int(used*100/s.MemoryKiB), 20),
		used*100/s.MemoryKiB, gib(used), gib(s.MemoryKiB), green, gib(s.AvailKiB), reset)
	head("Volumes")
	for _, v := range s.Volumes {
		fmt.Printf("  %-16s%s %3d %%   %s of %s\n", v.Name, bar(v.UsedPct, 30), v.UsedPct, gib(v.UsedKiB), gib(v.SizeKiB))
	}
	head("Network ports")
	for _, p := range s.Ports {
		fmt.Printf("  %-6s received %10s   sent %10s\n", p.Name, gib(p.RxBytes/1024), gib(p.TxBytes/1024))
	}
}

What you learn

  • A struct per kind of fact (CPU, Volume, Port) and one Summary that holds them all.
  • Tags such as `json:"used_percent"` give each field its name in JSON; omitempty leaves out an empty one.
  • flag.Bool("json", ...) adds the option -json, and flag.Parse reads it from the command line.
  • json.NewEncoder(os.Stdout) with SetIndent writes indented JSON straight to the output.
  • strings.Cut(l, ":") splits a line of /proc/net/dev at the first colon into the port name and the numbers.

How it works

collect fills a Summary. It counts the logical processors and the distinct pairs of physical id and core id in /proc/cpuinfo, reads the three load averages and the CPU temperature from getsysinfo cputmp, MemTotal and MemAvailable from /proc/meminfo, the data volumes from df -k and the received and sent bytes of each eth port from /proc/net/dev.

main reads the options and calls collect once. With -json it encodes the struct and ends. Otherwise it prints the screen: a title bar with the model, then the sections, each opened by head. The load bar shows the load of 1 minute per logical processor: 1.17 on 12 logical processors is 9 %.

The JSON form names the units in the field names: size_kib, received_bytes, uptime_seconds. Its first lines on the sample NAS:

{
  "model": "TBS-h574TX",
  "uptime_seconds": 133807,
  "cpu": {
    "name": "12th Gen Intel Core i5-1235U",
    "cores": 10,
    "logical_processors": 12,

Notes to the lines

  • 17–24The tags after each field are the JSON names; the program prints them only in the -json form.
  • 39–47Summary holds the other structs, so the JSON has the same nesting.
  • 54num reads a number and drops a "%" at its end, as in the column Use% of df.
  • 65–72A switch with conditions: the first "model name" gives the CPU name without "(R)", "(TM)" and "CPU".
  • 80–82getsysinfo cputmp answers "53 C/127 F"; %d reads the 53. Without getsysinfo the field stays 0, and omitempty leaves it out of the JSON.
  • 95–97A Volume literal fills its fields in their order: name, size, used and percentage.
  • 99–104The bytes received are the first number after the colon, the bytes sent the ninth.
  • 128–136The JSON form: encode, then return before the screen form.
  • 140The share of the logical processors that the load of 1 minute keeps busy.

Run it

Build it in the terminal of Bucket & Code's editor, with its Go runtime:

eval "$(bvs use go-1.27-x86_64)"
go build stats.go
./stats
./stats -json

The first run prints the screen, the second the JSON. The finished file runs on the NAS without Go.

Try it yourself

Add the system temperature from getsysinfo systmp as a field system_temperature_c. Write the JSON to a file with ./stats -json > /share/Public/nas.json and read it back with jq .cpu.cores, if TurboShell is installed.

More projects in Go