# Shared metric counters for the media scripts. Sourced, never executed. # # VG_MET_COMPONENT=sweep # a plain assignment, NOT a prefix on the next line: # . /usr/local/bin/vgmetrics.sh && vgmet_init # bash discards "VAR=x . file" assignments on return # vgmet_add "jobs:encode:done:stream" # +1 # vgmet_add "seconds:encode:stream" 41.2 # +41.2 # # Counters accumulate across runs in MARK/metrics/.counters as plain "key value" lines, and a # .pid file exists only while the script is executing. dumpd turns both into Prometheus text on # its /metrics; nothing here renders or serves anything, so the scripts stay simple and there is one place # that knows the metric names (bin/dumpd.py COUNTER_MAP). # # Keys are "name:label:label..." — the name picks the metric, the rest fill its labels in order. # Writes are atomic (temp file + mv) and every failure is silent: metrics must never break a sweep. VG_MET_DIR="${VG_MET_DIR:-${MEDIA_ROOT:-/srv/media}/.markers/metrics}" VG_MET_COMPONENT="${VG_MET_COMPONENT:-$(basename "${0%.sh}")}" VG_MET_START=0 declare -A VGMET=() vgmet_init() { : "${VG_MET_DIR:=${MEDIA_ROOT:-/srv/media}/.markers/metrics}" : "${VG_MET_COMPONENT:=unknown}" VG_MET_START=$(date +%s) mkdir -p "$VG_MET_DIR" 2>/dev/null || return 0 local f="$VG_MET_DIR/$VG_MET_COMPONENT.counters" k v if [[ -r $f ]]; then while read -r k v; do [[ -n ${k:-} && -n ${v:-} ]] && VGMET["$k"]="$v"; done < "$f" fi vgmet_add runs 1 printf '%s\n' "$$" > "$VG_MET_DIR/$VG_MET_COMPONENT.pid" 2>/dev/null trap vgmet_flush EXIT } # vgmet_add [amount] — float-safe accumulate vgmet_add() { local k="$1" v="${2:-1}" VGMET["$k"]=$(awk -v a="${VGMET[$k]:-0}" -v b="$v" 'BEGIN{ printf "%.3f", a+b }') } vgmet_set() { VGMET["$1"]="$2"; } vgmet_flush() { : "${VG_MET_DIR:=${MEDIA_ROOT:-/srv/media}/.markers/metrics}" : "${VG_MET_COMPONENT:=unknown}" local f="$VG_MET_DIR/$VG_MET_COMPONENT.counters" tmp now k rm -f "$VG_MET_DIR/$VG_MET_COMPONENT.pid" 2>/dev/null [[ -d $VG_MET_DIR ]] || return 0 now=$(date +%s) vgmet_set last_finish "$now" vgmet_set last_duration "$(( now - VG_MET_START ))" tmp=$(mktemp "$VG_MET_DIR/.$VG_MET_COMPONENT.XXXXXX" 2>/dev/null) || return 0 for k in "${!VGMET[@]}"; do printf '%s %s\n' "$k" "${VGMET[$k]}"; done > "$tmp" 2>/dev/null chmod 0644 "$tmp" 2>/dev/null mv -f "$tmp" "$f" 2>/dev/null || rm -f "$tmp" 2>/dev/null } # start/elapsed for one job vgmet_time() { date +%s.%N; } vgmet_since() { awk -v s="$1" -v e="$(date +%s.%N)" 'BEGIN{ printf "%.3f", e-s }'; } # No-op fallbacks are defined by the callers if this file is missing, so a half-finished deploy cannot # break normalising. Keep every function above failure-tolerant.