GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat(app): GET /app/metrics with memory, disk and device counts (#876)
Elio Bonfim Júniorc3bc4ed3b826
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 4064d53c..18748946 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -327,6 +327,73 @@ paths:application/json:schema:$ref: '#/components/schemas/ErrorInternalServer'+ /app/metrics:+ get:+ operationId: appMetrics+ tags:+ - app+ summary: Get server health metrics+ description: >+ Memory of the process and of its container (cgroup v2, then v1), CPU+ time, size of statics/media and storages (walk cached for a minute),+ free space on the volume, the session store and how many devices are+ registered, logged in and connected. Requires no device. Nullable fields+ are unknown on the current platform (non-Linux) or unlimited (container+ memory limit). Folder usage is best effort: missing or unreadable entries+ are omitted, and symlink targets are not traversed. Container metrics use+ the standard /sys/fs/cgroup mount and are null when unavailable. Uptime+ includes process initialization.+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ type: object+ properties:+ status: { type: integer, example: 200 }+ code: { type: string, example: SUCCESS }+ message: { type: string, example: Fetch app metrics success }+ results:+ type: object+ properties:+ version: { type: string, example: v9.6.0 }+ session_store: { type: string, enum: [sqlite, postgres] }+ devices:+ type: object+ properties:+ total: { type: integer, example: 5 }+ logged_in: { type: integer, example: 3 }+ connected: { type: integer, example: 3 }+ system:+ type: object+ properties:+ started_at: { type: string, format: date-time }+ uptime_seconds: { type: integer, example: 3600 }+ go_version: { type: string, example: go1.26.9 }+ cpu_seconds: { type: number, nullable: true, example: 17.9 }+ memory:+ type: object+ properties:+ heap_alloc_bytes: { type: integer, format: int64 }+ runtime_sys_bytes: { type: integer, format: int64 }+ process_rss_bytes: { type: integer, format: int64, nullable: true }+ container_bytes: { type: integer, format: int64, nullable: true }+ container_limit_bytes: { type: integer, format: int64, nullable: true }+ goroutines: { type: integer }+ gc_cycles: { type: integer }+ folders:+ type: object+ additionalProperties:+ type: object+ properties:+ bytes: { type: integer, format: int64 }+ files: { type: integer, format: int64 }+ filesystem:+ type: object+ properties:+ total_bytes: { type: integer, format: int64, nullable: true }+ free_bytes: { type: integer, format: int64, nullable: true }/app/info:get:operationId: appInfodiff --git a/src/pkg/sysmetrics/filesystem_unix.go b/src/pkg/sysmetrics/filesystem_unix.gonew file mode 100644index 00000000..2def144e--- /dev/null+++ b/src/pkg/sysmetrics/filesystem_unix.go@@ -0,0 +1,15 @@+//go:build !windows++package sysmetrics++import "syscall"++func filesystem(path string) Filesystem {+ var stat syscall.Statfs_t+ if err := syscall.Statfs(path, &stat); err != nil {+ return Filesystem{}+ }+ total := uint64(stat.Blocks) * uint64(stat.Bsize)+ free := uint64(stat.Bavail) * uint64(stat.Bsize)+ return Filesystem{TotalBytes: &total, FreeBytes: &free}+}diff --git a/src/pkg/sysmetrics/filesystem_windows.go b/src/pkg/sysmetrics/filesystem_windows.gonew file mode 100644index 00000000..2acc79a0--- /dev/null+++ b/src/pkg/sysmetrics/filesystem_windows.go@@ -0,0 +1,5 @@+//go:build windows++package sysmetrics++func filesystem(string) Filesystem { return Filesystem{} }diff --git a/src/pkg/sysmetrics/sysmetrics.go b/src/pkg/sysmetrics/sysmetrics.gonew file mode 100644index 00000000..aa204dff--- /dev/null+++ b/src/pkg/sysmetrics/sysmetrics.go@@ -0,0 +1,188 @@+// Package sysmetrics reports what an operator needs to size and watch a GOWA instance:+// memory of the process and of its container, disk used by media and storages, and the+// free space left on the volume. Everything is read from the runtime, /proc and the+// cgroup files; nothing is sampled in the background.+package sysmetrics++import (+ "io/fs"+ "os"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "sync"+ "time"+)++// Folder is the size of a directory tree.+type Folder struct {+ Bytes int64 `json:"bytes"`+ Files int64 `json:"files"`+}++// Filesystem is the volume a path lives on; nil fields mean "unknown on this platform".+type Filesystem struct {+ TotalBytes *uint64 `json:"total_bytes"`+ FreeBytes *uint64 `json:"free_bytes"`+}++// Memory groups the Go runtime, the process and the container (cgroup) view.+type Memory struct {+ HeapAllocBytes uint64 `json:"heap_alloc_bytes"`+ RuntimeSysBytes uint64 `json:"runtime_sys_bytes"`+ ProcessRSSBytes *uint64 `json:"process_rss_bytes"`+ ContainerBytes *uint64 `json:"container_bytes"`+ ContainerLimit *uint64 `json:"container_limit_bytes"`+ Goroutines int `json:"goroutines"`+ GarbageCollected uint32 `json:"gc_cycles"`+}++// Snapshot is what /app/metrics returns.+type Snapshot struct {+ StartedAt time.Time `json:"started_at"`+ UptimeSeconds int64 `json:"uptime_seconds"`+ GoVersion string `json:"go_version"`+ CPUSeconds *float64 `json:"cpu_seconds"`+ Memory Memory `json:"memory"`+ Folders map[string]Folder `json:"folders"`+ Filesystem Filesystem `json:"filesystem"`+}++var startedAt = time.Now()++// Folder sizes cost a full walk; media folders hold thousands of files, so a walk is+// reused for a minute.+const folderCacheFor = time.Minute++var (+ folderMu sync.Mutex+ folderCache map[string]Folder+ folderCached time.Time+)++// Collect builds a snapshot. folders maps a label to a path; fsPath is the path whose+// volume is reported.+func Collect(folders map[string]string, fsPath string) Snapshot {+ var mem runtime.MemStats+ runtime.ReadMemStats(&mem)++ snapshot := Snapshot{+ StartedAt: startedAt,+ UptimeSeconds: int64(time.Since(startedAt).Seconds()),+ GoVersion: runtime.Version(),+ CPUSeconds: processCPUSeconds(),+ Memory: Memory{+ HeapAllocBytes: mem.HeapAlloc,+ RuntimeSysBytes: mem.Sys,+ ProcessRSSBytes: processRSS(),+ Goroutines: runtime.NumGoroutine(),+ GarbageCollected: mem.NumGC,+ },+ Folders: folderSizes(folders),+ Filesystem: filesystem(fsPath),+ }+ snapshot.Memory.ContainerBytes, snapshot.Memory.ContainerLimit = containerMemory()+ return snapshot+}++func folderSizes(folders map[string]string) map[string]Folder {+ folderMu.Lock()+ defer folderMu.Unlock()+ if folderCache != nil && time.Since(folderCached) < folderCacheFor {+ return folderCache+ }+ result := make(map[string]Folder, len(folders))+ for label, root := range folders {+ var size Folder+ _ = filepath.WalkDir(root, func(_ string, entry fs.DirEntry, err error) error {+ if err != nil || entry.IsDir() {+ return nil+ }+ if info, err := entry.Info(); err == nil {+ size.Bytes += info.Size()+ size.Files+++ }+ return nil+ })+ result[label] = size+ }+ folderCache, folderCached = result, time.Now()+ return result+}++// processRSS reads VmRSS from /proc (Linux); nil elsewhere.+func processRSS() *uint64 {+ data, err := os.ReadFile("/proc/self/status")+ if err != nil {+ return nil+ }+ for _, line := range strings.Split(string(data), "\n") {+ if strings.HasPrefix(line, "VmRSS:") {+ fields := strings.Fields(line)+ if len(fields) >= 2 {+ if kb, err := strconv.ParseUint(fields[1], 10, 64); err == nil {+ bytes := kb * 1024+ return &bytes+ }+ }+ }+ }+ return nil+}++// processCPUSeconds is user+system CPU time from /proc/self/stat (Linux); nil elsewhere.+func processCPUSeconds() *float64 {+ data, err := os.ReadFile("/proc/self/stat")+ if err != nil {+ return nil+ }+ // The command name may contain spaces; fields are counted after its closing ')'.+ text := string(data)+ end := strings.LastIndex(text, ")")+ if end < 0 {+ return nil+ }+ fields := strings.Fields(text[end+1:])+ if len(fields) < 13 {+ return nil+ }+ user, err1 := strconv.ParseFloat(fields[11], 64)+ system, err2 := strconv.ParseFloat(fields[12], 64)+ if err1 != nil || err2 != nil {+ return nil+ }+ const ticksPerSecond = 100 // USER_HZ on every Linux the images run on+ seconds := (user + system) / ticksPerSecond+ return &seconds+}++// containerMemory reads the cgroup v2 files, falling back to cgroup v1. A limit of+// "max" (no limit) is reported as nil.+func containerMemory() (current, limit *uint64) {+ read := func(path string) *uint64 {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil+ }+ value := strings.TrimSpace(string(data))+ if value == "max" {+ return nil+ }+ n, err := strconv.ParseUint(value, 10, 64)+ if err != nil {+ return nil+ }+ return &n+ }+ if current = read("/sys/fs/cgroup/memory.current"); current != nil {+ return current, read("/sys/fs/cgroup/memory.max")+ }+ current = read("/sys/fs/cgroup/memory/memory.usage_in_bytes")+ limit = read("/sys/fs/cgroup/memory/memory.limit_in_bytes")+ // cgroup v1 reports "no limit" as a huge number.+ if limit != nil && *limit >= 1<<62 {+ limit = nil+ }+ return current, limit+}diff --git a/src/pkg/sysmetrics/sysmetrics_test.go b/src/pkg/sysmetrics/sysmetrics_test.gonew file mode 100644index 00000000..56c05dfa--- /dev/null+++ b/src/pkg/sysmetrics/sysmetrics_test.go@@ -0,0 +1,54 @@+package sysmetrics++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+ "time"+)++func TestCollectSizesFoldersAndReportsTheVolume(t *testing.T) {+ folderCache = nil+ root := t.TempDir()+ media := filepath.Join(root, "media", "5511900000000", "2026-10-12")+ if err := os.MkdirAll(media, 0o755); err != nil {+ t.Fatal(err)+ }+ for name, size := range map[string]int{"a.mp4": 1000, "b.jpg": 24} {+ if err := os.WriteFile(filepath.Join(media, name), make([]byte, size), 0o600); err != nil {+ t.Fatal(err)+ }+ }++ snapshot := Collect(map[string]string{"media": filepath.Join(root, "media"), "missing": filepath.Join(root, "nope")}, root)++ if got := snapshot.Folders["media"]; got.Bytes != 1024 || got.Files != 2 {+ t.Fatalf("media = %+v, want 1024 bytes in 2 files", got)+ }+ if got := snapshot.Folders["missing"]; got.Bytes != 0 || got.Files != 0 {+ t.Fatalf("missing folder = %+v, want zero", got)+ }+ if runtime.GOOS == "windows" {+ if snapshot.Filesystem.TotalBytes != nil || snapshot.Filesystem.FreeBytes != nil {+ t.Fatal("filesystem capacity should be unknown on Windows")+ }+ } else if snapshot.Filesystem.TotalBytes == nil || snapshot.Filesystem.FreeBytes == nil {+ t.Fatal("filesystem of the temp dir should be known")+ }+ if snapshot.Memory.HeapAllocBytes == 0 || snapshot.Memory.Goroutines == 0 {+ t.Fatal("runtime memory should be reported")+ }++ // A second call within the minute reuses the walk.+ if err := os.WriteFile(filepath.Join(media, "c.bin"), make([]byte, 10), 0o600); err != nil {+ t.Fatal(err)+ }+ if got := Collect(map[string]string{"media": filepath.Join(root, "media")}, root).Folders["media"]; got.Files != 2 {+ t.Fatalf("cache not reused: %+v", got)+ }+ folderCached = time.Now().Add(-2 * folderCacheFor)+ if got := Collect(map[string]string{"media": filepath.Join(root, "media")}, root).Folders["media"]; got.Files != 3 {+ t.Fatalf("expired cache not refreshed: %+v", got)+ }+}diff --git a/src/ui/rest/app.go b/src/ui/rest/app.goindex 07fea8b9..a28d083a 100644--- a/src/ui/rest/app.go+++ b/src/ui/rest/app.go@@ -2,10 +2,12 @@ package restimport ("fmt"+ "strings""github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sysmetrics""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/gofiber/fiber/v3""go.mau.fi/whatsmeow/types"@@ -34,6 +36,48 @@ func InitRestApp(app fiber.Router, service domainApp.IAppUsecase) App {// standalone UIs can read server metadata before any device exists.func InitRestAppInfo(app fiber.Router) {app.Get("/app/info", AppInfo)+ app.Get("/app/metrics", AppMetrics)+}++// AppMetrics reports the health of the instance itself — memory of the process and of+// its container, disk used by media and storages, free space on the volume, and how+// many devices are registered, logged in and connected — so a panel can show whether+// the server needs attention before a phone stops receiving messages.+func AppMetrics(c fiber.Ctx) error {+ snapshot := sysmetrics.Collect(map[string]string{+ "media": config.PathMedia,+ "storages": config.PathStorages,+ }, config.PathStorages)++ devices := map[string]int{"total": 0, "logged_in": 0, "connected": 0}+ if dm := whatsapp.GetDeviceManager(); dm != nil {+ for _, device := range dm.ListDevices() {+ devices["total"]+++ if device.IsLoggedIn() {+ devices["logged_in"]+++ }+ if device.IsConnected() {+ devices["connected"]+++ }+ }+ }++ sessionStore := "sqlite"+ if strings.HasPrefix(strings.Trim(config.DBURI, "\"'"), "postgres:") {+ sessionStore = "postgres"+ }++ return c.JSON(utils.ResponseData{+ Status: 200,+ Code: "SUCCESS",+ Message: "Fetch app metrics success",+ Results: map[string]any{+ "version": config.AppVersion,+ "session_store": sessionStore,+ "devices": devices,+ "system": snapshot,+ },+ })}func AppInfo(c fiber.Ctx) error {