Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
269 changes: 212 additions & 57 deletions apps/cli/src/command-internal/db-bootstrap/health-check.ts

Large diffs are not rendered by default.

657 changes: 639 additions & 18 deletions apps/cli/src/command-internal/db-bootstrap/health-check.unit.test.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* `db reset --local`'s container-recreate composition — not a thin wrapper over
* {@link startDatabase}, since the shared `StartDatabase`-equivalent primitive is never called
* from a reset either. Reuses the same underlying primitives (`ensureNetwork`,
* `buildPostgresStartContainerSpec`, `createContainer`, `waitForHealthyServices`,
* `buildPostgresStartContainerSpec`, `createContainer`, `waitForPostgresReady`,
* `startSetupLocalDatabase`) with a distinct sequence per major version: PG >= 15 recreates the
* container/volume/network and re-runs setup; PG <= 14 recreates the two databases in place and
* reinitializes the schema. Neither path probes for an existing volume, supports
Expand Down Expand Up @@ -53,7 +53,11 @@ import {
type FreshDbSetupInput,
type StartSetupLocalDatabaseError,
} from "./db-setup.ts";
import { waitForHealthyServices, type HealthCheckTimeoutError } from "./health-check.ts";
import {
awaitDockerHealthSettled,
waitForPostgresReady,
type HealthCheckTimeoutError,
} from "./health-check.ts";
import type { ImagePrepullError } from "./image-prepull.ts";
import { startInternalDbPassword } from "./internal-db-connection.ts";
import {
Expand Down Expand Up @@ -284,10 +288,18 @@ const recreateLocalDatabase15 = <E>(
yield* createContainer(spawner, postgresSpec, input.containerOpts);

// Never swallowed — reset has no `--from-backup`-equivalent gate.
yield* waitForHealthyServices(spawner, [postgresSpec.containerName], {
timeoutSeconds: input.dbHealthTimeoutSeconds,
images: new Map([[postgresSpec.containerName, resolvedPostgresImage]]),
});
yield* waitForPostgresReady(
spawner,
postgresSpec.containerName,
{
host: input.hostname,
port: input.dbPort,
user: "postgres",
password: startInternalDbPassword(input.setup.dbUrl),
database: "postgres",
},
{ timeoutSeconds: input.dbHealthTimeoutSeconds, image: resolvedPostgresImage },
);

// No fresh-volume gate needed: a reset just removed the volume above, so it's always fresh.
// Passes the resolved reset `version`/`seedFlags`, unlike `db start`'s own call.
Expand Down Expand Up @@ -378,9 +390,18 @@ const recreateLocalDatabase14 = <E>(
// the satellite restarts inside `restartServicesAndReloadKong`.
yield* output.raw("Restarting containers...\n", "stderr");
yield* restartContainer(spawner, input.dbContainerId);
yield* waitForHealthyServices(spawner, [input.dbContainerId], {
timeoutSeconds: input.dbHealthTimeoutSeconds,
});
yield* waitForPostgresReady(
spawner,
input.dbContainerId,
{
host: input.hostname,
port: input.dbPort,
user: "postgres",
password: dbPassword,
database: "postgres",
},
{ timeoutSeconds: input.dbHealthTimeoutSeconds },
);
yield* restartServicesAndReloadKong(spawner, input.projectId);

// Final connect as `postgres`/`postgres` to migrate and seed.
Expand Down Expand Up @@ -421,6 +442,7 @@ export const recreateLocalDatabase = <E>(
? recreateLocalDatabase14(spawner, input)
: recreateLocalDatabase15(spawner, input)
).pipe(
Effect.tap(() => awaitDockerHealthSettled(spawner, input.dbContainerId)),
Effect.withSpan("DbBootstrap.recreateLocalDatabase", {
attributes: { "db.major_version": input.setup.majorVersion },
}),
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/src/command-internal/db-bootstrap/shadow-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { START_DB_SCHEMA_SQL } from "./templates/db-schema.sql.ts";
import { START_DB_SUPABASE_SQL } from "./templates/db-supabase.sql.ts";
import { START_DB_WEBHOOK_SQL } from "./templates/db-webhook.sql.ts";
import { CREATE_VAULT_KV, READ_VAULT_KV, UPDATE_VAULT_KV, type VaultSecret } from "../vault.ts";
import { waitForShadowReady } from "./health-check.ts";
import { waitForPostgresReady } from "./health-check.ts";
import {
exportPgDataTar,
pgDataRestoreArchive,
Expand Down Expand Up @@ -532,7 +532,7 @@ const awaitShadowReady = <E>(
containerId: string,
what: string,
): Effect.Effect<void, ShadowCacheUnavailable, DbConnection> =>
waitForShadowReady(spawner, containerId, shadowConnConfig(input), {
waitForPostgresReady(spawner, containerId, shadowConnConfig(input), {
timeoutSeconds: input.healthTimeoutSeconds,
image: input.image,
}).pipe(
Expand Down
19 changes: 13 additions & 6 deletions apps/cli/src/command-internal/db-bootstrap/start-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ import {
type StartSetupLocalDatabaseError,
} from "./db-setup.ts";
import type { ImagePrepullError } from "./image-prepull.ts";
import { waitForHealthyServices, type HealthCheckTimeoutError } from "./health-check.ts";
import { waitForPostgresReady, type HealthCheckTimeoutError } from "./health-check.ts";
import { startInternalDbPassword } from "./internal-db-connection.ts";
import {
buildPostgresStartContainerSpec,
type PostgresStartServiceInput,
Expand Down Expand Up @@ -180,17 +181,23 @@ export const startDatabase = <E>(
});
yield* createContainer(spawner, postgresSpec, input.containerOpts);

const postgresHealthResult = yield* waitForHealthyServices(
// A host connect, not Docker's HEALTHCHECK: that needs `docker exec`, which nested or
// sandboxed Docker cannot do.
const postgresHealthResult = yield* waitForPostgresReady(
spawner,
[postgresSpec.containerName],
postgresSpec.containerName,
{
timeoutSeconds: input.dbHealthTimeoutSeconds,
images: new Map([[postgresSpec.containerName, resolvedPostgresImage]]),
host: input.hostname,
port: input.dbPort,
user: "postgres",
password: startInternalDbPassword(input.setup.dbUrl),
database: "postgres",
},
{ timeoutSeconds: input.dbHealthTimeoutSeconds, image: resolvedPostgresImage },
).pipe(Effect.result);
if (Result.isFailure(postgresHealthResult)) {
// Discarded only when `fromBackup` is set — the log dump to stderr already happened
// inside `waitForHealthyServices` regardless. Any other failure propagates bare; see this
// inside `waitForPostgresReady` regardless. Any other failure propagates bare; see this
// module's header for why `--ignore-health-check` is entirely the caller's concern.
if (fromBackup === undefined) {
return yield* postgresHealthResult.failure;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { goUrlParse } from "../storage-url.ts";
import { loadLocalProjectContext } from "../local-project-context.ts";
import { cliProjectFilterValue } from "../docker-ids.ts";
import { buildLocalDbContainerInputs } from "./local-container-inputs.ts";
import { awaitDockerHealthSettled } from "./health-check.ts";
import { isLocalDbRunning } from "./local-db-running.ts";
import { rollbackStart } from "./rollback.ts";
import { startDatabase } from "./start-database.ts";
Expand Down Expand Up @@ -722,5 +723,9 @@ export const startLocalDatabase = Effect.fn("DbBootstrap.startLocalDatabase")(fu
),
);

// The connect probe returns before Docker's first health probe, and `status` and the
// already-running gate still read Docker health.
yield* awaitDockerHealthSettled(spawner, dbContainerId);

return { status: "started" } satisfies StartLocalDatabaseResult;
});
80 changes: 75 additions & 5 deletions apps/cli/src/command-internal/docker-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,77 @@ export const inspectContainerState = (spawner: Spawner, containerId: string) =>
}),
).pipe(Effect.withTracerEnabled(false), Effect.provideService(ChildTracePropagation, false));

function parseContainerState(stdout: string): {
/** The most recent health-check probe Docker recorded for a container. */
interface ContainerHealthProbe {
readonly exitCode: number;
readonly output: string;
}

export interface ContainerState {
readonly running: boolean;
readonly status: string;
readonly exitCode: number;
readonly oomKilled: boolean;
readonly health?: string;
} {
readonly lastHealthProbe?: ContainerHealthProbe;
}

const HEALTH_PROBE_OUTPUT_MAX = 300;

function parseLastHealthProbe(health: unknown): ContainerHealthProbe | undefined {
if (!isJsonRecord(health)) return undefined;
const log = health["Log"];
if (!Array.isArray(log)) return undefined;
const last: unknown = log[log.length - 1];
if (!isJsonRecord(last)) return undefined;
const exitCode = last["ExitCode"];
const output = last["Output"];
if (typeof exitCode !== "number" || typeof output !== "string") return undefined;
return { exitCode, output: output.replace(/\s+/gu, " ").trim() };
}

// runc reports a bad healthcheck command as a Go `exec.Error`, an `os.PathError`, or (before
// runc 1.1) wrapped in "exec user process caused".
const EXEC_IMAGE_FAULT_PATTERNS: ReadonlyArray<RegExp> = [
/exec: \\?"[^"]*": (?:executable file not found in \$PATH|stat \S+: no such file or directory|permission denied)/u,
/(?:^|: )exec [^\s:]+: (?:no such file or directory|exec format error|permission denied)/u,
Comment thread
Coly010 marked this conversation as resolved.
Resolved
/exec user process caused:? \\?"?(?:no such file or directory|exec format error|permission denied)/u,
];

/**
* True when Docker could not launch the health check inside a running container. moby records an
* exec-start failure as probe exit code -1 with the runtime error as output; a probe timeout also
* uses -1 but its output never names the OCI runtime. Image faults in the healthcheck command are
* excluded: they are the image's problem, not the host's.
*/
export function healthCheckCannotExec(state: ContainerState): boolean {
const probe = state.lastHealthProbe;
if (!state.running || state.status !== "running" || state.health === "healthy") return false;
if (probe === undefined || probe.exitCode !== -1) return false;
const out = probe.output;
return (
out.includes("OCI runtime exec failed") &&
(out.includes("unable to start container process") ||
out.includes("starting container process caused")) &&
!EXEC_IMAGE_FAULT_PATTERNS.some((pattern) => pattern.test(out))
);
}

/** The not-ready reason for an unhealthy container, naming its last health-check probe. */
export function formatNotReadyReason(state: ContainerState): string {
const base = `container is not ready: ${state.health}`;
const probe = state.lastHealthProbe;
if (probe === undefined) return base;
const output =
probe.output.length > HEALTH_PROBE_OUTPUT_MAX
? `${probe.output.slice(0, HEALTH_PROBE_OUTPUT_MAX - 1)}…`
: probe.output;
return output.length > 0
? `${base} (last health check exit code ${probe.exitCode}: ${output})`
: `${base} (last health check exit code ${probe.exitCode})`;
}

function parseContainerState(stdout: string): ContainerState {
const trimmed = stdout.trim();
let parsed: unknown;
try {
Expand All @@ -262,9 +326,15 @@ function parseContainerState(stdout: string): {
const health = state["Health"];
const healthStatus =
isJsonRecord(health) && typeof health["Status"] === "string" ? health["Status"] : undefined;
return healthStatus !== undefined
? { running, status, exitCode, oomKilled, health: healthStatus }
: { running, status, exitCode, oomKilled };
const lastHealthProbe = parseLastHealthProbe(health);
return {
running,
status,
exitCode,
oomKilled,
...(healthStatus === undefined ? {} : { health: healthStatus }),
...(lastHealthProbe === undefined ? {} : { lastHealthProbe }),
};
}

function isJsonRecord(value: unknown): value is { readonly [key: string]: unknown } {
Expand Down
Loading
Loading