@mark1russell7/service 0.8.18 → 0.8.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +470 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +223 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +517 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +517 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +24 -3277
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
- package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +152 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +34 -0
- package/build/watchdog.js +53 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +4 -3
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-Bgy6Gmvl.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
package/build/host.js
CHANGED
|
@@ -1,2127 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
// src/host/ports.ts
|
|
14
|
-
/** This function joins the parts of a path with the separator of the platform. */
|
|
15
|
-
const joinPath = (platform, ...parts) => {
|
|
16
|
-
const separator = platform === "win32" ? "\\" : "/";
|
|
17
|
-
const isSeparator = (char) => char === "/" || char === "\\";
|
|
18
|
-
const trim = (part, head) => {
|
|
19
|
-
let start = 0;
|
|
20
|
-
let end = part.length;
|
|
21
|
-
while (head && start < end && isSeparator(part[start])) start += 1;
|
|
22
|
-
while (end > start && isSeparator(part[end - 1])) end -= 1;
|
|
23
|
-
return part.slice(start, end);
|
|
24
|
-
};
|
|
25
|
-
return parts.map((part, at) => trim(part, at !== 0)).filter((part, at) => at === 0 || part !== "").join(separator);
|
|
26
|
-
};
|
|
27
|
-
// src/host/render.ts
|
|
28
|
-
const NAME$1 = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
29
|
-
const DAILY = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
|
30
|
-
/** This function tells if a text has a control character. Such a character can add a line to a unit, or break the task file. */
|
|
31
|
-
const hasControl = (text) => {
|
|
32
|
-
for (let at = 0; at < text.length; at += 1) {
|
|
33
|
-
const code = text.charCodeAt(at);
|
|
34
|
-
if (code < 32 || code === 127) return true;
|
|
35
|
-
}
|
|
36
|
-
return false;
|
|
37
|
-
};
|
|
38
|
-
/** This function gives the time of a daily start, or null when the text is not `HH:MM`. */
|
|
39
|
-
const dailyTime = (text) => {
|
|
40
|
-
const found = DAILY.exec(text);
|
|
41
|
-
return found === null ? null : {
|
|
42
|
-
hour: found[1],
|
|
43
|
-
minute: found[2]
|
|
44
|
-
};
|
|
45
|
-
};
|
|
46
|
-
/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */
|
|
47
|
-
const runsUntilStop = (start) => start === "logon" || start === "boot";
|
|
48
|
-
/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */
|
|
49
|
-
const inBackground = (spec) => spec.background ?? spec.start === "boot";
|
|
50
|
-
/** This function tells if a value is a time: a quantity in a unit of time. */
|
|
51
|
-
const isTime = (value) => isQuantity(value) && convertible(value.unit, "ms");
|
|
52
|
-
/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */
|
|
53
|
-
const serviceProblems = (spec) => {
|
|
54
|
-
const problems = [];
|
|
55
|
-
if (!NAME$1.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, ".", "_" and "-"`);
|
|
56
|
-
const fields = [
|
|
57
|
-
["description", spec.description],
|
|
58
|
-
["program", spec.program],
|
|
59
|
-
["stateDir", spec.stateDir],
|
|
60
|
-
...spec.args.map((arg, at) => [`argument ${at}`, arg]),
|
|
61
|
-
...spec.cwd === void 0 ? [] : [["cwd", spec.cwd]]
|
|
62
|
-
];
|
|
63
|
-
for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);
|
|
64
|
-
if (spec.program === "") problems.push("the program is empty");
|
|
65
|
-
if (spec.stateDir === "") problems.push("the stateDir is empty");
|
|
66
|
-
if (!runsUntilStop(spec.start) && dailyTime(spec.start.daily) === null) problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);
|
|
67
|
-
if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push("a daily job has no restart: give null");
|
|
68
|
-
if (spec.background !== void 0 && typeof spec.background !== "boolean") problems.push("the background is not true or false");
|
|
69
|
-
if (spec.start === "boot" && spec.background === false) problems.push("a boot start runs before a logon: give background true, or leave it out");
|
|
70
|
-
if (inBackground(spec) && spec.console === "visible") problems.push("a program in the background has no desktop: give the console hidden, or leave it out");
|
|
71
|
-
if (spec.restart !== null && !(isTime(spec.restart.after) && valueIn(spec.restart.after, "ms") >= 0)) problems.push("the restart wait is not a time of zero or more");
|
|
72
|
-
if (spec.timeLimit !== void 0 && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, "ms") > 0)) problems.push("the time limit is not a time above zero");
|
|
73
|
-
if (spec.console !== void 0 && spec.console !== "hidden" && spec.console !== "visible") problems.push(`the console ${JSON.stringify(spec.console)} is not "hidden" or "visible"`);
|
|
74
|
-
return problems;
|
|
75
|
-
};
|
|
76
|
-
/**
|
|
77
|
-
* This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.
|
|
78
|
-
* It doubles each backslash before a quote and at the end. One pass keeps the time linear.
|
|
79
|
-
*/
|
|
80
|
-
const windowsArg = (arg) => {
|
|
81
|
-
if (arg !== "" && !/[\s"]/.test(arg)) return arg;
|
|
82
|
-
let quoted = "\"";
|
|
83
|
-
let slashes = 0;
|
|
84
|
-
for (const char of arg) {
|
|
85
|
-
if (char === "\\") {
|
|
86
|
-
slashes += 1;
|
|
87
|
-
continue;
|
|
88
|
-
}
|
|
89
|
-
quoted += char === "\"" ? `${"\\".repeat(slashes * 2 + 1)}"` : `${"\\".repeat(slashes)}${char}`;
|
|
90
|
-
slashes = 0;
|
|
91
|
-
}
|
|
92
|
-
return `${quoted}${"\\".repeat(slashes * 2)}"`;
|
|
93
|
-
};
|
|
94
|
-
/**
|
|
95
|
-
* This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as
|
|
96
|
-
* `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,
|
|
97
|
-
* a quote, a backslash or a `;` goes in double quotes.
|
|
98
|
-
*/
|
|
99
|
-
const systemdArg = (arg) => {
|
|
100
|
-
const escaped = arg.replace(/%/g, () => "%%").replace(/\$/g, () => "$$");
|
|
101
|
-
if (escaped !== "" && !/[\s"'\\;]/.test(escaped)) return escaped;
|
|
102
|
-
return `"${escaped.replace(/\\/g, () => "\\\\").replace(/"/g, () => "\\\"")}"`;
|
|
103
|
-
};
|
|
104
|
-
/** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */
|
|
105
|
-
const isoSeconds = (time) => `PT${Math.max(1, Math.ceil(valueIn(time, "s")))}S`;
|
|
106
|
-
/** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */
|
|
107
|
-
const repeatMinutes = (time) => Math.max(1, Math.ceil(valueIn(time, "min")));
|
|
108
|
-
/** This function gives the seconds of a restart wait for systemd, a whole number. */
|
|
109
|
-
const restartSeconds = (time) => Math.max(0, Math.ceil(valueIn(time, "s")));
|
|
110
|
-
const refuse = (spec) => {
|
|
111
|
-
const problems = serviceProblems(spec);
|
|
112
|
-
if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join("; ")}`);
|
|
113
|
-
};
|
|
114
|
-
/**
|
|
115
|
-
* This function gives the task file of Windows for a spec, as text. It is a pure function: the same
|
|
116
|
-
* spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.
|
|
117
|
-
* - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger
|
|
118
|
-
* also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).
|
|
119
|
-
* - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).
|
|
120
|
-
* - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.
|
|
121
|
-
* Otherwise the task runs only in the session of the user (`InteractiveToken`).
|
|
122
|
-
* Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.
|
|
123
|
-
*/
|
|
124
|
-
const renderTaskXml = (spec, context) => {
|
|
125
|
-
refuse(spec);
|
|
126
|
-
const user = escapeAttribute(context.user);
|
|
127
|
-
const hidden = (spec.console ?? "hidden") === "hidden";
|
|
128
|
-
const command = hidden ? context.conhost : spec.program;
|
|
129
|
-
const args = (hidden ? [
|
|
130
|
-
"--headless",
|
|
131
|
-
spec.program,
|
|
132
|
-
...spec.args
|
|
133
|
-
] : [...spec.args]).map(windowsArg).join(" ");
|
|
134
|
-
const triggers = [];
|
|
135
|
-
if (runsUntilStop(spec.start)) {
|
|
136
|
-
triggers.push(spec.start === "logon" ? ` <LogonTrigger>
|
|
137
|
-
<Enabled>true</Enabled>
|
|
138
|
-
<UserId>${user}</UserId>
|
|
139
|
-
</LogonTrigger>` : ` <BootTrigger>
|
|
140
|
-
<Enabled>true</Enabled>
|
|
141
|
-
</BootTrigger>`);
|
|
142
|
-
if (spec.restart !== null) triggers.push(` <TimeTrigger>
|
|
143
|
-
<Enabled>true</Enabled>
|
|
144
|
-
<StartBoundary>2000-01-01T00:00:00</StartBoundary>
|
|
145
|
-
<Repetition>
|
|
146
|
-
<Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>
|
|
147
|
-
<StopAtDurationEnd>false</StopAtDurationEnd>
|
|
148
|
-
</Repetition>
|
|
149
|
-
</TimeTrigger>`);
|
|
150
|
-
} else {
|
|
151
|
-
const time = dailyTime(spec.start.daily);
|
|
152
|
-
triggers.push(` <CalendarTrigger>
|
|
153
|
-
<Enabled>true</Enabled>
|
|
154
|
-
<StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>
|
|
155
|
-
<ScheduleByDay>
|
|
156
|
-
<DaysInterval>1</DaysInterval>
|
|
157
|
-
</ScheduleByDay>
|
|
158
|
-
</CalendarTrigger>`);
|
|
159
|
-
}
|
|
160
|
-
const cwd = spec.cwd === void 0 ? "" : `\n <WorkingDirectory>${escapeAttribute(spec.cwd)}</WorkingDirectory>`;
|
|
161
|
-
const limit = spec.timeLimit === void 0 ? "PT0S" : isoSeconds(spec.timeLimit);
|
|
162
|
-
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
163
|
-
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
164
|
-
<RegistrationInfo>
|
|
165
|
-
<Description>${escapeAttribute(spec.description)}</Description>
|
|
166
|
-
<URI>\\${escapeAttribute(spec.name)}</URI>
|
|
167
|
-
</RegistrationInfo>
|
|
168
|
-
<Triggers>
|
|
169
|
-
${triggers.join("\n")}
|
|
170
|
-
</Triggers>
|
|
171
|
-
<Principals>
|
|
172
|
-
<Principal id="Author">
|
|
173
|
-
<UserId>${user}</UserId>
|
|
174
|
-
<LogonType>${inBackground(spec) ? "S4U" : "InteractiveToken"}</LogonType>
|
|
175
|
-
<RunLevel>LeastPrivilege</RunLevel>
|
|
176
|
-
</Principal>
|
|
177
|
-
</Principals>
|
|
178
|
-
<Settings>
|
|
179
|
-
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
180
|
-
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
181
|
-
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
182
|
-
<AllowHardTerminate>true</AllowHardTerminate>
|
|
183
|
-
<StartWhenAvailable>true</StartWhenAvailable>
|
|
184
|
-
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
185
|
-
<IdleSettings>
|
|
186
|
-
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
187
|
-
<RestartOnIdle>false</RestartOnIdle>
|
|
188
|
-
</IdleSettings>
|
|
189
|
-
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
190
|
-
<Enabled>true</Enabled>
|
|
191
|
-
<Hidden>false</Hidden>
|
|
192
|
-
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
193
|
-
<WakeToRun>false</WakeToRun>
|
|
194
|
-
<ExecutionTimeLimit>${limit}</ExecutionTimeLimit>
|
|
195
|
-
<Priority>5</Priority>
|
|
196
|
-
</Settings>
|
|
197
|
-
<Actions Context="Author">
|
|
198
|
-
<Exec>
|
|
199
|
-
<Command>${escapeAttribute(windowsArg(command))}</Command>
|
|
200
|
-
<Arguments>${escapeAttribute(args)}</Arguments>${cwd}
|
|
201
|
-
</Exec>
|
|
202
|
-
</Actions>
|
|
203
|
-
</Task>
|
|
204
|
-
`;
|
|
205
|
-
};
|
|
206
|
-
/** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */
|
|
207
|
-
const utf16le = (text) => {
|
|
208
|
-
const bytes = new Uint8Array(2 + text.length * 2);
|
|
209
|
-
bytes[0] = 255;
|
|
210
|
-
bytes[1] = 254;
|
|
211
|
-
for (let at = 0; at < text.length; at += 1) {
|
|
212
|
-
const unit = text.charCodeAt(at);
|
|
213
|
-
bytes[2 + at * 2] = unit & 255;
|
|
214
|
-
bytes[3 + at * 2] = unit >> 8;
|
|
215
|
-
}
|
|
216
|
-
return bytes;
|
|
217
|
-
};
|
|
218
|
-
/**
|
|
219
|
-
* This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.
|
|
220
|
-
* - A start at logon or at boot is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.
|
|
221
|
-
* The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.
|
|
222
|
-
* - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.
|
|
223
|
-
*/
|
|
224
|
-
const renderSystemdUnit = (spec) => {
|
|
225
|
-
refuse(spec);
|
|
226
|
-
const lines = [
|
|
227
|
-
"[Unit]",
|
|
228
|
-
`Description=${spec.description.replace(/%/g, "%%")}`,
|
|
229
|
-
"",
|
|
230
|
-
"[Service]"
|
|
231
|
-
];
|
|
232
|
-
lines.push(runsUntilStop(spec.start) ? "Type=simple" : "Type=oneshot");
|
|
233
|
-
lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(" ")}`);
|
|
234
|
-
if (spec.cwd !== void 0) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, "%%")}`);
|
|
235
|
-
if (spec.restart !== null) lines.push("Restart=on-failure", `RestartSec=${restartSeconds(spec.restart.after)}`);
|
|
236
|
-
if (spec.timeLimit !== void 0) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, "s")))}`);
|
|
237
|
-
if (runsUntilStop(spec.start)) lines.push("", "[Install]", "WantedBy=default.target");
|
|
238
|
-
return `${lines.join("\n")}\n`;
|
|
239
|
-
};
|
|
240
|
-
/** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon or at boot. It is a pure function. */
|
|
241
|
-
const renderSystemdTimer = (spec) => {
|
|
242
|
-
refuse(spec);
|
|
243
|
-
if (runsUntilStop(spec.start)) return null;
|
|
244
|
-
const time = dailyTime(spec.start.daily);
|
|
245
|
-
return `${[
|
|
246
|
-
"[Unit]",
|
|
247
|
-
`Description=${spec.description.replace(/%/g, "%%")}`,
|
|
248
|
-
"",
|
|
249
|
-
"[Timer]",
|
|
250
|
-
`OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,
|
|
251
|
-
"Persistent=true",
|
|
252
|
-
"",
|
|
253
|
-
"[Install]",
|
|
254
|
-
"WantedBy=timers.target"
|
|
255
|
-
].join("\n")}\n`;
|
|
256
|
-
};
|
|
257
|
-
// src/host/processes.ts
|
|
258
|
-
/**
|
|
259
|
-
* This margin is the time after a recorded start in which a process can start and still be the same
|
|
260
|
-
* process, in milliseconds. A start time on Linux comes in ticks of 10 ms, and a step of the wall clock moves a time.
|
|
261
|
-
*/
|
|
262
|
-
const START_MARGIN_MS = 1e3;
|
|
263
|
-
/**
|
|
264
|
-
* This function tells if the process of a mark is alive and is the same process. Windows and Linux
|
|
265
|
-
* use a process ID again after a process stops. Thus a live process that started after the mark is a
|
|
266
|
-
* different process. A start time that the system does not give proves nothing, and the process counts as the same.
|
|
267
|
-
*/
|
|
268
|
-
const sameProcess = async (mark, ports) => {
|
|
269
|
-
if (!Number.isInteger(mark.pid) || mark.pid <= 0) return false;
|
|
270
|
-
if (mark.pid === ports.self.pid) return Math.abs(mark.startedAt - ports.self.startedAt) <= START_MARGIN_MS;
|
|
271
|
-
if (!ports.processes.alive(mark.pid)) return false;
|
|
272
|
-
let started;
|
|
273
|
-
try {
|
|
274
|
-
started = await ports.processes.startOf(mark.pid);
|
|
275
|
-
} catch {
|
|
276
|
-
started = null;
|
|
277
|
-
}
|
|
278
|
-
return started === null || started <= mark.startedAt + 1e3;
|
|
279
|
-
};
|
|
280
|
-
/**
|
|
281
|
-
* This function stops a process and each process under it, by its ID only. It does not find a process by
|
|
282
|
-
* its name or its command line. On Windows, it starts `taskkill /T /F /PID <pid>`. On Linux, it sends
|
|
283
|
-
* SIGKILL to the process group of the ID, or to the process when it leads no group. It does not throw.
|
|
284
|
-
*/
|
|
285
|
-
const stopTree = async (pid, ports) => {
|
|
286
|
-
if (!Number.isInteger(pid) || pid <= 0) return {
|
|
287
|
-
kind: "failed",
|
|
288
|
-
problem: `${pid} is not a process ID`
|
|
289
|
-
};
|
|
290
|
-
if (pid === ports.self.pid) return {
|
|
291
|
-
kind: "failed",
|
|
292
|
-
problem: "the host does not stop its own process"
|
|
293
|
-
};
|
|
294
|
-
if (!ports.processes.alive(pid)) return { kind: "absent" };
|
|
295
|
-
if (ports.platform === "win32") {
|
|
296
|
-
const result = await ports.commands.run("taskkill", [
|
|
297
|
-
"/T",
|
|
298
|
-
"/F",
|
|
299
|
-
"/PID",
|
|
300
|
-
String(pid)
|
|
301
|
-
]).catch((error) => ({
|
|
302
|
-
code: 127,
|
|
303
|
-
out: error instanceof Error ? error.message : String(error)
|
|
304
|
-
}));
|
|
305
|
-
if (result.code === 0 || !ports.processes.alive(pid)) return { kind: "stopped" };
|
|
306
|
-
return {
|
|
307
|
-
kind: "failed",
|
|
308
|
-
problem: `taskkill gave the code ${result.code}: ${result.out}`
|
|
309
|
-
};
|
|
310
|
-
}
|
|
311
|
-
if (ports.processes.signalGroup(pid, "SIGKILL") || ports.processes.signal(pid, "SIGKILL")) return { kind: "stopped" };
|
|
312
|
-
return ports.processes.alive(pid) ? {
|
|
313
|
-
kind: "failed",
|
|
314
|
-
problem: `the signal SIGKILL did not go to the process ${pid}`
|
|
315
|
-
} : { kind: "absent" };
|
|
316
|
-
};
|
|
317
|
-
// src/host/lock.ts
|
|
318
|
-
const isMark = (value) => {
|
|
319
|
-
if (typeof value !== "object" || value === null) return false;
|
|
320
|
-
const { pid, startedAt } = value;
|
|
321
|
-
return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && typeof startedAt === "number" && Number.isFinite(startedAt);
|
|
322
|
-
};
|
|
323
|
-
/** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */
|
|
324
|
-
const parseLockOwner = (text) => {
|
|
325
|
-
try {
|
|
326
|
-
const value = JSON.parse(text);
|
|
327
|
-
if (!isMark(value)) return null;
|
|
328
|
-
const child = value.child;
|
|
329
|
-
if (child !== void 0 && child !== null && !isMark(child)) return null;
|
|
330
|
-
return {
|
|
331
|
-
pid: value.pid,
|
|
332
|
-
startedAt: value.startedAt,
|
|
333
|
-
...isMark(child) ? { child: {
|
|
334
|
-
pid: child.pid,
|
|
335
|
-
startedAt: child.startedAt
|
|
336
|
-
} } : {}
|
|
337
|
-
};
|
|
338
|
-
} catch {
|
|
339
|
-
return null;
|
|
340
|
-
}
|
|
341
|
-
};
|
|
342
|
-
/** This function gives the text of a lock file for an owner. */
|
|
343
|
-
const lockText = (owner) => `${JSON.stringify(owner)}\n`;
|
|
344
|
-
/** This function tells if the owner of a lock is alive: its process, or its child. */
|
|
345
|
-
const ownerAlive = async (owner, ports) => await sameProcess(owner, ports) || owner.child !== void 0 && await sameProcess(owner.child, ports);
|
|
346
|
-
/**
|
|
347
|
-
* This function removes a file only when it has this text: a lock file or a discovery file. The
|
|
348
|
-
* removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find
|
|
349
|
-
* the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.
|
|
350
|
-
*/
|
|
351
|
-
const removeIfSame = async (path, text, ports) => {
|
|
352
|
-
const removal = `${path}.rm`;
|
|
353
|
-
const mine = lockText({
|
|
354
|
-
pid: ports.self.pid,
|
|
355
|
-
startedAt: ports.self.startedAt
|
|
356
|
-
});
|
|
357
|
-
if (!await ports.files.create(removal, mine)) {
|
|
358
|
-
const other = parseLockOwner(await ports.files.read(removal) ?? "");
|
|
359
|
-
if (other !== null && await ownerAlive(other, ports)) return false;
|
|
360
|
-
await ports.files.remove(removal);
|
|
361
|
-
if (!await ports.files.create(removal, mine)) return false;
|
|
362
|
-
}
|
|
363
|
-
try {
|
|
364
|
-
if (await ports.files.read(path) !== text) return false;
|
|
365
|
-
await ports.files.remove(path);
|
|
366
|
-
return true;
|
|
367
|
-
} finally {
|
|
368
|
-
if (await ports.files.read(removal) === mine) await ports.files.remove(removal);
|
|
369
|
-
}
|
|
370
|
-
};
|
|
371
|
-
/** This function examines a lock file. It does not throw. */
|
|
372
|
-
const inspectInstanceLock = async (path, ports) => {
|
|
373
|
-
try {
|
|
374
|
-
const text = await ports.files.read(path);
|
|
375
|
-
if (text === null) return { kind: "free" };
|
|
376
|
-
const owner = parseLockOwner(text);
|
|
377
|
-
if (owner === null) return {
|
|
378
|
-
kind: "malformed",
|
|
379
|
-
problem: "the lock file is not a lock record"
|
|
380
|
-
};
|
|
381
|
-
if (await ownerAlive(owner, ports)) return {
|
|
382
|
-
kind: "held",
|
|
383
|
-
owner
|
|
384
|
-
};
|
|
385
|
-
return {
|
|
386
|
-
kind: "stale",
|
|
387
|
-
owner,
|
|
388
|
-
why: `the owner process ${owner.pid} stopped`
|
|
389
|
-
};
|
|
390
|
-
} catch (error) {
|
|
391
|
-
return {
|
|
392
|
-
kind: "malformed",
|
|
393
|
-
problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
};
|
|
397
|
-
/**
|
|
398
|
-
* This function takes the lock of one instance: a lock file with the record of this process. Thus a
|
|
399
|
-
* second instance does not start. It does not throw.
|
|
400
|
-
* - A file whose owner and child stopped is stale: it goes, and the take tries again.
|
|
401
|
-
* - A malformed file can be the file of a take that writes at this time. The take reads it again after
|
|
402
|
-
* a pause, and after `tries` reads, it removes it.
|
|
403
|
-
* - A file whose owner or child is alive gives `held`.
|
|
404
|
-
*/
|
|
405
|
-
const acquireInstanceLock = async (path, ports, options = {}) => {
|
|
406
|
-
const tries = options.tries ?? 3;
|
|
407
|
-
const pause = options.pause ?? 100;
|
|
408
|
-
const owner = {
|
|
409
|
-
pid: ports.self.pid,
|
|
410
|
-
startedAt: ports.self.startedAt,
|
|
411
|
-
...options.child === void 0 ? {} : { child: options.child }
|
|
412
|
-
};
|
|
413
|
-
let recovered = null;
|
|
414
|
-
let malformed = 0;
|
|
415
|
-
try {
|
|
416
|
-
for (let attempt = 0; attempt < tries + 3; attempt += 1) {
|
|
417
|
-
const text = lockText(owner);
|
|
418
|
-
if (await ports.files.create(path, text)) {
|
|
419
|
-
ports.logger?.log("info", `the host took the lock ${path}`, {
|
|
420
|
-
path,
|
|
421
|
-
pid: owner.pid,
|
|
422
|
-
...recovered === null ? {} : { recovered }
|
|
423
|
-
});
|
|
424
|
-
return {
|
|
425
|
-
kind: "acquired",
|
|
426
|
-
lock: held(path, owner, text, ports),
|
|
427
|
-
recovered
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
const found = await ports.files.read(path);
|
|
431
|
-
if (found === null) continue;
|
|
432
|
-
const other = parseLockOwner(found);
|
|
433
|
-
if (other === null) {
|
|
434
|
-
malformed += 1;
|
|
435
|
-
if (malformed < tries) {
|
|
436
|
-
await delay(ports.clock, pause);
|
|
437
|
-
continue;
|
|
438
|
-
}
|
|
439
|
-
if (await removeIfSame(path, found, ports)) recovered = "the lock file was not a lock record";
|
|
440
|
-
continue;
|
|
441
|
-
}
|
|
442
|
-
if (await ownerAlive(other, ports)) return {
|
|
443
|
-
kind: "held",
|
|
444
|
-
owner: other
|
|
445
|
-
};
|
|
446
|
-
if (await removeIfSame(path, found, ports)) {
|
|
447
|
-
recovered = `the owner process ${other.pid} stopped`;
|
|
448
|
-
ports.logger?.log("warn", `the host removed the stale lock ${path}: ${recovered}`, {
|
|
449
|
-
path,
|
|
450
|
-
owner: other
|
|
451
|
-
});
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
return {
|
|
455
|
-
kind: "failed",
|
|
456
|
-
problem: `the lock ${path} did not come free after ${tries + 3} tries`
|
|
457
|
-
};
|
|
458
|
-
} catch (error) {
|
|
459
|
-
return {
|
|
460
|
-
kind: "failed",
|
|
461
|
-
problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}`
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
};
|
|
465
|
-
/** This function gives the handle of a lock that this process holds. */
|
|
466
|
-
const held = (path, first, firstText, ports) => {
|
|
467
|
-
let owner = first;
|
|
468
|
-
let text = firstText;
|
|
469
|
-
let released = false;
|
|
470
|
-
let queue = Promise.resolve();
|
|
471
|
-
const enqueue = (work) => {
|
|
472
|
-
const next = queue.then(work);
|
|
473
|
-
queue = next.catch(() => {});
|
|
474
|
-
return next;
|
|
475
|
-
};
|
|
476
|
-
return {
|
|
477
|
-
path,
|
|
478
|
-
get owner() {
|
|
479
|
-
return owner;
|
|
480
|
-
},
|
|
481
|
-
update: (child) => enqueue(async () => {
|
|
482
|
-
if (released) return;
|
|
483
|
-
const next = {
|
|
484
|
-
pid: owner.pid,
|
|
485
|
-
startedAt: owner.startedAt,
|
|
486
|
-
...child === null ? {} : { child }
|
|
487
|
-
};
|
|
488
|
-
const nextText = lockText(next);
|
|
489
|
-
await ports.files.write(path, nextText);
|
|
490
|
-
owner = next;
|
|
491
|
-
text = nextText;
|
|
492
|
-
}),
|
|
493
|
-
release: () => enqueue(async () => {
|
|
494
|
-
if (released) return;
|
|
495
|
-
released = true;
|
|
496
|
-
try {
|
|
497
|
-
await removeIfSame(path, text, ports);
|
|
498
|
-
} catch {}
|
|
499
|
-
})
|
|
500
|
-
};
|
|
501
|
-
};
|
|
502
|
-
// src/host/discovery.ts
|
|
503
|
-
const isPort = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
504
|
-
/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
|
|
505
|
-
const parseDiscovery = (text) => {
|
|
506
|
-
let value;
|
|
507
|
-
try {
|
|
508
|
-
value = JSON.parse(text);
|
|
509
|
-
} catch (error) {
|
|
510
|
-
return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;
|
|
511
|
-
}
|
|
512
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return "the file is not a JSON object";
|
|
513
|
-
const { pid, startedAt, port, url, extra } = value;
|
|
514
|
-
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return "the field pid is not a process ID";
|
|
515
|
-
if (typeof startedAt !== "string" || !Number.isFinite(Date.parse(startedAt))) return "the field startedAt is not an ISO time";
|
|
516
|
-
if (port !== null && port !== void 0 && !isPort(port)) return "the field port is not a port from 1 to 65535";
|
|
517
|
-
if (url !== null && url !== void 0 && typeof url !== "string") return "the field url is not a text";
|
|
518
|
-
if (extra !== void 0 && (typeof extra !== "object" || extra === null || Array.isArray(extra))) return "the field extra is not an object";
|
|
519
|
-
return {
|
|
520
|
-
pid,
|
|
521
|
-
startedAt,
|
|
522
|
-
port: isPort(port) ? port : null,
|
|
523
|
-
url: typeof url === "string" ? url : null,
|
|
524
|
-
...extra === void 0 ? {} : { extra }
|
|
525
|
-
};
|
|
526
|
-
};
|
|
527
|
-
/** This function gives the discovery record of the process of the host, with its start time. */
|
|
528
|
-
const discoveryOf = (fields, ports) => ({
|
|
529
|
-
pid: ports.self.pid,
|
|
530
|
-
startedAt: new Date(ports.self.startedAt).toISOString(),
|
|
531
|
-
port: fields.port ?? null,
|
|
532
|
-
url: fields.url ?? null,
|
|
533
|
-
...fields.extra === void 0 ? {} : { extra: fields.extra }
|
|
534
|
-
});
|
|
535
|
-
/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
|
|
536
|
-
const writeDiscovery = async (path, record, ports) => {
|
|
537
|
-
await ports.files.write(path, `${JSON.stringify(record, null, 2)}\n`);
|
|
538
|
-
};
|
|
539
|
-
/**
|
|
540
|
-
* This function reads a discovery file and examines its process. It does not throw: a file that is not
|
|
541
|
-
* a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
|
|
542
|
-
*/
|
|
543
|
-
const readDiscovery = async (path, ports, options = {}) => {
|
|
544
|
-
const { found, text } = await examine(path, ports);
|
|
545
|
-
if (options.clean === true && text !== null && (found.kind === "stale" || found.kind === "malformed")) try {
|
|
546
|
-
if (await removeIfSame(path, text, ports)) ports.logger?.log("info", `the host removed the ${found.kind} discovery file ${path}`, {
|
|
547
|
-
path,
|
|
548
|
-
kind: found.kind
|
|
549
|
-
});
|
|
550
|
-
} catch {}
|
|
551
|
-
return found;
|
|
552
|
-
};
|
|
553
|
-
const examine = async (path, ports) => {
|
|
554
|
-
let text;
|
|
555
|
-
try {
|
|
556
|
-
text = await ports.files.read(path);
|
|
557
|
-
} catch (error) {
|
|
558
|
-
return {
|
|
559
|
-
found: {
|
|
560
|
-
kind: "malformed",
|
|
561
|
-
problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
|
|
562
|
-
},
|
|
563
|
-
text: null
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
if (text === null) return {
|
|
567
|
-
found: { kind: "absent" },
|
|
568
|
-
text
|
|
569
|
-
};
|
|
570
|
-
const record = parseDiscovery(text);
|
|
571
|
-
if (typeof record === "string") return {
|
|
572
|
-
found: {
|
|
573
|
-
kind: "malformed",
|
|
574
|
-
problem: record
|
|
575
|
-
},
|
|
576
|
-
text
|
|
577
|
-
};
|
|
578
|
-
const mark = {
|
|
579
|
-
pid: record.pid,
|
|
580
|
-
startedAt: Date.parse(record.startedAt)
|
|
581
|
-
};
|
|
582
|
-
if (await sameProcess(mark, ports)) return {
|
|
583
|
-
found: {
|
|
584
|
-
kind: "running",
|
|
585
|
-
record
|
|
586
|
-
},
|
|
587
|
-
text
|
|
588
|
-
};
|
|
589
|
-
return {
|
|
590
|
-
found: {
|
|
591
|
-
kind: "stale",
|
|
592
|
-
record,
|
|
593
|
-
why: ports.processes.alive(record.pid) ? `the process ${record.pid} started after the record, thus it is a different process` : `the process ${record.pid} stopped`
|
|
594
|
-
},
|
|
595
|
-
text
|
|
596
|
-
};
|
|
597
|
-
};
|
|
598
|
-
/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
|
|
599
|
-
const removeDiscovery = async (path, ports, pid = ports.self.pid) => {
|
|
600
|
-
try {
|
|
601
|
-
const text = await ports.files.read(path);
|
|
602
|
-
if (text === null) return false;
|
|
603
|
-
const record = parseDiscovery(text);
|
|
604
|
-
if (typeof record === "string" || record.pid !== pid) return false;
|
|
605
|
-
return await removeIfSame(path, text, ports);
|
|
606
|
-
} catch {
|
|
607
|
-
return false;
|
|
608
|
-
}
|
|
609
|
-
};
|
|
610
|
-
// src/host/install.ts
|
|
611
|
-
/** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */
|
|
612
|
-
const unitDir = (ports) => {
|
|
613
|
-
const config = ports.env["XDG_CONFIG_HOME"];
|
|
614
|
-
return joinPath("linux", config === void 0 || config === "" ? joinPath("linux", ports.homeDir, ".config") : config, "systemd", "user");
|
|
615
|
-
};
|
|
616
|
-
/** This function gives the files of a service on the platform of the ports. */
|
|
617
|
-
const servicePaths = (spec, ports) => {
|
|
618
|
-
if (ports.platform === "win32") return {
|
|
619
|
-
unit: joinPath("win32", spec.stateDir, `${spec.name}.task.xml`),
|
|
620
|
-
timer: null
|
|
621
|
-
};
|
|
622
|
-
const dir = unitDir(ports);
|
|
623
|
-
return {
|
|
624
|
-
unit: joinPath("linux", dir, `${spec.name}.service`),
|
|
625
|
-
timer: runsUntilStop(spec.start) ? null : joinPath("linux", dir, `${spec.name}.timer`)
|
|
626
|
-
};
|
|
627
|
-
};
|
|
628
|
-
/** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */
|
|
629
|
-
const enabledUnit = (spec) => runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`;
|
|
630
|
-
/**
|
|
631
|
-
* This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger
|
|
632
|
-
* and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).
|
|
633
|
-
*/
|
|
634
|
-
const ELEVATION = "Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator";
|
|
635
|
-
/** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */
|
|
636
|
-
const conhostPath = (ports) => joinPath("win32", ports.env["SystemRoot"] ?? "%SystemRoot%", "System32", "conhost.exe");
|
|
637
|
-
const runner = (ports) => {
|
|
638
|
-
const commands = [];
|
|
639
|
-
return {
|
|
640
|
-
commands,
|
|
641
|
-
async run(file, args) {
|
|
642
|
-
let record;
|
|
643
|
-
try {
|
|
644
|
-
const result = await ports.commands.run(file, args);
|
|
645
|
-
record = {
|
|
646
|
-
file,
|
|
647
|
-
args,
|
|
648
|
-
code: result.code,
|
|
649
|
-
out: result.out.trim()
|
|
650
|
-
};
|
|
651
|
-
} catch (error) {
|
|
652
|
-
record = {
|
|
653
|
-
file,
|
|
654
|
-
args,
|
|
655
|
-
code: 127,
|
|
656
|
-
out: error instanceof Error ? error.message : String(error)
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
|
-
commands.push(record);
|
|
660
|
-
ports.logger?.log(record.code === 0 ? "debug" : "warn", `${file} ${args.join(" ")} gave the code ${record.code}`, { ...record });
|
|
661
|
-
return record;
|
|
662
|
-
}
|
|
663
|
-
};
|
|
664
|
-
};
|
|
665
|
-
const failed = (commands, record, note) => ({
|
|
666
|
-
kind: "failed",
|
|
667
|
-
commands,
|
|
668
|
-
problem: `${record.file} ${record.args.join(" ")} gave the code ${record.code}${record.out === "" ? "" : `: ${record.out}`}${note === null ? "" : ` (${note})`}`
|
|
669
|
-
});
|
|
670
|
-
/** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */
|
|
671
|
-
const noteOf = (spec, ports, record) => ports.platform === "win32" && record.file === "schtasks" && inBackground(spec) ? ELEVATION : null;
|
|
672
|
-
const problemOf = (error) => error instanceof Error ? error.message : String(error);
|
|
673
|
-
/**
|
|
674
|
-
* This function runs the steps of an operation. It refuses a spec with problems and a platform that
|
|
675
|
-
* is not Windows or Linux, and it catches each failure of the file system.
|
|
676
|
-
*/
|
|
677
|
-
const operate = async (spec, ports, steps) => {
|
|
678
|
-
const problems = serviceProblems(spec);
|
|
679
|
-
if (problems.length > 0) return {
|
|
680
|
-
kind: "refused",
|
|
681
|
-
problems
|
|
682
|
-
};
|
|
683
|
-
if (ports.platform !== "win32" && ports.platform !== "linux") return {
|
|
684
|
-
kind: "unsupported",
|
|
685
|
-
platform: ports.platform
|
|
686
|
-
};
|
|
687
|
-
const run = runner(ports);
|
|
688
|
-
const files = [];
|
|
689
|
-
try {
|
|
690
|
-
const failure = await steps(run, files);
|
|
691
|
-
if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));
|
|
692
|
-
} catch (error) {
|
|
693
|
-
return {
|
|
694
|
-
kind: "failed",
|
|
695
|
-
commands: run.commands,
|
|
696
|
-
problem: `the file system failed: ${problemOf(error)}`
|
|
697
|
-
};
|
|
698
|
-
}
|
|
699
|
-
return {
|
|
700
|
-
kind: "done",
|
|
701
|
-
commands: run.commands,
|
|
702
|
-
files
|
|
703
|
-
};
|
|
704
|
-
};
|
|
705
|
-
/** This function gives the first record whose code is not 0, or null. */
|
|
706
|
-
const firstFailure = (...records) => records.find((record) => record.code !== 0) ?? null;
|
|
707
|
-
/**
|
|
708
|
-
* This function installs a service of the user, and by default starts it. It does not throw.
|
|
709
|
-
* - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.
|
|
710
|
-
* - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.
|
|
711
|
-
* For a spec in the background, it first starts `loginctl enable-linger` for the user.
|
|
712
|
-
* A second install replaces the first. Give it the ports of a test, thus no test installs a real task.
|
|
713
|
-
* On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.
|
|
714
|
-
*/
|
|
715
|
-
const installService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
|
|
716
|
-
const start = options.start ?? true;
|
|
717
|
-
const paths = servicePaths(spec, ports);
|
|
718
|
-
if (ports.platform === "win32") {
|
|
719
|
-
await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, {
|
|
720
|
-
user: ports.user(),
|
|
721
|
-
conhost: conhostPath(ports)
|
|
722
|
-
})));
|
|
723
|
-
files.push(paths.unit);
|
|
724
|
-
const created = await run.run("schtasks", [
|
|
725
|
-
"/Create",
|
|
726
|
-
"/TN",
|
|
727
|
-
spec.name,
|
|
728
|
-
"/XML",
|
|
729
|
-
paths.unit,
|
|
730
|
-
"/F"
|
|
731
|
-
]);
|
|
732
|
-
if (created.code !== 0 || !start) return firstFailure(created);
|
|
733
|
-
return firstFailure(await run.run("schtasks", [
|
|
734
|
-
"/Run",
|
|
735
|
-
"/TN",
|
|
736
|
-
spec.name
|
|
737
|
-
]));
|
|
738
|
-
}
|
|
739
|
-
await ports.files.write(paths.unit, renderSystemdUnit(spec));
|
|
740
|
-
files.push(paths.unit);
|
|
741
|
-
const timer = renderSystemdTimer(spec);
|
|
742
|
-
if (paths.timer !== null && timer !== null) {
|
|
743
|
-
await ports.files.write(paths.timer, timer);
|
|
744
|
-
files.push(paths.timer);
|
|
745
|
-
}
|
|
746
|
-
if (inBackground(spec)) {
|
|
747
|
-
const lingered = await run.run("loginctl", ["enable-linger"]);
|
|
748
|
-
if (lingered.code !== 0) return lingered;
|
|
749
|
-
}
|
|
750
|
-
const reloaded = await run.run("systemctl", ["--user", "daemon-reload"]);
|
|
751
|
-
if (reloaded.code !== 0) return reloaded;
|
|
752
|
-
return firstFailure(await run.run("systemctl", [
|
|
753
|
-
"--user",
|
|
754
|
-
"enable",
|
|
755
|
-
...start ? ["--now"] : [],
|
|
756
|
-
enabledUnit(spec)
|
|
757
|
-
]));
|
|
758
|
-
});
|
|
759
|
-
/** This function stops the instance of a discovery file, when it is alive and is the same process. */
|
|
760
|
-
const stopInstance = async (ports, options) => {
|
|
761
|
-
if (options.discovery === void 0) return;
|
|
762
|
-
const found = await readDiscovery(options.discovery, ports, { clean: true });
|
|
763
|
-
if (found.kind !== "running") return;
|
|
764
|
-
const stopped = await stopTree(found.record.pid, ports);
|
|
765
|
-
ports.logger?.log(stopped.kind === "failed" ? "warn" : "info", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {
|
|
766
|
-
pid: found.record.pid,
|
|
767
|
-
outcome: stopped.kind
|
|
768
|
-
});
|
|
769
|
-
};
|
|
770
|
-
/**
|
|
771
|
-
* This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On
|
|
772
|
-
* Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,
|
|
773
|
-
* it then stops the process tree of an instance that stays.
|
|
774
|
-
*/
|
|
775
|
-
const uninstallService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
|
|
776
|
-
const paths = servicePaths(spec, ports);
|
|
777
|
-
let failure;
|
|
778
|
-
if (ports.platform === "win32") {
|
|
779
|
-
await run.run("schtasks", [
|
|
780
|
-
"/End",
|
|
781
|
-
"/TN",
|
|
782
|
-
spec.name
|
|
783
|
-
]);
|
|
784
|
-
failure = firstFailure(await run.run("schtasks", [
|
|
785
|
-
"/Delete",
|
|
786
|
-
"/TN",
|
|
787
|
-
spec.name,
|
|
788
|
-
"/F"
|
|
789
|
-
]));
|
|
790
|
-
await ports.files.remove(paths.unit);
|
|
791
|
-
} else {
|
|
792
|
-
failure = firstFailure(await run.run("systemctl", [
|
|
793
|
-
"--user",
|
|
794
|
-
"disable",
|
|
795
|
-
"--now",
|
|
796
|
-
enabledUnit(spec)
|
|
797
|
-
]));
|
|
798
|
-
if (paths.timer !== null) await run.run("systemctl", [
|
|
799
|
-
"--user",
|
|
800
|
-
"stop",
|
|
801
|
-
`${spec.name}.service`
|
|
802
|
-
]);
|
|
803
|
-
await ports.files.remove(paths.unit);
|
|
804
|
-
if (paths.timer !== null) await ports.files.remove(paths.timer);
|
|
805
|
-
await run.run("systemctl", ["--user", "daemon-reload"]);
|
|
806
|
-
}
|
|
807
|
-
files.push(paths.unit, ...paths.timer === null ? [] : [paths.timer]);
|
|
808
|
-
await stopInstance(ports, options);
|
|
809
|
-
return failure;
|
|
810
|
-
});
|
|
811
|
-
/** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */
|
|
812
|
-
const startService = (spec, ports) => operate(spec, ports, async (run) => {
|
|
813
|
-
if (ports.platform === "win32") {
|
|
814
|
-
const enabled = await run.run("schtasks", [
|
|
815
|
-
"/Change",
|
|
816
|
-
"/TN",
|
|
817
|
-
spec.name,
|
|
818
|
-
"/ENABLE"
|
|
819
|
-
]);
|
|
820
|
-
if (enabled.code !== 0) return enabled;
|
|
821
|
-
return firstFailure(await run.run("schtasks", [
|
|
822
|
-
"/Run",
|
|
823
|
-
"/TN",
|
|
824
|
-
spec.name
|
|
825
|
-
]));
|
|
826
|
-
}
|
|
827
|
-
return firstFailure(await run.run("systemctl", [
|
|
828
|
-
"--user",
|
|
829
|
-
"enable",
|
|
830
|
-
"--now",
|
|
831
|
-
enabledUnit(spec)
|
|
832
|
-
]));
|
|
833
|
-
});
|
|
834
|
-
/**
|
|
835
|
-
* This function stops a service, and keeps it stopped until `startService`. It does not throw.
|
|
836
|
-
* - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
|
|
837
|
-
* With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
|
|
838
|
-
* - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.
|
|
839
|
-
* Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,
|
|
840
|
-
* thus `run()` stops in its stages. A daily job that operates stops too.
|
|
841
|
-
*/
|
|
842
|
-
const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
|
|
843
|
-
if (ports.platform === "win32") {
|
|
844
|
-
const disabled = await run.run("schtasks", [
|
|
845
|
-
"/Change",
|
|
846
|
-
"/TN",
|
|
847
|
-
spec.name,
|
|
848
|
-
"/DISABLE"
|
|
849
|
-
]);
|
|
850
|
-
if (disabled.code !== 0) return disabled;
|
|
851
|
-
await run.run("schtasks", [
|
|
852
|
-
"/End",
|
|
853
|
-
"/TN",
|
|
854
|
-
spec.name
|
|
855
|
-
]);
|
|
856
|
-
await stopInstance(ports, options);
|
|
857
|
-
return null;
|
|
858
|
-
}
|
|
859
|
-
const disabled = await run.run("systemctl", [
|
|
860
|
-
"--user",
|
|
861
|
-
"disable",
|
|
862
|
-
"--now",
|
|
863
|
-
enabledUnit(spec)
|
|
864
|
-
]);
|
|
865
|
-
if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);
|
|
866
|
-
return firstFailure(await run.run("systemctl", [
|
|
867
|
-
"--user",
|
|
868
|
-
"stop",
|
|
869
|
-
`${spec.name}.service`
|
|
870
|
-
]));
|
|
871
|
-
});
|
|
872
|
-
/** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */
|
|
873
|
-
const listValue = (out, key) => {
|
|
874
|
-
for (const line of out.split(/\r?\n/)) {
|
|
875
|
-
const at = line.indexOf(":");
|
|
876
|
-
if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();
|
|
877
|
-
}
|
|
878
|
-
return null;
|
|
879
|
-
};
|
|
880
|
-
/**
|
|
881
|
-
* This function gives the status of a service. It does not throw. A service that the system does not
|
|
882
|
-
* have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.
|
|
883
|
-
*/
|
|
884
|
-
const serviceStatus = async (spec, ports, options = {}) => {
|
|
885
|
-
const run = runner(ports);
|
|
886
|
-
const instance = options.discovery === void 0 ? null : await readDiscovery(options.discovery, ports);
|
|
887
|
-
if (serviceProblems(spec).length > 0 || ports.platform !== "win32" && ports.platform !== "linux") return {
|
|
888
|
-
installed: false,
|
|
889
|
-
state: "unknown",
|
|
890
|
-
instance,
|
|
891
|
-
commands: run.commands
|
|
892
|
-
};
|
|
893
|
-
if (ports.platform === "win32") {
|
|
894
|
-
const query = await run.run("schtasks", [
|
|
895
|
-
"/Query",
|
|
896
|
-
"/TN",
|
|
897
|
-
spec.name,
|
|
898
|
-
"/V",
|
|
899
|
-
"/FO",
|
|
900
|
-
"LIST"
|
|
901
|
-
]);
|
|
902
|
-
if (query.code !== 0) return {
|
|
903
|
-
installed: false,
|
|
904
|
-
state: "unknown",
|
|
905
|
-
instance,
|
|
906
|
-
commands: run.commands
|
|
907
|
-
};
|
|
908
|
-
return {
|
|
909
|
-
installed: true,
|
|
910
|
-
state: listValue(query.out, "Status") ?? "unknown",
|
|
911
|
-
instance,
|
|
912
|
-
commands: run.commands
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
let installed;
|
|
916
|
-
try {
|
|
917
|
-
installed = await ports.files.read(servicePaths(spec, ports).unit) !== null;
|
|
918
|
-
} catch {
|
|
919
|
-
installed = false;
|
|
920
|
-
}
|
|
921
|
-
const state = (await run.run("systemctl", [
|
|
922
|
-
"--user",
|
|
923
|
-
"is-active",
|
|
924
|
-
`${spec.name}.service`
|
|
925
|
-
])).out.split(/\r?\n/)[0]?.trim() ?? "";
|
|
926
|
-
return {
|
|
927
|
-
installed,
|
|
928
|
-
state: state === "" ? "unknown" : state,
|
|
929
|
-
instance,
|
|
930
|
-
commands: run.commands
|
|
931
|
-
};
|
|
932
|
-
};
|
|
933
|
-
// src/host/probes.ts
|
|
934
|
-
/** This size is the largest answer that a probe with freshness bounds reads: 1 MiB. */
|
|
935
|
-
const PROBE_BODY_LIMIT = 1048576;
|
|
936
|
-
const isPointer = (pointer) => typeof pointer === "string" && (pointer === "" || pointer.startsWith("/") && !/~[^01]|~$/.test(pointer));
|
|
937
|
-
/** This function gives the problems of a probe: each value that a probe cannot use. */
|
|
938
|
-
const probeProblems = (probe) => {
|
|
939
|
-
if (probe.kind === "http") {
|
|
940
|
-
const problems = [];
|
|
941
|
-
if (!/^https?:\/\//.test(probe.url)) problems.push(`the address ${JSON.stringify(probe.url)} is not an http or https address`);
|
|
942
|
-
if (probe.status !== void 0 && !(Number.isInteger(probe.status) && probe.status >= 100 && probe.status <= 599)) problems.push(`the status ${probe.status} is not an HTTP status`);
|
|
943
|
-
if (probe.now !== void 0 && !isPointer(probe.now)) problems.push(`the now ${JSON.stringify(probe.now)} is not a JSON Pointer`);
|
|
944
|
-
if (probe.now !== void 0 && probe.fresh === void 0) problems.push("the probe has a now, but no fresh list");
|
|
945
|
-
if (probe.fresh !== void 0 && probe.fresh.length === 0) problems.push("the fresh list is empty");
|
|
946
|
-
for (const bound of probe.fresh ?? []) {
|
|
947
|
-
if (!isPointer(bound.pointer)) problems.push(`the freshness pointer ${JSON.stringify(bound.pointer)} is not a JSON Pointer`);
|
|
948
|
-
if (!(isQuantity(bound.within) && convertible(bound.within.unit, "ms") && valueIn(bound.within, "ms") >= 0)) problems.push(`the freshness bound of ${JSON.stringify(bound.pointer)} is not a time of zero or more`);
|
|
949
|
-
}
|
|
950
|
-
return problems;
|
|
951
|
-
}
|
|
952
|
-
if (probe.kind === "tcp") return Number.isInteger(probe.port) && probe.port >= 1 && probe.port <= 65535 ? [] : [`the port ${probe.port} is not a port from 1 to 65535`];
|
|
953
|
-
if (probe.kind === "command") return probe.program === "" ? ["the program of the command probe is empty"] : [];
|
|
954
|
-
return [`the probe kind ${JSON.stringify(probe.kind)} is not http, tcp or command`];
|
|
955
|
-
};
|
|
956
|
-
/** This function gives the value at a JSON Pointer (RFC 6901), or undefined when the document does not have it. */
|
|
957
|
-
const pointAt = (document, pointer) => {
|
|
958
|
-
if (pointer === "") return document;
|
|
959
|
-
let at = document;
|
|
960
|
-
for (const token of pointer.slice(1).split("/")) {
|
|
961
|
-
const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
962
|
-
if (Array.isArray(at)) {
|
|
963
|
-
if (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= at.length) return void 0;
|
|
964
|
-
at = at[Number(key)];
|
|
965
|
-
} else if (at !== null && typeof at === "object" && Object.hasOwn(at, key)) at = at[key];
|
|
966
|
-
else return void 0;
|
|
967
|
-
}
|
|
968
|
-
return at;
|
|
969
|
-
};
|
|
970
|
-
/** This function gives the time of a value in epoch milliseconds: a finite number, or an ISO 8601 text. */
|
|
971
|
-
const timeOf = (value) => {
|
|
972
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
973
|
-
if (typeof value === "string") {
|
|
974
|
-
const time = Date.parse(value);
|
|
975
|
-
return Number.isNaN(time) ? null : time;
|
|
976
|
-
}
|
|
977
|
-
return null;
|
|
978
|
-
};
|
|
979
|
-
/** This function examines the JSON answer of an http probe against its freshness bounds. */
|
|
980
|
-
const freshness = (url, body, bounds, nowPointer, wall) => {
|
|
981
|
-
let document;
|
|
982
|
-
try {
|
|
983
|
-
document = JSON.parse(body);
|
|
984
|
-
} catch {
|
|
985
|
-
return {
|
|
986
|
-
ok: false,
|
|
987
|
-
why: `${url} did not give JSON`
|
|
988
|
-
};
|
|
989
|
-
}
|
|
990
|
-
const now = nowPointer === void 0 ? wall : timeOf(pointAt(document, nowPointer));
|
|
991
|
-
if (now === null) return {
|
|
992
|
-
ok: false,
|
|
993
|
-
why: `${url} has no time at ${nowPointer}`
|
|
994
|
-
};
|
|
995
|
-
const stale = [];
|
|
996
|
-
for (const bound of bounds) {
|
|
997
|
-
const time = timeOf(pointAt(document, bound.pointer));
|
|
998
|
-
if (time === null) {
|
|
999
|
-
stale.push(`${bound.pointer} has no time`);
|
|
1000
|
-
continue;
|
|
1001
|
-
}
|
|
1002
|
-
const age = Math.max(0, now - time);
|
|
1003
|
-
if (age > valueIn(bound.within, "ms")) stale.push(`${bound.pointer} is ${formatDuration({
|
|
1004
|
-
value: age,
|
|
1005
|
-
unit: "ms"
|
|
1006
|
-
})} old, above ${formatDuration(bound.within)}`);
|
|
1007
|
-
}
|
|
1008
|
-
return stale.length === 0 ? { ok: true } : {
|
|
1009
|
-
ok: false,
|
|
1010
|
-
why: `${url}: ${stale.join("; ")}`
|
|
1011
|
-
};
|
|
1012
|
-
};
|
|
1013
|
-
/** This function uses a probe one time, in a timeout of milliseconds. It does not throw. */
|
|
1014
|
-
const probeOnce = async (probe, timeout, ports) => {
|
|
1015
|
-
try {
|
|
1016
|
-
if (probe.kind === "http") {
|
|
1017
|
-
const want = probe.status ?? 200;
|
|
1018
|
-
if (probe.fresh !== void 0) {
|
|
1019
|
-
if (ports.net.httpText === void 0) return {
|
|
1020
|
-
ok: false,
|
|
1021
|
-
why: "the net port cannot read an answer, thus it cannot examine freshness"
|
|
1022
|
-
};
|
|
1023
|
-
const answer = await ports.net.httpText(probe.url, timeout, PROBE_BODY_LIMIT);
|
|
1024
|
-
if (answer === null) return {
|
|
1025
|
-
ok: false,
|
|
1026
|
-
why: `${probe.url} gave no answer in ${timeout} ms`
|
|
1027
|
-
};
|
|
1028
|
-
if (answer.status !== want) return {
|
|
1029
|
-
ok: false,
|
|
1030
|
-
why: `${probe.url} gave ${answer.status}, not ${want}`
|
|
1031
|
-
};
|
|
1032
|
-
if (!answer.complete) return {
|
|
1033
|
-
ok: false,
|
|
1034
|
-
why: `the answer of ${probe.url} is above ${PROBE_BODY_LIMIT} bytes`
|
|
1035
|
-
};
|
|
1036
|
-
return freshness(probe.url, answer.body, probe.fresh, probe.now, ports.wall());
|
|
1037
|
-
}
|
|
1038
|
-
const status = await ports.net.httpStatus(probe.url, timeout);
|
|
1039
|
-
if (status === want) return { ok: true };
|
|
1040
|
-
return {
|
|
1041
|
-
ok: false,
|
|
1042
|
-
why: status === null ? `${probe.url} gave no answer in ${timeout} ms` : `${probe.url} gave ${status}, not ${want}`
|
|
1043
|
-
};
|
|
1044
|
-
}
|
|
1045
|
-
if (probe.kind === "tcp") {
|
|
1046
|
-
const host = probe.host ?? "127.0.0.1";
|
|
1047
|
-
if (await ports.net.tcpConnect(host, probe.port, timeout)) return { ok: true };
|
|
1048
|
-
return {
|
|
1049
|
-
ok: false,
|
|
1050
|
-
why: `no TCP connection to ${host}:${probe.port} in ${timeout} ms`
|
|
1051
|
-
};
|
|
1052
|
-
}
|
|
1053
|
-
const result = await ports.commands.run(probe.program, probe.args, {
|
|
1054
|
-
cwd: probe.cwd,
|
|
1055
|
-
timeout
|
|
1056
|
-
});
|
|
1057
|
-
return result.code === 0 ? { ok: true } : {
|
|
1058
|
-
ok: false,
|
|
1059
|
-
why: `${probe.program} gave the code ${result.code}`
|
|
1060
|
-
};
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
return {
|
|
1063
|
-
ok: false,
|
|
1064
|
-
why: `the probe failed: ${error instanceof Error ? error.message : String(error)}`
|
|
1065
|
-
};
|
|
1066
|
-
}
|
|
1067
|
-
};
|
|
1068
|
-
// src/host/watch.ts
|
|
1069
|
-
/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */
|
|
1070
|
-
const DEFAULT_VERDICT = {
|
|
1071
|
-
type: "debounce",
|
|
1072
|
-
failAfter: 3,
|
|
1073
|
-
recoverAfter: 2
|
|
1074
|
-
};
|
|
1075
|
-
const DEFAULT_JITTER = .1;
|
|
1076
|
-
const ms$1 = (amount) => valueIn(amount, "ms");
|
|
1077
|
-
const isTimeAtLeast$1 = (value, floor, strict) => isTime(value) && (strict ? ms$1(value) > floor : ms$1(value) >= floor);
|
|
1078
|
-
const whole = (value) => Number.isInteger(value) && value >= 1;
|
|
1079
|
-
/** This function gives the problems of a watch spec: each value that the watcher cannot use. */
|
|
1080
|
-
const watchProblems = (spec) => {
|
|
1081
|
-
const problems = [];
|
|
1082
|
-
if (spec.targets.length === 0) problems.push("the spec has no target");
|
|
1083
|
-
const names = /* @__PURE__ */ new Set();
|
|
1084
|
-
for (const target of spec.targets) {
|
|
1085
|
-
const of = `the target ${JSON.stringify(target.name)}`;
|
|
1086
|
-
if (target.name === "") problems.push("a target name is empty");
|
|
1087
|
-
if (names.has(target.name)) problems.push(`${of} is in the spec two times`);
|
|
1088
|
-
names.add(target.name);
|
|
1089
|
-
problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));
|
|
1090
|
-
if (!isTimeAtLeast$1(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);
|
|
1091
|
-
if (!isTimeAtLeast$1(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);
|
|
1092
|
-
else if (isTimeAtLeast$1(target.interval, 0, true) && ms$1(target.timeout) > ms$1(target.interval)) problems.push(`${of}: the timeout is above the interval`);
|
|
1093
|
-
const jitter = target.jitter ?? DEFAULT_JITTER;
|
|
1094
|
-
if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);
|
|
1095
|
-
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
1096
|
-
if (verdict.type === "debounce") {
|
|
1097
|
-
if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);
|
|
1098
|
-
if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);
|
|
1099
|
-
} else if (verdict.type === "window") {
|
|
1100
|
-
if (!isTimeAtLeast$1(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);
|
|
1101
|
-
if (verdict.recoverAfter !== void 0 && !isTimeAtLeast$1(verdict.recoverAfter, 0, false)) problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);
|
|
1102
|
-
} else problems.push(`${of}: the verdict type ${JSON.stringify(verdict.type)} is not debounce or window`);
|
|
1103
|
-
}
|
|
1104
|
-
return problems;
|
|
1105
|
-
};
|
|
1106
|
-
const timingOf = (target) => {
|
|
1107
|
-
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
1108
|
-
return verdict.type === "debounce" ? {
|
|
1109
|
-
type: "debounce",
|
|
1110
|
-
interval: target.interval,
|
|
1111
|
-
failAfter: verdict.failAfter,
|
|
1112
|
-
recoverAfter: verdict.recoverAfter
|
|
1113
|
-
} : {
|
|
1114
|
-
type: "window",
|
|
1115
|
-
failAfter: verdict.failAfter,
|
|
1116
|
-
recoverAfter: verdict.recoverAfter
|
|
1117
|
-
};
|
|
1118
|
-
};
|
|
1119
|
-
/**
|
|
1120
|
-
* This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the
|
|
1121
|
-
* clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a
|
|
1122
|
-
* window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change
|
|
1123
|
-
* goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a
|
|
1124
|
-
* problem.
|
|
1125
|
-
*/
|
|
1126
|
-
const watchTargets = (spec, ports, options) => {
|
|
1127
|
-
const problems = watchProblems(spec);
|
|
1128
|
-
if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join("; ")}`);
|
|
1129
|
-
const random = options.random ?? Math.random;
|
|
1130
|
-
let stopped = false;
|
|
1131
|
-
const emit = (unit, to) => {
|
|
1132
|
-
if (unit.health === to) return;
|
|
1133
|
-
const change = {
|
|
1134
|
-
target: unit.target.name,
|
|
1135
|
-
from: unit.health,
|
|
1136
|
-
to,
|
|
1137
|
-
at: ports.wall(),
|
|
1138
|
-
why: to === "down" ? unit.why : null
|
|
1139
|
-
};
|
|
1140
|
-
unit.health = to;
|
|
1141
|
-
unit.since = change.at;
|
|
1142
|
-
if (stopped) return;
|
|
1143
|
-
try {
|
|
1144
|
-
options.onChange(change);
|
|
1145
|
-
} catch (error) {
|
|
1146
|
-
ports.logger?.log("warn", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });
|
|
1147
|
-
}
|
|
1148
|
-
};
|
|
1149
|
-
const watched = spec.targets.map((target) => {
|
|
1150
|
-
const unit = {
|
|
1151
|
-
target,
|
|
1152
|
-
health: "unknown",
|
|
1153
|
-
since: ports.wall(),
|
|
1154
|
-
last: null,
|
|
1155
|
-
lastAt: null,
|
|
1156
|
-
failures: 0,
|
|
1157
|
-
why: null
|
|
1158
|
-
};
|
|
1159
|
-
const trace = options.trace === void 0 ? void 0 : (from, to, on) => options.trace?.(target.name, from, to, on);
|
|
1160
|
-
const timeout = ms$1(target.timeout);
|
|
1161
|
-
let probed = null;
|
|
1162
|
-
const gate = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? "down" : "up"), trace);
|
|
1163
|
-
const record = (result) => {
|
|
1164
|
-
const own = probed;
|
|
1165
|
-
probed = null;
|
|
1166
|
-
const seen = result.outcome === "ok" ? { ok: true } : {
|
|
1167
|
-
ok: false,
|
|
1168
|
-
why: !result.timedOut && own !== null && !own.ok ? own.why : result.cause ?? "the poll failed"
|
|
1169
|
-
};
|
|
1170
|
-
unit.last = seen;
|
|
1171
|
-
unit.lastAt = ports.wall();
|
|
1172
|
-
unit.failures = seen.ok ? 0 : unit.failures + 1;
|
|
1173
|
-
if (!seen.ok) unit.why = seen.why;
|
|
1174
|
-
gate.record(result);
|
|
1175
|
-
if (seen.ok && unit.health === "unknown" && !gate.tripped) emit(unit, "up");
|
|
1176
|
-
};
|
|
1177
|
-
return {
|
|
1178
|
-
unit,
|
|
1179
|
-
gate,
|
|
1180
|
-
loop: poller({
|
|
1181
|
-
name: target.name,
|
|
1182
|
-
poll: {
|
|
1183
|
-
interval: target.interval,
|
|
1184
|
-
jitter: target.jitter ?? DEFAULT_JITTER,
|
|
1185
|
-
timeout: target.timeout
|
|
1186
|
-
},
|
|
1187
|
-
run: async () => {
|
|
1188
|
-
const result = await probeOnce(target.probe, timeout, ports);
|
|
1189
|
-
probed = result;
|
|
1190
|
-
return result.ok ? "ok" : "error";
|
|
1191
|
-
},
|
|
1192
|
-
clock: ports.clock,
|
|
1193
|
-
random,
|
|
1194
|
-
forced: () => false,
|
|
1195
|
-
record,
|
|
1196
|
-
trace
|
|
1197
|
-
})
|
|
1198
|
-
};
|
|
1199
|
-
});
|
|
1200
|
-
const states = () => watched.map(({ unit }) => ({
|
|
1201
|
-
name: unit.target.name,
|
|
1202
|
-
health: unit.health,
|
|
1203
|
-
since: unit.since,
|
|
1204
|
-
last: unit.last,
|
|
1205
|
-
lastAt: unit.lastAt,
|
|
1206
|
-
failures: unit.failures
|
|
1207
|
-
}));
|
|
1208
|
-
for (const { loop } of watched) loop.start(0);
|
|
1209
|
-
return {
|
|
1210
|
-
states,
|
|
1211
|
-
async pollNow() {
|
|
1212
|
-
await Promise.all(watched.map(({ loop }) => loop.pollNow()));
|
|
1213
|
-
return states();
|
|
1214
|
-
},
|
|
1215
|
-
stop() {
|
|
1216
|
-
if (stopped) return;
|
|
1217
|
-
stopped = true;
|
|
1218
|
-
for (const { gate, loop } of watched) {
|
|
1219
|
-
loop.stop();
|
|
1220
|
-
gate.stop();
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
};
|
|
1224
|
-
};
|
|
1225
|
-
// src/host/env.ts
|
|
1226
|
-
const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1227
|
-
/** This function reads a value in double quotes: `\n`, `\t`, `\"` and `\\` are escapes. */
|
|
1228
|
-
const doubleQuoted = (body) => body.replace(/\\(.)/g, (_match, char) => char === "n" ? "\n" : char === "t" ? " " : char === "r" ? "\r" : char);
|
|
1229
|
-
/**
|
|
1230
|
-
* This function reads a file of environment variables, one `KEY=value` on each line. It is a pure
|
|
1231
|
-
* function. It does not throw: it skips a bad line and gives its problem.
|
|
1232
|
-
* - A blank line and a line that starts with `#` are skipped. A line can start with `export `.
|
|
1233
|
-
* - A value in single quotes is literal. A value in double quotes has the escapes `\n`, `\t`, `\"` and `\\`.
|
|
1234
|
-
* - A value without quotes ends at ` #`, and its spaces at the two ends go.
|
|
1235
|
-
* - A key that comes again replaces its value.
|
|
1236
|
-
*/
|
|
1237
|
-
const parseEnvFile = (text) => {
|
|
1238
|
-
const env = {};
|
|
1239
|
-
const problems = [];
|
|
1240
|
-
(text.charCodeAt(0) === 65279 ? text.slice(1) : text).split(/\r?\n/).forEach((raw, at) => {
|
|
1241
|
-
const line = raw.trim();
|
|
1242
|
-
if (line === "" || line.startsWith("#")) return;
|
|
1243
|
-
const body = line.startsWith("export ") ? line.slice(7).trimStart() : line;
|
|
1244
|
-
const equals = body.indexOf("=");
|
|
1245
|
-
if (equals <= 0) {
|
|
1246
|
-
problems.push(`line ${at + 1} has no KEY=value`);
|
|
1247
|
-
return;
|
|
1248
|
-
}
|
|
1249
|
-
const key = body.slice(0, equals).trim();
|
|
1250
|
-
if (!KEY.test(key)) {
|
|
1251
|
-
problems.push(`line ${at + 1}: ${JSON.stringify(key)} is not a name of a variable`);
|
|
1252
|
-
return;
|
|
1253
|
-
}
|
|
1254
|
-
const rest = body.slice(equals + 1).trim();
|
|
1255
|
-
const quote = rest[0];
|
|
1256
|
-
if (quote === "\"" || quote === "'") {
|
|
1257
|
-
const end = quote === "'" ? rest.indexOf("'", 1) : closingQuote(rest);
|
|
1258
|
-
if (end < 0) {
|
|
1259
|
-
problems.push(`line ${at + 1}: the value of ${key} has no closing quote`);
|
|
1260
|
-
return;
|
|
1261
|
-
}
|
|
1262
|
-
env[key] = quote === "'" ? rest.slice(1, end) : doubleQuoted(rest.slice(1, end));
|
|
1263
|
-
return;
|
|
1264
|
-
}
|
|
1265
|
-
const comment = rest.search(/\s#/);
|
|
1266
|
-
env[key] = (comment < 0 ? rest : rest.slice(0, comment)).trim();
|
|
1267
|
-
});
|
|
1268
|
-
return {
|
|
1269
|
-
env,
|
|
1270
|
-
problems
|
|
1271
|
-
};
|
|
1272
|
-
};
|
|
1273
|
-
/** This function gives the place of the double quote that closes a value, or -1. A quote after a backslash does not close it. */
|
|
1274
|
-
const closingQuote = (text) => {
|
|
1275
|
-
for (let at = 1; at < text.length; at += 1) if (text[at] === "\\") at += 1;
|
|
1276
|
-
else if (text[at] === "\"") return at;
|
|
1277
|
-
return -1;
|
|
1278
|
-
};
|
|
1279
|
-
// src/host/logs.ts
|
|
1280
|
-
const byteLength = (chunk) => typeof chunk === "string" ? new TextEncoder().encode(chunk).length : chunk.length;
|
|
1281
|
-
/**
|
|
1282
|
-
* This function makes a rotating log on a file port. Before a write that makes the file larger than
|
|
1283
|
-
* `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the
|
|
1284
|
-
* file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.
|
|
1285
|
-
*/
|
|
1286
|
-
const rotatingLog = (spec, files) => {
|
|
1287
|
-
const max = valueIn(spec.maxSize, "B");
|
|
1288
|
-
let chain = Promise.resolve();
|
|
1289
|
-
let size = null;
|
|
1290
|
-
let failures = 0;
|
|
1291
|
-
const rotate = async () => {
|
|
1292
|
-
if (spec.keep <= 0) {
|
|
1293
|
-
await files.remove(spec.path);
|
|
1294
|
-
return;
|
|
1295
|
-
}
|
|
1296
|
-
await files.remove(`${spec.path}.${spec.keep}`);
|
|
1297
|
-
for (let at = spec.keep - 1; at >= 1; at -= 1) if (await files.size(`${spec.path}.${at}`) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);
|
|
1298
|
-
await files.rename(spec.path, `${spec.path}.1`);
|
|
1299
|
-
};
|
|
1300
|
-
const append = async (chunk) => {
|
|
1301
|
-
const length = byteLength(chunk);
|
|
1302
|
-
size ??= await files.size(spec.path) ?? 0;
|
|
1303
|
-
if (size > 0 && size + length > max) {
|
|
1304
|
-
await rotate();
|
|
1305
|
-
size = 0;
|
|
1306
|
-
}
|
|
1307
|
-
await files.append(spec.path, chunk);
|
|
1308
|
-
size += length;
|
|
1309
|
-
};
|
|
1310
|
-
return {
|
|
1311
|
-
write(chunk) {
|
|
1312
|
-
chain = chain.then(() => append(chunk)).catch(() => {
|
|
1313
|
-
failures += 1;
|
|
1314
|
-
size = null;
|
|
1315
|
-
});
|
|
1316
|
-
},
|
|
1317
|
-
flush: () => chain,
|
|
1318
|
-
get failures() {
|
|
1319
|
-
return failures;
|
|
1320
|
-
}
|
|
1321
|
-
};
|
|
1322
|
-
};
|
|
1323
|
-
// src/host/group.ts
|
|
1324
|
-
/**
|
|
1325
|
-
* This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.
|
|
1326
|
-
* The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.
|
|
1327
|
-
*/
|
|
1328
|
-
const DEFAULT_RESTART = {
|
|
1329
|
-
backoff: {
|
|
1330
|
-
base: 1e3,
|
|
1331
|
-
factor: 2,
|
|
1332
|
-
cap: 6e4,
|
|
1333
|
-
jitter: {
|
|
1334
|
-
kind: "subtract",
|
|
1335
|
-
fraction: .5
|
|
1336
|
-
}
|
|
1337
|
-
},
|
|
1338
|
-
resetAfter: {
|
|
1339
|
-
value: 60,
|
|
1340
|
-
unit: "s"
|
|
1341
|
-
}
|
|
1342
|
-
};
|
|
1343
|
-
const DEFAULT_GRACE = {
|
|
1344
|
-
value: 10,
|
|
1345
|
-
unit: "s"
|
|
1346
|
-
};
|
|
1347
|
-
const DEFAULT_LOG_SIZE = {
|
|
1348
|
-
value: 10,
|
|
1349
|
-
unit: "MB"
|
|
1350
|
-
};
|
|
1351
|
-
const DEFAULT_LOG_KEEP = 3;
|
|
1352
|
-
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1353
|
-
const ms = (time) => valueIn(time, "ms");
|
|
1354
|
-
/**
|
|
1355
|
-
* This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the
|
|
1356
|
-
* layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.
|
|
1357
|
-
*/
|
|
1358
|
-
const startOrder = (spec) => {
|
|
1359
|
-
const names = new Set(spec.programs.map((program) => program.name));
|
|
1360
|
-
const placed = /* @__PURE__ */ new Set();
|
|
1361
|
-
const layers = [];
|
|
1362
|
-
for (;;) {
|
|
1363
|
-
const layer = spec.programs.filter((program) => !placed.has(program.name)).filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name))).map((program) => program.name);
|
|
1364
|
-
if (layer.length === 0) return layers;
|
|
1365
|
-
for (const name of layer) placed.add(name);
|
|
1366
|
-
layers.push([...new Set(layer)]);
|
|
1367
|
-
}
|
|
1368
|
-
};
|
|
1369
|
-
const isTimeAtLeast = (value, floor, strict) => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);
|
|
1370
|
-
/** This function gives the problems of a group spec: each value that the supervisor cannot use. */
|
|
1371
|
-
const groupProblems = (spec) => {
|
|
1372
|
-
const problems = [];
|
|
1373
|
-
if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, ".", "_" and "-"`);
|
|
1374
|
-
if (spec.stateDir === "") problems.push("the stateDir is empty");
|
|
1375
|
-
if (spec.programs.length === 0) problems.push("the group has no programs");
|
|
1376
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1377
|
-
const names = new Set(spec.programs.map((program) => program.name));
|
|
1378
|
-
for (const program of spec.programs) {
|
|
1379
|
-
const name = program.name;
|
|
1380
|
-
const of = `the program ${JSON.stringify(name)}`;
|
|
1381
|
-
if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, ".", "_" and "-"`);
|
|
1382
|
-
if (seen.has(name)) problems.push(`${of} comes two times`);
|
|
1383
|
-
seen.add(name);
|
|
1384
|
-
if (program.program === "") problems.push(`${of}: the program is empty`);
|
|
1385
|
-
for (const need of program.after ?? []) if (need === name) problems.push(`${of} is after itself`);
|
|
1386
|
-
else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);
|
|
1387
|
-
if (program.ready !== void 0) {
|
|
1388
|
-
problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));
|
|
1389
|
-
for (const field of [
|
|
1390
|
-
"interval",
|
|
1391
|
-
"timeout",
|
|
1392
|
-
"within"
|
|
1393
|
-
]) if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);
|
|
1394
|
-
}
|
|
1395
|
-
if (program.alive !== void 0) {
|
|
1396
|
-
problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));
|
|
1397
|
-
for (const field of ["interval", "timeout"]) if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);
|
|
1398
|
-
if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1)) problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);
|
|
1399
|
-
}
|
|
1400
|
-
if (program.restart !== void 0 && program.restart !== null) {
|
|
1401
|
-
problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));
|
|
1402
|
-
if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);
|
|
1403
|
-
}
|
|
1404
|
-
if (program.log !== void 0 && program.log !== null) {
|
|
1405
|
-
const size = program.log.maxSize;
|
|
1406
|
-
if (!(isQuantity(size) && convertible(size.unit, "B") && valueIn(size, "B") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);
|
|
1407
|
-
if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);
|
|
1408
|
-
if (program.log.path === "") problems.push(`${of}: the path of the log is empty`);
|
|
1409
|
-
}
|
|
1410
|
-
if (program.stop !== void 0) {
|
|
1411
|
-
if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);
|
|
1412
|
-
if (program.stop.message !== void 0 && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);
|
|
1413
|
-
const signal = program.stop.signal;
|
|
1414
|
-
if (signal !== void 0 && signal !== "SIGINT" && signal !== "SIGTERM") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);
|
|
1415
|
-
}
|
|
1416
|
-
const port = program.listen?.port;
|
|
1417
|
-
if (port !== void 0 && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65535)) problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);
|
|
1418
|
-
}
|
|
1419
|
-
const placed = new Set(startOrder(spec).flat());
|
|
1420
|
-
const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));
|
|
1421
|
-
if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(", ")} are in a cycle of "after", or after a program in one`);
|
|
1422
|
-
return problems;
|
|
1423
|
-
};
|
|
1424
|
-
/**
|
|
1425
|
-
* This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes
|
|
1426
|
-
* through the ports, thus a test gives `fakeHost()` and starts no process.
|
|
1427
|
-
* - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.
|
|
1428
|
-
* - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.
|
|
1429
|
-
* - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.
|
|
1430
|
-
* - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.
|
|
1431
|
-
* - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.
|
|
1432
|
-
*/
|
|
1433
|
-
const superviseGroup = (spec, ports, options = {}) => {
|
|
1434
|
-
const problems = groupProblems(spec);
|
|
1435
|
-
if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join("; ")}`);
|
|
1436
|
-
const abort = new AbortController();
|
|
1437
|
-
const layers = startOrder(spec);
|
|
1438
|
-
let started = false;
|
|
1439
|
-
let stopping = false;
|
|
1440
|
-
let stopped = null;
|
|
1441
|
-
const say = (level, message, fields) => {
|
|
1442
|
-
try {
|
|
1443
|
-
ports.logger?.log(level, message, {
|
|
1444
|
-
group: spec.name,
|
|
1445
|
-
...fields
|
|
1446
|
-
});
|
|
1447
|
-
} catch {}
|
|
1448
|
-
};
|
|
1449
|
-
const units = /* @__PURE__ */ new Map();
|
|
1450
|
-
for (const program of spec.programs) {
|
|
1451
|
-
const restart = program.restart === void 0 ? DEFAULT_RESTART : program.restart;
|
|
1452
|
-
const logSpec = program.log === void 0 ? {
|
|
1453
|
-
path: joinPath(ports.platform, spec.stateDir, "logs", `${program.name}.log`),
|
|
1454
|
-
maxSize: DEFAULT_LOG_SIZE,
|
|
1455
|
-
keep: DEFAULT_LOG_KEEP
|
|
1456
|
-
} : program.log;
|
|
1457
|
-
units.set(program.name, {
|
|
1458
|
-
spec: program,
|
|
1459
|
-
lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),
|
|
1460
|
-
discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),
|
|
1461
|
-
log: logSpec === null ? null : rotatingLog(logSpec, ports.files),
|
|
1462
|
-
retry: restart === null ? null : retrier({
|
|
1463
|
-
...restart.backoff,
|
|
1464
|
-
clock: ports.clock,
|
|
1465
|
-
signal: abort.signal,
|
|
1466
|
-
...options.random === void 0 ? {} : { random: options.random }
|
|
1467
|
-
}),
|
|
1468
|
-
phase: "waiting",
|
|
1469
|
-
child: null,
|
|
1470
|
-
lock: null,
|
|
1471
|
-
timers: [],
|
|
1472
|
-
watch: null,
|
|
1473
|
-
restarts: 0,
|
|
1474
|
-
detail: null,
|
|
1475
|
-
reason: null,
|
|
1476
|
-
waiters: []
|
|
1477
|
-
});
|
|
1478
|
-
}
|
|
1479
|
-
const unitOf = (name) => units.get(name);
|
|
1480
|
-
const clearTimers = (unit) => {
|
|
1481
|
-
for (const cancel of unit.timers.splice(0)) cancel();
|
|
1482
|
-
unit.watch?.();
|
|
1483
|
-
unit.watch = null;
|
|
1484
|
-
};
|
|
1485
|
-
const environment = async (unit) => {
|
|
1486
|
-
const env = {};
|
|
1487
|
-
for (const [key, value] of Object.entries(ports.env)) if (value !== void 0) env[key] = value;
|
|
1488
|
-
const file = unit.spec.envFile;
|
|
1489
|
-
if (file !== void 0) try {
|
|
1490
|
-
const text = await ports.files.read(file);
|
|
1491
|
-
if (text === null) say("warn", `the env file ${file} of ${unit.spec.name} does not exist`, {
|
|
1492
|
-
program: unit.spec.name,
|
|
1493
|
-
file
|
|
1494
|
-
});
|
|
1495
|
-
else {
|
|
1496
|
-
const parsed = parseEnvFile(text);
|
|
1497
|
-
Object.assign(env, parsed.env);
|
|
1498
|
-
for (const problem of parsed.problems) say("warn", `the env file ${file} of ${unit.spec.name}: ${problem}`, {
|
|
1499
|
-
program: unit.spec.name,
|
|
1500
|
-
file
|
|
1501
|
-
});
|
|
1502
|
-
}
|
|
1503
|
-
} catch (error) {
|
|
1504
|
-
say("warn", `the read of the env file ${file} of ${unit.spec.name} failed`, {
|
|
1505
|
-
program: unit.spec.name,
|
|
1506
|
-
file,
|
|
1507
|
-
error
|
|
1508
|
-
});
|
|
1509
|
-
}
|
|
1510
|
-
return Object.assign(env, unit.spec.env ?? {});
|
|
1511
|
-
};
|
|
1512
|
-
const consider = (unit) => {
|
|
1513
|
-
if (!started || stopping || unit.phase !== "waiting") return;
|
|
1514
|
-
if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === "ready")) return;
|
|
1515
|
-
launch(unit);
|
|
1516
|
-
};
|
|
1517
|
-
const considerAll = () => {
|
|
1518
|
-
for (const layer of layers) for (const name of layer) consider(unitOf(name));
|
|
1519
|
-
};
|
|
1520
|
-
/** This function starts the program again after the backoff, or ends it when it has no restart. */
|
|
1521
|
-
const later = (unit, phase) => {
|
|
1522
|
-
const delay = unit.retry?.schedule(() => {
|
|
1523
|
-
if (stopping) return;
|
|
1524
|
-
unit.phase = "waiting";
|
|
1525
|
-
unit.restarts += 1;
|
|
1526
|
-
consider(unit);
|
|
1527
|
-
});
|
|
1528
|
-
if (delay === void 0 || delay === null) {
|
|
1529
|
-
unit.phase = phase === "held" ? "held" : "exited";
|
|
1530
|
-
unit.lock?.release();
|
|
1531
|
-
unit.lock = null;
|
|
1532
|
-
return;
|
|
1533
|
-
}
|
|
1534
|
-
unit.phase = phase;
|
|
1535
|
-
say("info", `${unit.spec.name} starts again in ${delay} ms`, {
|
|
1536
|
-
program: unit.spec.name,
|
|
1537
|
-
delay: {
|
|
1538
|
-
value: delay,
|
|
1539
|
-
unit: "ms"
|
|
1540
|
-
},
|
|
1541
|
-
attempt: unit.retry?.attempts
|
|
1542
|
-
});
|
|
1543
|
-
};
|
|
1544
|
-
const markReady = (unit, child) => {
|
|
1545
|
-
if (unit.child !== child || stopping) return;
|
|
1546
|
-
unit.phase = "ready";
|
|
1547
|
-
unit.detail = null;
|
|
1548
|
-
say("info", `${unit.spec.name} is ready`, {
|
|
1549
|
-
program: unit.spec.name,
|
|
1550
|
-
pid: child.pid
|
|
1551
|
-
});
|
|
1552
|
-
const restart = unit.spec.restart === void 0 ? DEFAULT_RESTART : unit.spec.restart;
|
|
1553
|
-
if (unit.retry !== null && restart !== null) unit.timers.push(ports.clock.after(ms(restart.resetAfter), () => {
|
|
1554
|
-
if (unit.child === child && unit.phase === "ready") unit.retry?.reset();
|
|
1555
|
-
}));
|
|
1556
|
-
if (unit.spec.alive !== void 0) watch(unit, child, unit.spec.alive);
|
|
1557
|
-
considerAll();
|
|
1558
|
-
};
|
|
1559
|
-
/** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */
|
|
1560
|
-
const watch = (unit, child, alive) => {
|
|
1561
|
-
let failures = 0;
|
|
1562
|
-
const current = () => unit.child === child && unit.phase === "ready" && !stopping;
|
|
1563
|
-
const next = () => {
|
|
1564
|
-
unit.watch = ports.clock.after(ms(alive.interval), () => {
|
|
1565
|
-
unit.watch = null;
|
|
1566
|
-
check();
|
|
1567
|
-
});
|
|
1568
|
-
};
|
|
1569
|
-
const check = async () => {
|
|
1570
|
-
if (!current()) return;
|
|
1571
|
-
const result = await probeOnce(alive.probe, ms(alive.timeout), ports);
|
|
1572
|
-
if (!current()) return;
|
|
1573
|
-
if (result.ok) {
|
|
1574
|
-
if (failures > 0) say("info", `${unit.spec.name} is alive again`, {
|
|
1575
|
-
program: unit.spec.name,
|
|
1576
|
-
pid: child.pid,
|
|
1577
|
-
failures
|
|
1578
|
-
});
|
|
1579
|
-
failures = 0;
|
|
1580
|
-
unit.detail = null;
|
|
1581
|
-
next();
|
|
1582
|
-
return;
|
|
1583
|
-
}
|
|
1584
|
-
failures += 1;
|
|
1585
|
-
unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;
|
|
1586
|
-
if (failures < alive.failures) {
|
|
1587
|
-
say("warn", `${unit.spec.name}: ${unit.detail}`, {
|
|
1588
|
-
program: unit.spec.name,
|
|
1589
|
-
pid: child.pid,
|
|
1590
|
-
why: result.why
|
|
1591
|
-
});
|
|
1592
|
-
next();
|
|
1593
|
-
return;
|
|
1594
|
-
}
|
|
1595
|
-
unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;
|
|
1596
|
-
unit.detail = unit.reason;
|
|
1597
|
-
say("warn", `${unit.spec.name} is not alive, thus it stops`, {
|
|
1598
|
-
program: unit.spec.name,
|
|
1599
|
-
pid: child.pid,
|
|
1600
|
-
why: result.why
|
|
1601
|
-
});
|
|
1602
|
-
stagedStop(unit, child);
|
|
1603
|
-
};
|
|
1604
|
-
next();
|
|
1605
|
-
};
|
|
1606
|
-
const probe = (unit, child, ready) => {
|
|
1607
|
-
const deadline = ports.clock.now() + ms(ready.within);
|
|
1608
|
-
const attempt = async () => {
|
|
1609
|
-
if (unit.child !== child || stopping) return;
|
|
1610
|
-
const result = await probeOnce(ready.probe, ms(ready.timeout), ports);
|
|
1611
|
-
if (unit.child !== child || stopping) return;
|
|
1612
|
-
if (result.ok) {
|
|
1613
|
-
markReady(unit, child);
|
|
1614
|
-
return;
|
|
1615
|
-
}
|
|
1616
|
-
unit.detail = result.why;
|
|
1617
|
-
if (ports.clock.now() >= deadline) {
|
|
1618
|
-
unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;
|
|
1619
|
-
unit.detail = unit.reason;
|
|
1620
|
-
say("warn", `${unit.spec.name} is not ready in its time, thus it stops`, {
|
|
1621
|
-
program: unit.spec.name,
|
|
1622
|
-
pid: child.pid,
|
|
1623
|
-
why: result.why
|
|
1624
|
-
});
|
|
1625
|
-
stagedStop(unit, child);
|
|
1626
|
-
return;
|
|
1627
|
-
}
|
|
1628
|
-
unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));
|
|
1629
|
-
};
|
|
1630
|
-
attempt();
|
|
1631
|
-
};
|
|
1632
|
-
const exited = (unit, child, code, signal) => {
|
|
1633
|
-
if (unit.child !== child) return;
|
|
1634
|
-
clearTimers(unit);
|
|
1635
|
-
unit.child = null;
|
|
1636
|
-
for (const waiter of unit.waiters.splice(0)) waiter();
|
|
1637
|
-
if (child.pid !== null) removeDiscovery(unit.discoveryPath, ports, child.pid);
|
|
1638
|
-
unit.lock?.update(null).catch(() => {});
|
|
1639
|
-
if (stopping || unit.phase === "stopping") {
|
|
1640
|
-
unit.phase = "stopped";
|
|
1641
|
-
return;
|
|
1642
|
-
}
|
|
1643
|
-
const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? "unknown"}` : `the code ${code}`}`;
|
|
1644
|
-
unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;
|
|
1645
|
-
unit.reason = null;
|
|
1646
|
-
say("warn", `${unit.spec.name} stopped: ${unit.detail}`, {
|
|
1647
|
-
program: unit.spec.name,
|
|
1648
|
-
pid: child.pid,
|
|
1649
|
-
code,
|
|
1650
|
-
signal
|
|
1651
|
-
});
|
|
1652
|
-
later(unit, "backoff");
|
|
1653
|
-
};
|
|
1654
|
-
const launch = async (unit) => {
|
|
1655
|
-
unit.phase = "starting";
|
|
1656
|
-
unit.detail = null;
|
|
1657
|
-
const name = unit.spec.name;
|
|
1658
|
-
if (unit.lock === null) {
|
|
1659
|
-
const taken = await acquireInstanceLock(unit.lockPath, ports);
|
|
1660
|
-
if (stopping) {
|
|
1661
|
-
if (taken.kind === "acquired") await taken.lock.release();
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
if (taken.kind !== "acquired") {
|
|
1665
|
-
unit.detail = taken.kind === "held" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;
|
|
1666
|
-
say("warn", `${name} does not start: ${unit.detail}`, {
|
|
1667
|
-
program: name,
|
|
1668
|
-
lock: unit.lockPath
|
|
1669
|
-
});
|
|
1670
|
-
later(unit, "held");
|
|
1671
|
-
return;
|
|
1672
|
-
}
|
|
1673
|
-
unit.lock = taken.lock;
|
|
1674
|
-
}
|
|
1675
|
-
const lock = unit.lock;
|
|
1676
|
-
const env = await environment(unit);
|
|
1677
|
-
if (stopping) {
|
|
1678
|
-
await lock.release();
|
|
1679
|
-
unit.lock = null;
|
|
1680
|
-
return;
|
|
1681
|
-
}
|
|
1682
|
-
const child = ports.processes.spawn({
|
|
1683
|
-
program: unit.spec.program,
|
|
1684
|
-
args: unit.spec.args ?? [],
|
|
1685
|
-
cwd: unit.spec.cwd,
|
|
1686
|
-
env,
|
|
1687
|
-
ipc: unit.spec.ipc ?? false
|
|
1688
|
-
});
|
|
1689
|
-
const startedAt = ports.wall();
|
|
1690
|
-
unit.child = child;
|
|
1691
|
-
child.onOutput((_stream, chunk) => unit.log?.write(chunk));
|
|
1692
|
-
child.onExit((code, signal) => exited(unit, child, code, signal));
|
|
1693
|
-
const pid = child.pid;
|
|
1694
|
-
if (pid === null) return;
|
|
1695
|
-
say("info", `${name} started`, {
|
|
1696
|
-
program: name,
|
|
1697
|
-
pid
|
|
1698
|
-
});
|
|
1699
|
-
const mark = {
|
|
1700
|
-
pid,
|
|
1701
|
-
startedAt
|
|
1702
|
-
};
|
|
1703
|
-
try {
|
|
1704
|
-
await lock.update(mark);
|
|
1705
|
-
await writeDiscovery(unit.discoveryPath, {
|
|
1706
|
-
pid,
|
|
1707
|
-
startedAt: new Date(startedAt).toISOString(),
|
|
1708
|
-
port: unit.spec.listen?.port ?? null,
|
|
1709
|
-
url: unit.spec.listen?.url ?? null,
|
|
1710
|
-
extra: {
|
|
1711
|
-
group: spec.name,
|
|
1712
|
-
program: name
|
|
1713
|
-
}
|
|
1714
|
-
}, ports);
|
|
1715
|
-
} catch (error) {
|
|
1716
|
-
say("warn", `the files of ${name} were not written`, {
|
|
1717
|
-
program: name,
|
|
1718
|
-
error
|
|
1719
|
-
});
|
|
1720
|
-
}
|
|
1721
|
-
if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);
|
|
1722
|
-
if (unit.child !== child || stopping) return;
|
|
1723
|
-
if (unit.spec.ready === void 0) markReady(unit, child);
|
|
1724
|
-
else probe(unit, child, unit.spec.ready);
|
|
1725
|
-
};
|
|
1726
|
-
/** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */
|
|
1727
|
-
const ended = (unit, child, wait) => new Promise((resolve) => {
|
|
1728
|
-
if (unit.child !== child) {
|
|
1729
|
-
resolve(true);
|
|
1730
|
-
return;
|
|
1731
|
-
}
|
|
1732
|
-
const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));
|
|
1733
|
-
unit.waiters.push(() => {
|
|
1734
|
-
cancel();
|
|
1735
|
-
resolve(true);
|
|
1736
|
-
});
|
|
1737
|
-
});
|
|
1738
|
-
/**
|
|
1739
|
-
* This function stops a child in stages. The message goes on its IPC channel when it has one. Else
|
|
1740
|
-
* Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.
|
|
1741
|
-
*/
|
|
1742
|
-
const stagedStop = async (unit, child) => {
|
|
1743
|
-
const pid = child.pid;
|
|
1744
|
-
if (pid === null || unit.child !== child) return;
|
|
1745
|
-
const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);
|
|
1746
|
-
const gone = ended(unit, child, grace);
|
|
1747
|
-
let asked = null;
|
|
1748
|
-
if (child.ipc && child.send(unit.spec.stop?.message ?? "shutdown")) asked = "the IPC message";
|
|
1749
|
-
else if (ports.platform === "win32") {
|
|
1750
|
-
if ((await ports.commands.run("taskkill", [
|
|
1751
|
-
"/T",
|
|
1752
|
-
"/PID",
|
|
1753
|
-
String(pid)
|
|
1754
|
-
]).catch(() => null))?.code === 0) asked = "taskkill";
|
|
1755
|
-
} else {
|
|
1756
|
-
const signal = unit.spec.stop?.signal ?? "SIGTERM";
|
|
1757
|
-
if (ports.processes.signal(pid, signal)) asked = signal;
|
|
1758
|
-
}
|
|
1759
|
-
say("info", `${unit.spec.name} stops${asked === null ? "" : ` through ${asked}`}`, {
|
|
1760
|
-
program: unit.spec.name,
|
|
1761
|
-
pid,
|
|
1762
|
-
grace: {
|
|
1763
|
-
value: grace,
|
|
1764
|
-
unit: "ms"
|
|
1765
|
-
}
|
|
1766
|
-
});
|
|
1767
|
-
if (asked !== null && await gone) return;
|
|
1768
|
-
const tree = await stopTree(pid, ports);
|
|
1769
|
-
const why = asked === null ? "the staged stop did not go" : "it did not stop in its grace";
|
|
1770
|
-
say(tree.kind === "failed" ? "error" : "warn", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {
|
|
1771
|
-
program: unit.spec.name,
|
|
1772
|
-
pid,
|
|
1773
|
-
outcome: tree.kind
|
|
1774
|
-
});
|
|
1775
|
-
if (!await ended(unit, child, grace)) say("error", `${unit.spec.name} did not end after the stop of its process tree`, {
|
|
1776
|
-
program: unit.spec.name,
|
|
1777
|
-
pid
|
|
1778
|
-
});
|
|
1779
|
-
};
|
|
1780
|
-
const stopUnit = async (unit) => {
|
|
1781
|
-
clearTimers(unit);
|
|
1782
|
-
const child = unit.child;
|
|
1783
|
-
const pid = child?.pid ?? null;
|
|
1784
|
-
if (child !== null && pid !== null) {
|
|
1785
|
-
unit.phase = "stopping";
|
|
1786
|
-
await stagedStop(unit, child);
|
|
1787
|
-
await removeDiscovery(unit.discoveryPath, ports, pid);
|
|
1788
|
-
}
|
|
1789
|
-
unit.phase = "stopped";
|
|
1790
|
-
await unit.lock?.release();
|
|
1791
|
-
unit.lock = null;
|
|
1792
|
-
};
|
|
1793
|
-
return {
|
|
1794
|
-
start() {
|
|
1795
|
-
if (started || stopping) return;
|
|
1796
|
-
started = true;
|
|
1797
|
-
say("info", `the group ${spec.name} starts`, { layers });
|
|
1798
|
-
considerAll();
|
|
1799
|
-
},
|
|
1800
|
-
stop() {
|
|
1801
|
-
if (stopped !== null) return stopped;
|
|
1802
|
-
stopping = true;
|
|
1803
|
-
abort.abort();
|
|
1804
|
-
stopped = (async () => {
|
|
1805
|
-
for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));
|
|
1806
|
-
await Promise.all([...units.values()].map((unit) => unit.log?.flush()));
|
|
1807
|
-
say("info", `the group ${spec.name} stopped`, {});
|
|
1808
|
-
})();
|
|
1809
|
-
return stopped;
|
|
1810
|
-
},
|
|
1811
|
-
states() {
|
|
1812
|
-
return spec.programs.map((program) => {
|
|
1813
|
-
const unit = unitOf(program.name);
|
|
1814
|
-
return {
|
|
1815
|
-
name: program.name,
|
|
1816
|
-
phase: unit.phase,
|
|
1817
|
-
pid: unit.child?.pid ?? null,
|
|
1818
|
-
restarts: unit.restarts,
|
|
1819
|
-
detail: unit.detail
|
|
1820
|
-
};
|
|
1821
|
-
});
|
|
1822
|
-
}
|
|
1823
|
-
};
|
|
1824
|
-
};
|
|
1825
|
-
// src/host/node.ts
|
|
1826
|
-
const codeOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
|
|
1827
|
-
const missing = (error) => codeOf(error) === "ENOENT";
|
|
1828
|
-
const nodeCommands = { run: (file, args, options = {}) => new Promise((resolve) => {
|
|
1829
|
-
execFile(file, [...args], {
|
|
1830
|
-
...options.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
1831
|
-
timeout: options.timeout ?? 0,
|
|
1832
|
-
windowsHide: true,
|
|
1833
|
-
encoding: "utf8",
|
|
1834
|
-
maxBuffer: 16777216
|
|
1835
|
-
}, (error, stdout, stderr) => {
|
|
1836
|
-
const out = `${stdout}${stderr}`;
|
|
1837
|
-
if (error === null) {
|
|
1838
|
-
resolve({
|
|
1839
|
-
code: 0,
|
|
1840
|
-
out
|
|
1841
|
-
});
|
|
1842
|
-
return;
|
|
1843
|
-
}
|
|
1844
|
-
if (missing(error)) resolve({
|
|
1845
|
-
code: 127,
|
|
1846
|
-
out: error.message
|
|
1847
|
-
});
|
|
1848
|
-
else if (error.killed === true && options.timeout !== void 0) resolve({
|
|
1849
|
-
code: 124,
|
|
1850
|
-
out
|
|
1851
|
-
});
|
|
1852
|
-
else resolve({
|
|
1853
|
-
code: typeof error.code === "number" ? error.code : 1,
|
|
1854
|
-
out: out === "" ? error.message : out
|
|
1855
|
-
});
|
|
1856
|
-
});
|
|
1857
|
-
}) };
|
|
1858
|
-
let serial = 0;
|
|
1859
|
-
const nodeFiles = {
|
|
1860
|
-
async read(path) {
|
|
1861
|
-
try {
|
|
1862
|
-
return await readFile(path, "utf8");
|
|
1863
|
-
} catch (error) {
|
|
1864
|
-
if (missing(error)) return null;
|
|
1865
|
-
throw error;
|
|
1866
|
-
}
|
|
1867
|
-
},
|
|
1868
|
-
async write(path, data) {
|
|
1869
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1870
|
-
serial += 1;
|
|
1871
|
-
const temporary = `${path}.${process.pid}.${serial}.tmp`;
|
|
1872
|
-
await writeFile(temporary, data);
|
|
1873
|
-
try {
|
|
1874
|
-
await rename(temporary, path);
|
|
1875
|
-
} catch (error) {
|
|
1876
|
-
await rm(temporary, { force: true });
|
|
1877
|
-
throw error;
|
|
1878
|
-
}
|
|
1879
|
-
},
|
|
1880
|
-
async create(path, data) {
|
|
1881
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1882
|
-
try {
|
|
1883
|
-
await writeFile(path, data, { flag: "wx" });
|
|
1884
|
-
return true;
|
|
1885
|
-
} catch (error) {
|
|
1886
|
-
if (codeOf(error) === "EEXIST") return false;
|
|
1887
|
-
throw error;
|
|
1888
|
-
}
|
|
1889
|
-
},
|
|
1890
|
-
async append(path, data) {
|
|
1891
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1892
|
-
await appendFile(path, data);
|
|
1893
|
-
},
|
|
1894
|
-
async size(path) {
|
|
1895
|
-
try {
|
|
1896
|
-
return (await stat(path)).size;
|
|
1897
|
-
} catch (error) {
|
|
1898
|
-
if (missing(error)) return null;
|
|
1899
|
-
throw error;
|
|
1900
|
-
}
|
|
1901
|
-
},
|
|
1902
|
-
rename: (from, to) => rename(from, to),
|
|
1903
|
-
remove: (path) => rm(path, { force: true })
|
|
1904
|
-
};
|
|
1905
|
-
/** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */
|
|
1906
|
-
const FILETIME_EPOCH_MS = 11644473600000n;
|
|
1907
|
-
/**
|
|
1908
|
-
* This limit is the longest time of the query of a start time on Windows, in milliseconds. A cold start of PowerShell
|
|
1909
|
-
* on a loaded host can take more than 10 seconds (SYS-47). After the limit the start time is null, and the lock then
|
|
1910
|
-
* counts a live process ID as its owner. Thus a short limit can hold a stale lock, and the limit is wide.
|
|
1911
|
-
*/
|
|
1912
|
-
const WINDOWS_START_LIMIT_MS = 3e4;
|
|
1913
|
-
/** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */
|
|
1914
|
-
const windowsStart = async (pid) => {
|
|
1915
|
-
const result = await nodeCommands.run("powershell.exe", [
|
|
1916
|
-
"-NoProfile",
|
|
1917
|
-
"-NonInteractive",
|
|
1918
|
-
"-Command",
|
|
1919
|
-
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`
|
|
1920
|
-
], { timeout: WINDOWS_START_LIMIT_MS });
|
|
1921
|
-
const text = result.out.trim();
|
|
1922
|
-
if (result.code !== 0 || !/^\d+$/.test(text)) return null;
|
|
1923
|
-
return Number(BigInt(text) / 10000n - FILETIME_EPOCH_MS);
|
|
1924
|
-
};
|
|
1925
|
-
/** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */
|
|
1926
|
-
const LINUX_TICKS = 100;
|
|
1927
|
-
/** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */
|
|
1928
|
-
const linuxStart = async (pid) => {
|
|
1929
|
-
const record = await readFile(`/proc/${pid}/stat`, "utf8");
|
|
1930
|
-
const fields = record.slice(record.lastIndexOf(")") + 2).split(" ");
|
|
1931
|
-
const ticks = Number(fields[19]);
|
|
1932
|
-
const boot = /^btime (\d+)$/m.exec(await readFile("/proc/stat", "utf8"));
|
|
1933
|
-
if (!Number.isFinite(ticks) || boot === null) return null;
|
|
1934
|
-
return Number(boot[1]) * 1e3 + ticks * 1e3 / LINUX_TICKS;
|
|
1935
|
-
};
|
|
1936
|
-
const sendSignal = (pid, signal) => {
|
|
1937
|
-
try {
|
|
1938
|
-
return process.kill(pid, signal);
|
|
1939
|
-
} catch {
|
|
1940
|
-
return false;
|
|
1941
|
-
}
|
|
1942
|
-
};
|
|
1943
|
-
const nodeSpawn = (request) => {
|
|
1944
|
-
const outputs = [];
|
|
1945
|
-
const exits = [];
|
|
1946
|
-
let end = null;
|
|
1947
|
-
const finish = (code, signal) => {
|
|
1948
|
-
if (end !== null) return;
|
|
1949
|
-
end = {
|
|
1950
|
-
code,
|
|
1951
|
-
signal
|
|
1952
|
-
};
|
|
1953
|
-
for (const handler of exits) handler(code, signal);
|
|
1954
|
-
};
|
|
1955
|
-
const child = spawn(request.program, [...request.args], {
|
|
1956
|
-
...request.cwd === void 0 ? {} : { cwd: request.cwd },
|
|
1957
|
-
env: { ...request.env },
|
|
1958
|
-
stdio: request.ipc ? [
|
|
1959
|
-
"ignore",
|
|
1960
|
-
"pipe",
|
|
1961
|
-
"pipe",
|
|
1962
|
-
"ipc"
|
|
1963
|
-
] : [
|
|
1964
|
-
"ignore",
|
|
1965
|
-
"pipe",
|
|
1966
|
-
"pipe"
|
|
1967
|
-
],
|
|
1968
|
-
detached: process.platform !== "win32",
|
|
1969
|
-
windowsHide: true
|
|
1970
|
-
});
|
|
1971
|
-
child.stdout?.on("data", (chunk) => {
|
|
1972
|
-
for (const handler of outputs) handler("stdout", chunk);
|
|
1973
|
-
});
|
|
1974
|
-
child.stderr?.on("data", (chunk) => {
|
|
1975
|
-
for (const handler of outputs) handler("stderr", chunk);
|
|
1976
|
-
});
|
|
1977
|
-
child.on("error", () => {
|
|
1978
|
-
if (child.pid === void 0) finish(null, null);
|
|
1979
|
-
});
|
|
1980
|
-
child.on("exit", (code, signal) => finish(code, signal));
|
|
1981
|
-
return {
|
|
1982
|
-
pid: child.pid ?? null,
|
|
1983
|
-
ipc: request.ipc,
|
|
1984
|
-
onOutput(handler) {
|
|
1985
|
-
outputs.push(handler);
|
|
1986
|
-
},
|
|
1987
|
-
onExit(handler) {
|
|
1988
|
-
exits.push(handler);
|
|
1989
|
-
if (end !== null) handler(end.code, end.signal);
|
|
1990
|
-
},
|
|
1991
|
-
send(message) {
|
|
1992
|
-
if (!child.connected) return false;
|
|
1993
|
-
try {
|
|
1994
|
-
return child.send(message);
|
|
1995
|
-
} catch {
|
|
1996
|
-
return false;
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
};
|
|
2000
|
-
};
|
|
2001
|
-
const nodeProcesses = {
|
|
2002
|
-
alive(pid) {
|
|
2003
|
-
try {
|
|
2004
|
-
process.kill(pid, 0);
|
|
2005
|
-
return true;
|
|
2006
|
-
} catch (error) {
|
|
2007
|
-
return codeOf(error) === "EPERM";
|
|
2008
|
-
}
|
|
2009
|
-
},
|
|
2010
|
-
async startOf(pid) {
|
|
2011
|
-
try {
|
|
2012
|
-
if (process.platform === "win32") return await windowsStart(pid);
|
|
2013
|
-
if (process.platform === "linux") return await linuxStart(pid);
|
|
2014
|
-
return null;
|
|
2015
|
-
} catch {
|
|
2016
|
-
return null;
|
|
2017
|
-
}
|
|
2018
|
-
},
|
|
2019
|
-
signal: (pid, signal) => sendSignal(pid, signal),
|
|
2020
|
-
signalGroup: (pid, signal) => process.platform !== "win32" && sendSignal(-pid, signal),
|
|
2021
|
-
spawn: nodeSpawn
|
|
2022
|
-
};
|
|
2023
|
-
/**
|
|
2024
|
-
* This function sends a GET request that does not follow a redirect. The timeout also stops the
|
|
2025
|
-
* read of the body. The status read and the text read use it, thus they have one timeout.
|
|
2026
|
-
*/
|
|
2027
|
-
const get = (url, timeout) => fetch(url, {
|
|
2028
|
-
signal: AbortSignal.timeout(timeout),
|
|
2029
|
-
redirect: "manual"
|
|
2030
|
-
});
|
|
2031
|
-
/**
|
|
2032
|
-
* This function reads the body of an answer up to `limit` bytes, and gives the status and the text.
|
|
2033
|
-
* At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a
|
|
2034
|
-
* character that two parts of the body split. The unit tests give it answers with no network.
|
|
2035
|
-
*/
|
|
2036
|
-
const answerText = async (response, limit) => {
|
|
2037
|
-
const reader = response.body?.getReader();
|
|
2038
|
-
if (reader === void 0) return {
|
|
2039
|
-
status: response.status,
|
|
2040
|
-
body: "",
|
|
2041
|
-
complete: true
|
|
2042
|
-
};
|
|
2043
|
-
const decoder = new TextDecoder();
|
|
2044
|
-
let body = "";
|
|
2045
|
-
let size = 0;
|
|
2046
|
-
for (;;) {
|
|
2047
|
-
const read = await reader.read();
|
|
2048
|
-
if (read.done) return {
|
|
2049
|
-
status: response.status,
|
|
2050
|
-
body: body + decoder.decode(),
|
|
2051
|
-
complete: true
|
|
2052
|
-
};
|
|
2053
|
-
if (size + read.value.byteLength > limit) {
|
|
2054
|
-
body += decoder.decode(read.value.subarray(0, limit - size));
|
|
2055
|
-
await reader.cancel();
|
|
2056
|
-
return {
|
|
2057
|
-
status: response.status,
|
|
2058
|
-
body,
|
|
2059
|
-
complete: false
|
|
2060
|
-
};
|
|
2061
|
-
}
|
|
2062
|
-
body += decoder.decode(read.value, { stream: true });
|
|
2063
|
-
size += read.value.byteLength;
|
|
2064
|
-
}
|
|
2065
|
-
};
|
|
2066
|
-
const nodeNet = {
|
|
2067
|
-
async httpStatus(url, timeout) {
|
|
2068
|
-
try {
|
|
2069
|
-
const response = await get(url, timeout);
|
|
2070
|
-
await response.body?.cancel();
|
|
2071
|
-
return response.status;
|
|
2072
|
-
} catch {
|
|
2073
|
-
return null;
|
|
2074
|
-
}
|
|
2075
|
-
},
|
|
2076
|
-
async httpText(url, timeout, limit) {
|
|
2077
|
-
try {
|
|
2078
|
-
return await answerText(await get(url, timeout), limit);
|
|
2079
|
-
} catch {
|
|
2080
|
-
return null;
|
|
2081
|
-
}
|
|
2082
|
-
},
|
|
2083
|
-
tcpConnect: (host, port, timeout) => new Promise((resolve) => {
|
|
2084
|
-
const socket = connect({
|
|
2085
|
-
host,
|
|
2086
|
-
port
|
|
2087
|
-
});
|
|
2088
|
-
const done = (open) => {
|
|
2089
|
-
socket.destroy();
|
|
2090
|
-
resolve(open);
|
|
2091
|
-
};
|
|
2092
|
-
socket.setTimeout(timeout, () => done(false));
|
|
2093
|
-
socket.once("connect", () => done(true));
|
|
2094
|
-
socket.once("error", () => done(false));
|
|
2095
|
-
})
|
|
2096
|
-
};
|
|
2097
|
-
/**
|
|
2098
|
-
* This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.
|
|
2099
|
-
* Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.
|
|
2100
|
-
*/
|
|
2101
|
-
const nodeHostPorts = (options = {}) => {
|
|
2102
|
-
const user = () => {
|
|
2103
|
-
const name = userInfo().username;
|
|
2104
|
-
const domain = process.env["USERDOMAIN"];
|
|
2105
|
-
return process.platform === "win32" && domain !== void 0 && domain !== "" ? `${domain}\\${name}` : name;
|
|
2106
|
-
};
|
|
2107
|
-
return {
|
|
2108
|
-
platform: process.platform,
|
|
2109
|
-
commands: nodeCommands,
|
|
2110
|
-
files: nodeFiles,
|
|
2111
|
-
processes: nodeProcesses,
|
|
2112
|
-
net: nodeNet,
|
|
2113
|
-
clock: options.clock ?? realClock,
|
|
2114
|
-
wall: () => Date.now(),
|
|
2115
|
-
self: {
|
|
2116
|
-
pid: process.pid,
|
|
2117
|
-
startedAt: Math.round(Date.now() - process.uptime() * 1e3)
|
|
2118
|
-
},
|
|
2119
|
-
env: process.env,
|
|
2120
|
-
homeDir: homedir(),
|
|
2121
|
-
user,
|
|
2122
|
-
...options.logger === void 0 ? {} : { logger: options.logger }
|
|
2123
|
-
};
|
|
2124
|
-
};
|
|
1
|
+
import { joinPath } from "./host/ports.js";
|
|
2
|
+
import { renderSystemdTimer, renderSystemdUnit, renderTaskXml, serviceProblems, systemdArg, utf16le, windowsArg } from "./host/render.js";
|
|
3
|
+
import { START_MARGIN_MS, sameProcess, stopTree } from "./host/processes.js";
|
|
4
|
+
import { discoveryOf, parseDiscovery, readDiscovery, removeDiscovery, writeDiscovery } from "./host/discovery.js";
|
|
5
|
+
import { acquireInstanceLock, inspectInstanceLock, lockText, parseLockOwner } from "./host/lock.js";
|
|
6
|
+
import { installService, servicePaths, serviceStatus, startService, stopService, uninstallService } from "./host/install.js";
|
|
7
|
+
import { PROBE_BODY_LIMIT, probeOnce, probeProblems } from "./host/probes.js";
|
|
8
|
+
import { DEFAULT_VERDICT, watchProblems, watchTargets } from "./host/watch.js";
|
|
9
|
+
import { parseEnvFile } from "./host/env.js";
|
|
10
|
+
import { rotatingLog } from "./host/logs.js";
|
|
11
|
+
import { DEFAULT_RESTART, groupProblems, startOrder, superviseGroup } from "./host/group.js";
|
|
12
|
+
import { nodeHostPorts } from "./host/node.js";
|
|
2125
13
|
export { DEFAULT_RESTART, DEFAULT_VERDICT, PROBE_BODY_LIMIT, START_MARGIN_MS, acquireInstanceLock, discoveryOf, groupProblems, inspectInstanceLock, installService, joinPath, lockText, nodeHostPorts, parseDiscovery, parseEnvFile, parseLockOwner, probeOnce, probeProblems, readDiscovery, removeDiscovery, renderSystemdTimer, renderSystemdUnit, renderTaskXml, rotatingLog, sameProcess, servicePaths, serviceProblems, serviceStatus, startOrder, startService, stopService, stopTree, superviseGroup, systemdArg, uninstallService, utf16le, watchProblems, watchTargets, windowsArg, writeDiscovery };
|
|
2126
|
-
|
|
2127
|
-
//# sourceMappingURL=host.js.map
|