Sidecar that bridges short-lived and non-Go applications (PHP, cron jobs, scripts) to Prometheus-compatible monitoring. It accepts newline-delimited JSON metric payloads over a Unix domain socket, accumulates Prometheus counters, gauges and histograms in memory, and either exposes them over HTTP for Prometheus or vmagent to scrape (pull-mode) or pushes them over HTTP on a fixed interval (push-mode) to vmagent, to Prometheus and other remote write receivers, or to a Pushgateway.
Two roles:
- Pull-mode - sidecar in long-lived pods. Unix socket in,
:9099/metricsout, scraped by Prometheus or vmagent. - Push-mode - sidecar in cron or batch pods that live too short to be scraped. Unix socket in, periodic HTTP POST
to
-vmagent-url, and a final flush on shutdown. The payload is the Prometheus text format (vmagent/api/v1/import/prometheus, Pushgateway) or Prometheus remote write (Prometheus, VictoriaMetrics, Mimir, Thanos), see Push targets. Push-mode is enabled when-remoteis set to any non-empty value (the value itself is ignored, the URL is read from-vmagent-url).
- Quick start
- Installation
- Flags
- Wire format
- Modes
- Self metrics
- Restrictions
- Security
- Development
- Contributing
- License
Pull-mode with a socket in a named volume that the application container shares:
docker volume create metrics-socket
docker run -d --name metrics-server \
-v metrics-socket:/run/metrics-server \
-p 9099:9099 \
ghcr.io/tentens-tech/metrics-server:latest
# Send a metric through the socket (from any container that mounts the volume)
docker run --rm -i -v metrics-socket:/run/metrics-server alpine/socat \
- UNIX-CONNECT:/run/metrics-server/metric-server.sock \
<<< '{"name":"smoke","labels":{"a":"1"},"op":"inc","value":1}'
curl -s localhost:9099/metrics | grep smokeThe image is based on distroless, runs as the unprivileged user 1010:1010 (--build-arg UID=... GID=... to change it) and works with a read-only root filesystem.
The default socket is /run/metrics-server/metric-server.sock.
The application container and the sidecar share the socket directory through an emptyDir.
apiVersion: v1
kind: Pod
metadata:
name: app
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9099"
spec:
volumes:
- name: metrics-socket
emptyDir: {}
containers:
- name: app
image: example/app:latest
volumeMounts:
- name: metrics-socket
mountPath: /run/metrics-server
- name: metrics-server
image: ghcr.io/tentens-tech/metrics-server:latest
args:
- -uds=/run/metrics-server/metric-server.sock
- -socket=:9099
- -extra-labels=app:my-app
- -shutdown-delay=5s
ports:
- name: metrics
containerPort: 9099
readinessProbe:
httpGet:
path: /health
port: metrics
livenessProbe:
httpGet:
path: /livez
port: metrics
securityContext:
runAsNonRoot: true
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
volumeMounts:
- name: metrics-socket
mountPath: /run/metrics-serverFor a cron pod, use push-mode instead:
args:
- -uds=/run/metrics-server/metric-server.sock
- -remote=enabled
- -vmagent-url=http://vmagent.monitoring.svc.cluster.local:8429/api/v1/import/prometheus
# or straight into Prometheus (started with --web.enable-remote-write-receiver):
# - -vmagent-url=http://prometheus.monitoring.svc.cluster.local:9090/api/v1/write
- -vmagent-push-interval=15sA complete CronJob is in examples/kubernetes/push-cronjob.yaml.
go run main.go -uds ./metric-server.sock -socket :9099
# in another shell:
echo '{"name":"smoke","labels":{"a":"1"},"op":"inc","value":1}' | nc -U ./metric-server.sock -w 1
curl -s localhost:9099/metrics | grep smokePush-mode:
go run main.go -uds ./metric-server.sock -remote=enabled \
-vmagent-url=http://localhost:8429/api/v1/import/prometheus \
-vmagent-push-interval=2s
echo '{"name":"smoke","labels":{"a":"1"},"op":"inc","value":1}' | nc -U ./metric-server.sock -w 1
# observe POSTs at the vmagent endpointPush-mode into a local Prometheus: docker compose -f examples/docker-compose.prometheus.yaml up, see
Push targets.
Sample payloads are in client/metrics.json. Reference clients are client/main.go (Go) and client/client.php (PHP).
Multi-arch images (linux/amd64, linux/arm64) are published to the GitHub Container Registry:
docker pull ghcr.io/tentens-tech/metrics-server:latest # latest release
docker pull ghcr.io/tentens-tech/metrics-server:v1.4.1 # a specific releaseImages are signed with cosign and carry an SBOM and a provenance attestation, see Verifying releases.
Binaries for linux/amd64 and linux/arm64 and their checksums.txt are attached to every
GitHub release:
VERSION=v1.4.1
curl -fsSLO "https://github.com/tentens-tech/metrics-server/releases/download/${VERSION}/metrics-server_${VERSION}_linux_amd64.tar.gz"
tar xzf "metrics-server_${VERSION}_linux_amd64.tar.gz" metrics-servergo install github.com/tentens-tech/metrics-server@latest-debug enable debug log level
-socket <addr> HTTP /metrics listen addr (pull-mode only, default :9099)
-uds <path> primary UDS listen path (default ./metric-server.sock)
-uds-pool <p1,p2,...> additional UDS listen paths
-uds-mode <octal> permission bits of the socket files (default 0777)
-extra-labels <k:v,k:v> inline labels added to every metric
-extra-labels-file-path <path> Java-properties-style file with extra labels
-shutdown-delay <duration> delay before exit on SIGTERM (default 0s)
-metric-clean-up enable TTL cleanup
-metric-ttl <duration> TTL for cleanup (default 24h)
-pyroscope-url <url> Pyroscope endpoint (optional)
-remote <any> push-mode toggle; any non-empty value enables push-mode
-vmagent-url <url> push endpoint (push-mode only): vmagent, Prometheus remote write receiver
or Pushgateway, see Push targets
(default http://vmagent-vmagent.monitoring.svc.cluster.local:8429/api/v1/import/prometheus)
-push-format <format> push payload format: auto, text or remote-write (default auto)
-vmagent-push-interval <dur> push period (default 15s)
-vmagent-push-timeout <dur> HTTP timeout per push (default 5s)
Notes:
-extra-labelsand-extra-labels-file-pathlabels are added to every metric. In the file, onekey=valueper line.-metric-clean-upremoves a time series that has not been updated for-metric-ttl. The clean-up runs every-metric-ttl(plus 1%) on its own, also when no new events arrive, so a series is gone at most about two TTLs after its last update.-remoteis kept for compatibility: its value is ignored and any non-empty value enables push-mode.-vmagent-urland the-vmagent-push-*flags keep their names for compatibility; they apply to every push target.-push-format=autouses the text format for Pushgateway URLs (the path contains/metrics/job/), remote write when the-vmagent-urlpath ends with/api/v1/write,/api/v1/push,/api/v1/receiveor/api/prom/push, and the text format otherwise. An unknown value stops the start with an error.-shutdown-delaymakes/health(and/readyz) return503while the process waits, so Kubernetes can stop routing before exit./livezstays200, see Health endpoints.-socketis not used in push-mode: no HTTP listener is started.
Newline-delimited JSON over a Unix domain socket. One object per metric event:
op |
Semantics |
|---|---|
inc |
Counter accumulation (delta) |
set |
Gauge overwrite |
obs |
Histogram observation |
Counter increments must be non-negative numbers, other values are dropped with a warning.
{"name":"metric_name","help":"description","labels":{"k":"v"},"op":"inc","value":1.0}{"name":"metric_name","help":"description","labels":{"k":"v"},"op":"set","value":1.0}{"name":"metric_request_duration_ms","labels":{"k":"v"},"op":"obs","value":2.0}Optional bucket configuration fields on the first observation:
buckets(int) - number of buckets (default 20, at most 1000)bucket_width(float) - linear bucket width (default 10)bucket_start(float) - first linear bucket boundary (default 0)bucket_min,bucket_max- exponential rangebucket_factor- exponential factorbucket_custom([float]) - explicit bucket boundaries
When several are given, the first match wins: exponential range (bucket_min and bucket_max), then
bucket_factor, then bucket_custom, then linear buckets. Boundaries must be strictly increasing.
| Pull-mode | Push-mode | |
|---|---|---|
| Enabled by | default | -remote=<any non-empty value> |
| Output | HTTP GET :9099/metrics, /health, /readyz, /livez |
HTTP POST to -vmagent-url every -vmagent-push-interval, text format or remote write |
| Best for | long-lived pods | cron jobs and short-lived pods |
| On shutdown | stops after -shutdown-delay |
stops the pusher and flushes the final batch |
On SIGTERM or SIGINT the server:
- marks itself not ready (
/healthand/readyzreturn503) and waits-shutdown-delay; - closes its sockets, so no new clients connect, and removes the socket files;
- lets connected clients finish for up to 1 second, then closes their connections;
- processes every event received so far;
- pushes once more (push-mode), so events written right before the signal are delivered;
- exits with status 0.
Steps 2 to 4 take at most 5 seconds; events still in flight after that are lost and a warning is logged. The final push
is bounded by -vmagent-push-timeout. Keep terminationGracePeriodSeconds above -shutdown-delay plus these bounds.
The server creates all its sockets before it reports ready. When a socket cannot be created (missing directory, no permission, a file that is not a socket at the path), it exits with status 1 and an error that names the socket.
In pull-mode the HTTP listener serves, besides /metrics:
| Path | Status | Use as |
|---|---|---|
/health |
200 when ready, 503 from SIGTERM on |
readiness probe |
/readyz |
same as /health |
readiness probe |
/livez |
200 as long as the process serves HTTP, also during shutdown |
liveness probe |
Do not use /health as a liveness probe together with -shutdown-delay: it fails on purpose during the delay, and the
kubelet could kill the container before the shutdown is complete.
Up to 1024 clients can be connected to the sockets at the same time, and a client may buffer up to 64 KiB
of an unterminated JSON object. Malformed lines are logged and dropped, they do not stop the server.
-push-format selects the payload. With the default auto it follows from the path of -vmagent-url: a path with
/metrics/job/ is a Pushgateway grouping key and gets text (even when a grouping value looks like a remote write
path, as in /metrics/job/api/v1/push), the remote write suffixes below get remote-write, anything else text:
| Target | -vmagent-url |
Format picked by auto |
|---|---|---|
| vmagent, VictoriaMetrics (import) | http://vmagent:8429/api/v1/import/prometheus |
text |
| Prometheus (remote write receiver) | http://prometheus:9090/api/v1/write |
remote-write |
| vmagent, VictoriaMetrics (remote write) | http://vmagent:8429/api/v1/write |
remote-write |
| Grafana Mimir, Cortex | http://mimir:8080/api/v1/push |
remote-write |
| Thanos Receive | http://thanos-receive:19291/api/v1/receive |
remote-write |
| Grafana Cloud, Cortex (legacy path) | https://prometheus-prod.grafana.net/api/prom/push |
remote-write |
| Pushgateway | http://pushgateway:9091/metrics/job/<job> |
text |
textPOSTs the Prometheus text exposition format withContent-Type: text/plain.remote-writePOSTs a Prometheus remote write 1.0WriteRequest: snappy compressed protobuf withContent-Encoding: snappy,Content-Type: application/x-protobufandX-Prometheus-Remote-Write-Version: 0.1.0. Counters, gauges and untyped metrics become one series each, histograms_bucketseries (withle, including+Inf),_sumand_count. Every sample carries the push time, so a series shows the value of the last push. TheHELP,TYPEand unit of each family are sent as metadata. TheUser-Agentismetrics-server/<version>.- Remote write labels follow the specification: a label with an empty value is left out (Prometheus treats it as
absent, so
-extra-labels=env:adds nothing), and labels with a name outside[a-zA-Z_][a-zA-Z0-9_]*, a value that is not valid UTF-8, or a name that is already taken (__name__, theleof a histogram bucket, thequantileof a summary) are dropped with a warning, logged at most once a minute. - When a series that was pushed with remote write disappears, for example removed by
-metric-clean-up, the next push sends a stale marker for it, so it ends at once instead of after the query lookback (5 minutes in Prometheus). - Set
-push-formatexplicitly when the path does not tell, for example a remote write receiver behind a proxy path.
vmagent (the default):
metrics-server -remote=enabled \
-vmagent-url=http://vmagent:8429/api/v1/import/prometheusPrometheus 2.33 or newer, started with --web.enable-remote-write-receiver:
prometheus --config.file=prometheus.yml --web.enable-remote-write-receiver
metrics-server -remote=enabled -extra-labels=job:report \
-vmagent-url=http://prometheus:9090/api/v1/writeexamples/docker-compose.prometheus.yaml runs this setup locally.
Pushgateway: the URL carries the grouping key, each push replaces the metrics of the group with the same names:
metrics-server -remote=enabled \
-vmagent-url=http://pushgateway:9091/metrics/job/report/instance/eu1The Pushgateway keeps the last pushed values until the group is deleted, also after the job is gone.
Pushed series have no scrape target, so they get no job and instance labels from the receiver (the Pushgateway adds
the ones of the grouping key). Use -extra-labels to identify the source.
Only a 2xx answer is a successful push. Redirects are followed only with 307 and 308, which resend the POST; a
301, 302 or 303 would turn it into a GET without body and is counted as error_3xx. A remote write push answered
with 5xx or 429, or failing in transport, is sent again unchanged up to 3 times in total, after 0.5s and 1s, as long
as it fits in -vmagent-push-interval (-vmagent-push-timeout for the final flush on shutdown); other 4xx are not
retried. Text pushes are not retried, the next push sends the current values again. Failed pushes are logged and
counted in metrics_server_vmagent_push_total{result}.
| Metric | Type | Description |
|---|---|---|
metrics_server_processed_metrics_total{type} |
counter | Events applied, by operation (inc, set, obs) |
metrics_server_events_dropped_total{reason} |
counter | Events dropped: registration_conflict, invalid_value, invalid_buckets, malformed, oversized, unknown_op, panic, see Restrictions |
metrics_server_deleted_metrics_total{type} |
counter | Series removed by TTL clean-up |
metrics_server_staled_storage_length |
gauge | Series tracked for TTL clean-up |
metrics_server_staled_clean_up_duration_seconds |
histogram | Duration of a clean-up run |
metrics_server_vmagent_push_total{result} |
counter | Pushes by final outcome: success, error_3xx, error_4xx, error_5xx, error_transport, error_gather, error_encode (push-mode; a retried push counts once) |
metrics_server_vmagent_push_retries_total |
counter | Remote write push retries (push-mode) |
metrics_server_vmagent_push_duration_seconds |
histogram | Duration of push HTTP calls, retries included (push-mode) |
metrics_server_vmagent_push_bytes |
histogram | Size of push payloads (push-mode; compressed size for remote write) |
A given metric name may only be registered with one set of label keys, one type and one help text. Once a name is
registered, every event that uses it with other label keys, another type or another help text is dropped, as are events
with a name or label name that Prometheus does not accept. Each of them is counted in
metrics_server_events_dropped_total{reason="registration_conflict"} and logged as an error.
Invalid events (malformed JSON, negative counter increments, invalid bucket configurations, oversized payloads) are
dropped as well and counted with their own reason. The log of dropped events is rate-limited to one message per reason
and minute; the counter counts every event.
- The collector sockets are created with mode
0777by default so that clients running under any uid can write to them. Restrict it with-uds-mode(for example-uds-mode=0660) and share the socket directory only with the application container. - The
/metrics,/health,/readyzand/livezendpoints have no authentication. Do not expose the port outside the pod network. - Release images and binaries are signed and attested, see SECURITY.md for how to verify them and how to report a vulnerability privately.
make test # unit tests with the race detector
make fuzz # fuzz tests, 30s each
make lint # golangci-lint
make vuln # govulncheck
make e2e # end-to-end tests in Docker (needs Docker)
make docker-buildSee CONTRIBUTING.md for the full workflow.
Contributions are welcome. Please read CONTRIBUTING.md and the Code of Conduct first. Report security issues privately, see SECURITY.md.
Apache License 2.0, see LICENSE.