#!/usr/bin/env bash # Host checks that logs alone cannot show (BUG-2348). Install on the production # host, every 5 minutes: # - a container restarted on its own, or was killed for memory # - host available memory is low # - BUG-2428: one container uses 85 % or more of its own memory limit # - the oldest report job has waited too long to start # - new user feedback arrived (count only; no feedback text, no account) # - BUG-2416: host CPU or one container's CPU stays high across two runs # (about 10 minutes), a high-CPU process that is not on the allowlist, a # known miner name or stratum URL in a command line, or an established # connection to a common mining-pool port. Alerts carry the process name and # pid only; command lines and environment are never sent. set -euo pipefail set +x umask 077 script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # shellcheck source=notify-feishu.sh source "$script_dir/notify-feishu.sh" case "${1:-}" in "") ;; *) echo "unknown argument" >&2 exit 2 ;; esac state_dir="${JYOTISHA_MONITOR_STATE_DIR:-/var/lib/jyotisha-monitor}" ensure_private_dir "$state_dir" env_file="${JYOTISHA_MONITOR_ENV:-/opt/jyotisha-production/.monitor.env}" load_monitor_env "$env_file" project="${JYOTISHA_COMPOSE_PROJECT:-jyotisha-production}" [[ "$project" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || exit 2 queue_limit="${JYOTISHA_QUEUE_WAIT_LIMIT:-600}" memory_limit="${JYOTISHA_MEMORY_PERCENT_LIMIT:-90}" [[ "$queue_limit" =~ ^[1-9][0-9]{1,5}$ ]] || exit 2 [[ "$memory_limit" =~ ^[1-9][0-9]$ ]] || exit 2 cpu_limit="${JYOTISHA_CPU_PERCENT_LIMIT:-85}" container_cpu_limit="${JYOTISHA_CONTAINER_CPU_LIMIT:-90}" sustain_runs="${JYOTISHA_CPU_SUSTAIN_RUNS:-2}" process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}" process_min_age="${JYOTISHA_PROCESS_MIN_AGE:-120}" # BUG-2437: seconds [[ "$cpu_limit" =~ ^[1-9][0-9]$ ]] || exit 2 [[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2 [[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2 [[ "$process_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2 container_memory_limit="${JYOTISHA_CONTAINER_MEMORY_PERCENT_LIMIT:-85}" [[ "$container_memory_limit" =~ ^[1-9][0-9]$ ]] || exit 2 # Tests replace docker and the memory file; production uses sudo -n docker # because the monitor user is not in the docker group. docker_cmd() { if [ -n "${JYOTISHA_DOCKER:-}" ]; then "$JYOTISHA_DOCKER" "$@" else sudo -n docker "$@" fi } stamp() { date -u +%Y-%m-%dT%H:%M:%SZ } now_epoch() { if [[ "${JYOTISHA_NOW:-}" =~ ^[0-9]{9,11}$ ]]; then printf '%s' "$JYOTISHA_NOW" else date +%s fi } # Tests replace ps and ss with fixture scripts. ps_cmd() { if [ -n "${JYOTISHA_PS:-}" ]; then "$JYOTISHA_PS" "$@"; else ps "$@"; fi } ss_cmd() { if [ -n "${JYOTISHA_SS:-}" ]; then "$JYOTISHA_SS" "$@"; else ss "$@"; fi } state_file="$state_dir/ops-check.state" declare -A restarts=() memory_open=0 queue_open=0 feedback_seen="" cpu_prev="" cpu_hot=0 cpu_open=0 declare -A ccpu_prev=() ccpu_hot=() ccpu_open=() cmem_open=() suspects=() suspects_now=() container_ids="" read_state() { local line key value [ -f "$state_file" ] && [ ! -L "$state_file" ] || return 0 while IFS= read -r line || [ -n "$line" ]; do case "$line" in restart:*=*) key="${line%%=*}" key="${key#restart:}" value="${line#*=}" [[ "$key" =~ ^[0-9a-f]{12,64}$ ]] && [[ "$value" =~ ^[0-9]+$ ]] && restarts["$key"]="$value" ;; memory_open=[01]) memory_open="${line#memory_open=}" ;; queue_open=[01]) queue_open="${line#queue_open=}" ;; feedback_seen=*) value="${line#feedback_seen=}" [[ "$value" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$ ]] && feedback_seen="$value" ;; cpu_prev=*) value="${line#cpu_prev=}" [[ "$value" =~ ^[0-9]+:[0-9]+$ ]] && cpu_prev="$value" ;; cpu_hot=[0-9]) cpu_hot="${line#cpu_hot=}" ;; cpu_open=[01]) cpu_open="${line#cpu_open=}" ;; ccpu:*=*) key="${line%%=*}" key="${key#ccpu:}" value="${line#*=}" [[ "$key" =~ ^[0-9a-f]{64}$ ]] || continue [[ "$value" =~ ^([0-9]+):([0-9]+):([0-9]):([01])$ ]] || continue ccpu_prev["$key"]="${BASH_REMATCH[1]}:${BASH_REMATCH[2]}" ccpu_hot["$key"]="${BASH_REMATCH[3]}" ccpu_open["$key"]="${BASH_REMATCH[4]}" ;; cmem:*=1) key="${line%%=*}" key="${key#cmem:}" [[ "$key" =~ ^[0-9a-f]{64}$ ]] && cmem_open["$key"]=1 ;; suspect:*) key="${line#suspect:}" [[ "$key" =~ ^[0-9]+/[A-Za-z0-9_.-]+$ ]] && suspects["$key"]=1 ;; esac done <"$state_file" } write_state() { local tmp key tmp="$state_file.tmp.$$" { printf 'memory_open=%s\nqueue_open=%s\nfeedback_seen=%s\n' "$memory_open" "$queue_open" "$feedback_seen" printf 'cpu_prev=%s\ncpu_hot=%s\ncpu_open=%s\n' "$cpu_prev" "$cpu_hot" "$cpu_open" for key in "${!restarts[@]}"; do printf 'restart:%s=%s\n' "$key" "${restarts[$key]}" done for key in "${!ccpu_prev[@]}"; do printf 'ccpu:%s=%s:%s:%s\n' "$key" "${ccpu_prev[$key]}" "${ccpu_hot[$key]:-0}" "${ccpu_open[$key]:-0}" done for key in "${!cmem_open[@]}"; do printf 'cmem:%s=1\n' "$key" done for key in "${!suspects[@]}"; do printf 'suspect:%s\n' "$key" done } >"$tmp" if [ "$(uname -s)" = "Linux" ]; then chmod 600 "$tmp" fi mv "$tmp" "$state_file" } alerts="" queue_alert() { alerts="${alerts}service=$1 route=$2 errorCode=$3 count=$4 requestId=- time=$(stamp)"$'\n' } check_containers() { local ids line id name count oom service declare -A current=() ids="$(docker_cmd ps -q --filter "label=com.docker.compose.project=${project}")" || return 0 [ -n "$ids" ] || return 0 # shellcheck disable=SC2086 while IFS=' ' read -r id name count oom || [ -n "${id:-}" ]; do [[ "${id:-}" =~ ^[0-9a-f]{12,64}$ ]] || continue [[ "${count:-}" =~ ^[0-9]+$ ]] || continue service="${name#/}" service="${service#${project}-}" service="${service%-[0-9]*}" [[ "$service" =~ ^[a-z0-9_-]+$ ]] || service="container" current["$id"]="$count" container_ids="${container_ids}${id}:${service}"$'\n' if [ -n "${restarts[$id]:-}" ] && [ "$count" -gt "${restarts[$id]}" ]; then if [ "$oom" = "true" ]; then queue_alert "$service" - container_oom "$count" else queue_alert "$service" - container_restarted "$count" fi elif [ -z "${restarts[$id]:-}" ] && [ "$count" -gt 0 ]; then queue_alert "$service" - container_restarted "$count" fi done < <(docker_cmd inspect --format '{{.Id}} {{.Name}} {{.RestartCount}} {{.State.OOMKilled}}' $ids) # Containers that are gone (a deploy recreated them) drop out of the state. restarts=() for id in "${!current[@]}"; do restarts["$id"]="${current[$id]}" done } check_memory() { local file total available used file="${JYOTISHA_MEMINFO:-/proc/meminfo}" [ -r "$file" ] || return 0 total="$(awk '$1 == "MemTotal:" {print $2}' "$file")" available="$(awk '$1 == "MemAvailable:" {print $2}' "$file")" [[ "$total" =~ ^[0-9]+$ ]] && [[ "$available" =~ ^[0-9]+$ ]] && [ "$total" -gt 0 ] || return 0 used=$(( (total - available) * 100 / total )) if [ "$used" -ge "$memory_limit" ]; then if [ "$memory_open" -eq 0 ]; then queue_alert host - memory_high "$used" memory_open=1 fi elif [ "$memory_open" -eq 1 ]; then queue_alert host - recovered 0 memory_open=0 fi } # One read-only query through the postgres container. The SQL is fixed text; # its output is numbers and a timestamp only. psql_value() { local sql="$1" local container="${JYOTISHA_POSTGRES_CONTAINER:-${project}-postgres-1}" [[ "$container" =~ ^[a-z0-9][a-z0-9_.-]*$ ]] || return 1 docker_cmd exec -i "$container" sh -c 'psql -X -q -A -t -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "${POSTGRES_DB:-postgres}"' <<<"$sql" } check_report_queue() { local wait wait="$(psql_value "select coalesce(extract(epoch from now() - min(coalesce(next_attempt_at, created_at)))::bigint, 0) from public.personal_report_jobs where status in ('queued', 'retrying') and coalesce(next_attempt_at, created_at) <= now();" 2>/dev/null | tr -d '\r[:space:]')" || return 0 [[ "$wait" =~ ^[0-9]+$ ]] || return 0 if [ "$wait" -ge "$queue_limit" ]; then if [ "$queue_open" -eq 0 ]; then queue_alert report /api/reports report_queue_stuck "$wait" queue_open=1 fi elif [ "$queue_open" -eq 1 ]; then queue_alert report /api/reports recovered 0 queue_open=0 fi } check_feedback() { local row count newest since since="${feedback_seen:-}" if [ -z "$since" ]; then # First run: start from now so old feedback is not announced. row="$(psql_value "select to_char(now() at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"');" 2>/dev/null | tr -d '\r[:space:]')" || return 0 [[ "$row" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] && feedback_seen="$row" return 0 fi row="$(psql_value "select count(*) || '|' || coalesce(to_char(max(created_at) at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), '') from public.user_feedback where created_at > '${since}'::timestamptz;" 2>/dev/null | tr -d '\r[:space:]')" || return 0 count="${row%%|*}" newest="${row#*|}" [[ "$count" =~ ^[0-9]+$ ]] || return 0 if [ "$count" -gt 0 ] && [[ "$newest" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$ ]]; then queue_alert web /admin/feedback feedback_new "$count" feedback_seen="$newest" fi } # Host CPU over the interval since the previous run, from /proc/stat. Two # consecutive hot intervals (about 10 minutes at the 5-minute schedule) alert once. check_host_cpu() { local file line total idle prev_total prev_idle dt di used file="${JYOTISHA_PROC_STAT:-/proc/stat}" [ -r "$file" ] || return 0 line="$(awk '$1 == "cpu" {t = 0; for (i = 2; i <= 9 && i <= NF; i++) t += $i; print t ":" ($5 + $6); exit}' "$file")" [[ "$line" =~ ^[0-9]+:[0-9]+$ ]] || return 0 total="${line%%:*}" idle="${line#*:}" if [ -n "$cpu_prev" ]; then prev_total="${cpu_prev%%:*}" prev_idle="${cpu_prev#*:}" dt=$((total - prev_total)) di=$((idle - prev_idle)) if [ "$dt" -gt 0 ] && [ "$di" -ge 0 ]; then used=$(( (dt - di) * 100 / dt )) if [ "$used" -ge "$cpu_limit" ]; then cpu_hot=$((cpu_hot < 9 ? cpu_hot + 1 : 9)) if [ "$cpu_hot" -ge "$sustain_runs" ] && [ "$cpu_open" -eq 0 ]; then queue_alert host - cpu_high "$used" cpu_open=1 fi else cpu_hot=0 if [ "$cpu_open" -eq 1 ]; then queue_alert host - recovered 0 cpu_open=0 fi fi fi fi cpu_prev="$total:$idle" } # Per-container CPU from the cgroup v2 cpu.stat counter (percent of one core). check_container_cpu() { local root now entry id service file usage prev_usage prev_time dt pct declare -A seen=() root="${JYOTISHA_CGROUP_ROOT:-/sys/fs/cgroup}" now="$(now_epoch)" while IFS= read -r entry; do [ -n "$entry" ] || continue id="${entry%%:*}" service="${entry#*:}" [[ "$id" =~ ^[0-9a-f]{64}$ ]] || continue file="$root/system.slice/docker-$id.scope/cpu.stat" [ -r "$file" ] || continue usage="$(awk '$1 == "usage_usec" {print $2; exit}' "$file")" [[ "$usage" =~ ^[0-9]+$ ]] || continue seen["$id"]=1 if [ -n "${ccpu_prev[$id]:-}" ]; then prev_usage="${ccpu_prev[$id]%%:*}" prev_time="${ccpu_prev[$id]#*:}" dt=$((now - prev_time)) if [ "$dt" -gt 0 ] && [ "$usage" -ge "$prev_usage" ]; then pct=$(( (usage - prev_usage) / (dt * 10000) )) if [ "$pct" -ge "$container_cpu_limit" ]; then ccpu_hot["$id"]=$(( ${ccpu_hot[$id]:-0} < 9 ? ${ccpu_hot[$id]:-0} + 1 : 9 )) if [ "${ccpu_hot[$id]}" -ge "$sustain_runs" ] && [ "${ccpu_open[$id]:-0}" -eq 0 ]; then queue_alert "$service" - container_cpu_high "$pct" ccpu_open["$id"]=1 fi else ccpu_hot["$id"]=0 if [ "${ccpu_open[$id]:-0}" -eq 1 ]; then queue_alert "$service" - recovered 0 ccpu_open["$id"]=0 fi fi fi fi ccpu_prev["$id"]="$usage:$now" done <<<"$container_ids" for id in "${!ccpu_prev[@]}"; do if [ -z "${seen[$id]:-}" ]; then unset "ccpu_prev[$id]" "ccpu_hot[$id]" "ccpu_open[$id]" fi done } # BUG-2428: per-container memory against its own compose limit (cgroup v2). # Used memory = memory.current minus inactive_file, the same figure docker stats # shows, so reclaimable page cache (postgres reads) does not count. Containers # without a limit (memory.max = max) are skipped. Alert once, recover once. check_container_memory() { local root entry id service dir current max inactive used pct declare -A seen=() root="${JYOTISHA_CGROUP_ROOT:-/sys/fs/cgroup}" while IFS= read -r entry; do [ -n "$entry" ] || continue id="${entry%%:*}" service="${entry#*:}" [[ "$id" =~ ^[0-9a-f]{64}$ ]] || continue dir="$root/system.slice/docker-$id.scope" [ -r "$dir/memory.current" ] && [ -r "$dir/memory.max" ] || continue current="$(tr -d '[:space:]' <"$dir/memory.current")" max="$(tr -d '[:space:]' <"$dir/memory.max")" [[ "$current" =~ ^[0-9]+$ ]] && [[ "$max" =~ ^[1-9][0-9]*$ ]] || continue inactive=0 if [ -r "$dir/memory.stat" ]; then inactive="$(awk '$1 == "inactive_file" {print $2; exit}' "$dir/memory.stat")" [[ "$inactive" =~ ^[0-9]+$ ]] || inactive=0 fi used=$((current > inactive ? current - inactive : 0)) pct=$((used * 100 / max)) seen["$id"]=1 if [ "$pct" -ge "$container_memory_limit" ]; then if [ -z "${cmem_open[$id]:-}" ]; then queue_alert "$service" - container_memory_high "$pct" cmem_open["$id"]=1 fi elif [ -n "${cmem_open[$id]:-}" ]; then queue_alert "$service" - recovered 0 unset "cmem_open[$id]" fi done <<<"$container_ids" for id in "${!cmem_open[@]}"; do [ -n "${seen[$id]:-}" ] || unset "cmem_open[$id]" done } # Process names that may legitimately use a lot of CPU on this host. allowed_process() { case "$1" in node|next-server*|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;; caddy|dockerd|containerd|containerd-shim*|runc|docker|docker-proxy|docker-compose) return 0 ;; sshd|cron|systemd|systemd-*|journald|rsyslogd|unattended-upgr*|apt|apt-get|dpkg|http|https|gpgv) return 0 ;; bash|sh|awk|gzip|zstd|xz|tar|sort|ps|ss|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;; esac return 1 } miner_text() { case "$1" in *stratum+tcp* | *stratum+ssl* | *stratum2+* | *xmrig* | *kdevtmpfsi* | *kinsing* | *minerd* | *cpuminer* | *nanominer* | *nbminer* | *lolminer* | *t-rex* | *--donate-level*) return 0 ;; esac return 1 } report_suspect() { local pid="$1" name="$2" code="$3" [[ "$pid" =~ ^[0-9]+$ ]] || return 0 name="$(printf '%s' "$name" | tr -c 'A-Za-z0-9_.-' '_' | cut -c1-40)" [ -n "$name" ] || name="unknown" suspects_now["$pid/$name"]=1 # One alert per process: a miner that keeps running is not re-announced every 5 minutes. [ -z "${suspects[$pid/$name]:-}" ] || return 0 suspects["$pid/$name"]=1 queue_alert host "/proc/$name" "$code" "$pid" } # Keep only processes still seen this run, so the state stays small. prune_suspects() { local key suspects=() for key in "${!suspects_now[@]}"; do suspects["$key"]=1 done } # BUG-2437: ps reports %CPU as CPU time over lifetime, so a process seconds old (ps itself, a # deploy step, a server warming up) reads near 100 %. Only a process running at least # process_min_age seconds counts as hot; a miner keeps running and is still caught, and the # name / pool checks ignore age. check_processes() { local pid etimes pcpu comm args pct while read -r pid etimes pcpu comm args || [ -n "${pid:-}" ]; do [[ "${pid:-}" =~ ^[0-9]+$ ]] || continue if miner_text "$comm $args"; then report_suspect "$pid" "$comm" miner_process continue fi [[ "${etimes:-}" =~ ^[0-9]+$ ]] && [ "$etimes" -ge "$process_min_age" ] || continue pct="${pcpu%%.*}" [[ "$pct" =~ ^[0-9]+$ ]] || continue if [ "$pct" -ge "$process_cpu_limit" ] && ! allowed_process "$comm"; then report_suspect "$pid" "$comm" suspicious_process fi done < <(ps_cmd -eo pid=,etimes=,pcpu=,comm=,args= 2>/dev/null || true) } # Established outbound connections to common mining-pool ports. mining_port() { case "$1" in 3333|4444|5555|6666|7777|8888|9999|14433|14444|45560|45700) return 0 ;; esac return 1 } check_egress() { local line local_addr local_port peer port proc pid name while IFS= read -r line; do [ -n "$line" ] || continue local_addr="$(awk '{print $3}' <<<"$line")" local_port="${local_addr##*:}" # Inbound connections to our own services: the client's port can be anything. case "$local_port" in 22|80|443|3000|5200|5432) continue ;; esac peer="$(awk '{print $4}' <<<"$line")" port="${peer##*:}" [[ "$port" =~ ^[0-9]+$ ]] || continue mining_port "$port" || continue proc="$(grep -oE 'users:\(\("[^"]+",pid=[0-9]+' <<<"$line" | head -1)" name="$(sed -E 's/^users:\(\("([^"]+)".*/\1/' <<<"$proc")" pid="$(sed -E 's/.*pid=([0-9]+)$/\1/' <<<"$proc")" [[ "$pid" =~ ^[0-9]+$ ]] || pid=0 [ -n "$name" ] || name="unknown" report_suspect "$pid" "$name" mining_pool_connection done < <(ss_cmd -Htnp state established 2>/dev/null || true) } read_state check_containers check_memory check_host_cpu check_container_cpu check_container_memory check_processes check_egress prune_suspects check_report_queue check_feedback if [ -n "$alerts" ]; then post_monitor_alert "${alerts%$'\n'}" fi write_state