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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
#!/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 { 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';
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;
}
// 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() {
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;
}
// 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: {
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' };
// --start returns once the run holds the lock and status names
// it. A start already past the checks above is refused there.
const arg = (iface != '') ? ` ${iface}` : '';
const p = popen(`${RUN} --start${arg} 2>&1`, 'r');
const out = trim(p?.read('all') ?? '');
const rc = p?.close();
if (rc === 0)
return { started: true };
return { error: (rc === 3) ? 'already running' : (out || 'not started') };
}
},
stop: {
call: function() {
const st = read_json(STATE);
// The run's trap ends librespeed-cli and the sampler with it.
// Only a librespeed-run is signalled, not whatever holds the pid
// of a stale record.
const pid = int(st?.pid ?? 0);
const cmd = (pid > 1) ? (readfile(`/proc/${pid}/cmdline`) ?? '') : '';
if (is_running() && index(cmd, 'librespeed-run') >= 0)
system(`kill -TERM ${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 ?? '' };
// 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) {
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);
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;
}
},
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();
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.
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, 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: 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: own != null,
interval: config_get(uci, 'schedule', 'interval', '1d'),
days: config_get(uci, 'schedule', 'days', '*'),
hours: config_get(uci, 'schedule', 'hours', ''),
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',
`${STATE_DIR}/history.jsonl`),
retention: config_get(uci, 'history', 'retention', '30d')
}
};
uci.unload('librespeed');
return out;
}
},
links: {
call: links
}
};
return { librespeed: methods };
|