#!/bin/bash
# Checks VictoriaLogs ingestion + storage via its /metrics endpoint.
# CRITICAL if the endpoint is unreachable or storage has gone read-only (out of disk).
# WARNING if nothing has been ingested yet.
RESP=$(curl -sf --max-time 5 http://127.0.0.1:9428/metrics 2>/dev/null) || {
  echo "CRITICAL: VictoriaLogs metrics endpoint unreachable on 127.0.0.1:9428"
  exit 2
}
# vl_rows_ingested_total is reported per input type, so sum every series.
INGESTED=$(echo "$RESP" | awk -F'[ }]' '/^vl_rows_ingested_total/ {sum+=$NF} END {printf "%d", sum+0}')
STORED=$(echo "$RESP" | awk -F'[ }]' '/^vl_data_size_bytes\{type="storage"/ {printf "%d", $NF; exit}')
STORED=${STORED:-0}
READONLY=$(echo "$RESP" | awk '/^vl_storage_is_read_only/ {printf "%d", $2; exit}')
HUMAN=$(numfmt --to=iec "$STORED" 2>/dev/null || echo "${STORED}B")
PERF="| rows_ingested=${INGESTED}c data_size_bytes=${STORED}B"
if [ "${READONLY:-0}" -ne 0 ]; then
  echo "CRITICAL: VictoriaLogs storage is read-only (out of disk space) $PERF"
  exit 2
fi
if [ "$INGESTED" -eq 0 ]; then
  echo "WARNING: VictoriaLogs has 0 ingested rows (no logs?) $PERF"
  exit 1
fi
echo "OK: VictoriaLogs $INGESTED rows ingested, $HUMAN stored $PERF"
exit 0
