start-command 0.37.8 → 0.37.9

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.
@@ -13,6 +13,8 @@ const { ControlAction, controlExecution } = require('./execution-control');
13
13
  const { attachExecution } = require('./execution-attach');
14
14
  const { resumeAllExecutions, resumeExecution } = require('./execution-resume');
15
15
  const { uploadExecutionLog } = require('./log-uploader');
16
+ const { snapshotResumeSettings } = require('./snapshot-resume-options');
17
+ const { cleanupExecution } = require('./execution-cleanup');
16
18
 
17
19
  /**
18
20
  * Print a handler result, returning the process exit code.
@@ -68,6 +70,8 @@ async function handleResumeQuery(
68
70
  outputFormat,
69
71
  resourceOptions,
70
72
  removeOriginal: resourceOptions.removeOriginal === true,
73
+ removeOriginalAfter: resourceOptions.removeOriginalAfter ?? 0,
74
+ snapshotOptions: snapshotResumeSettings(resourceOptions),
71
75
  })
72
76
  );
73
77
  }
@@ -78,12 +82,21 @@ function handleResumeAllQuery(store, outputFormat) {
78
82
 
79
83
  /**
80
84
  * Handle --cleanup / --cleanup-dry-run.
81
- * Cleans up stale "executing" records (processes that crashed or were killed).
85
+ * Cleans up stale "executing" records (processes that crashed or were killed),
86
+ * or with a target the Docker containers and snapshot images of one execution.
82
87
  * @param {?object} store - Execution store
83
88
  * @param {boolean} dryRun - If true, just report what would be cleaned
89
+ * @param {?string} [target] - UUID or session name of one execution
84
90
  * @returns {number} Exit code
85
91
  */
86
- function handleCleanup(store, dryRun) {
92
+ function handleCleanup(store, dryRun, target = null) {
93
+ if (hasValue(target)) {
94
+ const result = cleanupExecution(store, target, { dryRun });
95
+ if (!result.success && result.output) {
96
+ console.log(result.output);
97
+ }
98
+ return reportResult(result);
99
+ }
87
100
  if (!store) {
88
101
  console.error('Error: Execution tracking is disabled.');
89
102
  return 1;
@@ -193,7 +206,7 @@ async function dispatchQueryCommand(options, context = {}) {
193
206
  return handleResumeAllQuery(store, outputFormat);
194
207
  }
195
208
  if (options.cleanup) {
196
- return handleCleanup(store, options.cleanupDryRun);
209
+ return handleCleanup(store, options.cleanupDryRun, options.cleanupTarget);
197
210
  }
198
211
 
199
212
  return null;
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Options for the guarded Docker snapshot resume (issue #224):
3
+ * --snapshot-wait <seconds> wait for the host snapshot lock
4
+ * --snapshot-disk-wait <seconds> wait for free disk instead of refusing
5
+ * --remove-original-after <seconds> remove the original only if the
6
+ * replacement still runs after the delay
7
+ * --snapshot-size-hint <bytes> skip the `docker inspect --size` walk
8
+ * --snapshot-prepare <command> `docker exec` a command in the original
9
+ * before it is committed
10
+ *
11
+ * They only apply to `--resume`. The two waits also read
12
+ * START_SNAPSHOT_LOCK_WAIT and START_SNAPSHOT_DISK_WAIT when the flags are
13
+ * absent, so a supervisor can set them once for every resume it runs.
14
+ */
15
+
16
+ const FIELDS = {
17
+ '--snapshot-wait': 'snapshotWait',
18
+ '--snapshot-disk-wait': 'snapshotDiskWait',
19
+ '--remove-original-after': 'removeOriginalAfter',
20
+ '--snapshot-size-hint': 'snapshotSizeHint',
21
+ '--snapshot-prepare': 'snapshotPrepare',
22
+ };
23
+
24
+ const ENV_DEFAULTS = {
25
+ snapshotWait: ['START_SNAPSHOT_LOCK_WAIT', '--snapshot-wait'],
26
+ snapshotDiskWait: ['START_SNAPSHOT_DISK_WAIT', '--snapshot-disk-wait'],
27
+ };
28
+
29
+ const UNITS = {
30
+ '': 1,
31
+ b: 1,
32
+ k: 1024,
33
+ m: 1024 ** 2,
34
+ g: 1024 ** 3,
35
+ t: 1024 ** 4,
36
+ };
37
+
38
+ function createSnapshotOptionDefaults() {
39
+ return {
40
+ snapshotWait: null,
41
+ snapshotDiskWait: null,
42
+ removeOriginalAfter: null,
43
+ snapshotSizeHint: null,
44
+ snapshotPrepare: null,
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Parse a non-negative number of seconds; fractions are allowed.
50
+ * @param {string} value - Raw value
51
+ * @param {string} name - Option or variable name for the error message
52
+ * @returns {number} Seconds
53
+ */
54
+ function parseSeconds(value, name) {
55
+ const text = String(value).trim();
56
+ const seconds = Number(text);
57
+ if (!/^\d+(?:\.\d+)?$/.test(text) || !Number.isFinite(seconds)) {
58
+ throw new Error(
59
+ `Invalid ${name} value: "${value}". Expected a non-negative number of seconds.`
60
+ );
61
+ }
62
+ return seconds;
63
+ }
64
+
65
+ /**
66
+ * Parse a size in bytes; k, m, g and t suffixes are 1024-based.
67
+ * @param {string} value - Raw value
68
+ * @returns {number} Bytes
69
+ */
70
+ function parseSizeHint(value) {
71
+ const match = /^(\d+)([bkmgt])?$/.exec(String(value).trim().toLowerCase());
72
+ const bytes = match ? Number(match[1]) * UNITS[match[2] || ''] : NaN;
73
+ if (!Number.isSafeInteger(bytes)) {
74
+ throw new Error(
75
+ `Invalid --snapshot-size-hint value: "${value}". Expected a number of bytes (k, m, g, t suffixes allowed).`
76
+ );
77
+ }
78
+ return bytes;
79
+ }
80
+
81
+ function parseValue(flag, value) {
82
+ if (flag === '--snapshot-size-hint') {
83
+ return parseSizeHint(value);
84
+ }
85
+ if (flag === '--snapshot-prepare') {
86
+ if (String(value).trim() === '') {
87
+ throw new Error('--snapshot-prepare requires a non-empty command');
88
+ }
89
+ return value;
90
+ }
91
+ return parseSeconds(value, flag);
92
+ }
93
+
94
+ /**
95
+ * Parse one snapshot option.
96
+ * @returns {number} Arguments consumed, 0 when `args[index]` is not one
97
+ */
98
+ function parse(args, index, options) {
99
+ const arg = args[index];
100
+ const equals = arg.indexOf('=');
101
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
102
+ const field = FIELDS[flag];
103
+ if (!field) {
104
+ return 0;
105
+ }
106
+ if (equals !== -1) {
107
+ options[field] = parseValue(flag, arg.slice(equals + 1));
108
+ return 1;
109
+ }
110
+ const value = args[index + 1];
111
+ // A prepare command may itself start with a dash only through `=`.
112
+ if (value === undefined || value.startsWith('-')) {
113
+ const kind = {
114
+ '--snapshot-size-hint': 'bytes',
115
+ '--snapshot-prepare': 'command',
116
+ }[flag];
117
+ throw new Error(`Option ${flag} requires a ${kind || 'seconds'} argument`);
118
+ }
119
+ options[field] = parseValue(flag, value);
120
+ return 2;
121
+ }
122
+
123
+ function hasValue(value) {
124
+ return value !== null && value !== undefined;
125
+ }
126
+
127
+ /**
128
+ * Reject snapshot options outside `--resume` and fill the waits from the
129
+ * environment.
130
+ * @param {object} options - Parsed wrapper options
131
+ * @param {object} [env] - Environment
132
+ */
133
+ function validate(options, env = process.env) {
134
+ if (!hasValue(options.resume)) {
135
+ for (const [flag, field] of Object.entries(FIELDS)) {
136
+ if (hasValue(options[field])) {
137
+ throw new Error(`${flag} is only valid with --resume`);
138
+ }
139
+ }
140
+ return;
141
+ }
142
+ for (const [field, [name, flag]] of Object.entries(ENV_DEFAULTS)) {
143
+ if (!hasValue(options[field]) && hasValue(env[name]) && env[name] !== '') {
144
+ options[field] = parseSeconds(env[name], `${name} (${flag})`);
145
+ }
146
+ }
147
+ if (hasValue(options.removeOriginalAfter)) {
148
+ options.removeOriginal = true;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * The `snapshotOptions` `resumeExecution` reads from the wrapper options.
154
+ * @param {object} options - Parsed wrapper options
155
+ * @returns {object} {waitSeconds, diskWaitSeconds, sizeHint, prepare}
156
+ */
157
+ function snapshotResumeSettings(options = {}) {
158
+ return {
159
+ waitSeconds: options.snapshotWait ?? 0,
160
+ diskWaitSeconds: options.snapshotDiskWait ?? 0,
161
+ sizeHint: options.snapshotSizeHint ?? null,
162
+ prepare: options.snapshotPrepare ?? null,
163
+ };
164
+ }
165
+
166
+ module.exports = {
167
+ FIELDS,
168
+ createSnapshotOptionDefaults,
169
+ parse,
170
+ parseSeconds,
171
+ parseSizeHint,
172
+ snapshotResumeSettings,
173
+ validate,
174
+ };
@@ -7,11 +7,12 @@
7
7
  * - Text: Human-readable text format
8
8
  */
9
9
 
10
- const { execSync, spawnSync } = require('child_process');
10
+ const { execSync } = require('child_process');
11
+ const { escapeForLinksNotation } = require('./output-blocks');
11
12
  const {
12
- escapeForLinksNotation,
13
- formatAsNestedLinksNotation,
14
- } = require('./output-blocks');
13
+ appendLinksValue,
14
+ formatTextOptionValue,
15
+ } = require('./status-links-notation');
15
16
  const { collectProcessIds } = require('./execution-control');
16
17
  const { getDockerCommand, getDockerSpawnOptions } = require('./docker-cleanup');
17
18
  const {
@@ -27,6 +28,11 @@ const {
27
28
  const { normalizeDockerTimestamp } = require('./docker-post-mortem');
28
29
  const { END_TIME_SOURCE } = require('./detached-finalize');
29
30
  const { formatCgroupMemory } = require('./cgroup-memory');
31
+ const {
32
+ attachContainerRemoval,
33
+ dockerInspect,
34
+ persistContainerRemoval,
35
+ } = require('./container-removal');
30
36
 
31
37
  /**
32
38
  * Inspect the live state of a detached docker container by name.
@@ -43,32 +49,31 @@ const { formatCgroupMemory } = require('./cgroup-memory');
43
49
  * instead of fabricating a terminal `-1` result.
44
50
  *
45
51
  * @param {string} sessionName - Container name
52
+ * @param {Object|null} [probe] - Receives `sessionNotFound` (issue #225)
46
53
  * @returns {{running: boolean, exitCode: number|null, oomKilled: boolean|null}|null} State,
47
54
  * or null when the container cannot be inspected (not found yet, removed, or docker error)
48
55
  */
49
- function inspectDockerState(sessionName) {
50
- const result = spawnSync(
56
+ function inspectDockerState(sessionName, probe = null) {
57
+ const { stdout, notFound } = dockerInspect(
51
58
  getDockerCommand(),
52
- [
53
- 'inspect',
54
- '-f',
55
- '{{.State.Running}} {{.State.ExitCode}} {{.State.OOMKilled}} ' +
56
- '{{.State.StartedAt}} {{.State.FinishedAt}}',
57
- sessionName,
58
- ],
59
- getDockerSpawnOptions({
60
- encoding: 'utf8',
61
- env: process.env,
62
- stdio: ['pipe', 'pipe', 'pipe'],
63
- })
59
+ dockerProbeSpawnOptions(),
60
+ '{{.State.Running}} {{.State.ExitCode}} {{.State.OOMKilled}} ' +
61
+ '{{.State.StartedAt}} {{.State.FinishedAt}}',
62
+ sessionName
64
63
  );
65
- if (result.error || result.status !== 0 || !result.stdout) {
64
+ if (probe) {
65
+ // "No such container" is a fact, unlike a docker that cannot be reached
66
+ // (issue #225); it still reads as unknown liveness here (issue #136).
67
+ probe.sessionNotFound = notFound;
68
+ }
69
+ if (stdout === null) {
66
70
  return null;
67
71
  }
68
72
  // Parsed positionally and defensively: an older docker (or a stubbed one)
69
73
  // may answer with fewer fields than the template asks for.
70
- const [runningRaw, exitRaw, oomKilledRaw, startedRaw, finishedRaw] =
71
- result.stdout.trim().split(/\s+/);
74
+ const [runningRaw, exitRaw, oomKilledRaw, startedRaw, finishedRaw] = stdout
75
+ .trim()
76
+ .split(/\s+/);
72
77
  const exitCode = Number.parseInt(exitRaw, 10);
73
78
  return {
74
79
  running: runningRaw === 'true',
@@ -89,12 +94,20 @@ function isDetachedDockerRecord(record) {
89
94
  );
90
95
  }
91
96
 
92
- function readDockerState(record) {
97
+ function dockerProbeSpawnOptions() {
98
+ return getDockerSpawnOptions({
99
+ encoding: 'utf8',
100
+ env: process.env,
101
+ stdio: ['pipe', 'pipe', 'pipe'],
102
+ });
103
+ }
104
+
105
+ function readDockerState(record, probe = null) {
93
106
  const opts = record.options || {};
94
107
  if (opts.isolated !== 'docker' || !opts.sessionName) {
95
108
  return null;
96
109
  }
97
- const state = inspectDockerState(opts.sessionName);
110
+ const state = inspectDockerState(opts.sessionName, probe);
98
111
  if (
99
112
  record.attempt &&
100
113
  state?.startedAt &&
@@ -325,14 +338,14 @@ function applyEndTime(enriched, dockerState, footerFinishedAt) {
325
338
  enriched.observedAt = enriched.endTime;
326
339
  }
327
340
 
328
- function resolveDetachedStatus(record, logTail) {
341
+ function resolveDetachedStatus(record, logTail, probe = null) {
329
342
  if (require('./launch-owner').hasActiveLaunch(record)) {
330
343
  return record;
331
344
  }
332
345
  const footer = parseFooterFromTail(logTail);
333
346
  const footerExit = footer.exitCode;
334
347
  const dockerState = isDetachedDockerRecord(record)
335
- ? readDockerState(record)
348
+ ? readDockerState(record, probe)
336
349
  : null;
337
350
  const alive = isDetachedDockerRecord(record)
338
351
  ? dockerState === null
@@ -550,7 +563,14 @@ function enrichDetachedStatus(record) {
550
563
  const logTail = record
551
564
  ? readAttemptLogTail(record, FATAL_MARKER_TAIL_BYTES)
552
565
  : null;
553
- const resolved = resolveDetachedStatus(record, logTail);
566
+ const probe = {
567
+ dockerCommand: getDockerCommand(),
568
+ spawnOptions: dockerProbeSpawnOptions(),
569
+ };
570
+ const resolved = attachContainerRemoval(
571
+ resolveDetachedStatus(record, logTail, probe),
572
+ probe
573
+ );
554
574
  const enriched = attachMemoryExhaustion(
555
575
  attachExitReason(resolved, logTail),
556
576
  logTail
@@ -671,22 +691,21 @@ function formatRecordAsLinksNotation(record) {
671
691
  for (const [key, value] of Object.entries(obj)) {
672
692
  if (value !== null && value !== undefined) {
673
693
  if (key === 'options' && typeof value === 'object') {
674
- // Format options as nested Links notation
694
+ // Nested option values (launchOwner, exitEvidence, resolvedLimits…)
695
+ // are rendered as nested Links notation, never "[object Object]"
696
+ // (issue #226).
675
697
  const optionEntries = Object.entries(value).filter(
676
698
  ([, v]) => v !== null && v !== undefined
677
699
  );
678
700
  if (optionEntries.length > 0) {
679
701
  lines.push(' options');
680
702
  for (const [optKey, optValue] of optionEntries) {
681
- const formattedOptValue = escapeForLinksNotation(optValue);
682
- lines.push(` ${optKey} ${formattedOptValue}`);
703
+ appendLinksValue(lines, optKey, optValue, 4);
683
704
  }
684
705
  }
685
706
  } else if (typeof value === 'object') {
686
- // For other objects, still format as nested Links notation
687
- lines.push(` ${key}`);
688
- const nested = formatAsNestedLinksNotation(value, 2, 2);
689
- lines.push(nested);
707
+ // Other objects use the same nested layout as the Rust formatter.
708
+ appendLinksValue(lines, key, value, 2);
690
709
  } else {
691
710
  const formattedValue = escapeForLinksNotation(value);
692
711
  lines.push(` ${key} ${formattedValue}`);
@@ -751,6 +770,11 @@ function formatRecordAsText(record) {
751
770
  if (obj.staleDetectedAt) {
752
771
  lines.push(`Stale Detected At: ${obj.staleDetectedAt}`);
753
772
  }
773
+ if (obj.containerState) {
774
+ // The container no longer exists; `containerId` is history (issue #225).
775
+ lines.push(`Container State: ${obj.containerState}`);
776
+ lines.push(`Container Removed: ${obj.containerRemovedObservedAt || 'N/A'}`);
777
+ }
754
778
  lines.push(`Log Path: ${obj.logPath}`);
755
779
  if (obj.attempt) {
756
780
  lines.push(
@@ -770,7 +794,7 @@ function formatRecordAsText(record) {
770
794
  if (optionEntries.length > 0) {
771
795
  lines.push(`Options:`);
772
796
  for (const [key, value] of optionEntries) {
773
- lines.push(` ${key}: ${value}`);
797
+ lines.push(` ${key}: ${formatTextOptionValue(value)}`);
774
798
  }
775
799
  }
776
800
 
@@ -897,6 +921,7 @@ function queryStatus(store, identifier, outputFormat) {
897
921
  try {
898
922
  // Enrich detached execution status with live session check
899
923
  const enrichedRecord = enrichDetachedStatus(record);
924
+ persistContainerRemoval(store, record, enrichedRecord);
900
925
  const withProcessIds = attachProcessIds(enrichedRecord);
901
926
  // Attach currentTime so callers can see how long an executing command has been running
902
927
  const withCurrentTime = attachCurrentTime(withProcessIds);
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Links-notation and text rendering of nested `--status` values.
3
+ *
4
+ * `--status` stores structured option values such as `launchOwner`,
5
+ * `exitEvidence`, `resolvedLimits` and `resourceLimitSpecs`. They used to be
6
+ * passed through `escapeForLinksNotation` (and a template string in the text
7
+ * format), which printed `"[object Object]"` and lost the values (issue #226).
8
+ * These helpers render nested objects and arrays the same way the Rust
9
+ * formatter's `append_links_value` does, so both implementations print the
10
+ * same layout.
11
+ */
12
+
13
+ const { escapeForLinksNotation } = require('./output-blocks');
14
+
15
+ function isPresent(value) {
16
+ return value !== null && value !== undefined;
17
+ }
18
+
19
+ /**
20
+ * Append an array as a `(` … `)` block.
21
+ * @param {string[]} lines - Output lines
22
+ * @param {Array} values - Array to render
23
+ * @param {number} indent - Indentation of the parentheses
24
+ */
25
+ function appendLinksArray(lines, values, indent) {
26
+ const prefix = ' '.repeat(indent);
27
+ if (values.length === 0) {
28
+ lines.push(`${prefix}()`);
29
+ return;
30
+ }
31
+ lines.push(`${prefix}(`);
32
+ for (const value of values) {
33
+ if (Array.isArray(value)) {
34
+ appendLinksArray(lines, value, indent + 2);
35
+ } else if (isPresent(value) && typeof value === 'object') {
36
+ for (const [childKey, childValue] of Object.entries(value)) {
37
+ if (isPresent(childValue)) {
38
+ appendLinksValue(lines, childKey, childValue, indent + 2);
39
+ }
40
+ }
41
+ } else {
42
+ lines.push(`${' '.repeat(indent + 2)}${escapeForLinksNotation(value)}`);
43
+ }
44
+ }
45
+ lines.push(`${prefix})`);
46
+ }
47
+
48
+ /**
49
+ * Append `key value`, or `key` followed by its nested children.
50
+ * Children of an object are indented by four more spaces, matching the
51
+ * top-level ` key` / ` child` layout `--status` has always used.
52
+ * @param {string[]} lines - Output lines
53
+ * @param {string} key - Field name
54
+ * @param {*} value - Field value
55
+ * @param {number} indent - Indentation of the key
56
+ */
57
+ function appendLinksValue(lines, key, value, indent) {
58
+ const prefix = ' '.repeat(indent);
59
+ if (Array.isArray(value)) {
60
+ lines.push(`${prefix}${key}`);
61
+ appendLinksArray(lines, value, indent + 2);
62
+ return;
63
+ }
64
+ if (isPresent(value) && typeof value === 'object') {
65
+ const entries = Object.entries(value);
66
+ if (entries.length === 0) {
67
+ return;
68
+ }
69
+ lines.push(`${prefix}${key}`);
70
+ for (const [childKey, childValue] of entries) {
71
+ if (isPresent(childValue)) {
72
+ appendLinksValue(lines, childKey, childValue, indent + 4);
73
+ }
74
+ }
75
+ return;
76
+ }
77
+ lines.push(`${prefix}${key} ${escapeForLinksNotation(value)}`);
78
+ }
79
+
80
+ /**
81
+ * Render an option value for the text format: scalars as-is, structured
82
+ * values as compact JSON (the Rust formatter uses `serde_json::to_string`).
83
+ * @param {*} value - Option value
84
+ * @returns {string} Rendered value
85
+ */
86
+ function formatTextOptionValue(value) {
87
+ if (isPresent(value) && typeof value === 'object') {
88
+ return JSON.stringify(value);
89
+ }
90
+ return String(value);
91
+ }
92
+
93
+ module.exports = {
94
+ appendLinksArray,
95
+ appendLinksValue,
96
+ formatTextOptionValue,
97
+ };
@@ -14,6 +14,8 @@ class LockManager {
14
14
  this.identity = null;
15
15
  this.token = null;
16
16
  this.monitorOwner = monitorOwner;
17
+ // Extra fields published in the lock file, for example who holds it.
18
+ this.metadata = {};
17
19
  }
18
20
 
19
21
  acquire(timeout = LOCK_TIMEOUT_MS) {
@@ -44,6 +46,7 @@ class LockManager {
44
46
  this.fs.writeFileSync(
45
47
  temp,
46
48
  JSON.stringify({
49
+ ...this.metadata,
47
50
  pid: process.pid,
48
51
  timestamp: Date.now(),
49
52
  hostname: os.hostname(),
package/src/lib/usage.js CHANGED
@@ -54,9 +54,16 @@ Options:
54
54
  --resume <id> Restart a stopped detached execution in the same environment
55
55
  (append -- <command> to run a different command there)
56
56
  --remove-original With legacy snapshot resume, remove the stopped original after launch
57
+ --remove-original-after <s> Remove it only if the replacement still runs after <s> seconds
58
+ --snapshot-wait <s> Wait up to <s> seconds for another snapshot on this host (exit 75 after)
59
+ --snapshot-disk-wait <s> Wait up to <s> seconds for free disk instead of refusing (exit 75 after)
60
+ --snapshot-size-hint <bytes> Use this writable-layer size instead of docker inspect --size
61
+ --snapshot-prepare <cmd> docker exec <cmd> in the started original before it is snapshotted
57
62
  --resume-all Re-attach or reconcile every execution still marked running
58
63
  --cleanup Clean up stale "executing" records (crashed/killed processes)
59
64
  --cleanup-dry-run Show stale records that would be cleaned up (without cleaning)
65
+ --cleanup <id> Remove a Docker execution's containers and snapshot images (never forced)
66
+ --cleanup-dry-run <id> Show the containers and images --cleanup <id> would remove
60
67
  --version, -v Show version information
61
68
 
62
69
  Examples: