Skip to content

Commit 36554c2

Browse files
authored
refactor(daemon): consolidate managed service lifecycle ownership (#119647)
1 parent 21b6478 commit 36554c2

9 files changed

Lines changed: 98 additions & 202 deletions

‎src/daemon/constants.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ export const GATEWAY_SERVICE_RUNTIME_PID_ENV = "OPENCLAW_GATEWAY_SERVICE_PID";
1111
const NODE_LAUNCH_AGENT_LABEL = "ai.openclaw.node";
1212
const NODE_SYSTEMD_SERVICE_NAME = "openclaw-node";
1313
const NODE_WINDOWS_TASK_NAME = "OpenClaw Node";
14-
export const NODE_SERVICE_MARKER = "openclaw";
14+
const NODE_SERVICE_MARKER = "openclaw";
1515
export const NODE_SERVICE_KIND = "node";
16-
export const NODE_WINDOWS_TASK_SCRIPT_NAME = "node.cmd";
16+
const NODE_WINDOWS_TASK_SCRIPT_NAME = "node.cmd";
1717
export const LEGACY_GATEWAY_SYSTEMD_SERVICE_NAMES: string[] = ["clawdbot-gateway"];
1818

1919
function normalizeGatewayProfile(profile?: string): string | null {
@@ -137,6 +137,19 @@ export function resolveNodeWindowsTaskName(): string {
137137
return NODE_WINDOWS_TASK_NAME;
138138
}
139139

140+
export function resolveNodeServiceIdentityEnvironment(): Record<string, string> {
141+
return {
142+
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
143+
OPENCLAW_SYSTEMD_UNIT: resolveNodeSystemdServiceName(),
144+
OPENCLAW_WINDOWS_TASK_NAME: resolveNodeWindowsTaskName(),
145+
OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER: "1",
146+
OPENCLAW_TASK_SCRIPT_NAME: NODE_WINDOWS_TASK_SCRIPT_NAME,
147+
OPENCLAW_LOG_PREFIX: "node",
148+
OPENCLAW_SERVICE_MARKER: NODE_SERVICE_MARKER,
149+
OPENCLAW_SERVICE_KIND: NODE_SERVICE_KIND,
150+
};
151+
}
152+
140153
export function formatNodeServiceDescription(params?: { version?: string }): string {
141154
const version = params?.version?.trim();
142155
if (!version) {

‎src/daemon/node-service.ts‎

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,5 @@
11
/** Adapts the generic gateway service manager for OpenClaw node-host services. */
2-
import {
3-
NODE_SERVICE_KIND,
4-
NODE_SERVICE_MARKER,
5-
NODE_WINDOWS_TASK_SCRIPT_NAME,
6-
resolveNodeLaunchAgentLabel,
7-
resolveNodeSystemdServiceName,
8-
resolveNodeWindowsTaskName,
9-
} from "./constants.js";
2+
import { resolveNodeServiceIdentityEnvironment } from "./constants.js";
103
import type { GatewayService, GatewayServiceInstallArgs } from "./service.js";
114
import { resolveGatewayService } from "./service.js";
125

@@ -18,14 +11,7 @@ function withNodeServiceEnv(
1811
// node-specific labels, logs, task script, and service marker.
1912
return {
2013
...env,
21-
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
22-
OPENCLAW_SYSTEMD_UNIT: resolveNodeSystemdServiceName(),
23-
OPENCLAW_WINDOWS_TASK_NAME: resolveNodeWindowsTaskName(),
24-
OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER: "1",
25-
OPENCLAW_TASK_SCRIPT_NAME: NODE_WINDOWS_TASK_SCRIPT_NAME,
26-
OPENCLAW_LOG_PREFIX: "node",
27-
OPENCLAW_SERVICE_MARKER: NODE_SERVICE_MARKER,
28-
OPENCLAW_SERVICE_KIND: NODE_SERVICE_KIND,
14+
...resolveNodeServiceIdentityEnvironment(),
2915
};
3016
}
3117

‎src/daemon/service-audit.ts‎

Lines changed: 3 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,7 @@ import {
55
normalizeLowercaseStringOrEmpty,
66
normalizeOptionalString,
77
} from "@openclaw/normalization-core/string-coerce";
8-
import {
9-
normalizeStringEntries,
10-
sortUniqueStrings,
11-
} from "@openclaw/normalization-core/string-normalization";
12-
import { normalizeEnvVarKey } from "../infra/host-env-security.js";
8+
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
139
import { resolveInlineCommandMatch } from "../infra/shell-inline-command.js";
1410
import { POSIX_SHELL_WRAPPERS } from "../infra/shell-wrapper-resolution.js";
1511
import { parseTcpPort } from "../infra/tcp-port.js";
@@ -25,9 +21,8 @@ import { getMinimalServicePathPartsFromEnv } from "./service-env.js";
2521
import { SERVICE_PROXY_ENV_KEYS } from "./service-env.js";
2622
import {
2723
collectInlineManagedServiceEnvKeys,
28-
hasInlineEnvironmentSource,
24+
collectInlineServiceEnvKeys,
2925
isEnvironmentFileOnlySource,
30-
readEnvironmentValueSource,
3126
} from "./service-managed-env.js";
3227
import { isNonMinimalServicePathEntry, normalizeServicePathEntry } from "./service-path-policy.js";
3328
import type { GatewayServiceEnvironmentValueSource } from "./service-types.js";
@@ -390,47 +385,11 @@ function auditManagedServiceEnvironment(
390385
});
391386
}
392387

393-
function normalizeServiceEnvKey(key: string): string | null {
394-
return normalizeEnvVarKey(key, { portable: true })?.toUpperCase() ?? null;
395-
}
396-
397-
const SERVICE_PROXY_ENV_KEY_SET = new Set(
398-
SERVICE_PROXY_ENV_KEYS.flatMap((key) => {
399-
const normalized = normalizeServiceEnvKey(key);
400-
return normalized ? [normalized] : [];
401-
}),
402-
);
403-
404-
function collectInlineProxyEnvKeys(command: GatewayServiceCommand): string[] {
405-
if (!command?.environment) {
406-
return [];
407-
}
408-
const inlineKeys: string[] = [];
409-
for (const [rawKey, value] of Object.entries(command.environment)) {
410-
if (typeof value !== "string" || !value.trim()) {
411-
continue;
412-
}
413-
const normalized = normalizeServiceEnvKey(rawKey);
414-
if (!normalized || !SERVICE_PROXY_ENV_KEY_SET.has(normalized)) {
415-
continue;
416-
}
417-
if (
418-
!hasInlineEnvironmentSource(
419-
readEnvironmentValueSource(command.environmentValueSources, normalized),
420-
)
421-
) {
422-
continue;
423-
}
424-
inlineKeys.push(normalized);
425-
}
426-
return sortUniqueStrings(inlineKeys);
427-
}
428-
429388
function auditProxyServiceEnvironment(
430389
command: GatewayServiceCommand,
431390
issues: ServiceConfigIssue[],
432391
) {
433-
const inlineKeys = collectInlineProxyEnvKeys(command);
392+
const inlineKeys = collectInlineServiceEnvKeys(command, SERVICE_PROXY_ENV_KEYS);
434393
if (inlineKeys.length === 0) {
435394
return;
436395
}

‎src/daemon/service-env-plan.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/** Builds normalized environment plans for managed daemon service rendering. */
2-
import { normalizeEnvVarKey } from "../infra/host-env-security.js";
2+
import { normalizeServiceEnvKey } from "./service-managed-env.js";
33
import type { GatewayServiceEnvironmentValueSource } from "./service-types.js";
44

55
export type MutableServiceEnvPlan = {
@@ -14,10 +14,6 @@ export function createMutableServiceEnvPlan(): MutableServiceEnvPlan {
1414
};
1515
}
1616

17-
export function normalizeServiceEnvPlanKey(rawKey: string): string | undefined {
18-
return normalizeEnvVarKey(rawKey, { portable: true })?.toUpperCase();
19-
}
20-
2117
export function addServiceEnvPlanEntries(
2218
plan: MutableServiceEnvPlan,
2319
entries: Record<string, string | undefined>,
@@ -42,7 +38,7 @@ export function addServiceEnvPlanEntries(
4238
continue;
4339
}
4440
const value = rawValue;
45-
const normalizedKey = normalizeServiceEnvPlanKey(rawKey);
41+
const normalizedKey = normalizeServiceEnvKey(rawKey);
4642
if (!normalizedKey) {
4743
continue;
4844
}

‎src/daemon/service-env-render-policy.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** Applies platform render policy for managed daemon service environment values. */
2-
import { normalizeServiceEnvPlanKey, type MutableServiceEnvPlan } from "./service-env-plan.js";
2+
import type { MutableServiceEnvPlan } from "./service-env-plan.js";
33
import {
4+
normalizeServiceEnvKey,
45
readManagedServiceEnvKeysFromEnvironment,
56
writeManagedServiceEnvKeysToEnvironment,
67
} from "./service-managed-env.js";
@@ -26,7 +27,7 @@ function addManagedServiceEnvEntries(params: {
2627
if (typeof value !== "string" || !value.trim()) {
2728
continue;
2829
}
29-
const key = normalizeServiceEnvPlanKey(rawKey);
30+
const key = normalizeServiceEnvKey(rawKey);
3031
if (!key || !params.managedKeys.has(key)) {
3132
continue;
3233
}

‎src/daemon/service-env.ts‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,7 @@ import {
1111
resolveGatewayLaunchAgentLabel,
1212
resolveGatewaySystemdServiceName,
1313
resolveGatewayWindowsTaskName,
14-
NODE_SERVICE_KIND,
15-
NODE_SERVICE_MARKER,
16-
NODE_WINDOWS_TASK_SCRIPT_NAME,
17-
resolveNodeLaunchAgentLabel,
18-
resolveNodeSystemdServiceName,
19-
resolveNodeWindowsTaskName,
14+
resolveNodeServiceIdentityEnvironment,
2015
} from "./constants.js";
2116
import { resolveGatewayHeapNodeOptions } from "./gateway-heap.js";
2217
import { resolveGatewayStateDir } from "./paths.js";
@@ -395,14 +390,7 @@ export function buildNodeServiceEnvironment(params: {
395390
OPENCLAW_GATEWAY_TOKEN: gatewayToken,
396391
OPENCLAW_GATEWAY_PASSWORD: gatewayPassword,
397392
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS: allowInsecurePrivateWs,
398-
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
399-
OPENCLAW_SYSTEMD_UNIT: resolveNodeSystemdServiceName(),
400-
OPENCLAW_WINDOWS_TASK_NAME: resolveNodeWindowsTaskName(),
401-
OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER: "1",
402-
OPENCLAW_TASK_SCRIPT_NAME: NODE_WINDOWS_TASK_SCRIPT_NAME,
403-
OPENCLAW_LOG_PREFIX: "node",
404-
OPENCLAW_SERVICE_MARKER: NODE_SERVICE_MARKER,
405-
OPENCLAW_SERVICE_KIND: NODE_SERVICE_KIND,
393+
...resolveNodeServiceIdentityEnvironment(),
406394
OPENCLAW_SERVICE_VERSION: VERSION,
407395
};
408396
}

‎src/daemon/service-managed-env.ts‎

Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,19 @@ type ServiceEnvCommand = {
1111
environmentValueSources?: Record<string, GatewayServiceEnvironmentValueSource | undefined>;
1212
} | null;
1313

14-
function normalizeServiceEnvKey(key: string): string | null {
14+
export function normalizeServiceEnvKey(key: string): string | null {
1515
return normalizeEnvVarKey(key, { portable: true })?.toUpperCase() ?? null;
1616
}
1717

18+
export function normalizeServiceEnvKeys(keys: Iterable<string>): Set<string> {
19+
return new Set(
20+
[...keys].flatMap((key) => {
21+
const normalized = normalizeServiceEnvKey(key);
22+
return normalized ? [normalized] : [];
23+
}),
24+
);
25+
}
26+
1827
export function hasInlineEnvironmentSource(
1928
source: GatewayServiceEnvironmentValueSource | undefined,
2029
): boolean {
@@ -34,34 +43,17 @@ export function hasEnvironmentFileSource(
3443
}
3544

3645
function parseManagedServiceEnvKeys(value: string | undefined): Set<string> {
37-
const keys = new Set<string>();
38-
for (const entry of value?.split(",") ?? []) {
39-
const key = normalizeServiceEnvKey(entry.trim());
40-
if (key) {
41-
keys.add(key);
42-
}
43-
}
44-
return keys;
46+
return normalizeServiceEnvKeys(value?.split(",") ?? []);
4547
}
4648

4749
export function formatManagedServiceEnvKeys(
4850
managedEnvironment: Record<string, string | undefined>,
4951
options?: { omitKeys?: Iterable<string> },
5052
): string | undefined {
51-
const omitKeys = new Set(
52-
[...(options?.omitKeys ?? [])].flatMap((key) => {
53-
const normalized = normalizeServiceEnvKey(key);
54-
return normalized ? [normalized] : [];
55-
}),
56-
);
53+
const omitKeys = normalizeServiceEnvKeys(options?.omitKeys ?? []);
5754
const keys = Object.keys(managedEnvironment)
58-
.flatMap((key) => {
59-
const normalized = normalizeServiceEnvKey(key);
60-
if (!normalized || omitKeys.has(normalized)) {
61-
return [];
62-
}
63-
return [normalized];
64-
})
55+
.map(normalizeServiceEnvKey)
56+
.filter((key): key is string => Boolean(key && !omitKeys.has(key)))
6557
.toSorted();
6658
return keys.length > 0 ? keys.join(",") : undefined;
6759
}
@@ -84,12 +76,7 @@ function deleteManagedServiceEnvKeys(
8476
environment: Record<string, string | undefined>,
8577
keys: Iterable<string>,
8678
): void {
87-
const normalizedKeys = new Set(
88-
[...keys].flatMap((key) => {
89-
const normalized = normalizeServiceEnvKey(key);
90-
return normalized ? [normalized] : [];
91-
}),
92-
);
79+
const normalizedKeys = normalizeServiceEnvKeys(keys);
9380
if (normalizedKeys.size === 0) {
9481
return;
9582
}
@@ -140,13 +127,21 @@ export function collectInlineManagedServiceEnvKeys(
140127
return [];
141128
}
142129
const managedKeys = parseManagedServiceEnvKeys(command.environment[MANAGED_SERVICE_ENV_KEYS_VAR]);
143-
for (const key of expectedManagedKeys ?? []) {
144-
const normalized = normalizeServiceEnvKey(key);
145-
if (normalized) {
146-
managedKeys.add(normalized);
147-
}
130+
for (const key of normalizeServiceEnvKeys(expectedManagedKeys ?? [])) {
131+
managedKeys.add(key);
132+
}
133+
return collectInlineServiceEnvKeys(command, managedKeys);
134+
}
135+
136+
export function collectInlineServiceEnvKeys(
137+
command: ServiceEnvCommand,
138+
expectedKeys: Iterable<string>,
139+
): string[] {
140+
if (!command?.environment) {
141+
return [];
148142
}
149-
if (managedKeys.size === 0) {
143+
const normalizedKeys = normalizeServiceEnvKeys(expectedKeys);
144+
if (normalizedKeys.size === 0) {
150145
return [];
151146
}
152147
const inlineKeys: string[] = [];
@@ -155,7 +150,7 @@ export function collectInlineManagedServiceEnvKeys(
155150
continue;
156151
}
157152
const normalized = normalizeServiceEnvKey(rawKey);
158-
if (!normalized || !managedKeys.has(normalized)) {
153+
if (!normalized || !normalizedKeys.has(normalized)) {
159154
continue;
160155
}
161156
if (normalized === MANAGED_SERVICE_ENV_KEYS_VAR) {

‎src/daemon/service.ts‎

Lines changed: 19 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -380,54 +380,31 @@ const GATEWAY_SERVICE_REGISTRY: Record<SupportedGatewayServicePlatform, GatewayS
380380
},
381381
};
382382

383-
function assertGatewayServiceMutationOwnedByOpenClaw(
383+
function guardGatewayServiceMutation<TArgs extends { env?: GatewayServiceEnv }, TResult>(
384384
action: string,
385-
env?: GatewayServiceEnv,
386-
): void {
387-
assertGatewayServiceMutationAllowed(action, process.env);
388-
if (env && env !== process.env) {
389-
assertGatewayServiceMutationAllowed(action, env);
390-
}
385+
mutate: (args: TArgs) => Promise<TResult>,
386+
): (args: TArgs) => Promise<TResult> {
387+
return async (args) => {
388+
// Mutations must satisfy both lifecycle ownership and durable-config
389+
// version guards before invoking any platform service manager.
390+
assertGatewayServiceMutationAllowed(action, process.env);
391+
if (args.env && args.env !== process.env) {
392+
assertGatewayServiceMutationAllowed(action, args.env);
393+
}
394+
await assertFutureConfigActionAllowed(action);
395+
return await mutate(args);
396+
};
391397
}
392398

393399
function withGatewayServiceMutationGuards(service: GatewayService): GatewayService {
394400
return {
395401
...service,
396-
stage: async (args) => {
397-
// Service mutations rewrite durable launchd/systemd/schtasks files, so
398-
// block them when config was produced by a newer OpenClaw.
399-
assertGatewayServiceMutationOwnedByOpenClaw("rewrite the gateway service", args.env);
400-
await assertFutureConfigActionAllowed("rewrite the gateway service");
401-
return await service.stage(args);
402-
},
403-
install: async (args) => {
404-
assertGatewayServiceMutationOwnedByOpenClaw(
405-
"install or rewrite the gateway service",
406-
args.env,
407-
);
408-
await assertFutureConfigActionAllowed("install or rewrite the gateway service");
409-
return await service.install(args);
410-
},
411-
uninstall: async (args) => {
412-
assertGatewayServiceMutationOwnedByOpenClaw("uninstall the gateway service", args.env);
413-
await assertFutureConfigActionAllowed("uninstall the gateway service");
414-
return await service.uninstall(args);
415-
},
416-
start: async (args) => {
417-
assertGatewayServiceMutationOwnedByOpenClaw("start the gateway service", args.env);
418-
await assertFutureConfigActionAllowed("start the gateway service");
419-
return await service.start(args);
420-
},
421-
stop: async (args) => {
422-
assertGatewayServiceMutationOwnedByOpenClaw("stop the gateway service", args.env);
423-
await assertFutureConfigActionAllowed("stop the gateway service");
424-
return await service.stop(args);
425-
},
426-
restart: async (args) => {
427-
assertGatewayServiceMutationOwnedByOpenClaw("restart the gateway service", args.env);
428-
await assertFutureConfigActionAllowed("restart the gateway service");
429-
return await service.restart(args);
430-
},
402+
stage: guardGatewayServiceMutation("rewrite the gateway service", service.stage),
403+
install: guardGatewayServiceMutation("install or rewrite the gateway service", service.install),
404+
uninstall: guardGatewayServiceMutation("uninstall the gateway service", service.uninstall),
405+
start: guardGatewayServiceMutation("start the gateway service", service.start),
406+
stop: guardGatewayServiceMutation("stop the gateway service", service.stop),
407+
restart: guardGatewayServiceMutation("restart the gateway service", service.restart),
431408
};
432409
}
433410

0 commit comments

Comments
 (0)