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
125 changes: 125 additions & 0 deletions packages/cli/src/cli/commands/restart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { Command } from "commander";
import type { Plugin, WorkspaceConfig } from "@lo1/sdk";
import { loadWorkspaceConfig } from "../../config/loader";
import { buildEndpointRegistry } from "../../discovery/registry";
import { Lo1Error } from "../../errors";
import { executeHook } from "../../hooks/executor";
import { appendLog } from "../../logs/writer";
import { createEventFormatter } from "../../output/format";
import { loadPlugins } from "../../plugin/loader";
import { restartService } from "../../orchestrator/restart";
import { startService, BUILTIN_TYPES } from "../../orchestrator/service";
import { applyModeOverride, buildServiceState, createLogger } from "../../orchestrator/start";
import { readState, writeState } from "../../orchestrator/state";
import { hydrateHandles } from "../../orchestrator/stop";
import { withWorkspaceLock } from "../../orchestrator/lock";
import type { OrchestratorEvent, WorkspaceState } from "../../orchestrator/types";

export class RestartError extends Lo1Error {
constructor(message: string, code = "RestartError") {
super(message, code);
this.name = "RestartError";
}
}

export function validateRestartTargets(names: string[], config: WorkspaceConfig): void {
for (const name of names) {
const service = config.services[name];
if (!service) {
throw new RestartError(`Unknown service "${name}". Check the services in lo1.yaml.`);
}
if (service.mode === "skip") {
throw new RestartError(`Service "${name}" has mode: skip, so lo1 does not run it.`);
}
}
}

async function loadNeededPlugins(
names: string[],
config: WorkspaceConfig,
workspaceDir: string,
emit: (event: OrchestratorEvent) => void,
): Promise<Map<string, Plugin>> {
const needsPlugins = names.some((name) => !BUILTIN_TYPES.has(config.services[name].type));
if (!needsPlugins) return new Map();
return loadPlugins(config.plugins ?? {}, {
workspaceDir,
workspaceName: config.name,
logger: createLogger(emit),
});
}

function createRestartEventHandler(workspaceDir: string): (event: OrchestratorEvent) => void {
const format = createEventFormatter();
return (event) => {
if (event.kind === "output") {
void appendLog(workspaceDir, event.line.service, event.line.text).catch(() => {});
} else if (event.kind === "hook") {
void appendLog(workspaceDir, "hooks", event.output.text).catch(() => {});
}
const message = format(event);
if (message) process.stdout.write(message.trimEnd() + "\n");
};
}

async function requireRunningWorkspace(workspaceDir: string): Promise<WorkspaceState> {
const state = await readState(workspaceDir);
if (!state) {
throw new RestartError("No running workspace found. Start one with lo1 up.", "NoWorkspace");
}
return state;
}

export const restartCommand = new Command("restart")
.description("Restart services, or run init tasks again, in the running workspace")
.argument("<services...>", "Services or init tasks to restart, in order")
.action(async (names: string[]) => {
const workspaceDir = process.cwd();
const controller = new AbortController();
process.on("SIGINT", () => controller.abort());

// Held from reading the state to writing it, so concurrent restarts
// can't overwrite each other's process ids.
await withWorkspaceLock(workspaceDir, () =>
restartServices(names, workspaceDir, controller.signal),
);
});

async function restartServices(
names: string[],
workspaceDir: string,
signal: AbortSignal,
): Promise<void> {
const state = await requireRunningWorkspace(workspaceDir);
const config = applyModeOverride(await loadWorkspaceConfig(), state.modeOverride);
validateRestartTargets(names, config);

const emit = createRestartEventHandler(workspaceDir);
const ctx = {
config,
workspaceDir,
registry: buildEndpointRegistry(config),
plugins: await loadNeededPlugins(names, config, workspaceDir, emit),
pluginEnvVars: state.pluginEnvVars ?? {},
compose: { projectName: state.projectName, fileArgs: state.fileArgs, cwd: workspaceDir },
detached: true,
signal,
emit,
deps: { startService, executeHook },
};

const current = hydrateHandles(state);
for (const name of names) {
const index = current.findIndex((h) => h.serviceName === name);
const handle = await restartService(name, current[index], ctx);

Check warning on line 114 in packages/cli/src/cli/commands/restart.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_lo1&issues=AaHolgJBcWhJbf0ONTkl&open=AaHolgJBcWhJbf0ONTkl&pullRequest=26
handle.releaseLogs?.();
handle.detach?.();
// A name given twice restarts the replacement, not the original again.
if (index === -1) current.push(handle);
else current[index] = handle;

const { [name]: _previous, ...others } = state.services;
state.services = { ...others, ...buildServiceState([handle]) };
await writeState(state, workspaceDir);

Check warning on line 123 in packages/cli/src/cli/commands/restart.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_lo1&issues=AaHob450DNizRe_5uBeT&open=AaHob450DNizRe_5uBeT&pullRequest=26
}
}
55 changes: 53 additions & 2 deletions packages/cli/src/cli/commands/up.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { Command } from "commander";
import { spawn } from "node:child_process";
import { platform } from "node:os";
import { startWorkspace } from "../../orchestrator/start";
import { stopWorkspace } from "../../orchestrator/stop";
import { buildServiceState, startWorkspace } from "../../orchestrator/start";
import { hydrateHandles, stopWorkspace } from "../../orchestrator/stop";
import { watchPluginServices } from "../../orchestrator/watch";
import { withWorkspaceLock } from "../../orchestrator/lock";
import { readState, writeState } from "../../orchestrator/state";
import { startService, type ServiceHandle } from "../../orchestrator/service";
import { executeHook } from "../../hooks/executor";
import { loadWorkspaceConfig } from "../../config/loader";
import { collectDomains } from "../../proxy/domains";
import { initLogDir, appendLog, logDir } from "../../logs/writer";
Expand Down Expand Up @@ -123,6 +128,30 @@ async function teardown(opts: TeardownOptions): Promise<void> {
}
}

/** A service's handle as the state file records it, if the workspace is still running. */
export async function recordedHandle(
workspaceDir: string,
name: string,
): Promise<ServiceHandle | undefined> {
const state = await readState(workspaceDir);
if (!state?.services[name]) return undefined;
return hydrateHandles({ ...state, services: { [name]: state.services[name] } })[0];
}

/** Points the state file at a service's new process after the watcher restarts it. */
export async function recordReplacement(
workspaceDir: string,
handle: ServiceHandle,
): Promise<void> {
const state = await readState(workspaceDir);
if (!state) return;
const { [handle.serviceName]: _previous, ...others } = state.services;
await writeState(
{ ...state, services: { ...others, ...buildServiceState([handle]) } },
workspaceDir,
);
}

export const upCommand = new Command("up")
.description("Start all services and infrastructure")
.option("--services <names>", "Comma-separated list of services to start")
Expand Down Expand Up @@ -186,7 +215,29 @@ export const upCommand = new Command("up")
return;
}

const watcher = watchPluginServices(
result.handles,
{
config: result.config,
workspaceDir,
registry: result.registry,
plugins: result.plugins,
pluginEnvVars: result.pluginEnvVars,
compose: result.compose,
detached: false,
signal: controller.signal,
emit: onEvent,
deps: { startService, executeHook },
},
{
runExclusive: (fn) => withWorkspaceLock(workspaceDir, fn),
onReplaced: (handle) => recordReplacement(workspaceDir, handle),
recordedHandle: (name) => recordedHandle(workspaceDir, name),
},
);
await waitForShutdownSignal(controller);
// Let a restart under way finish, so teardown sees its new process.
await watcher.stop();
} catch (err) {
if (!controller.signal.aborted) {
startupError = err;
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { hostsCommand } from "./commands/hosts";
import { tlsSetupCommand } from "./commands/tls-setup";
import { logsCommand } from "./commands/logs";
import { doctorCommand } from "./commands/doctor";
import { restartCommand } from "./commands/restart";

export const program = new Command();

Expand All @@ -31,6 +32,7 @@ program.addCommand(hostsCommand);
program.addCommand(tlsSetupCommand);
program.addCommand(logsCommand);
program.addCommand(doctorCommand);
program.addCommand(restartCommand);

export function formatErrorForOutput(err: unknown, json: boolean): string {
if (json) {
Expand Down
100 changes: 100 additions & 0 deletions packages/cli/src/orchestrator/lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { randomUUID } from "node:crypto";
import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createLog } from "../debug";
import { Lo1Error } from "../errors";

const debug = createLog("orchestrator:lock");

export class WorkspaceLockError extends Lo1Error {
constructor(message: string) {
super(message, "WorkspaceLocked");
this.name = "WorkspaceLockError";
}
}

export type WorkspaceLockOptions = {
/** How long to wait for another lo1 command to finish. */
timeoutMs?: number;
pollMs?: number;
isAlive?: (pid: number) => boolean;
};

export function lockPath(workspaceDir: string): string {
return join(workspaceDir, ".lo1", "state.lock");
}

function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return (err as NodeJS.ErrnoException).code === "EPERM";
}
}

/**
* Creates the lock with our pid already in it: the pid goes into a private
* file that is then hard-linked into place, which fails if the lock exists.
* Nobody can see a lock file without a pid and mistake it for a stale one.
*/
async function tryAcquire(path: string): Promise<boolean> {
// Unique per attempt: the watcher may contend for the lock within one process.
const own = `${path}.${process.pid}.${randomUUID()}`;
await writeFile(own, String(process.pid));
try {
await link(own, path);
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
throw err;
} finally {
await unlink(own).catch(() => {});
}
}

/** The pid holding the lock, or null when the lock is gone or its holder has exited. */
async function liveHolder(path: string, isAlive: (pid: number) => boolean): Promise<number | null> {
const content = await readFile(path, "utf-8").catch(() => "");
const pid = Number.parseInt(content, 10);
if (Number.isInteger(pid) && isAlive(pid)) return pid;

await unlink(path).catch(() => {});
return null;
}

/**
* Runs `fn` while holding the workspace's state lock, so lo1 commands that
* read, change and write the state file (restarts) never interleave. Waits
* for a running holder and takes over a lock whose holder has exited.
*/
export async function withWorkspaceLock<T>(
workspaceDir: string,
fn: () => Promise<T>,
options: WorkspaceLockOptions = {},
): Promise<T> {
const { timeoutMs = 120_000, pollMs = 100, isAlive = isProcessAlive } = options;
const path = lockPath(workspaceDir);
await mkdir(join(workspaceDir, ".lo1"), { recursive: true });

const deadline = Date.now() + timeoutMs;
while (!(await tryAcquire(path))) {

Check warning on line 81 in packages/cli/src/orchestrator/lock.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_lo1&issues=AaHolgK-cWhJbf0ONTko&open=AaHolgK-cWhJbf0ONTko&pullRequest=26
const holder = await liveHolder(path, isAlive);

Check warning on line 82 in packages/cli/src/orchestrator/lock.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_lo1&issues=AaHolgK-cWhJbf0ONTkp&open=AaHolgK-cWhJbf0ONTkp&pullRequest=26
if (holder === null) continue;
if (Date.now() >= deadline) {
throw new WorkspaceLockError(
`Another lo1 command (pid ${holder}) is still changing this workspace. ` +
`Wait for it to finish, then try again.`,
);
}
await new Promise((r) => setTimeout(r, pollMs));

Check warning on line 90 in packages/cli/src/orchestrator/lock.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=newstack-cloud_lo1&issues=AaHolgK-cWhJbf0ONTkq&open=AaHolgK-cWhJbf0ONTkq&pullRequest=26
}

debug("acquired %s", path);
try {
return await fn();
} finally {
await unlink(path).catch(() => {});
debug("released %s", path);
}
}
76 changes: 76 additions & 0 deletions packages/cli/src/orchestrator/restart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { resolve } from "node:path";
import type { Plugin, WorkspaceConfig } from "@lo1/sdk";
import type { EndpointRegistry } from "../discovery/registry";
import { createLog } from "../debug";
import { runServicePreStop } from "./stop";
import type { ComposeContext, ServiceHandle } from "./service";
import type { OrchestratorDeps, OrchestratorEvent } from "./types";

const debug = createLog("orchestrator:restart");

/** Everything needed to start a service again outside the initial `lo1 up`. */
export type RestartContext = {
config: WorkspaceConfig;
workspaceDir: string;
registry: EndpointRegistry;
plugins: Map<string, Plugin>;
pluginEnvVars: Record<string, string>;
compose: ComposeContext;
/** Restarted host processes outlive the command that restarted them. */
detached: boolean;
signal?: AbortSignal;
emit: (event: OrchestratorEvent) => void;
deps: Pick<OrchestratorDeps, "startService" | "executeHook">;
};

/**
* Stops a service (running its preStop hook) and starts it again, waiting
* for it to be ready. An init task is simply run again and waited on.
*/
export async function restartService(
name: string,
current: ServiceHandle | undefined,
ctx: RestartContext,
): Promise<ServiceHandle> {
const serviceConfig = ctx.config.services[name];
debug("restartService: %s (init task: %s)", name, serviceConfig.initTask);

if (current?.running && !serviceConfig.initTask) {
ctx.emit({ kind: "service", service: name, status: "stopping" });
await runServicePreStop({
handle: current,
config: ctx.config,
workspaceDir: ctx.workspaceDir,
pluginEnvVars: ctx.pluginEnvVars,
executeHook: ctx.deps.executeHook,
emit: ctx.emit,
signal: ctx.signal,
});
await current.stop();
current.releaseLogs?.();
ctx.emit({ kind: "service", service: name, status: "stopped" });
}

ctx.emit({ kind: "service", service: name, status: "starting" });
const handle = await ctx.deps.startService({
serviceName: name,
serviceConfig,
config: ctx.config,
plugin: ctx.plugins.get(serviceConfig.type),
registry: ctx.registry,
pluginEnvVars: ctx.pluginEnvVars,
workspaceDir: resolve(ctx.workspaceDir),
compose: ctx.compose,
detached: ctx.detached,
recreate: true,
signal: ctx.signal,
onOutput: (line) => ctx.emit({ kind: "output", line }),
onHookOutput: (output) => ctx.emit({ kind: "hook", hook: name, output }),
});
ctx.emit({
kind: "service",
service: name,
status: serviceConfig.initTask ? "completed" : "started",
});
return handle;
}
Loading
Loading