summaryrefslogtreecommitdiff
path: root/statuspage/lib/common.sh
blob: dcc26f5245cd12e90337abc6ba829a58da53047c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/bin/sh
# lib/common.sh
# Shared helpers for statuspage check scripts. Source this, don't execute it.
#
#   . "$(dirname "$0")/../lib/common.sh"

# json_line SECTION LABEL VALUE STATUS
# Emits one JSONL row on stdout. Escapes double quotes and backslashes in
# LABEL/VALUE so a stray '"' in e.g. `zpool status` output can't break the
# line for the renderer's parser.
json_line() {
    section=$1
    label=$2
    value=$3
    status=$4

    # Order matters: backslashes first, then quotes, then newlines (zpool
    # status output can be multi-line when a pool is degraded) so a JSONL
    # line always stays exactly one line.
    label=$(printf '%s' "$label" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr '\n' '\1' | sed 's/\x01/\\n/g')
    value=$(printf '%s' "$value" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr '\n' '\1' | sed 's/\x01/\\n/g')

    printf '{"section": "%s", "label": "%s", "value": "%s", "status": "%s"}\n' \
        "$section" "$label" "$value" "$status"
}

# svc_status NAME
# Prints "ok" or "down" depending on `service NAME status`.
svc_status() {
    service "$1" status >/dev/null 2>&1 && echo "ok" || echo "down"
}

# wg_status IFACE
# Prints "ok" or "down" depending on whether wg reports handshakes for IFACE.
wg_status() {
    wg show "$1" latest-handshakes >/dev/null 2>&1 && echo "ok" || echo "down"
}

# port_check IP PORT
# Prints "ok" or "down" depending on TCP connect success.
port_check() {
    nc -z -w2 "$1" "$2" >/dev/null 2>&1 && echo "ok" || echo "down"
}

# jail_status NAME
# Prints "ok" or "down" depending on whether the jail is running.
jail_status() {
    jls -j "$1" >/dev/null 2>&1 && echo "ok" || echo "down"
}

# proc_running PATTERN
# Prints "ok" or "down" depending on whether any process's command line
# matches PATTERN (pgrep -f). For ad-hoc background processes that
# aren't rc.d-managed, so there's no `service ... status` for them.
proc_running() {
    pgrep -f "$1" >/dev/null 2>&1 && echo "ok" || echo "down"
}