diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5bf06dc..78a8d8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,7 @@ env: REGISTRY: registry.plusclouds.com IMAGE: monitoring IMAGE_GRAFANA: monitoring-grafana + IMAGE_AGENT: monitoring-agent jobs: lint: @@ -99,6 +100,7 @@ jobs: echo "version=$version" >> "$GITHUB_OUTPUT" echo "tags=-t $REGISTRY/$IMAGE:$version -t $REGISTRY/$IMAGE:latest" >> "$GITHUB_OUTPUT" echo "grafana_tags=-t $REGISTRY/$IMAGE_GRAFANA:$version -t $REGISTRY/$IMAGE_GRAFANA:latest" >> "$GITHUB_OUTPUT" + echo "agent_tags=-t $REGISTRY/$IMAGE_AGENT:$version -t $REGISTRY/$IMAGE_AGENT:latest" >> "$GITHUB_OUTPUT" # Building needs no credentials (public base images), so it uses its own # Docker config: ~/.docker/buildx on the shared runner is root-owned @@ -117,6 +119,21 @@ jobs: - name: Check the image runs run: docker run --rm "$REGISTRY/$IMAGE:${{ steps.tags.outputs.version }}" version + # The monitoring agent (F15), to COPY --from into other images + # (Dockerfile.agent). + - name: Build agent image + env: + DOCKER_CONFIG: ${{ runner.temp }}/docker-build + run: | + docker build --pull -f Dockerfile.agent \ + --build-arg VERSION=${{ github.ref_name }} \ + --build-arg COMMIT=${{ github.sha }} \ + --label org.opencontainers.image.revision=${{ github.sha }} \ + ${{ steps.tags.outputs.agent_tags }} . + + - name: Check the agent image runs + run: docker run --rm "$REGISTRY/$IMAGE_AGENT:${{ steps.tags.outputs.version }}" version + # Grafana with the dashboards baked in (deploy/grafana/Dockerfile). - name: Build Grafana image env: @@ -134,6 +151,7 @@ jobs: run: | docker image push --all-tags "$REGISTRY/$IMAGE" docker image push --all-tags "$REGISTRY/$IMAGE_GRAFANA" + docker image push --all-tags "$REGISTRY/$IMAGE_AGENT" # Remove only this build's images: a full prune would also delete # other repositories' images and build cache on the shared runner. @@ -142,4 +160,5 @@ jobs: run: | docker image ls --format '{{.Repository}}:{{.Tag}}' "$REGISTRY/$IMAGE" | xargs -r docker image rm -f docker image ls --format '{{.Repository}}:{{.Tag}}' "$REGISTRY/$IMAGE_GRAFANA" | xargs -r docker image rm -f + docker image ls --format '{{.Repository}}:{{.Tag}}' "$REGISTRY/$IMAGE_AGENT" | xargs -r docker image rm -f docker image prune -f diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c95c10..5ac9a7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Notable changes per release. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions are git tags. The project is pre-1.0: the API can change between minor versions. Per-milestone detail is in [docs/progress.md](docs/progress.md). +## [Unreleased] +### Added +- Monitoring agent (`cmd/agent`, F15): one static binary to copy into any Docker image (`COPY --from=registry.plusclouds.com/monitoring-agent /agent ...`, `ENTRYPOINT ["agent","run","--", ...]`) or run as a sidecar. Collectors: host/container (cgroup-aware), Docker engine, tcp/http/process probes, redis, postgres, nginx, php-fpm, elasticsearch, node.js. See `docs/agent.md` and ADR-0016. +- `host.agent` ingester plugin and push token for it (weight 2 in usage metering, to be confirmed); unique `agent_id` per tenant (migration 00026). +- `Dockerfile.agent`, `make build-agent`, CI builds and pushes `monitoring-agent` with every version tag. +- Grafana dashboard "Agents: hosts, containers and services". +- `elasticsearch.cluster` collector: cluster health and shards, per-node heap, CPU, disk, old-generation GC and rejected requests, and the largest indices (documents, size, health) as objects. Optional `http_basic` or `http_bearer` credential. Each node bills as `elasticsearch.cluster:node` (weight 3, TBD with billing). +- Grafana dashboard "Elasticsearch clusters". + ## [0.14.1] - 2026-10-12 ### Fixed - Lint failure (unnecessary conversion) in device notifications. diff --git a/Dockerfile.agent b/Dockerfile.agent new file mode 100644 index 0000000..afc51cd --- /dev/null +++ b/Dockerfile.agent @@ -0,0 +1,36 @@ +# The monitoring agent (F15): one static binary, built to be copied into any +# Docker image at build time, or run as a sidecar. +# +# In your own Dockerfile (any base image, with or without a shell): +# +# COPY --from=registry.plusclouds.com/monitoring-agent:latest /agent /usr/local/bin/agent +# ENTRYPOINT ["/usr/local/bin/agent", "run", "--", "nginx", "-g", "daemon off;"] +# +# As a sidecar (watches the Docker engine through the mounted socket): +# +# docker run -e AGENT_URL=... -e AGENT_TOKEN=... registry.plusclouds.com/monitoring-agent +# +# Build with: +# docker build -f Dockerfile.agent --build-arg VERSION=$(git describe --tags --always) -t monitoring-agent . +FROM golang:1.27 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +ARG VERSION=dev +ARG COMMIT= +RUN CGO_ENABLED=0 go build -trimpath \ + -ldflags "-s -w -X github.com/plusclouds/monitoring.server/internal/buildinfo.Version=${VERSION} -X github.com/plusclouds/monitoring.server/internal/buildinfo.Commit=${COMMIT}" \ + -o /out/agent ./cmd/agent + +# distroless/static carries the CA certificates the agent needs for HTTPS. +FROM gcr.io/distroless/static-debian12:nonroot +ARG VERSION=dev +LABEL org.opencontainers.image.title="monitoring-agent" \ + org.opencontainers.image.description="Monitoring agent for Docker images and hosts" \ + org.opencontainers.image.source="https://github.com/plusclouds/monitoring.server" \ + org.opencontainers.image.licenses="MIT" \ + org.opencontainers.image.version="${VERSION}" +COPY --from=build /out/agent /agent +ENTRYPOINT ["/agent"] +CMD ["daemon"] diff --git a/Makefile b/Makefile index 3b37609..b4fe449 100644 --- a/Makefile +++ b/Makefile @@ -2,17 +2,21 @@ GO ?= go BIN ?= bin/monitor +AGENT_BIN ?= bin/agent VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) LDFLAGS := -s -w -X github.com/plusclouds/monitoring.server/internal/buildinfo.Version=$(VERSION) # Licenses allowed for linked dependencies (ADR-0010). ALLOWED_LICENSES := MIT,BSD-2-Clause,BSD-3-Clause,Apache-2.0,ISC,MPL-2.0 -.PHONY: build test lint vuln licenses tidy-check generate generate-check check fuzz +.PHONY: build build-agent test lint vuln licenses tidy-check generate generate-check check fuzz build: CGO_ENABLED=0 $(GO) build -trimpath -ldflags '$(LDFLAGS)' -o $(BIN) ./cmd/monitor +build-agent: + CGO_ENABLED=0 $(GO) build -trimpath -ldflags '$(LDFLAGS)' -o $(AGENT_BIN) ./cmd/agent + test: $(GO) test -race ./... $(MAKE) fuzz @@ -24,6 +28,7 @@ fuzz: $(GO) test ./plugins/push -run '^$$' -fuzz '^FuzzDecode$$' -fuzztime $(FUZZTIME) $(GO) test ./plugins/vmagent -run '^$$' -fuzz '^FuzzDecode$$' -fuzztime $(FUZZTIME) $(GO) test ./plugins/boxagent -run '^$$' -fuzz '^FuzzDecode$$' -fuzztime $(FUZZTIME) + $(GO) test ./plugins/hostagent -run '^$$' -fuzz '^FuzzParse$$' -fuzztime $(FUZZTIME) lint: golangci-lint run ./... diff --git a/README.md b/README.md index 70a959e..5ba903f 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ An API-first, extensible monitoring engine written in Go. One engine watches network devices, server hardware (BMCs), IP cameras, web endpoints and ports, hypervisors and their VMs, and IoT/facility devices, and turns what it sees into incidents and signed webhook events. -> **Status: v0.14, pre-1.0.** Scheduling, state, incidents, signed webhooks, metrics, Grafana dashboards and plugins for HTTP, ICMP, SNMP, Redfish, XCP-ng, cameras, HTTP/MQTT push and UPS/PDU all run today. Remote probes, VMware/Proxmox and the Phase 2 and 3 items in the [roadmap](#roadmap) do not exist yet. The API can still change before 1.0; see the [changelog](CHANGELOG.md) and [implementation progress](docs/progress.md). +> **Status: v0.14, pre-1.0.** Scheduling, state, incidents, signed webhooks, metrics, Grafana dashboards and plugins for HTTP, ICMP, SNMP, Redfish, XCP-ng, cameras, HTTP/MQTT push, UPS/PDU, Elasticsearch and a monitoring agent for Docker images all run today. Remote probes, VMware/Proxmox and the Phase 2 and 3 items in the [roadmap](#roadmap) do not exist yet. The API can still change before 1.0; see the [changelog](CHANGELOG.md) and [implementation progress](docs/progress.md). -**No built-in UI, by design.** The engine is an API; dashboards are [Grafana](deploy/grafana/README.md), reading PostgreSQL directly, with seven ready-made dashboards (devices and incidents, websites, network interfaces, server hardware, power, cameras, XCP-ng) provisioned for you. If you want a point-and-click admin UI instead, this is not that tool yet. +**No built-in UI, by design.** The engine is an API; dashboards are [Grafana](deploy/grafana/README.md), reading PostgreSQL directly, with nine ready-made dashboards (devices and incidents, websites, network interfaces, server hardware, power, cameras, XCP-ng, Elasticsearch, agents) provisioned for you. If you want a point-and-click admin UI instead, this is not that tool yet. @@ -46,6 +46,8 @@ After a few failed runs a signed `monitoring.incident.opened` event arrives at y | IP cameras | ICMP, RTSP, ONVIF, HTTP snapshot | Reachability, codec, resolution, FPS, bitrate, RTP loss/jitter | | Web and services | HTTP(S), TCP, UDP, DNS, TLS, WHOIS | Status code, keyword match, timing breakdown, certificate and domain expiry | | Hypervisors and VMs | XenServer/XCP-ng first, then VMware, then Proxmox | Host CPU/memory/NIC/storage, per-VM CPU ready/steal, memory, disk latency, snapshots | +| Search clusters | Elasticsearch REST API | Cluster health, shards, per-node heap/CPU/disk/GC/rejections, per-index documents, size and health | +| Docker images and containers | Monitoring agent (`COPY --from` into your image, or a sidecar), HTTP push | Container CPU/memory/disk/network, the wrapped process and its exit code, Docker engine state, health and restarts, PostgreSQL, Redis, nginx, php-fpm, Elasticsearch, Node.js; see [the agent guide](docs/agent.md) | | IoT and facility | MQTT, SNMP (UPS/PDU), HTTP push | UPS battery/runtime, PDU current, temperature/humidity/leak/door sensors, last-seen | | LLMs | Synthetic inference requests, Prometheus scraping, OpenTelemetry GenAI traces | Availability, time to first token, tokens/s, GPU health; per application errors, tokens, cost and quality scores | diff --git a/cmd/agent/main.go b/cmd/agent/main.go new file mode 100644 index 0000000..03ba6be --- /dev/null +++ b/cmd/agent/main.go @@ -0,0 +1,187 @@ +// Command agent is the monitoring agent (F15): one static binary that runs +// inside a Docker image, wrapping the image's own process, or beside it as a +// sidecar, and reports host, container, probe and service metrics to the +// monitoring server over HTTP. +// +// agent run -- nginx -g 'daemon off;' wrap the image's process (PID 1) +// agent daemon sidecar or standalone +// agent check collect once and print the report +// agent version +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "syscall" + "time" + + "github.com/plusclouds/monitoring.server/internal/agent" + _ "github.com/plusclouds/monitoring.server/internal/agent/collectors/all" // collectors register themselves + "github.com/plusclouds/monitoring.server/internal/buildinfo" +) + +const defaultConfigPath = "/etc/monitor-agent/agent.yaml" + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "agent:", err) + os.Exit(1) + } +} + +func run(args []string) error { + cmd := "daemon" + if len(args) > 0 && len(args[0]) > 0 && args[0][0] != '-' { + cmd, args = args[0], args[1:] + } + switch cmd { + case "daemon": + return daemon(args) + case "run": + return wrap(args) + case "check": + return check(args) + case "version": + fmt.Printf("agent %s (%s)\n", buildinfo.Version, buildinfo.CommitOrVCS()) + return nil + } + return fmt.Errorf("unknown command %q; use daemon, run, check or version", cmd) +} + +// loadFlags parses --config and loads the config. A missing default file is +// not an error: the environment alone is a complete configuration. +func loadFlags(name string, args []string) (agent.Config, []string, error) { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + def := defaultConfigPath + if v := os.Getenv("AGENT_CONFIG"); v != "" { + def = v + } + path := fs.String("config", def, "config file") + if err := fs.Parse(args); err != nil { + return agent.Config{}, nil, err + } + p := *path + if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) && p == defaultConfigPath { //nolint:gosec // the operator chooses the config file + p = "" + } + cfg, err := agent.LoadConfig(p, nil) + return cfg, fs.Args(), err +} + +func newLogger() *slog.Logger { + return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{})) +} + +// build makes the agent and its pusher from a loaded config. +func build(cfg agent.Config, log *slog.Logger) (*agent.Agent, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + a, err := agent.New(cfg, buildinfo.Version, log) + if err != nil { + return nil, err + } + p, err := agent.NewPusher(cfg) + if err != nil { + return nil, err + } + a.SetPusher(p) + return a, nil +} + +func daemon(args []string) error { + cfg, _, err := loadFlags("daemon", args) + if err != nil { + return err + } + log := newLogger() + a, err := build(cfg, log) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + log.Info("agent started", "agent_id", cfg.AgentID, "interval", cfg.Interval.String(), "version", buildinfo.Version) + a.Run(ctx) + return nil +} + +// check collects once and prints the report; with --send it also delivers it. +func check(args []string) error { + cfg, _, err := loadFlags("check", args) + if err != nil { + return err + } + log := newLogger() + a, err := agent.New(cfg, buildinfo.Version, log) + if err != nil { + return err + } + // Rates need two samples. + a.Collect(context.Background()) + time.Sleep(time.Second) + r := a.Collect(context.Background()) + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(r) +} + +// wrap runs the image's own process under the agent. Whatever is wrong with +// the agent's setup, the process starts: monitoring never takes the service +// down. +func wrap(args []string) error { + fs := flag.NewFlagSet("run", flag.ContinueOnError) + def := defaultConfigPath + if v := os.Getenv("AGENT_CONFIG"); v != "" { + def = v + } + path := fs.String("config", def, "config file") + if err := fs.Parse(args); err != nil { + return err + } + cmdline := fs.Args() + log := newLogger() + + p, err := agent.StartProcess(cmdline) + if err != nil { + return fmt.Errorf("start %v: %w", cmdline, err) + } + + var a *agent.Agent + cfgPath := *path + if _, err := os.Stat(cfgPath); errors.Is(err, os.ErrNotExist) && cfgPath == defaultConfigPath { //nolint:gosec // the operator chooses the config file + cfgPath = "" + } + if cfg, err := agent.LoadConfig(cfgPath, nil); err != nil { + log.Error("monitoring disabled: config", "error", err) + } else if a, err = build(cfg, log); err != nil { + log.Error("monitoring disabled", "error", err) + a = nil + } + + if a == nil { + <-p.Done() + os.Exit(p.ExitCode()) + } + a.Extra = func() []agent.Object { return []agent.Object{p.Object()} } + ctx, cancel := context.WithCancel(context.Background()) + loop := make(chan struct{}) + go func() { a.Run(ctx); close(loop) }() + + <-p.Done() + cancel() + <-loop + // One last report says why the process ended; the silence after it is + // the server's last-seen rule. + fctx, fcancel := context.WithTimeout(context.Background(), 10*time.Second) + a.Tick(fctx) + fcancel() + os.Exit(p.ExitCode()) + return nil +} diff --git a/deploy/agent/agent.example.yaml b/deploy/agent/agent.example.yaml new file mode 100644 index 0000000..f3b39ce --- /dev/null +++ b/deploy/agent/agent.example.yaml @@ -0,0 +1,77 @@ +# Monitoring agent configuration (F15). Every top-level key has an AGENT_* +# environment variable that wins over the file; with no file at all, the +# environment alone is a complete configuration: +# +# AGENT_URL=https://monitor.example.com/ingest/v1/ +# AGENT_TOKEN_FILE=/run/secrets/agent_token +# AGENT_COLLECTORS=host,redis # settings: AGENT_REDIS_ADDR=127.0.0.1:6379 +# +# Default path: /etc/monitor-agent/agent.yaml (override with AGENT_CONFIG or +# --config). Unknown keys are an error. + +# The check's ingest_url, from the API response that created the host.agent +# check (field push.ingest_url). +url: https://monitor.example.com/ingest/v1/00000000-0000-0000-0000-000000000000 + +# The check's push token (mpush_...), shown once when the check is created. +# Prefer token_file: a Docker or Kubernetes secret. +token_file: /run/secrets/agent_token + +# Must equal the check's config.agent_id. Default: the hostname. +agent_id: web-1 + +# Report interval, at least 5s. Keep it at or below the check's +# interval_seconds: the check goes CRITICAL after missed_count (default 3) +# intervals without a report. +interval: 30s + +# Extra CA certificate for the server's HTTPS certificate (private CA). +# ca_file: /etc/monitor-agent/ca.pem + +# What to collect. Each entry has a type, an optional name (default: the +# type; two entries of one type need distinct names) and the collector's own +# options. Any option can also come from AGENT__