diff --git a/utils/librespeed-common/Makefile b/utils/librespeed-common/Makefile index f6b2e99d43..cf69590121 100644 --- a/utils/librespeed-common/Makefile +++ b/utils/librespeed-common/Makefile @@ -9,7 +9,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=librespeed-common PKG_VERSION:=1.0.0 -PKG_RELEASE:=3 +PKG_RELEASE:=4 PKG_MAINTAINER:=Josef Schlehofer PKG_LICENSE:=GPL-2.0-only diff --git a/utils/librespeed-common/files/librespeed-aggregate b/utils/librespeed-common/files/librespeed-aggregate index 2c3a078b8d..60b86f6209 100755 --- a/utils/librespeed-common/files/librespeed-aggregate +++ b/utils/librespeed-common/files/librespeed-aggregate @@ -22,7 +22,7 @@ if (length(ARGV) > 0) { } print("Usage: librespeed-aggregate\n" + "Reduces completed days of measurement history to daily min/avg/max\n" + - "aggregates. Runs from cron; takes no arguments.\n"); + "aggregates per interface. Runs from cron; takes no arguments.\n"); exit(0); } import { cursor } from 'uci'; @@ -96,7 +96,8 @@ const have = {}; for (let e in archive) have[e.timestamp] = true; -// Group raw lines by local calendar day, completed days only. +// Group raw lines by local calendar day and interface, completed days only. +// A run without an interface gets its own group, '', which no name can be. const days = {}; for (let e in read_lines(raw_path)) { @@ -110,23 +111,28 @@ for (let e in read_lines(raw_path)) { if (key >= today || have[key]) continue; - days[key] = days[key] ?? []; - push(days[key], e); + const iface = (type(e.interface) == 'string') ? e.interface : ''; + + days[key] = days[key] ?? {}; + days[key][iface] = days[key][iface] ?? []; + push(days[key][iface], e); } -let changed = false; - -for (let key in sort(keys(days))) { +function summarize(key, iface, group) { const entry = { timestamp: key, - epoch: day_start(key), - samples: length(days[key]) + epoch: day_start(key) }; + if (iface != '') + entry.interface = iface; + + entry.samples = length(group); + for (let m in METRICS) { let lo = null, hi = null, sum = 0.0, n = 0; - for (let e in days[key]) { + for (let e in group) { const v = e[m]; if (type(v) != 'double' && type(v) != 'int') @@ -147,8 +153,16 @@ for (let key in sort(keys(days))) { } } - push(archive, entry); - changed = true; + return entry; +} + +let changed = false; + +for (let key in sort(keys(days))) { + for (let iface in sort(keys(days[key]))) { + push(archive, summarize(key, iface, days[key][iface])); + changed = true; + } } // Archive retention: integer comparison on the day-start epoch. @@ -164,7 +178,15 @@ if (!changed) let tmp = `${archive_path}.tmp`; let out = ''; -for (let e in sort(kept, (a, b) => int(a.epoch) - int(b.epoch))) +// By day, then interface ('' first): sort() is not stable. +function by_day(a, b) { + const d = int(a.epoch) - int(b.epoch); + const x = a.interface ?? '', y = b.interface ?? ''; + + return d ? d : (x < y ? -1 : (x > y ? 1 : 0)); +} + +for (let e in sort(kept, by_day)) out += sprintf('%J\n', e); // The last component only, never the whole tree: archive_path commonly diff --git a/utils/librespeed-common/files/librespeed-run b/utils/librespeed-common/files/librespeed-run index 405509fb23..34e4dc3221 100755 --- a/utils/librespeed-common/files/librespeed-run +++ b/utils/librespeed-common/files/librespeed-run @@ -4,10 +4,11 @@ # # The only thing that starts a measurement: LuCI reaches it through rpcd, the # scheduler calls it directly. Holding the lock for the whole run means a second -# invocation from either side fails instead of measuring against the first. +# invocation from either side waits instead of measuring against the first. # Packaging checks probe every executable for these; a runner that ignored # them would start a measurement instead of answering. +links="" case "$1" in --version) echo "librespeed-common %%VERSION%%" @@ -15,24 +16,47 @@ case "$1" in ;; --help|-h) cat <<'EOF' -Usage: librespeed-run +Usage: librespeed-run [INTERFACE] Runs one LibreSpeed measurement according to /etc/config/librespeed and -records the result for the ubus interface. Started by LuCI or cron; takes -no arguments. +records the result for the ubus interface. Started by LuCI or cron. +INTERFACE is a logical interface (default: librespeed.main.interface). +It is measured bound to the device of its link and recorded under the +link (wan6 beside wan counts as wan). It is not measured, and that is +recorded as its failure, when its link is down, netifd does not know it +or netifd does not answer. +--links print each interface's link, the links to offer and the + interfaces whose link is down, as JSON EOF exit 0 ;; +--links) + [ $# -eq 1 ] || { echo "Usage: librespeed-run --links" >&2; exit 2; } + links=1 + shift + ;; esac +# The name reaches jsonfilter expressions and the crontab: UCI's alphabet only. +usage() { + echo "Usage: librespeed-run [INTERFACE]" >&2 + exit 2 +} +[ $# -le 1 ] || usage +case "$1" in *[!A-Za-z0-9_]*) usage ;; esac +want=$1 + . /lib/functions.sh -. /lib/functions/network.sh . /usr/share/libubox/jshn.sh CLI=/usr/bin/librespeed-cli STATE_DIR=/tmp/librespeed STATE="$STATE_DIR/state.json" RESULT="$STATE_DIR/result.json" +FAILED="$STATE_DIR/failed" LOCK=/var/lock/librespeed.lock +# A down interface still sits on the device it is configured on only as +# DHCP, DHCPv6 or static: PPP and qmi bring up a device of their own. +DEVP="@.proto='dhcp' || @.proto='dhcpv6' || @.proto='static'" mkdir -p "$STATE_DIR" @@ -45,6 +69,12 @@ atomic_write() { write_state() { json_init json_add_boolean running "$1" + # A run names its link once bound; a failed one, its for_iface. + if [ "$1" = 1 ]; then + [ -n "$state_iface" ] && json_add_string interface "$state_iface" + elif [ -n "$5" ] && [ -n "$for_iface" ]; then + json_add_string interface "$for_iface" + fi [ -n "$2" ] && json_add_int pid "$2" [ -n "$3" ] && json_add_int started "$3" [ -n "$4" ] && json_add_int last_finished "$4" @@ -94,25 +124,178 @@ sampler() { } fail() { + local at + # A run that failed with the cached server drops the cache: the next run # rediscovers instead of failing against the same dead choice forever. [ "${used_cache:-0}" = 1 ] && rm -f "$LIST_CACHE" "$LIST_CACHE.src" "$CHOICE_CACHE" - write_state 0 "" "" "$(date +%s)" "$1" - logger -t librespeed "measurement failed: $1" + at=$(date +%s) + write_state 0 "" "" "$at" "$1" + # Kept until a result is recorded on this link; other links leave it. + if [ -n "$for_iface" ]; then + mkdir -p "$FAILED" + atomic_write "$FAILED/$for_iface" "$at $1" + fi + logger -t librespeed "measurement of ${for_iface:-$iface} failed: $1" exit 1 } +# ifdump_get VAR PATH: PATH below @.interface of the netifd snapshot, taken +# once so a run is judged by the state it began with. Matches space-joined. +ifdump_get() { + local __v + + [ -n "$ifdump" ] || return 1 + __v=$(jsonfilter -s "$ifdump" -e "$1=@.interface$2" 2>/dev/null) + [ -n "$__v" ] || { unset "$1"; return 1; } + eval "$__v" +} + +if_device() { + case "$2" in ''|*[!A-Za-z0-9_.-]*) unset "$1"; return 1 ;; esac + ifdump_get "$1" "[@.interface='$2'].l3_device" +} + +# The UCI section device $1 is recorded under: wan for wan6, even while wan is +# down. Several are narrowed in turn, a step only where it leaves some: to the +# IPv4 default's holder, then not DHCPv6, then no IPv6 address. A down one +# counts only as DHCP or static (PPP has a device of its own). More left: none. +dev_iface() { + local p q f on="@.dynamic=false && (@.l3_device='$1' || (@.up=false && @.device='$1' && (@.proto='dhcp' || @.proto='static')))" + + case "$1" in ''|*[!A-Za-z0-9_.-]*) return 1 ;; esac + ifdump_get p "[$on].interface" || return 1 + for f in "!@.ip4table && @.route[@.target='0.0.0.0' && !@.table]" \ + "@.proto!='dhcpv6'" "!@['ipv6-address'][0]"; do + case "$p" in *' '*) ;; *) break ;; esac + ifdump_get q "[$on && $f].interface" && on="$on && $f" p=$q + done + case "$p" in *' '*) return 1 ;; esac + echo "$p" +} + +# bind_dev VAR NAME: the device a test of NAME is bound to: its l3_device, or +# while it is down the device it sits on, if another interface of its link +# is up there (wan6 beside a down wan). None: its link is down. +bind_dev() { + local d u + + case "$2" in ''|*[!A-Za-z0-9_]*) return 1 ;; esac + if_device "$1" "$2" && return 0 + ifdump_get d "[@.interface='$2' && @.up=false && ($DEVP)].device" || return 1 + dev_iface "$d" > /dev/null || return 1 + ifdump_get u "[@.l3_device='$d'].interface" || return 1 + eval "$1=\$d" +} + +# --links: the link a bound run of each interface records (wan6 as wan), no +# lock taken. A dynamic interface without a link is left out. A static link +# without a gateway (lan) is not offered: no default route in the dump, which +# shows routes only while up, and no gateway or ip6gw in UCI. down lists those +# a run refuses as down: no l3_device, and bind_dev finds none. +print_links() { + local names x d l g4 g6 cache="" map="" nogw="" nol3="" + + ifdump_get names "[*].interface" + ifdump_get nol3 "[!@.l3_device].interface" + for x in $names; do + case "$x" in *[!A-Za-z0-9_]*) continue ;; esac + if_device d "$x" || + ifdump_get d "[@.interface='$x' && @.up=false && ($DEVP)].device" || + d="" + [ "$d" = lo ] && continue + l="" + if [ -n "$d" ]; then + case " $cache " in + *" $d="*) l=${cache##* "$d"=}; l=${l%% *} ;; + *) l=$(dev_iface "$d"); cache="$cache $d=$l" ;; + esac + fi + [ -n "$l" ] || + ifdump_get l "[@.interface='$x' && @.dynamic=false].interface" || + continue + map="$map $x=$l" + done + ifdump_get nogw "[@.proto='static' && !@.route[@.mask=0]].interface" && + config_load network + json_init + json_add_array links + for l in $(for x in $map; do echo "${x#*=}"; done | sort -u); do + case " $nogw " in + *" $l "*) + config_get g4 "$l" gateway + config_get g6 "$l" ip6gw + [ -n "$g4$g6" ] || continue + ;; + esac + json_add_string "" "$l" + done + json_close_array + json_add_object interfaces + for x in $map; do + json_add_string "${x%%=*}" "${x#*=}" + done + json_close_object + json_add_array down + for x in $map; do + x=${x%%=*} + case " $nol3 " in *" $x "*) bind_dev b "$x" || json_add_string "" "$x" ;; esac + done + json_close_array + json_dump + [ -n "$names" ] +} + +if [ -n "$links" ]; then + ifdump=$(ubus -t 5 call network.interface dump 2>/dev/null) + print_links + exit +fi + # One measurement at a time. The descriptor stays open for the whole run, so the # kernel releases the lock even if this script is killed -- there is no stale # state to time out. +# Schedules fire at the same minute: a run waits up to 3 minutes for the lock +# (BusyBox flock has no -w) and writes nothing meanwhile, then gives up +# (exit 3) and records that as its interface's failure. exec 9>"$LOCK" -flock -n 9 || { - echo "already running" >&2 - exit 3 -} +tries=0 +until flock -n 9; do + if [ "$tries" = 0 ]; then + echo "waiting for the running measurement to finish" >&2 + logger -t librespeed "measurement of ${want:-the default interface} waits for the running one" + elif [ "$tries" -ge 36 ]; then + echo "already running" >&2 + logger -t librespeed "skipped measurement of ${want:-the default interface}: another one held the lock for 3 minutes" + # A lost slot is a gap in the data: kept as the interface's failure, + # not in state.json, which is the lock holder's. + skip=$want + [ -n "$skip" ] || { config_load librespeed; config_get skip main interface wan; } + case "$skip" in ''|*[!A-Za-z0-9_]*) ;; *) + mkdir -p "$FAILED" + atomic_write "$FAILED/$skip" "$(date +%s) skipped: another measurement held the lock for 3 minutes" + esac + exit 3 + fi + tries=$((tries + 1)) + sleep 5 +done + +# From here status reads state.json as this run's: clear the last interface. +state_iface="" for_iface="" +started=$(date +%s) +write_state 1 $$ "$started" + +# stop kills our whole process group, so librespeed-cli dies with us; ash runs +# this trap once the foreground child has exited, and it records that the run +# was stopped rather than pretending the measurement failed. +sampler_pid= +trap '[ -n "$sampler_pid" ] && kill "$sampler_pid" 2>/dev/null + write_state 0 "" "" "$(date +%s)" "stopped"; exit 1' TERM config_load librespeed config_get iface main interface wan +[ -n "$want" ] && iface=$want config_get server main server auto config_get scheme main scheme auto config_get server_list main server_list '' @@ -120,9 +303,18 @@ config_get_bool hist_enabled history enabled 1 config_get hist_path history path "$STATE_DIR/history.jsonl" config_get hist_retention history retention 30d -# --interface takes a device, and UCI carries a logical interface name. -dev="" -network_get_device dev "$iface" 2>/dev/null +# --interface takes a device, and UCI carries a logical interface name. A run +# is bound to the device of its link or measures nothing, so its link is never +# a guess. Failures go under the name asked for, once bound under its link. +for_iface=$iface +case "$for_iface" in *[!A-Za-z0-9_]*) for_iface="" ;; esac +ifdump=$(ubus call network.interface dump 2>/dev/null) +[ -n "$ifdump" ] || fail "netifd did not answer" +ifdump_get known "[@.interface='$for_iface'].interface" || + fail "interface disabled or not configured" +bind_dev dev "$for_iface" || fail "interface is down" +state_iface=$(dev_iface "$dev" 2>/dev/null) || state_iface=$for_iface +for_iface=$state_iface [ -x "$CLI" ] || fail "librespeed-cli is not installed" @@ -178,7 +370,7 @@ elif [ "$cache_fresh" = 1 ]; then elif [ -n "$server_list" ]; then set -- "$@" --server-json "$LIST_URL" fi -[ -n "$dev" ] && set -- "$@" --interface "$dev" +set -- "$@" --interface "$dev" # TLS itself can bound the result on routers without AES acceleration, so the # scheme is a measurement setting, not just a transport detail. case "$scheme" in @@ -188,16 +380,9 @@ esac # Never --bytes: it switches the report to MB/s and the history would end up # holding two units that cannot be told apart afterwards. -started=$(date +%s) +# Now with its link. write_state 1 $$ "$started" -# stop kills our whole process group, so librespeed-cli dies with us; ash runs -# this trap once the foreground child has exited, and it records that the run -# was stopped rather than pretending the measurement failed. -trap '[ -n "$sampler_pid" ] && kill "$sampler_pid" 2>/dev/null - write_state 0 "" "" "$(date +%s)" "stopped"; exit 1' TERM -sampler_pid= - if [ "$stream" = 1 ]; then # The while runs in a subshell, so the reports cannot come back in a # variable; they land in a file instead. State updates are throttled to @@ -232,11 +417,9 @@ if [ "$stream" = 1 ]; then fail "${err:-measurement failed}" fi else - if [ -n "$dev" ]; then - # Not with fd 9: its last sleep would hold the lock after the run. - sampler "$dev" 9>&- & - sampler_pid=$! - fi + # Not with fd 9: its last sleep would hold the lock after the run. + sampler "$dev" 9>&- & + sampler_pid=$! out=$("$@" 2>"$STATE_DIR/stderr.log" < /dev/null); rc=$? [ -n "$sampler_pid" ] && kill "$sampler_pid" 2>/dev/null if [ "$rc" != 0 ]; then @@ -305,7 +488,7 @@ json_init json_add_string timestamp "$ts" json_add_int started "$started" json_add_int finished "$finished" -json_add_string interface "$iface" +json_add_string interface "$state_iface" json_add_object server # Absent until the CLI reports it; consumers treat null as unknown. [ -n "$srv_id" ] && json_add_int id "$srv_id" @@ -334,7 +517,7 @@ if [ "$hist_enabled" = "1" ]; then json_init json_add_string timestamp "$ts" json_add_int epoch "$finished" - json_add_string interface "$iface" + json_add_string interface "$state_iface" json_add_object server [ -n "$srv_id" ] && json_add_int id "$srv_id" json_add_string name "$srv_name" @@ -389,6 +572,15 @@ if [ "$hist_enabled" = "1" ]; then fi write_state 0 "" "" "$finished" "" +# A result clears the failures of all interfaces on its device (down ones +# only as DHCP, DHCPv6 or static). +on="" +case "$dev" in *[!A-Za-z0-9_.-]*) ;; *) + ifdump_get on "[@.l3_device='$dev' || (@.up=false && @.device='$dev' && ($DEVP))].interface" +esac +for k in $state_iface $on; do + case "$k" in *[!A-Za-z0-9_]*) ;; *) rm -f "$FAILED/$k" ;; esac +done # Refresh the server cache after the run, so the next one starts instantly: # at most one list download a day, and the choice is the server this run @@ -414,5 +606,5 @@ if [ "$cache_fresh" = 0 ]; then esac fi fi -logger -t librespeed "measurement done: ${download} Mbps down, ${upload} Mbps up" +logger -t librespeed "measurement of $for_iface done: ${download} Mbps down, ${upload} Mbps up" exit 0 diff --git a/utils/librespeed-common/files/librespeed.init b/utils/librespeed-common/files/librespeed.init index a1a87d60e8..4c15b949b1 100644 --- a/utils/librespeed-common/files/librespeed.init +++ b/utils/librespeed-common/files/librespeed.init @@ -35,8 +35,10 @@ valid_field() { return 0 } +# $4 is the section's place in the sync: all calls of one sync share the +# seed, so each skips the draws of those before it; the first draws as before. cron_expr() { - local interval="$1" days="$2" hours="$3" + local interval="$1" days="$2" hours="$3" salt="${4:-0}" local start end m h v case "$interval" in @@ -64,8 +66,11 @@ cron_expr() { [ "$end" -ge "$start" ] 2>/dev/null || end=$start # Time xor pid as the seed: seconds-granular srand() alone would give # two syncs in the same second the same draw. - set -- $(awk -v a="$start" -v b="$end" -v s="$(( $(date +%s) ^ $$ ))" 'BEGIN { + set -- $(awk -v a="$start" -v b="$end" -v s="$(( $(date +%s) ^ $$ ))" \ + -v skip="$salt" 'BEGIN { srand(s) + for (i = 0; i < skip * 2; i++) + rand() printf "%d %d", int(rand() * 60), a + int(rand() * (b - a + 1)) }') echo "$1 $2 * * $days" @@ -84,16 +89,35 @@ restart_cron() { return 0 } -sync_cron() { - local enabled interval days hours expr hist_enabled archive_path +# Appends the cron line of one schedule section (uses sync_cron's locals). The +# first enabled section of an interface whose interval is valid wins, the +# legacy 'schedule' first. +sync_schedule() { + local section="$1" enabled iface interval days hours expr - config_load librespeed - config_get_bool enabled schedule enabled 0 - config_get interval schedule interval 1d - config_get days schedule days '*' - config_get hours schedule hours '' - config_get_bool hist_enabled history enabled 1 - config_get archive_path history archive_path '' + config_get_bool enabled "$section" enabled 0 + [ "$enabled" = 1 ] || return 0 + config_get iface "$section" interface '' + config_get interval "$section" interval 1d + config_get days "$section" days '*' + config_get hours "$section" hours '' + + # Only the legacy section may name none; its line stays bare, as before. + if [ -z "$iface" ] && [ "$section" != schedule ]; then + logger -t librespeed "skipped an automatic test that names no interface" + return 0 + fi + # The name lands in root's crontab: a bad one is skipped, not replaced. + case "$iface" in *[!A-Za-z0-9_]*) + logger -t librespeed "skipped an automatic test of invalid interface '$iface'" + return 0 + ;; + esac + case " $seen " in *" ${iface:-$main_iface} "*) + logger -t librespeed "skipped a second automatic test of ${iface:-$main_iface}" + return 0 + ;; + esac # These end up verbatim in root's crontab, so anything unexpected becomes # the harmless default rather than a cron field it was not meant to be. @@ -108,6 +132,23 @@ sync_cron() { hours='' fi + if expr=$(cron_expr "$interval" "$days" "$hours" "$salt"); then + echo "$expr $RUN${iface:+ $iface}" >> "$CRONTAB" + seen="$seen ${iface:-$main_iface}" + else + logger -t librespeed "unsupported schedule interval '$interval' for ${iface:-$main_iface}" + fi + salt=$((salt + 1)) +} + +sync_cron() { + local hist_enabled archive_path main_iface seen="" salt=0 + + config_load librespeed + config_get main_iface main interface wan + config_get_bool hist_enabled history enabled 1 + config_get archive_path history archive_path '' + mkdir -p "${CRONTAB%/*}" touch "$CRONTAB" sed -i "\\#$RUN#d;\\#$AGG#d" "$CRONTAB" @@ -119,13 +160,8 @@ sync_cron() { echo "5 0 * * * $AGG" >> "$CRONTAB" fi - if [ "$enabled" = 1 ]; then - if expr=$(cron_expr "$interval" "$days" "$hours"); then - echo "$expr $RUN" >> "$CRONTAB" - else - logger -t librespeed "unsupported schedule interval '$interval'" - fi - fi + sync_schedule schedule + config_foreach sync_schedule schedule restart_cron } diff --git a/utils/librespeed-common/files/librespeed.uc b/utils/librespeed-common/files/librespeed.uc index fee8b9751a..f920a7aaaf 100644 --- a/utils/librespeed-common/files/librespeed.uc +++ b/utils/librespeed-common/files/librespeed.uc @@ -8,12 +8,13 @@ 'use strict'; -import { open, readfile, stat } from 'fs'; +import { lsdir, open, popen, readfile, stat } from 'fs'; import { cursor } from 'uci'; const STATE_DIR = '/tmp/librespeed'; const STATE = `${STATE_DIR}/state.json`; const RESULT = `${STATE_DIR}/result.json`; +const FAILED = `${STATE_DIR}/failed`; const LOCK = '/var/lock/librespeed.lock'; const RUN = '/usr/libexec/librespeed-run'; @@ -50,6 +51,41 @@ function pgid_of(pid) { return int(f[2] ?? 0); } +// Each interface's last failure, newest first, kept until its link succeeds. +// A name neither configured nor scheduled any more (removed, renamed) is left +// out: no run can clear it, and a page would show a name that is gone. +function failures() { + const out = []; + let known = null; + + for (let name in (lsdir(FAILED) ?? [])) { + if (!match(name, /^[A-Za-z0-9_]+$/)) + continue; + + if (known == null) { + const uci = cursor(); + const main = uci.get('librespeed', 'main', 'interface'); + + known = {}; + known[(main == null || main == '') ? 'wan' : main] = true; + uci.foreach('librespeed', 'schedule', (s) => { if (s.interface) known[s.interface] = true; }); + uci.foreach('network', 'interface', (s) => { known[s['.name']] = true; }); + uci.unload('librespeed'); + uci.unload('network'); + } + + if (!known[name]) + continue; + + const m = match(readfile(`${FAILED}/${name}`) ?? '', /^([0-9]+) ([^\n]*)/); + + if (m) + push(out, { interface: name, error: m[2], finished: int(m[1]) }); + } + + return sort(out, (a, b) => b.finished - a.finished); +} + // The lock says whether a measurement runs, not a field in a file: a process // that dies takes its lock with it, so there is no stale state to age out. function is_running() { @@ -163,17 +199,62 @@ function cron_next(line, count) { return out; } +// Synchronous: the runner takes no lock, netifd gets 5 s. It exits 1 when +// netifd gave no dump: that is no reply, not an empty one. +function links() { + if (!stat(RUN)) + return { error: 'not installed' }; + + const p = popen(`${RUN} --links 2>/dev/null`, 'r'); + let v = null; + + try { + v = json(p?.read('all') ?? ''); + } + catch (e) { + v = null; + } + + const rc = p?.close(); + + return (rc === 0 && type(v?.interfaces) == 'object') ? v : { error: 'no reply' }; +} + const methods = { start: { - call: function() { + args: { interface: '' }, + call: function(request) { + const iface = request.args?.interface ?? ''; + if (is_running()) return { error: 'already running' }; if (!stat(RUN)) return { error: 'not installed' }; + // A UCI network interface only: any session the ACL admits gets + // here, and the name goes into a shell command below. + if (iface != '' && (type(iface) != 'string' || + !match(iface, /^[A-Za-z0-9_]+$/) || + cursor().get('network', iface) != 'interface')) + return { error: 'unknown interface' }; + + // Refused here as the runner would: its links name every interface + // netifd lists (loopback aside) and those whose link is down. + const name = iface || config_get(cursor(), 'main', 'interface', 'wan'); + const known = links(); + + if (known.error) + return { error: 'netifd did not answer' }; + if (known.interfaces[name] == null) + return { error: 'interface disabled or not configured' }; + if (name in (known.down ?? [])) + return { error: 'interface is down' }; + // Detached: the frontend polls status instead of waiting here. - system(`start-stop-daemon -S -b -x ${RUN} >/dev/null 2>&1 || ( setsid ${RUN} >/dev/null 2>&1 & )`); + const arg = (iface != '') ? ` ${iface}` : ''; + + system(`start-stop-daemon -S -b -x ${RUN}${arg ? ' --' + arg : ''} >/dev/null 2>&1 || ( setsid ${RUN}${arg} >/dev/null 2>&1 & )`); return { started: true }; } @@ -207,6 +288,10 @@ const methods = { if (is_running()) { const out = { running: true, phase: st.phase ?? '' }; + // Written once the run is bound. A state that is not running + // is the last run's, not this one's. + if (st.running && type(st.interface) == 'string' && st.interface != '') + out.interface = st.interface; if (st.pid) out.pid = int(st.pid); if (st.started) { @@ -219,14 +304,18 @@ const methods = { out.mbps = st.mbps + 0.0; if (st.progress != null) out.progress = int(st.progress); + out.failures = failures(); return out; } const out = { running: false, last_error: st.last_error ?? '' }; + if (out.last_error != '' && type(st.interface) == 'string' && st.interface != '') + out.interface = st.interface; if (st.last_finished) out.last_finished = int(st.last_finished); + out.failures = failures(); return out; } @@ -308,37 +397,74 @@ const methods = { config: { call: function() { const uci = cursor(); + const main_iface = config_get(uci, 'main', 'interface', 'wan'); + + // A line's section: the first enabled one naming its interface, + // legacy first, as librespeed.init picks it unless a hand-set + // interval is invalid. A bare line is legacy's. + const legacy = uci.get_all('librespeed', 'schedule'); + const owners = legacy ? [ legacy ] : []; + + uci.foreach('librespeed', 'schedule', (s) => { push(owners, s); }); + + const owner = (arg) => (arg == '') ? legacy : filter(owners, (s) => + s.interface == arg && + (s.enabled in [ '1', 'on', 'true', 'yes', 'enabled' ]))[0]; + const opt = (sec, o, fallback) => + (sec?.[o] == null || sec[o] == '') ? fallback : sec[o]; // The drawn schedule lives in the crontab, not in UCI: for a daily // interval the time is picked at sync. Handing the line out lets // the frontend show when measurements will actually run. - let cron = ''; + const schedules = []; + let own = null; const cf = open('/etc/crontabs/root', 'r'); if (cf) { - for (let line = cf.read('line'); length(line); line = cf.read('line')) - if (index(line, '/usr/libexec/librespeed-run') >= 0) - cron = trim(line); + for (let line = cf.read('line'); length(line); line = cf.read('line')) { + if (index(line, RUN) < 0) + continue; + + const f = split(trim(line), /\s+/); + const at = index(f, RUN); + const arg = (at >= 0) ? (f[at + 1] ?? '') : ''; + const sec = owner(arg); + const entry = { + interface: (arg != '') ? arg : main_iface, + interval: opt(sec, 'interval', '1d'), + days: opt(sec, 'days', '*'), + hours: opt(sec, 'hours', ''), + cron: trim(line), + next_runs: cron_next(line, 3) + }; + + push(schedules, entry); + + if (arg == '' || sec?.['.name'] == 'schedule') + own = entry; + } cf.close(); } const out = { - interface: config_get(uci, 'main', 'interface', 'wan'), + interface: main_iface, server: config_get(uci, 'main', 'server', 'auto'), scheme: config_get(uci, 'main', 'scheme', 'auto'), server_list: config_get(uci, 'main', 'server_list', ''), + // The legacy section and its own line, not another schedule's. schedule: { // What the crontab holds, not what UCI intends: a // hand-set 'true' satisfies the init script's bool but // not a string compare, and the page would say No while // cron fires. The line is the one source of truth. - enabled: cron != '', + enabled: own != null, interval: config_get(uci, 'schedule', 'interval', '1d'), days: config_get(uci, 'schedule', 'days', '*'), hours: config_get(uci, 'schedule', 'hours', ''), - cron: cron, - next_runs: cron != '' ? cron_next(cron, 3) : [] + cron: own?.cron ?? '', + next_runs: own?.next_runs ?? [] }, + schedules: schedules, history: { enabled: config_get(uci, 'history', 'enabled', '1') != '0', path: config_get(uci, 'history', 'path', @@ -351,6 +477,10 @@ const methods = { return out; } + }, + + links: { + call: links } }; diff --git a/utils/librespeed-common/test.sh b/utils/librespeed-common/test.sh index bc33849d6e..cccab262ca 100755 --- a/utils/librespeed-common/test.sh +++ b/utils/librespeed-common/test.sh @@ -1,35 +1,482 @@ #!/bin/sh # The package ships scripts and an rpcd plugin, no binary of its own, so the -# generic --version probe cannot apply; check the installed pieces instead. +# generic --version probe cannot apply; check the installed pieces and their +# behaviour instead. What the test plants uses test-only names and is removed. +# Runs and --links read UCI from a private UCI_CONFIG_DIR. The init script (its +# crontab path is fixed) and the rpcd plugin (ucode's uci cursor reads only +# /etc/config) see the live config with uncommitted changes that cleanup +# reverts, so the test refuses to start while librespeed has changes pending. + +RUN=/usr/libexec/librespeed-run +PLUGIN=/usr/share/rpcd/ucode/librespeed.uc +WORK_DIR=/tmp/librespeed-test +STATE_DIR=/tmp/librespeed +CRONTAB=/etc/crontabs/root fail() { echo "FAIL: $1"; exit 1; } -[ -x /usr/libexec/librespeed-run ] || fail "librespeed-run not installed" -[ -x /usr/libexec/librespeed-aggregate ] || fail "librespeed-aggregate not installed" -[ -f /usr/share/rpcd/ucode/librespeed.uc ] || fail "rpcd plugin not installed" -[ -f /etc/config/librespeed ] || fail "UCI config not installed" -[ -x /etc/init.d/librespeed ] || fail "init script not installed" +# expect RC ERE WHAT CMD...: CMD exits RC and prints a line matching ERE. +expect() { + local rc="$1" re="$2" what="$3" out got -sh -n /usr/libexec/librespeed-run || fail "librespeed-run does not parse" -/usr/libexec/librespeed-run --version | grep librespeed-common \ - || fail "librespeed-run --version" -/usr/libexec/librespeed-aggregate --version | grep librespeed-common \ - || fail "librespeed-aggregate --version" -sh -n /etc/init.d/librespeed || fail "init script does not parse" + shift 3 + out=$("$@" 2>&1) + got=$? + printf '%s\n' "$out" + [ "$got" = "$rc" ] || fail "$what (exit $got)" + printf '%s\n' "$out" | grep -qE -- "$re" || fail "$what" +} -# The plugin file has no side effects at load time: it defines its methods -# and returns them. Run as a file, the way rpcd loads it -- include() cannot -# be used here, it rejects the module import statements the plugin needs. -ucode /usr/share/rpcd/ucode/librespeed.uc >/dev/null \ - || fail "rpcd plugin does not load" +test_install() { + local line -# Retention must recognise epoch as jshn actually writes it -- with a space -# after the colon. The fixture comes from json_dump itself, so the check -# breaks if either side changes shape. -line=$(. /usr/share/libubox/jshn.sh; json_init; json_add_int epoch 1; json_dump) \ - || fail "jshn not usable" -echo "$line" | awk 'match($0, /"epoch":[[:space:]]*[0-9]+/) { ok = 1 } - { print } - END { exit !ok }' || fail "retention regex does not match jshn output" + echo "== test_install" + [ -x $RUN ] || fail "librespeed-run not installed" + [ -x /usr/libexec/librespeed-aggregate ] || fail "librespeed-aggregate not installed" + [ -f $PLUGIN ] || fail "rpcd plugin not installed" + [ -f /etc/config/librespeed ] || fail "UCI config not installed" + [ -x /etc/init.d/librespeed ] || fail "init script not installed" + sh -n $RUN || fail "librespeed-run does not parse" + sh -n /etc/init.d/librespeed || fail "init script does not parse" + expect 0 '^librespeed-common ' "librespeed-run --version" $RUN --version + expect 0 '^librespeed-common ' "librespeed-aggregate --version" \ + /usr/libexec/librespeed-aggregate --version + # Run as a file, the way rpcd loads it: include() rejects the module + # imports the plugin needs. Loading it has no side effects. + ucode $PLUGIN > /dev/null || fail "rpcd plugin does not load" + # Retention matches epoch as jshn writes it, with a space after the colon; + # the line comes from json_dump, so a change on either side breaks this. + line=$(. /usr/share/libubox/jshn.sh; json_init; json_add_int epoch 1; json_dump) || + fail "jshn not usable" + echo "$line" | awk 'match($0, /"epoch":[[:space:]]*[0-9]+/) { ok = 1 } + { print } + END { exit !ok }' || fail "retention regex does not match jshn output" +} +# Names outside UCI's alphabet and extra arguments are refused. +test_args() { + echo "== test_args" + expect 2 '^Usage: librespeed-run \[INTERFACE\]$' "librespeed-run accepted 'a;b'" $RUN 'a;b' + expect 2 '^Usage: librespeed-run \[INTERFACE\]$' "librespeed-run accepted 'a-b'" $RUN a-b + expect 2 '^Usage: librespeed-run \[INTERFACE\]$' "librespeed-run accepted two arguments" $RUN a b + expect 2 '^Usage: librespeed-run --links$' "--links accepted an argument" $RUN --links x +} + +# Stubs, first in PATH: ubus prints $WORK_DIR/dump as netifd's dump, +# start-stop-daemon records launches, and grep marks that the runner's client +# probe asked the client, holding it while $WORK_DIR/hold exists. The client +# of a run fails against a closed port. +setup() { + mkdir -p "$WORK_DIR/bin" "$WORK_DIR/uci" "$STATE_DIR/failed" + cp "$STATE_DIR/state.json" "$WORK_DIR/" 2>/dev/null + printf '#!/bin/sh\ncat %s/dump\n' "$WORK_DIR" > "$WORK_DIR/bin/ubus" + printf '#!/bin/sh\necho "$*" >> %s/launched\n' "$WORK_DIR" \ + > "$WORK_DIR/bin/start-stop-daemon" + # BusyBox sleep takes whole seconds only. + cat > "$WORK_DIR/bin/grep" <<-EOF + #!/bin/sh + case "\$*" in + *json-stream*) + touch $WORK_DIR/asked + while [ -e $WORK_DIR/hold ]; do sleep 1; done + ;; + esac + PATH=\${PATH#*:} exec grep "\$@" + EOF + chmod +x "$WORK_DIR/bin/ubus" "$WORK_DIR/bin/start-stop-daemon" "$WORK_DIR/bin/grep" + : > "$WORK_DIR/uci/network" + cat > "$WORK_DIR/uci/librespeed" <<-'EOF' + config librespeed 'main' + option interface 'lsdown' + option server_list 'http://127.0.0.1:1/' + EOF +} + +# planted NAME...: records the test-only (ls*) names among NAME; cleanup +# removes the failures of exactly these. +planted() { + local name + + for name; do + case "$name" in ls*) echo "$name" >> "$WORK_DIR/planted" ;; esac + done +} + +plant_failure() { # NAME TEXT + planted "$1" + echo "$2" > "$STATE_DIR/failed/$1" +} + +cleanup() { + local name + + uci revert librespeed + resync + sort -u "$WORK_DIR/planted" 2>/dev/null | while read -r name; do + rm -f "$STATE_DIR/failed/$name" + done + mv "$WORK_DIR/state.json" "$STATE_DIR/" 2>/dev/null || rm -f "$STATE_DIR/state.json" + rm -rf "$WORK_DIR" +} + +resync() { (. /lib/functions.sh; . /etc/init.d/librespeed; sync_cron); } + +# One word per interface: NAME:up|down:PROTO:L3_DEVICE:DEVICE[:dyn|:def4], +# def4 holding the IPv4 default route. netifd shows l3_device only while up. +# --links lists as down the interfaces whose link has none up on their device. +fixture() { + local word + + for word; do planted "${word%%:*}"; done + echo "$*" | awk '{ + printf "{\"interface\":[" + for (i = 1; i <= NF; i++) { + split($i, f, ":") + printf "%s{\"interface\":\"%s\",\"up\":%s,\"dynamic\":%s,\"proto\":\"%s\"", + (i > 1 ? "," : ""), f[1], (f[2] == "up" ? "true" : "false"), + (f[6] == "dyn" ? "true" : "false"), f[3] + if (f[4] != "") + printf ",\"l3_device\":\"%s\"", f[4] + if (f[5] != "") + printf ",\"device\":\"%s\"", f[5] + if (f[6] == "def4") + printf ",\"route\":[{\"target\":\"0.0.0.0\",\"mask\":0}]" + printf "}" + } + print "]}" + }' > "$WORK_DIR/dump" +} + +# --links as "RC links=... map=NAME:LINK,... down=...", not as jshn spaces it. +links_are() { + local out rc + + out=$(PATH="$WORK_DIR/bin:$PATH" UCI_CONFIG_DIR="$WORK_DIR/uci" $RUN --links) + rc=$? + out="$rc $(J="$out" ucode -e 'let v = json(getenv("J")); + print("links=", join(",", v.links), " map=", join(",", + map(sort(keys(v.interfaces)), (k) => k + ":" + v.interfaces[k])), + " down=", join(",", sort(v.down ?? [])), "\n");')" + echo "$out" + [ "$out" = "$1" ] || fail "--links: $2" +} + +test_links() { + echo "== test_links" + fixture loopback:up:static:lo:lo lan:up:static:br-lan:br-lan \ + wan:up:dhcp:eth1:eth1:def4 wan6:up:dhcpv6:eth1:eth1 + links_are "0 links=wan map=lan:lan,wan:wan,wan6:wan down=" "wan and wan6, lan not offered" + fixture wan:up:dhcp:eth1:eth1:def4 wan6:down:dhcpv6::eth1 + links_are "0 links=wan map=wan:wan,wan6:wan down=" "IPv4-only uplink" + fixture wan:down:dhcp::eth1 wan6:up:dhcpv6:eth1:eth1 + links_are "0 links=wan map=wan:wan,wan6:wan down=" "IPv6-only uplink" + fixture wan6:up:dhcpv6:eth1:eth1 + links_are "0 links=wan6 map=wan6:wan6 down=" "no IPv4 section" + fixture wan:up:pppoe:pppoe-wan:eth1:def4 wan6:up:dhcpv6:pppoe-wan:pppoe-wan + links_are "0 links=wan map=wan:wan,wan6:wan down=" "@wan while wan is up" + fixture wan:down:dhcp::eth1 wan6:down:dhcpv6:: + links_are "0 links=wan,wan6 map=wan:wan,wan6:wan6 down=wan,wan6" "@wan while wan is down" + fixture wan:up:pppoe:pppoe-wan:eth1:def4 wan_6:up:dhcpv6:pppoe-wan:pppoe-wan:dyn + links_are "0 links=wan map=wan:wan,wan_6:wan down=" "PPPoE with wan_6" + fixture wan:down:pppoe::eth1 + links_are "0 links=wan map=wan:wan down=wan" "PPPoE down" + fixture lte:up:qmi:wwan0: lte_4:up:dhcp:wwan0:wwan0:dyn wan:up:dhcp:eth1:eth1:def4 + links_are "0 links=lte,wan map=lte:lte,lte_4:lte,wan:wan down=" "qmi with lte_4" + fixture modem:up:static:eth1:eth1 vpn:up:wireguard:vpn: wan:up:dhcp:eth1:eth1:def4 + links_are "0 links=vpn,wan map=modem:wan,vpn:vpn,wan:wan down=" "modem access, wan up" + fixture modem:up:static:eth1:eth1 wan:down:dhcp::eth1 wan_4:up:dhcp:eth1:eth1:dyn + links_are "0 links=wan map=modem:modem,wan:wan down=wan" "modem access, wan down" + # A static link is offered with a default route in the dump or a gateway + # in UCI, as the dump shows routes only while an interface is up. + cat > "$WORK_DIR/uci/network" <<-'EOF' + config interface 'lan' + option ip6assign '60' + + config interface 'sgw' + option gateway '192.0.2.1' + + config interface 'sgw6' + option ip6gw '2001:db8::1' + EOF + fixture lan:up:static:br-lan:br-lan sgw:down:static::eth2 sgw6:down:static::eth3 \ + sup:up:static:eth4:eth4:def4 + links_are "0 links=sgw,sgw6,sup map=lan:lan,sgw:sgw,sgw6:sgw6,sup:sup down=sgw,sgw6" \ + "static links" + : > "$WORK_DIR/uci/network" + : > "$WORK_DIR/dump" + links_are "1 links= map= down=" "netifd unreachable" +} + +# ls_run ARG NAME: a run of ARG ('' for the default) with the stubs; prints +# NAME's recorded failure and whether the client was asked, exits as the run. +ls_run() { + local rc client=asked + + planted "$1" "$2" + rm -f "$WORK_DIR/asked" "$STATE_DIR/failed/$2" + PATH="$WORK_DIR/bin:$PATH" UCI_CONFIG_DIR="$WORK_DIR/uci" $RUN ${1:+"$1"} + rc=$? + [ -e "$WORK_DIR/asked" ] || client="not asked" + echo "$2: $(cat "$STATE_DIR/failed/$2" 2>/dev/null), client $client" + return $rc +} + +# A run is bound to the device of its link or measures nothing: a refusal is +# recorded as that name's failure and asks no client, also from cron, which +# runs the default without an argument. Bound, its failure goes under its link. +test_runs() { + local name + + echo "== test_runs" + fixture lsup:up:dhcp:eth9:eth9:def4 lsup6:up:dhcpv6:eth9:eth9 \ + lswan:down:dhcp::eth7 lswan6:up:dhcpv6:eth7:eth7 \ + lsv4:up:dhcp:eth6:eth6:def4 lsv6:down:dhcpv6::eth6 \ + lsdown:down:dhcp::eth8 lsdown6:down:dhcpv6::eth8 + expect 1 '^lsgone: [0-9]+ interface disabled or not configured, client not asked$' \ + "an interface netifd does not list was not refused" ls_run lsgone lsgone + expect 1 '^lsdown: [0-9]+ interface is down, client not asked$' \ + "a down link was not refused" ls_run lsdown lsdown + expect 1 '^lsdown: [0-9]+ interface is down, client not asked$' \ + "a down default was not refused" ls_run '' lsdown + # Bound to eth9, eth7, eth6, where an interface of the link is up: lsup6 + # beside lsup, lswan while only lswan6 is up, lsv6 while only lsv4 is. + expect 1 '^lsup: [0-9]+ .*, client asked$' \ + "a bound run did not fail at its client under its link" ls_run lsup6 lsup + expect 1 '^lswan: [0-9]+ .*, client asked$' \ + "a down interface was not bound to its link's device" ls_run lswan lswan + expect 1 '^lsv4: [0-9]+ .*, client asked$' \ + "a down wan6 was not bound to its link's device" ls_run lsv6 lsv4 + for name in lsup6 lswan6 lsv6; do + [ ! -e "$STATE_DIR/failed/$name" ] || + fail "a bound run's failure is not under its link ($name)" + done + : > "$WORK_DIR/dump" + expect 1 '^lsup: [0-9]+ netifd did not answer, client not asked$' \ + "a run went on while netifd gave no dump" ls_run lsup lsup +} + +# call METHOD: the plugin's METHOD without arguments. The runner it starts for +# links reads the private UCI; the plugin itself reads the live config. +call() { + PATH="$WORK_DIR/bin:$PATH" UCI_CONFIG_DIR="$WORK_DIR/uci" P=$PLUGIN M="$1" ucode -e ' + const m = loadfile(getenv("P"))().librespeed; + printf("%s %J\n", getenv("M"), m[getenv("M")].call({ args: {} }));' +} + +# ubus start refuses at once what a run would refuse, and launches nothing +# then; links answers an error for a silent netifd, not an empty map. A down +# interface whose link is up starts. Start without an interface runs the +# default, which the plugin takes from the live config (wan when unset). +test_start() { + local main + + echo "== test_start" + main=$(uci -q get librespeed.main.interface) + [ -n "$main" ] || main=wan + fixture "$main:up:dhcp:eth9:eth9:def4" + expect 0 '"started"' "start did not launch a link netifd lists" call start + [ -s "$WORK_DIR/launched" ] || fail "start launched nothing" + rm -f "$WORK_DIR/launched" + fixture "$main:down:dhcp::eth9" "ls${main}6:up:dhcpv6:eth9:eth9" + expect 0 '"started"' "start did not launch a down interface whose link is up" call start + [ -s "$WORK_DIR/launched" ] || fail "start launched nothing for a link that is up" + rm -f "$WORK_DIR/launched" + fixture "ls$main:up:dhcp:eth9:eth9:def4" + expect 0 '"interface disabled or not configured"' \ + "start launched a name netifd does not list" call start + fixture "$main:down:dhcp::eth9" + expect 0 '"interface is down"' "start launched a down interface" call start + : > "$WORK_DIR/dump" + expect 0 '"netifd did not answer"' "start did not refuse while netifd gave no dump" call start + [ ! -e "$WORK_DIR/launched" ] || fail "start launched a refused run" + expect 0 '"error"' "links read a silent netifd as no links" call links +} + +# A stop is no failure: it records "stopped" and leaves the interface's +# earlier failure as it was. The run is held in its client probe and stopped. +test_stop() { + local run_pid waited=0 + + echo "== test_stop" + fixture lsstop:up:dhcp:eth9:eth9 + plant_failure lsstop "1 an earlier failure" + rm -f "$WORK_DIR/asked" + touch "$WORK_DIR/hold" + PATH="$WORK_DIR/bin:$PATH" UCI_CONFIG_DIR="$WORK_DIR/uci" $RUN lsstop & + run_pid=$! + while [ ! -e "$WORK_DIR/asked" ] && [ "$waited" -lt 10 ]; do + sleep 1 + waited=$((waited + 1)) + done + kill -TERM "$run_pid" + rm -f "$WORK_DIR/hold" + wait "$run_pid" + [ $? = 1 ] && [ "$(jsonfilter -i "$STATE_DIR/state.json" -e @.last_error)" = stopped ] && + [ "$(jsonfilter -i "$STATE_DIR/state.json" -e @.interface)" = lsstop ] || + fail "a stopped run is not recorded as stopped" + [ "$(cat "$STATE_DIR/failed/lsstop")" = "1 an earlier failure" ] || + fail "a stop changed a failure" +} + +# A run that never gets the lock gives up after 3 minutes, at once here (a +# sleep stub: BusyBox ash has no builtin sleep), and records that as its +# interface's failure; state.json is the lock holder's. +test_lock() { + local state_before + + echo "== test_lock" + printf '#!/bin/sh\n' > "$WORK_DIR/bin/sleep" + chmod +x "$WORK_DIR/bin/sleep" + exec 8>/var/lock/librespeed.lock + flock -n 8 || fail "the lock is taken before the skip test" + state_before=$(cat "$STATE_DIR/state.json" 2>/dev/null) + planted lsbusy + expect 3 '^already running$' "a run that never got the lock" \ + env PATH="$WORK_DIR/bin:$PATH" UCI_CONFIG_DIR="$WORK_DIR/uci" $RUN lsbusy + exec 8>&- + rm "$WORK_DIR/bin/sleep" + grep -E '^[0-9]+ skipped: ' "$STATE_DIR/failed/lsbusy" || fail "a skipped run left no failure" + [ "$(cat "$STATE_DIR/state.json" 2>/dev/null)" = "$state_before" ] || + fail "a skipped run wrote state.json" +} + +# row INTERFACE ENABLED INTERVAL [DAYS [HOURS]]: a schedule row. +row() { + local section + + section=$(uci add librespeed schedule) + [ -n "$1" ] && uci set "librespeed.$section.interface=$1" + uci set "librespeed.$section.enabled=$2" + uci set "librespeed.$section.interval=$3" + [ -n "$4" ] && uci set "librespeed.$section.days=$4" + [ -n "$5" ] && uci set "librespeed.$section.hours=$5" +} + +# The legacy line stays bare, then one line per interface, from its first +# enabled row whose interval is valid. +test_cron() { + echo "== test_cron" + uci set librespeed.schedule.enabled=1 + row lte 1 1d 0 3 + row wan2 1 2h + row ifb 1 1d 1-5 4 + row badiv 1 90m + row off 0 1d + row lte 1 15m + row '' 1 1d + row a-b 1 1d + row lsd2 1 90m + row lsd2 1 2h + resync + grep -E '^[0-9]+ [2-5] \* \* \* /usr/libexec/librespeed-run$' $CRONTAB || fail "legacy line" + [ "$(grep -c 'librespeed-run$' $CRONTAB)" = 1 ] || fail "a second bare line" + grep -E '^[0-9]+ 3 \* \* 0 /usr/libexec/librespeed-run lte$' $CRONTAB || fail "daily line" + [ "$(grep -c 'librespeed-run lte$' $CRONTAB)" = 1 ] || fail "lte twice" + grep -E '^0 \*/2 \* \* \* /usr/libexec/librespeed-run wan2$' $CRONTAB || fail "2h line" + grep -E '^[0-9]+ 4 \* \* 1-5 /usr/libexec/librespeed-run ifb$' $CRONTAB || fail "day range" + grep -E 'librespeed-run (badiv|off|a-b)$' $CRONTAB && fail "a skipped row has a line" + grep -E '^0 \*/2 \* \* \* /usr/libexec/librespeed-run lsd2$' $CRONTAB || + fail "an invalid interval kept a later row of its interface out" + + # A changed default moves the legacy line to wan2, so the wan2 row is + # skipped, unless the legacy interval is invalid. + uci set librespeed.main.interface=wan2 + resync + [ "$(grep -c 'librespeed-run$' $CRONTAB)" = 1 ] || fail "bare line after the change" + [ "$(grep -c 'librespeed-run wan2$' $CRONTAB)" = 0 ] || fail "wan2 twice" + uci set librespeed.schedule.interval=90m + resync + [ "$(grep -c 'librespeed-run$' $CRONTAB)" = 0 ] || fail "a bare line with an invalid interval" + grep -E '^0 \*/2 \* \* \* /usr/libexec/librespeed-run wan2$' $CRONTAB || + fail "an invalid legacy interval kept the wan2 row out" +} + +# aggregates FIELD...: one line per archived aggregate, its FIELDs ("-" for +# one it lacks). +aggregates() { + local line + + while read -r line; do + J="$line" ucode -e 'const a = json(getenv("J")); + print(join(" ", map(ARGV, (f) => a[f] ?? "-")), "\n");' "$@" + done < "$WORK_DIR/archive.jsonl" +} + +# A completed day is archived as one line per interface, the unnamed first. +# A day archived before per-interface history names no interface; it is kept +# as it is, neither split nor archived again. +test_history() { + local epoch line got archived_epoch pending_epoch archived_day pending_day + + echo "== test_history" + uci set librespeed.history.path="$WORK_DIR/raw.jsonl" + uci set librespeed.history.archive_path="$WORK_DIR/archive.jsonl" + epoch=$(( $(date +%s) - 2 * 86400 )) + for line in '"interface":"wan","download_mbps":100' '"download_mbps":50' \ + '"interface":"lte","download_mbps":30' '"interface":"wan","download_mbps":200'; do + echo "{\"epoch\":$epoch,$line}" + done > "$WORK_DIR/raw.jsonl" + /usr/libexec/librespeed-aggregate + got=$(aggregates interface samples download_mbps) + echo "$got" + [ "$got" = "$(printf '%s\n' '- 1 50' 'lte 1 30' 'wan 2 150')" ] || + fail "per-interface aggregates" + + archived_epoch=$(( $(date +%s) - 4 * 86400 )) pending_epoch=$(( $(date +%s) - 2 * 86400 )) + archived_day=$(date -d "@$archived_epoch" +%Y-%m-%d) + pending_day=$(date -d "@$pending_epoch" +%Y-%m-%d) + printf '{"timestamp":"%s","epoch":%s,"samples":2,"download_mbps":65}\n' \ + "$archived_day" "$archived_epoch" > "$WORK_DIR/archive.jsonl" + printf '{"epoch":%s,"interface":"wan","download_mbps":%s}\n' \ + "$archived_epoch" 100 "$archived_epoch" 30 "$pending_epoch" 40 > "$WORK_DIR/raw.jsonl" + /usr/libexec/librespeed-aggregate + got=$(aggregates timestamp interface samples) + [ "$got" = "$(printf '%s\n' "$archived_day - 2" "$pending_day wan 1")" ] || + fail "an aggregate archived before was split or archived again" +} + +status() { + P=$PLUGIN ucode -e 'printf("%J\n", loadfile(getenv("P"))().librespeed.status.call({}));' +} + +# status lists the failures of names still configured or scheduled (the +# default, a schedule row, a network interface), not of a removed one. A run +# holding the lock before its first state write is not named after the last. +test_status() { + local name got + + echo "== test_status" + uci set librespeed.main.interface=lsmain + uci set librespeed.lsrow=schedule + uci set librespeed.lsrow.interface=lsrow + for name in lsghost lsmain lsrow; do plant_failure "$name" "1 failed"; done + got=$(status | jsonfilter -e '@.failures[*].interface' | sort | tr '\n' ' ') + case " $got " in *" lsghost "*) fail "a failure of a gone name is listed: $got" ;; esac + for name in lsmain lsrow; do + case " $got " in *" $name "*) ;; *) fail "the failure of $name is not listed: $got" ;; esac + done + + echo '{ "running": false, "interface": "lsold", "last_error": "x" }' > "$STATE_DIR/state.json" + (exec 9>/var/lock/librespeed.lock; flock 9; sleep 3) & + sleep 1 + got=$(status) + wait + [ "$(echo "$got" | jsonfilter -e @.running)" = true ] && + [ -z "$(echo "$got" | jsonfilter -e @.interface)" ] || fail "status while locked: $got" +} + +test_install +test_args +[ -z "$(uci -q changes librespeed)" ] || + fail "librespeed has uncommitted changes, which the test's cleanup would revert" +trap cleanup EXIT +setup +test_links +test_runs +test_start +test_stop +test_lock +test_cron +test_history +test_status echo "librespeed-common: installed files OK"