summaryrefslogtreecommitdiffstats
path: root/utils/librespeed-common/files/librespeed.uc
blob: fee8b9751a6b8af50475d3debf3643cd8fdf0ab6 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env ucode
// ubus interface for LibreSpeed measurements.
//
// Runs inside rpcd, which is exactly why it never measures anything itself: a
// measurement takes tens of seconds and would stall rpcd's event loop -- and
// with it every rpcd consumer on the system. Anything long-lived is handed to
// librespeed-run as a detached process.

'use strict';

import { open, 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 LOCK = '/var/lock/librespeed.lock';
const RUN = '/usr/libexec/librespeed-run';

function read_json(path) {
	const text = readfile(path);

	if (text == null)
		return null;

	let value = null;

	try {
		value = json(text);
	}
	catch (e) {
		value = null;
	}

	return value;
}

// The process group of a pid, read from /proc: the runner is spawned detached
// (start-stop-daemon -b or setsid), so its group holds the whole measurement
// tree and nothing else. Parsed after the comm field's closing parenthesis,
// the one place a process can put spaces.
function pgid_of(pid) {
	const st = readfile(`/proc/${pid}/stat`);

	if (!st)
		return 0;

	const f = split(trim(substr(st, rindex(st, ')') + 1)), ' ');

	return int(f[2] ?? 0);
}

// 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() {
	const f = open(LOCK, 'r');

	if (!f)
		return false;

	const acquired = f.lock('xn');

	if (acquired)
		f.lock('u');

	f.close();

	return !acquired;
}

function config_get(uci, section, option, fallback) {
	const v = uci.get('librespeed', section, option);

	return (v == null || v == '') ? fallback : v;
}

// Next occurrences of the drawn cron line, computed here rather than in the
// browser: the schedule fires in the router's timezone, and the browser may
// well sit in another one. Understands only the shapes librespeed.init
// emits: numbers, ranges, ranges with a step, star, and comma lists.
// Hoisted: ucode recompiles a regex literal on every evaluation, and these
// two dominate cron_next's cost inside rpcd, which must never stall.
const CRON_STEP = /^(.+)\/([0-9]+)$/;
const CRON_RANGE = /^([0-9]+)-([0-9]+)$/;

function cron_next(line, count) {
	const f = split(trim(line ?? ''), /\s+/);

	if (length(f) < 5)
		return [];

	const match_field = function(pat, val) {
		for (let part in split(pat, ',')) {
			let step = 1;
			let m = match(part, CRON_STEP);

			if (m) {
				part = m[1];
				step = int(m[2]);
			}

			let a, b;

			if (part == '*') {
				a = 0;
				b = 59;
			}
			else {
				m = match(part, CRON_RANGE);
				if (m) {
					a = int(m[1]);
					b = int(m[2]);
				}
				else {
					a = int(part);
					b = a;
				}
			}

			if (val >= a && val <= b && (val - a) % step == 0)
				return true;
		}

		return false;
	};

	const out = [];
	let t = time();
	t -= t % 60;

	// A miss skips the rest of the day or hour instead of walking its
	// minutes; that keeps this cheap inside rpcd's event loop, and cheap
	// enough for a five-week horizon, which a weekly schedule needs to
	// fill three rows where eight days could not. The day jump aims at
	// 23:00, not midnight: it is computed in local minutes but applied as
	// real ones, and across a spring-forward that lands an hour long --
	// from 23:00 the hour branch walks the last hour and cannot overshoot
	// into minutes that were never examined.
	for (let i = 0; i < 35 * 24 * 60 && length(out) < count; ) {
		t += 60;
		const lt = localtime(t);
		let skip;

		// % 7 folds both weekday conventions onto cron's 0-6 with Sunday 0.
		if (!match_field(f[4], lt.wday % 7)) {
			skip = (24 - lt.hour) * 60 - lt.min - 60;
			if (skip <= 0)
				skip = 60 - lt.min;
		}
		else if (!match_field(f[1], lt.hour))
			skip = 60 - lt.min;
		else {
			if (match_field(f[0], lt.min))
				push(out, t);
			i++;
			continue;
		}

		t += (skip - 1) * 60;
		i += skip;
	}

	return out;
}

const methods = {
	start: {
		call: function() {
			if (is_running())
				return { error: 'already running' };

			if (!stat(RUN))
				return { error: 'not installed' };

			// 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 & )`);

			return { started: true };
		}
	},

	stop: {
		call: function() {
			const st = read_json(STATE);

			// Kill the whole process group, not just the wrapper shell:
			// librespeed-cli and the sampler must die with it, or a "stopped"
			// answer would leave the measurement running on inherited fds.
			// busybox kill takes the negative pgid without `--`.
			if (is_running() && st?.pid) {
				const pg = pgid_of(int(st.pid));

				if (pg > 0)
					system(`kill -TERM -${pg} 2>/dev/null`);
				else
					system(`kill -TERM ${int(st.pid)} 2>/dev/null`);
			}

			return { stopped: true };
		}
	},

	status: {
		call: function() {
			const st = read_json(STATE) ?? {};

			if (is_running()) {
				const out = { running: true, phase: st.phase ?? '' };

				if (st.pid)
					out.pid = int(st.pid);
				if (st.started) {
					out.started = int(st.started);
					// Elapsed is computed here, on the clock that stamped
					// started: the browser's clock may sit anywhere.
					out.elapsed = time() - int(st.started);
				}
				if (st.mbps != null)
					out.mbps = st.mbps + 0.0;
				if (st.progress != null)
					out.progress = int(st.progress);

				return out;
			}

			const out = { running: false, last_error: st.last_error ?? '' };

			if (st.last_finished)
				out.last_finished = int(st.last_finished);

			return out;
		}
	},

	result: {
		call: function() {
			return read_json(RESULT) ?? {};
		}
	},

	// Contract: one response comes from exactly one source. A range that fits
	// the raw retention window returns raw measurements; an older range is
	// served from the daily archive at 1d resolution (completed days only, so
	// today is absent there). The two never mix in one response --
	// `resolution` names the source, and a consumer comparing two windows
	// must compare like with like.
	history: {
		args: { from: 0, to: 0, limit: 0 },
		call: function(request) {
			const from = int(request.args?.from ?? 0);
			const to = int(request.args?.to ?? 0);
			const limit = int(request.args?.limit ?? 0);

			const uci = cursor();
			const raw_path = config_get(uci, 'history', 'path',
				`${STATE_DIR}/history.jsonl`);
			const archive_path = config_get(uci, 'history', 'archive_path', '');
			const raw_days = int(config_get(uci, 'history', 'retention', '30d')) || 30;
			uci.unload('librespeed');

			// Ranges the raw window can answer come from raw; anything reaching
			// further back is served from the daily archive when one is kept.
			// The hour of slack keeps the boundary request -- "the last 30
			// days" against a 30-day window -- from flapping between sources
			// over clock skew.
			let resolution = 'raw';
			let path = raw_path;

			if (archive_path != '' && stat(archive_path) &&
			    (from == 0 || from < time() - raw_days * 86400 - 3600)) {
				resolution = '1d';
				path = archive_path;
			}

			const entries = [];
			const f = open(path, 'r');

			if (f) {
				for (let line = f.read('line'); length(line); line = f.read('line')) {
					let e = null;

					try {
						e = json(line);
					}
					catch (err) {
						continue;
					}

					if (from > 0 && int(e?.epoch ?? 0) < from)
						continue;
					if (to > 0 && int(e?.epoch ?? 0) > to)
						continue;

					push(entries, e);
				}

				f.close();
			}

			// Newest N, still oldest first.
			const kept = (limit > 0 && length(entries) > limit)
				? slice(entries, -limit) : entries;

			return { resolution: resolution, entries: kept };
		}
	},

	config: {
		call: function() {
			const uci = cursor();

			// 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 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);
				cf.close();
			}

			const out = {
				interface: config_get(uci, 'main', 'interface', 'wan'),
				server: config_get(uci, 'main', 'server', 'auto'),
				scheme: config_get(uci, 'main', 'scheme', 'auto'),
				server_list: config_get(uci, 'main', 'server_list', ''),
				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 != '',
					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) : []
				},
				history: {
					enabled: config_get(uci, 'history', 'enabled', '1') != '0',
					path: config_get(uci, 'history', 'path',
						`${STATE_DIR}/history.jsonl`),
					retention: config_get(uci, 'history', 'retention', '30d')
				}
			};

			uci.unload('librespeed');

			return out;
		}
	}
};

return { librespeed: methods };