@overcy/hive 0.0.0-stage → 0.2.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/README.md +213 -2
- package/dist/api.d.ts +31 -0
- package/dist/api.js +83 -0
- package/dist/atomic.d.ts +1 -0
- package/dist/atomic.js +24 -0
- package/dist/binding.d.ts +5 -0
- package/dist/binding.js +16 -0
- package/dist/bootstrap/deps.d.ts +3 -0
- package/dist/bootstrap/deps.js +35 -0
- package/dist/bootstrap/doctor.d.ts +29 -0
- package/dist/bootstrap/doctor.js +80 -0
- package/dist/bootstrap/engine.d.ts +29 -0
- package/dist/bootstrap/engine.js +160 -0
- package/dist/bootstrap/forwarder.d.ts +11 -0
- package/dist/bootstrap/forwarder.js +30 -0
- package/dist/bootstrap/identity.d.ts +7 -0
- package/dist/bootstrap/identity.js +52 -0
- package/dist/bootstrap/index.d.ts +36 -0
- package/dist/bootstrap/index.js +40 -0
- package/dist/bootstrap/kit.d.ts +9 -0
- package/dist/bootstrap/kit.js +56 -0
- package/dist/bootstrap/manifest.d.ts +73 -0
- package/dist/bootstrap/manifest.js +309 -0
- package/dist/bootstrap/model-access.d.ts +43 -0
- package/dist/bootstrap/model-access.js +74 -0
- package/dist/bootstrap/pin.d.ts +2 -0
- package/dist/bootstrap/pin.js +16 -0
- package/dist/bootstrap/plan.d.ts +49 -0
- package/dist/bootstrap/plan.js +69 -0
- package/dist/bootstrap/prompt.d.ts +3 -0
- package/dist/bootstrap/prompt.js +35 -0
- package/dist/bootstrap/registry.d.ts +85 -0
- package/dist/bootstrap/registry.js +38 -0
- package/dist/bootstrap/secrets.d.ts +11 -0
- package/dist/bootstrap/secrets.js +105 -0
- package/dist/bootstrap/steps/agents.d.ts +9 -0
- package/dist/bootstrap/steps/agents.js +75 -0
- package/dist/bootstrap/steps/auth.d.ts +8 -0
- package/dist/bootstrap/steps/auth.js +138 -0
- package/dist/bootstrap/steps/cron.d.ts +7 -0
- package/dist/bootstrap/steps/cron.js +74 -0
- package/dist/bootstrap/steps/drift.d.ts +5 -0
- package/dist/bootstrap/steps/drift.js +67 -0
- package/dist/bootstrap/steps/env.d.ts +6 -0
- package/dist/bootstrap/steps/env.js +108 -0
- package/dist/bootstrap/steps/files.d.ts +7 -0
- package/dist/bootstrap/steps/files.js +28 -0
- package/dist/bootstrap/steps/lanes.d.ts +14 -0
- package/dist/bootstrap/steps/lanes.js +153 -0
- package/dist/bootstrap/steps/model-access.d.ts +10 -0
- package/dist/bootstrap/steps/model-access.js +122 -0
- package/dist/bootstrap/steps/preflight.d.ts +3 -0
- package/dist/bootstrap/steps/preflight.js +49 -0
- package/dist/bootstrap/steps/reporter.d.ts +12 -0
- package/dist/bootstrap/steps/reporter.js +155 -0
- package/dist/bootstrap/system.d.ts +5 -0
- package/dist/bootstrap/system.js +69 -0
- package/dist/bootstrap/types.d.ts +157 -0
- package/dist/bootstrap/types.js +14 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +23 -0
- package/dist/collect.d.ts +28 -0
- package/dist/collect.js +63 -0
- package/dist/commands/connect.d.ts +33 -0
- package/dist/commands/connect.js +306 -0
- package/dist/commands/doctor.d.ts +7 -0
- package/dist/commands/doctor.js +13 -0
- package/dist/commands/login.d.ts +3 -0
- package/dist/commands/login.js +118 -0
- package/dist/commands/logout.d.ts +2 -0
- package/dist/commands/logout.js +37 -0
- package/dist/commands/node-add.d.ts +7 -0
- package/dist/commands/node-add.js +56 -0
- package/dist/commands/node.d.ts +19 -0
- package/dist/commands/node.js +43 -0
- package/dist/commands/prEvents.d.ts +7 -0
- package/dist/commands/prEvents.js +32 -0
- package/dist/commands/setup.d.ts +15 -0
- package/dist/commands/setup.js +35 -0
- package/dist/commands/status.d.ts +18 -0
- package/dist/commands/status.js +71 -0
- package/dist/commands/threads.d.ts +6 -0
- package/dist/commands/threads.js +36 -0
- package/dist/config.d.ts +71 -0
- package/dist/config.js +121 -0
- package/dist/context.d.ts +26 -0
- package/dist/context.js +31 -0
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +50 -0
- package/dist/machine.d.ts +66 -0
- package/dist/machine.js +103 -0
- package/dist/node/cli.d.ts +25 -0
- package/dist/node/cli.js +130 -0
- package/dist/node/engine.d.ts +47 -0
- package/dist/node/engine.js +463 -0
- package/dist/node/ingress.d.ts +102 -0
- package/dist/node/ingress.js +473 -0
- package/dist/node/layout.d.ts +56 -0
- package/dist/node/layout.js +55 -0
- package/dist/node/leave.d.ts +8 -0
- package/dist/node/leave.js +32 -0
- package/dist/node/lock.d.ts +19 -0
- package/dist/node/lock.js +99 -0
- package/dist/node/modelAccess.d.ts +2 -0
- package/dist/node/modelAccess.js +44 -0
- package/dist/node/repair.d.ts +28 -0
- package/dist/node/repair.js +78 -0
- package/dist/node/services.d.ts +58 -0
- package/dist/node/services.js +171 -0
- package/dist/node/state.d.ts +127 -0
- package/dist/node/state.js +95 -0
- package/dist/node/steps.d.ts +74 -0
- package/dist/node/steps.js +158 -0
- package/dist/node/supervisor.d.ts +22 -0
- package/dist/node/supervisor.js +95 -0
- package/dist/node/tick.d.ts +47 -0
- package/dist/node/tick.js +278 -0
- package/dist/node/toolchain.d.ts +50 -0
- package/dist/node/toolchain.js +230 -0
- package/dist/nodeContract.d.ts +101 -0
- package/dist/nodeContract.js +192 -0
- package/dist/package.d.ts +3 -0
- package/dist/package.js +5 -0
- package/dist/prEvents.d.ts +109 -0
- package/dist/prEvents.js +374 -0
- package/dist/run.d.ts +19 -0
- package/dist/run.js +487 -0
- package/dist/specs/device-client.json +920 -0
- package/dist/threads.d.ts +88 -0
- package/dist/threads.js +268 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +35 -4
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Desired } from '../nodeContract.ts';
|
|
2
|
+
import { type SupervisorState } from './state.ts';
|
|
3
|
+
import type { NodeStep } from './steps.ts';
|
|
4
|
+
/**
|
|
5
|
+
* The `cli` step: upgrades the supervisor itself. It lays the release Hive pins into `cli/<version>/`, with the
|
|
6
|
+
* manifest Hive signed in `.release/`, checks it with install.sh's `release-verify` as the keeper does, points
|
|
7
|
+
* `previous` at the running release and `current` at the new one. The supervisor then exits 75 and the keeper starts
|
|
8
|
+
* the new release. If that crashes three times within two minutes, the keeper flips `current` back, and the next
|
|
9
|
+
* supervisor records the version as rolled back, so it is not tried again until Hive pins another one or asks for a
|
|
10
|
+
* rerun of setup.
|
|
11
|
+
*/
|
|
12
|
+
export declare const CLI_ARTIFACT = "hive-cli";
|
|
13
|
+
/** A swapped-in release that has run this long is past the keeper's two minute crash window, with room to spare. */
|
|
14
|
+
export declare const SWAP_SETTLE_MS: number;
|
|
15
|
+
export declare function cliTarget(desired: Desired | null): {
|
|
16
|
+
version: string;
|
|
17
|
+
route: string;
|
|
18
|
+
} | null;
|
|
19
|
+
/**
|
|
20
|
+
* Reads what happened to the last swap from the release the supervisor runs now. Called once at the start of a tick.
|
|
21
|
+
* Back on the release it swapped from means the keeper rolled the new one back. A rejection for a version Hive no
|
|
22
|
+
* longer pins is dropped.
|
|
23
|
+
*/
|
|
24
|
+
export declare function settleCliSwap(state: SupervisorState, running: string | null, desired: Desired | null, now: Date): void;
|
|
25
|
+
export declare const cliStep: NodeStep;
|
package/dist/node/cli.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { copyFile, mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { download, linkTarget, requestArtifact, switchLink } from "./services.js";
|
|
4
|
+
import { writeState } from "./state.js";
|
|
5
|
+
/**
|
|
6
|
+
* The `cli` step: upgrades the supervisor itself. It lays the release Hive pins into `cli/<version>/`, with the
|
|
7
|
+
* manifest Hive signed in `.release/`, checks it with install.sh's `release-verify` as the keeper does, points
|
|
8
|
+
* `previous` at the running release and `current` at the new one. The supervisor then exits 75 and the keeper starts
|
|
9
|
+
* the new release. If that crashes three times within two minutes, the keeper flips `current` back, and the next
|
|
10
|
+
* supervisor records the version as rolled back, so it is not tried again until Hive pins another one or asks for a
|
|
11
|
+
* rerun of setup.
|
|
12
|
+
*/
|
|
13
|
+
export const CLI_ARTIFACT = 'hive-cli';
|
|
14
|
+
/** A swapped-in release that has run this long is past the keeper's two minute crash window, with room to spare. */
|
|
15
|
+
export const SWAP_SETTLE_MS = 5 * 60_000;
|
|
16
|
+
const RELEASE_NAME = /^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/;
|
|
17
|
+
export function cliTarget(desired) {
|
|
18
|
+
const version = desired?.versions?.cli;
|
|
19
|
+
if (version === undefined)
|
|
20
|
+
return null;
|
|
21
|
+
return { version, route: desired?.versions?.channel === 'dev' ? 'dev' : version };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reads what happened to the last swap from the release the supervisor runs now. Called once at the start of a tick.
|
|
25
|
+
* Back on the release it swapped from means the keeper rolled the new one back. A rejection for a version Hive no
|
|
26
|
+
* longer pins is dropped.
|
|
27
|
+
*/
|
|
28
|
+
export function settleCliSwap(state, running, desired, now) {
|
|
29
|
+
const memory = state.cli;
|
|
30
|
+
const swap = memory.swap;
|
|
31
|
+
if (swap !== null) {
|
|
32
|
+
if (running === swap.to) {
|
|
33
|
+
if (now.getTime() - Date.parse(swap.at) >= SWAP_SETTLE_MS)
|
|
34
|
+
memory.swap = null;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
if (running !== null && running === swap.from) {
|
|
38
|
+
memory.rejected = {
|
|
39
|
+
version: swap.to,
|
|
40
|
+
at: now.toISOString(),
|
|
41
|
+
detail: `CLI ${swap.to} was rolled back to ${swap.from}: the keeper flipped cli/current back because it crashed or failed its check within two minutes of the swap. Pin another version in Hive, or re-run setup to try ${swap.to} again.`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
memory.swap = null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const target = cliTarget(desired);
|
|
48
|
+
if (memory.rejected !== null && target?.version !== memory.rejected.version)
|
|
49
|
+
memory.rejected = null;
|
|
50
|
+
}
|
|
51
|
+
async function observeCli(run) {
|
|
52
|
+
const running = await linkTarget(run.layout.cliCurrent);
|
|
53
|
+
const target = cliTarget(run.desired);
|
|
54
|
+
if (target === null)
|
|
55
|
+
return { status: 'ok', detail: `${running ?? 'no release'} runs. Hive has not pinned a CLI version` };
|
|
56
|
+
const rejected = run.state.cli.rejected;
|
|
57
|
+
if (rejected !== null && rejected.version === target.version)
|
|
58
|
+
return { status: 'needs_action', detail: rejected.detail, fix: 'hive_button' };
|
|
59
|
+
if (running === target.version)
|
|
60
|
+
return { status: 'ok', detail: `${running} runs, the version Hive pinned` };
|
|
61
|
+
return { status: 'stale', detail: `${running ?? 'no release'} runs, Hive pinned ${target.version}` };
|
|
62
|
+
}
|
|
63
|
+
/** Removes every release but the two the links name. The running supervisor's own release is one of them. */
|
|
64
|
+
async function pruneReleases(run, keep) {
|
|
65
|
+
for (const name of await readdir(run.layout.cliDir)) {
|
|
66
|
+
if (name.startsWith('.') || name === 'current' || name === 'previous' || keep.includes(name))
|
|
67
|
+
continue;
|
|
68
|
+
await rm(join(run.layout.cliDir, name), { recursive: true, force: true });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function repairCli(run) {
|
|
72
|
+
const target = cliTarget(run.desired);
|
|
73
|
+
if (target === null)
|
|
74
|
+
return;
|
|
75
|
+
const running = await linkTarget(run.layout.cliCurrent);
|
|
76
|
+
if (running === target.version)
|
|
77
|
+
return;
|
|
78
|
+
const rejected = run.state.cli.rejected;
|
|
79
|
+
if (rejected !== null) {
|
|
80
|
+
if (rejected.version === target.version)
|
|
81
|
+
return;
|
|
82
|
+
run.state.cli.rejected = null;
|
|
83
|
+
}
|
|
84
|
+
if (!RELEASE_NAME.test(target.version))
|
|
85
|
+
throw new Error(`${target.version} is not a release name.`);
|
|
86
|
+
const answer = await requestArtifact(run, CLI_ARTIFACT, target.route);
|
|
87
|
+
if (answer.manifest === undefined || answer.key_id === undefined)
|
|
88
|
+
throw new Error(`Hive's answer for CLI ${target.version} has no release manifest.`);
|
|
89
|
+
if (answer.version !== target.version) {
|
|
90
|
+
throw new Error(`Hive serves CLI ${answer.version ?? 'of no version'} for ${target.route}, and desired state pins ${target.version}. Pin the version Hive serves.`);
|
|
91
|
+
}
|
|
92
|
+
const dir = run.layout.cliDir;
|
|
93
|
+
const stage = join(dir, `${target.version}.new`);
|
|
94
|
+
const fetched = await download(run, answer.url, CLI_ARTIFACT, dir);
|
|
95
|
+
try {
|
|
96
|
+
await rm(stage, { recursive: true, force: true });
|
|
97
|
+
await mkdir(join(stage, '.release'), { recursive: true });
|
|
98
|
+
// The same unpack install.sh does, so release-verify compares the same files.
|
|
99
|
+
const unpacked = await run.exec('tar', ['-xzf', fetched.file, '-C', stage, '--strip-components=1', '--no-same-owner', '--no-same-permissions']);
|
|
100
|
+
if (unpacked.code !== 0)
|
|
101
|
+
throw new Error(`CLI ${target.version} did not unpack: ${unpacked.stderr.trim().slice(-300)}`);
|
|
102
|
+
await writeFile(join(stage, '.release', 'manifest'), answer.manifest);
|
|
103
|
+
await writeFile(join(stage, '.release', 'key_id'), `${answer.key_id}\n`);
|
|
104
|
+
await writeFile(join(stage, '.release', 'signature'), `${answer.signature ?? ''}\n`);
|
|
105
|
+
await copyFile(fetched.file, join(stage, '.release', 'archive.tar.gz'));
|
|
106
|
+
const verified = await run.exec(run.layout.releaseVerify, [stage]);
|
|
107
|
+
if (verified.code !== 0)
|
|
108
|
+
throw new Error(`CLI ${target.version} did not verify: ${(verified.stderr || verified.stdout).trim().slice(-300)}`);
|
|
109
|
+
await rm(join(dir, target.version), { recursive: true, force: true });
|
|
110
|
+
await rename(stage, join(dir, target.version));
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await rm(stage, { recursive: true, force: true });
|
|
114
|
+
await rm(fetched.file, { force: true });
|
|
115
|
+
}
|
|
116
|
+
// The record goes to disk before the link moves, so a supervisor that starts on the old release again can tell.
|
|
117
|
+
run.state.cli.swap = { from: running, to: target.version, at: run.ctx.now().toISOString() };
|
|
118
|
+
await writeState(run.layout, run.state);
|
|
119
|
+
if (running !== null)
|
|
120
|
+
await switchLink(run.layout.cliPrevious, running);
|
|
121
|
+
await switchLink(run.layout.cliCurrent, target.version);
|
|
122
|
+
await pruneReleases(run, [running, target.version]);
|
|
123
|
+
run.ctx.io.out(`Swapped the CLI from ${running ?? 'nothing'} to ${target.version}. The keeper starts it next.`);
|
|
124
|
+
}
|
|
125
|
+
export const cliStep = {
|
|
126
|
+
id: 'cli',
|
|
127
|
+
needs: ['identity', 'desired'],
|
|
128
|
+
observe: observeCli,
|
|
129
|
+
repair: repairCli,
|
|
130
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Desired } from '../nodeContract.ts';
|
|
2
|
+
import type { NodeStep, TickRun } from './steps.ts';
|
|
3
|
+
/** The engine is OvercyCode, run as `t3 serve` by the init adapter as user `hive`. This file is the `engine` step. */
|
|
4
|
+
export declare const ENGINE_ARTIFACT = "overcycode";
|
|
5
|
+
export declare const DEFAULT_ENGINE_PORT = 3773;
|
|
6
|
+
/** After a restart the engine gets this long to answer before the step calls it broken. It starts in about a second. */
|
|
7
|
+
export declare const START_GRACE_MS = 90000;
|
|
8
|
+
/** A broken engine is restarted at most this often. Its unit already restarts a crashed process every two seconds. */
|
|
9
|
+
export declare const RESTART_PACE_MS: number;
|
|
10
|
+
export declare const KEEP_BACKUPS = 3;
|
|
11
|
+
/** After an upgrade the new engine must answer with its version within this long, or the step rolls it back. */
|
|
12
|
+
export declare const UPGRADE_HEALTH_MS = 60000;
|
|
13
|
+
export type EngineHealth = {
|
|
14
|
+
up: boolean;
|
|
15
|
+
version: string | null;
|
|
16
|
+
};
|
|
17
|
+
export type ModelKey = {
|
|
18
|
+
method: 'byok';
|
|
19
|
+
name: string;
|
|
20
|
+
version: number;
|
|
21
|
+
value: string;
|
|
22
|
+
};
|
|
23
|
+
export declare function enginePort(env: NodeJS.ProcessEnv): number;
|
|
24
|
+
/** The version to run and the version segment of the artifacts route: `dev` on the dev channel, else the version. */
|
|
25
|
+
export declare function engineTarget(desired: Desired | null): {
|
|
26
|
+
version: string;
|
|
27
|
+
route: string;
|
|
28
|
+
} | null;
|
|
29
|
+
export declare function readModelKey(run: TickRun): Promise<ModelKey | null>;
|
|
30
|
+
/**
|
|
31
|
+
* The one definition of `service.env`. install.sh's `engine-run` sources it with `set -a`, so every line is
|
|
32
|
+
* `KEY='value'`. The order is fixed and nothing in it changes by itself, so the same desired state always gives the
|
|
33
|
+
* same bytes and a rewrite never restarts the engine for nothing.
|
|
34
|
+
*
|
|
35
|
+
* The Hive node id is `nodes.id` from `GET /nodes/me`, never the connection id in `node.json`: HiveCode tokens carry
|
|
36
|
+
* `nodes.id`, and the wrong one makes every ticket a 401. `T3CODE_HIVE_URL` is the bare origin, because HiveCodeAuth
|
|
37
|
+
* compares it with the browser's Origin exactly.
|
|
38
|
+
*/
|
|
39
|
+
export declare function wantedServiceEnv(run: TickRun): Promise<string | null>;
|
|
40
|
+
/** Probes the engine on loopback, once per tick unless a restart clears it. The environment route needs no auth and names the running version. */
|
|
41
|
+
export declare function engineHealth(run: TickRun): Promise<EngineHealth>;
|
|
42
|
+
/**
|
|
43
|
+
* Writes `service.env` and restarts the engine when its content moved past what the engine last started with, or when
|
|
44
|
+
* `force` says so. The engine and model-access steps both end here. Returns whether it restarted.
|
|
45
|
+
*/
|
|
46
|
+
export declare function applyEngineEnv(run: TickRun, force?: boolean): Promise<boolean>;
|
|
47
|
+
export declare const engineStep: NodeStep;
|
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { constants, createReadStream, createWriteStream } from 'node:fs';
|
|
2
|
+
import { chmod, lstat, mkdir, open, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { fetchArtifact, isExecutable, linkTarget, readText, serviceControl, sha256, shQuote, switchLink, unpack, writeIfChanged } from "./services.js";
|
|
6
|
+
/** The engine is OvercyCode, run as `t3 serve` by the init adapter as user `hive`. This file is the `engine` step. */
|
|
7
|
+
export const ENGINE_ARTIFACT = 'overcycode';
|
|
8
|
+
export const DEFAULT_ENGINE_PORT = 3773;
|
|
9
|
+
/** After a restart the engine gets this long to answer before the step calls it broken. It starts in about a second. */
|
|
10
|
+
export const START_GRACE_MS = 90_000;
|
|
11
|
+
/** A broken engine is restarted at most this often. Its unit already restarts a crashed process every two seconds. */
|
|
12
|
+
export const RESTART_PACE_MS = 3 * 60_000;
|
|
13
|
+
export const KEEP_BACKUPS = 3;
|
|
14
|
+
/** After an upgrade the new engine must answer with its version within this long, or the step rolls it back. */
|
|
15
|
+
export const UPGRADE_HEALTH_MS = 60_000;
|
|
16
|
+
const DB_FILES = ['', '-wal', '-shm'];
|
|
17
|
+
export function enginePort(env) {
|
|
18
|
+
const port = Number(env.HIVE_ENGINE_PORT);
|
|
19
|
+
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_ENGINE_PORT;
|
|
20
|
+
}
|
|
21
|
+
/** The version to run and the version segment of the artifacts route: `dev` on the dev channel, else the version. */
|
|
22
|
+
export function engineTarget(desired) {
|
|
23
|
+
const version = desired?.versions?.engine;
|
|
24
|
+
if (version === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
return { version, route: desired?.versions?.channel === 'dev' ? 'dev' : version };
|
|
27
|
+
}
|
|
28
|
+
const releases = (run) => join(run.layout.binDir, 'releases', ENGINE_ARTIFACT);
|
|
29
|
+
const versionDir = (run, version) => join(releases(run), version);
|
|
30
|
+
const linkFor = (version) => join('releases', ENGINE_ARTIFACT, version, 't3');
|
|
31
|
+
const engineLink = (run) => join(run.layout.binDir, 't3');
|
|
32
|
+
const database = (run) => join(run.layout.engineHome, 'userdata', 'statev2.sqlite');
|
|
33
|
+
export async function readModelKey(run) {
|
|
34
|
+
const text = await readText(run.layout.modelKey);
|
|
35
|
+
if (text === null)
|
|
36
|
+
return null;
|
|
37
|
+
try {
|
|
38
|
+
const parsed = JSON.parse(text);
|
|
39
|
+
return parsed.method === 'byok' && typeof parsed.value === 'string' && typeof parsed.name === 'string' && Number.isInteger(parsed.version) ? parsed : null;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The one definition of `service.env`. install.sh's `engine-run` sources it with `set -a`, so every line is
|
|
47
|
+
* `KEY='value'`. The order is fixed and nothing in it changes by itself, so the same desired state always gives the
|
|
48
|
+
* same bytes and a rewrite never restarts the engine for nothing.
|
|
49
|
+
*
|
|
50
|
+
* The Hive node id is `nodes.id` from `GET /nodes/me`, never the connection id in `node.json`: HiveCode tokens carry
|
|
51
|
+
* `nodes.id`, and the wrong one makes every ticket a 401. `T3CODE_HIVE_URL` is the bare origin, because HiveCodeAuth
|
|
52
|
+
* compares it with the browser's Origin exactly.
|
|
53
|
+
*/
|
|
54
|
+
export async function wantedServiceEnv(run) {
|
|
55
|
+
if (run.state.hive_node_id === null)
|
|
56
|
+
return null;
|
|
57
|
+
const lib = dirname(run.layout.servicectl);
|
|
58
|
+
const lines = [
|
|
59
|
+
['T3CODE_HIVE_URL', new URL(run.ctx.url).origin],
|
|
60
|
+
['T3CODE_HIVE_TEAM_ID', String(run.node.team.id)],
|
|
61
|
+
['T3CODE_HIVE_NODE_ID', String(run.state.hive_node_id)],
|
|
62
|
+
['T3CODE_HOST', '127.0.0.1'],
|
|
63
|
+
['T3CODE_PORT', String(enginePort(run.ctx.env))],
|
|
64
|
+
['T3CODE_MANAGED_BY', 'hive'],
|
|
65
|
+
// The foreground keeper starts the engine with a bare PATH. Agents the engine spawns find the tools the toolchain
|
|
66
|
+
// step installed first, then the node's Node and the system directories.
|
|
67
|
+
['PATH', `${run.layout.toolsDir}:${lib}/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`],
|
|
68
|
+
// The toolchain step is the only writer of the claude version. hive cannot write bin/ anyway.
|
|
69
|
+
['DISABLE_AUTOUPDATER', '1'],
|
|
70
|
+
];
|
|
71
|
+
const ca = run.ctx.env.NODE_EXTRA_CA_CERTS;
|
|
72
|
+
if (ca !== undefined && ca !== '')
|
|
73
|
+
lines.push(['NODE_EXTRA_CA_CERTS', ca]);
|
|
74
|
+
const key = run.desired?.model_access?.method === 'byok' ? await readModelKey(run) : null;
|
|
75
|
+
if (key !== null)
|
|
76
|
+
lines.push(['ANTHROPIC_API_KEY', key.value]);
|
|
77
|
+
return `# Written by hive node run. It is rewritten within a minute of any change.\n${lines.map(([name, value]) => `${name}=${shQuote(value)}`).join('\n')}\n`;
|
|
78
|
+
}
|
|
79
|
+
/** Probes the engine on loopback, once per tick unless a restart clears it. The environment route needs no auth and names the running version. */
|
|
80
|
+
export function engineHealth(run) {
|
|
81
|
+
run.cache.engine ??= (async () => {
|
|
82
|
+
try {
|
|
83
|
+
const response = await fetch(`http://127.0.0.1:${enginePort(run.ctx.env)}/.well-known/t3/environment`, { signal: AbortSignal.any([run.signal, AbortSignal.timeout(2_000)]) });
|
|
84
|
+
if (!response.ok)
|
|
85
|
+
return { up: false, version: null };
|
|
86
|
+
const body = (await response.json());
|
|
87
|
+
return { up: true, version: typeof body.serverVersion === 'string' ? body.serverVersion : null };
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return { up: false, version: null };
|
|
91
|
+
}
|
|
92
|
+
})();
|
|
93
|
+
return run.cache.engine;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Tools that appeared or changed version since the engine last started. OvercyCode checks for claude and codex only
|
|
97
|
+
* at startup (spike finding 7), so a tool installed later stays "Not found" until a restart. A tool the probe could
|
|
98
|
+
* not read is left out, so a failed `--version` never restarts a healthy engine.
|
|
99
|
+
*/
|
|
100
|
+
const probedTools = (run) => Object.keys(run.versions).filter((tool) => tool !== 'engine');
|
|
101
|
+
function newTools(run) {
|
|
102
|
+
const versions = run.versions;
|
|
103
|
+
return probedTools(run).filter((tool) => versions[tool] !== run.state.engine.tools[tool]).map((tool) => `${tool} ${versions[tool]}`);
|
|
104
|
+
}
|
|
105
|
+
const since = (run, at) => (at === null ? Infinity : run.ctx.now().getTime() - Date.parse(at));
|
|
106
|
+
const paused = (run) => run.desired?.paused === true;
|
|
107
|
+
const wantedRestarts = (run) => run.desired?.actions?.restart_engine ?? 0;
|
|
108
|
+
async function linkPointsAt(run, version) {
|
|
109
|
+
return (await linkTarget(engineLink(run))) === linkFor(version) && (await isExecutable(engineLink(run)));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The database the engine and the relay share must be group-writable. SQLite gives `-wal` and `-shm` the main file's
|
|
113
|
+
* mode, so a 0640 database lets whichever user opens it first lock the other out (spike 2b). The supervisor creates
|
|
114
|
+
* the file empty at 0660 before the first start. It cannot fix a file another user owns, so that is a person's job.
|
|
115
|
+
*/
|
|
116
|
+
async function databaseProblem(run) {
|
|
117
|
+
try {
|
|
118
|
+
const info = await stat(database(run));
|
|
119
|
+
if ((info.mode & 0o060) === 0o060)
|
|
120
|
+
return null;
|
|
121
|
+
return `${database(run)} is mode 0${(info.mode & 0o777).toString(8)}, so the relay can lock the engine out of it. Run: sudo chmod 0660 ${database(run)}*`;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function ensureDatabase(run) {
|
|
128
|
+
const file = database(run);
|
|
129
|
+
try {
|
|
130
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o770 });
|
|
131
|
+
await writeFile(file, '', { mode: 0o660, flag: 'wx' });
|
|
132
|
+
await chmod(file, 0o660);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (error.code !== 'EEXIST')
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function observeEngine(run) {
|
|
140
|
+
const target = engineTarget(run.desired);
|
|
141
|
+
if (target === null)
|
|
142
|
+
return { status: 'needs_action', detail: 'Hive has not pinned an OvercyCode version for this node yet', fix: 'hive_button' };
|
|
143
|
+
const memory = run.state.engine;
|
|
144
|
+
if (memory.rejected !== null && memory.rejected.version === target.version)
|
|
145
|
+
return { status: 'needs_action', detail: memory.rejected.detail, fix: 'hive_button' };
|
|
146
|
+
if (memory.upgrade !== null)
|
|
147
|
+
return { status: 'stale', detail: `the upgrade from OvercyCode ${memory.upgrade.from} to ${memory.upgrade.to} waits for the new engine to answer` };
|
|
148
|
+
if (paused(run))
|
|
149
|
+
return memory.stopped ? { status: 'ok', detail: 'Hive paused this node, so the engine is stopped' } : { status: 'stale', detail: 'Hive paused this node and the engine still runs' };
|
|
150
|
+
const wanted = await wantedServiceEnv(run);
|
|
151
|
+
if (wanted === null)
|
|
152
|
+
return { status: 'failing', detail: 'the Hive node id is not known yet', fix: 'rerun_install' };
|
|
153
|
+
// Broken is damage to what was installed: a missing binary or service.env. Stale is a change Hive asked for.
|
|
154
|
+
const broken = [];
|
|
155
|
+
const stale = [];
|
|
156
|
+
const installed = memory.version !== null;
|
|
157
|
+
if (memory.version !== target.version)
|
|
158
|
+
stale.push(installed ? `OvercyCode ${memory.version} is installed, Hive pinned ${target.version}` : `OvercyCode ${target.version} is not installed`);
|
|
159
|
+
else if (!(await linkPointsAt(run, target.version)))
|
|
160
|
+
broken.push(`${engineLink(run)} does not point at OvercyCode ${target.version}`);
|
|
161
|
+
const current = await readText(run.layout.serviceEnv);
|
|
162
|
+
if (current === null)
|
|
163
|
+
(installed ? broken : stale).push('service.env is missing');
|
|
164
|
+
else if (current !== wanted)
|
|
165
|
+
stale.push('service.env differs from what Hive wants');
|
|
166
|
+
else if (memory.env_hash !== sha256(wanted))
|
|
167
|
+
stale.push('the engine has not restarted since service.env changed');
|
|
168
|
+
if (memory.stopped)
|
|
169
|
+
stale.push('the engine is stopped since the node was paused');
|
|
170
|
+
if (wantedRestarts(run) > run.state.generations.restart_engine)
|
|
171
|
+
stale.push('Hive asked for a restart');
|
|
172
|
+
const tools = newTools(run);
|
|
173
|
+
if (installed && memory.env_hash !== null && tools.length > 0)
|
|
174
|
+
stale.push(`${tools.join(', ')} appeared since the engine started`);
|
|
175
|
+
if (broken.length > 0)
|
|
176
|
+
return { status: 'failing', detail: [...broken, ...stale].join('; '), fix: 'rerun_install' };
|
|
177
|
+
if (stale.length > 0)
|
|
178
|
+
return { status: 'stale', detail: stale.join('; ') };
|
|
179
|
+
const problem = await databaseProblem(run);
|
|
180
|
+
if (problem !== null)
|
|
181
|
+
return { status: 'needs_action', detail: problem, fix: 'human' };
|
|
182
|
+
const port = enginePort(run.ctx.env);
|
|
183
|
+
const health = await engineHealth(run);
|
|
184
|
+
const starting = since(run, memory.restarted_at) < START_GRACE_MS;
|
|
185
|
+
if (!health.up)
|
|
186
|
+
return starting ? { status: 'ok', detail: `OvercyCode ${target.version} is starting on 127.0.0.1:${port}` } : { status: 'failing', detail: `OvercyCode does not answer on 127.0.0.1:${port}`, fix: 'rerun_install' };
|
|
187
|
+
if (health.version !== null && health.version !== target.version) {
|
|
188
|
+
return starting ? { status: 'ok', detail: `OvercyCode ${target.version} is starting, ${health.version} still answers` } : { status: 'failing', detail: `OvercyCode ${health.version} answers on 127.0.0.1:${port}, ${target.version} is installed`, fix: 'rerun_install' };
|
|
189
|
+
}
|
|
190
|
+
return { status: 'ok', detail: `OvercyCode ${target.version} on 127.0.0.1:${port}` };
|
|
191
|
+
}
|
|
192
|
+
async function stopAndWait(run) {
|
|
193
|
+
await serviceControl(run, 'stop', 'engine');
|
|
194
|
+
// systemd stops synchronously. The foreground keeper only signals, so wait until the port closes.
|
|
195
|
+
for (let tries = 0; tries < 30; tries++) {
|
|
196
|
+
run.cache.engine = undefined;
|
|
197
|
+
if (!(await engineHealth(run)).up)
|
|
198
|
+
return;
|
|
199
|
+
await run.ctx.sleep(500, run.signal);
|
|
200
|
+
}
|
|
201
|
+
throw new Error('the engine did not stop within 15 seconds, so the upgrade did not touch its database');
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The engine's user can write `engine/userdata/`, so a database file there may be a link it planted. Every read and
|
|
205
|
+
* write of those files goes through these two, which refuse to follow a link: otherwise a backup could copy a file
|
|
206
|
+
* only `hive-node` may read, and a restore could hand it to the engine or overwrite one.
|
|
207
|
+
*/
|
|
208
|
+
const NO_FOLLOW_WRITE = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW;
|
|
209
|
+
async function copyNoFollow(from, to, flags = NO_FOLLOW_WRITE) {
|
|
210
|
+
let source;
|
|
211
|
+
try {
|
|
212
|
+
// O_NONBLOCK, so a FIFO put in place of a file cannot hold the open. It changes nothing for a regular file.
|
|
213
|
+
source = await open(from, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
const code = error.code;
|
|
217
|
+
if (code === 'ENOENT')
|
|
218
|
+
return false;
|
|
219
|
+
if (code === 'ELOOP')
|
|
220
|
+
throw new Error(`${from} is a link, so the step will not copy it`);
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
let target;
|
|
224
|
+
try {
|
|
225
|
+
if (!(await source.stat()).isFile())
|
|
226
|
+
throw new Error(`${from} is not a regular file, so the step will not copy it`);
|
|
227
|
+
target = await open(to, flags, 0o660).catch((error) => {
|
|
228
|
+
throw error.code === 'ELOOP' ? new Error(`${to} is a link, so the step will not write through it`) : error;
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
await source.close();
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
// open() applies the umask. A file this step just created is its own, so it can set the mode the engine needs.
|
|
236
|
+
if ((flags & constants.O_EXCL) !== 0)
|
|
237
|
+
await target.chmod(0o660);
|
|
238
|
+
// Both streams close their handle when they end.
|
|
239
|
+
await pipeline(source.createReadStream(), target.createWriteStream());
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* O_NOFOLLOW guards only the last part of a path. The engine's user can also rename `userdata/` itself, so before the
|
|
244
|
+
* step touches the database it checks that `userdata/` is a real directory right under the engine home. The engine
|
|
245
|
+
* is stopped at that point, and under systemd stopping it ends every agent it started too.
|
|
246
|
+
*/
|
|
247
|
+
async function checkDatabaseDir(run) {
|
|
248
|
+
const dir = dirname(database(run));
|
|
249
|
+
const info = await lstat(dir).catch(() => null);
|
|
250
|
+
if (info === null)
|
|
251
|
+
return;
|
|
252
|
+
if (!info.isDirectory() || (await realpath(dir)) !== join(await realpath(run.layout.engineHome), 'userdata')) {
|
|
253
|
+
throw new Error(`${dir} is not a directory under ${run.layout.engineHome}, so the step will not touch the database`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** Copies the engine database, with its `-wal` and `-shm`, while the engine is stopped. Keeps the newest few. */
|
|
257
|
+
async function backUpDatabase(run, from) {
|
|
258
|
+
await checkDatabaseDir(run);
|
|
259
|
+
const file = database(run);
|
|
260
|
+
if (!(await lstat(file).then((info) => info.isFile() && info.size > 0, () => false)))
|
|
261
|
+
return null;
|
|
262
|
+
const stamp = run.ctx.now().toISOString().replace(/[:.]/g, '-');
|
|
263
|
+
const dir = join(run.layout.backupsDir, `${stamp}-${from}`);
|
|
264
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
265
|
+
for (const suffix of DB_FILES) {
|
|
266
|
+
await copyNoFollow(`${file}${suffix}`, join(dir, `statev2.sqlite${suffix}`), NO_FOLLOW_WRITE | constants.O_EXCL);
|
|
267
|
+
}
|
|
268
|
+
const names = (await readdir(run.layout.backupsDir)).sort();
|
|
269
|
+
for (const old of names.slice(0, Math.max(0, names.length - KEEP_BACKUPS)))
|
|
270
|
+
await rm(join(run.layout.backupsDir, old), { recursive: true, force: true });
|
|
271
|
+
return dir;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Lays OvercyCode `target` into `bin/releases/overcycode/<version>/` and points `bin/t3` at it. The archive is checked before the
|
|
275
|
+
* link moves: it must hold an executable `t3`, and `t3 --version` must name the pinned version, which also catches a
|
|
276
|
+
* box that lacks a library the binary needs. A signed release set replaces the version check in plan item 10.
|
|
277
|
+
*/
|
|
278
|
+
async function installEngine(run, target) {
|
|
279
|
+
const root = releases(run);
|
|
280
|
+
const download = await fetchArtifact(run, ENGINE_ARTIFACT, target.route, root);
|
|
281
|
+
const stage = join(root, `.stage-${process.pid}`);
|
|
282
|
+
try {
|
|
283
|
+
const unpacked = await unpack(run, download.file, stage, 't3');
|
|
284
|
+
const probe = await run.exec(join(unpacked, 't3'), ['--version']);
|
|
285
|
+
const reported = /\d+\.\d+\.\d+[0-9A-Za-z.+-]*/.exec(probe.stdout)?.[0] ?? null;
|
|
286
|
+
if (probe.code !== 0)
|
|
287
|
+
throw new Error(`the downloaded t3 does not run: ${(probe.stderr || probe.stdout).trim().slice(-300)}`);
|
|
288
|
+
if (reported !== target.version)
|
|
289
|
+
throw new Error(`the downloaded t3 is ${reported ?? 'an unknown version'}, Hive pinned ${target.version}`);
|
|
290
|
+
const previous = run.state.engine.version;
|
|
291
|
+
const previousSha = run.state.engine.sha256;
|
|
292
|
+
let backup = null;
|
|
293
|
+
const upgrading = previous !== null && previous !== target.version;
|
|
294
|
+
if (upgrading) {
|
|
295
|
+
await stopAndWait(run);
|
|
296
|
+
try {
|
|
297
|
+
backup = await backUpDatabase(run, previous);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
// No backup, no upgrade: the old version starts again as it was.
|
|
301
|
+
await serviceControl(run, 'restart', 'engine');
|
|
302
|
+
throw new Error(`the engine database could not be backed up, so the upgrade stopped before it changed anything: ${error instanceof Error ? error.message : String(error)}`);
|
|
303
|
+
}
|
|
304
|
+
if (backup !== null)
|
|
305
|
+
run.ctx.io.out(`Backed up the engine database to ${backup}.`);
|
|
306
|
+
}
|
|
307
|
+
await rm(versionDir(run, target.version), { recursive: true, force: true });
|
|
308
|
+
await rename(unpacked, versionDir(run, target.version));
|
|
309
|
+
await switchLink(engineLink(run), linkFor(target.version));
|
|
310
|
+
run.state.engine.version = target.version;
|
|
311
|
+
run.state.engine.sha256 = download.sha256;
|
|
312
|
+
if (upgrading)
|
|
313
|
+
run.state.engine.upgrade = { from: previous, from_sha256: previousSha, to: target.version, backup, at: run.ctx.now().toISOString() };
|
|
314
|
+
// The new version and the one before it stay, so a rollback needs no download.
|
|
315
|
+
for (const name of await readdir(root)) {
|
|
316
|
+
if (!name.startsWith('.') && name !== target.version && name !== previous)
|
|
317
|
+
await rm(join(root, name), { recursive: true, force: true });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
await rm(stage, { recursive: true, force: true });
|
|
322
|
+
await rm(download.file, { force: true });
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Writes `service.env` and restarts the engine when its content moved past what the engine last started with, or when
|
|
327
|
+
* `force` says so. The engine and model-access steps both end here. Returns whether it restarted.
|
|
328
|
+
*/
|
|
329
|
+
export async function applyEngineEnv(run, force = false) {
|
|
330
|
+
if (paused(run) || run.state.engine.version === null)
|
|
331
|
+
return false;
|
|
332
|
+
const wanted = await wantedServiceEnv(run);
|
|
333
|
+
if (wanted === null)
|
|
334
|
+
return false;
|
|
335
|
+
await writeIfChanged(run.layout.serviceEnv, wanted, 0o640);
|
|
336
|
+
const hash = sha256(wanted);
|
|
337
|
+
if (!force && hash === run.state.engine.env_hash && !run.state.engine.stopped)
|
|
338
|
+
return false;
|
|
339
|
+
await serviceControl(run, 'restart', 'engine');
|
|
340
|
+
for (const tool of probedTools(run))
|
|
341
|
+
run.state.engine.tools[tool] = run.versions[tool];
|
|
342
|
+
run.state.engine.env_hash = hash;
|
|
343
|
+
run.state.engine.restarted_at = run.ctx.now().toISOString();
|
|
344
|
+
run.state.engine.stopped = false;
|
|
345
|
+
run.cache.engine = undefined;
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
async function repairEngine(run) {
|
|
349
|
+
if (paused(run)) {
|
|
350
|
+
await serviceControl(run, 'stop', 'engine');
|
|
351
|
+
run.state.engine.stopped = true;
|
|
352
|
+
run.cache.engine = undefined;
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const target = engineTarget(run.desired);
|
|
356
|
+
if (target === null)
|
|
357
|
+
return;
|
|
358
|
+
// An upgrade a crash or a stop left open is settled before anything else, from the time the engine restarted.
|
|
359
|
+
if (run.state.engine.upgrade !== null && !(await settleUpgrade(run)))
|
|
360
|
+
return;
|
|
361
|
+
const rejected = run.state.engine.rejected;
|
|
362
|
+
if (rejected !== null) {
|
|
363
|
+
if (rejected.version === target.version)
|
|
364
|
+
return;
|
|
365
|
+
run.state.engine.rejected = null;
|
|
366
|
+
}
|
|
367
|
+
const wanted = await wantedServiceEnv(run);
|
|
368
|
+
if (wanted === null)
|
|
369
|
+
throw new Error('the Hive node id is not known yet');
|
|
370
|
+
// service.env comes first: the foreground keeper starts the engine as soon as bin/t3 is executable.
|
|
371
|
+
await writeIfChanged(run.layout.serviceEnv, wanted, 0o640);
|
|
372
|
+
let restart = false;
|
|
373
|
+
if (run.state.engine.version !== target.version || !(await linkPointsAt(run, target.version))) {
|
|
374
|
+
await installEngine(run, target);
|
|
375
|
+
restart = true;
|
|
376
|
+
}
|
|
377
|
+
await ensureDatabase(run);
|
|
378
|
+
const generation = wantedRestarts(run);
|
|
379
|
+
if (generation > run.state.generations.restart_engine || newTools(run).length > 0)
|
|
380
|
+
restart = true;
|
|
381
|
+
if (!restart && !(await engineHealth(run)).up && since(run, run.state.engine.restarted_at) >= RESTART_PACE_MS)
|
|
382
|
+
restart = true;
|
|
383
|
+
await applyEngineEnv(run, restart);
|
|
384
|
+
// The counter moves only after the restart ran, so a crash in between runs it again.
|
|
385
|
+
if (generation > run.state.generations.restart_engine)
|
|
386
|
+
run.state.generations.restart_engine = generation;
|
|
387
|
+
if (run.state.engine.upgrade !== null)
|
|
388
|
+
await settleUpgrade(run);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Waits for the upgraded engine to answer with its new version, until `UPGRADE_HEALTH_MS` after it restarted. Returns
|
|
392
|
+
* true when it did. Otherwise it rolls back and returns false.
|
|
393
|
+
*/
|
|
394
|
+
async function settleUpgrade(run) {
|
|
395
|
+
const upgrade = run.state.engine.upgrade;
|
|
396
|
+
const started = Date.parse(run.state.engine.restarted_at ?? upgrade.at);
|
|
397
|
+
const deadline = Math.max(started, Date.parse(upgrade.at)) + UPGRADE_HEALTH_MS;
|
|
398
|
+
for (;;) {
|
|
399
|
+
run.cache.engine = undefined;
|
|
400
|
+
const health = await engineHealth(run);
|
|
401
|
+
if (health.up && health.version === upgrade.to) {
|
|
402
|
+
run.state.engine.upgrade = null;
|
|
403
|
+
run.ctx.io.out(`OvercyCode ${upgrade.to} answers. The upgrade from ${upgrade.from} is done.`);
|
|
404
|
+
return true;
|
|
405
|
+
}
|
|
406
|
+
const left = deadline - run.ctx.now().getTime();
|
|
407
|
+
if (left <= 0)
|
|
408
|
+
break;
|
|
409
|
+
await run.ctx.sleep(Math.min(1_000, left), run.signal);
|
|
410
|
+
}
|
|
411
|
+
await rollBackEngine(run, upgrade);
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Puts the engine back on the version it ran before the upgrade: it stops the engine, restores the database backup
|
|
416
|
+
* the upgrade made, points `bin/t3` at the old version, and starts it. The new version is recorded as rejected, so the
|
|
417
|
+
* step does not try it again until Hive pins another one or asks for a rerun of setup.
|
|
418
|
+
*/
|
|
419
|
+
async function rollBackEngine(run, upgrade) {
|
|
420
|
+
if (!(await isExecutable(join(versionDir(run, upgrade.from), 't3')))) {
|
|
421
|
+
throw new Error(`OvercyCode ${upgrade.to} does not answer, and ${upgrade.from} is gone from ${releases(run)}, so the step cannot roll back`);
|
|
422
|
+
}
|
|
423
|
+
await stopAndWait(run);
|
|
424
|
+
await restoreDatabase(run, upgrade.backup);
|
|
425
|
+
await switchLink(engineLink(run), linkFor(upgrade.from));
|
|
426
|
+
const seconds = Math.round(UPGRADE_HEALTH_MS / 1000);
|
|
427
|
+
run.state.engine.version = upgrade.from;
|
|
428
|
+
run.state.engine.sha256 = upgrade.from_sha256;
|
|
429
|
+
run.state.engine.upgrade = null;
|
|
430
|
+
run.state.engine.rejected = {
|
|
431
|
+
version: upgrade.to,
|
|
432
|
+
at: run.ctx.now().toISOString(),
|
|
433
|
+
detail: `OvercyCode ${upgrade.to} did not answer within ${seconds} seconds of the upgrade, so the node went back to ${upgrade.from} and restored the database ${upgrade.backup === null ? 'to empty, as it was' : `from ${upgrade.backup}`}. Pin another version in Hive, or re-run setup to try ${upgrade.to} again.`,
|
|
434
|
+
};
|
|
435
|
+
await applyEngineEnv(run, true);
|
|
436
|
+
run.ctx.io.err(`Rolled the engine back from OvercyCode ${upgrade.to} to ${upgrade.from}.`);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Puts the backup in place of the engine database. Each file the version that failed left is deleted first, a link
|
|
440
|
+
* too (rm removes the link, never what it points at), so SQLite never replays a log of that version. Then each file of
|
|
441
|
+
* the backup is created fresh, at 0660 in a directory of group `hive`, so the engine can open it again.
|
|
442
|
+
*/
|
|
443
|
+
async function restoreDatabase(run, backup) {
|
|
444
|
+
await checkDatabaseDir(run);
|
|
445
|
+
const file = database(run);
|
|
446
|
+
for (const suffix of DB_FILES) {
|
|
447
|
+
await rm(`${file}${suffix}`, { force: true });
|
|
448
|
+
const from = backup === null ? null : join(backup, `statev2.sqlite${suffix}`);
|
|
449
|
+
if (from !== null && (await copyNoFollow(from, `${file}${suffix}`, NO_FOLLOW_WRITE | constants.O_EXCL)))
|
|
450
|
+
continue;
|
|
451
|
+
if (suffix === '') {
|
|
452
|
+
const empty = await open(file, NO_FOLLOW_WRITE | constants.O_EXCL, 0o660);
|
|
453
|
+
await empty.chmod(0o660);
|
|
454
|
+
await empty.close();
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
export const engineStep = {
|
|
459
|
+
id: 'engine',
|
|
460
|
+
needs: ['identity', 'desired'],
|
|
461
|
+
observe: observeEngine,
|
|
462
|
+
repair: repairEngine,
|
|
463
|
+
};
|