add docker
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

This commit is contained in:
2026-10-23 00:39:04 +05:00
parent 965b00dba5
commit e5f01d0e94
16 changed files with 463 additions and 52 deletions

View File

@@ -0,0 +1,7 @@
//go:build !unix
package sysstats
import "errors"
func diskUsage(string) (Disk, error) { return Disk{}, errors.New("disk stats unsupported") }

24
pkg/sysstats/disk_unix.go Normal file
View File

@@ -0,0 +1,24 @@
//go:build unix
package sysstats
import "syscall"
func diskUsage(path string) (Disk, error) {
var st syscall.Statfs_t
if err := syscall.Statfs(path, &st); err != nil {
return Disk{}, err
}
bsize := uint64(st.Bsize)
total := uint64(st.Blocks) * bsize
free := uint64(st.Bavail) * bsize // space available to non-root users
used := total - uint64(st.Bfree)*bsize
return Disk{
Path: path,
TotalBytes: total,
UsedBytes: used,
FreeBytes: free,
UsagePercent: percent(used, used+free),
}, nil
}

118
pkg/sysstats/sysstats.go Normal file
View File

@@ -0,0 +1,118 @@
// Package sysstats reports host CPU, memory and disk usage plus the Go
// process's own footprint. It reads /proc and statfs directly so the binary
// keeps working in the scratch image without extra dependencies. Fields the
// current OS cannot provide are left nil.
package sysstats
import (
"context"
"os"
"runtime"
"time"
)
// cpuSampleWindow is how long CPU counters are sampled to compute usage.
const cpuSampleWindow = 250 * time.Millisecond
type CPU struct {
Cores int `json:"cores"`
UsagePercent *float64 `json:"usagePercent"`
LoadAvg *[3]float64 `json:"loadAvg"`
}
type Memory struct {
TotalBytes uint64 `json:"totalBytes"`
UsedBytes uint64 `json:"usedBytes"`
AvailableBytes uint64 `json:"availableBytes"`
UsagePercent float64 `json:"usagePercent"`
SwapTotalBytes uint64 `json:"swapTotalBytes"`
SwapUsedBytes uint64 `json:"swapUsedBytes"`
// LimitBytes is the container (cgroup) memory limit, nil when unlimited.
LimitBytes *uint64 `json:"limitBytes"`
}
type Disk struct {
Path string `json:"path"`
TotalBytes uint64 `json:"totalBytes"`
UsedBytes uint64 `json:"usedBytes"`
FreeBytes uint64 `json:"freeBytes"`
UsagePercent float64 `json:"usagePercent"`
}
type Process struct {
Goroutines int `json:"goroutines"`
HeapAllocBytes uint64 `json:"heapAllocBytes"`
SysBytes uint64 `json:"sysBytes"`
NumGC uint32 `json:"numGc"`
UptimeSeconds int64 `json:"uptimeSeconds"`
}
type Stats struct {
Hostname string `json:"hostname"`
OS string `json:"os"`
Arch string `json:"arch"`
GoVersion string `json:"goVersion"`
HostUptimeSeconds *int64 `json:"hostUptimeSeconds"`
CPU CPU `json:"cpu"`
Memory *Memory `json:"memory"`
Disks []Disk `json:"disks"`
Process Process `json:"process"`
CollectedAt time.Time `json:"collectedAt"`
}
var processStart = time.Now()
// Collect gathers a snapshot. It blocks for about cpuSampleWindow while CPU
// usage is sampled. Disk paths that cannot be read are skipped.
func Collect(ctx context.Context, diskPaths []string) (Stats, error) {
hostname, _ := os.Hostname()
usage, err := cpuUsage(ctx, cpuSampleWindow)
if err != nil {
return Stats{}, err
}
disks := make([]Disk, 0, len(diskPaths))
for _, p := range diskPaths {
if d, err := diskUsage(p); err == nil {
disks = append(disks, d)
}
}
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
return Stats{
Hostname: hostname,
OS: runtime.GOOS,
Arch: runtime.GOARCH,
GoVersion: runtime.Version(),
HostUptimeSeconds: hostUptime(),
CPU: CPU{
Cores: runtime.NumCPU(),
UsagePercent: usage,
LoadAvg: loadAvg(),
},
Memory: memory(),
Disks: disks,
Process: Process{
Goroutines: runtime.NumGoroutine(),
HeapAllocBytes: ms.HeapAlloc,
SysBytes: ms.Sys,
NumGC: ms.NumGC,
UptimeSeconds: int64(time.Since(processStart).Seconds()),
},
CollectedAt: time.Now(),
}, nil
}
func percent(part, total uint64) float64 {
if total == 0 {
return 0
}
return round2(float64(part) / float64(total) * 100)
}
func round2(v float64) float64 {
return float64(int64(v*100+0.5)) / 100
}

View File

@@ -0,0 +1,158 @@
package sysstats
import (
"bufio"
"context"
"os"
"strconv"
"strings"
"time"
)
// cpuUsage samples the aggregate "cpu" line of /proc/stat twice and returns
// the busy share of the elapsed ticks.
func cpuUsage(ctx context.Context, window time.Duration) (*float64, error) {
idle1, total1, err := readCPUTimes()
if err != nil {
return nil, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(window):
}
idle2, total2, err := readCPUTimes()
if err != nil || total2 <= total1 {
return nil, nil
}
busy := (total2 - total1) - (idle2 - idle1)
v := percent(busy, total2-total1)
return &v, nil
}
func readCPUTimes() (idle, total uint64, err error) {
data, err := os.ReadFile("/proc/stat")
if err != nil {
return 0, 0, err
}
line, _, _ := strings.Cut(string(data), "\n")
fields := strings.Fields(line)
if len(fields) < 5 || fields[0] != "cpu" {
return 0, 0, os.ErrInvalid
}
// user nice system idle iowait irq softirq steal [guest guest_nice]
// guest time is already counted in user/nice, so stop at steal.
for i, f := range fields[1:] {
if i >= 8 {
break
}
v, err := strconv.ParseUint(f, 10, 64)
if err != nil {
return 0, 0, err
}
total += v
if i == 3 || i == 4 { // idle, iowait
idle += v
}
}
return idle, total, nil
}
func memory() *Memory {
f, err := os.Open("/proc/meminfo")
if err != nil {
return nil
}
defer f.Close()
info := make(map[string]uint64)
sc := bufio.NewScanner(f)
for sc.Scan() {
key, rest, ok := strings.Cut(sc.Text(), ":")
if !ok {
continue
}
fields := strings.Fields(rest)
if len(fields) == 0 {
continue
}
v, err := strconv.ParseUint(fields[0], 10, 64)
if err != nil {
continue
}
info[key] = v * 1024 // values are in kB
}
total := info["MemTotal"]
available, ok := info["MemAvailable"]
if !ok {
available = info["MemFree"] + info["Buffers"] + info["Cached"]
}
used := total - min(available, total)
return &Memory{
TotalBytes: total,
UsedBytes: used,
AvailableBytes: available,
UsagePercent: percent(used, total),
SwapTotalBytes: info["SwapTotal"],
SwapUsedBytes: info["SwapTotal"] - min(info["SwapFree"], info["SwapTotal"]),
LimitBytes: cgroupMemoryLimit(),
}
}
// cgroupMemoryLimit reads the container memory limit (cgroup v2, then v1).
// Very large v1 values mean "no limit".
func cgroupMemoryLimit() *uint64 {
for _, path := range []string{
"/sys/fs/cgroup/memory.max",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
} {
data, err := os.ReadFile(path)
if err != nil {
continue
}
v, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
if err != nil || v >= 1<<60 {
return nil // "max" or effectively unlimited
}
return &v
}
return nil
}
func loadAvg() *[3]float64 {
data, err := os.ReadFile("/proc/loadavg")
if err != nil {
return nil
}
fields := strings.Fields(string(data))
if len(fields) < 3 {
return nil
}
var out [3]float64
for i := range out {
v, err := strconv.ParseFloat(fields[i], 64)
if err != nil {
return nil
}
out[i] = v
}
return &out
}
func hostUptime() *int64 {
data, err := os.ReadFile("/proc/uptime")
if err != nil {
return nil
}
first, _, _ := strings.Cut(string(data), " ")
v, err := strconv.ParseFloat(first, 64)
if err != nil {
return nil
}
s := int64(v)
return &s
}

View File

@@ -0,0 +1,15 @@
//go:build !linux
package sysstats
import (
"context"
"time"
)
// Host CPU, memory, load and uptime are only read from /proc on Linux.
func cpuUsage(context.Context, time.Duration) (*float64, error) { return nil, nil }
func memory() *Memory { return nil }
func loadAvg() *[3]float64 { return nil }
func hostUptime() *int64 { return nil }