agent-neckbeard 1.1.18 → 1.1.19
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/CHANGELOG.md +26 -0
- package/README.md +171 -67
- package/dist/chunk-33IXN6MM.js +21 -0
- package/dist/chunk-3EB4CT5S.js +2516 -0
- package/dist/{chunk-AM2J5KBI.js → chunk-DHFC3O44.js} +4 -8
- package/dist/index.cjs +3646 -535
- package/dist/index.d.cts +150 -56
- package/dist/index.d.ts +150 -56
- package/dist/index.js +1161 -501
- package/dist/{invoke-client-XEH6FVRH.js → invoke-client-D5TMTOYM.js} +2 -1
- package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +77 -0
- package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +77 -0
- package/dist/supervisor.cjs +6043 -0
- package/dist/supervisor.d.cts +470 -0
- package/dist/supervisor.d.ts +470 -0
- package/dist/supervisor.js +3535 -0
- package/docs/SUPERVISOR.md +248 -0
- package/package.json +20 -8
|
@@ -0,0 +1,2516 @@
|
|
|
1
|
+
// src/sandbox-capabilities.ts
|
|
2
|
+
var SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";
|
|
3
|
+
var SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";
|
|
4
|
+
var SUPERVISOR_ENVIRONMENT_FD = 3;
|
|
5
|
+
var SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;
|
|
6
|
+
var SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;
|
|
7
|
+
var SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;
|
|
8
|
+
var SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
9
|
+
function supervisorEnvironmentByteLength(value) {
|
|
10
|
+
return new TextEncoder().encode(value).byteLength;
|
|
11
|
+
}
|
|
12
|
+
function isRecord(value) {
|
|
13
|
+
if (typeof value !== "object" || value === null) return false;
|
|
14
|
+
try {
|
|
15
|
+
return !Array.isArray(value);
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function normalizeSupervisorEnvironment(value) {
|
|
21
|
+
if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };
|
|
22
|
+
let entries;
|
|
23
|
+
try {
|
|
24
|
+
entries = Object.entries(value).sort(
|
|
25
|
+
([left], [right]) => left < right ? -1 : left > right ? 1 : 0
|
|
26
|
+
);
|
|
27
|
+
} catch {
|
|
28
|
+
return { ok: false, reason: "invalid_environment" };
|
|
29
|
+
}
|
|
30
|
+
if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {
|
|
31
|
+
return { ok: false, reason: "entry_limit" };
|
|
32
|
+
}
|
|
33
|
+
const environment = /* @__PURE__ */ Object.create(null);
|
|
34
|
+
let environmentBytes = 0;
|
|
35
|
+
let exceedsByteLimit = false;
|
|
36
|
+
for (const [name, item] of entries) {
|
|
37
|
+
if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {
|
|
38
|
+
return { ok: false, reason: "invalid_name" };
|
|
39
|
+
}
|
|
40
|
+
if (typeof item !== "string" || item.includes("\0")) {
|
|
41
|
+
return { ok: false, reason: "invalid_value" };
|
|
42
|
+
}
|
|
43
|
+
if (!exceedsByteLimit) {
|
|
44
|
+
if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
|
|
45
|
+
exceedsByteLimit = true;
|
|
46
|
+
} else {
|
|
47
|
+
environmentBytes += name.length + supervisorEnvironmentByteLength(item);
|
|
48
|
+
if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
|
|
49
|
+
exceedsByteLimit = true;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
environment[name] = item;
|
|
54
|
+
}
|
|
55
|
+
if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };
|
|
56
|
+
return {
|
|
57
|
+
ok: true,
|
|
58
|
+
environment,
|
|
59
|
+
environmentKeys: entries.map(([name]) => name)
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function serializeSupervisorEnvironmentHandoff(value, defaults) {
|
|
63
|
+
let normalized = normalizeSupervisorEnvironment(value);
|
|
64
|
+
if (!normalized.ok) return normalized;
|
|
65
|
+
if (defaults !== void 0) {
|
|
66
|
+
const normalizedDefaults = normalizeSupervisorEnvironment(defaults);
|
|
67
|
+
if (!normalizedDefaults.ok) return normalizedDefaults;
|
|
68
|
+
const environment = Object.assign(
|
|
69
|
+
/* @__PURE__ */ Object.create(null),
|
|
70
|
+
normalizedDefaults.environment,
|
|
71
|
+
normalized.environment
|
|
72
|
+
);
|
|
73
|
+
normalized = normalizeSupervisorEnvironment(environment);
|
|
74
|
+
if (!normalized.ok) return normalized;
|
|
75
|
+
}
|
|
76
|
+
let payload;
|
|
77
|
+
try {
|
|
78
|
+
payload = JSON.stringify({ version: 1, environment: normalized.environment });
|
|
79
|
+
} catch {
|
|
80
|
+
return { ok: false, reason: "serialization_failed" };
|
|
81
|
+
}
|
|
82
|
+
if (payload.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(payload) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
|
|
83
|
+
return { ok: false, reason: "byte_limit" };
|
|
84
|
+
}
|
|
85
|
+
return { ...normalized, payload };
|
|
86
|
+
}
|
|
87
|
+
function normalizeProviderSandboxDetachedCommandOptions(value, failure, policy = {}) {
|
|
88
|
+
if (policy.requireObject) {
|
|
89
|
+
try {
|
|
90
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
91
|
+
throw new Error("invalid detached command options");
|
|
92
|
+
}
|
|
93
|
+
} catch {
|
|
94
|
+
throw failure("Detached command options could not be inspected.");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let cwd;
|
|
98
|
+
let rawEnvironment;
|
|
99
|
+
let launchId;
|
|
100
|
+
let beforeRelease;
|
|
101
|
+
let environmentMode;
|
|
102
|
+
let environmentRevision;
|
|
103
|
+
let restartReleasedWhenExited;
|
|
104
|
+
try {
|
|
105
|
+
cwd = Reflect.get(value, "cwd");
|
|
106
|
+
rawEnvironment = Reflect.get(value, "envs");
|
|
107
|
+
launchId = Reflect.get(value, "launchId");
|
|
108
|
+
beforeRelease = Reflect.get(value, "beforeRelease");
|
|
109
|
+
environmentMode = Reflect.get(value, "environmentMode");
|
|
110
|
+
environmentRevision = Reflect.get(value, "environmentRevision");
|
|
111
|
+
restartReleasedWhenExited = Reflect.get(
|
|
112
|
+
value,
|
|
113
|
+
"restartReleasedWhenExited"
|
|
114
|
+
);
|
|
115
|
+
} catch {
|
|
116
|
+
throw failure("Detached command options could not be inspected.");
|
|
117
|
+
}
|
|
118
|
+
if (cwd !== void 0 && typeof cwd !== "string") {
|
|
119
|
+
throw failure("Detached command cwd must be a string when provided.");
|
|
120
|
+
}
|
|
121
|
+
if (policy.validateBeforeRelease && beforeRelease !== void 0 && typeof beforeRelease !== "function") {
|
|
122
|
+
throw failure("Detached command beforeRelease must be a function.");
|
|
123
|
+
}
|
|
124
|
+
const options = {
|
|
125
|
+
cwd,
|
|
126
|
+
envs: rawEnvironment,
|
|
127
|
+
launchId,
|
|
128
|
+
beforeRelease,
|
|
129
|
+
environmentMode,
|
|
130
|
+
environmentRevision,
|
|
131
|
+
restartReleasedWhenExited
|
|
132
|
+
};
|
|
133
|
+
return {
|
|
134
|
+
options,
|
|
135
|
+
environment: {
|
|
136
|
+
environmentMode,
|
|
137
|
+
environmentRevision,
|
|
138
|
+
restartReleasedWhenExited,
|
|
139
|
+
rawEnvironment
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/shell.ts
|
|
145
|
+
function shellQuote(value) {
|
|
146
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/providers/detached-process.ts
|
|
150
|
+
import { isUtf8 } from "buffer";
|
|
151
|
+
import { createHash, randomUUID } from "crypto";
|
|
152
|
+
var DETACHED_PROCESS_ROOT = "/tmp/agent-neckbeard-detached";
|
|
153
|
+
var DETACHED_PROCESS_CONTROL_TIMEOUT_MS = 3e4;
|
|
154
|
+
var DETACHED_PROCESS_LOG_MAX_BYTES = 8 * 1024 * 1024;
|
|
155
|
+
var DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES = 64 * 1024;
|
|
156
|
+
var DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES = 256 + 8 * Math.ceil(DETACHED_PROCESS_LOG_MAX_BYTES / 3);
|
|
157
|
+
var DETACHED_PROCESS_TRUSTED_PATH = "/usr/local/share/nvm/current/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
|
158
|
+
var DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT = {
|
|
159
|
+
PATH: DETACHED_PROCESS_TRUSTED_PATH,
|
|
160
|
+
HOME: "/tmp",
|
|
161
|
+
TMPDIR: "/tmp",
|
|
162
|
+
LANG: "C.UTF-8"
|
|
163
|
+
};
|
|
164
|
+
var DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT = Object.freeze({
|
|
165
|
+
...DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT,
|
|
166
|
+
HOME: "/nonexistent",
|
|
167
|
+
BASH_ENV: "/dev/null",
|
|
168
|
+
ENV: "/dev/null",
|
|
169
|
+
SHELLOPTS: "",
|
|
170
|
+
BASHOPTS: "",
|
|
171
|
+
PS4: "+ ",
|
|
172
|
+
BASH_XTRACEFD: ""
|
|
173
|
+
});
|
|
174
|
+
var DETACHED_PROCESS_LOG_CHUNK_BYTES = 64 * 1024;
|
|
175
|
+
var DETACHED_PROCESS_LOG_SEGMENT_BYTES = DETACHED_PROCESS_LOG_MAX_BYTES / 2 - DETACHED_PROCESS_LOG_CHUNK_BYTES;
|
|
176
|
+
var DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES = 96;
|
|
177
|
+
var DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS = 100;
|
|
178
|
+
var IDENTITY_PREFIX = "NECKBEARD_PROCESS_V3";
|
|
179
|
+
var LEGACY_IDENTITY_PREFIX = "NECKBEARD_PROCESS_V2";
|
|
180
|
+
var DECISION_PREFIX = "NECKBEARD_DECISION_V1";
|
|
181
|
+
var STARTED_PREFIX = "NECKBEARD_STARTED_V1";
|
|
182
|
+
var QUIESCENT_PREFIX = "NECKBEARD_QUIESCENT_V1";
|
|
183
|
+
var PREPARED_SENTINEL = "NECKBEARD_DETACHED_PREPARED";
|
|
184
|
+
var RELEASED_SENTINEL = "NECKBEARD_DETACHED_RELEASED";
|
|
185
|
+
var RELEASED_GENERATION_UNAVAILABLE_SENTINEL = "NECKBEARD_DETACHED_RELEASED_GENERATION_UNAVAILABLE";
|
|
186
|
+
var CANCELLED_SENTINEL = "NECKBEARD_DETACHED_CANCELLED";
|
|
187
|
+
var STOPPED_SENTINEL = "NECKBEARD_DETACHED_STOPPED";
|
|
188
|
+
var DISPOSED_SENTINEL = "NECKBEARD_DETACHED_ARTIFACTS_DISPOSED";
|
|
189
|
+
var LOGS_PREFIX = "NECKBEARD_DETACHED_LOGS_V1";
|
|
190
|
+
var LEGACY_LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V1";
|
|
191
|
+
var LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V2";
|
|
192
|
+
var DESCRIPTOR_MISMATCH_SENTINEL = "NECKBEARD_DETACHED_DESCRIPTOR_MISMATCH";
|
|
193
|
+
var HASH_PATTERN = "[a-f0-9]{64}";
|
|
194
|
+
var PREPARED_PATTERN = new RegExp(
|
|
195
|
+
`^${PREPARED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
|
|
196
|
+
"u"
|
|
197
|
+
);
|
|
198
|
+
var RELEASED_PATTERN = new RegExp(
|
|
199
|
+
`^${RELEASED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
|
|
200
|
+
"u"
|
|
201
|
+
);
|
|
202
|
+
var HANDLE_PATTERN = new RegExp(
|
|
203
|
+
`^(daytona|e2b)-process-v2:(\\d+):(\\d+):(\\d+):(${HASH_PATTERN}):(${HASH_PATTERN})$`,
|
|
204
|
+
"u"
|
|
205
|
+
);
|
|
206
|
+
function boundDetachedProcessLog(value) {
|
|
207
|
+
const candidate = value.length > DETACHED_PROCESS_LOG_MAX_BYTES ? value.slice(-DETACHED_PROCESS_LOG_MAX_BYTES) : value;
|
|
208
|
+
const bytes = Buffer.from(candidate, "utf8");
|
|
209
|
+
if (bytes.byteLength <= DETACHED_PROCESS_LOG_MAX_BYTES) return candidate;
|
|
210
|
+
let offset = bytes.byteLength - DETACHED_PROCESS_LOG_MAX_BYTES;
|
|
211
|
+
while (offset < bytes.byteLength && ((bytes[offset] ?? 0) & 192) === 128) {
|
|
212
|
+
offset += 1;
|
|
213
|
+
}
|
|
214
|
+
return bytes.subarray(offset).toString("utf8");
|
|
215
|
+
}
|
|
216
|
+
var DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER = /* @__PURE__ */ Symbol.for(
|
|
217
|
+
"agent-neckbeard.detached-process-launch-cancelled.v1"
|
|
218
|
+
);
|
|
219
|
+
var DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER = /* @__PURE__ */ Symbol.for(
|
|
220
|
+
"agent-neckbeard.detached-process-released-generation-unavailable.v1"
|
|
221
|
+
);
|
|
222
|
+
var DetachedProcessLaunchCancelledError = class extends Error {
|
|
223
|
+
name = "DetachedProcessLaunchCancelledError";
|
|
224
|
+
[DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER] = true;
|
|
225
|
+
constructor() {
|
|
226
|
+
super("Detached process launch was cancelled before release.");
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
var DetachedProcessReleasedGenerationUnavailableError = class extends Error {
|
|
230
|
+
name = "DetachedProcessReleasedGenerationUnavailableError";
|
|
231
|
+
[DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER] = true;
|
|
232
|
+
constructor() {
|
|
233
|
+
super("Detached released process generation is unavailable.");
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
function isDetachedProcessLaunchCancelledError(error) {
|
|
237
|
+
return hasDetachedProcessErrorMarker(
|
|
238
|
+
error,
|
|
239
|
+
DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
function isDetachedProcessReleasedGenerationUnavailableError(error) {
|
|
243
|
+
return hasDetachedProcessErrorMarker(
|
|
244
|
+
error,
|
|
245
|
+
DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
function hasDetachedProcessErrorMarker(error, marker) {
|
|
249
|
+
if (typeof error !== "object" && typeof error !== "function" || error === null) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
return Reflect.get(error, marker) === true;
|
|
254
|
+
} catch {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
function markDetachedProcessLaunchCancelled(error) {
|
|
259
|
+
return markDetachedProcessError(error, DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER);
|
|
260
|
+
}
|
|
261
|
+
function markDetachedProcessReleasedGenerationUnavailable(error) {
|
|
262
|
+
return markDetachedProcessError(
|
|
263
|
+
error,
|
|
264
|
+
DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
function markDetachedProcessError(error, marker) {
|
|
268
|
+
if (typeof error !== "object" && typeof error !== "function" || error === null) {
|
|
269
|
+
return error;
|
|
270
|
+
}
|
|
271
|
+
try {
|
|
272
|
+
Reflect.defineProperty(error, marker, {
|
|
273
|
+
configurable: false,
|
|
274
|
+
enumerable: false,
|
|
275
|
+
value: true,
|
|
276
|
+
writable: false
|
|
277
|
+
});
|
|
278
|
+
} catch {
|
|
279
|
+
}
|
|
280
|
+
return error;
|
|
281
|
+
}
|
|
282
|
+
function messageFrom(error) {
|
|
283
|
+
return error instanceof Error ? error.message : String(error);
|
|
284
|
+
}
|
|
285
|
+
function hash(parts) {
|
|
286
|
+
return createHash("sha256").update(JSON.stringify(parts), "utf8").digest("hex");
|
|
287
|
+
}
|
|
288
|
+
function detachedEnvironmentFailureMessage(boundary, reason) {
|
|
289
|
+
const subject = `${boundary} environment`;
|
|
290
|
+
if (reason === "entry_limit") return `${subject} exceeds the entry limit.`;
|
|
291
|
+
if (reason === "invalid_name") {
|
|
292
|
+
return `${subject} contains an invalid or reserved name.`;
|
|
293
|
+
}
|
|
294
|
+
if (reason === "invalid_value") return `${subject} contains an invalid value.`;
|
|
295
|
+
if (reason === "byte_limit") return `${subject} exceeds the byte limit.`;
|
|
296
|
+
if (reason === "invalid_environment" && boundary === "Detached command") {
|
|
297
|
+
return `${subject} could not be inspected.`;
|
|
298
|
+
}
|
|
299
|
+
return `${subject} could not be serialized.`;
|
|
300
|
+
}
|
|
301
|
+
function serializeDetachedEnvironment(value, boundary, defaults) {
|
|
302
|
+
const handoff = serializeSupervisorEnvironmentHandoff(
|
|
303
|
+
value === void 0 ? {} : value,
|
|
304
|
+
defaults
|
|
305
|
+
);
|
|
306
|
+
if (!handoff.ok) {
|
|
307
|
+
throw new Error(detachedEnvironmentFailureMessage(boundary, handoff.reason));
|
|
308
|
+
}
|
|
309
|
+
return handoff;
|
|
310
|
+
}
|
|
311
|
+
function createDetachedEnvironmentTransport(options, genericPayloadEnvironmentDefaults) {
|
|
312
|
+
const {
|
|
313
|
+
environmentMode: mode,
|
|
314
|
+
environmentRevision,
|
|
315
|
+
restartReleasedWhenExited,
|
|
316
|
+
rawEnvironment
|
|
317
|
+
} = options;
|
|
318
|
+
const hasSupervisorControl = mode !== void 0 || environmentRevision !== void 0 || restartReleasedWhenExited !== void 0;
|
|
319
|
+
if (!hasSupervisorControl) {
|
|
320
|
+
const handoff2 = serializeDetachedEnvironment(
|
|
321
|
+
rawEnvironment,
|
|
322
|
+
"Detached command",
|
|
323
|
+
genericPayloadEnvironmentDefaults
|
|
324
|
+
);
|
|
325
|
+
return {
|
|
326
|
+
mode: "exec",
|
|
327
|
+
providerEnvironment: {
|
|
328
|
+
...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
|
|
329
|
+
[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff2.payload
|
|
330
|
+
},
|
|
331
|
+
environmentKeys: handoff2.environmentKeys
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
if (mode !== "supervisor-fd-v1" || typeof environmentRevision !== "string" || !/^[a-f0-9]{64}$/u.test(environmentRevision) || restartReleasedWhenExited !== true) {
|
|
335
|
+
throw new Error(
|
|
336
|
+
"Supervisor detached commands require FD mode, a lowercase SHA-256 environment revision, and exited-generation restart control."
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
const handoff = serializeDetachedEnvironment(rawEnvironment, "Supervisor");
|
|
340
|
+
return {
|
|
341
|
+
mode: "supervisor-fd-v1",
|
|
342
|
+
providerEnvironment: {
|
|
343
|
+
...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
|
|
344
|
+
[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff.payload
|
|
345
|
+
},
|
|
346
|
+
environmentKeys: handoff.environmentKeys,
|
|
347
|
+
environmentRevision
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
function createDetachedLaunchDescriptor(command, cwd, environment, restartReleasedWhenExited = false) {
|
|
351
|
+
return hash([
|
|
352
|
+
"detached-command-v2",
|
|
353
|
+
command,
|
|
354
|
+
cwd ?? null,
|
|
355
|
+
environment?.mode ?? "exec",
|
|
356
|
+
...environment?.environmentKeys ?? [],
|
|
357
|
+
...environment?.environmentRevision === void 0 ? [] : ["environment-revision-v1", environment.environmentRevision],
|
|
358
|
+
...restartReleasedWhenExited ? ["replacement-policy-v1"] : []
|
|
359
|
+
]);
|
|
360
|
+
}
|
|
361
|
+
function createDetachedLaunchPaths(launchId) {
|
|
362
|
+
const semanticId = launchId === void 0 ? randomUUID() : launchId;
|
|
363
|
+
if (typeof semanticId !== "string" || !semanticId || semanticId.length > 512) {
|
|
364
|
+
throw new Error("Detached command launchId must contain between 1 and 512 characters.");
|
|
365
|
+
}
|
|
366
|
+
const launchKey = hash(["detached-launch-v1", semanticId]);
|
|
367
|
+
return pathsForLaunchKey(launchKey);
|
|
368
|
+
}
|
|
369
|
+
function pathsForLaunchKey(launchKey) {
|
|
370
|
+
const directory = `${DETACHED_PROCESS_ROOT}/${launchKey}`;
|
|
371
|
+
return detachedLaunchPathsForDirectory(
|
|
372
|
+
launchKey,
|
|
373
|
+
directory,
|
|
374
|
+
`${DETACHED_PROCESS_ROOT}/${launchKey}.lock`,
|
|
375
|
+
`${DETACHED_PROCESS_ROOT}/.${launchKey}.retired`
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
function detachedLaunchPathsForDirectory(launchKey, directory, controlLock, retiredDirectory) {
|
|
379
|
+
return {
|
|
380
|
+
launchKey,
|
|
381
|
+
directory,
|
|
382
|
+
record: `${directory}/identity`,
|
|
383
|
+
recordPartial: `${directory}/.identity.partial`,
|
|
384
|
+
decision: `${directory}/decision`,
|
|
385
|
+
releaseDecisionPartial: `${directory}/.release-decision.partial`,
|
|
386
|
+
cancelDecisionPartial: `${directory}/.cancel-decision.partial`,
|
|
387
|
+
started: `${directory}/started`,
|
|
388
|
+
startedPartial: `${directory}/.started.partial`,
|
|
389
|
+
quiescent: `${directory}/quiescent`,
|
|
390
|
+
controlLock,
|
|
391
|
+
retiredDirectory,
|
|
392
|
+
stdout: `${directory}/stdout.log`,
|
|
393
|
+
stderr: `${directory}/stderr.log`
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
function pathsForDetachedLaunchDirectory(paths, directory) {
|
|
397
|
+
return detachedLaunchPathsForDirectory(
|
|
398
|
+
paths.launchKey,
|
|
399
|
+
directory,
|
|
400
|
+
paths.controlLock,
|
|
401
|
+
paths.retiredDirectory
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
function parseIdentityOutput(pattern, provider, paths, descriptorKey, output) {
|
|
405
|
+
const match = pattern.exec(output.trim());
|
|
406
|
+
if (!match) return null;
|
|
407
|
+
const [, pid, startTicks, sessionId, returnedDescriptor] = match;
|
|
408
|
+
if (!pid || !startTicks || !sessionId || !returnedDescriptor || pid !== sessionId || returnedDescriptor !== descriptorKey) {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
return { provider, pid, startTicks, sessionId, launchKey: paths.launchKey, descriptorKey };
|
|
412
|
+
}
|
|
413
|
+
function parsePreparedIdentity(provider, paths, descriptorKey, output) {
|
|
414
|
+
return parseIdentityOutput(PREPARED_PATTERN, provider, paths, descriptorKey, output);
|
|
415
|
+
}
|
|
416
|
+
function parseReleasedIdentity(provider, paths, descriptorKey, output) {
|
|
417
|
+
return parseIdentityOutput(RELEASED_PATTERN, provider, paths, descriptorKey, output);
|
|
418
|
+
}
|
|
419
|
+
function isDescriptorMismatch(output) {
|
|
420
|
+
return output.trim() === DESCRIPTOR_MISMATCH_SENTINEL;
|
|
421
|
+
}
|
|
422
|
+
function formatDetachedCommand(identity) {
|
|
423
|
+
return {
|
|
424
|
+
sessionId: `${identity.provider}-process-v2:${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.launchKey}:${identity.descriptorKey}`,
|
|
425
|
+
commandId: identity.pid
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function parseDetachedCommand(sessionId) {
|
|
429
|
+
const match = HANDLE_PATTERN.exec(sessionId);
|
|
430
|
+
if (!match) return null;
|
|
431
|
+
const [, provider, pid, startTicks, processSessionId, launchKey, descriptorKey] = match;
|
|
432
|
+
if (provider !== "daytona" && provider !== "e2b" || !pid || !startTicks || !processSessionId || !launchKey || !descriptorKey || pid !== processSessionId) {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
provider,
|
|
437
|
+
pid,
|
|
438
|
+
startTicks,
|
|
439
|
+
sessionId: processSessionId,
|
|
440
|
+
launchKey,
|
|
441
|
+
descriptorKey
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
function hasDetachedProcessV2Prefix(sessionId) {
|
|
445
|
+
return /^(?:daytona|e2b)-process-v2/u.test(sessionId);
|
|
446
|
+
}
|
|
447
|
+
function detachedProcessProviderName(provider) {
|
|
448
|
+
return provider === "daytona" ? "Daytona" : "E2B";
|
|
449
|
+
}
|
|
450
|
+
function resolveDetachedCommandForProvider(sessionId, expectedProvider, failure, commandId) {
|
|
451
|
+
const identity = parseDetachedCommand(sessionId);
|
|
452
|
+
if (identity?.provider === expectedProvider) {
|
|
453
|
+
if (commandId !== void 0 && commandId !== identity.pid) {
|
|
454
|
+
throw failure(
|
|
455
|
+
`Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
return identity;
|
|
459
|
+
}
|
|
460
|
+
if (identity || hasDetachedProcessV2Prefix(sessionId)) {
|
|
461
|
+
throw failure(
|
|
462
|
+
`Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
function pathsForIdentity(identity) {
|
|
468
|
+
return pathsForLaunchKey(identity.launchKey);
|
|
469
|
+
}
|
|
470
|
+
function disposedDirectoryForIdentity(identity) {
|
|
471
|
+
const disposalKey = hash([
|
|
472
|
+
"detached-disposal-v1",
|
|
473
|
+
identity.provider,
|
|
474
|
+
identity.pid,
|
|
475
|
+
identity.startTicks,
|
|
476
|
+
identity.sessionId,
|
|
477
|
+
identity.launchKey,
|
|
478
|
+
identity.descriptorKey
|
|
479
|
+
]);
|
|
480
|
+
return `${DETACHED_PROCESS_ROOT}/.${identity.launchKey}.${disposalKey}.disposed`;
|
|
481
|
+
}
|
|
482
|
+
var DetachedProcessController = class {
|
|
483
|
+
constructor(options) {
|
|
484
|
+
this.options = options;
|
|
485
|
+
}
|
|
486
|
+
get providerName() {
|
|
487
|
+
return detachedProcessProviderName(this.options.provider);
|
|
488
|
+
}
|
|
489
|
+
resolve(command) {
|
|
490
|
+
return resolveDetachedCommandForProvider(
|
|
491
|
+
command.sessionId,
|
|
492
|
+
this.options.provider,
|
|
493
|
+
this.options.failure,
|
|
494
|
+
command.commandId
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
async executeControl(command, options, stdoutMaxBytes = DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES) {
|
|
498
|
+
try {
|
|
499
|
+
const response = await this.options.execute(command, {
|
|
500
|
+
...options,
|
|
501
|
+
envs: options?.envs ?? {
|
|
502
|
+
...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT
|
|
503
|
+
}
|
|
504
|
+
});
|
|
505
|
+
if (!response || typeof response !== "object") {
|
|
506
|
+
throw new Error("invalid detached control response");
|
|
507
|
+
}
|
|
508
|
+
const state = Reflect.get(response, "state");
|
|
509
|
+
if (state === "failed") {
|
|
510
|
+
return {
|
|
511
|
+
state: "failed",
|
|
512
|
+
error: new Error(`${this.providerName} detached command control request failed.`)
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
if (state !== "completed") {
|
|
516
|
+
throw new Error("invalid detached control response");
|
|
517
|
+
}
|
|
518
|
+
const result = Reflect.get(response, "result");
|
|
519
|
+
if (!result || typeof result !== "object") {
|
|
520
|
+
throw new Error("invalid detached control result");
|
|
521
|
+
}
|
|
522
|
+
const exitCode = Reflect.get(result, "exitCode");
|
|
523
|
+
const stdout = Reflect.get(result, "stdout");
|
|
524
|
+
const stderr = Reflect.get(result, "stderr");
|
|
525
|
+
if (typeof exitCode !== "number" || !Number.isSafeInteger(exitCode) || typeof stdout !== "string" || typeof stderr !== "string" || stdout.length > stdoutMaxBytes || stderr.length > DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES || Buffer.byteLength(stdout, "utf8") > stdoutMaxBytes || Buffer.byteLength(stderr, "utf8") > DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES) {
|
|
526
|
+
throw new Error("invalid detached control result");
|
|
527
|
+
}
|
|
528
|
+
return {
|
|
529
|
+
state: "completed",
|
|
530
|
+
result: { exitCode, stdout, stderr }
|
|
531
|
+
};
|
|
532
|
+
} catch {
|
|
533
|
+
return {
|
|
534
|
+
state: "failed",
|
|
535
|
+
error: new Error(`${this.providerName} detached command control request failed.`)
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
async start(command, options = {}) {
|
|
540
|
+
if (typeof command !== "string") {
|
|
541
|
+
throw this.options.failure("Detached command must be a string.");
|
|
542
|
+
}
|
|
543
|
+
const normalized = normalizeProviderSandboxDetachedCommandOptions(
|
|
544
|
+
options,
|
|
545
|
+
this.options.failure,
|
|
546
|
+
{ validateBeforeRelease: true }
|
|
547
|
+
);
|
|
548
|
+
const inspectedOptions = normalized.options;
|
|
549
|
+
const environment = createDetachedEnvironmentTransport(
|
|
550
|
+
normalized.environment,
|
|
551
|
+
this.options.genericPayloadEnvironmentDefaults
|
|
552
|
+
);
|
|
553
|
+
const protectProviderDiagnostics = environment.mode === "supervisor-fd-v1";
|
|
554
|
+
const restartReleasedWhenExited = protectProviderDiagnostics;
|
|
555
|
+
const paths = createDetachedLaunchPaths(inspectedOptions.launchId);
|
|
556
|
+
const descriptorKey = createDetachedLaunchDescriptor(
|
|
557
|
+
command,
|
|
558
|
+
inspectedOptions.cwd,
|
|
559
|
+
environment,
|
|
560
|
+
restartReleasedWhenExited
|
|
561
|
+
);
|
|
562
|
+
const identity = await this.prepareWithAdoption(
|
|
563
|
+
command,
|
|
564
|
+
paths,
|
|
565
|
+
descriptorKey,
|
|
566
|
+
inspectedOptions,
|
|
567
|
+
environment,
|
|
568
|
+
restartReleasedWhenExited
|
|
569
|
+
);
|
|
570
|
+
const detached = formatDetachedCommand(identity);
|
|
571
|
+
try {
|
|
572
|
+
await inspectedOptions.beforeRelease?.(detached);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
const resolution2 = await this.cancelOrAdopt(
|
|
575
|
+
paths,
|
|
576
|
+
descriptorKey,
|
|
577
|
+
identity,
|
|
578
|
+
"Detached command preparation callback failed",
|
|
579
|
+
error,
|
|
580
|
+
protectProviderDiagnostics,
|
|
581
|
+
restartReleasedWhenExited
|
|
582
|
+
);
|
|
583
|
+
if (resolution2.state === "cancelled") {
|
|
584
|
+
throw markDetachedProcessLaunchCancelled(error);
|
|
585
|
+
}
|
|
586
|
+
if (resolution2.state === "released_generation_unavailable") {
|
|
587
|
+
throw markDetachedProcessReleasedGenerationUnavailable(error);
|
|
588
|
+
}
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
let releaseFailure;
|
|
592
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
593
|
+
const release = await this.executeControl(
|
|
594
|
+
buildReleaseDetachedCommand(paths, identity, restartReleasedWhenExited)
|
|
595
|
+
);
|
|
596
|
+
if (release.state === "completed" && release.result.exitCode === 0 && isReleaseConfirmation(release.result.stdout, identity)) {
|
|
597
|
+
return detached;
|
|
598
|
+
}
|
|
599
|
+
if (restartReleasedWhenExited && release.state === "completed" && release.result.exitCode === 0 && release.result.stdout.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
|
|
600
|
+
throw new DetachedProcessReleasedGenerationUnavailableError();
|
|
601
|
+
}
|
|
602
|
+
if (release.state === "failed") {
|
|
603
|
+
releaseFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command release failed.`) : new Error(`${this.providerName} detached command release failed.`);
|
|
604
|
+
} else if (protectProviderDiagnostics) {
|
|
605
|
+
releaseFailure = new Error(
|
|
606
|
+
`${this.providerName} did not confirm supervisor detached command release.`
|
|
607
|
+
);
|
|
608
|
+
} else {
|
|
609
|
+
releaseFailure = new Error(`${this.providerName} did not confirm detached command release.`);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const resolution = await this.cancelOrAdopt(
|
|
613
|
+
paths,
|
|
614
|
+
descriptorKey,
|
|
615
|
+
identity,
|
|
616
|
+
`${this.providerName} detached command release was uncertain`,
|
|
617
|
+
releaseFailure,
|
|
618
|
+
protectProviderDiagnostics,
|
|
619
|
+
restartReleasedWhenExited
|
|
620
|
+
);
|
|
621
|
+
if (resolution.state === "released") return formatDetachedCommand(resolution.identity);
|
|
622
|
+
const failedRelease = this.options.failure(
|
|
623
|
+
protectProviderDiagnostics ? `${this.providerName} detached command release failed: ${messageFrom(releaseFailure)}` : `${this.providerName} detached command release failed.`
|
|
624
|
+
);
|
|
625
|
+
throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedRelease) : markDetachedProcessLaunchCancelled(failedRelease);
|
|
626
|
+
}
|
|
627
|
+
async prepareWithAdoption(command, paths, descriptorKey, options, environment, restartReleasedWhenExited) {
|
|
628
|
+
let failure;
|
|
629
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
630
|
+
await this.options.beforePrepareMutation?.();
|
|
631
|
+
const prepared = await this.executeControl(
|
|
632
|
+
buildPrepareDetachedCommand(
|
|
633
|
+
paths,
|
|
634
|
+
descriptorKey,
|
|
635
|
+
command,
|
|
636
|
+
environment.mode,
|
|
637
|
+
restartReleasedWhenExited
|
|
638
|
+
),
|
|
639
|
+
{ cwd: options.cwd, envs: environment.providerEnvironment }
|
|
640
|
+
);
|
|
641
|
+
if (prepared.state === "failed") {
|
|
642
|
+
failure = environment.mode === "supervisor-fd-v1" ? new Error(`${this.providerName} supervisor environment handoff failed.`) : new Error(`${this.providerName} detached command preparation failed.`);
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
const { result } = prepared;
|
|
646
|
+
const identity = result.exitCode === 0 ? parsePreparedIdentity(this.options.provider, paths, descriptorKey, result.stdout) : null;
|
|
647
|
+
if (identity) return identity;
|
|
648
|
+
if (isDescriptorMismatch(result.stdout)) {
|
|
649
|
+
throw this.options.failure(
|
|
650
|
+
"Detached command launchId is already bound to a different launch descriptor."
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
if (environment.mode === "supervisor-fd-v1") {
|
|
654
|
+
failure = new Error(
|
|
655
|
+
`${this.providerName} did not confirm the supervisor environment handoff.`
|
|
656
|
+
);
|
|
657
|
+
} else {
|
|
658
|
+
failure = new Error(`${this.providerName} did not confirm detached command preparation.`);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
const resolution = await this.cancelOrAdopt(
|
|
662
|
+
paths,
|
|
663
|
+
descriptorKey,
|
|
664
|
+
void 0,
|
|
665
|
+
`${this.providerName} detached command preparation was uncertain`,
|
|
666
|
+
failure,
|
|
667
|
+
environment.mode === "supervisor-fd-v1",
|
|
668
|
+
restartReleasedWhenExited
|
|
669
|
+
);
|
|
670
|
+
if (resolution.state === "released") return resolution.identity;
|
|
671
|
+
const failedPreparation = this.options.failure(
|
|
672
|
+
environment.mode === "supervisor-fd-v1" ? `Failed to prepare detached ${this.providerName} process: ${messageFrom(failure)}` : `Failed to prepare detached ${this.providerName} process.`
|
|
673
|
+
);
|
|
674
|
+
throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedPreparation) : markDetachedProcessLaunchCancelled(failedPreparation);
|
|
675
|
+
}
|
|
676
|
+
async cancelOrAdopt(paths, descriptorKey, identity, context, cause, protectProviderDiagnostics = false, serializeGenerationChanges = false) {
|
|
677
|
+
let cleanupFailure;
|
|
678
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
679
|
+
if (identity === void 0) {
|
|
680
|
+
await this.options.beforePrepareMutation?.();
|
|
681
|
+
}
|
|
682
|
+
const stopped = await this.executeControl(
|
|
683
|
+
buildCancelDetachedCommand(
|
|
684
|
+
paths,
|
|
685
|
+
descriptorKey,
|
|
686
|
+
identity,
|
|
687
|
+
serializeGenerationChanges
|
|
688
|
+
)
|
|
689
|
+
);
|
|
690
|
+
if (stopped.state === "failed") {
|
|
691
|
+
cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command cleanup failed.`) : new Error(`${this.providerName} detached command cleanup failed.`);
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
const { result } = stopped;
|
|
695
|
+
const parsedResolution = result.exitCode === 0 ? parseCancellationResult(
|
|
696
|
+
this.options.provider,
|
|
697
|
+
paths,
|
|
698
|
+
descriptorKey,
|
|
699
|
+
result.stdout
|
|
700
|
+
) : null;
|
|
701
|
+
const resolution = parsedResolution?.state === "released_generation_unavailable" && !serializeGenerationChanges ? null : parsedResolution;
|
|
702
|
+
if (resolution) return resolution;
|
|
703
|
+
if (isDescriptorMismatch(result.stdout)) {
|
|
704
|
+
throw this.options.failure(
|
|
705
|
+
"Detached command launchId is already bound to a different launch descriptor."
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} did not confirm supervisor detached command cleanup.`) : new Error(`${this.providerName} did not confirm detached command cleanup.`);
|
|
709
|
+
}
|
|
710
|
+
throw this.options.failure(
|
|
711
|
+
protectProviderDiagnostics ? `${context}: ${messageFrom(cause)}. Cleanup could not be confirmed: ${messageFrom(cleanupFailure)}` : `${context}. Cleanup could not be confirmed.`
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
async stop(command) {
|
|
715
|
+
const identity = this.resolve(command);
|
|
716
|
+
if (!identity) return this.options.stopLegacy(command);
|
|
717
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
718
|
+
await this.options.beforeStopOrDisposeMutation?.();
|
|
719
|
+
const stopped = await this.executeControl(
|
|
720
|
+
buildStopDetachedCommand(pathsForIdentity(identity), identity)
|
|
721
|
+
);
|
|
722
|
+
if (stopped.state === "failed") {
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (stopped.result.exitCode === 0 && isStopConfirmation(stopped.result.stdout)) return;
|
|
726
|
+
}
|
|
727
|
+
throw this.options.failure(`Failed to stop detached ${this.providerName} process.`);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Irreversibly removes the private lifecycle state and diagnostics for one
|
|
731
|
+
* exact managed generation. This is deliberately separate from `stop()`:
|
|
732
|
+
* callers must first obtain exact stop confirmation and perform any final
|
|
733
|
+
* diagnostic read they need.
|
|
734
|
+
*/
|
|
735
|
+
async dispose(command) {
|
|
736
|
+
const identity = this.resolve(command);
|
|
737
|
+
if (!identity) {
|
|
738
|
+
throw this.options.failure(
|
|
739
|
+
`Detached ${this.providerName} artifact disposal requires a managed process handle.`
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
743
|
+
await this.options.beforeStopOrDisposeMutation?.();
|
|
744
|
+
const disposed = await this.executeControl(
|
|
745
|
+
buildDisposeDetachedArtifactsCommand(pathsForIdentity(identity), identity)
|
|
746
|
+
);
|
|
747
|
+
if (disposed.state === "failed") continue;
|
|
748
|
+
if (disposed.result.exitCode === 0 && isDisposeConfirmation(disposed.result.stdout)) {
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
throw this.options.failure(
|
|
753
|
+
`Failed to dispose detached ${this.providerName} process artifacts.`
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
async readLogs(command) {
|
|
757
|
+
const identity = this.resolve(command);
|
|
758
|
+
if (!identity) return this.options.readLegacyLogs(command);
|
|
759
|
+
const read = await this.executeControl(
|
|
760
|
+
buildReadDetachedLogsCommand(identity),
|
|
761
|
+
void 0,
|
|
762
|
+
DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES
|
|
763
|
+
);
|
|
764
|
+
if (read.state !== "completed" || read.result.exitCode !== 0) {
|
|
765
|
+
return { stdout: "", stderr: "" };
|
|
766
|
+
}
|
|
767
|
+
return parseDetachedProcessLogs(read.result.stdout) ?? { stdout: "", stderr: "" };
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
function processStatParserFunctions() {
|
|
771
|
+
return [
|
|
772
|
+
"read_process_stat_file() {",
|
|
773
|
+
" proc_stat_raw=",
|
|
774
|
+
" proc_stat_separator=",
|
|
775
|
+
" proc_stat_seen=no",
|
|
776
|
+
" proc_stat_newline=$(printf '\\n_') || return 1",
|
|
777
|
+
" proc_stat_newline=${proc_stat_newline%_}",
|
|
778
|
+
" {",
|
|
779
|
+
" while :; do",
|
|
780
|
+
" proc_stat_line=",
|
|
781
|
+
" IFS= read -r proc_stat_line",
|
|
782
|
+
" proc_stat_read_status=$?",
|
|
783
|
+
' if [ "$proc_stat_read_status" -ne 0 ] && [ -z "$proc_stat_line" ]; then break; fi',
|
|
784
|
+
' proc_stat_raw="${proc_stat_raw}${proc_stat_separator}${proc_stat_line}"',
|
|
785
|
+
" proc_stat_separator=$proc_stat_newline",
|
|
786
|
+
" proc_stat_seen=yes",
|
|
787
|
+
' [ "$proc_stat_read_status" -eq 0 ] || break',
|
|
788
|
+
' done < "$1"',
|
|
789
|
+
" } 2>/dev/null",
|
|
790
|
+
' [ "$proc_stat_seen" = yes ]',
|
|
791
|
+
"}",
|
|
792
|
+
"parse_process_stat() {",
|
|
793
|
+
" proc_stat_fields=${1##*) }",
|
|
794
|
+
" proc_stat_index=1",
|
|
795
|
+
" proc_stat_state=",
|
|
796
|
+
" proc_stat_pgrp=",
|
|
797
|
+
" proc_stat_session=",
|
|
798
|
+
" proc_stat_ticks=",
|
|
799
|
+
' while [ "$proc_stat_index" -le 20 ]; do',
|
|
800
|
+
' case "$proc_stat_fields" in',
|
|
801
|
+
" *' '*) proc_stat_field=${proc_stat_fields%% *}; proc_stat_fields=${proc_stat_fields#* } ;;",
|
|
802
|
+
" *) proc_stat_field=$proc_stat_fields; proc_stat_fields= ;;",
|
|
803
|
+
" esac",
|
|
804
|
+
' [ -n "$proc_stat_field" ] || return 1',
|
|
805
|
+
' case "$proc_stat_index" in',
|
|
806
|
+
" 1) proc_stat_state=$proc_stat_field ;;",
|
|
807
|
+
" 3) proc_stat_pgrp=$proc_stat_field ;;",
|
|
808
|
+
" 4) proc_stat_session=$proc_stat_field ;;",
|
|
809
|
+
" 20) proc_stat_ticks=$proc_stat_field ;;",
|
|
810
|
+
" esac",
|
|
811
|
+
" proc_stat_index=$((proc_stat_index + 1))",
|
|
812
|
+
" done",
|
|
813
|
+
' [ -n "$proc_stat_state" ] && [ -n "$proc_stat_pgrp" ] && [ -n "$proc_stat_session" ] && [ -n "$proc_stat_ticks" ]',
|
|
814
|
+
"}"
|
|
815
|
+
];
|
|
816
|
+
}
|
|
817
|
+
function identityFunctions(paths) {
|
|
818
|
+
return [
|
|
819
|
+
...processStatParserFunctions(),
|
|
820
|
+
"read_launch_identity() {",
|
|
821
|
+
...assertSafeRegularFile(paths.record).map((line) => ` ${line}`),
|
|
822
|
+
` [ -s ${shellQuote(paths.record)} ] || return 1`,
|
|
823
|
+
` identity=$(cat ${shellQuote(paths.record)}) || return 1`,
|
|
824
|
+
` identity_prefix=$(printf '%s\\n' "$identity" | awk 'NF == 5 { print $1 }')`,
|
|
825
|
+
` target_pid=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
|
|
826
|
+
` target_ticks=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
|
|
827
|
+
` target_session=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
|
|
828
|
+
` target_descriptor=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
|
|
829
|
+
' case "$identity_prefix" in',
|
|
830
|
+
` ${IDENTITY_PREFIX}) target_reaper_protocol=v3 ;;`,
|
|
831
|
+
` ${LEGACY_IDENTITY_PREFIX}) target_reaper_protocol=v2 ;;`,
|
|
832
|
+
" *) return 1 ;;",
|
|
833
|
+
" esac",
|
|
834
|
+
' [ -n "$target_pid" ] && [ -n "$target_ticks" ] && [ "$target_pid" = "$target_session" ] && [ ${#target_descriptor} -eq 64 ]',
|
|
835
|
+
"}",
|
|
836
|
+
"leader_identity_status() {",
|
|
837
|
+
' read_process_stat_file "/proc/$target_pid/stat" || return 1',
|
|
838
|
+
' parse_process_stat "$proc_stat_raw" || return 1',
|
|
839
|
+
" state=$proc_stat_state",
|
|
840
|
+
" pgrp=$proc_stat_pgrp",
|
|
841
|
+
" current_session=$proc_stat_session",
|
|
842
|
+
" current_ticks=$proc_stat_ticks",
|
|
843
|
+
' [ "$current_ticks" = "$target_ticks" ] && [ "$pgrp" = "$target_pid" ] && [ "$current_session" = "$target_session" ] || return 2',
|
|
844
|
+
' [ "$state" != "Z" ] || return 1',
|
|
845
|
+
" return 0",
|
|
846
|
+
"}"
|
|
847
|
+
];
|
|
848
|
+
}
|
|
849
|
+
function decisionFunctions(paths) {
|
|
850
|
+
return [
|
|
851
|
+
"read_launch_decision() {",
|
|
852
|
+
...assertSafeRegularFile(paths.decision).map((line) => ` ${line}`),
|
|
853
|
+
` [ -s ${shellQuote(paths.decision)} ] || return 1`,
|
|
854
|
+
` decision=$(cat ${shellQuote(paths.decision)}) || return 1`,
|
|
855
|
+
` decision_prefix=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $1 }')`,
|
|
856
|
+
` decision_action=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $2 }')`,
|
|
857
|
+
` decision_pid=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $3 ~ /^[0-9]+$/ { print $3 }')`,
|
|
858
|
+
` decision_ticks=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $4 ~ /^[0-9]+$/ { print $4 }')`,
|
|
859
|
+
` decision_session=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $5 ~ /^[0-9]+$/ { print $5 }')`,
|
|
860
|
+
` decision_descriptor=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $6 ~ /^[a-f0-9]+$/ { print $6 }')`,
|
|
861
|
+
` [ "$decision_prefix" = ${shellQuote(DECISION_PREFIX)} ] || return 1`,
|
|
862
|
+
' case "$decision_action" in RELEASE|CANCEL) ;; *) return 1 ;; esac',
|
|
863
|
+
' [ -n "$decision_pid" ] && [ -n "$decision_ticks" ] && [ -n "$decision_session" ] && [ ${#decision_descriptor} -eq 64 ]',
|
|
864
|
+
"}",
|
|
865
|
+
"read_started_identity() {",
|
|
866
|
+
...assertSafeRegularFile(paths.started).map((line) => ` ${line}`),
|
|
867
|
+
` [ -s ${shellQuote(paths.started)} ] || return 1`,
|
|
868
|
+
` started=$(cat ${shellQuote(paths.started)}) || return 1`,
|
|
869
|
+
` started_prefix=$(printf '%s\\n' "$started" | awk 'NF == 5 { print $1 }')`,
|
|
870
|
+
` started_pid=$(printf '%s\\n' "$started" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
|
|
871
|
+
` started_ticks=$(printf '%s\\n' "$started" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
|
|
872
|
+
` started_session=$(printf '%s\\n' "$started" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
|
|
873
|
+
` started_descriptor=$(printf '%s\\n' "$started" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
|
|
874
|
+
` [ "$started_prefix" = ${shellQuote(STARTED_PREFIX)} ] || return 1`,
|
|
875
|
+
' [ "$started_pid:$started_ticks:$started_session:$started_descriptor" = "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" ]',
|
|
876
|
+
"}"
|
|
877
|
+
];
|
|
878
|
+
}
|
|
879
|
+
function exactLifecycleMarkerFunction(functionName, variablePrefix, path, expectation) {
|
|
880
|
+
const quotedPath = shellQuote(path);
|
|
881
|
+
const missingMarker = expectation.kind === "populated" ? [
|
|
882
|
+
` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
|
|
883
|
+
] : [];
|
|
884
|
+
const expectedMarker = expectation.kind === "populated" ? [
|
|
885
|
+
` ${variablePrefix}_expected="${expectation.markerPrefix} $target_pid $target_ticks $target_session $target_descriptor"`,
|
|
886
|
+
` ${variablePrefix}_expected_size=$((\${#${variablePrefix}_expected} + 1))`
|
|
887
|
+
] : [];
|
|
888
|
+
const expectedSize = expectation.kind === "populated" ? `$${variablePrefix}_expected_size` : "0";
|
|
889
|
+
const exactContentProof = expectation.kind === "populated" ? [
|
|
890
|
+
` printf '%s\\n' "$${variablePrefix}_expected" | cmp -s - /proc/self/fd/8 || { exec 8<&-; return 2; }`
|
|
891
|
+
] : [];
|
|
892
|
+
return [
|
|
893
|
+
`${functionName}() {`,
|
|
894
|
+
...missingMarker,
|
|
895
|
+
` [ -f ${quotedPath} ] && [ ! -L ${quotedPath} ] || return 2`,
|
|
896
|
+
...expectedMarker,
|
|
897
|
+
` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || return 2`,
|
|
898
|
+
` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:${expectedSize}" ] || return 2`,
|
|
899
|
+
` exec 8<${quotedPath} || return 2`,
|
|
900
|
+
` ${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
901
|
+
` [ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || { exec 8<&-; return 2; }`,
|
|
902
|
+
` ${variablePrefix}_path_inode=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
903
|
+
` ${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
904
|
+
` [ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || { exec 8<&-; return 2; }`,
|
|
905
|
+
...exactContentProof,
|
|
906
|
+
` ${variablePrefix}_path_metadata_after=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
907
|
+
` ${variablePrefix}_path_inode_after=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
908
|
+
` ${variablePrefix}_descriptor_metadata_after=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
909
|
+
` ${variablePrefix}_descriptor_inode_after=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
|
|
910
|
+
" exec 8<&-",
|
|
911
|
+
` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_descriptor_metadata_after:$${variablePrefix}_descriptor_inode_after" ] || return 2`,
|
|
912
|
+
` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_path_metadata:$${variablePrefix}_path_inode" ] || return 2`,
|
|
913
|
+
" return 0",
|
|
914
|
+
"}"
|
|
915
|
+
];
|
|
916
|
+
}
|
|
917
|
+
function processTreeFunctions(paths) {
|
|
918
|
+
const liveness = paths === void 0 ? [
|
|
919
|
+
// Pre-V2 provider handles have no durable reaper proof. Preserve
|
|
920
|
+
// their documented best-effort session scan without using it for a
|
|
921
|
+
// current V3 generation.
|
|
922
|
+
"target_has_live_processes() {",
|
|
923
|
+
" for stat_path in /proc/[0-9]*/stat; do",
|
|
924
|
+
" assert_no_pid_reuse || return 2",
|
|
925
|
+
' read_process_stat_file "$stat_path" || continue',
|
|
926
|
+
' parse_process_stat "$proc_stat_raw" || continue',
|
|
927
|
+
" state=$proc_stat_state",
|
|
928
|
+
" process_session=$proc_stat_session",
|
|
929
|
+
' [ "$process_session" = "$target_session" ] && [ "$state" != "Z" ] && return 0',
|
|
930
|
+
" done",
|
|
931
|
+
" return 1",
|
|
932
|
+
"}",
|
|
933
|
+
"assert_no_pid_reuse() {",
|
|
934
|
+
" leader_identity_status",
|
|
935
|
+
" identity_status=$?",
|
|
936
|
+
' [ "$identity_status" -ne 2 ]',
|
|
937
|
+
"}"
|
|
938
|
+
] : [
|
|
939
|
+
...exactLifecycleMarkerFunction(
|
|
940
|
+
"read_exact_started_marker",
|
|
941
|
+
"exact_started",
|
|
942
|
+
paths.started,
|
|
943
|
+
{ kind: "populated", markerPrefix: STARTED_PREFIX }
|
|
944
|
+
),
|
|
945
|
+
...exactLifecycleMarkerFunction(
|
|
946
|
+
"read_exact_quiescent_marker",
|
|
947
|
+
"exact_quiescent",
|
|
948
|
+
paths.quiescent,
|
|
949
|
+
{ kind: "populated", markerPrefix: QUIESCENT_PREFIX }
|
|
950
|
+
),
|
|
951
|
+
"target_has_live_processes() {",
|
|
952
|
+
" leader_identity_status",
|
|
953
|
+
" target_leader_status=$?",
|
|
954
|
+
' [ "$target_leader_status" -ne 0 ] || return 0',
|
|
955
|
+
" read_exact_started_marker",
|
|
956
|
+
" target_started_status=$?",
|
|
957
|
+
' if [ "$target_leader_status" -eq 2 ]; then',
|
|
958
|
+
' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 1 ]; then',
|
|
959
|
+
" return 1",
|
|
960
|
+
" fi",
|
|
961
|
+
' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 0 ]; then',
|
|
962
|
+
" read_exact_quiescent_marker",
|
|
963
|
+
' [ "$?" -eq 0 ] && return 1',
|
|
964
|
+
" fi",
|
|
965
|
+
" return 2",
|
|
966
|
+
" fi",
|
|
967
|
+
' case "$target_started_status" in',
|
|
968
|
+
" 1) return 1 ;;",
|
|
969
|
+
" 2) return 2 ;;",
|
|
970
|
+
" esac",
|
|
971
|
+
' [ "$target_reaper_protocol" = v3 ] || return 2',
|
|
972
|
+
" read_exact_quiescent_marker",
|
|
973
|
+
' [ "$?" -eq 0 ] && return 1',
|
|
974
|
+
" return 2",
|
|
975
|
+
"}"
|
|
976
|
+
];
|
|
977
|
+
return [
|
|
978
|
+
...liveness,
|
|
979
|
+
"signal_target_session() {",
|
|
980
|
+
" signal_name=$1",
|
|
981
|
+
` PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
|
|
982
|
+
" export PATH",
|
|
983
|
+
" command -v python3 >/dev/null 2>&1 || return 1",
|
|
984
|
+
" preserve_target_leader=no",
|
|
985
|
+
...paths === void 0 ? [] : [
|
|
986
|
+
' if [ "$target_reaper_protocol" = v3 ]; then',
|
|
987
|
+
" read_exact_started_marker",
|
|
988
|
+
" target_started_status=$?",
|
|
989
|
+
' [ "$target_started_status" -ne 2 ] || return 2',
|
|
990
|
+
' [ "$target_started_status" -ne 0 ] || preserve_target_leader=yes',
|
|
991
|
+
" fi"
|
|
992
|
+
],
|
|
993
|
+
" # pidfds bind every candidate before its session is checked and signaled.",
|
|
994
|
+
// -I excludes the caller working directory and PYTHON* settings from
|
|
995
|
+
// module lookup; -S prevents sitecustomize from running before fencing.
|
|
996
|
+
` python3 -I -S - "$target_pid" "$target_ticks" "$target_session" "$signal_name" "$preserve_target_leader" <<'PY'`,
|
|
997
|
+
"import os",
|
|
998
|
+
"import signal",
|
|
999
|
+
"import sys",
|
|
1000
|
+
"",
|
|
1001
|
+
"target_pid = int(sys.argv[1])",
|
|
1002
|
+
"target_ticks = int(sys.argv[2])",
|
|
1003
|
+
"target_session = int(sys.argv[3])",
|
|
1004
|
+
'signal_value = getattr(signal, "SIG" + sys.argv[4])',
|
|
1005
|
+
'preserve_target_leader = sys.argv[5] == "yes"',
|
|
1006
|
+
'if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):',
|
|
1007
|
+
" raise SystemExit(1)",
|
|
1008
|
+
"",
|
|
1009
|
+
"def read_identity(pid):",
|
|
1010
|
+
" try:",
|
|
1011
|
+
' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
|
|
1012
|
+
" raw = stat_file.read()",
|
|
1013
|
+
" except (FileNotFoundError, ProcessLookupError):",
|
|
1014
|
+
" return None",
|
|
1015
|
+
' marker = raw.rfind(b") ")',
|
|
1016
|
+
" fields = raw[marker + 2:].split() if marker >= 0 else []",
|
|
1017
|
+
" if len(fields) <= 19:",
|
|
1018
|
+
" raise SystemExit(1)",
|
|
1019
|
+
" return fields[0], int(fields[2]), int(fields[3]), int(fields[19])",
|
|
1020
|
+
"",
|
|
1021
|
+
"def leader_was_reused():",
|
|
1022
|
+
" identity = read_identity(target_pid)",
|
|
1023
|
+
" if identity is None:",
|
|
1024
|
+
" return False",
|
|
1025
|
+
" _state, pgrp, session_id, ticks = identity",
|
|
1026
|
+
" return (pgrp, session_id, ticks) != (target_pid, target_session, target_ticks)",
|
|
1027
|
+
"",
|
|
1028
|
+
'for entry in os.scandir("/proc"):',
|
|
1029
|
+
" if not entry.name.isdecimal():",
|
|
1030
|
+
" continue",
|
|
1031
|
+
" pid = int(entry.name)",
|
|
1032
|
+
" if pid == target_pid:",
|
|
1033
|
+
" if preserve_target_leader:",
|
|
1034
|
+
" continue",
|
|
1035
|
+
" try:",
|
|
1036
|
+
" pidfd = os.pidfd_open(pid)",
|
|
1037
|
+
" except (PermissionError, ProcessLookupError):",
|
|
1038
|
+
" continue",
|
|
1039
|
+
" try:",
|
|
1040
|
+
" identity = read_identity(pid)",
|
|
1041
|
+
" if identity is None:",
|
|
1042
|
+
" continue",
|
|
1043
|
+
" state, _pgrp, session_id, _ticks = identity",
|
|
1044
|
+
' if session_id != target_session or state == b"Z":',
|
|
1045
|
+
" continue",
|
|
1046
|
+
" if leader_was_reused():",
|
|
1047
|
+
" raise SystemExit(2)",
|
|
1048
|
+
" try:",
|
|
1049
|
+
" signal.pidfd_send_signal(pidfd, signal_value)",
|
|
1050
|
+
" except ProcessLookupError:",
|
|
1051
|
+
" pass",
|
|
1052
|
+
" finally:",
|
|
1053
|
+
" os.close(pidfd)",
|
|
1054
|
+
"PY",
|
|
1055
|
+
"}"
|
|
1056
|
+
];
|
|
1057
|
+
}
|
|
1058
|
+
function stopTargetCommands(options) {
|
|
1059
|
+
const stoppedAction = options?.exitAsSoonAsStopped ? "exit 0" : "break";
|
|
1060
|
+
return [
|
|
1061
|
+
"target_has_live_processes",
|
|
1062
|
+
"target_status=$?",
|
|
1063
|
+
'[ "$target_status" -ne 2 ] || exit 2',
|
|
1064
|
+
...options?.exitAsSoonAsStopped ? ['[ "$target_status" -eq 0 ] || exit 0'] : [],
|
|
1065
|
+
'if [ "$target_status" -eq 0 ]; then signal_target_session TERM || exit $?; fi',
|
|
1066
|
+
"attempt=0",
|
|
1067
|
+
'while [ "$attempt" -lt 150 ]; do',
|
|
1068
|
+
" target_has_live_processes",
|
|
1069
|
+
" target_status=$?",
|
|
1070
|
+
' [ "$target_status" -ne 2 ] || exit 2',
|
|
1071
|
+
` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
|
|
1072
|
+
" sleep 0.1",
|
|
1073
|
+
" attempt=$((attempt + 1))",
|
|
1074
|
+
"done",
|
|
1075
|
+
'if [ "$target_status" -eq 0 ]; then signal_target_session KILL || exit $?; fi',
|
|
1076
|
+
"attempt=0",
|
|
1077
|
+
'while [ "$attempt" -lt 50 ]; do',
|
|
1078
|
+
" target_has_live_processes",
|
|
1079
|
+
" target_status=$?",
|
|
1080
|
+
' [ "$target_status" -ne 2 ] || exit 2',
|
|
1081
|
+
` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
|
|
1082
|
+
" sleep 0.1",
|
|
1083
|
+
" attempt=$((attempt + 1))",
|
|
1084
|
+
"done",
|
|
1085
|
+
...options?.failureMessage === void 0 ? ['[ "$target_status" -ne 0 ] || exit 1'] : [
|
|
1086
|
+
'if [ "$target_status" -eq 0 ]; then',
|
|
1087
|
+
` printf '%s\\n' ${shellQuote(options.failureMessage)} >&2`,
|
|
1088
|
+
" exit 1",
|
|
1089
|
+
"fi"
|
|
1090
|
+
]
|
|
1091
|
+
];
|
|
1092
|
+
}
|
|
1093
|
+
function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
|
|
1094
|
+
return [
|
|
1095
|
+
"umask 077",
|
|
1096
|
+
...secureDetachedRoot(),
|
|
1097
|
+
`target_pid=${shellQuote(pid)}`,
|
|
1098
|
+
`target_ticks=${shellQuote(startTicks)}`,
|
|
1099
|
+
"target_session=$target_pid",
|
|
1100
|
+
...processStatParserFunctions(),
|
|
1101
|
+
"leader_identity_status() {",
|
|
1102
|
+
' read_process_stat_file "/proc/$target_pid/stat" || return 1',
|
|
1103
|
+
' parse_process_stat "$proc_stat_raw" || return 1',
|
|
1104
|
+
" current_ticks=$proc_stat_ticks",
|
|
1105
|
+
' [ "$current_ticks" = "$target_ticks" ] || return 2',
|
|
1106
|
+
" return 0",
|
|
1107
|
+
"}",
|
|
1108
|
+
"target_reaper_protocol=legacy",
|
|
1109
|
+
...processTreeFunctions(),
|
|
1110
|
+
"# Revalidate the leader birth immediately before every scan and every kill.",
|
|
1111
|
+
...stopTargetCommands({
|
|
1112
|
+
exitAsSoonAsStopped: true,
|
|
1113
|
+
failureMessage: `Detached ${providerName} process ${pid} did not stop.`
|
|
1114
|
+
})
|
|
1115
|
+
].join("\n");
|
|
1116
|
+
}
|
|
1117
|
+
function atomicFile(partialPath, path, parentDirectory, write) {
|
|
1118
|
+
return [
|
|
1119
|
+
`${write} || exit 1`,
|
|
1120
|
+
`sync -f ${shellQuote(partialPath)} || exit 1`,
|
|
1121
|
+
`mv -f ${shellQuote(partialPath)} ${shellQuote(path)} || exit 1`,
|
|
1122
|
+
`sync -f ${shellQuote(parentDirectory)} || exit 1`
|
|
1123
|
+
];
|
|
1124
|
+
}
|
|
1125
|
+
function secureDirectory(path, create) {
|
|
1126
|
+
return [
|
|
1127
|
+
...create ? [
|
|
1128
|
+
`if [ ! -e ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ]; then`,
|
|
1129
|
+
` mkdir ${shellQuote(path)} 2>/dev/null || true`,
|
|
1130
|
+
"fi"
|
|
1131
|
+
] : [],
|
|
1132
|
+
`[ -d ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`,
|
|
1133
|
+
`directory_owner=$(stat -c %u ${shellQuote(path)} 2>/dev/null) || exit 1`,
|
|
1134
|
+
'[ "$directory_owner" = "$(id -u)" ] || exit 1',
|
|
1135
|
+
`directory_mode=$(stat -c %a ${shellQuote(path)} 2>/dev/null) || exit 1`,
|
|
1136
|
+
'[ "$directory_mode" = 700 ] || exit 1'
|
|
1137
|
+
];
|
|
1138
|
+
}
|
|
1139
|
+
function secureDetachedRoot() {
|
|
1140
|
+
return secureDirectory(DETACHED_PROCESS_ROOT, true);
|
|
1141
|
+
}
|
|
1142
|
+
function secureLaunchDirectory(paths, create) {
|
|
1143
|
+
return secureDirectory(paths.directory, create);
|
|
1144
|
+
}
|
|
1145
|
+
function assertSafeRegularFile(path) {
|
|
1146
|
+
return [
|
|
1147
|
+
`[ -e ${shellQuote(path)} ] || return 1`,
|
|
1148
|
+
`[ -f ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`
|
|
1149
|
+
];
|
|
1150
|
+
}
|
|
1151
|
+
function publishDecision(paths, action, partialPath) {
|
|
1152
|
+
return [
|
|
1153
|
+
`printf '${DECISION_PREFIX} ${action} %s %s %s %s\\n' "$publish_pid" "$publish_ticks" "$publish_session" "$publish_descriptor" > ${shellQuote(partialPath)} || exit 1`,
|
|
1154
|
+
`sync -f ${shellQuote(partialPath)} || exit 1`,
|
|
1155
|
+
`ln ${shellQuote(partialPath)} ${shellQuote(paths.decision)} 2>/dev/null || true`,
|
|
1156
|
+
`rm -f ${shellQuote(partialPath)} || exit 1`,
|
|
1157
|
+
`sync -f ${shellQuote(paths.directory)} || exit 1`,
|
|
1158
|
+
"read_launch_decision || exit 1"
|
|
1159
|
+
];
|
|
1160
|
+
}
|
|
1161
|
+
function waitForStarted(paths) {
|
|
1162
|
+
return [
|
|
1163
|
+
"attempt=0",
|
|
1164
|
+
`while [ ! -s ${shellQuote(paths.started)} ] && [ "$attempt" -lt 400 ]; do`,
|
|
1165
|
+
" sleep 0.05",
|
|
1166
|
+
" attempt=$((attempt + 1))",
|
|
1167
|
+
"done",
|
|
1168
|
+
"read_started_identity || exit 1"
|
|
1169
|
+
];
|
|
1170
|
+
}
|
|
1171
|
+
function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges) {
|
|
1172
|
+
if (!serializeGenerationChanges) {
|
|
1173
|
+
return [
|
|
1174
|
+
...waitForStarted(paths),
|
|
1175
|
+
`printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
|
|
1176
|
+
"exit 0"
|
|
1177
|
+
];
|
|
1178
|
+
}
|
|
1179
|
+
return [
|
|
1180
|
+
// Replacement-capable adoption runs under the generation lock. Rebind the
|
|
1181
|
+
// durable decision to the exact current record before returning any handle.
|
|
1182
|
+
"read_launch_identity || exit 1",
|
|
1183
|
+
`[ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
1184
|
+
'[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
|
|
1185
|
+
'[ "$target_reaper_protocol" = v3 ] || exit 1',
|
|
1186
|
+
...waitForStarted(paths),
|
|
1187
|
+
"read_exact_started_marker || exit 1",
|
|
1188
|
+
"leader_identity_status",
|
|
1189
|
+
"released_leader_status=$?",
|
|
1190
|
+
'if [ "$released_leader_status" -eq 0 ]; then',
|
|
1191
|
+
` printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
|
|
1192
|
+
" exit 0",
|
|
1193
|
+
"fi",
|
|
1194
|
+
// Exact quiescence is recoverable by retrying the same deterministic
|
|
1195
|
+
// launch. Any absent or ambiguous proof after exact STARTED is a distinct
|
|
1196
|
+
// reset-required outcome, never a stale released-handle adoption.
|
|
1197
|
+
"read_exact_quiescent_marker",
|
|
1198
|
+
"released_quiescent_status=$?",
|
|
1199
|
+
'[ "$released_quiescent_status" -ne 0 ] || exit 1',
|
|
1200
|
+
`printf '${RELEASED_GENERATION_UNAVAILABLE_SENTINEL}\\n'`,
|
|
1201
|
+
"exit 0"
|
|
1202
|
+
];
|
|
1203
|
+
}
|
|
1204
|
+
function renderShellLockAssertion(options) {
|
|
1205
|
+
const { functionName, variablePrefix, path, descriptorFd } = options;
|
|
1206
|
+
const pathExpression = shellQuote(path);
|
|
1207
|
+
const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
|
|
1208
|
+
const descriptorChecks = [
|
|
1209
|
+
`[ -f ${descriptorPathExpression} ] || return 1`,
|
|
1210
|
+
`${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s ${descriptorPathExpression} 2>/dev/null) || return 1`,
|
|
1211
|
+
`[ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || return 1`,
|
|
1212
|
+
`${variablePrefix}_path_inode=$(stat -c %d:%i ${pathExpression} 2>/dev/null) || return 1`,
|
|
1213
|
+
`${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i ${descriptorPathExpression} 2>/dev/null) || return 1`,
|
|
1214
|
+
`[ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || return 1`
|
|
1215
|
+
];
|
|
1216
|
+
return [
|
|
1217
|
+
`${functionName}() {`,
|
|
1218
|
+
` [ -f ${pathExpression} ] && [ ! -L ${pathExpression} ] || return 1`,
|
|
1219
|
+
` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${pathExpression} 2>/dev/null) || return 1`,
|
|
1220
|
+
` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:0" ] || return 1`,
|
|
1221
|
+
...descriptorChecks.map((line) => ` ${line}`),
|
|
1222
|
+
" return 0",
|
|
1223
|
+
"}"
|
|
1224
|
+
];
|
|
1225
|
+
}
|
|
1226
|
+
function generationLock(paths) {
|
|
1227
|
+
return [
|
|
1228
|
+
"command -v flock >/dev/null 2>&1 || exit 1",
|
|
1229
|
+
`if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then [ -f ${shellQuote(paths.controlLock)} ] && [ ! -L ${shellQuote(paths.controlLock)} ] || exit 1; fi`,
|
|
1230
|
+
`exec 9>>${shellQuote(paths.controlLock)} || exit 1`,
|
|
1231
|
+
...renderShellLockAssertion({
|
|
1232
|
+
functionName: "assert_generation_lock",
|
|
1233
|
+
variablePrefix: "generation_lock",
|
|
1234
|
+
path: paths.controlLock,
|
|
1235
|
+
descriptorFd: 9
|
|
1236
|
+
}),
|
|
1237
|
+
"assert_generation_lock || exit 1",
|
|
1238
|
+
"flock -w 8 9 || exit 1",
|
|
1239
|
+
"assert_generation_lock || exit 1"
|
|
1240
|
+
];
|
|
1241
|
+
}
|
|
1242
|
+
function acquireGenerationLock(paths) {
|
|
1243
|
+
return [...secureDetachedRoot(), ...generationLock(paths)];
|
|
1244
|
+
}
|
|
1245
|
+
function retireExitedReleasedLaunch(paths, descriptorKey) {
|
|
1246
|
+
return [
|
|
1247
|
+
`if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
|
|
1248
|
+
...secureDirectory(paths.retiredDirectory, false).map((line) => ` ${line}`),
|
|
1249
|
+
` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
|
|
1250
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1251
|
+
"fi",
|
|
1252
|
+
`if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
|
|
1253
|
+
...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
|
|
1254
|
+
` if [ ! -e ${shellQuote(paths.record)} ] && [ ! -L ${shellQuote(paths.record)} ]; then`,
|
|
1255
|
+
` [ ! -e ${shellQuote(paths.decision)} ] && [ ! -L ${shellQuote(paths.decision)} ] || exit 1`,
|
|
1256
|
+
` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
|
|
1257
|
+
` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
|
|
1258
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1259
|
+
` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
|
|
1260
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1261
|
+
" elif read_launch_identity; then",
|
|
1262
|
+
` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
1263
|
+
" if read_launch_decision; then",
|
|
1264
|
+
` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
1265
|
+
' [ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
|
|
1266
|
+
' if [ "$decision_action" = RELEASE ]; then',
|
|
1267
|
+
` if [ -e ${shellQuote(paths.started)} ] || [ -L ${shellQuote(paths.started)} ]; then`,
|
|
1268
|
+
" read_started_identity || exit 1",
|
|
1269
|
+
" fi",
|
|
1270
|
+
" target_has_live_processes",
|
|
1271
|
+
" target_status=$?",
|
|
1272
|
+
' [ "$target_status" -ne 2 ] || exit 1',
|
|
1273
|
+
' if [ "$target_status" -ne 0 ]; then',
|
|
1274
|
+
` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
|
|
1275
|
+
` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
|
|
1276
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1277
|
+
` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
|
|
1278
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1279
|
+
" fi",
|
|
1280
|
+
" fi",
|
|
1281
|
+
" fi",
|
|
1282
|
+
" fi",
|
|
1283
|
+
"fi"
|
|
1284
|
+
];
|
|
1285
|
+
}
|
|
1286
|
+
function buildEnvironmentFdLaunch(paths, child, environmentMode) {
|
|
1287
|
+
const handoff = `${paths.directory}/.supervisor-environment-v1.empty`;
|
|
1288
|
+
const cleanLaunch = "nohup setsid env -i " + Object.entries(DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT).map(([name, value]) => shellQuote(`${name}=${value}`)).join(" ") + (environmentMode === "supervisor-fd-v1" ? ` ${SUPERVISOR_ENVIRONMENT_FD_ENV}=${SUPERVISOR_ENVIRONMENT_FD}` : "") + ` sh -c ${shellQuote(child)} >/dev/null 2>/dev/null < /dev/null ${SUPERVISOR_ENVIRONMENT_FD}<&7 7<&- &`;
|
|
1289
|
+
return [
|
|
1290
|
+
`: > ${shellQuote(handoff)} || exit 1`,
|
|
1291
|
+
`chmod 600 ${shellQuote(handoff)} || exit 1`,
|
|
1292
|
+
// Keep the inherited reader writable so the selected payload boundary can
|
|
1293
|
+
// erase the anonymous inode before closing its copy. This also clears any
|
|
1294
|
+
// duplicate retained by a generic parent shell after it forks the command.
|
|
1295
|
+
`exec 7<>${shellQuote(handoff)} || exit 1`,
|
|
1296
|
+
`exec 8>${shellQuote(handoff)} || exit 1`,
|
|
1297
|
+
`rm -f -- ${shellQuote(handoff)} || exit 1`,
|
|
1298
|
+
`printf '%s' "$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" >&8 || exit 1`,
|
|
1299
|
+
"exec 8>&-",
|
|
1300
|
+
`unset ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}`,
|
|
1301
|
+
cleanLaunch,
|
|
1302
|
+
"exec 7<&-"
|
|
1303
|
+
];
|
|
1304
|
+
}
|
|
1305
|
+
function cleanLifecycleShell(script, environmentMode) {
|
|
1306
|
+
let suffix = 0;
|
|
1307
|
+
let delimiter = "NECKBEARD_DETACHED_LIFECYCLE";
|
|
1308
|
+
const lines = new Set(script.split("\n"));
|
|
1309
|
+
while (lines.has(delimiter)) {
|
|
1310
|
+
suffix += 1;
|
|
1311
|
+
delimiter = `NECKBEARD_DETACHED_LIFECYCLE_${suffix}`;
|
|
1312
|
+
}
|
|
1313
|
+
const fixedEnvironment = Object.entries(
|
|
1314
|
+
DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT
|
|
1315
|
+
).map(([name, value]) => shellQuote(`${name}=${value}`)).join(" ");
|
|
1316
|
+
return [
|
|
1317
|
+
`export PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
|
|
1318
|
+
...environmentMode === "exec" ? [
|
|
1319
|
+
`if [ -z "\${${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}+present}" ]; then ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=${shellQuote('{"version":1,"environment":{}}')}; fi`
|
|
1320
|
+
] : [],
|
|
1321
|
+
`exec env -i ${fixedEnvironment} ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" sh -s <<'${delimiter}'`,
|
|
1322
|
+
script,
|
|
1323
|
+
delimiter
|
|
1324
|
+
].join("\n");
|
|
1325
|
+
}
|
|
1326
|
+
function previousLogPath(path) {
|
|
1327
|
+
return `${path}.previous`;
|
|
1328
|
+
}
|
|
1329
|
+
function logPipePath(path) {
|
|
1330
|
+
return `${path}.pipe`;
|
|
1331
|
+
}
|
|
1332
|
+
function logSnapshotPath(path) {
|
|
1333
|
+
return `${path}.snapshot`;
|
|
1334
|
+
}
|
|
1335
|
+
function logSnapshotStagingPath(path) {
|
|
1336
|
+
return `${logSnapshotPath(path)}.partial`;
|
|
1337
|
+
}
|
|
1338
|
+
function legacyLogSnapshotLockPath(path) {
|
|
1339
|
+
return `${logSnapshotPath(path)}.lock`;
|
|
1340
|
+
}
|
|
1341
|
+
function logChunkPath(path) {
|
|
1342
|
+
return `${path}.chunk`;
|
|
1343
|
+
}
|
|
1344
|
+
function boundedLogProgram() {
|
|
1345
|
+
return [
|
|
1346
|
+
"const fs = require('node:fs');",
|
|
1347
|
+
"const [input, output, previous, snapshot, snapshotStaging] = process.argv.slice(1);",
|
|
1348
|
+
"let generation = 0;",
|
|
1349
|
+
"let captureEnabled = true;",
|
|
1350
|
+
"const waitArray = new Int32Array(new SharedArrayBuffer(4));",
|
|
1351
|
+
"function assertSafeLeaf(path, optional = false) {",
|
|
1352
|
+
" let stats;",
|
|
1353
|
+
" try { stats = fs.lstatSync(path); } catch (error) { if (optional && error?.code === 'ENOENT') return; throw error; }",
|
|
1354
|
+
" if (!stats.isFile() || stats.isSymbolicLink()) throw new Error('unsafe log leaf');",
|
|
1355
|
+
"}",
|
|
1356
|
+
"function publishSnapshot(state) {",
|
|
1357
|
+
` fs.writeFileSync(snapshotStaging, \`${LOG_SNAPSHOT_PREFIX} \${state} \${generation}\\n\`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });`,
|
|
1358
|
+
" fs.chmodSync(snapshotStaging, 0o600);",
|
|
1359
|
+
" fs.renameSync(snapshotStaging, snapshot);",
|
|
1360
|
+
"}",
|
|
1361
|
+
"void (async () => {",
|
|
1362
|
+
` for await (const chunk of fs.createReadStream(input, { highWaterMark: ${DETACHED_PROCESS_LOG_CHUNK_BYTES} })) {`,
|
|
1363
|
+
" if (captureEnabled) {",
|
|
1364
|
+
" try {",
|
|
1365
|
+
" generation += 1;",
|
|
1366
|
+
" publishSnapshot('ROTATING');",
|
|
1367
|
+
" assertSafeLeaf(output);",
|
|
1368
|
+
" assertSafeLeaf(previous, true);",
|
|
1369
|
+
" fs.appendFileSync(output, chunk);",
|
|
1370
|
+
` if (fs.statSync(output).size >= ${DETACHED_PROCESS_LOG_SEGMENT_BYTES}) {`,
|
|
1371
|
+
" fs.renameSync(output, previous);",
|
|
1372
|
+
" fs.writeFileSync(output, '', { mode: 0o600, flag: 'wx' });",
|
|
1373
|
+
" fs.chmodSync(output, 0o600);",
|
|
1374
|
+
" }",
|
|
1375
|
+
" publishSnapshot('STABLE');",
|
|
1376
|
+
" } catch {",
|
|
1377
|
+
" // Diagnostic capture failure must never close the target pipe.",
|
|
1378
|
+
" captureEnabled = false;",
|
|
1379
|
+
" }",
|
|
1380
|
+
" }",
|
|
1381
|
+
" // Avoid monopolizing the process while the pipe remains continuously readable.",
|
|
1382
|
+
" Atomics.wait(waitArray, 0, 0, 10);",
|
|
1383
|
+
" }",
|
|
1384
|
+
" fs.rmSync(input);",
|
|
1385
|
+
"})().catch(() => { process.exitCode = 1; });"
|
|
1386
|
+
].join("\n");
|
|
1387
|
+
}
|
|
1388
|
+
function boundedLogShellFunctions() {
|
|
1389
|
+
return [
|
|
1390
|
+
"bounded_log_shell() {",
|
|
1391
|
+
" log_input=$1",
|
|
1392
|
+
" log_output=$2",
|
|
1393
|
+
" log_previous=$3",
|
|
1394
|
+
" log_snapshot=$4",
|
|
1395
|
+
" log_snapshot_staging=$5",
|
|
1396
|
+
" log_chunk=$6",
|
|
1397
|
+
" log_generation=0",
|
|
1398
|
+
" log_capture_enabled=yes",
|
|
1399
|
+
' exec 6<"$log_input" || exit 1',
|
|
1400
|
+
" while :; do",
|
|
1401
|
+
' if [ "$log_capture_enabled" != yes ]; then',
|
|
1402
|
+
" cat <&6 >/dev/null 2>&1 || true",
|
|
1403
|
+
" break",
|
|
1404
|
+
" fi",
|
|
1405
|
+
` if ! dd bs=${DETACHED_PROCESS_LOG_CHUNK_BYTES} count=1 <&6 >"$log_chunk" 2>/dev/null; then`,
|
|
1406
|
+
" cat <&6 >/dev/null 2>&1 || true",
|
|
1407
|
+
" break",
|
|
1408
|
+
" fi",
|
|
1409
|
+
' if ! log_chunk_size=$(stat -c %s "$log_chunk" 2>/dev/null); then',
|
|
1410
|
+
" log_capture_enabled=no",
|
|
1411
|
+
" continue",
|
|
1412
|
+
" fi",
|
|
1413
|
+
' [ "$log_chunk_size" -gt 0 ] || break',
|
|
1414
|
+
" log_generation=$((log_generation + 1))",
|
|
1415
|
+
" if ! (",
|
|
1416
|
+
' publish_log_snapshot ROTATING "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
|
|
1417
|
+
' [ -f "$log_output" ] && [ ! -L "$log_output" ] || exit 1',
|
|
1418
|
+
' if [ -e "$log_previous" ] || [ -L "$log_previous" ]; then [ -f "$log_previous" ] && [ ! -L "$log_previous" ] || exit 1; fi',
|
|
1419
|
+
' cat "$log_chunk" >> "$log_output" || exit 1',
|
|
1420
|
+
' log_after=$(stat -c %s "$log_output" 2>/dev/null) || exit 1',
|
|
1421
|
+
` if [ "$log_after" -ge ${DETACHED_PROCESS_LOG_SEGMENT_BYTES} ]; then`,
|
|
1422
|
+
' mv -f -- "$log_output" "$log_previous" || exit 1',
|
|
1423
|
+
' ( set -C; : > "$log_output" ) 2>/dev/null || exit 1',
|
|
1424
|
+
' chmod 600 "$log_output" || exit 1',
|
|
1425
|
+
" fi",
|
|
1426
|
+
' publish_log_snapshot STABLE "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
|
|
1427
|
+
" ); then",
|
|
1428
|
+
" # Keep draining even when diagnostic capture becomes unavailable.",
|
|
1429
|
+
" log_capture_enabled=no",
|
|
1430
|
+
" fi",
|
|
1431
|
+
" # Avoid monopolizing the shell while the pipe remains continuously readable.",
|
|
1432
|
+
" sleep 0.01",
|
|
1433
|
+
" done",
|
|
1434
|
+
" exec 6<&-",
|
|
1435
|
+
' rm -f -- "$log_input" 2>/dev/null || true',
|
|
1436
|
+
"}",
|
|
1437
|
+
"publish_log_snapshot() {",
|
|
1438
|
+
" log_snapshot_state=$1",
|
|
1439
|
+
" log_snapshot_generation=$2",
|
|
1440
|
+
" log_snapshot_path=$3",
|
|
1441
|
+
" log_snapshot_staging_path=$4",
|
|
1442
|
+
' [ ! -e "$log_snapshot_staging_path" ] && [ ! -L "$log_snapshot_staging_path" ] || return 1',
|
|
1443
|
+
` printf '${LOG_SNAPSHOT_PREFIX} %s %s\\n' "$log_snapshot_state" "$log_snapshot_generation" > "$log_snapshot_staging_path" || return 1`,
|
|
1444
|
+
' chmod 600 "$log_snapshot_staging_path" || return 1',
|
|
1445
|
+
' mv -f -- "$log_snapshot_staging_path" "$log_snapshot_path" || return 1',
|
|
1446
|
+
"}",
|
|
1447
|
+
"assert_legacy_log_lock_leaf() {",
|
|
1448
|
+
" legacy_log_lock_path=$1",
|
|
1449
|
+
' [ -f "$legacy_log_lock_path" ] && [ ! -L "$legacy_log_lock_path" ] || return 1',
|
|
1450
|
+
' legacy_log_lock_metadata=$(stat -c %u:%a:%h:%s "$legacy_log_lock_path" 2>/dev/null) || return 1',
|
|
1451
|
+
' [ "$legacy_log_lock_metadata" = "$(id -u):600:1:0" ]',
|
|
1452
|
+
"}"
|
|
1453
|
+
];
|
|
1454
|
+
}
|
|
1455
|
+
function boundedLogCaptureSetup(paths) {
|
|
1456
|
+
const stdoutPipe = logPipePath(paths.stdout);
|
|
1457
|
+
const stderrPipe = logPipePath(paths.stderr);
|
|
1458
|
+
return [
|
|
1459
|
+
...boundedLogShellFunctions(),
|
|
1460
|
+
"if ! command -v node >/dev/null 2>&1; then",
|
|
1461
|
+
" command -v dd >/dev/null 2>&1 || exit 1",
|
|
1462
|
+
"fi",
|
|
1463
|
+
"command -v python3 >/dev/null 2>&1 || exit 1",
|
|
1464
|
+
`: > ${shellQuote(paths.stdout)} || exit 1`,
|
|
1465
|
+
`: > ${shellQuote(paths.stderr)} || exit 1`,
|
|
1466
|
+
`: > ${shellQuote(logChunkPath(paths.stdout))} || exit 1`,
|
|
1467
|
+
`: > ${shellQuote(logChunkPath(paths.stderr))} || exit 1`,
|
|
1468
|
+
`( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} ) 2>/dev/null || exit 1`,
|
|
1469
|
+
`( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} ) 2>/dev/null || exit 1`,
|
|
1470
|
+
`chmod 600 ${shellQuote(paths.stdout)} ${shellQuote(paths.stderr)} ${shellQuote(logChunkPath(paths.stdout))} ${shellQuote(logChunkPath(paths.stderr))} ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} || exit 1`,
|
|
1471
|
+
`assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} || exit 1`,
|
|
1472
|
+
`assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} || exit 1`,
|
|
1473
|
+
`publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stdout))} ${shellQuote(logSnapshotStagingPath(paths.stdout))} || exit 1`,
|
|
1474
|
+
`publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stderr))} ${shellQuote(logSnapshotStagingPath(paths.stderr))} || exit 1`,
|
|
1475
|
+
`mkfifo -m 600 ${shellQuote(stdoutPipe)} ${shellQuote(stderrPipe)} || exit 1`,
|
|
1476
|
+
...assertSafeRegularFile(paths.stdout).map((line) => line.replace("return 1", "exit 1")),
|
|
1477
|
+
...assertSafeRegularFile(paths.stderr).map((line) => line.replace("return 1", "exit 1")),
|
|
1478
|
+
`[ -p ${shellQuote(stdoutPipe)} ] && [ ! -L ${shellQuote(stdoutPipe)} ] || exit 1`,
|
|
1479
|
+
`[ -p ${shellQuote(stderrPipe)} ] && [ ! -L ${shellQuote(stderrPipe)} ] || exit 1`,
|
|
1480
|
+
`( set -C; : > ${shellQuote(paths.quiescent)} ) 2>/dev/null || exit 1`,
|
|
1481
|
+
`chmod 600 ${shellQuote(paths.quiescent)} || exit 1`,
|
|
1482
|
+
`exec 6<>${shellQuote(paths.quiescent)} || exit 1`,
|
|
1483
|
+
...renderShellLockAssertion({
|
|
1484
|
+
functionName: "assert_quiescent_descriptor",
|
|
1485
|
+
variablePrefix: "quiescent",
|
|
1486
|
+
path: paths.quiescent,
|
|
1487
|
+
descriptorFd: 6
|
|
1488
|
+
}),
|
|
1489
|
+
"assert_quiescent_descriptor || exit 1",
|
|
1490
|
+
"sync -f /proc/self/fd/6 || exit 1",
|
|
1491
|
+
`sync -f ${shellQuote(paths.directory)} || exit 1`
|
|
1492
|
+
];
|
|
1493
|
+
}
|
|
1494
|
+
function detachedProcessReaperProgram() {
|
|
1495
|
+
return [
|
|
1496
|
+
"import ctypes",
|
|
1497
|
+
"import errno",
|
|
1498
|
+
"import fcntl",
|
|
1499
|
+
"import json",
|
|
1500
|
+
"import os",
|
|
1501
|
+
"import re",
|
|
1502
|
+
"import stat",
|
|
1503
|
+
"import subprocess",
|
|
1504
|
+
"import sys",
|
|
1505
|
+
"import time",
|
|
1506
|
+
"",
|
|
1507
|
+
"PR_SET_CHILD_SUBREAPER = 36",
|
|
1508
|
+
"command = sys.argv[1]",
|
|
1509
|
+
"logger_mode = sys.argv[2]",
|
|
1510
|
+
"node_program = sys.argv[3]",
|
|
1511
|
+
"shell_program = sys.argv[4]",
|
|
1512
|
+
"stdout_args = sys.argv[5:11]",
|
|
1513
|
+
"stderr_args = sys.argv[11:17]",
|
|
1514
|
+
"completion_path = sys.argv[17]",
|
|
1515
|
+
"started_partial_path = sys.argv[18]",
|
|
1516
|
+
"started_path = sys.argv[19]",
|
|
1517
|
+
"launch_directory = sys.argv[20]",
|
|
1518
|
+
"target_pid = int(sys.argv[21])",
|
|
1519
|
+
"target_ticks = sys.argv[22]",
|
|
1520
|
+
"target_session = int(sys.argv[23])",
|
|
1521
|
+
"target_descriptor = sys.argv[24]",
|
|
1522
|
+
"environment_mode = sys.argv[25]",
|
|
1523
|
+
"environment_fd = int(sys.argv[26])",
|
|
1524
|
+
"completion_fd = int(sys.argv[27])",
|
|
1525
|
+
"if len(stdout_args) != 6 or len(stderr_args) != 6:",
|
|
1526
|
+
" raise SystemExit(1)",
|
|
1527
|
+
'if environment_mode not in ("exec", "supervisor-fd-v1"):',
|
|
1528
|
+
" raise SystemExit(1)",
|
|
1529
|
+
"if os.getpid() != target_pid or os.getpgrp() != target_pid or os.getsid(0) != target_session:",
|
|
1530
|
+
" raise SystemExit(1)",
|
|
1531
|
+
"",
|
|
1532
|
+
"def process_start_ticks(pid):",
|
|
1533
|
+
' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
|
|
1534
|
+
" raw = stat_file.read()",
|
|
1535
|
+
' marker = raw.rfind(b") ")',
|
|
1536
|
+
" fields = raw[marker + 2:].split() if marker >= 0 else []",
|
|
1537
|
+
" if len(fields) <= 19:",
|
|
1538
|
+
" raise SystemExit(1)",
|
|
1539
|
+
' return fields[19].decode("ascii")',
|
|
1540
|
+
"",
|
|
1541
|
+
"def consume_exec_environment():",
|
|
1542
|
+
" descriptor_stats = os.fstat(environment_fd)",
|
|
1543
|
+
" if (",
|
|
1544
|
+
" not stat.S_ISREG(descriptor_stats.st_mode)",
|
|
1545
|
+
" or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
|
|
1546
|
+
" or descriptor_stats.st_uid != os.geteuid()",
|
|
1547
|
+
" or descriptor_stats.st_nlink != 0",
|
|
1548
|
+
" or descriptor_stats.st_size <= 0",
|
|
1549
|
+
` or descriptor_stats.st_size > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}`,
|
|
1550
|
+
" ):",
|
|
1551
|
+
" raise SystemExit(1)",
|
|
1552
|
+
' source = b""',
|
|
1553
|
+
" try:",
|
|
1554
|
+
` while len(source) <= ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
|
|
1555
|
+
` chunk = os.read(environment_fd, ${SUPERVISOR_ENVIRONMENT_MAX_BYTES + 1} - len(source))`,
|
|
1556
|
+
" if not chunk:",
|
|
1557
|
+
" break",
|
|
1558
|
+
" source += chunk",
|
|
1559
|
+
" finally:",
|
|
1560
|
+
" os.ftruncate(environment_fd, 0)",
|
|
1561
|
+
" os.close(environment_fd)",
|
|
1562
|
+
` if not source or len(source) > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
|
|
1563
|
+
" raise SystemExit(1)",
|
|
1564
|
+
" try:",
|
|
1565
|
+
' payload = json.loads(source.decode("utf-8", errors="strict"))',
|
|
1566
|
+
" except (UnicodeDecodeError, json.JSONDecodeError):",
|
|
1567
|
+
" raise SystemExit(1)",
|
|
1568
|
+
" if (",
|
|
1569
|
+
" type(payload) is not dict",
|
|
1570
|
+
' or set(payload) != {"version", "environment"}',
|
|
1571
|
+
' or type(payload.get("version")) is not int',
|
|
1572
|
+
' or payload.get("version") != 1',
|
|
1573
|
+
' or type(payload.get("environment")) is not dict',
|
|
1574
|
+
" ):",
|
|
1575
|
+
" raise SystemExit(1)",
|
|
1576
|
+
' environment = payload["environment"]',
|
|
1577
|
+
` if len(environment) > ${SUPERVISOR_ENVIRONMENT_MAX_ENTRIES} or any(`,
|
|
1578
|
+
" type(name) is not str",
|
|
1579
|
+
` or len(name) > ${SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES}`,
|
|
1580
|
+
' or re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) is None',
|
|
1581
|
+
` or name in (${JSON.stringify(SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV)}, ${JSON.stringify(SUPERVISOR_ENVIRONMENT_FD_ENV)})`,
|
|
1582
|
+
' or "\\x00" in name',
|
|
1583
|
+
" or type(value) is not str",
|
|
1584
|
+
' or "\\x00" in value',
|
|
1585
|
+
" for name, value in environment.items()",
|
|
1586
|
+
" ):",
|
|
1587
|
+
" raise SystemExit(1)",
|
|
1588
|
+
" payload_environment = {",
|
|
1589
|
+
...Object.entries(DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT).map(
|
|
1590
|
+
([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`
|
|
1591
|
+
),
|
|
1592
|
+
" }",
|
|
1593
|
+
" payload_environment.update(environment)",
|
|
1594
|
+
" return payload_environment",
|
|
1595
|
+
"",
|
|
1596
|
+
"def validate_completion_descriptor(expected_size=None):",
|
|
1597
|
+
" descriptor_stats = os.fstat(completion_fd)",
|
|
1598
|
+
" path_stats = os.lstat(completion_path)",
|
|
1599
|
+
" if (",
|
|
1600
|
+
" not stat.S_ISREG(descriptor_stats.st_mode)",
|
|
1601
|
+
" or not stat.S_ISREG(path_stats.st_mode)",
|
|
1602
|
+
" or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
|
|
1603
|
+
" or stat.S_IMODE(path_stats.st_mode) != 0o600",
|
|
1604
|
+
" or descriptor_stats.st_uid != os.geteuid()",
|
|
1605
|
+
" or path_stats.st_uid != os.geteuid()",
|
|
1606
|
+
" or descriptor_stats.st_nlink != 1",
|
|
1607
|
+
" or path_stats.st_nlink != 1",
|
|
1608
|
+
" or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
|
|
1609
|
+
" or (expected_size is not None and descriptor_stats.st_size != expected_size)",
|
|
1610
|
+
" ):",
|
|
1611
|
+
" raise SystemExit(1)",
|
|
1612
|
+
" return descriptor_stats",
|
|
1613
|
+
"",
|
|
1614
|
+
"def validate_launch_directory(directory_fd):",
|
|
1615
|
+
" descriptor_stats = os.fstat(directory_fd)",
|
|
1616
|
+
" path_stats = os.lstat(launch_directory)",
|
|
1617
|
+
" if (",
|
|
1618
|
+
" not stat.S_ISDIR(descriptor_stats.st_mode)",
|
|
1619
|
+
" or not stat.S_ISDIR(path_stats.st_mode)",
|
|
1620
|
+
" or stat.S_IMODE(descriptor_stats.st_mode) != 0o700",
|
|
1621
|
+
" or stat.S_IMODE(path_stats.st_mode) != 0o700",
|
|
1622
|
+
" or descriptor_stats.st_uid != os.geteuid()",
|
|
1623
|
+
" or path_stats.st_uid != os.geteuid()",
|
|
1624
|
+
" or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
|
|
1625
|
+
" ):",
|
|
1626
|
+
" raise SystemExit(1)",
|
|
1627
|
+
"",
|
|
1628
|
+
"def publish_started():",
|
|
1629
|
+
" if (",
|
|
1630
|
+
" os.path.dirname(started_partial_path) != launch_directory",
|
|
1631
|
+
" or os.path.dirname(started_path) != launch_directory",
|
|
1632
|
+
" ):",
|
|
1633
|
+
" raise SystemExit(1)",
|
|
1634
|
+
" partial_leaf = os.path.basename(started_partial_path)",
|
|
1635
|
+
" started_leaf = os.path.basename(started_path)",
|
|
1636
|
+
` value = f"${STARTED_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
|
|
1637
|
+
" directory_fd = os.open(",
|
|
1638
|
+
" launch_directory,",
|
|
1639
|
+
" os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,",
|
|
1640
|
+
" )",
|
|
1641
|
+
" started_fd = -1",
|
|
1642
|
+
" try:",
|
|
1643
|
+
" validate_launch_directory(directory_fd)",
|
|
1644
|
+
" started_fd = os.open(",
|
|
1645
|
+
" partial_leaf,",
|
|
1646
|
+
" os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW,",
|
|
1647
|
+
" 0o600,",
|
|
1648
|
+
" dir_fd=directory_fd,",
|
|
1649
|
+
" )",
|
|
1650
|
+
" os.fchmod(started_fd, 0o600)",
|
|
1651
|
+
" offset = 0",
|
|
1652
|
+
" while offset < len(value):",
|
|
1653
|
+
" written = os.write(started_fd, value[offset:])",
|
|
1654
|
+
" if written <= 0:",
|
|
1655
|
+
" raise SystemExit(1)",
|
|
1656
|
+
" offset += written",
|
|
1657
|
+
" os.fsync(started_fd)",
|
|
1658
|
+
" partial_stats = os.fstat(started_fd)",
|
|
1659
|
+
" if (",
|
|
1660
|
+
" not stat.S_ISREG(partial_stats.st_mode)",
|
|
1661
|
+
" or stat.S_IMODE(partial_stats.st_mode) != 0o600",
|
|
1662
|
+
" or partial_stats.st_uid != os.geteuid()",
|
|
1663
|
+
" or partial_stats.st_nlink != 1",
|
|
1664
|
+
" or partial_stats.st_size != len(value)",
|
|
1665
|
+
" ):",
|
|
1666
|
+
" raise SystemExit(1)",
|
|
1667
|
+
" os.replace(",
|
|
1668
|
+
" partial_leaf,",
|
|
1669
|
+
" started_leaf,",
|
|
1670
|
+
" src_dir_fd=directory_fd,",
|
|
1671
|
+
" dst_dir_fd=directory_fd,",
|
|
1672
|
+
" )",
|
|
1673
|
+
" os.fsync(directory_fd)",
|
|
1674
|
+
" validate_launch_directory(directory_fd)",
|
|
1675
|
+
" published_stats = os.stat(started_leaf, dir_fd=directory_fd, follow_symlinks=False)",
|
|
1676
|
+
" full_path_stats = os.lstat(started_path)",
|
|
1677
|
+
" if (",
|
|
1678
|
+
" (published_stats.st_dev, published_stats.st_ino)",
|
|
1679
|
+
" != (partial_stats.st_dev, partial_stats.st_ino)",
|
|
1680
|
+
" or (full_path_stats.st_dev, full_path_stats.st_ino)",
|
|
1681
|
+
" != (partial_stats.st_dev, partial_stats.st_ino)",
|
|
1682
|
+
" or published_stats.st_nlink != 1",
|
|
1683
|
+
" or full_path_stats.st_nlink != 1",
|
|
1684
|
+
" or published_stats.st_size != len(value)",
|
|
1685
|
+
" or full_path_stats.st_size != len(value)",
|
|
1686
|
+
" ):",
|
|
1687
|
+
" raise SystemExit(1)",
|
|
1688
|
+
" finally:",
|
|
1689
|
+
" if started_fd >= 0:",
|
|
1690
|
+
" os.close(started_fd)",
|
|
1691
|
+
" os.close(directory_fd)",
|
|
1692
|
+
"",
|
|
1693
|
+
"if process_start_ticks(target_pid) != target_ticks:",
|
|
1694
|
+
" raise SystemExit(1)",
|
|
1695
|
+
"validate_completion_descriptor(0)",
|
|
1696
|
+
"os.set_inheritable(completion_fd, False)",
|
|
1697
|
+
"libc = ctypes.CDLL(None, use_errno=True)",
|
|
1698
|
+
"if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:",
|
|
1699
|
+
" raise SystemExit(1)",
|
|
1700
|
+
"payload_environment = None",
|
|
1701
|
+
'if environment_mode == "exec":',
|
|
1702
|
+
" payload_environment = consume_exec_environment()",
|
|
1703
|
+
" environment_fd = -1",
|
|
1704
|
+
"publish_started()",
|
|
1705
|
+
"",
|
|
1706
|
+
"def spawn_logger(arguments):",
|
|
1707
|
+
' if logger_mode == "node":',
|
|
1708
|
+
' argv = ["node", "-e", node_program, *arguments]',
|
|
1709
|
+
' elif logger_mode == "shell":',
|
|
1710
|
+
' argv = ["sh", "-c", shell_program, "bounded-log", *arguments]',
|
|
1711
|
+
" else:",
|
|
1712
|
+
" raise SystemExit(1)",
|
|
1713
|
+
" return subprocess.Popen(",
|
|
1714
|
+
" argv,",
|
|
1715
|
+
" stdin=subprocess.DEVNULL,",
|
|
1716
|
+
" stdout=subprocess.DEVNULL,",
|
|
1717
|
+
" stderr=subprocess.DEVNULL,",
|
|
1718
|
+
" close_fds=True,",
|
|
1719
|
+
" )",
|
|
1720
|
+
"",
|
|
1721
|
+
"def open_fifo_writer(path, logger):",
|
|
1722
|
+
" deadline = time.monotonic() + 5",
|
|
1723
|
+
" while True:",
|
|
1724
|
+
" try:",
|
|
1725
|
+
" descriptor = os.open(",
|
|
1726
|
+
" path,",
|
|
1727
|
+
" os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC,",
|
|
1728
|
+
" )",
|
|
1729
|
+
" break",
|
|
1730
|
+
" except OSError as error:",
|
|
1731
|
+
" if error.errno != errno.ENXIO or logger.poll() is not None or time.monotonic() >= deadline:",
|
|
1732
|
+
" raise",
|
|
1733
|
+
" time.sleep(0.01)",
|
|
1734
|
+
" descriptor_stats = os.fstat(descriptor)",
|
|
1735
|
+
" path_stats = os.lstat(path)",
|
|
1736
|
+
" if (",
|
|
1737
|
+
" not stat.S_ISFIFO(descriptor_stats.st_mode)",
|
|
1738
|
+
" or not stat.S_ISFIFO(path_stats.st_mode)",
|
|
1739
|
+
" or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
|
|
1740
|
+
" or stat.S_IMODE(path_stats.st_mode) != 0o600",
|
|
1741
|
+
" or descriptor_stats.st_uid != os.geteuid()",
|
|
1742
|
+
" or path_stats.st_uid != os.geteuid()",
|
|
1743
|
+
" or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
|
|
1744
|
+
" ):",
|
|
1745
|
+
" os.close(descriptor)",
|
|
1746
|
+
" raise SystemExit(1)",
|
|
1747
|
+
" flags = fcntl.fcntl(descriptor, fcntl.F_GETFL)",
|
|
1748
|
+
" fcntl.fcntl(descriptor, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)",
|
|
1749
|
+
' return os.fdopen(descriptor, "wb", buffering=0)',
|
|
1750
|
+
"",
|
|
1751
|
+
"if environment_fd < 0:",
|
|
1752
|
+
" try:",
|
|
1753
|
+
` os.close(${SUPERVISOR_ENVIRONMENT_FD})`,
|
|
1754
|
+
" except OSError:",
|
|
1755
|
+
" pass",
|
|
1756
|
+
"children = []",
|
|
1757
|
+
"writers = []",
|
|
1758
|
+
"payload = None",
|
|
1759
|
+
"payload_returncode = 1",
|
|
1760
|
+
"initialization_failed = False",
|
|
1761
|
+
"try:",
|
|
1762
|
+
" stdout_logger = spawn_logger(stdout_args)",
|
|
1763
|
+
" children.append(stdout_logger)",
|
|
1764
|
+
" stderr_logger = spawn_logger(stderr_args)",
|
|
1765
|
+
" children.append(stderr_logger)",
|
|
1766
|
+
" stdout_writer = open_fifo_writer(stdout_args[0], stdout_logger)",
|
|
1767
|
+
" writers.append(stdout_writer)",
|
|
1768
|
+
" stderr_writer = open_fifo_writer(stderr_args[0], stderr_logger)",
|
|
1769
|
+
" writers.append(stderr_writer)",
|
|
1770
|
+
" payload = subprocess.Popen(",
|
|
1771
|
+
' ["/bin/sh", "-c", command],',
|
|
1772
|
+
" stdin=subprocess.DEVNULL,",
|
|
1773
|
+
" stdout=stdout_writer,",
|
|
1774
|
+
" stderr=stderr_writer,",
|
|
1775
|
+
" env=payload_environment,",
|
|
1776
|
+
" close_fds=True,",
|
|
1777
|
+
" pass_fds=(() if environment_fd < 0 else (environment_fd,)),",
|
|
1778
|
+
" )",
|
|
1779
|
+
" children.append(payload)",
|
|
1780
|
+
"except BaseException:",
|
|
1781
|
+
" initialization_failed = True",
|
|
1782
|
+
"finally:",
|
|
1783
|
+
" for writer in writers:",
|
|
1784
|
+
" try:",
|
|
1785
|
+
" writer.close()",
|
|
1786
|
+
" except OSError:",
|
|
1787
|
+
" pass",
|
|
1788
|
+
" if environment_fd >= 0:",
|
|
1789
|
+
" try:",
|
|
1790
|
+
" os.close(environment_fd)",
|
|
1791
|
+
" except OSError:",
|
|
1792
|
+
" pass",
|
|
1793
|
+
"",
|
|
1794
|
+
"if initialization_failed:",
|
|
1795
|
+
" for child in children:",
|
|
1796
|
+
" if child.poll() is None:",
|
|
1797
|
+
" try:",
|
|
1798
|
+
" child.terminate()",
|
|
1799
|
+
" except ProcessLookupError:",
|
|
1800
|
+
" pass",
|
|
1801
|
+
" for child in children:",
|
|
1802
|
+
" try:",
|
|
1803
|
+
" child.wait(timeout=2)",
|
|
1804
|
+
" except subprocess.TimeoutExpired:",
|
|
1805
|
+
" try:",
|
|
1806
|
+
" child.kill()",
|
|
1807
|
+
" except ProcessLookupError:",
|
|
1808
|
+
" pass",
|
|
1809
|
+
" child.wait()",
|
|
1810
|
+
"else:",
|
|
1811
|
+
" payload_returncode = payload.wait()",
|
|
1812
|
+
" stdout_logger.wait()",
|
|
1813
|
+
" stderr_logger.wait()",
|
|
1814
|
+
"while True:",
|
|
1815
|
+
" try:",
|
|
1816
|
+
" os.wait()",
|
|
1817
|
+
" except InterruptedError:",
|
|
1818
|
+
" continue",
|
|
1819
|
+
" except ChildProcessError:",
|
|
1820
|
+
" break",
|
|
1821
|
+
"",
|
|
1822
|
+
`completion = f"${QUIESCENT_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
|
|
1823
|
+
"validate_completion_descriptor()",
|
|
1824
|
+
"os.ftruncate(completion_fd, 0)",
|
|
1825
|
+
"os.lseek(completion_fd, 0, os.SEEK_SET)",
|
|
1826
|
+
"offset = 0",
|
|
1827
|
+
"while offset < len(completion):",
|
|
1828
|
+
" written = os.write(completion_fd, completion[offset:])",
|
|
1829
|
+
" if written <= 0:",
|
|
1830
|
+
" raise SystemExit(1)",
|
|
1831
|
+
" offset += written",
|
|
1832
|
+
"os.fsync(completion_fd)",
|
|
1833
|
+
"validate_completion_descriptor(len(completion))",
|
|
1834
|
+
"raise SystemExit(payload_returncode if 0 <= payload_returncode <= 255 else 1)"
|
|
1835
|
+
].join("\n");
|
|
1836
|
+
}
|
|
1837
|
+
function boundedLogCaptureLaunch(paths, descriptorKey, environmentMode) {
|
|
1838
|
+
const stdoutArgs = [
|
|
1839
|
+
logPipePath(paths.stdout),
|
|
1840
|
+
paths.stdout,
|
|
1841
|
+
previousLogPath(paths.stdout),
|
|
1842
|
+
logSnapshotPath(paths.stdout),
|
|
1843
|
+
logSnapshotStagingPath(paths.stdout),
|
|
1844
|
+
logChunkPath(paths.stdout)
|
|
1845
|
+
];
|
|
1846
|
+
const stderrArgs = [
|
|
1847
|
+
logPipePath(paths.stderr),
|
|
1848
|
+
paths.stderr,
|
|
1849
|
+
previousLogPath(paths.stderr),
|
|
1850
|
+
logSnapshotPath(paths.stderr),
|
|
1851
|
+
logSnapshotStagingPath(paths.stderr),
|
|
1852
|
+
logChunkPath(paths.stderr)
|
|
1853
|
+
];
|
|
1854
|
+
const shellLogger = [...boundedLogShellFunctions(), 'bounded_log_shell "$@"'].join("\n");
|
|
1855
|
+
const args = [
|
|
1856
|
+
'"$1"',
|
|
1857
|
+
'"$logger_mode"',
|
|
1858
|
+
shellQuote(boundedLogProgram()),
|
|
1859
|
+
shellQuote(shellLogger),
|
|
1860
|
+
...stdoutArgs.map(shellQuote),
|
|
1861
|
+
...stderrArgs.map(shellQuote),
|
|
1862
|
+
shellQuote(paths.quiescent),
|
|
1863
|
+
shellQuote(paths.startedPartial),
|
|
1864
|
+
shellQuote(paths.started),
|
|
1865
|
+
shellQuote(paths.directory),
|
|
1866
|
+
'"$pid"',
|
|
1867
|
+
'"$ticks"',
|
|
1868
|
+
'"$session"',
|
|
1869
|
+
shellQuote(descriptorKey),
|
|
1870
|
+
shellQuote(environmentMode),
|
|
1871
|
+
String(SUPERVISOR_ENVIRONMENT_FD),
|
|
1872
|
+
"6"
|
|
1873
|
+
];
|
|
1874
|
+
return [
|
|
1875
|
+
"if command -v node >/dev/null 2>&1; then logger_mode=node; else logger_mode=shell; fi",
|
|
1876
|
+
// The provider-selected cwd is payload state, not trusted lifecycle code.
|
|
1877
|
+
// Isolated/no-site mode keeps it and sitecustomize out of reaper startup.
|
|
1878
|
+
`exec python3 -I -S -c ${shellQuote(detachedProcessReaperProgram())} ${args.join(" ")}`
|
|
1879
|
+
];
|
|
1880
|
+
}
|
|
1881
|
+
function buildPrepareDetachedCommand(paths, descriptorKey, command, environmentMode = "exec", restartReleasedWhenExited = false) {
|
|
1882
|
+
const recordWrite = `printf '${IDENTITY_PREFIX} %s %s %s ${descriptorKey}\\n' "$pid" "$ticks" "$session" > ` + shellQuote(paths.recordPartial);
|
|
1883
|
+
const child = [
|
|
1884
|
+
"pid=$$",
|
|
1885
|
+
"stat=$(cat /proc/$$/stat 2>/dev/null) || exit 1",
|
|
1886
|
+
"rest=${stat##*) }",
|
|
1887
|
+
`pgrp=$(printf '%s\\n' "$rest" | awk '{print $3}')`,
|
|
1888
|
+
`session=$(printf '%s\\n' "$rest" | awk '{print $4}')`,
|
|
1889
|
+
`ticks=$(printf '%s\\n' "$rest" | awk '{print $20}')`,
|
|
1890
|
+
`case "$pid:$pgrp:$session:$ticks" in *[!0-9:]*) exit 1 ;; esac`,
|
|
1891
|
+
'[ "$pid" = "$pgrp" ] && [ "$pid" = "$session" ] && [ -n "$ticks" ] || exit 1',
|
|
1892
|
+
...boundedLogCaptureSetup(paths),
|
|
1893
|
+
...atomicFile(paths.recordPartial, paths.record, paths.directory, recordWrite),
|
|
1894
|
+
...restartReleasedWhenExited ? ["exec 9>&-"] : [],
|
|
1895
|
+
"attempt=0",
|
|
1896
|
+
`while [ ! -s ${shellQuote(paths.decision)} ] && [ "$attempt" -lt 1200 ]; do`,
|
|
1897
|
+
" sleep 0.05",
|
|
1898
|
+
" attempt=$((attempt + 1))",
|
|
1899
|
+
"done",
|
|
1900
|
+
...decisionFunctions(paths),
|
|
1901
|
+
"read_launch_decision || exit 1",
|
|
1902
|
+
`[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || exit 1`,
|
|
1903
|
+
'[ "$decision_action" = RELEASE ] || exit 1',
|
|
1904
|
+
'[ "$decision_pid:$decision_ticks:$decision_session" = "$pid:$ticks:$session" ] || exit 1',
|
|
1905
|
+
...boundedLogCaptureLaunch(paths, descriptorKey, environmentMode)
|
|
1906
|
+
].join("\n");
|
|
1907
|
+
const childCommand = `set -- ${shellQuote(command)}
|
|
1908
|
+
${child}`;
|
|
1909
|
+
const launch = buildEnvironmentFdLaunch(paths, childCommand, environmentMode);
|
|
1910
|
+
return cleanLifecycleShell(
|
|
1911
|
+
[
|
|
1912
|
+
"umask 077",
|
|
1913
|
+
...secureDetachedRoot(),
|
|
1914
|
+
...restartReleasedWhenExited ? generationLock(paths) : [],
|
|
1915
|
+
...identityFunctions(paths),
|
|
1916
|
+
...decisionFunctions(paths),
|
|
1917
|
+
...processTreeFunctions(paths),
|
|
1918
|
+
...restartReleasedWhenExited ? retireExitedReleasedLaunch(paths, descriptorKey) : [],
|
|
1919
|
+
`if [ ! -e ${shellQuote(paths.directory)} ] && [ ! -L ${shellQuote(paths.directory)} ] && mkdir ${shellQuote(paths.directory)} 2>/dev/null; then`,
|
|
1920
|
+
...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
|
|
1921
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1922
|
+
...launch.map((line) => ` ${line}`),
|
|
1923
|
+
"fi",
|
|
1924
|
+
...secureLaunchDirectory(paths, false),
|
|
1925
|
+
"attempt=0",
|
|
1926
|
+
`while [ ! -s ${shellQuote(paths.record)} ] && [ "$attempt" -lt 200 ]; do`,
|
|
1927
|
+
" sleep 0.05",
|
|
1928
|
+
" attempt=$((attempt + 1))",
|
|
1929
|
+
"done",
|
|
1930
|
+
"read_launch_identity || exit 1",
|
|
1931
|
+
`if [ "$target_descriptor" != ${shellQuote(descriptorKey)} ]; then`,
|
|
1932
|
+
` printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'`,
|
|
1933
|
+
" exit 2",
|
|
1934
|
+
"fi",
|
|
1935
|
+
"if read_launch_decision; then",
|
|
1936
|
+
` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
1937
|
+
` [ "$decision_action" = RELEASE ] || { printf '${CANCELLED_SENTINEL}\\n'; exit 3; }`,
|
|
1938
|
+
...waitForStarted(paths).map((line) => ` ${line}`),
|
|
1939
|
+
"else",
|
|
1940
|
+
" leader_identity_status || exit 1",
|
|
1941
|
+
"fi",
|
|
1942
|
+
...restartReleasedWhenExited ? ["exec 9>&-"] : [],
|
|
1943
|
+
`printf '${PREPARED_SENTINEL} %s %s %s %s\\n' "$target_pid" "$target_ticks" "$target_session" "$target_descriptor"`
|
|
1944
|
+
].join("\n"),
|
|
1945
|
+
environmentMode
|
|
1946
|
+
);
|
|
1947
|
+
}
|
|
1948
|
+
function buildReleaseDetachedCommand(paths, identity, serializeGenerationChanges = false) {
|
|
1949
|
+
return [
|
|
1950
|
+
"umask 077",
|
|
1951
|
+
...serializeGenerationChanges ? acquireGenerationLock(paths) : [],
|
|
1952
|
+
...serializeGenerationChanges ? [] : secureDetachedRoot(),
|
|
1953
|
+
...secureLaunchDirectory(paths, false),
|
|
1954
|
+
...identityFunctions(paths),
|
|
1955
|
+
...decisionFunctions(paths),
|
|
1956
|
+
...serializeGenerationChanges ? processTreeFunctions(paths) : [],
|
|
1957
|
+
"read_launch_identity || exit 1",
|
|
1958
|
+
`[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
|
|
1959
|
+
`${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.descriptorKey}`
|
|
1960
|
+
)} ] || exit 1`,
|
|
1961
|
+
"publish_pid=$target_pid",
|
|
1962
|
+
"publish_ticks=$target_ticks",
|
|
1963
|
+
"publish_session=$target_session",
|
|
1964
|
+
"publish_descriptor=$target_descriptor",
|
|
1965
|
+
...publishDecision(paths, "RELEASE", paths.releaseDecisionPartial),
|
|
1966
|
+
'[ "$decision_action" = RELEASE ] || exit 3',
|
|
1967
|
+
'[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
|
|
1968
|
+
...releasedAdoptionOutcome(
|
|
1969
|
+
paths,
|
|
1970
|
+
identity.descriptorKey,
|
|
1971
|
+
serializeGenerationChanges
|
|
1972
|
+
)
|
|
1973
|
+
].join("\n");
|
|
1974
|
+
}
|
|
1975
|
+
function isReleaseConfirmation(output, identity) {
|
|
1976
|
+
return Boolean(
|
|
1977
|
+
parseIdentityOutput(
|
|
1978
|
+
RELEASED_PATTERN,
|
|
1979
|
+
identity.provider,
|
|
1980
|
+
pathsForIdentity(identity),
|
|
1981
|
+
identity.descriptorKey,
|
|
1982
|
+
output
|
|
1983
|
+
)
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
function buildCancelDetachedCommand(paths, descriptorKey, expected, serializeGenerationChanges = false) {
|
|
1987
|
+
return [
|
|
1988
|
+
"umask 077",
|
|
1989
|
+
...serializeGenerationChanges ? acquireGenerationLock(paths) : secureDetachedRoot(),
|
|
1990
|
+
...secureLaunchDirectory(paths, true),
|
|
1991
|
+
`sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
1992
|
+
...identityFunctions(paths),
|
|
1993
|
+
...decisionFunctions(paths),
|
|
1994
|
+
...processTreeFunctions(paths),
|
|
1995
|
+
"if read_launch_identity; then",
|
|
1996
|
+
` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
1997
|
+
...expected ? [
|
|
1998
|
+
` [ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
|
|
1999
|
+
`${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
|
|
2000
|
+
)} ] || exit 1`
|
|
2001
|
+
] : [],
|
|
2002
|
+
" publish_pid=$target_pid",
|
|
2003
|
+
" publish_ticks=$target_ticks",
|
|
2004
|
+
" publish_session=$target_session",
|
|
2005
|
+
"else",
|
|
2006
|
+
" publish_pid=0",
|
|
2007
|
+
" publish_ticks=0",
|
|
2008
|
+
" publish_session=0",
|
|
2009
|
+
"fi",
|
|
2010
|
+
`publish_descriptor=${shellQuote(descriptorKey)}`,
|
|
2011
|
+
...publishDecision(paths, "CANCEL", paths.cancelDecisionPartial),
|
|
2012
|
+
`[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
|
|
2013
|
+
'if [ "$decision_action" = RELEASE ]; then',
|
|
2014
|
+
...releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges).map(
|
|
2015
|
+
(line) => ` ${line}`
|
|
2016
|
+
),
|
|
2017
|
+
"fi",
|
|
2018
|
+
"# CANCEL won the only durable decision. The child can never execute the requested command.",
|
|
2019
|
+
"if read_launch_identity; then",
|
|
2020
|
+
...stopTargetCommands().map((line) => ` ${line}`),
|
|
2021
|
+
"fi",
|
|
2022
|
+
`printf '${CANCELLED_SENTINEL}\\n'`
|
|
2023
|
+
].join("\n");
|
|
2024
|
+
}
|
|
2025
|
+
function parseCancellationResult(provider, paths, descriptorKey, output) {
|
|
2026
|
+
if (output.trim() === CANCELLED_SENTINEL) return { state: "cancelled" };
|
|
2027
|
+
if (output.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
|
|
2028
|
+
return { state: "released_generation_unavailable" };
|
|
2029
|
+
}
|
|
2030
|
+
const identity = parseReleasedIdentity(
|
|
2031
|
+
provider,
|
|
2032
|
+
paths,
|
|
2033
|
+
descriptorKey,
|
|
2034
|
+
output
|
|
2035
|
+
);
|
|
2036
|
+
return identity ? { state: "released", identity } : null;
|
|
2037
|
+
}
|
|
2038
|
+
function buildStopDetachedCommand(paths, expected) {
|
|
2039
|
+
return [
|
|
2040
|
+
"umask 077",
|
|
2041
|
+
...secureDetachedRoot(),
|
|
2042
|
+
...secureLaunchDirectory(paths, false),
|
|
2043
|
+
...identityFunctions(paths),
|
|
2044
|
+
...processTreeFunctions(paths),
|
|
2045
|
+
"read_launch_identity || exit 1",
|
|
2046
|
+
`[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
|
|
2047
|
+
`${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
|
|
2048
|
+
)} ] || exit 1`,
|
|
2049
|
+
"# Revalidate the leader birth immediately before every scan and every kill.",
|
|
2050
|
+
...stopTargetCommands(),
|
|
2051
|
+
`printf '${STOPPED_SENTINEL}\\n'`
|
|
2052
|
+
].join("\n");
|
|
2053
|
+
}
|
|
2054
|
+
function disposableLaunchDirectoryProof(paths, expected, namespace) {
|
|
2055
|
+
const readIdentity = `read_exact_${namespace}_identity`;
|
|
2056
|
+
const readStarted = `read_exact_${namespace}_started`;
|
|
2057
|
+
const readQuiescent = `read_exact_${namespace}_quiescent`;
|
|
2058
|
+
const readEmptyQuiescent = `read_exact_${namespace}_empty_quiescent`;
|
|
2059
|
+
const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:` + expected.descriptorKey;
|
|
2060
|
+
return [
|
|
2061
|
+
...secureLaunchDirectory(paths, false),
|
|
2062
|
+
...identityFunctions(paths),
|
|
2063
|
+
...exactLifecycleMarkerFunction(
|
|
2064
|
+
readIdentity,
|
|
2065
|
+
`exact_${namespace}_identity`,
|
|
2066
|
+
paths.record,
|
|
2067
|
+
{ kind: "populated", markerPrefix: IDENTITY_PREFIX }
|
|
2068
|
+
),
|
|
2069
|
+
...exactLifecycleMarkerFunction(
|
|
2070
|
+
readStarted,
|
|
2071
|
+
`exact_${namespace}_started`,
|
|
2072
|
+
paths.started,
|
|
2073
|
+
{ kind: "populated", markerPrefix: STARTED_PREFIX }
|
|
2074
|
+
),
|
|
2075
|
+
...exactLifecycleMarkerFunction(
|
|
2076
|
+
readQuiescent,
|
|
2077
|
+
`exact_${namespace}_quiescent`,
|
|
2078
|
+
paths.quiescent,
|
|
2079
|
+
{ kind: "populated", markerPrefix: QUIESCENT_PREFIX }
|
|
2080
|
+
),
|
|
2081
|
+
...exactLifecycleMarkerFunction(
|
|
2082
|
+
readEmptyQuiescent,
|
|
2083
|
+
`exact_${namespace}_empty_quiescent`,
|
|
2084
|
+
paths.quiescent,
|
|
2085
|
+
{ kind: "empty" }
|
|
2086
|
+
),
|
|
2087
|
+
"read_launch_identity || exit 1",
|
|
2088
|
+
`[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 1`,
|
|
2089
|
+
'[ "$target_reaper_protocol" = v3 ] || exit 1',
|
|
2090
|
+
`${readIdentity} || exit 1`,
|
|
2091
|
+
"leader_identity_status",
|
|
2092
|
+
`${namespace}_leader_status=$?`,
|
|
2093
|
+
`[ "$${namespace}_leader_status" -ne 0 ] || exit 1`,
|
|
2094
|
+
`${readStarted}`,
|
|
2095
|
+
`${namespace}_started_status=$?`,
|
|
2096
|
+
`case "$${namespace}_started_status" in`,
|
|
2097
|
+
` 0) ${readQuiescent} || exit 1 ;;`,
|
|
2098
|
+
` 1) ${readEmptyQuiescent} || exit 1 ;;`,
|
|
2099
|
+
" *) exit 1 ;;",
|
|
2100
|
+
"esac"
|
|
2101
|
+
];
|
|
2102
|
+
}
|
|
2103
|
+
function buildDisposeDetachedArtifactsCommand(paths, expected) {
|
|
2104
|
+
const disposedDirectory = disposedDirectoryForIdentity(expected);
|
|
2105
|
+
const retiredPaths = pathsForDetachedLaunchDirectory(
|
|
2106
|
+
paths,
|
|
2107
|
+
paths.retiredDirectory
|
|
2108
|
+
);
|
|
2109
|
+
return [
|
|
2110
|
+
"umask 077",
|
|
2111
|
+
...acquireGenerationLock(paths),
|
|
2112
|
+
`if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then`,
|
|
2113
|
+
...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
|
|
2114
|
+
` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
|
|
2115
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2116
|
+
"fi",
|
|
2117
|
+
`if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
|
|
2118
|
+
...disposableLaunchDirectoryProof(
|
|
2119
|
+
retiredPaths,
|
|
2120
|
+
expected,
|
|
2121
|
+
"retired_disposal"
|
|
2122
|
+
).map((line) => ` ${line}`),
|
|
2123
|
+
` mv -- ${shellQuote(paths.retiredDirectory)} ${shellQuote(disposedDirectory)} || exit 1`,
|
|
2124
|
+
...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
|
|
2125
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2126
|
+
` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
|
|
2127
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2128
|
+
"fi",
|
|
2129
|
+
`if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
|
|
2130
|
+
...disposableLaunchDirectoryProof(paths, expected, "live_disposal").map(
|
|
2131
|
+
(line) => ` ${line}`
|
|
2132
|
+
),
|
|
2133
|
+
` mv -- ${shellQuote(paths.directory)} ${shellQuote(disposedDirectory)} || exit 1`,
|
|
2134
|
+
...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
|
|
2135
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2136
|
+
` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
|
|
2137
|
+
` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2138
|
+
"fi",
|
|
2139
|
+
`if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then exit 1; fi`,
|
|
2140
|
+
`if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then exit 1; fi`,
|
|
2141
|
+
`if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then exit 1; fi`,
|
|
2142
|
+
"assert_generation_lock || exit 1",
|
|
2143
|
+
`rm -f -- ${shellQuote(paths.controlLock)} || exit 1`,
|
|
2144
|
+
`if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then exit 1; fi`,
|
|
2145
|
+
`sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
|
|
2146
|
+
`printf '${DISPOSED_SENTINEL}
|
|
2147
|
+
'`
|
|
2148
|
+
].join("\n");
|
|
2149
|
+
}
|
|
2150
|
+
function isDisposeConfirmation(output) {
|
|
2151
|
+
return output.trim() === DISPOSED_SENTINEL;
|
|
2152
|
+
}
|
|
2153
|
+
function buildReadDetachedLogsCommand(expected) {
|
|
2154
|
+
const paths = pathsForIdentity(expected);
|
|
2155
|
+
const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`;
|
|
2156
|
+
return [
|
|
2157
|
+
"umask 077",
|
|
2158
|
+
...secureDetachedRoot(),
|
|
2159
|
+
...secureLaunchDirectory(paths, false),
|
|
2160
|
+
...identityFunctions(paths),
|
|
2161
|
+
...processTreeFunctions(paths),
|
|
2162
|
+
"read_launch_identity || exit 1",
|
|
2163
|
+
`[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`,
|
|
2164
|
+
...readLogFiles(
|
|
2165
|
+
paths.stdout,
|
|
2166
|
+
paths.stderr,
|
|
2167
|
+
{
|
|
2168
|
+
stdout: previousLogPath(paths.stdout),
|
|
2169
|
+
stderr: previousLogPath(paths.stderr)
|
|
2170
|
+
},
|
|
2171
|
+
[
|
|
2172
|
+
"read_launch_identity || exit 1",
|
|
2173
|
+
`[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`
|
|
2174
|
+
]
|
|
2175
|
+
)
|
|
2176
|
+
].join("\n");
|
|
2177
|
+
}
|
|
2178
|
+
function buildReadLegacyDetachedLogsCommand(nonce) {
|
|
2179
|
+
const stdout = `${DETACHED_PROCESS_ROOT}/${nonce}.stdout.log`;
|
|
2180
|
+
const stderr = `${DETACHED_PROCESS_ROOT}/${nonce}.stderr.log`;
|
|
2181
|
+
return [
|
|
2182
|
+
"umask 077",
|
|
2183
|
+
...secureDetachedRoot(),
|
|
2184
|
+
...readLogFiles(stdout, stderr)
|
|
2185
|
+
].join("\n");
|
|
2186
|
+
}
|
|
2187
|
+
function readLogFiles(stdout, stderr, previous, beforePrint = []) {
|
|
2188
|
+
const optionalPrevious = (path) => [
|
|
2189
|
+
`if [ -e ${shellQuote(path)} ] || [ -L ${shellQuote(path)} ]; then`,
|
|
2190
|
+
...assertSafeRegularFile(path).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
|
|
2191
|
+
"fi"
|
|
2192
|
+
];
|
|
2193
|
+
const boundedPayload = (current, prior) => prior === void 0 ? `read_bounded_log_file ${shellQuote(current)}` : `read_bounded_log_snapshot ${shellQuote(current)} ${shellQuote(prior)} ${shellQuote(logSnapshotPath(current))}`;
|
|
2194
|
+
return [
|
|
2195
|
+
...previous === void 0 ? [] : [...optionalPrevious(previous.stdout), ...optionalPrevious(previous.stderr)],
|
|
2196
|
+
"command -v base64 >/dev/null 2>&1 || exit 1",
|
|
2197
|
+
...previous === void 0 ? [] : ["command -v head >/dev/null 2>&1 || exit 1"],
|
|
2198
|
+
"command -v tail >/dev/null 2>&1 || exit 1",
|
|
2199
|
+
"command -v tr >/dev/null 2>&1 || exit 1",
|
|
2200
|
+
"close_log_segment_descriptors() {",
|
|
2201
|
+
" exec 6<&-",
|
|
2202
|
+
" exec 7<&-",
|
|
2203
|
+
"}",
|
|
2204
|
+
"assert_log_segment_descriptor() {",
|
|
2205
|
+
" snapshot_log_path=$1",
|
|
2206
|
+
" snapshot_log_fd=$2",
|
|
2207
|
+
' [ -f "$snapshot_log_path" ] && [ ! -L "$snapshot_log_path" ] || return 1',
|
|
2208
|
+
' [ -f "/proc/self/fd/$snapshot_log_fd" ] || return 1',
|
|
2209
|
+
' snapshot_log_path_metadata=$(stat -c %u:%a:%h "$snapshot_log_path" 2>/dev/null) || return 1',
|
|
2210
|
+
' snapshot_log_descriptor_metadata=$(stat -Lc %u:%a:%h "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
|
|
2211
|
+
' [ "$snapshot_log_path_metadata" = "$(id -u):600:1" ] || return 1',
|
|
2212
|
+
' [ "$snapshot_log_descriptor_metadata" = "$snapshot_log_path_metadata" ] || return 1',
|
|
2213
|
+
' snapshot_log_path_inode=$(stat -c %d:%i "$snapshot_log_path" 2>/dev/null) || return 1',
|
|
2214
|
+
' snapshot_log_descriptor_inode=$(stat -Lc %d:%i "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
|
|
2215
|
+
' [ "$snapshot_log_descriptor_inode" = "$snapshot_log_path_inode" ]',
|
|
2216
|
+
"}",
|
|
2217
|
+
"read_bounded_log_file() {",
|
|
2218
|
+
" snapshot_current=$1",
|
|
2219
|
+
" close_log_segment_descriptors",
|
|
2220
|
+
' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
|
|
2221
|
+
' exec 6<"$snapshot_current" || return 1',
|
|
2222
|
+
' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
|
|
2223
|
+
` tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/6 | base64 6<&- 7<&- | tr -d '\\n' 6<&- 7<&-`,
|
|
2224
|
+
" snapshot_segment_status=$?",
|
|
2225
|
+
" close_log_segment_descriptors",
|
|
2226
|
+
' return "$snapshot_segment_status"',
|
|
2227
|
+
"}",
|
|
2228
|
+
...previous === void 0 ? [] : [
|
|
2229
|
+
"read_log_snapshot_marker() {",
|
|
2230
|
+
" snapshot_marker_path=$1",
|
|
2231
|
+
' [ -e "$snapshot_marker_path" ] || return 1',
|
|
2232
|
+
' [ -f "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ] || return 1',
|
|
2233
|
+
` snapshot_marker=$(head -c ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES + 1} -- "$snapshot_marker_path") || return 1`,
|
|
2234
|
+
` [ "\${#snapshot_marker}" -le ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES} ] || return 1`,
|
|
2235
|
+
` snapshot_marker_valid=$(printf '%s\\n' "$snapshot_marker" | awk 'NR == 1 && ($1 == "${LEGACY_LOG_SNAPSHOT_PREFIX}" || $1 == "${LOG_SNAPSHOT_PREFIX}") && ($2 == "STABLE" || $2 == "ROTATING") && $3 ~ /^[0-9]+$/ && NF == 3 { valid = 1; next } { valid = 0 } END { if (NR == 1 && valid == 1) print "yes" }')`,
|
|
2236
|
+
' [ "$snapshot_marker_valid" = yes ] || return 1',
|
|
2237
|
+
` printf '%s\\n' "$snapshot_marker"`,
|
|
2238
|
+
"}",
|
|
2239
|
+
"read_legacy_log_snapshot() {",
|
|
2240
|
+
" snapshot_current=$1",
|
|
2241
|
+
" snapshot_previous=$2",
|
|
2242
|
+
" snapshot_marker_path=$3",
|
|
2243
|
+
" snapshot_attempt=0",
|
|
2244
|
+
` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
|
|
2245
|
+
' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
|
|
2246
|
+
` case "$snapshot_before" in '${LEGACY_LOG_SNAPSHOT_PREFIX} STABLE '*) ;; '${LEGACY_LOG_SNAPSHOT_PREFIX} ROTATING '*) snapshot_attempt=$((snapshot_attempt + 1)); sleep 0.01; continue ;; *) return 1 ;; esac`,
|
|
2247
|
+
' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
|
|
2248
|
+
' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
|
|
2249
|
+
' if [ "$snapshot_before" = "$snapshot_after" ]; then',
|
|
2250
|
+
` printf '%s' "$snapshot_payload"`,
|
|
2251
|
+
" return 0",
|
|
2252
|
+
" fi",
|
|
2253
|
+
" snapshot_attempt=$((snapshot_attempt + 1))",
|
|
2254
|
+
" sleep 0.01",
|
|
2255
|
+
" done",
|
|
2256
|
+
" return 1",
|
|
2257
|
+
"}",
|
|
2258
|
+
"target_is_quiescent() {",
|
|
2259
|
+
" target_has_live_processes",
|
|
2260
|
+
" snapshot_process_status=$?",
|
|
2261
|
+
' [ "$snapshot_process_status" -eq 1 ]',
|
|
2262
|
+
"}",
|
|
2263
|
+
"open_log_segment_descriptors() {",
|
|
2264
|
+
" snapshot_current=$1",
|
|
2265
|
+
" snapshot_previous=$2",
|
|
2266
|
+
" close_log_segment_descriptors",
|
|
2267
|
+
' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
|
|
2268
|
+
' exec 6<"$snapshot_current" || return 1',
|
|
2269
|
+
' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
|
|
2270
|
+
" snapshot_has_previous=no",
|
|
2271
|
+
' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
|
|
2272
|
+
' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || { close_log_segment_descriptors; return 1; }',
|
|
2273
|
+
' exec 7<"$snapshot_previous" || { close_log_segment_descriptors; return 1; }',
|
|
2274
|
+
' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
|
|
2275
|
+
" snapshot_has_previous=yes",
|
|
2276
|
+
" fi",
|
|
2277
|
+
' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
|
|
2278
|
+
' if [ "$snapshot_has_previous" = yes ]; then',
|
|
2279
|
+
' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
|
|
2280
|
+
" fi",
|
|
2281
|
+
"}",
|
|
2282
|
+
"read_bounded_log_segments() {",
|
|
2283
|
+
" snapshot_current=$1",
|
|
2284
|
+
" snapshot_previous=$2",
|
|
2285
|
+
' open_log_segment_descriptors "$snapshot_current" "$snapshot_previous" || return 1',
|
|
2286
|
+
` { if [ "$snapshot_has_previous" = yes ]; then tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/7; fi; tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/6; } | tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} 6<&- 7<&- | base64 6<&- 7<&- | tr -d '\\n' 6<&- 7<&-`,
|
|
2287
|
+
" snapshot_segment_status=$?",
|
|
2288
|
+
" close_log_segment_descriptors",
|
|
2289
|
+
' return "$snapshot_segment_status"',
|
|
2290
|
+
"}",
|
|
2291
|
+
"read_v2_log_snapshot() {",
|
|
2292
|
+
" snapshot_current=$1",
|
|
2293
|
+
" snapshot_previous=$2",
|
|
2294
|
+
" snapshot_marker_path=$3",
|
|
2295
|
+
" snapshot_attempt=0",
|
|
2296
|
+
` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
|
|
2297
|
+
" snapshot_before=",
|
|
2298
|
+
' if [ ! -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
|
|
2299
|
+
" # Markerless V2 logs predate marker coordination and are safe",
|
|
2300
|
+
" # to inspect only after their exact process session is quiescent.",
|
|
2301
|
+
" target_is_quiescent || return 1",
|
|
2302
|
+
" else",
|
|
2303
|
+
' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
|
|
2304
|
+
` case "$snapshot_before" in '${LOG_SNAPSHOT_PREFIX} STABLE '*) ;; '${LOG_SNAPSHOT_PREFIX} ROTATING '*) if ! target_is_quiescent; then snapshot_attempt=$((snapshot_attempt + 1)); sleep 0.01; continue; fi ;; *) return 1 ;; esac`,
|
|
2305
|
+
" fi",
|
|
2306
|
+
' if [ ! -e "$snapshot_current" ] && [ ! -L "$snapshot_current" ]; then',
|
|
2307
|
+
" # A crashed rotation may strand current absent after it became",
|
|
2308
|
+
" # previous. Recreate it only after the captured session is gone.",
|
|
2309
|
+
" target_is_quiescent || return 1",
|
|
2310
|
+
' ( set -C; : > "$snapshot_current" ) 2>/dev/null || true',
|
|
2311
|
+
' [ -e "$snapshot_current" ] || return 1',
|
|
2312
|
+
' chmod 600 "$snapshot_current" || return 1',
|
|
2313
|
+
" fi",
|
|
2314
|
+
' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
|
|
2315
|
+
' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
|
|
2316
|
+
' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || return 1',
|
|
2317
|
+
" fi",
|
|
2318
|
+
' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
|
|
2319
|
+
' if [ -z "$snapshot_before" ]; then',
|
|
2320
|
+
` printf '%s' "$snapshot_payload"`,
|
|
2321
|
+
" return 0",
|
|
2322
|
+
" fi",
|
|
2323
|
+
' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
|
|
2324
|
+
' if [ "$snapshot_before" = "$snapshot_after" ]; then',
|
|
2325
|
+
` printf '%s' "$snapshot_payload"`,
|
|
2326
|
+
" return 0",
|
|
2327
|
+
" fi",
|
|
2328
|
+
" snapshot_attempt=$((snapshot_attempt + 1))",
|
|
2329
|
+
" sleep 0.01",
|
|
2330
|
+
" done",
|
|
2331
|
+
" return 1",
|
|
2332
|
+
"}",
|
|
2333
|
+
"read_bounded_log_snapshot() {",
|
|
2334
|
+
" snapshot_current=$1",
|
|
2335
|
+
" snapshot_previous=$2",
|
|
2336
|
+
" snapshot_marker_path=$3",
|
|
2337
|
+
' if [ -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
|
|
2338
|
+
' snapshot_protocol=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
|
|
2339
|
+
` case "$snapshot_protocol" in '${LEGACY_LOG_SNAPSHOT_PREFIX} '*) read_legacy_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"; return $? ;; esac`,
|
|
2340
|
+
" fi",
|
|
2341
|
+
' read_v2_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"',
|
|
2342
|
+
"}"
|
|
2343
|
+
],
|
|
2344
|
+
`stdout_payload=$(${boundedPayload(stdout, previous?.stdout)}) || exit 1`,
|
|
2345
|
+
`stderr_payload=$(${boundedPayload(stderr, previous?.stderr)}) || exit 1`,
|
|
2346
|
+
...beforePrint,
|
|
2347
|
+
'stdout_padding=0; case "$stdout_payload" in *==) stdout_padding=2 ;; *=) stdout_padding=1 ;; esac',
|
|
2348
|
+
'stderr_padding=0; case "$stderr_payload" in *==) stderr_padding=2 ;; *=) stderr_padding=1 ;; esac',
|
|
2349
|
+
"stdout_size=$((${#stdout_payload} / 4 * 3 - stdout_padding))",
|
|
2350
|
+
"stderr_size=$((${#stderr_payload} / 4 * 3 - stderr_padding))",
|
|
2351
|
+
`printf '${LOGS_PREFIX} %s %s\\n' "$stdout_size" "$stderr_size"`,
|
|
2352
|
+
`printf '%s\\n%s\\n' "$stdout_payload" "$stderr_payload"`
|
|
2353
|
+
];
|
|
2354
|
+
}
|
|
2355
|
+
function parseDetachedProcessLogs(output) {
|
|
2356
|
+
const lineEnd = output.indexOf("\n");
|
|
2357
|
+
if (lineEnd < 0) return null;
|
|
2358
|
+
const header = output.slice(0, lineEnd);
|
|
2359
|
+
const match = new RegExp(`^${LOGS_PREFIX} (0|[1-9][0-9]*) (0|[1-9][0-9]*)$`, "u").exec(
|
|
2360
|
+
header
|
|
2361
|
+
);
|
|
2362
|
+
if (!match?.[1] || !match[2]) return null;
|
|
2363
|
+
const stdoutBytes = Number(match[1]);
|
|
2364
|
+
const stderrBytes = Number(match[2]);
|
|
2365
|
+
if (!Number.isSafeInteger(stdoutBytes) || !Number.isSafeInteger(stderrBytes) || stdoutBytes > DETACHED_PROCESS_LOG_MAX_BYTES || stderrBytes > DETACHED_PROCESS_LOG_MAX_BYTES) {
|
|
2366
|
+
return null;
|
|
2367
|
+
}
|
|
2368
|
+
const payloadLines = output.slice(lineEnd + 1).split("\n");
|
|
2369
|
+
if (payloadLines.length !== 3 || payloadLines[2] !== "") return null;
|
|
2370
|
+
const [stdoutBase64, stderrBase64] = payloadLines;
|
|
2371
|
+
if (stdoutBase64 === void 0 || stderrBase64 === void 0) return null;
|
|
2372
|
+
if (stdoutBase64.length !== 4 * Math.ceil(stdoutBytes / 3) || stderrBase64.length !== 4 * Math.ceil(stderrBytes / 3)) {
|
|
2373
|
+
return null;
|
|
2374
|
+
}
|
|
2375
|
+
const decodeCanonicalBase64 = (value) => {
|
|
2376
|
+
const decoded = Buffer.from(value, "base64");
|
|
2377
|
+
return decoded.toString("base64") === value ? decoded : null;
|
|
2378
|
+
};
|
|
2379
|
+
const stdout = decodeCanonicalBase64(stdoutBase64);
|
|
2380
|
+
const stderr = decodeCanonicalBase64(stderrBase64);
|
|
2381
|
+
if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !isUtf8(stdout) || !isUtf8(stderr)) {
|
|
2382
|
+
return null;
|
|
2383
|
+
}
|
|
2384
|
+
return {
|
|
2385
|
+
stdout: stdout.toString("utf8"),
|
|
2386
|
+
stderr: stderr.toString("utf8")
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
function isStopConfirmation(output) {
|
|
2390
|
+
return output.trim() === STOPPED_SENTINEL;
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
// src/providers/daytona-transport.ts
|
|
2394
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
2395
|
+
function daytonaTimeoutSeconds(timeoutMs) {
|
|
2396
|
+
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
2397
|
+
}
|
|
2398
|
+
function daytonaCommandOutput(result) {
|
|
2399
|
+
return result.artifacts?.stdout || result.result || "";
|
|
2400
|
+
}
|
|
2401
|
+
async function discoverDaytonaSandboxDirectories(sandbox, options) {
|
|
2402
|
+
await options.beforeIo?.();
|
|
2403
|
+
const reportedWorkDir = await sandbox.getWorkDir();
|
|
2404
|
+
await options.beforeIo?.();
|
|
2405
|
+
const reportedHomeDir = await sandbox.getUserHomeDir();
|
|
2406
|
+
const workDir = reportedWorkDir ?? reportedHomeDir;
|
|
2407
|
+
const homeDir = reportedHomeDir ?? workDir;
|
|
2408
|
+
if (!homeDir || !workDir) {
|
|
2409
|
+
throw options.failure(
|
|
2410
|
+
"Daytona sandbox did not report a home or working directory."
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
return { homeDir, workDir };
|
|
2414
|
+
}
|
|
2415
|
+
async function executeDaytonaCommand(sandbox, command, options) {
|
|
2416
|
+
const result = await executeRawDaytonaCommand(sandbox, command, options);
|
|
2417
|
+
return {
|
|
2418
|
+
exitCode: result.exitCode,
|
|
2419
|
+
stdout: daytonaCommandOutput(result),
|
|
2420
|
+
stderr: ""
|
|
2421
|
+
};
|
|
2422
|
+
}
|
|
2423
|
+
async function executeRawDaytonaCommand(sandbox, command, options) {
|
|
2424
|
+
await options.beforeIo?.();
|
|
2425
|
+
return sandbox.process.executeCommand(
|
|
2426
|
+
command,
|
|
2427
|
+
options.cwd,
|
|
2428
|
+
options.envs,
|
|
2429
|
+
daytonaTimeoutSeconds(options.timeoutMs)
|
|
2430
|
+
);
|
|
2431
|
+
}
|
|
2432
|
+
async function makeDaytonaDirectory(sandbox, path, options) {
|
|
2433
|
+
return executeRawDaytonaCommand(
|
|
2434
|
+
sandbox,
|
|
2435
|
+
`mkdir -p -- ${shellQuote(path)}`,
|
|
2436
|
+
options
|
|
2437
|
+
);
|
|
2438
|
+
}
|
|
2439
|
+
function daytonaUploadContent(content) {
|
|
2440
|
+
if (Buffer2.isBuffer(content)) return content;
|
|
2441
|
+
if (typeof content === "string") return Buffer2.from(content);
|
|
2442
|
+
if (content instanceof Uint8Array) return Buffer2.from(content);
|
|
2443
|
+
return Buffer2.from(content);
|
|
2444
|
+
}
|
|
2445
|
+
async function uploadDaytonaFile(sandbox, path, content, options) {
|
|
2446
|
+
await options.beforeIo?.();
|
|
2447
|
+
await sandbox.fs.uploadFile(
|
|
2448
|
+
daytonaUploadContent(content),
|
|
2449
|
+
path,
|
|
2450
|
+
daytonaTimeoutSeconds(options.timeoutMs)
|
|
2451
|
+
);
|
|
2452
|
+
}
|
|
2453
|
+
function createDaytonaProcessController(sandbox, options) {
|
|
2454
|
+
return new DetachedProcessController({
|
|
2455
|
+
provider: "daytona",
|
|
2456
|
+
...options.homeDir === void 0 ? {} : { genericPayloadEnvironmentDefaults: { HOME: options.homeDir } },
|
|
2457
|
+
...options.beforePrepareMutation === void 0 ? {} : { beforePrepareMutation: options.beforePrepareMutation },
|
|
2458
|
+
...options.beforeStopOrDisposeMutation === void 0 ? {} : {
|
|
2459
|
+
beforeStopOrDisposeMutation: options.beforeStopOrDisposeMutation
|
|
2460
|
+
},
|
|
2461
|
+
execute: async (command, commandOptions) => {
|
|
2462
|
+
try {
|
|
2463
|
+
const result = await executeDaytonaCommand(sandbox, command, {
|
|
2464
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
|
|
2465
|
+
...commandOptions?.cwd === void 0 ? {} : { cwd: commandOptions.cwd },
|
|
2466
|
+
...commandOptions?.envs === void 0 ? {} : { envs: commandOptions.envs }
|
|
2467
|
+
});
|
|
2468
|
+
return { state: "completed", result };
|
|
2469
|
+
} catch (error) {
|
|
2470
|
+
return { state: "failed", error };
|
|
2471
|
+
}
|
|
2472
|
+
},
|
|
2473
|
+
readLegacyLogs: options.readLegacyLogs,
|
|
2474
|
+
stopLegacy: options.stopLegacy,
|
|
2475
|
+
failure: options.failure
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
function createDaytonaDetachedProcessController(sandbox, options) {
|
|
2479
|
+
const controller = createDaytonaProcessController(sandbox, options);
|
|
2480
|
+
return {
|
|
2481
|
+
start: (command, startOptions) => controller.start(command, startOptions),
|
|
2482
|
+
readLogs: (command) => controller.readLogs(command),
|
|
2483
|
+
stop: (command) => controller.stop(command),
|
|
2484
|
+
dispose: (command) => controller.dispose(command)
|
|
2485
|
+
};
|
|
2486
|
+
}
|
|
2487
|
+
function createDaytonaTerminalDetachedProcessController(sandbox, options) {
|
|
2488
|
+
const controller = createDaytonaProcessController(sandbox, options);
|
|
2489
|
+
return {
|
|
2490
|
+
stop: (command) => controller.stop(command),
|
|
2491
|
+
dispose: (command) => controller.dispose(command)
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
export {
|
|
2496
|
+
serializeSupervisorEnvironmentHandoff,
|
|
2497
|
+
normalizeProviderSandboxDetachedCommandOptions,
|
|
2498
|
+
shellQuote,
|
|
2499
|
+
DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
|
|
2500
|
+
DETACHED_PROCESS_LOG_MAX_BYTES,
|
|
2501
|
+
boundDetachedProcessLog,
|
|
2502
|
+
isDetachedProcessLaunchCancelledError,
|
|
2503
|
+
isDetachedProcessReleasedGenerationUnavailableError,
|
|
2504
|
+
DetachedProcessController,
|
|
2505
|
+
buildLegacyDetachedStopCommand,
|
|
2506
|
+
buildReadLegacyDetachedLogsCommand,
|
|
2507
|
+
parseDetachedProcessLogs,
|
|
2508
|
+
daytonaTimeoutSeconds,
|
|
2509
|
+
discoverDaytonaSandboxDirectories,
|
|
2510
|
+
executeDaytonaCommand,
|
|
2511
|
+
executeRawDaytonaCommand,
|
|
2512
|
+
makeDaytonaDirectory,
|
|
2513
|
+
uploadDaytonaFile,
|
|
2514
|
+
createDaytonaDetachedProcessController,
|
|
2515
|
+
createDaytonaTerminalDetachedProcessController
|
|
2516
|
+
};
|