-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
545 lines (508 loc) · 18.4 KB
/
Copy pathindex.ts
File metadata and controls
545 lines (508 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import { Flags } from "@oclif/core";
import consola from "consola";
import { claimAction, claimCommand } from "../../lib/claim-state";
import { ZitadelError } from "../../lib/errors";
import { assertServerPackageAvailable } from "../../lib/local-server/binary";
import { dockerAvailable, imageAvailable } from "../../lib/local-server/docker";
import {
dockerRuntimeGuidance,
dockerUnavailableMessage,
} from "../../lib/local-server/docker-guidance";
import {
discoverManagedRuntimeProcesses,
type ManagedRuntimeProcess,
} from "../../lib/local-server/processes";
import {
DEFAULT_LOCAL_SERVER_PORT,
assertLocalStateWritable,
checkLocalServerHealth,
defaultLocalServerImageForCliVersion,
localServerUrl,
readRuntimeMetadata,
type RuntimeBackend,
type RuntimeMetadata,
} from "../../lib/local-server/runtime";
import { BaseCommand, type JsonEnvelope } from "../../lib/oclif";
import { createOrca } from "../../lib/orca";
import { hasZitadelConfig } from "../../lib/project";
import { listenersForPort } from "../../lib/prober/ports";
import { publicCliCommand } from "../../lib/public-cli";
import { SANITY_CHECKS, type CheckContext, type CheckOutcome } from "./checks";
const LOCAL_RUNTIME_CHECK_NAMES = new Set([
"server-binary",
"docker-cli",
"image",
"state-dir",
"port",
"runtime",
]);
/**
* `zitadel doctor` — verify generated files and local state.
*
* Runs every registered {@link SANITY_CHECKS} entry and emits the aggregate
* result; if any check fails it throws `E_VALIDATION` carrying the full check
* details. With `--fix`, each check that did not pass — failed or warned —
* first attempts its own repair (a no-op for checks with no safe automatic
* remedy), then the battery re-runs.
*
* The `--fix` loop is best-effort: a repair that throws (e.g. a missing
* prerequisite file the check itself would also flag) is logged at debug
* level and skipped, not propagated — the post-fix re-verify still reports
* whatever remains broken.
*/
export default class Doctor extends BaseCommand {
static override description = "Verify local runtime and project state.";
static override flags = {
fix: Flags.boolean({ description: "Repair missing files and stale managed wiring." }),
image: Flags.string({ description: "Container image to check." }),
port: Flags.integer({ description: "Local HTTP port.", default: DEFAULT_LOCAL_SERVER_PORT }),
runtime: Flags.string({
description: "Local runtime backend.",
options: ["binary", "docker"],
}),
};
async run(): Promise<JsonEnvelope> {
const { flags } = await this.parse(Doctor);
const port = flags.port ?? DEFAULT_LOCAL_SERVER_PORT;
await this.toMeta(flags, { resolveServer: false, source: localServerUrl(port) });
const { cwd, dryRun } = this.meta;
const existingRuntime = await readRuntimeMetadata(cwd);
const runtimeBackend = resolveRuntimeBackend({
runtime: flags.runtime,
image: flags.image,
envImage: this.meta.env.ZITADEL_LOCAL_IMAGE,
existingRuntime,
});
const image =
flags.image ??
this.meta.env.ZITADEL_LOCAL_IMAGE ??
defaultLocalServerImageForCliVersion(this.meta.cliVersion);
const runtimeChecks = await runLocalRuntimeChecks(cwd, runtimeBackend, image, port);
const hasConfig = await hasZitadelConfig(cwd);
const ctx: CheckContext = { cwd, orca: createOrca(), cliVersion: this.meta.cliVersion, dryRun };
if (hasConfig && flags.fix) {
const before = await Promise.all(SANITY_CHECKS.map((check) => check.run(ctx)));
for (const [index, check] of SANITY_CHECKS.entries()) {
// Repair warn-level drift too (e.g. a deleted presentation page):
// fixes are restore-missing-only, so running one on a warning is safe.
if (before[index]?.status === "pass") {
continue;
}
try {
await check.fix(ctx);
} catch (error) {
consola.debug(`doctor --fix: ${check.name} repair failed`, error);
}
}
}
const projectChecks = hasConfig
? await Promise.all(SANITY_CHECKS.map((check) => check.run(ctx)))
: [];
const checks = [...runtimeChecks, ...projectChecks];
const failed = checks.filter((check) => check.status === "fail");
const warnings = checks.filter((check) => check.status === "warn");
const warningAdvice = advisoryForWarnings(warnings, this.meta.cliVersion);
this.recordTelemetry({
runtime: runtimeBackend,
checks_total: checks.length,
checks_failed: failed.length,
checks_warn: warnings.length,
failed_checks: failed.length > 0 ? failed.map((check) => check.name).join(",") : undefined,
});
const data = {
title:
failed.length > 0
? "Zitadel doctor found issues."
: warnings.length > 0
? "Zitadel doctor passed with warnings."
: "Zitadel doctor passed.",
ok: failed.length === 0,
runtime: runtimeBackend,
...(runtimeBackend === "docker" ? { image } : {}),
port,
project: {
lifecycle: hasConfig ? "configured" : "not-configured",
},
checks,
...(warningAdvice
? {
next_actions: warningAdvice.nextActions,
next_commands: warningAdvice.nextCommands,
}
: {}),
};
if (failed.length > 0) {
const advice = failureAdvice(failed, image, port, this.meta.cliVersion);
// A check that failed with a typed CLI error advertises its own
// category (e.g. the framework floor's E_UNSUPPORTED_PROJECT_SHAPE) —
// surface that instead of the generic validation class so agents can
// branch on it. The port check keeps its dedicated code first.
const code = failed.some((check) => check.name === "port")
? "E_PORT_IN_USE"
: (failed.find((check) => check.code !== undefined)?.code ?? "E_VALIDATION");
throw new ZitadelError(code, "Zitadel doctor found issues", {
hint: advice.hint,
nextCommands: advice.nextCommands,
details: data,
});
}
return this.emit({
status: "ok",
data,
warnings: warnings.map((warning) => `${warning.name}: ${warning.message}`),
});
}
}
function failureAdvice(
failed: CheckOutcome[],
image: string,
port: number,
cliVersion: string,
): { hint: string; nextCommands: string[] } {
const failedNames = new Set(failed.map((check) => check.name));
if (failedNames.has("server-binary")) {
return {
hint: "The Zitadel server npm package is not available. Reinstall the CLI package, then retry.",
nextCommands: [publicCliCommand("doctor", cliVersion)],
};
}
if (failedNames.has("docker-cli")) {
const advice = dockerRuntimeGuidance("doctor", cliVersion);
return {
hint: advice.hint,
nextCommands: advice.nextCommands,
};
}
if (failedNames.has("image")) {
return {
hint: "The local Zitadel image is not available. Check Docker registry access, build it locally, or pass --image / ZITADEL_LOCAL_IMAGE.",
nextCommands: [`docker pull ${image}`, publicCliCommand("doctor", cliVersion)],
};
}
if (failedNames.has("state-dir")) {
return {
hint: "The local Zitadel state directory is not writable. Fix directory permissions, then rerun `zitadel doctor`.",
nextCommands: [publicCliCommand("doctor", cliVersion)],
};
}
if (failedNames.has("port")) {
const fallbackPort = port === DEFAULT_LOCAL_SERVER_PORT ? port + 1 : DEFAULT_LOCAL_SERVER_PORT;
const stopCommand = publicCliCommand("stop --all", cliVersion);
const retryCommand = publicCliCommand("doctor", cliVersion);
const alternatePortCommand = publicCliCommand(
`doctor --port ${String(fallbackPort)}`,
cliVersion,
);
return {
hint:
`Port ${String(port)} is already in use. Stop the process using it, ` +
`run \`${stopCommand}\` for CLI-managed local runtimes, then rerun ` +
`\`${retryCommand}\`; or choose another port with \`${alternatePortCommand}\`.`,
nextCommands: [stopCommand, retryCommand, alternatePortCommand],
};
}
if (failedNames.has("runtime")) {
return {
hint: "Existing local runtime metadata was found, but the local Zitadel server is not healthy. Start it again or reset stale local data.",
nextCommands: [
publicCliCommand("start", cliVersion),
publicCliCommand("reset --force", cliVersion),
],
};
}
// A failure that surfaced as a typed CLI error carries its own remedy —
// e.g. the framework floor's upgrade hint. That beats the generic --fix
// advice below, which cannot repair an unsupported version.
const typed = failed.find((check) => check.code !== undefined && check.hint !== undefined);
if (typed?.hint !== undefined) {
return { hint: typed.hint, nextCommands: [publicCliCommand("doctor", cliVersion)] };
}
const hasProjectFailure = failed.some((check) => !LOCAL_RUNTIME_CHECK_NAMES.has(check.name));
if (hasProjectFailure) {
return {
hint: `Run \`${publicCliCommand("doctor --fix", cliVersion)}\` to re-apply missing managed files.`,
nextCommands: [publicCliCommand("doctor --fix", cliVersion)],
};
}
return {
hint: "Fix the reported checks, then rerun `zitadel doctor`.",
nextCommands: [publicCliCommand("doctor", cliVersion)],
};
}
function advisoryForWarnings(
warnings: CheckOutcome[],
cliVersion: string,
): { nextActions: string[]; nextCommands: string[] } | undefined {
const nextActions: string[] = [];
const nextCommands: string[] = [];
if (warnings.some((check) => check.name === "docker-cli")) {
const advice = dockerRuntimeGuidance("doctor", cliVersion);
nextActions.push(...advice.nextActions);
nextCommands.push(...advice.nextCommands);
}
if (warnings.some((check) => check.name === "claim")) {
nextActions.push(claimAction(cliVersion));
nextCommands.push(claimCommand(cliVersion));
}
const managedRuntimeWarning = warnings.find((check) => check.name === "managed-runtime-processes");
if (hasManagedRuntimeProcesses(managedRuntimeWarning)) {
nextActions.push(
"Review other host-wide CLI-managed local Zitadel runtimes before starting a new one.",
);
nextCommands.push(publicCliCommand("stop --all", cliVersion));
}
if (nextActions.length === 0 && nextCommands.length === 0) {
return undefined;
}
return { nextActions: unique(nextActions), nextCommands: unique(nextCommands) };
}
async function runLocalRuntimeChecks(
cwd: string,
runtimeBackend: RuntimeBackend,
image: string,
port: number,
): Promise<CheckOutcome[]> {
const runtime = await readRuntimeMetadata(cwd);
const managedRuntimeCheck = await checkManagedRuntimeProcesses(runtime);
if (runtimeBackend === "binary") {
return [
await check("server-binary", "Server npm package is available", async () => {
const version = await assertServerPackageAvailable();
return `@zitadel/server ${version} is available`;
}),
await check(
"state-dir",
"Local state directory is writable",
async () => {
const probe = await assertLocalStateWritable(cwd);
return probe.checkedPath === probe.targetPath
? `${probe.targetPath} is writable`
: `${probe.targetPath} can be created (${probe.checkedPath} is writable)`;
},
"warn",
),
await check(
"port",
`Port ${String(port)} is available`,
() => checkPortAvailability(runtime, port),
),
await checkRuntime(runtime, runtimeBackend),
managedRuntimeCheck,
];
}
const docker = await check(
"docker-cli",
"Docker is reachable",
async () => {
let result: Awaited<ReturnType<typeof dockerAvailable>>;
try {
result = await dockerAvailable();
} catch (error) {
throw new Error(dockerUnavailableMessage(error), { cause: error });
}
if (result.status !== 0) {
throw new Error(dockerUnavailableMessage(result.stderr || "docker version failed"));
}
return `Docker engine ${result.stdout.trim() || "available"}`;
},
"warn",
);
const imageCheck =
docker.status === "pass"
? await check(
"image",
`Image ${image} is available`,
async () => {
try {
const source = await imageAvailable(image);
return source === "local"
? `Image ${image} is available locally`
: `Image ${image} is available from the registry`;
} catch (error) {
throw new Error(imageUnavailableMessage(image, error), { cause: error });
}
},
"warn",
)
: ({
name: "image",
status: "warn",
message: "Skipped image check because Docker is not reachable.",
} satisfies CheckOutcome);
return [
docker,
imageCheck,
await check(
"state-dir",
"Local state directory is writable",
async () => {
const probe = await assertLocalStateWritable(cwd);
return probe.checkedPath === probe.targetPath
? `${probe.targetPath} is writable`
: `${probe.targetPath} can be created (${probe.checkedPath} is writable)`;
},
"warn",
),
await check(
"port",
`Port ${String(port)} is available`,
() => checkPortAvailability(runtime, port),
),
await checkRuntime(runtime, runtimeBackend),
managedRuntimeCheck,
];
}
async function checkPortAvailability(
runtime: RuntimeMetadata | undefined,
port: number,
): Promise<string> {
if (runtime?.port === port && (await checkLocalServerHealth(runtime.server_url))) {
return `${runtime.server_url} is already healthy`;
}
const listeners = await listenersForPort(port);
if (listeners.length > 0) {
throw new PortInUseCheckError(port, localServerUrl(port), listeners);
}
return `Port ${String(port)} is available`;
}
class PortInUseCheckError extends Error {
constructor(
readonly port: number,
readonly serverUrl: string,
readonly listeners: Awaited<ReturnType<typeof listenersForPort>>,
) {
super(`Port ${String(port)} is already in use by ${formatListeners(listeners)}`);
}
}
async function checkManagedRuntimeProcesses(
runtime: RuntimeMetadata | undefined,
): Promise<CheckOutcome> {
const discovery = await discoverManagedRuntimeProcesses();
if (!discovery.supported) {
return {
name: "managed-runtime-processes",
status: "warn",
message: "Managed local runtime process discovery is unavailable.",
details: { supported: false, error: discovery.error },
};
}
const processes = additionalManagedRuntimeProcesses(discovery.processes, runtime);
if (processes.length === 0) {
return {
name: "managed-runtime-processes",
status: "pass",
message: "No additional host-wide managed local runtime processes found.",
details: { supported: true, scope: "host", processes: [] },
};
}
return {
name: "managed-runtime-processes",
status: "warn",
message: `${String(processes.length)} other host-wide managed local runtime process${processes.length === 1 ? "" : "es"} found.`,
details: { supported: true, scope: "host", processes },
};
}
function additionalManagedRuntimeProcesses(
processes: ReadonlyArray<ManagedRuntimeProcess>,
runtime: RuntimeMetadata | undefined,
): ReadonlyArray<ManagedRuntimeProcess> {
if (runtime?.backend !== "binary") {
return processes;
}
return processes.filter((processInfo) => processInfo.pid !== runtime.pid && processInfo.ppid !== runtime.pid);
}
async function checkRuntime(
runtime: { backend: RuntimeBackend; server_url: string } | undefined,
runtimeBackend: RuntimeBackend,
): Promise<CheckOutcome> {
return check("runtime", "Existing local runtime is healthy", async () => {
if (!runtime) {
return "No existing runtime metadata";
}
if (runtime.backend !== runtimeBackend) {
throw new Error(
`Existing local runtime uses ${runtime.backend}; run start --runtime ${runtimeBackend} to switch backends.`,
);
}
if (!(await checkLocalServerHealth(runtime.server_url))) {
throw new Error(`${runtime.server_url} did not respond to /healthz`);
}
return `${runtime.server_url} is healthy`;
});
}
function formatListeners(listeners: Awaited<ReturnType<typeof listenersForPort>>): string {
return listeners
.map((listener) =>
[listener.command ?? "unknown", listener.pid ? `pid ${String(listener.pid)}` : undefined]
.filter(Boolean)
.join(" "),
)
.join(", ");
}
function hasManagedRuntimeProcesses(check: CheckOutcome | undefined): boolean {
if (!check || check.status !== "warn") {
return false;
}
const details = check.details;
return (
typeof details === "object" &&
details !== null &&
"supported" in details &&
(details as { supported?: unknown }).supported === true &&
Array.isArray((details as { processes?: unknown }).processes) &&
((details as { processes?: unknown[] }).processes?.length ?? 0) > 0
);
}
function unique(values: string[]): string[] {
return [...new Set(values)];
}
function resolveRuntimeBackend(input: {
runtime: unknown;
image: string | undefined;
envImage: string | undefined;
existingRuntime: { backend: RuntimeBackend } | undefined;
}): RuntimeBackend {
if (input.runtime === "binary" || input.runtime === "docker") {
return input.runtime;
}
if (input.existingRuntime) {
return input.existingRuntime.backend;
}
if (input.image || input.envImage) {
return "docker";
}
return "binary";
}
async function check(
name: string,
fallback: string,
run: () => Promise<string>,
failureStatus: "warn" | "fail" = "fail",
): Promise<CheckOutcome> {
try {
return { name, status: "pass", message: await run() };
} catch (error) {
if (error instanceof PortInUseCheckError) {
return {
name,
status: failureStatus,
message: error.message,
details: {
port: error.port,
server_url: error.serverUrl,
listeners: error.listeners,
},
};
}
return {
name,
status: failureStatus,
message: error instanceof Error ? error.message : fallback,
};
}
}
function imageUnavailableMessage(image: string, error: unknown): string {
const detail = error instanceof Error ? error.message : String(error);
const suffix = detail.trim() ? ` (${detail.trim()})` : "";
return `Image ${image} is not available to Docker${suffix}; \`zitadel start\` may need a pull or a different image.`;
}