add docker
This commit is contained in:
@@ -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
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -77,3 +77,6 @@ bank_db_schema.drawio
|
||||
# Debug
|
||||
__debug_bin
|
||||
debug
|
||||
|
||||
# Docker image bundles (make docker-bundle)
|
||||
dist/
|
||||
|
||||
41
Dockerfile
41
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"]
|
||||
|
||||
24
Makefile
24
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
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
DROP TABLE IF EXISTS payment_texts;
|
||||
@@ -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;
|
||||
@@ -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"]
|
||||
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||
|
||||
@@ -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
|
||||
driver: bridge
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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")
|
||||
|
||||
7
pkg/sysstats/disk_other.go
Normal file
7
pkg/sysstats/disk_other.go
Normal 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
24
pkg/sysstats/disk_unix.go
Normal 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
118
pkg/sysstats/sysstats.go
Normal 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
|
||||
}
|
||||
158
pkg/sysstats/sysstats_linux.go
Normal file
158
pkg/sysstats/sysstats_linux.go
Normal 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
|
||||
}
|
||||
15
pkg/sysstats/sysstats_other.go
Normal file
15
pkg/sysstats/sysstats_other.go
Normal 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 }
|
||||
Reference in New Issue
Block a user