@countinghouse/ch-local 0.0.0-stage → 1.0.0
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/LICENSE +202 -0
- package/README.md +361 -2
- package/bin/ch-local.js +472 -0
- package/clients/claude-code/.claude-plugin/plugin.json +6 -0
- package/clients/claude-code/.mcp.json +11 -0
- package/clients/claude-code/bin/launch.js +235 -0
- package/clients/claude-code/bin/win-acl.js +420 -0
- package/clients/claude-code/skills/ci-failure-triage/SKILL.md +21 -0
- package/clients/claude-code/skills/countinghouse-module/SKILL.md +177 -0
- package/clients/claude-code/skills/countinghouse-setup/SKILL.md +74 -0
- package/lib/allowlist.js +65 -0
- package/lib/aside.js +16 -0
- package/lib/atomic.js +45 -0
- package/lib/auto-apply.js +245 -0
- package/lib/auto-upgrade.js +98 -0
- package/lib/availability.js +307 -0
- package/lib/ceiling.js +280 -0
- package/lib/clean-text.js +20 -0
- package/lib/cli-change.js +38 -0
- package/lib/client-conditions-fixtures.js +143 -0
- package/lib/client-conditions.js +656 -0
- package/lib/clients.js +179 -0
- package/lib/command-line.js +202 -0
- package/lib/conditions-command.js +116 -0
- package/lib/control.js +134 -0
- package/lib/credential-store.js +414 -0
- package/lib/credentials-command.js +344 -0
- package/lib/daemon-requests.js +137 -0
- package/lib/daemon.js +888 -0
- package/lib/describe-module.js +137 -0
- package/lib/description-check.js +175 -0
- package/lib/failed-json.js +43 -0
- package/lib/gc.js +274 -0
- package/lib/github-token.js +57 -0
- package/lib/handoff-io.js +73 -0
- package/lib/held-back.js +116 -0
- package/lib/hidden-input.js +64 -0
- package/lib/history.js +49 -0
- package/lib/home.js +372 -0
- package/lib/in-place.js +1036 -0
- package/lib/install-plan.js +142 -0
- package/lib/install.js +846 -0
- package/lib/installed-description.js +153 -0
- package/lib/integrity.js +7 -0
- package/lib/lock.js +456 -0
- package/lib/lockfile-rules.js +98 -0
- package/lib/machine.js +20 -0
- package/lib/module-credentials.js +403 -0
- package/lib/module-record.js +298 -0
- package/lib/module-roles.js +44 -0
- package/lib/module-seams.js +26 -0
- package/lib/module-store.js +202 -0
- package/lib/module-values.js +334 -0
- package/lib/names.js +31 -0
- package/lib/next-steps.js +8 -0
- package/lib/node-check.js +56 -0
- package/lib/npm-fetch.js +123 -0
- package/lib/npm-release.js +99 -0
- package/lib/npm-upgrade.js +146 -0
- package/lib/npm.js +41 -0
- package/lib/outside-edits.js +162 -0
- package/lib/own-applied.js +175 -0
- package/lib/own-command.js +380 -0
- package/lib/own-file.js +120 -0
- package/lib/own-record.js +96 -0
- package/lib/own-tree.js +336 -0
- package/lib/pack-table.js +290 -0
- package/lib/packs-command.js +570 -0
- package/lib/packs.js +219 -0
- package/lib/pins.js +64 -0
- package/lib/pipe-probe.js +82 -0
- package/lib/plain-read.js +63 -0
- package/lib/private-file.js +90 -0
- package/lib/private-write.js +33 -0
- package/lib/provenance.js +234 -0
- package/lib/record.js +82 -0
- package/lib/registry.js +22 -0
- package/lib/release-pins.js +350 -0
- package/lib/release-pins.json +4225 -0
- package/lib/release-tags.js +12 -0
- package/lib/release.js +36 -0
- package/lib/restart-command.js +161 -0
- package/lib/rollback.js +227 -0
- package/lib/run-liveness.js +15 -0
- package/lib/runtime-log.js +287 -0
- package/lib/sandbox-support.js +17 -0
- package/lib/semver-order.js +40 -0
- package/lib/session-socket.js +69 -0
- package/lib/session-table.js +238 -0
- package/lib/session.js +281 -0
- package/lib/settings-command.js +82 -0
- package/lib/settings.js +564 -0
- package/lib/shim-binary.js +152 -0
- package/lib/shim-config.js +159 -0
- package/lib/shim-install.js +365 -0
- package/lib/sigstore/README.md +44 -0
- package/lib/sigstore/npm-keys.json +18 -0
- package/lib/sigstore/trusted-root.json +126 -0
- package/lib/snippets.js +76 -0
- package/lib/start.js +721 -0
- package/lib/store-files.js +48 -0
- package/lib/store-paths.js +33 -0
- package/lib/swap-preload.js +38 -0
- package/lib/tar.js +220 -0
- package/lib/uninstall.js +314 -0
- package/lib/unpack.js +41 -0
- package/lib/upgrade-stamp.js +63 -0
- package/lib/upgrade.js +281 -0
- package/lib/watch.js +40 -0
- package/lib/win-acl.js +420 -0
- package/node_modules/@sigstore/bundle/LICENSE +202 -0
- package/node_modules/@sigstore/bundle/README.md +19 -0
- package/node_modules/@sigstore/bundle/dist/build.d.ts +18 -0
- package/node_modules/@sigstore/bundle/dist/build.js +100 -0
- package/node_modules/@sigstore/bundle/dist/bundle.d.ts +74 -0
- package/node_modules/@sigstore/bundle/dist/bundle.js +24 -0
- package/node_modules/@sigstore/bundle/dist/error.d.ts +4 -0
- package/node_modules/@sigstore/bundle/dist/error.js +25 -0
- package/node_modules/@sigstore/bundle/dist/index.d.ts +8 -0
- package/node_modules/@sigstore/bundle/dist/index.js +43 -0
- package/node_modules/@sigstore/bundle/dist/serialized.d.ts +74 -0
- package/node_modules/@sigstore/bundle/dist/serialized.js +49 -0
- package/node_modules/@sigstore/bundle/dist/utility.d.ts +14 -0
- package/node_modules/@sigstore/bundle/dist/utility.js +2 -0
- package/node_modules/@sigstore/bundle/dist/validate.d.ts +7 -0
- package/node_modules/@sigstore/bundle/dist/validate.js +199 -0
- package/node_modules/@sigstore/bundle/package.json +35 -0
- package/node_modules/@sigstore/core/LICENSE +202 -0
- package/node_modules/@sigstore/core/README.md +10 -0
- package/node_modules/@sigstore/core/dist/asn1/error.d.ts +4 -0
- package/node_modules/@sigstore/core/dist/asn1/error.js +24 -0
- package/node_modules/@sigstore/core/dist/asn1/index.d.ts +1 -0
- package/node_modules/@sigstore/core/dist/asn1/index.js +20 -0
- package/node_modules/@sigstore/core/dist/asn1/length.d.ts +3 -0
- package/node_modules/@sigstore/core/dist/asn1/length.js +62 -0
- package/node_modules/@sigstore/core/dist/asn1/obj.d.ts +14 -0
- package/node_modules/@sigstore/core/dist/asn1/obj.js +155 -0
- package/node_modules/@sigstore/core/dist/asn1/parse.d.ts +6 -0
- package/node_modules/@sigstore/core/dist/asn1/parse.js +124 -0
- package/node_modules/@sigstore/core/dist/asn1/tag.d.ts +16 -0
- package/node_modules/@sigstore/core/dist/asn1/tag.js +89 -0
- package/node_modules/@sigstore/core/dist/crypto.d.ts +6 -0
- package/node_modules/@sigstore/core/dist/crypto.js +69 -0
- package/node_modules/@sigstore/core/dist/dsse.d.ts +1 -0
- package/node_modules/@sigstore/core/dist/dsse.js +29 -0
- package/node_modules/@sigstore/core/dist/encoding.d.ts +2 -0
- package/node_modules/@sigstore/core/dist/encoding.js +27 -0
- package/node_modules/@sigstore/core/dist/index.d.ts +9 -0
- package/node_modules/@sigstore/core/dist/index.js +66 -0
- package/node_modules/@sigstore/core/dist/json.d.ts +1 -0
- package/node_modules/@sigstore/core/dist/json.js +60 -0
- package/node_modules/@sigstore/core/dist/oid.d.ts +3 -0
- package/node_modules/@sigstore/core/dist/oid.js +20 -0
- package/node_modules/@sigstore/core/dist/pem.d.ts +2 -0
- package/node_modules/@sigstore/core/dist/pem.js +43 -0
- package/node_modules/@sigstore/core/dist/rfc3161/error.d.ts +2 -0
- package/node_modules/@sigstore/core/dist/rfc3161/error.js +21 -0
- package/node_modules/@sigstore/core/dist/rfc3161/index.d.ts +1 -0
- package/node_modules/@sigstore/core/dist/rfc3161/index.js +20 -0
- package/node_modules/@sigstore/core/dist/rfc3161/timestamp.d.ts +36 -0
- package/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +212 -0
- package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.d.ts +12 -0
- package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +72 -0
- package/node_modules/@sigstore/core/dist/stream.d.ts +21 -0
- package/node_modules/@sigstore/core/dist/stream.js +117 -0
- package/node_modules/@sigstore/core/dist/x509/cert.d.ts +43 -0
- package/node_modules/@sigstore/core/dist/x509/cert.js +245 -0
- package/node_modules/@sigstore/core/dist/x509/ext.d.ts +41 -0
- package/node_modules/@sigstore/core/dist/x509/ext.js +146 -0
- package/node_modules/@sigstore/core/dist/x509/index.d.ts +2 -0
- package/node_modules/@sigstore/core/dist/x509/index.js +23 -0
- package/node_modules/@sigstore/core/dist/x509/sct.d.ts +25 -0
- package/node_modules/@sigstore/core/dist/x509/sct.js +158 -0
- package/node_modules/@sigstore/core/package.json +31 -0
- package/node_modules/@sigstore/protobuf-specs/LICENSE +202 -0
- package/node_modules/@sigstore/protobuf-specs/README.md +5 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.d.ts +44 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +59 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.d.ts +64 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +174 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.d.ts +74 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +141 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.d.ts +74 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +35 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.d.ts +1309 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +2191 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.d.ts +113 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +29 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.d.ts +23 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js +55 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.d.ts +43 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js +81 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.d.ts +22 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js +56 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.d.ts +35 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js +74 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.d.ts +146 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +103 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.d.ts +304 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +612 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.d.ts +33 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.js +55 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.d.ts +144 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +137 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.d.ts +386 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +284 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.d.ts +191 -0
- package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +281 -0
- package/node_modules/@sigstore/protobuf-specs/dist/index.d.ts +6 -0
- package/node_modules/@sigstore/protobuf-specs/dist/index.js +37 -0
- package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.d.ts +4 -0
- package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js +35 -0
- package/node_modules/@sigstore/protobuf-specs/package.json +35 -0
- package/node_modules/@sigstore/verify/README.md +9 -0
- package/node_modules/@sigstore/verify/dist/bundle/dsse.d.ts +12 -0
- package/node_modules/@sigstore/verify/dist/bundle/dsse.js +44 -0
- package/node_modules/@sigstore/verify/dist/bundle/index.d.ts +4 -0
- package/node_modules/@sigstore/verify/dist/bundle/index.js +59 -0
- package/node_modules/@sigstore/verify/dist/bundle/message.d.ts +13 -0
- package/node_modules/@sigstore/verify/dist/bundle/message.js +54 -0
- package/node_modules/@sigstore/verify/dist/error.d.ts +16 -0
- package/node_modules/@sigstore/verify/dist/error.js +34 -0
- package/node_modules/@sigstore/verify/dist/index.d.ts +6 -0
- package/node_modules/@sigstore/verify/dist/index.js +28 -0
- package/node_modules/@sigstore/verify/dist/key/certificate.d.ts +21 -0
- package/node_modules/@sigstore/verify/dist/key/certificate.js +216 -0
- package/node_modules/@sigstore/verify/dist/key/index.d.ts +10 -0
- package/node_modules/@sigstore/verify/dist/key/index.js +75 -0
- package/node_modules/@sigstore/verify/dist/key/sct.d.ts +4 -0
- package/node_modules/@sigstore/verify/dist/key/sct.js +78 -0
- package/node_modules/@sigstore/verify/dist/policy.d.ts +5 -0
- package/node_modules/@sigstore/verify/dist/policy.js +50 -0
- package/node_modules/@sigstore/verify/dist/shared.types.d.ts +50 -0
- package/node_modules/@sigstore/verify/dist/shared.types.js +2 -0
- package/node_modules/@sigstore/verify/dist/timestamp/index.d.ts +11 -0
- package/node_modules/@sigstore/verify/dist/timestamp/index.js +24 -0
- package/node_modules/@sigstore/verify/dist/timestamp/tsa.d.ts +3 -0
- package/node_modules/@sigstore/verify/dist/timestamp/tsa.js +63 -0
- package/node_modules/@sigstore/verify/dist/tlog/checkpoint.d.ts +11 -0
- package/node_modules/@sigstore/verify/dist/tlog/checkpoint.js +154 -0
- package/node_modules/@sigstore/verify/dist/tlog/dsse.d.ts +6 -0
- package/node_modules/@sigstore/verify/dist/tlog/dsse.js +106 -0
- package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.d.ts +6 -0
- package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +94 -0
- package/node_modules/@sigstore/verify/dist/tlog/index.d.ts +5 -0
- package/node_modules/@sigstore/verify/dist/tlog/index.js +92 -0
- package/node_modules/@sigstore/verify/dist/tlog/intoto.d.ts +3 -0
- package/node_modules/@sigstore/verify/dist/tlog/intoto.js +62 -0
- package/node_modules/@sigstore/verify/dist/tlog/merkle.d.ts +3 -0
- package/node_modules/@sigstore/verify/dist/tlog/merkle.js +104 -0
- package/node_modules/@sigstore/verify/dist/tlog/set.d.ts +3 -0
- package/node_modules/@sigstore/verify/dist/tlog/set.js +60 -0
- package/node_modules/@sigstore/verify/dist/trust/filter.d.ts +8 -0
- package/node_modules/@sigstore/verify/dist/trust/filter.js +23 -0
- package/node_modules/@sigstore/verify/dist/trust/index.d.ts +5 -0
- package/node_modules/@sigstore/verify/dist/trust/index.js +90 -0
- package/node_modules/@sigstore/verify/dist/trust/trust.types.d.ts +29 -0
- package/node_modules/@sigstore/verify/dist/trust/trust.types.js +2 -0
- package/node_modules/@sigstore/verify/dist/verifier.d.ts +31 -0
- package/node_modules/@sigstore/verify/dist/verifier.js +160 -0
- package/node_modules/@sigstore/verify/package.json +36 -0
- package/package.json +37 -4
package/lib/daemon.js
ADDED
|
@@ -0,0 +1,888 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// ch-local daemon --home <abs> (countinghouse's shared-runtime design, #236,
|
|
3
|
+
// section 6, "Starting"): the one runtime this user's sessions share. The
|
|
4
|
+
// native shim spawns it with the home as its working directory and a cleared
|
|
5
|
+
// environment (shim.json's), and releases start.lock at once.
|
|
6
|
+
//
|
|
7
|
+
// 1. SIGHUP is ignored from the first line, so the daemon outlives the shim's
|
|
8
|
+
// parent ending.
|
|
9
|
+
// 2. --home must be absolute and name the working directory.
|
|
10
|
+
// 3. start.lock (<home>/run/daemon/start.lock, lib/lock.js's protocol) is
|
|
11
|
+
// taken as the first act, waiting behind the shim's release.
|
|
12
|
+
// 4. daemon.json is checked again under the lock: a live pid whose socket
|
|
13
|
+
// proves the secret is another daemon, and this one exits 0 at once.
|
|
14
|
+
// Anything else there is stale.
|
|
15
|
+
// 5. The runtime starts on its session socket (start's session mode: the
|
|
16
|
+
// home given, its environment shim.json's allowlist, its own process
|
|
17
|
+
// group), and daemon.json ({pid, socket, runtimeVersion, daemonVersion,
|
|
18
|
+
// started}, 0600) is written once the runtime has told this daemon it
|
|
19
|
+
// listens on that socket AND the socket proves the secret, within
|
|
20
|
+
// READY_MS. Then the lock is released, and the runtime runs on. A runtime
|
|
21
|
+
// not adopted (no tell, a timeout, daemon.json not written) is stopped,
|
|
22
|
+
// and its end awaited; a first one that never listened writes failed.json
|
|
23
|
+
// after GRACE_MS of that wait, so the shim that started this daemon falls
|
|
24
|
+
// back inside its 28 s.
|
|
25
|
+
// 6. Supervised (C3a): a runtime that ends unasked is restarted, under
|
|
26
|
+
// start.lock, at once and then after 1, 5 and 30 s, each one handed the
|
|
27
|
+
// session table; after 5 failures in 10 minutes, failed.json and an exit.
|
|
28
|
+
// The idle stop, and a SIGINT or SIGTERM, stop it; then daemon.json goes,
|
|
29
|
+
// under start.lock, if it is still this daemon's. failed.json's `signal`
|
|
30
|
+
// is null: start's spawn reports a signal death as exit 1.
|
|
31
|
+
// Where it listens (C4c, lib/session-socket.js): on Windows a named pipe,
|
|
32
|
+
// its name random per runtime start, so daemon.json is rewritten at each
|
|
33
|
+
// restart; on POSIX <home>/run/daemon/sessions.sock, or the long-home
|
|
34
|
+
// fallback. The run directory is passed as --sessionDir (countinghouse C2).
|
|
35
|
+
// On Windows the home, <home>/run and <home>/run/daemon pass win-acl.js
|
|
36
|
+
// privateProblem, the two run directories made private by DACL first, and
|
|
37
|
+
// daemon.json and failed.json are created with an owner-only DACL.
|
|
38
|
+
//
|
|
39
|
+
// 7. Upgrades (C3b): <home>/run/daemon/requests (lib/daemon-requests.js),
|
|
40
|
+
// which an install appends to. A runtime that changed is drained, and
|
|
41
|
+
// restarted with the table under start.lock. A ch-local that changed is
|
|
42
|
+
// drained; then, under start.lock, daemon.json goes, the runtime stops,
|
|
43
|
+
// and a new daemon is started with the table on its fd 3 (never in argv
|
|
44
|
+
// or env; the secret is never in it). This daemon exits once the new one
|
|
45
|
+
// has written daemon.json. A failed handoff starts the new one empty.
|
|
46
|
+
const crypto = require('node:crypto');
|
|
47
|
+
const fs = require('node:fs');
|
|
48
|
+
const net = require('node:net');
|
|
49
|
+
const path = require('node:path');
|
|
50
|
+
const {withLockFile} = require('./lock');
|
|
51
|
+
const {readPrivateIn} = require('./private-file');
|
|
52
|
+
const {createSessionTable} = require('./session-table');
|
|
53
|
+
const {readRequests, emptyRequests} = require('./daemon-requests');
|
|
54
|
+
const {SOCKET, isPipeName, socketFor, socketDirProblem, socketOk} = require('./session-socket');
|
|
55
|
+
|
|
56
|
+
// How long a runtime may take to listen. With the shim's longest retry gap
|
|
57
|
+
// (30 s) and one handshake (5 s), inside a restored session's 60 s reconnect
|
|
58
|
+
// window.
|
|
59
|
+
const READY_MS = 20000;
|
|
60
|
+
// A first start with provably nothing to restore may go on to this, counted
|
|
61
|
+
// from the daemon's own process start: inside the 28 s of the shim that
|
|
62
|
+
// started it (shim/src/attach.rs COLD_BUDGET), whose clock began before the
|
|
63
|
+
// spawn: at most 1 s of late spawn, then this, then 2 s for the last probe,
|
|
64
|
+
// daemon.json and the handshake, or, when it never listened, for GRACE_MS and
|
|
65
|
+
// failed.json (on a busy machine a cold start can outlast the plain 20 s
|
|
66
|
+
// budget).
|
|
67
|
+
const COLD_READY_MS = 25000;
|
|
68
|
+
// The first runtime's wait. The longer one only when nothing can be waiting to
|
|
69
|
+
// resume: no handoff at all (not an empty one, nor a --handoff whose pipe
|
|
70
|
+
// could not be read: handedOver), an empty table,
|
|
71
|
+
// and no daemon.json left behind (a crashed daemon's, readable or not; an idle
|
|
72
|
+
// stop removes its own). Anything that can't be judged keeps `ready`, as does
|
|
73
|
+
// a daemon that has already used the time (never shorter than `ready`).
|
|
74
|
+
// elapsed: since this process began, on a monotonic clock (never read as
|
|
75
|
+
// less than 0, so the wait is never past `cold`).
|
|
76
|
+
// {handoff, handedOver, rows, leftover, ready, cold, elapsed} -> ms
|
|
77
|
+
function firstReadyMs({handoff, handedOver = false, rows, leftover, ready, cold, elapsed = 0}) {
|
|
78
|
+
if (handoff != null || handedOver !== false || rows !== 0 || leftover !== false) return ready;
|
|
79
|
+
return Math.max(ready, cold - Math.max(0, elapsed));
|
|
80
|
+
}
|
|
81
|
+
// a stopped runtime's end, awaited at most this long: start's SIGKILL comes
|
|
82
|
+
// at 10 s
|
|
83
|
+
const STOP_MS = 15000;
|
|
84
|
+
// a first runtime that never listened: its moment to end on the signal before
|
|
85
|
+
// failed.json is written
|
|
86
|
+
const GRACE_MS = 500;
|
|
87
|
+
// after the last session leaves (#236 section 6, daemonIdleMinutes)
|
|
88
|
+
const IDLE_MS = 10 * 60 * 1000;
|
|
89
|
+
// restarts: at once, then 1, 5 and 30 s; 5 failures in 10 minutes give up
|
|
90
|
+
const BACKOFF_MS = [0, 1000, 5000, 30000];
|
|
91
|
+
const MAX_FAILURES = 5;
|
|
92
|
+
const FAILURE_WINDOW_MS = 10 * 60 * 1000;
|
|
93
|
+
// the requests file's poll; a drain's wait for in-flight calls, unless the
|
|
94
|
+
// runtime says drained first: drainBoundMs
|
|
95
|
+
const POLL_MS = 1000;
|
|
96
|
+
// a refused read of the requests file is tried again after this (M2)
|
|
97
|
+
const REFUSED_RETRY_MS = 12000;
|
|
98
|
+
// (an answer's way back after its call's own timeout)
|
|
99
|
+
const DRAIN_MARGIN_MS = 2000;
|
|
100
|
+
const PROBE_MS = 2000;
|
|
101
|
+
const SECRET_FORM = /^[0-9a-f]{64}\n?$/;
|
|
102
|
+
|
|
103
|
+
const hmac = (secret, ...parts) => crypto.createHmac('sha256', secret).update(Buffer.concat(parts.map((p) => Buffer.from(p)))).digest();
|
|
104
|
+
const frame = (kind, obj) => { const b = Buffer.from(JSON.stringify(obj)); const h = Buffer.alloc(5); h.write(kind, 0, 'ascii'); h.writeUInt32BE(b.length, 1); return Buffer.concat([h, b]); };
|
|
105
|
+
|
|
106
|
+
// Whether the socket proves the secret (contract 2's HELLO and PROVE; AUTH is
|
|
107
|
+
// never sent, so no session opens) -> Promise<boolean>
|
|
108
|
+
// Used on a socket this daemon's own runtime has just told it listens on;
|
|
109
|
+
// a daemon.json's, read from disk, goes through probeRecorded.
|
|
110
|
+
function probe(socket, secret, ms = PROBE_MS, {platform = process.platform} = {}) {
|
|
111
|
+
// its own runtime's unix socket, by absolute path, or on Windows its named
|
|
112
|
+
// pipe and nothing else: never a host and port
|
|
113
|
+
const ok = platform === 'win32' ? isPipeName(socket) : (typeof socket === 'string' && path.isAbsolute(socket));
|
|
114
|
+
if (!ok) return Promise.resolve(false);
|
|
115
|
+
return new Promise((resolve) => {
|
|
116
|
+
let done = false;
|
|
117
|
+
let buf = Buffer.alloc(0);
|
|
118
|
+
const finish = (v) => { if (!done) { done = true; clearTimeout(timer); c.destroy(); resolve(v); } };
|
|
119
|
+
const nc = crypto.randomBytes(32);
|
|
120
|
+
const c = net.createConnection(socket);
|
|
121
|
+
const timer = setTimeout(() => finish(false), ms);
|
|
122
|
+
c.on('connect', () => c.write(frame('H', {protocol: 1, nc: nc.toString('base64')})));
|
|
123
|
+
c.on('data', (d) => {
|
|
124
|
+
buf = Buffer.concat([buf, d]);
|
|
125
|
+
if (buf.length < 5) return;
|
|
126
|
+
if (String.fromCharCode(buf[0]) !== 'P') return finish(false);
|
|
127
|
+
const n = buf.readUInt32BE(1);
|
|
128
|
+
if (n > 4096) return finish(false);
|
|
129
|
+
if (buf.length < 5 + n) return;
|
|
130
|
+
try {
|
|
131
|
+
const prove = JSON.parse(buf.subarray(5, 5 + n).toString('utf8'));
|
|
132
|
+
const ns = Buffer.from(String(prove.ns), 'base64');
|
|
133
|
+
const ms2 = Buffer.from(String(prove.ms), 'base64');
|
|
134
|
+
const want = hmac(secret, 'ch-server', Buffer.from([1]), nc, ns);
|
|
135
|
+
return finish(ns.length === 32 && ms2.length === want.length && crypto.timingSafeEqual(ms2, want));
|
|
136
|
+
} catch (e) {
|
|
137
|
+
return finish(false);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
c.on('error', () => finish(false));
|
|
141
|
+
c.on('close', () => finish(false));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// A daemon.json's socket, which may be stale and on Windows taken by anyone:
|
|
146
|
+
// there, PowerShell's probe (lib/pipe-probe.js: Identification only, the
|
|
147
|
+
// pipe's owner this user, SYSTEM or Administrators, then the PROVE); on
|
|
148
|
+
// POSIX the socket is in the private run directory, and probe() serves.
|
|
149
|
+
const probeRecorded = (socket, secret, {platform = process.platform, probePipe = null} = {}) => (platform === 'win32'
|
|
150
|
+
? (probePipe || require('./pipe-probe').probePipe)(socket, secret, PROBE_MS)
|
|
151
|
+
: probe(socket, secret, PROBE_MS, {platform}));
|
|
152
|
+
|
|
153
|
+
const readSecret = (runDir) => {
|
|
154
|
+
try {
|
|
155
|
+
const text = readPrivateIn(runDir, 'secret', 80).toString('utf8');
|
|
156
|
+
return SECRET_FORM.test(text) ? Buffer.from(text.slice(0, 64), 'hex') : null;
|
|
157
|
+
} catch (e) {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const readDaemonJson = (runDir) => {
|
|
162
|
+
try {
|
|
163
|
+
return JSON.parse(readPrivateIn(runDir, 'daemon.json', 4096).toString('utf8'));
|
|
164
|
+
} catch (e) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// daemon.json read plainly, for the daemon's identity check on its own file
|
|
170
|
+
// (writeMine, removeMine): a regular file under one name, never a link, at
|
|
171
|
+
// most 4096 bytes. Not the private read, whose Windows ACL check is a
|
|
172
|
+
// blocking PowerShell run, two more per restart while shims wait inside
|
|
173
|
+
// their attach (the closing pass, L3). -> the object, or null
|
|
174
|
+
const readOwnDaemonJson = (runDir) => {
|
|
175
|
+
const file = path.join(runDir, 'daemon.json');
|
|
176
|
+
let fd = null;
|
|
177
|
+
try {
|
|
178
|
+
// (a link refused on every platform: Windows has no O_NOFOLLOW)
|
|
179
|
+
if (!fs.lstatSync(file).isFile()) return null;
|
|
180
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
181
|
+
const st = fs.fstatSync(fd);
|
|
182
|
+
if (!st.isFile() || st.size > 4096) return null;
|
|
183
|
+
const buf = Buffer.alloc(st.size);
|
|
184
|
+
fs.readSync(fd, buf, 0, st.size, 0);
|
|
185
|
+
return JSON.parse(buf.toString('utf8'));
|
|
186
|
+
} catch (e) {
|
|
187
|
+
return null;
|
|
188
|
+
} finally {
|
|
189
|
+
if (fd != null) try { fs.closeSync(fd); } catch (e) { /* closed */ }
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// <home>/run and <home>/run/daemon, made 0700 if missing. On Windows (C4c)
|
|
194
|
+
// neither may be a link or a junction; both get a protected DACL (this user
|
|
195
|
+
// and SYSTEM, inherited by what is made in them), and must then pass
|
|
196
|
+
// privateProblem, checked as directories (an inherit-only rule for anyone
|
|
197
|
+
// else flows into the files), in one PowerShell run. -> {runDir} or {problem}
|
|
198
|
+
function ensureRunDir(home, {platform = process.platform, winAcl = null} = {}) {
|
|
199
|
+
const run = path.join(home, 'run');
|
|
200
|
+
const runDir = path.join(run, 'daemon');
|
|
201
|
+
if (platform !== 'win32') {
|
|
202
|
+
// (each made on its own, never the home: one an uninstall removed is not
|
|
203
|
+
// made again -- the medium on A9's round, 2)
|
|
204
|
+
for (const d of [run, runDir]) {
|
|
205
|
+
try { fs.mkdirSync(d, {mode: 0o700}); } catch (e) { if (e.code !== 'EEXIST') return {problem: `its run directory ${d} could not be made (${e.code || e.message})`}; }
|
|
206
|
+
fs.chmodSync(d, 0o700);
|
|
207
|
+
}
|
|
208
|
+
return {runDir};
|
|
209
|
+
}
|
|
210
|
+
// a directory there already must be one, not a link or a junction (both
|
|
211
|
+
// read as links), before its DACL is set: a junction's target would have
|
|
212
|
+
// its DACL rewritten (the review of #39). The home was checked before this.
|
|
213
|
+
for (const d of [run, runDir]) {
|
|
214
|
+
let st = null;
|
|
215
|
+
try { st = fs.lstatSync(d); } catch (e) { if (e.code !== 'ENOENT') return {problem: `its run directory ${d} could not be read (${e.code || e.message})`}; }
|
|
216
|
+
if (st != null && (st.isSymbolicLink() || !st.isDirectory())) return {problem: `its run directory ${d} is not a directory (a link or a junction is refused)`};
|
|
217
|
+
}
|
|
218
|
+
const acl = winAcl || require('./win-acl');
|
|
219
|
+
let read;
|
|
220
|
+
try {
|
|
221
|
+
read = acl.makePrivateDirs([run, runDir], [run, runDir]);
|
|
222
|
+
} catch (e) {
|
|
223
|
+
return {problem: `its run directory could not be made private (${e.code || e.message})`};
|
|
224
|
+
}
|
|
225
|
+
const names = [`its run directory ${run}`, `its run directory ${runDir}`];
|
|
226
|
+
for (let i = 0; i < names.length; i++) {
|
|
227
|
+
const why = acl.privateProblem(names[i], read[i], {directory: true});
|
|
228
|
+
if (why != null) return {problem: why};
|
|
229
|
+
}
|
|
230
|
+
return {runDir};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// (writePrivate: lib/private-write.js, shared with start's held-back file)
|
|
234
|
+
const {writePrivate} = require('./private-write');
|
|
235
|
+
|
|
236
|
+
// A drain's bound: the longest a call may still be inside its own timeout --
|
|
237
|
+
// the requestTimeout setting's largest value, which no start, live set or
|
|
238
|
+
// session's confirmed loosening goes past (lib/settings.js) -- and
|
|
239
|
+
// DRAIN_MARGIN_MS. Only a bound: the runtime says drained once its calls
|
|
240
|
+
// have ended, and a runtime that ends ends the wait too. Not what is stored
|
|
241
|
+
// now: the runtime may run with another value (set live since, a session's
|
|
242
|
+
// loosening, a file edited by hand or holding another key it can't read).
|
|
243
|
+
// The drain runs outside start.lock (the stop and the restart take it
|
|
244
|
+
// after), so the bound never makes that lock look stale.
|
|
245
|
+
// At most DRAIN_SESSION_MS, though: the runtime closes its idle sessions'
|
|
246
|
+
// connections as it drains, which starts each one's 60 s reconnect window,
|
|
247
|
+
// and their reattach is refused meanwhile; past 60 s the runtime ends them
|
|
248
|
+
// and their rows, with confirmed loosenings and locks, are lost at the
|
|
249
|
+
// restart. After the drain the restart still waits for start.lock and stops
|
|
250
|
+
// the old runtime (STOP_MS at most), all inside that window: so the drain
|
|
251
|
+
// takes 60 s less STOP_MS less 5 s for the lock and the restart, and a call
|
|
252
|
+
// longer than that is cut, as before A13, while every other session resumes
|
|
253
|
+
// (the final pass on #148, and its medium; the runtime keeping a session its
|
|
254
|
+
// own drain detached is a countinghouse row). -> ms
|
|
255
|
+
const SESSION_WINDOW_MS = 60000;
|
|
256
|
+
const DRAIN_SESSION_MS = SESSION_WINDOW_MS - STOP_MS - 5000;
|
|
257
|
+
function drainBoundMs() {
|
|
258
|
+
return Math.min(require('./settings').entryOf('requestTimeout').max + DRAIN_MARGIN_MS, DRAIN_SESSION_MS);
|
|
259
|
+
}
|
|
260
|
+
const {preloadForSwap} = require('./swap-preload');
|
|
261
|
+
|
|
262
|
+
const version = (file) => { try { return String(JSON.parse(fs.readFileSync(file, 'utf8')).version); } catch (e) { return 'unknown'; } };
|
|
263
|
+
// the version of the code this process runs, read once as daemon.js loads at
|
|
264
|
+
// the process's start: never the disk's later, which an install that swaps
|
|
265
|
+
// app/ meanwhile changes under it (A6, the final pass)
|
|
266
|
+
const RUNNING_VERSION = version(path.join(__dirname, '..', 'package.json'));
|
|
267
|
+
|
|
268
|
+
// the runtime, in start's session mode -> Promise<exit code>.
|
|
269
|
+
// opts: {socket, sessionDir, home, signal (abort stops the runtime), onListening(msg)}
|
|
270
|
+
// The re-exec handoff (C3b): the table, as one frame on the new daemon's fd
|
|
271
|
+
// 3, a 4-byte big-endian length and {v: 1, sessions, declines}. It never
|
|
272
|
+
// goes in argv or env, and the secret is never in it.
|
|
273
|
+
const MAX_HANDOFF = 32 * 1024 * 1024;
|
|
274
|
+
function encodeHandoff(restore) {
|
|
275
|
+
const body = Buffer.from(JSON.stringify({v: 1, sessions: restore.sessions, declines: restore.declines}));
|
|
276
|
+
const head = Buffer.alloc(4);
|
|
277
|
+
head.writeUInt32BE(body.length, 0);
|
|
278
|
+
return Buffer.concat([head, body]);
|
|
279
|
+
}
|
|
280
|
+
// -> {sessions, declines} or null
|
|
281
|
+
function decodeHandoff(buf) {
|
|
282
|
+
if (!Buffer.isBuffer(buf) || buf.length < 4) return null;
|
|
283
|
+
const n = buf.readUInt32BE(0);
|
|
284
|
+
if (n > MAX_HANDOFF || buf.length !== 4 + n) return null;
|
|
285
|
+
try {
|
|
286
|
+
const t = JSON.parse(buf.subarray(4).toString('utf8'));
|
|
287
|
+
return t != null && t.v === 1 && Array.isArray(t.sessions) && Array.isArray(t.declines) ? t : null;
|
|
288
|
+
} catch (e) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function defaultRun({socket, sessionDir, home, signal, onListening, onTold, onControl, restore, onRestoreRefused}, io) {
|
|
294
|
+
return require('./start').start({passThrough: [], session: {socket, sessionDir, home, signal, onListening, onTold, onControl, restore, onRestoreRefused}}, io);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// {home, handoff?} -> exit code. handoff: the bytes read from fd 3 when
|
|
298
|
+
// started with --handoff (C3b). run: the runtime's start, for the tests.
|
|
299
|
+
// (the shared runtime's log, closed once the daemon ends, its lines written:
|
|
300
|
+
// C-daemon-log)
|
|
301
|
+
async function daemon(args, io, opts) {
|
|
302
|
+
const held = {log: null};
|
|
303
|
+
try {
|
|
304
|
+
return await daemonRun(args, io, opts, held);
|
|
305
|
+
} catch (e) {
|
|
306
|
+
// (an end no one said: in the log as well, before it goes)
|
|
307
|
+
if (held.log != null) held.log.write(`ch-local daemon: ended by an error: ${(e && e.stack) || e}`);
|
|
308
|
+
throw e;
|
|
309
|
+
} finally {
|
|
310
|
+
if (held.log != null) await held.log.close();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function daemonRun({home, handoff = null, handedOver = false}, io, {run = defaultRun} = {}, held = {}) {
|
|
315
|
+
if (typeof io.ignoreSignal === 'function') io.ignoreSignal('SIGHUP');
|
|
316
|
+
const fail = (s, code = 1) => { io.stderr.write(`ch-local daemon: ${s}\n`); return code; };
|
|
317
|
+
const say = (s) => io.stderr.write(`ch-local daemon: ${s}\n`);
|
|
318
|
+
// failed.json as this process began (before its own checks, which take a
|
|
319
|
+
// while on Windows), by what a new one changes
|
|
320
|
+
const failedKey = () => { try { const st = fs.lstatSync(path.join(home, 'run', 'daemon', 'failed.json')); return `${st.ino}:${st.size}:${st.mtimeMs}`; } catch (e) { return null; } };
|
|
321
|
+
const failedBefore = failedKey();
|
|
322
|
+
const platform = io.platform || process.platform;
|
|
323
|
+
let cwdReal = null;
|
|
324
|
+
let homeReal = null;
|
|
325
|
+
try {
|
|
326
|
+
cwdReal = fs.realpathSync(io.cwd);
|
|
327
|
+
homeReal = fs.realpathSync(home);
|
|
328
|
+
} catch (e) {
|
|
329
|
+
return fail(`the home ${home} could not be read (${e.code || e.message})`, 2);
|
|
330
|
+
}
|
|
331
|
+
if (cwdReal !== homeReal) return fail(`--home ${home} is not the working directory`, 2);
|
|
332
|
+
const owned = require('./home').homeOwnershipProblem(homeReal, platform, {fileAcl: io.winAcl != null ? io.winAcl.fileAcl : undefined});
|
|
333
|
+
if (owned != null) return fail(`--home ${home}: ${owned}`, 2);
|
|
334
|
+
const made = ensureRunDir(home, {platform, winAcl: io.winAcl || null});
|
|
335
|
+
if (made.problem != null) return fail(`--home ${home}: ${made.problem}`, 2);
|
|
336
|
+
const runDir = made.runDir;
|
|
337
|
+
// The shared runtime's log (C-daemon-log, lib/runtime-log.js): the shim
|
|
338
|
+
// starts this daemon with its output discarded, so its own lines and its
|
|
339
|
+
// runtime's go to <runDir>/runtime.log -- appended to as it is, and
|
|
340
|
+
// rotated by size only by the daemon that has the home (own(), below;
|
|
341
|
+
// never a second daemon that finds one serving). One
|
|
342
|
+
// that can't be used is said where the daemon's lines go anyway, and the
|
|
343
|
+
// daemon serves on.
|
|
344
|
+
if (io.runtimeLog !== false) {
|
|
345
|
+
const log = require('./runtime-log').openRuntimeLog(runDir, {platform, acl: io.winAcl || null, ...(io.runtimeLogOptions || {})});
|
|
346
|
+
held.log = log;
|
|
347
|
+
const plain = io.stderr;
|
|
348
|
+
const tee = {write: (s) => { try { plain.write(s); } catch (e) { /* none */ } log.write(s); return true; }};
|
|
349
|
+
io = new Proxy(io, {get: (t, k) => (k === 'stderr' ? tee : k === 'runtimeOutput' ? log : t[k]), set: (t, k, v) => { t[k] = v; return true; }});
|
|
350
|
+
if (log.problem != null) say(`its log: ${log.problem}`);
|
|
351
|
+
}
|
|
352
|
+
// (it outlives an install's swap of <home>/app: every module it may
|
|
353
|
+
// require later is loaded from this release now, lib/swap-preload.js)
|
|
354
|
+
try { preloadForSwap(); } catch (err) { return fail(`this ch-local could not be loaded whole (${err.code || err.message})`); }
|
|
355
|
+
// the socket for one runtime start: on Windows a new pipe name each time;
|
|
356
|
+
// on POSIX always the same path, its fallback directory checked once here
|
|
357
|
+
const env = io.env || process.env;
|
|
358
|
+
const pickSocket = () => socketFor(runDir, {platform, env}).socket;
|
|
359
|
+
if (platform !== 'win32') {
|
|
360
|
+
const {fallback} = socketFor(runDir, {platform, env});
|
|
361
|
+
const why = fallback != null ? socketDirProblem(fallback) : null;
|
|
362
|
+
if (why != null) return fail(`--home ${home}: ${why}`, 2);
|
|
363
|
+
}
|
|
364
|
+
const lockFile = path.join(runDir, 'start.lock');
|
|
365
|
+
const readyMs = Number.isInteger(io.daemonReadyMs) ? io.daemonReadyMs : READY_MS;
|
|
366
|
+
// (a test's short ready wait is the cold one too, unless it names its own)
|
|
367
|
+
const coldReadyMs = Number.isInteger(io.daemonColdReadyMs) ? io.daemonColdReadyMs : Number.isInteger(io.daemonReadyMs) ? io.daemonReadyMs : COLD_READY_MS;
|
|
368
|
+
const stopMs = Number.isInteger(io.daemonStopMs) ? io.daemonStopMs : STOP_MS;
|
|
369
|
+
const graceMs = Number.isInteger(io.daemonGraceMs) ? io.daemonGraceMs : GRACE_MS;
|
|
370
|
+
const idleMs = Number.isInteger(io.daemonIdleMs) ? io.daemonIdleMs : IDLE_MS;
|
|
371
|
+
const backoff = Array.isArray(io.daemonBackoffMs) ? io.daemonBackoffMs : BACKOFF_MS;
|
|
372
|
+
|
|
373
|
+
// the session table, in memory only, across this daemon's runtimes, and
|
|
374
|
+
// across a re-exec through the handoff
|
|
375
|
+
const table = createSessionTable({warn: say});
|
|
376
|
+
if (handoff != null) {
|
|
377
|
+
const t = decodeHandoff(handoff);
|
|
378
|
+
if (t == null) say('the handoff from the previous daemon could not be read: starting with an empty session table');
|
|
379
|
+
else {
|
|
380
|
+
const {kept, loosened} = table.seed(t);
|
|
381
|
+
say(`the previous daemon handed over ${kept} session(s)${loosened > 0 ? `; ${loosened} session(s) lost loosenings, which a handover never carries` : ''}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
const pollMs = Number.isInteger(io.daemonPollMs) ? io.daemonPollMs : POLL_MS;
|
|
385
|
+
const drainMs = Number.isInteger(io.daemonDrainMs) ? io.daemonDrainMs : drainBoundMs();
|
|
386
|
+
let loopDone = false; // the supervisor loop has ended (stopped, or gave up)
|
|
387
|
+
const drainTimers = io.daemonDrainTimers || {setTimeout, clearTimeout};
|
|
388
|
+
const selfPackage = typeof io.daemonPackage === 'string' ? io.daemonPackage : path.join(__dirname, '..', 'package.json');
|
|
389
|
+
// (a test's own package stands in for the code, read at this start)
|
|
390
|
+
const runningVersion = typeof io.daemonPackage === 'string' ? version(io.daemonPackage) : RUNNING_VERSION;
|
|
391
|
+
const runtimePackage = path.join(home, 'app', 'node_modules', 'countinghouse', 'package.json');
|
|
392
|
+
let drained = null; // resolves the wait after a drain
|
|
393
|
+
let current = null; // the runtime now running
|
|
394
|
+
let stopping = false; // an idle stop or a signal: its end is no failure
|
|
395
|
+
let idleTimer = null;
|
|
396
|
+
let isIdle = false; // the runtime's last word: idle, or busy
|
|
397
|
+
const armIdle = () => {
|
|
398
|
+
if (idleTimer != null || stopping) return;
|
|
399
|
+
idleTimer = setTimeout(() => { idleTimer = null; idleStop().catch((e) => say(`the idle stop failed (${e.message})`)); }, idleMs);
|
|
400
|
+
if (typeof idleTimer.unref === 'function') idleTimer.unref();
|
|
401
|
+
};
|
|
402
|
+
const onTold = (m) => {
|
|
403
|
+
if (m.type === 'drained') { if (drained != null) drained(); return; }
|
|
404
|
+
if (m.type === 'busy') { isIdle = false; clearTimeout(idleTimer); idleTimer = null; return; }
|
|
405
|
+
if (m.type === 'idle') { isIdle = true; armIdle(); return; }
|
|
406
|
+
table.told(m);
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
// one runtime, in start's session mode -> its handle
|
|
410
|
+
let requestsAtStart = 0;
|
|
411
|
+
const startRuntime = () => {
|
|
412
|
+
// (the requests file's size as this runtime starts: a restart asked
|
|
413
|
+
// within it was written before this start read what is stored -- R3)
|
|
414
|
+
try { requestsAtStart = fs.lstatSync(path.join(runDir, require('./daemon-requests').NAME)).size; } catch (e) { requestsAtStart = 0; }
|
|
415
|
+
const h = {ended: null, told: false, request: null, stop: new AbortController(), socket: pickSocket()};
|
|
416
|
+
const onListening = (m) => { if (m != null && m.type === 'listening' && m.socket === h.socket) h.told = true; };
|
|
417
|
+
h.exited = Promise.resolve()
|
|
418
|
+
.then(() => run({socket: h.socket, sessionDir: runDir, home, signal: h.stop.signal, onListening, onTold, onControl: (fn) => { h.request = fn; }, restore: () => table.restore(),
|
|
419
|
+
// only the runtime still current: a late word from one that has been
|
|
420
|
+
// replaced (it crashed during its restore) never clears the table
|
|
421
|
+
onRestoreRefused: () => { if (current !== h) return; say('the runtime refused the session table: starting it over'); table.clear(); }}, io))
|
|
422
|
+
.then((c) => { h.ended = {code: c}; return c; }, (err) => { h.ended = {code: 1, err}; return 1; });
|
|
423
|
+
// ready: our own runtime told us it listens on this socket (an older
|
|
424
|
+
// runtime's socket can prove a secret too), AND the socket proves it
|
|
425
|
+
h.ready = async(bound = readyMs) => {
|
|
426
|
+
const until = performance.now() + bound;
|
|
427
|
+
while (h.ended == null && performance.now() < until) {
|
|
428
|
+
if (h.told) {
|
|
429
|
+
const secret = readSecret(runDir);
|
|
430
|
+
if (secret != null && await probe(h.socket, secret, 500)) return true;
|
|
431
|
+
}
|
|
432
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
433
|
+
}
|
|
434
|
+
return false;
|
|
435
|
+
};
|
|
436
|
+
// stopped (SIGTERM, then start's SIGKILL), and its end awaited within a
|
|
437
|
+
// bound, so a hung one never holds start.lock -> whether it ended
|
|
438
|
+
// ms: how long (the stop's bound), for a caller that waits in two parts
|
|
439
|
+
h.abandon = async(ms = stopMs) => {
|
|
440
|
+
h.stop.abort();
|
|
441
|
+
let timer = null;
|
|
442
|
+
const gone = await Promise.race([h.exited.then(() => true), new Promise((r) => { timer = setTimeout(() => r(false), ms); })]);
|
|
443
|
+
clearTimeout(timer);
|
|
444
|
+
return gone;
|
|
445
|
+
};
|
|
446
|
+
return h;
|
|
447
|
+
};
|
|
448
|
+
const exitOf = (h) => (h.ended != null && Number.isSafeInteger(h.ended.code) ? h.ended.code : null);
|
|
449
|
+
// failed.json (#236 section 6): the shims fall back to their own runtimes
|
|
450
|
+
// for 10 minutes instead of starting daemon after daemon
|
|
451
|
+
const writeFailed = (reason, exit) => {
|
|
452
|
+
try {
|
|
453
|
+
writePrivate(runDir, 'failed.json', `${JSON.stringify({v: 1, at: Date.now(), exit: Number.isSafeInteger(exit) ? exit : null, signal: null, reason})}\n`);
|
|
454
|
+
} catch (e) {
|
|
455
|
+
say(`failed.json could not be written (${e.code || e.message})`);
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
let mine = null;
|
|
459
|
+
let wake = null; // ends a backoff's sleep at a stop signal
|
|
460
|
+
const removeMine = () => {
|
|
461
|
+
const now = platform === 'win32' ? readOwnDaemonJson(runDir) : readDaemonJson(runDir);
|
|
462
|
+
if (mine != null && now != null && now.pid === mine.pid && now.started === mine.started) fs.rmSync(path.join(runDir, 'daemon.json'), {force: true});
|
|
463
|
+
};
|
|
464
|
+
// a SIGINT or SIGTERM to the daemon stops it, not a restart
|
|
465
|
+
if (typeof io.trapSignals === 'function') {
|
|
466
|
+
io.trapSignals(() => { stopping = true; if (current != null) current.stop.abort(); if (wake != null) wake(); }, ['SIGINT', 'SIGTERM']);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// The idle stop (#236 section 6): under start.lock, the runtime is asked
|
|
470
|
+
// to drain only if no session is held and no handshake is under way, which
|
|
471
|
+
// it checks in one step; then daemon.json goes and the runtime stops. A
|
|
472
|
+
// shim arriving meanwhile is refused SHUTTING_DOWN, or waits on the lock,
|
|
473
|
+
// and finds no daemon.json: it starts a new daemon.
|
|
474
|
+
const idleStop = () => withLockFile(lockFile, runDir, io, async() => {
|
|
475
|
+
const h = current;
|
|
476
|
+
if (h == null || stopping || typeof h.request !== 'function') return 0;
|
|
477
|
+
const reply = await h.request({type: 'idle-stop'});
|
|
478
|
+
// a session or a handshake came: not idle. With no 'busy' after it (a
|
|
479
|
+
// handshake in pre-auth that went away), the timer is armed again.
|
|
480
|
+
if (reply != null && reply.code === 'CONTROL_BUSY') { if (isIdle) armIdle(); return 0; }
|
|
481
|
+
// ok, or no answer or a failure: the runtime may drain later and refuse
|
|
482
|
+
// every handshake, so it stops either way
|
|
483
|
+
if (reply == null || reply.ok !== true) say(`the idle stop was answered ${reply != null ? reply.code : 'nothing'}: stopping anyway`);
|
|
484
|
+
stopping = true;
|
|
485
|
+
removeMine();
|
|
486
|
+
say(`idle for ${idleMs / 1000} s: stopping`);
|
|
487
|
+
await h.abandon();
|
|
488
|
+
return 0;
|
|
489
|
+
}, {wait: true, what: 'to finish the idle stop'});
|
|
490
|
+
|
|
491
|
+
// The first runtime, under start.lock, from the shim's release on.
|
|
492
|
+
// (a run directory removed while this waited -- an uninstall -- ends this
|
|
493
|
+
// daemon, never a start without the lock: the medium on A9's round, 2)
|
|
494
|
+
const first = await withLockFile(lockFile, runDir, io, async(release) => {
|
|
495
|
+
// (a stop asked while this waited on the lock: a stop, never a runtime
|
|
496
|
+
// served with the poller and the idle stop off -- the closing pass, L6)
|
|
497
|
+
if (stopping) { say('stopped before it started'); return 0; }
|
|
498
|
+
const info = readDaemonJson(runDir);
|
|
499
|
+
// another daemon: a live pid, on a socket a daemon of this home would
|
|
500
|
+
// have chosen (on POSIX this one, no other; on Windows a pipe of the
|
|
501
|
+
// form), proving the secret
|
|
502
|
+
if (info != null && Number.isInteger(info.pid) && io.alive(info.pid) && socketOk(info.socket, runDir, {platform, env})) {
|
|
503
|
+
const secret = readSecret(runDir);
|
|
504
|
+
if (secret != null && await probeRecorded(info.socket, secret, {platform, probePipe: io.probePipe || null})) {
|
|
505
|
+
io.stderr.write(`ch-local daemon: another daemon (pid ${info.pid}) is running\n`);
|
|
506
|
+
return 0;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
// another daemon gave up since this one began (it waited for the lock): no
|
|
510
|
+
// second try, the sessions run their own runtimes for the file's 10
|
|
511
|
+
// minutes, as they do after any give-up. A file there before this began is
|
|
512
|
+
// the shim's to judge, which does just before it spawns. Never a
|
|
513
|
+
// hand-over's daemon, whose sessions hold its table.
|
|
514
|
+
const failedNow = handoff == null && handedOver === false ? failedKey() : null;
|
|
515
|
+
if (failedNow != null && failedNow !== failedBefore && require('./failed-json').read(runDir) != null) {
|
|
516
|
+
io.stderr.write('ch-local daemon: another daemon gave up while this one waited (failed.json): not starting\n');
|
|
517
|
+
return 0;
|
|
518
|
+
}
|
|
519
|
+
// (judged before daemon.json is cleared: one left behind is a crash's)
|
|
520
|
+
let leftover;
|
|
521
|
+
try { fs.lstatSync(path.join(runDir, 'daemon.json')); leftover = true; } catch (e) { leftover = e.code === 'ENOENT' ? false : null; }
|
|
522
|
+
const firstBound = firstReadyMs({handoff, handedOver, rows: table.size(), leftover, ready: readyMs, cold: coldReadyMs,
|
|
523
|
+
elapsed: typeof io.daemonUptimeMs === 'function' ? io.daemonUptimeMs() : 0});
|
|
524
|
+
fs.rmSync(path.join(runDir, 'daemon.json'), {force: true});
|
|
525
|
+
// (this daemon has the home: it rotates its log at the cap)
|
|
526
|
+
if (held.log != null) held.log.own();
|
|
527
|
+
current = startRuntime();
|
|
528
|
+
if (!(await current.ready(firstBound))) {
|
|
529
|
+
// a SIGINT or SIGTERM while it started: a stop, not a failure
|
|
530
|
+
if (stopping) { if (current.ended == null) await current.abandon(); say('stopped while starting'); return 0; }
|
|
531
|
+
const ended = current.ended != null;
|
|
532
|
+
// failed.json before the rest of a hung runtime's stop (up to 15 s):
|
|
533
|
+
// the shim that started this daemon gives up at 28 s, and one that
|
|
534
|
+
// reads it goes to a runtime of its own (R-first-start-failed-json).
|
|
535
|
+
// Only after a moment to end: one that is merely slow ends on the
|
|
536
|
+
// signal, so the sessions' own runtimes don't start beside it. The
|
|
537
|
+
// lock is held until it has ended, as before.
|
|
538
|
+
const began = performance.now();
|
|
539
|
+
const quick = ended || await current.abandon(Math.min(graceMs, stopMs));
|
|
540
|
+
const rest = () => current.abandon(Math.max(0, stopMs - (performance.now() - began)));
|
|
541
|
+
// (a stop meanwhile is a stop, not a failure, as above; one that comes
|
|
542
|
+
// after the file is written leaves it)
|
|
543
|
+
if (stopping) { if (!quick) await rest(); say('stopped while starting'); return 0; }
|
|
544
|
+
writeFailed('never-listened', exitOf(current));
|
|
545
|
+
const gone = quick || await rest();
|
|
546
|
+
if (ended) return fail(`the runtime ended before it listened (exit ${current.ended.code})`);
|
|
547
|
+
const within = Math.round(firstBound / 1000);
|
|
548
|
+
return fail(gone ? `the runtime did not listen within ${within} s; it was stopped` : `the runtime did not listen within ${within} s; it was stopped, and did not end within ${stopMs / 1000} s`);
|
|
549
|
+
}
|
|
550
|
+
const body = {pid: io.pid, socket: current.socket, runtimeVersion: version(runtimePackage),
|
|
551
|
+
daemonVersion: runningVersion, started: new Date().toISOString(), runtimeStarted: new Date().toISOString()};
|
|
552
|
+
try {
|
|
553
|
+
writePrivate(runDir, 'daemon.json', `${JSON.stringify(body)}\n`);
|
|
554
|
+
} catch (e) {
|
|
555
|
+
const gone = await current.abandon();
|
|
556
|
+
return fail(`daemon.json could not be written (${e.code || e.message}); the runtime was stopped${gone ? '' : `, and did not end within ${stopMs / 1000} s`}`);
|
|
557
|
+
}
|
|
558
|
+
mine = body;
|
|
559
|
+
// the shared mode works again: the shims' fallback ends
|
|
560
|
+
fs.rmSync(path.join(runDir, 'failed.json'), {force: true});
|
|
561
|
+
release();
|
|
562
|
+
return null;
|
|
563
|
+
}, {wait: true, what: 'to finish starting the shared runtime', missing: () => { io.stderr.write('ch-local daemon: the home\'s run directory was removed (an uninstall): not starting\n'); return 0; }});
|
|
564
|
+
if (first !== null) return first;
|
|
565
|
+
|
|
566
|
+
// Supervised: a runtime that ends unasked is restarted at once, then after
|
|
567
|
+
// 1, 5 and 30 s, each handed the table. After 5 failures in 10 minutes the
|
|
568
|
+
// daemon gives up: failed.json, daemon.json removed, exit 1.
|
|
569
|
+
// Upgrades (#236 section 6): <home>/run/daemon/requests is read from where
|
|
570
|
+
// it stood at adoption. A runtime that changed is drained and restarted
|
|
571
|
+
// with the table; a ch-local that changed re-execs this daemon.
|
|
572
|
+
let offset = readRequests(home, 0).offset;
|
|
573
|
+
let seen = null;
|
|
574
|
+
let upgrading = false;
|
|
575
|
+
let replacing = null; // a runtime upgrade swapping `current`: the loop waits for it
|
|
576
|
+
let exitCode = 0;
|
|
577
|
+
// drain, and wait for the in-flight calls: until the runtime says drained,
|
|
578
|
+
// or the bound (which covers the drain request too). A drain refused or
|
|
579
|
+
// left unanswered (an older runtime, a control channel that failed) waits
|
|
580
|
+
// the bound too: how long its calls may run is not known, and only a
|
|
581
|
+
// delay is lost, never a call. The
|
|
582
|
+
// runtime's end -- a crash, the idle stop, a signal's abort -- ends the
|
|
583
|
+
// wait, and the supervisor loop takes that end (counted, restarted, or
|
|
584
|
+
// given up) before the caller goes on, as an end it was not asked for
|
|
585
|
+
const drainWait = async(h) => {
|
|
586
|
+
if (typeof h.request !== 'function') return;
|
|
587
|
+
let timer = null;
|
|
588
|
+
const bound = new Promise((r) => { timer = drainTimers.setTimeout(r, drainMs); });
|
|
589
|
+
const said = new Promise((r) => { drained = r; });
|
|
590
|
+
try {
|
|
591
|
+
const asked = Promise.resolve().then(() => h.request({type: 'drain'})).then((reply) => {
|
|
592
|
+
// (gone: the runtime's end, below; refused or unanswered: the bound)
|
|
593
|
+
if (reply == null || reply.ok !== false) return said;
|
|
594
|
+
return reply.code === 'CONTROL_GONE' ? h.exited : bound;
|
|
595
|
+
});
|
|
596
|
+
await Promise.race([asked, bound, h.exited]);
|
|
597
|
+
} finally {
|
|
598
|
+
// (a drained answer before the bound leaves no timer behind)
|
|
599
|
+
drainTimers.clearTimeout(timer);
|
|
600
|
+
drained = null;
|
|
601
|
+
}
|
|
602
|
+
// (bounded: the loop takes an end within its longest backoff and a
|
|
603
|
+
// stop; past that this caller goes on as the end's owner -- its locked
|
|
604
|
+
// step finds the runtime ended and starts the next one, and the loop,
|
|
605
|
+
// finding it replaced, watches that one -- said once)
|
|
606
|
+
if (h.ended != null && current === h && !stopping && !loopDone) {
|
|
607
|
+
let late = false;
|
|
608
|
+
const lateTimer = drainTimers.setTimeout(() => { late = true; }, stopMs + Math.max(...backoff));
|
|
609
|
+
try {
|
|
610
|
+
while (h.ended != null && current === h && !stopping && !loopDone && !late) await new Promise((r) => setTimeout(r, 50));
|
|
611
|
+
} finally {
|
|
612
|
+
drainTimers.clearTimeout(lateTimer);
|
|
613
|
+
}
|
|
614
|
+
if (late && current === h && !stopping && !loopDone) say('the runtime ended during the drain and the supervisor has not taken that end; going on without it');
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
// daemon.json after a restart: the runtime's version, and its socket (on
|
|
618
|
+
// Windows a new pipe name at each start)
|
|
619
|
+
// (only over this daemon's own file, or none: never another daemon's --
|
|
620
|
+
// a successor's after a hand-over, or a second daemon's -- whatever this
|
|
621
|
+
// one's state; said once, as removeMine leaves another's: A7, the final
|
|
622
|
+
// pass)
|
|
623
|
+
// (a file that can't be read is not taken for another's: writes run under
|
|
624
|
+
// start.lock, so no other daemon writes it meanwhile -- the medium on A7,
|
|
625
|
+
// 1. One that names another daemon ends this one: it can no longer be
|
|
626
|
+
// found, and would act on requests meant for the recorded one -- the
|
|
627
|
+
// medium, 2)
|
|
628
|
+
let saidTheirs = false;
|
|
629
|
+
// (the identity check reads plainly on Windows only, where a private read
|
|
630
|
+
// is a blocking PowerShell run; POSIX keeps the private read -- L3 and
|
|
631
|
+
// the medium on the closing pass, 5)
|
|
632
|
+
const readMine = () => (platform === 'win32' ? readOwnDaemonJson(runDir) : readDaemonJson(runDir));
|
|
633
|
+
// daemon.json another daemon's now: said once, and this daemon stops
|
|
634
|
+
// (A7). Checked on its own wherever this daemon would go on, never only
|
|
635
|
+
// as writeMine's side effect: a socket already null writes nothing (the
|
|
636
|
+
// medium on the closing pass, 2). -> true when it stops
|
|
637
|
+
const theirsNow = () => {
|
|
638
|
+
const there = readMine();
|
|
639
|
+
if (!(there != null && mine != null && (there.pid !== mine.pid || there.started !== mine.started))) return false;
|
|
640
|
+
if (!saidTheirs) say('daemon.json is another daemon\'s now: not rewritten; this daemon stops');
|
|
641
|
+
saidTheirs = true;
|
|
642
|
+
stopping = true;
|
|
643
|
+
if (current != null) current.stop.abort();
|
|
644
|
+
if (wake != null) wake();
|
|
645
|
+
return true;
|
|
646
|
+
};
|
|
647
|
+
const writeMine = (fields) => {
|
|
648
|
+
if (theirsNow()) return;
|
|
649
|
+
mine = Object.assign({}, mine, fields);
|
|
650
|
+
try { writePrivate(runDir, 'daemon.json', `${JSON.stringify(mine)}\n`); } catch (e) { say(`daemon.json could not be rewritten (${e.code || e.message})`); }
|
|
651
|
+
};
|
|
652
|
+
// (runtimeStarted: when this runtime began listening, so `ch-local
|
|
653
|
+
// restart` sees a restart happen -- A5)
|
|
654
|
+
const writeVersion = () => writeMine({socket: current.socket, runtimeVersion: version(runtimePackage), runtimeStarted: new Date().toISOString()});
|
|
655
|
+
// a runtime that ended, until its successor listens: daemon.json names no
|
|
656
|
+
// socket, so nothing probes a name that is free for anyone to take (the
|
|
657
|
+
// review of #39)
|
|
658
|
+
const clearSocket = () => { if (mine != null && mine.socket != null) writeMine({socket: null}); };
|
|
659
|
+
// the runtime drained, then stopped and started again on what is installed
|
|
660
|
+
// and stored (an upgrade of the runtime; a credential added or removed:
|
|
661
|
+
// the new runtime takes the token then), in one hold of start.lock
|
|
662
|
+
const restartRuntime = async(why, what = 'the restarted runtime') => {
|
|
663
|
+
say(`${why}: draining, then restarting the runtime`);
|
|
664
|
+
const h = current;
|
|
665
|
+
await drainWait(h);
|
|
666
|
+
// the stop and the restart in one hold of start.lock, as any restart:
|
|
667
|
+
// a shim's daemon spawned meanwhile waits, then finds this daemon
|
|
668
|
+
await withLockFile(lockFile, runDir, io, async() => {
|
|
669
|
+
if (stopping) return 0;
|
|
670
|
+
// it crashed during the drain, and the loop restarted it onto the
|
|
671
|
+
// installed files already: nothing more to stop or start
|
|
672
|
+
if (current !== h) { if (current.ended == null) writeVersion(); return 0; }
|
|
673
|
+
let done = null;
|
|
674
|
+
replacing = new Promise((r) => { done = r; });
|
|
675
|
+
try {
|
|
676
|
+
await h.abandon();
|
|
677
|
+
clearSocket();
|
|
678
|
+
// (a stop asked during the abandon, or daemon.json another daemon's,
|
|
679
|
+
// checked whatever the socket was: no runtime started after it --
|
|
680
|
+
// the closing pass, L2 and L6)
|
|
681
|
+
if (stopping || theirsNow()) return 0;
|
|
682
|
+
current = startRuntime();
|
|
683
|
+
if (await current.ready()) writeVersion();
|
|
684
|
+
else {
|
|
685
|
+
if (current.ended == null) await current.abandon();
|
|
686
|
+
if (!stopping) say(`${what} did not listen`);
|
|
687
|
+
}
|
|
688
|
+
} finally {
|
|
689
|
+
replacing = null;
|
|
690
|
+
done();
|
|
691
|
+
}
|
|
692
|
+
return 0;
|
|
693
|
+
}, {wait: true, what: `to finish restarting ${what}`});
|
|
694
|
+
};
|
|
695
|
+
// (forRestart: entered only for a restart request, which says its own line)
|
|
696
|
+
const takeUpInstalled = async(forRestart = false) => {
|
|
697
|
+
const runtimeNow = version(runtimePackage);
|
|
698
|
+
const selfNow = version(selfPackage);
|
|
699
|
+
// (a version that couldn't be read is never compared: no hand-over on it
|
|
700
|
+
// -- the medium, 6)
|
|
701
|
+
if (selfNow !== mine.daemonVersion && selfNow !== 'unknown' && mine.daemonVersion !== 'unknown') {
|
|
702
|
+
say(`ch-local ${mine.daemonVersion} -> ${selfNow}: draining, then handing over to a new daemon`);
|
|
703
|
+
await drainWait(current);
|
|
704
|
+
// (a daemon stopped meanwhile -- the idle stop, a signal -- stays
|
|
705
|
+
// stopped: nothing is handed over)
|
|
706
|
+
let wasStopping = false;
|
|
707
|
+
await withLockFile(lockFile, runDir, io, async() => {
|
|
708
|
+
if (stopping) { wasStopping = true; return 0; }
|
|
709
|
+
stopping = true;
|
|
710
|
+
removeMine();
|
|
711
|
+
// whichever runtime is running now: one that crashed during the drain
|
|
712
|
+
// has been replaced by the loop
|
|
713
|
+
await current.abandon();
|
|
714
|
+
const started = typeof io.spawnDaemon === 'function'
|
|
715
|
+
? io.spawnDaemon(['daemon', '--home', home, '--handoff'], {handoff: encodeHandoff(table.restore())})
|
|
716
|
+
: false;
|
|
717
|
+
if (!started) { exitCode = 1; say('the new daemon could not be started; the next session starts one, with an empty table'); }
|
|
718
|
+
return 0;
|
|
719
|
+
}, {wait: true, what: 'to hand over to the new daemon'});
|
|
720
|
+
if (wasStopping) return 'nothing';
|
|
721
|
+
if (exitCode !== 0) return 'handed over';
|
|
722
|
+
// this daemon goes once the new one has written its daemon.json
|
|
723
|
+
const until = performance.now() + READY_MS + stopMs;
|
|
724
|
+
for (;;) {
|
|
725
|
+
const now = readDaemonJson(runDir);
|
|
726
|
+
if (now != null && now.pid !== mine.pid) return 'handed over';
|
|
727
|
+
if (performance.now() > until) { say('the new daemon did not write daemon.json in time; leaving'); return 'handed over'; }
|
|
728
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
// (a version that can't be read now is never a change; one readable now
|
|
732
|
+
// against one that couldn't be read at the start is: N4, and the medium
|
|
733
|
+
// on #147's last round, 4)
|
|
734
|
+
if (runtimeNow !== mine.runtimeVersion && runtimeNow !== 'unknown') {
|
|
735
|
+
await restartRuntime(`countinghouse ${mine.runtimeVersion} -> ${runtimeNow}`, 'the upgraded runtime');
|
|
736
|
+
return 'restarted';
|
|
737
|
+
}
|
|
738
|
+
if (!forRestart) say('an upgrade request, and nothing changed');
|
|
739
|
+
return 'nothing';
|
|
740
|
+
};
|
|
741
|
+
// (a refused read is tried again after REFUSED_RETRY_MS, counted in
|
|
742
|
+
// polls, no clock read -- the closing pass, M2)
|
|
743
|
+
const refusedRetryPolls = Math.max(1, Math.ceil((Number.isInteger(io.daemonRefusedRetryMs) ? io.daemonRefusedRetryMs : REFUSED_RETRY_MS) / pollMs));
|
|
744
|
+
// (a refusal that lasts -- a file too big, of another mode or owner, a
|
|
745
|
+
// link -- is said once per reason, by its code, never its content, and
|
|
746
|
+
// tried again less often each time it is refused at the same size, up to
|
|
747
|
+
// 10 times the first wait; a read that works, or a size that changes,
|
|
748
|
+
// starts again at the first -- the medium on the closing pass, 3 and 4)
|
|
749
|
+
let refusedWait = 0;
|
|
750
|
+
let refusedRun = 0;
|
|
751
|
+
let refusedSize = null;
|
|
752
|
+
const refusedSaid = new Set();
|
|
753
|
+
const poller = setInterval(() => {
|
|
754
|
+
if (upgrading || stopping) return;
|
|
755
|
+
if (refusedWait > 0) { refusedWait -= 1; return; }
|
|
756
|
+
const r = readRequests(home, offset, seen);
|
|
757
|
+
if (r.refused === true) {
|
|
758
|
+
seen = null;
|
|
759
|
+
if (!refusedSaid.has(r.why)) { refusedSaid.add(r.why); say(`the requests file could not be read (${r.why}); trying again`); }
|
|
760
|
+
refusedRun = r.size === refusedSize ? refusedRun + 1 : 1;
|
|
761
|
+
refusedSize = r.size;
|
|
762
|
+
refusedWait = refusedRetryPolls * Math.min(2 ** (refusedRun - 1), 10);
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
refusedRun = 0;
|
|
766
|
+
refusedSize = null;
|
|
767
|
+
// (a read that made no progress on a partial line isn't made again
|
|
768
|
+
// until the size changes; one that did forgets it, since the next
|
|
769
|
+
// request line is likely the same length -- A2. A refused read is not
|
|
770
|
+
// such a read: tried again above)
|
|
771
|
+
seen = r.offset === offset ? r.size : null;
|
|
772
|
+
if (r.offset === offset) return;
|
|
773
|
+
offset = r.offset;
|
|
774
|
+
upgrading = true;
|
|
775
|
+
// (a restart asked before the runtime last started is served by that
|
|
776
|
+
// start, which read what was stored then: never a second restart after
|
|
777
|
+
// "restarted" was said -- the reviewer's high on #147, R3. Judged as
|
|
778
|
+
// read, before the file is emptied)
|
|
779
|
+
const restartAsked = r.requests.some((q) => q.op === 'restart' && (r.replaced || !(q.end <= requestsAtStart)));
|
|
780
|
+
(async() => {
|
|
781
|
+
// every whole line read: the file is emptied under start.lock, which an
|
|
782
|
+
// appender takes too, so nothing written meanwhile is lost
|
|
783
|
+
await withLockFile(lockFile, runDir, io, async() => {
|
|
784
|
+
// (emptied: what follows was written after the runtime now running
|
|
785
|
+
// started, unless a start comes after it -- R3)
|
|
786
|
+
if (emptyRequests(home, offset)) { offset = 0; requestsAtStart = 0; }
|
|
787
|
+
return 0;
|
|
788
|
+
}, {wait: true, what: 'to finish reading its requests'});
|
|
789
|
+
// -> 'restarted' | 'handed over' | 'nothing'
|
|
790
|
+
// (a restart takes up what is installed first, so a changed ch-local
|
|
791
|
+
// is handed over to, as the stale line's "restart" promises -- the
|
|
792
|
+
// reviewer's high on #147, L1)
|
|
793
|
+
const upgradeAsked = r.requests.some((q) => q.op === 'upgrade');
|
|
794
|
+
const upgraded = upgradeAsked || restartAsked ? await takeUpInstalled(!upgradeAsked) : 'nothing';
|
|
795
|
+
// a credential stored or removed (ch-local credentials): the runtime
|
|
796
|
+
// takes the token only at its start, so it restarts, unless the
|
|
797
|
+
// upgrade just did (or handed over to a new daemon, which starts one)
|
|
798
|
+
if (restartAsked && upgraded === 'nothing' && !stopping) await restartRuntime('a restart was asked for (a stored credential changed, or the restart command)');
|
|
799
|
+
})().catch((e) => say(`the upgrade failed (${e.message})`)).finally(() => { upgrading = false; });
|
|
800
|
+
}, pollMs);
|
|
801
|
+
if (typeof poller.unref === 'function') poller.unref();
|
|
802
|
+
|
|
803
|
+
const failures = [];
|
|
804
|
+
for (;;) {
|
|
805
|
+
const watched = current;
|
|
806
|
+
const code = await watched.exited;
|
|
807
|
+
if (stopping) break;
|
|
808
|
+
// the upgrade already swapped in a successor: watch that one
|
|
809
|
+
if (replacing == null && current !== watched) continue;
|
|
810
|
+
// a runtime upgrade stopped it on purpose, and is starting its successor
|
|
811
|
+
if (replacing != null) { await replacing; if (stopping) break; continue; }
|
|
812
|
+
// start.lock from the unasked end until the restarted runtime is ready,
|
|
813
|
+
// or the daemon gives up: a shim that reattaches meanwhile, or the daemon
|
|
814
|
+
// it would spawn, waits on the lock and then finds this daemon, never a
|
|
815
|
+
// second one beside it, and never a failed.json written behind its back
|
|
816
|
+
const gaveUp = await withLockFile(lockFile, runDir, io, async() => {
|
|
817
|
+
// an upgrade may have swapped in a runtime while this waited on the
|
|
818
|
+
// lock: that one runs, and nothing is restarted over it
|
|
819
|
+
if (stopping || current !== watched) return null;
|
|
820
|
+
clearSocket();
|
|
821
|
+
// (daemon.json another daemon's, checked whatever the socket was: this
|
|
822
|
+
// daemon stops now, never saying "restarting" and sleeping a backoff
|
|
823
|
+
// with start.lock held -- the closing pass, L2)
|
|
824
|
+
if (stopping || theirsNow()) return null;
|
|
825
|
+
const now = Date.now();
|
|
826
|
+
while (failures.length > 0 && now - failures[0] > FAILURE_WINDOW_MS) failures.shift();
|
|
827
|
+
failures.push(now);
|
|
828
|
+
if (failures.length >= MAX_FAILURES) {
|
|
829
|
+
// (only while daemon.json is this daemon's: never turning shared mode
|
|
830
|
+
// off under another, healthy one -- the medium, 5)
|
|
831
|
+
if (!saidTheirs) writeFailed('restarts-exhausted', code);
|
|
832
|
+
removeMine();
|
|
833
|
+
return fail(`the shared runtime failed ${MAX_FAILURES} times in 10 minutes (last exit ${code}); the sessions run their own runtimes for now`);
|
|
834
|
+
}
|
|
835
|
+
const wait = backoff[Math.min(failures.length - 1, backoff.length - 1)];
|
|
836
|
+
say(`the shared runtime ended (exit ${code}); restarting${wait > 0 ? ` in ${wait / 1000} s` : ''}`);
|
|
837
|
+
if (wait > 0) await new Promise((r) => { wake = r; setTimeout(r, wait); });
|
|
838
|
+
wake = null;
|
|
839
|
+
if (stopping) return null;
|
|
840
|
+
current = startRuntime();
|
|
841
|
+
if (await current.ready()) {
|
|
842
|
+
writeVersion();
|
|
843
|
+
} else {
|
|
844
|
+
if (current.ended == null) await current.abandon();
|
|
845
|
+
if (!stopping) say('the restarted runtime did not listen');
|
|
846
|
+
}
|
|
847
|
+
return null;
|
|
848
|
+
}, {wait: true, what: 'to finish restarting the shared runtime'});
|
|
849
|
+
// (given up: an upgrade waiting on its drain restarts nothing and hands
|
|
850
|
+
// nothing over -- stopping, as any stop)
|
|
851
|
+
if (gaveUp != null) { loopDone = true; stopping = true; clearTimeout(idleTimer); clearInterval(poller); return gaveUp; }
|
|
852
|
+
if (stopping) break;
|
|
853
|
+
}
|
|
854
|
+
loopDone = true;
|
|
855
|
+
clearTimeout(idleTimer);
|
|
856
|
+
clearInterval(poller);
|
|
857
|
+
// an upgrade's handover in progress: it finishes, then this daemon goes
|
|
858
|
+
while (upgrading) await new Promise((r) => setTimeout(r, 50));
|
|
859
|
+
// stopped: daemon.json goes if it is still this daemon's (the idle stop
|
|
860
|
+
// and the handover have removed it already), under start.lock
|
|
861
|
+
await withLockFile(lockFile, runDir, io, async() => { removeMine(); return 0; }, {wait: true, what: 'to finish stopping the shared runtime'});
|
|
862
|
+
return exitCode;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// Whether a daemon may be serving this home now, for uninstall (A9), under
|
|
866
|
+
// start.lock. Failing closed: the socket daemon.json names proves the
|
|
867
|
+
// secret, OR daemon.json's pid is alive -- a daemon draining for an upgrade,
|
|
868
|
+
// or between a crash and its restart, answers no handshake but lives (the
|
|
869
|
+
// medium on A9's round, 1). A live pid only ever adds a refusal; it never
|
|
870
|
+
// permits a removal, so a reused one costs a refusal (with the way out),
|
|
871
|
+
// never a home. Only a daemon.json whose pid is gone is stale: no clock is
|
|
872
|
+
// read, since a clock stepped after boot would call a live daemon stale
|
|
873
|
+
// (the final medium on A9, 1).
|
|
874
|
+
// ({platform, probePipe, alive}) -> Promise<{serving, pid}>
|
|
875
|
+
async function daemonServing(home, {platform = process.platform, probePipe = null, alive = pidAlive} = {}) {
|
|
876
|
+
const runDir = path.join(home, 'run', 'daemon');
|
|
877
|
+
if (!fs.existsSync(path.join(runDir, 'daemon.json'))) return {serving: false, pid: null};
|
|
878
|
+
const recorded = readDaemonJson(runDir);
|
|
879
|
+
// (there but not readable: a check that can't be made, said as such)
|
|
880
|
+
if (recorded == null) return {serving: true, pid: null, by: 'unreadable'};
|
|
881
|
+
const pid = Number.isSafeInteger(recorded.pid) && recorded.pid > 0 ? recorded.pid : null;
|
|
882
|
+
const secret = readSecret(runDir);
|
|
883
|
+
if (secret != null && typeof recorded.socket === 'string' && await probeRecorded(recorded.socket, secret, {platform, probePipe})) return {serving: true, pid, by: 'socket'};
|
|
884
|
+
return pid != null && alive(pid) ? {serving: true, pid, by: 'pid'} : {serving: false, pid};
|
|
885
|
+
}
|
|
886
|
+
const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
887
|
+
|
|
888
|
+
module.exports = {daemon, probe, daemonServing, readDaemonJson, ensureRunDir, encodeHandoff, decodeHandoff, drainBoundMs, firstReadyMs, SESSION_WINDOW_MS, READY_MS, COLD_READY_MS, SOCKET, BACKOFF_MS, STOP_MS, GRACE_MS};
|