From e5f01d0e9421d2f24f5ab4cf0ce72b9bcca55d74 Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Fri, 23 Oct 2026 00:39:04 +0500 Subject: [PATCH] add docker --- .DS_Store | Bin 12292 -> 14340 bytes .dockerignore | 12 +- .gitignore | 3 + Dockerfile | 41 +++-- Makefile | 24 +++ .../20260930120000_payment_texts.down.sql | 1 - .../20260930120000_payment_texts.up.sql | 23 --- deployment/Dockerfile.minio | 33 +++- docker-compose.yaml | 26 ++- internal/dashboard/handler.go | 28 +++- internal/handlers/manager/manager.go | 2 +- pkg/sysstats/disk_other.go | 7 + pkg/sysstats/disk_unix.go | 24 +++ pkg/sysstats/sysstats.go | 118 +++++++++++++ pkg/sysstats/sysstats_linux.go | 158 ++++++++++++++++++ pkg/sysstats/sysstats_other.go | 15 ++ 16 files changed, 463 insertions(+), 52 deletions(-) delete mode 100644 db/migrations/20260930120000_payment_texts.down.sql delete mode 100644 db/migrations/20260930120000_payment_texts.up.sql create mode 100644 pkg/sysstats/disk_other.go create mode 100644 pkg/sysstats/disk_unix.go create mode 100644 pkg/sysstats/sysstats.go create mode 100644 pkg/sysstats/sysstats_linux.go create mode 100644 pkg/sysstats/sysstats_other.go diff --git a/.DS_Store b/.DS_Store index a6b506ae1d8551651a31932fa8cf1da061e0bdf3..9fb69605d6b3cf363d70e005cc12013469f7d562 100644 GIT binary patch delta 573 zcmZokXem%&U|?W$DortDU@!nOIe-{M3-B;7FmW<4DDX^F&=*w(iZBBO85l|!QW=UE z@)!~sayDLE%sAOVhlQ09D9f_>g6dmF_LSg)#N^DpjTf0&HnVfEa4_;uzMv{H`J%ef z#0lDy`2`G&`5E$o+H)8(fn+L!E<+N~sAPt020exu@SNctb>hL88sz z$l%2g%#guQ&d|p&i(whV4u+!)w;0|qd}Cx`6r1d;Y%L16yDYdUFDE}Q9jKde^I2s! zrp+x9cI=X@5Yr5}fwU`f_-?%To_R9Aj;;x20#W2h`|Jj9Sab9a*oc# N$(I$?2FzQIi~!K;d+q=L delta 393 zcmY*V%}N4M6#nka$V@re^dkrn+_FLlZPY1>S_v)Mw5SItwNOdY9Nn}GX)pIpy6d1t zL~qbL)S^eQ?+yfYFZX=s@1FCWGwzQsB>+(yU6p|XRgceL;8Q#TGCh$ySxLjD6KEkm z>Gqn9Zm%)9%d0SQQi4H8odw(KP|oUyT+P+4=XhdH-3L|u73{hfn>a@k16=doB1RiM z3?WfL$hU_g@qn^Ql&B}MGW{jm`;;cHgg*bae!H_N>EMa%Gb)=agks&O)8sHLb6VPjk;M2V2y>e6{u4mTl=J>r<$}T2?ZstWH@cl~h9^O+5a) u8NJ|q+iE^4&X^Uvm^5|dulTgg8bJ(IJDOz3d&tQL#5%f4Y`p*LBBnntNlViJ diff --git a/.dockerignore b/.dockerignore index 7918de0..cbe865e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,26 @@ .git .github .cursor +.claude +.DS_Store logs tmp temp -vendor +dist *.md *.log +*.tar +*.tar.gz coverage.out coverage.html +config.yaml config.local.yaml +docker-compose.yaml docker-compose.override.yaml docker-compose.override.yml +deployment/minio.deb +myapp public/images/* !public/images/.gitkeep +public/backups/* +!public/backups/.gitkeep diff --git a/.gitignore b/.gitignore index b578e49..eb47639 100644 --- a/.gitignore +++ b/.gitignore @@ -77,3 +77,6 @@ bank_db_schema.drawio # Debug __debug_bin debug + +# Docker image bundles (make docker-bundle) +dist/ diff --git a/Dockerfile b/Dockerfile index 01629c0..9f38c49 100755 --- a/Dockerfile +++ b/Dockerfile @@ -1,30 +1,39 @@ -#!/bin/ash -# Specifies a parent image +# Offline build: nothing in this file touches the network. +# - Go modules come from the committed vendor/ directory. +# - The runtime stage is postgres:14.1-alpine, the same image main-db uses, +# so pg_dump (backups), tzdata and CA certificates are already there and no +# `apk add` is needed. Its layers are shared with main-db on the server. +# The server only needs the base images loaded once (see `make docker-bundle`). +# +# No "# syntax=" directive on purpose: it makes BuildKit pull a frontend image. + FROM golang:1.26.4-alpine AS builder -# Creates an app directory to hold your app’s source code WORKDIR /build -# Installs Go dependencies -COPY go.mod ./ -COPY go.sum ./ -RUN go mod download +ENV CGO_ENABLED=0 \ + GOOS=linux \ + GOARCH=amd64 \ + GOFLAGS=-mod=vendor \ + GOPROXY=off COPY . . -# Builds your app with optional configuration -RUN GOARCH=amd64 GOOS=linux go build -o myapp ./app.go +RUN go build -trimpath -ldflags="-s -w" -o myapp ./app.go -FROM scratch +FROM postgres:14.1-alpine -WORKDIR /app/ +# Fresher CA bundle than the 2021 one in postgres:14.1-alpine (HTTPS to mpi.gov.tm). +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt + +WORKDIR /app COPY --from=builder /build/myapp . -COPY --from=builder /build/config.yaml . -# Tells Docker which network port your container listens on +# config.yaml is mounted at runtime (see docker-compose.yaml), not baked in. +RUN mkdir -p /app/public/images /app/public/backups /app/logs + EXPOSE 5050 -#ENTRYPOINT ["/app/myapp"] -CMD ["/app/myapp"] - +# Replaces the postgres docker-entrypoint.sh inherited from the base image. +ENTRYPOINT ["/app/myapp"] diff --git a/Makefile b/Makefile index 795abc2..101fab8 100755 --- a/Makefile +++ b/Makefile @@ -39,3 +39,27 @@ deploy: build-linux ssh $(DEPLOY_HOST) 'mkdir -p $(DEPLOY_DIR)' scp ./$(BINARY) $(DEPLOY_HOST):$(DEPLOY_DIR)/$(BINARY).new ssh $(DEPLOY_HOST) 'cd $(DEPLOY_DIR) && chmod +x $(BINARY).new && mv $(BINARY).new $(BINARY)' + +# --------------------------------------------------------------------------- +# Docker (serwerde internet ýok). Papka serwere göni göçürilýär: +# 1) internet bar maşynda: make docker-bundle → dist/ içine ähli image-ler +# 2) serwerde: make docker-load (bir gezek, ýa-da täze bundle-da) +# docker compose up -d --build (internetsiz build) +# --------------------------------------------------------------------------- +DOCKER_PLATFORM ?= linux/amd64 +DOCKER_BASE_IMAGES ?= golang:1.26.4-alpine postgres:14.1-alpine +DOCKER_IMAGES ?= main-app:latest main-minio:latest $(DOCKER_BASE_IMAGES) +DOCKER_BUNDLE ?= dist/online-back-images.tar.gz + +.PHONY: docker-bundle docker-load + +docker-bundle: + for img in $(DOCKER_BASE_IMAGES); do \ + docker image inspect $$img >/dev/null 2>&1 || docker pull --platform $(DOCKER_PLATFORM) $$img || exit 1; \ + done + DOCKER_DEFAULT_PLATFORM=$(DOCKER_PLATFORM) docker compose build + mkdir -p $(dir $(DOCKER_BUNDLE)) + docker save $(DOCKER_IMAGES) | gzip > $(DOCKER_BUNDLE) + +docker-load: + gunzip -c $(DOCKER_BUNDLE) | docker load diff --git a/db/migrations/20260930120000_payment_texts.down.sql b/db/migrations/20260930120000_payment_texts.down.sql deleted file mode 100644 index d61702c..0000000 --- a/db/migrations/20260930120000_payment_texts.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS payment_texts; diff --git a/db/migrations/20260930120000_payment_texts.up.sql b/db/migrations/20260930120000_payment_texts.up.sql deleted file mode 100644 index 9e9afe2..0000000 --- a/db/migrations/20260930120000_payment_texts.up.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Admin-editable texts shown to clients around a visa/master/sber payout --- (e.g. the warning before paying). Clients look a text up by its fixed --- code, so codes are seeded here and never created/deleted from the admin --- UI - only name/text/is_active are editable. text is {"tm","ru","en"}. -CREATE TABLE IF NOT EXISTS payment_texts ( - id bigserial PRIMARY KEY, - code character varying(64) NOT NULL, - name character varying(255) NOT NULL, - text jsonb NOT NULL DEFAULT '{"tm":"","ru":"","en":""}'::jsonb, - is_active boolean NOT NULL DEFAULT true, - updated_by bigint, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - CONSTRAINT payment_texts_code_key UNIQUE (code), - CONSTRAINT payment_texts_updated_by_fkey - FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL -); - -INSERT INTO payment_texts (code, name, text) VALUES - ('payment_warning_text', 'Visa/Master töleg duýduryş', - '{"tm":"Dogry töleg aýyny saýlamagyňyzy haýyş edýäris","ru":"","en":""}'::jsonb), - ('sber_payment_warning', 'Sber töleg duýduryş', - '{"tm":"Sber töleg duýduryş","ru":"","en":""}'::jsonb) -ON CONFLICT (code) DO NOTHING; diff --git a/deployment/Dockerfile.minio b/deployment/Dockerfile.minio index 2904a0e..ff71207 100755 --- a/deployment/Dockerfile.minio +++ b/deployment/Dockerfile.minio @@ -1,4 +1,33 @@ -FROM quay.io/minio/minio +# MinIO no longer publishes images (quay.io/minio/minio and minio/minio are not +# pullable), so the server binary comes from minio.deb next to this file. +# Both stages use golang:1.26.4-alpine, which is already in the offline bundle, +# so this builds without network. + +FROM golang:1.26.4-alpine AS extract + +WORKDIR /tmp/deb + +COPY minio.deb . + +# A .deb is an ar archive and busybox here has no `ar`, so read it by hand: +# 8-byte magic, then per member a 60-byte header (name at 1-16, size at 49-58), +# the data, and one pad byte when the size is odd. +RUN set -e; \ + f=minio.deb; off=8; total=$(stat -c %s "$f"); \ + while [ "$off" -lt "$total" ]; do \ + name=$(tail -c +$((off + 1)) "$f" | head -c 16 | tr -d ' /'); \ + size=$(tail -c +$((off + 49)) "$f" | head -c 10 | tr -d ' '); \ + if [ "$name" = "data.tar.gz" ]; then \ + tail -c +$((off + 61)) "$f" | head -c "$size" | tar -xzf - ./usr/local/bin/minio; \ + break; \ + fi; \ + off=$((off + 60 + size + size % 2)); \ + done; \ + ./usr/local/bin/minio --version + +FROM golang:1.26.4-alpine + +COPY --from=extract /tmp/deb/usr/local/bin/minio /usr/bin/minio RUN mkdir /storage @@ -8,4 +37,4 @@ ENV MINIO_VOLUMES="/storage" EXPOSE 9000 EXPOSE 9093 -CMD ["minio", "server", "/storage", "--console-address", ":9093"] \ No newline at end of file +CMD ["minio", "server", "/storage", "--console-address", ":9093"] diff --git a/docker-compose.yaml b/docker-compose.yaml index f616bfa..46610bf 100755 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,5 +1,6 @@ services: main-db: + # Keep in sync with the runtime stage in Dockerfile: pg_dump must match this major version. image: postgres:14.1-alpine container_name: "main-db" restart: always @@ -11,31 +12,44 @@ services: - '5424:5432' volumes: - main-db-storage:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U bank_admin -d bank_db"] + interval: 5s + timeout: 5s + retries: 20 networks: - myNetwork main-server: - image: main-app + image: main-app:latest restart: unless-stopped container_name: "main-app" build: context: . dockerfile: Dockerfile + environment: + - TZ=Asia/Ashgabat ports: - "5050:5050" volumes: + # Inside this network the config must point at main-db:5432 and main-minio:9000. + - ./config.yaml:/app/config.yaml:ro - ./public:/app/public + - ./logs:/app/logs depends_on: - - main-db - - main-minio + main-db: + condition: service_healthy + main-minio: + condition: service_started networks: - myNetwork main-minio: + image: main-minio:latest container_name: "main-minio" build: - context: . - dockerfile: deployment/Dockerfile.minio + context: ./deployment + dockerfile: Dockerfile.minio restart: unless-stopped environment: - MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z @@ -54,4 +68,4 @@ volumes: networks: myNetwork: - driver: bridge \ No newline at end of file + driver: bridge diff --git a/internal/dashboard/handler.go b/internal/dashboard/handler.go index a294e3b..05c299c 100644 --- a/internal/dashboard/handler.go +++ b/internal/dashboard/handler.go @@ -10,6 +10,7 @@ import ( "online-back/internal/identity/rbac" "online-back/internal/identity/rbac/perm" "online-back/pkg/logging" + "online-back/pkg/sysstats" "github.com/gin-gonic/gin" ) @@ -24,15 +25,18 @@ const ( type handler struct { logger *logging.Logger repository Repository + // diskPaths are the mount points reported by /server-stats. + diskPaths []string } -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: repository} +func NewHandler(logger *logging.Logger, repository Repository, diskPaths []string) handlers.Handler { + return &handler{logger: logger, repository: repository, diskPaths: diskPaths} } func (h *handler) Register(router *gin.RouterGroup) { group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard)) group.GET("/overview", h.overview) + group.GET("/server-stats", h.serverStats) } // overview godoc @@ -65,6 +69,26 @@ func (h *handler) overview(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } +// serverStats godoc +// @Summary Server statistics +// @Description Returns host CPU, RAM and disk usage plus the API process's own memory and uptime. CPU usage is sampled over ~250ms; host fields are null when the OS cannot report them. +// @Tags dashboard +// @Produce json +// @Security BearerAuth +// @Success 200 {object} appresult.AppSuccess{data=sysstats.Stats} +// @Failure 500 {object} appresult.AppError +// @Router /dashboard/server-stats [get] +func (h *handler) serverStats(c *gin.Context) { + stats, err := sysstats.Collect(c.Request.Context(), h.diskPaths) + if err != nil { + h.logger.Errorf("dashboard server stats failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(stats)) +} + func parseOverviewFilter(c *gin.Context) (OverviewFilter, bool) { filter := OverviewFilter{ Year: time.Now().Year(), diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index 3b0c623..7897a19 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -80,7 +80,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin. currencyRepo := currencydb.NewRepository(client, logger) payment.Register(adminGroup, client, logger, currencyRepo, paymentGatewayClient(cfg, logger), cfg.PublicBaseURL) currency.NewHandler(logger, currencyRepo).Register(adminGroup) - dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger)).Register(adminGroup) + dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger), []string{"/", cfg.PublicFilePath}).Register(adminGroup) analytics.NewHandler(logger, analyticsdb.NewRepository(client, logger)).Register(adminGroup) backupDir := filepath.Join(cfg.PublicFilePath, "backups") diff --git a/pkg/sysstats/disk_other.go b/pkg/sysstats/disk_other.go new file mode 100644 index 0000000..e44f396 --- /dev/null +++ b/pkg/sysstats/disk_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package sysstats + +import "errors" + +func diskUsage(string) (Disk, error) { return Disk{}, errors.New("disk stats unsupported") } diff --git a/pkg/sysstats/disk_unix.go b/pkg/sysstats/disk_unix.go new file mode 100644 index 0000000..f8a379e --- /dev/null +++ b/pkg/sysstats/disk_unix.go @@ -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 +} diff --git a/pkg/sysstats/sysstats.go b/pkg/sysstats/sysstats.go new file mode 100644 index 0000000..391138e --- /dev/null +++ b/pkg/sysstats/sysstats.go @@ -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 +} diff --git a/pkg/sysstats/sysstats_linux.go b/pkg/sysstats/sysstats_linux.go new file mode 100644 index 0000000..c407df7 --- /dev/null +++ b/pkg/sysstats/sysstats_linux.go @@ -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 +} diff --git a/pkg/sysstats/sysstats_other.go b/pkg/sysstats/sysstats_other.go new file mode 100644 index 0000000..a96f485 --- /dev/null +++ b/pkg/sysstats/sysstats_other.go @@ -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 }