@serve.zone/witness 1.1.0 → 1.2.1
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/.smartconfig.json +36 -0
- package/changelog.md +12 -0
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/classes.storage.d.ts +2 -0
- package/dist_ts/classes.storage.js +86 -5
- package/dist_ts/classes.witness.d.ts +14 -1
- package/dist_ts/classes.witness.js +131 -35
- package/dist_ts/index.d.ts +2 -1
- package/dist_ts/index.js +3 -2
- package/dist_ts/plugins.d.ts +4 -2
- package/dist_ts/plugins.js +5 -3
- package/dist_ts/witness.cli.d.ts +3 -0
- package/dist_ts/witness.cli.js +129 -14
- package/dist_ts/witness.config.d.ts +12 -0
- package/dist_ts/witness.config.js +20 -1
- package/dist_ts/witness.enroll.d.ts +26 -0
- package/dist_ts/witness.enroll.js +74 -0
- package/package.json +9 -6
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/classes.storage.ts +82 -4
- package/ts/classes.witness.ts +137 -33
- package/ts/index.ts +3 -0
- package/ts/plugins.ts +4 -0
- package/ts/witness.cli.ts +132 -13
- package/ts/witness.config.ts +29 -0
- package/ts/witness.enroll.ts +113 -0
package/ts/classes.witness.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as plugins from './plugins.js';
|
|
2
|
+
import { commitinfo } from './00_commitinfo_data.js';
|
|
2
3
|
import { WitnessRegister, type IWitnessIssuedPairingCode } from './classes.register.js';
|
|
3
4
|
import { WitnessServer } from './classes.server.js';
|
|
4
5
|
import { WitnessStorage } from './classes.storage.js';
|
|
@@ -12,12 +13,19 @@ export interface IWitnessOptions extends IWitnessServeConfig {
|
|
|
12
13
|
clock?: () => number;
|
|
13
14
|
/** Called once when the storage engine exits on its own: the witness can no longer serve. */
|
|
14
15
|
onStorageFailure?: (errorArg: Error) => void;
|
|
16
|
+
/** Loopback host for the observability server (`/livez`, `/readyz`, `/metrics`); default `'127.0.0.1'`. */
|
|
17
|
+
observabilityHost?: string;
|
|
18
|
+
/** Loopback port for the observability server; default `0` (ephemeral), or `false` to disable. */
|
|
19
|
+
observabilityPort?: number | false;
|
|
20
|
+
/** Optional external shutdown state predicate (e.g. from `registerProcessLifecycle`). */
|
|
21
|
+
isShuttingDown?: () => boolean;
|
|
15
22
|
}
|
|
16
23
|
|
|
17
24
|
interface IRunningWitness {
|
|
18
25
|
storage: WitnessStorage;
|
|
19
26
|
register: WitnessRegister;
|
|
20
27
|
server: WitnessServer;
|
|
28
|
+
observability: plugins.runtimeLifecycle.IObservabilityServerHandle | null;
|
|
21
29
|
}
|
|
22
30
|
|
|
23
31
|
/**
|
|
@@ -28,6 +36,9 @@ interface IRunningWitness {
|
|
|
28
36
|
export class Witness {
|
|
29
37
|
private readonly log: WitnessLog;
|
|
30
38
|
private running: IRunningWitness | null = null;
|
|
39
|
+
private startPromise: Promise<void> | null = null;
|
|
40
|
+
private stopPromise: Promise<void> | null = null;
|
|
41
|
+
private stopping = false;
|
|
31
42
|
|
|
32
43
|
constructor(private readonly options: IWitnessOptions) {
|
|
33
44
|
this.log = new WitnessLog(options.logSink);
|
|
@@ -42,51 +53,144 @@ export class Witness {
|
|
|
42
53
|
return port;
|
|
43
54
|
}
|
|
44
55
|
|
|
56
|
+
/** The bound loopback observability port while the witness runs with observability enabled. */
|
|
57
|
+
public get observabilityPort(): number {
|
|
58
|
+
const port = this.running?.observability?.port;
|
|
59
|
+
if (port === undefined) {
|
|
60
|
+
throw new Error('The witness observability server is not running.');
|
|
61
|
+
}
|
|
62
|
+
return port;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The bound loopback observability base URL while the witness runs with observability enabled. */
|
|
66
|
+
public get observabilityUrl(): string {
|
|
67
|
+
const url = this.running?.observability?.url;
|
|
68
|
+
if (url === undefined) {
|
|
69
|
+
throw new Error('The witness observability server is not running.');
|
|
70
|
+
}
|
|
71
|
+
return url;
|
|
72
|
+
}
|
|
73
|
+
|
|
45
74
|
public async start(): Promise<void> {
|
|
46
75
|
if (this.running) {
|
|
47
76
|
throw new Error('The witness is running already.');
|
|
48
77
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
78
|
+
if (this.startPromise) {
|
|
79
|
+
throw new Error('The witness is starting already.');
|
|
80
|
+
}
|
|
81
|
+
if (this.stopPromise || this.stopping || this.options.isShuttingDown?.()) {
|
|
82
|
+
throw new Error('Witness shutdown was requested before startup.');
|
|
83
|
+
}
|
|
84
|
+
const observabilityHost = this.options.observabilityHost ?? '127.0.0.1';
|
|
85
|
+
if (this.options.observabilityPort !== false && observabilityHost !== '127.0.0.1' && observabilityHost !== '::1') {
|
|
86
|
+
throw new Error('Witness observabilityHost must be a loopback address (\'127.0.0.1\' or \'::1\').');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const startTask = (async () => {
|
|
90
|
+
const [tlsCertificatePem, tlsPrivateKeyPem] = await Promise.all([
|
|
91
|
+
plugins.fs.readFile(this.options.tlsCertPath, 'utf8'),
|
|
92
|
+
plugins.fs.readFile(this.options.tlsKeyPath, 'utf8'),
|
|
93
|
+
]);
|
|
94
|
+
if (this.stopping || this.options.isShuttingDown?.()) {
|
|
95
|
+
throw new Error('Witness shutdown was requested during startup.');
|
|
96
|
+
}
|
|
97
|
+
const storage = await WitnessStorage.start({
|
|
98
|
+
dataDir: this.options.dataDir,
|
|
62
99
|
log: this.log,
|
|
100
|
+
onEngineExit: this.options.onStorageFailure,
|
|
101
|
+
});
|
|
102
|
+
let server: WitnessServer | null = null;
|
|
103
|
+
let observability: plugins.runtimeLifecycle.IObservabilityServerHandle | null = null;
|
|
104
|
+
try {
|
|
105
|
+
if (this.stopping || this.options.isShuttingDown?.()) {
|
|
106
|
+
throw new Error('Witness shutdown was requested during startup.');
|
|
107
|
+
}
|
|
108
|
+
const register = new WitnessRegister({ storage, log: this.log, clock: this.options.clock ?? Date.now });
|
|
109
|
+
server = new WitnessServer({
|
|
110
|
+
register,
|
|
111
|
+
log: this.log,
|
|
112
|
+
listenHost: this.options.listenHost,
|
|
113
|
+
port: this.options.port,
|
|
114
|
+
tlsCertificatePem,
|
|
115
|
+
tlsPrivateKeyPem,
|
|
116
|
+
});
|
|
117
|
+
await server.start();
|
|
118
|
+
if (this.stopping || this.options.isShuttingDown?.()) {
|
|
119
|
+
throw new Error('Witness shutdown was requested during startup.');
|
|
120
|
+
}
|
|
121
|
+
if (this.options.observabilityPort !== false) {
|
|
122
|
+
observability = await plugins.runtimeLifecycle.startObservabilityServer({
|
|
123
|
+
host: observabilityHost,
|
|
124
|
+
port: this.options.observabilityPort ?? 0,
|
|
125
|
+
serviceName: 'witness',
|
|
126
|
+
version: commitinfo.version,
|
|
127
|
+
isShuttingDown: () => this.stopping || Boolean(this.options.isShuttingDown?.()),
|
|
128
|
+
isLive: () => !this.stopping && Boolean(this.running),
|
|
129
|
+
readinessChecks: {
|
|
130
|
+
storage: async () => ({ ok: await storage.isReady() }),
|
|
131
|
+
},
|
|
132
|
+
legacyAliases: {
|
|
133
|
+
livenessPaths: ['/live'],
|
|
134
|
+
readinessPaths: ['/ready'],
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
if (this.stopping || this.options.isShuttingDown?.()) {
|
|
139
|
+
throw new Error('Witness shutdown was requested during startup.');
|
|
140
|
+
}
|
|
141
|
+
this.running = { storage, register, server, observability };
|
|
142
|
+
} catch (error) {
|
|
143
|
+
await observability?.stop().catch(() => undefined);
|
|
144
|
+
await server?.stop().catch(() => undefined);
|
|
145
|
+
await storage.stop().catch(() => undefined);
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
this.log.write('info', 'started', {
|
|
63
149
|
listenHost: this.options.listenHost,
|
|
64
|
-
port: this.
|
|
65
|
-
|
|
66
|
-
tlsPrivateKeyPem,
|
|
150
|
+
port: this.port,
|
|
151
|
+
observabilityUrl: observability?.url ?? null,
|
|
67
152
|
});
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
153
|
+
})();
|
|
154
|
+
|
|
155
|
+
this.startPromise = startTask;
|
|
156
|
+
try {
|
|
157
|
+
await startTask;
|
|
158
|
+
} finally {
|
|
159
|
+
if (this.startPromise === startTask) {
|
|
160
|
+
this.startPromise = null;
|
|
161
|
+
}
|
|
73
162
|
}
|
|
74
|
-
this.log.write('info', 'started', { listenHost: this.options.listenHost, port: this.port });
|
|
75
163
|
}
|
|
76
164
|
|
|
77
|
-
/** Stops the listener, letting requests in flight finish, then the storage. */
|
|
165
|
+
/** Stops the listener, letting requests in flight finish, then the storage and observability. */
|
|
78
166
|
public async stop(): Promise<void> {
|
|
79
|
-
|
|
80
|
-
if (
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
this.running = null;
|
|
84
|
-
try {
|
|
85
|
-
await running.server.stop();
|
|
86
|
-
} finally {
|
|
87
|
-
await running.storage.stop();
|
|
167
|
+
this.stopping = true;
|
|
168
|
+
if (this.stopPromise) {
|
|
169
|
+
return this.stopPromise;
|
|
88
170
|
}
|
|
89
|
-
this.
|
|
171
|
+
this.stopPromise = (async () => {
|
|
172
|
+
try {
|
|
173
|
+
await this.startPromise?.catch(() => undefined);
|
|
174
|
+
const running = this.running;
|
|
175
|
+
if (!running) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.running = null;
|
|
179
|
+
try {
|
|
180
|
+
await running.server.stop();
|
|
181
|
+
} finally {
|
|
182
|
+
try {
|
|
183
|
+
await running.storage.stop();
|
|
184
|
+
} finally {
|
|
185
|
+
await running.observability?.stop();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
this.log.write('info', 'stopped');
|
|
189
|
+
} finally {
|
|
190
|
+
this.stopPromise = null;
|
|
191
|
+
}
|
|
192
|
+
})();
|
|
193
|
+
return this.stopPromise;
|
|
90
194
|
}
|
|
91
195
|
|
|
92
196
|
/** Makes a one-time pairing code for one controller id; see `witness pairing-code`. */
|
package/ts/index.ts
CHANGED
|
@@ -2,10 +2,12 @@ export { Witness, type IWitnessOptions } from './classes.witness.js';
|
|
|
2
2
|
export { witnessPairingCodeLifetime, type IWitnessIssuedPairingCode } from './classes.register.js';
|
|
3
3
|
export {
|
|
4
4
|
readWitnessConfig,
|
|
5
|
+
readWitnessObservabilityConfig,
|
|
5
6
|
readWitnessServeConfig,
|
|
6
7
|
witnessEnvironmentKeys,
|
|
7
8
|
witnessPaths,
|
|
8
9
|
type IWitnessConfig,
|
|
10
|
+
type IWitnessObservabilityConfig,
|
|
9
11
|
type IWitnessPaths,
|
|
10
12
|
type IWitnessServeConfig,
|
|
11
13
|
type TWitnessEnvironment,
|
|
@@ -19,4 +21,5 @@ export {
|
|
|
19
21
|
type TWitnessLogValue,
|
|
20
22
|
} from './witness.log.js';
|
|
21
23
|
export { runCli, type IWitnessCliIo } from './witness.cli.js';
|
|
24
|
+
export { enrollWitness, WITNESS_VERSION, type IWitnessEnrollOptions, type IWitnessEnrollResult } from './witness.enroll.js';
|
|
22
25
|
export { commitinfo } from './00_commitinfo_data.js';
|
package/ts/plugins.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// node native scope
|
|
2
2
|
import * as crypto from 'node:crypto';
|
|
3
3
|
import * as fs from 'node:fs/promises';
|
|
4
|
+
import * as net from 'node:net';
|
|
4
5
|
import * as path from 'node:path';
|
|
5
6
|
import * as util from 'node:util';
|
|
6
7
|
|
|
7
8
|
export {
|
|
8
9
|
crypto,
|
|
9
10
|
fs,
|
|
11
|
+
net,
|
|
10
12
|
path,
|
|
11
13
|
util,
|
|
12
14
|
}
|
|
@@ -32,7 +34,9 @@ export {
|
|
|
32
34
|
|
|
33
35
|
// @serve.zone scope
|
|
34
36
|
import * as servezoneInterfaces from '@serve.zone/interfaces';
|
|
37
|
+
import * as runtimeLifecycle from '@serve.zone/interfaces/runtime/lifecycle';
|
|
35
38
|
|
|
36
39
|
export {
|
|
40
|
+
runtimeLifecycle,
|
|
37
41
|
servezoneInterfaces,
|
|
38
42
|
}
|
package/ts/witness.cli.ts
CHANGED
|
@@ -2,13 +2,15 @@ import * as plugins from './plugins.js';
|
|
|
2
2
|
import { WitnessRegister, witnessPairingCodeLifetime } from './classes.register.js';
|
|
3
3
|
import { WitnessStorage } from './classes.storage.js';
|
|
4
4
|
import { Witness } from './classes.witness.js';
|
|
5
|
+
import { enrollWitness, WITNESS_VERSION } from './witness.enroll.js';
|
|
5
6
|
import {
|
|
6
7
|
readWitnessConfig,
|
|
8
|
+
readWitnessObservabilityConfig,
|
|
7
9
|
readWitnessServeConfig,
|
|
8
10
|
witnessEnvironmentKeys,
|
|
9
11
|
type TWitnessEnvironment,
|
|
10
12
|
} from './witness.config.js';
|
|
11
|
-
import { formatWitnessLogLine, WitnessLog, writeWitnessLogLine, type TWitnessLogSink } from './witness.log.js';
|
|
13
|
+
import { formatWitnessLogLine, WitnessLog, writeWitnessLogLine, type TWitnessLogSink, type TWitnessLogValue } from './witness.log.js';
|
|
12
14
|
|
|
13
15
|
/** Where the CLI reads its configuration and writes its output. */
|
|
14
16
|
export interface IWitnessCliIo {
|
|
@@ -19,43 +21,124 @@ export interface IWitnessCliIo {
|
|
|
19
21
|
stderr: (textArg: string) => void;
|
|
20
22
|
/** The log of `witness serve`. */
|
|
21
23
|
logSink: TWitnessLogSink;
|
|
24
|
+
/** Optional process signal/exit target for in-process lifecycle testing. */
|
|
25
|
+
processTarget?: plugins.runtimeLifecycle.IProcessLifecycleProcessTarget;
|
|
22
26
|
}
|
|
23
27
|
|
|
24
28
|
const usage = [
|
|
25
29
|
'usage:',
|
|
30
|
+
' witness --version',
|
|
26
31
|
' witness serve',
|
|
27
32
|
` witness pairing-code --controller <controllerId> [--lifetime-minutes <1-${witnessPairingCodeLifetime.maximumMinutes}>]`,
|
|
33
|
+
' witness enroll --cloudly-url <https://...> --host-id <id> --controller <controllerId> --token-file <path>',
|
|
28
34
|
'configuration:',
|
|
29
35
|
` ${witnessEnvironmentKeys.dataDir}: absolute directory of the witness state (every command)`,
|
|
30
36
|
` ${witnessEnvironmentKeys.tlsCertPath}, ${witnessEnvironmentKeys.tlsKeyPath}: PEM certificate chain and key (serve)`,
|
|
31
37
|
` ${witnessEnvironmentKeys.listenHost} (default 0.0.0.0), ${witnessEnvironmentKeys.port} (default 443) (serve)`,
|
|
38
|
+
` ${witnessEnvironmentKeys.observabilityHost} (default 127.0.0.1), ${witnessEnvironmentKeys.observabilityPort} (default 9443) (serve)`,
|
|
32
39
|
'',
|
|
33
40
|
].join('\n');
|
|
34
41
|
|
|
35
|
-
|
|
42
|
+
const toLogFields = (metaArg: unknown): Record<string, TWitnessLogValue> => {
|
|
43
|
+
if (metaArg === undefined) {
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
if (metaArg instanceof Error) {
|
|
47
|
+
return WitnessLog.describeError(metaArg);
|
|
48
|
+
}
|
|
49
|
+
if (typeof metaArg === 'object' && metaArg !== null) {
|
|
50
|
+
const fields: Record<string, TWitnessLogValue> = {};
|
|
51
|
+
for (const [key, value] of Object.entries(metaArg as Record<string, unknown>)) {
|
|
52
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null) {
|
|
53
|
+
fields[key] = value;
|
|
54
|
+
} else if (value !== undefined) {
|
|
55
|
+
fields[key] = String(value);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return fields;
|
|
59
|
+
}
|
|
60
|
+
return { detail: String(metaArg) };
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Serves until SIGINT or SIGTERM (exit 0) or until the storage engine or fatal error fails (exit 1). */
|
|
36
64
|
const serve = async (argsArg: string[], ioArg: IWitnessCliIo): Promise<number> => {
|
|
37
65
|
plugins.util.parseArgs({ args: argsArg, options: {}, strict: true, allowPositionals: false });
|
|
38
66
|
const config = readWitnessServeConfig(ioArg.env);
|
|
67
|
+
const observabilityConfig = readWitnessObservabilityConfig(ioArg.env);
|
|
39
68
|
// The storage logs its own failure; serve only ends on it.
|
|
40
69
|
let reportStorageFailure: () => void = () => undefined;
|
|
41
70
|
const storageFailure = new Promise<'storage-failed'>((resolveArg) => {
|
|
42
71
|
reportStorageFailure = () => resolveArg('storage-failed');
|
|
43
72
|
});
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
73
|
+
let resolveLifecycleShutdown: (outcomeArg: 'signal' | 'fatal') => void = () => undefined;
|
|
74
|
+
const lifecycleShutdown = new Promise<'signal' | 'fatal'>((resolveArg) => {
|
|
75
|
+
resolveLifecycleShutdown = (outcomeArg) => resolveArg(outcomeArg);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
let lifecycle: plugins.runtimeLifecycle.IProcessLifecycleHandle | null = null;
|
|
79
|
+
const witness = new Witness({
|
|
80
|
+
...config,
|
|
81
|
+
...observabilityConfig,
|
|
82
|
+
logSink: ioArg.logSink,
|
|
83
|
+
isShuttingDown: () => Boolean(lifecycle?.isShuttingDown()),
|
|
84
|
+
onStorageFailure: () => reportStorageFailure(),
|
|
48
85
|
});
|
|
49
|
-
|
|
50
|
-
|
|
86
|
+
const lifecycleLog = new WitnessLog(ioArg.logSink);
|
|
87
|
+
lifecycle = plugins.runtimeLifecycle.registerProcessLifecycle({
|
|
88
|
+
serviceName: 'witness',
|
|
89
|
+
shutdownTimeoutMs: 25_000,
|
|
90
|
+
fatalShutdownTimeoutMs: 5_000,
|
|
91
|
+
processTarget: ioArg.processTarget,
|
|
92
|
+
logger: {
|
|
93
|
+
log: (levelArg, messageArg, metaArg) => {
|
|
94
|
+
lifecycleLog.write(levelArg, 'process-lifecycle', {
|
|
95
|
+
message: messageArg,
|
|
96
|
+
...toLogFields(metaArg),
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
onShutdown: async (reasonArg) => {
|
|
101
|
+
try {
|
|
102
|
+
await witness.stop();
|
|
103
|
+
} finally {
|
|
104
|
+
queueMicrotask(() => {
|
|
105
|
+
resolveLifecycleShutdown(reasonArg === 'fatal' ? 'fatal' : 'signal');
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
let lifecycleTriggered = false;
|
|
51
112
|
try {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
113
|
+
if (!lifecycle.signal.aborted) {
|
|
114
|
+
try {
|
|
115
|
+
await witness.start();
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (!lifecycle.isShuttingDown()) {
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (lifecycle.isShuttingDown()) {
|
|
123
|
+
lifecycleTriggered = true;
|
|
124
|
+
const outcome = await lifecycleShutdown;
|
|
125
|
+
return outcome === 'fatal' ? 1 : 0;
|
|
126
|
+
}
|
|
127
|
+
const outcome = await Promise.race([lifecycleShutdown, storageFailure]);
|
|
128
|
+
if (outcome === 'signal') {
|
|
129
|
+
lifecycleTriggered = true;
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
if (outcome === 'fatal') {
|
|
133
|
+
lifecycleTriggered = true;
|
|
134
|
+
return 1;
|
|
135
|
+
}
|
|
136
|
+
return 1;
|
|
55
137
|
} finally {
|
|
56
|
-
process.off('SIGINT', onSignal);
|
|
57
|
-
process.off('SIGTERM', onSignal);
|
|
58
138
|
await witness.stop();
|
|
139
|
+
if (!lifecycleTriggered) {
|
|
140
|
+
lifecycle.dispose();
|
|
141
|
+
}
|
|
59
142
|
}
|
|
60
143
|
};
|
|
61
144
|
|
|
@@ -93,6 +176,36 @@ const pairingCode = async (argsArg: string[], ioArg: IWitnessCliIo): Promise<num
|
|
|
93
176
|
}
|
|
94
177
|
};
|
|
95
178
|
|
|
179
|
+
/** One-time cloud-init enrollment bootstrap: issues a pairing code and redeems the enrollment token. */
|
|
180
|
+
const enroll = async (argsArg: string[], ioArg: IWitnessCliIo): Promise<number> => {
|
|
181
|
+
const { values } = plugins.util.parseArgs({
|
|
182
|
+
args: argsArg,
|
|
183
|
+
options: {
|
|
184
|
+
'cloudly-url': { type: 'string' },
|
|
185
|
+
'host-id': { type: 'string' },
|
|
186
|
+
controller: { type: 'string' },
|
|
187
|
+
'token-file': { type: 'string' },
|
|
188
|
+
},
|
|
189
|
+
strict: true,
|
|
190
|
+
allowPositionals: false,
|
|
191
|
+
});
|
|
192
|
+
if (!values['cloudly-url'] || !values['host-id'] || !values.controller || !values['token-file']) {
|
|
193
|
+
throw new Error('--cloudly-url, --host-id, --controller, and --token-file are required.');
|
|
194
|
+
}
|
|
195
|
+
const config = readWitnessConfig(ioArg.env);
|
|
196
|
+
const enrollmentToken = (await plugins.fs.readFile(values['token-file'], 'utf8')).trim();
|
|
197
|
+
const result = await enrollWitness({
|
|
198
|
+
cloudlyUrl: values['cloudly-url'],
|
|
199
|
+
hostId: values['host-id'],
|
|
200
|
+
controllerId: values.controller,
|
|
201
|
+
enrollmentToken,
|
|
202
|
+
dataDir: config.dataDir,
|
|
203
|
+
});
|
|
204
|
+
await plugins.fs.rm(values['token-file'], { force: true }).catch(() => undefined);
|
|
205
|
+
ioArg.stdout(`${JSON.stringify(result)}\n`);
|
|
206
|
+
return 0;
|
|
207
|
+
};
|
|
208
|
+
|
|
96
209
|
/**
|
|
97
210
|
* The witness CLI on the witness host. Resolves with the process exit code: 0 done, 1 failed, 2 usage.
|
|
98
211
|
*/
|
|
@@ -112,12 +225,18 @@ export const runCli = async (
|
|
|
112
225
|
...ioArg,
|
|
113
226
|
};
|
|
114
227
|
const [command, ...args] = argvArg;
|
|
228
|
+
if (command === '--version' || command === '-v') {
|
|
229
|
+
io.stdout(`${WITNESS_VERSION}\n`);
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
115
232
|
try {
|
|
116
233
|
switch (command) {
|
|
117
234
|
case 'serve':
|
|
118
235
|
return await serve(args, io);
|
|
119
236
|
case 'pairing-code':
|
|
120
237
|
return await pairingCode(args, io);
|
|
238
|
+
case 'enroll':
|
|
239
|
+
return await enroll(args, io);
|
|
121
240
|
default:
|
|
122
241
|
io.stderr(usage);
|
|
123
242
|
return 2;
|
package/ts/witness.config.ts
CHANGED
|
@@ -15,6 +15,10 @@ export const witnessEnvironmentKeys = Object.freeze({
|
|
|
15
15
|
listenHost: 'WITNESS_LISTEN_HOST',
|
|
16
16
|
/** TCP port of the listener; default 443. */
|
|
17
17
|
port: 'WITNESS_PORT',
|
|
18
|
+
/** Loopback interface address for `/livez`, `/readyz`, `/metrics`; default `127.0.0.1`. */
|
|
19
|
+
observabilityHost: 'WITNESS_OBSERVABILITY_HOST',
|
|
20
|
+
/** Loopback TCP port for `/livez`, `/readyz`, `/metrics`; default 9443. */
|
|
21
|
+
observabilityPort: 'WITNESS_OBSERVABILITY_PORT',
|
|
18
22
|
} as const);
|
|
19
23
|
|
|
20
24
|
/** What every witness command needs: where the witness keeps its state. */
|
|
@@ -32,6 +36,13 @@ export interface IWitnessServeConfig extends IWitnessConfig {
|
|
|
32
36
|
port: number;
|
|
33
37
|
}
|
|
34
38
|
|
|
39
|
+
/** Loopback HTTP observability listener configuration for `witness serve`. */
|
|
40
|
+
export interface IWitnessObservabilityConfig {
|
|
41
|
+
observabilityHost: string;
|
|
42
|
+
/** 0 to 65535; default 9443. */
|
|
43
|
+
observabilityPort: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
/** The paths below `dataDir`. */
|
|
36
47
|
export interface IWitnessPaths {
|
|
37
48
|
/** The NoSQLDB storage root; NoSQLDB creates it accessible to its owner alone. */
|
|
@@ -105,3 +116,21 @@ export const readWitnessServeConfig = (environmentArg: TWitnessEnvironment): IWi
|
|
|
105
116
|
port: Number(portValue),
|
|
106
117
|
};
|
|
107
118
|
};
|
|
119
|
+
|
|
120
|
+
/** Reads the loopback observability listener configuration of `witness serve`. */
|
|
121
|
+
export const readWitnessObservabilityConfig = (
|
|
122
|
+
environmentArg: TWitnessEnvironment,
|
|
123
|
+
): IWitnessObservabilityConfig => {
|
|
124
|
+
const hostValue = readValue(environmentArg, witnessEnvironmentKeys.observabilityHost) ?? '127.0.0.1';
|
|
125
|
+
if (hostValue !== '127.0.0.1' && hostValue !== '::1') {
|
|
126
|
+
throw new Error(`${witnessEnvironmentKeys.observabilityHost} must be '127.0.0.1' or '::1'.`);
|
|
127
|
+
}
|
|
128
|
+
const portValue = readValue(environmentArg, witnessEnvironmentKeys.observabilityPort) ?? '9443';
|
|
129
|
+
if (!/^(?:0|[1-9][0-9]{0,4})$/.test(portValue) || Number(portValue) > 65535) {
|
|
130
|
+
throw new Error(`${witnessEnvironmentKeys.observabilityPort} must be a port from 0 to 65535.`);
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
observabilityHost: hostValue,
|
|
134
|
+
observabilityPort: Number(portValue),
|
|
135
|
+
};
|
|
136
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import { WitnessRegister } from './classes.register.js';
|
|
3
|
+
import { WitnessStorage } from './classes.storage.js';
|
|
4
|
+
import { WitnessLog } from './witness.log.js';
|
|
5
|
+
|
|
6
|
+
export const WITNESS_VERSION = '1.2.0';
|
|
7
|
+
|
|
8
|
+
export interface IWitnessEnrollOptions {
|
|
9
|
+
cloudlyUrl: string;
|
|
10
|
+
hostId: string;
|
|
11
|
+
controllerId: string;
|
|
12
|
+
enrollmentToken: string;
|
|
13
|
+
dataDir: string;
|
|
14
|
+
fetchFn?: typeof fetch;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface IWitnessEnrollResult {
|
|
18
|
+
witnessOrigin: string;
|
|
19
|
+
controllerId: string;
|
|
20
|
+
tlsCertPath: string | null;
|
|
21
|
+
tlsKeyPath: string | null;
|
|
22
|
+
pairingCodeIssued: true;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Single-use cloud-init enrollment bootstrap for a Hetzner-managed witness host:
|
|
27
|
+
* 1. Opens embedded NoSQLDB briefly (before `witness serve` starts) to mint one pairing code
|
|
28
|
+
* for `controllerId` and closes storage cleanly so `witness serve` holds the root exclusively.
|
|
29
|
+
* 2. Redeems the single-use `enrollmentToken` over HTTPS against Cloudly's
|
|
30
|
+
* `claimManagedHostEnrollment`, delivering the one-time pairing code so Cloudly can pair
|
|
31
|
+
* automatically without SSH access.
|
|
32
|
+
* 3. Persists any controller-provided TLS certificate/key (`0600`) under `<dataDir>/tls/`.
|
|
33
|
+
*/
|
|
34
|
+
export async function enrollWitness(optionsArg: IWitnessEnrollOptions): Promise<IWitnessEnrollResult> {
|
|
35
|
+
const dataDir = plugins.path.resolve(optionsArg.dataDir);
|
|
36
|
+
const log = new WitnessLog(() => undefined);
|
|
37
|
+
|
|
38
|
+
const storage = await WitnessStorage.start({ dataDir, log });
|
|
39
|
+
let pairingCode: string;
|
|
40
|
+
try {
|
|
41
|
+
const register = new WitnessRegister({ storage, log, clock: Date.now });
|
|
42
|
+
const issued = await register.issuePairingCode(optionsArg.controllerId, 15);
|
|
43
|
+
pairingCode = issued.pairingCode;
|
|
44
|
+
} finally {
|
|
45
|
+
await storage.stop();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const fetchImpl = optionsArg.fetchFn ?? fetch;
|
|
49
|
+
const endpoint = new URL('/typedrequest', optionsArg.cloudlyUrl).toString();
|
|
50
|
+
const response = await fetchImpl(endpoint, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: { 'content-type': 'application/json' },
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
method: 'claimManagedHostEnrollment',
|
|
55
|
+
request: {
|
|
56
|
+
hostId: optionsArg.hostId,
|
|
57
|
+
enrollmentToken: optionsArg.enrollmentToken,
|
|
58
|
+
installedVersion: WITNESS_VERSION,
|
|
59
|
+
witnessPairingCode: pairingCode,
|
|
60
|
+
},
|
|
61
|
+
response: null,
|
|
62
|
+
correlation: { id: plugins.crypto.randomUUID(), phase: 'request' },
|
|
63
|
+
}),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new Error(`Witness enrollment failed with HTTP ${response.status}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const envelope = (await response.json()) as {
|
|
71
|
+
response?: {
|
|
72
|
+
ok: true;
|
|
73
|
+
bootstrap: {
|
|
74
|
+
role: string;
|
|
75
|
+
witnessOrigin: string;
|
|
76
|
+
controllerId: string;
|
|
77
|
+
tlsCertificatePem?: string;
|
|
78
|
+
tlsPrivateKeyPem?: string;
|
|
79
|
+
};
|
|
80
|
+
} | {
|
|
81
|
+
ok: false;
|
|
82
|
+
code: string;
|
|
83
|
+
message: string;
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const answer = envelope.response;
|
|
88
|
+
if (!answer || !answer.ok) {
|
|
89
|
+
throw new Error(`Witness enrollment refused: ${answer && !answer.ok ? `${answer.code}: ${answer.message}` : 'empty response'}`);
|
|
90
|
+
}
|
|
91
|
+
if (answer.bootstrap.role !== 'witness') {
|
|
92
|
+
throw new Error(`Unexpected enrollment role: ${answer.bootstrap.role}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let tlsCertPath: string | null = null;
|
|
96
|
+
let tlsKeyPath: string | null = null;
|
|
97
|
+
if (answer.bootstrap.tlsCertificatePem && answer.bootstrap.tlsPrivateKeyPem) {
|
|
98
|
+
const tlsDir = plugins.path.join(dataDir, 'tls');
|
|
99
|
+
await plugins.fs.mkdir(tlsDir, { recursive: true, mode: 0o700 });
|
|
100
|
+
tlsCertPath = plugins.path.join(tlsDir, 'cert.pem');
|
|
101
|
+
tlsKeyPath = plugins.path.join(tlsDir, 'key.pem');
|
|
102
|
+
await plugins.fs.writeFile(tlsCertPath, answer.bootstrap.tlsCertificatePem, { mode: 0o644 });
|
|
103
|
+
await plugins.fs.writeFile(tlsKeyPath, answer.bootstrap.tlsPrivateKeyPem, { mode: 0o600 });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
witnessOrigin: answer.bootstrap.witnessOrigin,
|
|
108
|
+
controllerId: answer.bootstrap.controllerId,
|
|
109
|
+
tlsCertPath,
|
|
110
|
+
tlsKeyPath,
|
|
111
|
+
pairingCodeIssued: true,
|
|
112
|
+
};
|
|
113
|
+
}
|