@camunda8/cli 4.2.0-alpha.1 → 4.2.0-alpha.3

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.
@@ -8,12 +8,13 @@
8
8
  * c8ctl cluster stop [<version>]
9
9
  */
10
10
 
11
- import { spawn } from 'node:child_process';
11
+ import { spawn, execFileSync } from 'node:child_process';
12
12
  import {
13
13
  createWriteStream,
14
14
  existsSync,
15
15
  mkdirSync,
16
16
  writeFileSync,
17
+ renameSync,
17
18
  rmSync,
18
19
  readdirSync,
19
20
  readFileSync,
@@ -299,6 +300,8 @@ function fireAndForget(promise) {
299
300
  return promise.catch(() => {});
300
301
  }
301
302
 
303
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
304
+
302
305
  // ---------------------------------------------------------------------------
303
306
  // Plugin metadata
304
307
  // ---------------------------------------------------------------------------
@@ -368,6 +371,12 @@ function getLogger() {
368
371
 
369
372
  const ACTIVE_MARKER_FILE = 'cluster.active';
370
373
  const VERSION_MARKER_FILE = 'cluster.version';
374
+ // Durable running-cluster PID record, written at start time. Unlike c8run's
375
+ // own `.process` pidfiles — which live INSIDE a version's install dir and
376
+ // vanish when that dir is replaced or removed — this record lives at the
377
+ // cache root, so a running instance stays trackable (status/stop) even after
378
+ // its install directory is deleted or upgraded out from under it (#560).
379
+ const PID_RECORD_FILE = 'cluster.pids';
371
380
  const CLUSTER_STARTUP_TIMEOUT_MS = 120000;
372
381
  const HEALTH_CHECK_TIMEOUT_MS = 3_000;
373
382
  const ALIAS_COLUMN_WIDTH = 22;
@@ -663,6 +672,20 @@ export function getC8RunBinaryPath(config) {
663
672
 
664
673
  export function purgeInstalledVersion(config, { reason } = {}) {
665
674
  const logger = getLogger();
675
+
676
+ // Never remove a version's install dir while an instance started from it is
677
+ // still running — doing so orphans the process (it keeps holding its ports)
678
+ // and destroys the .process pidfiles c8ctl relied on to find it, so
679
+ // status/stop go blind (#560). This backstops every caller: the delete/purge
680
+ // subcommands guard earlier with a friendlier message, and the rolling-update
681
+ // path relies on this to refuse an in-place upgrade of a running version.
682
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
683
+ throw new Error(
684
+ `Refusing to remove c8run ${config.version}: an instance started from this version is still running. ` +
685
+ 'Stop it first with "c8ctl cluster stop".',
686
+ );
687
+ }
688
+
666
689
  const installDir = join(config.cacheDir, `c8run-${config.version}`);
667
690
  const platformInfo = getPlatformIdentifier();
668
691
  const archiveFile = join(
@@ -752,6 +775,16 @@ export async function ensureC8RunInstalled(config) {
752
775
  logger.info(`c8run ${config.version} is already installed and up to date.`);
753
776
  return;
754
777
  }
778
+ // Refuse to replace a running version's install dir out from under it.
779
+ // purgeInstalledVersion throws if an instance is still running; surface
780
+ // an update-specific hint so the user knows to stop the cluster first.
781
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
782
+ throw new Error(
783
+ `A newer c8run ${config.version} is available, but an instance started from the current ` +
784
+ 'install is still running. Updating now would orphan it and free none of its ports. ' +
785
+ 'Stop it first with "c8ctl cluster stop", then re-run the install.',
786
+ );
787
+ }
755
788
  purgeInstalledVersion(config);
756
789
  } else {
757
790
  // Use local installation as-is (start subcommand, or pinned version)
@@ -776,6 +809,22 @@ export async function ensureC8RunInstalled(config) {
776
809
  }
777
810
  }
778
811
 
812
+ // Reached the download/extract fallback. Either nothing is installed, or the
813
+ // install dir exists but its binary is missing/corrupt (isC8RunInstalled is
814
+ // false, so the guarded rolling-update branch above was skipped entirely).
815
+ // extractArchive writes into c8run-${version}; if an instance started from
816
+ // this version is still live — a partial/corrupt install whose processes are
817
+ // running — extracting would overwrite files under the live cluster and could
818
+ // corrupt it. Refuse here too, mirroring the rolling-update guard above, so a
819
+ // (re)install can never mutate a running install (#560).
820
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
821
+ throw new Error(
822
+ `Refusing to (re)install c8run ${config.version}: an instance started from it is still running, ` +
823
+ 'and extracting now would overwrite files under the live cluster. ' +
824
+ 'Stop it first with "c8ctl cluster stop", then re-run the install.',
825
+ );
826
+ }
827
+
779
828
  logger.info('No local installation found. Setting up...');
780
829
 
781
830
  const { archivePath, etag } = await downloadC8Run(config);
@@ -896,6 +945,23 @@ async function startC8Run(config, debug = false) {
896
945
  logger.warn('Found stale cluster marker (no running processes detected). Cleaning up.');
897
946
  if (existsSync(markerFile)) rmSync(markerFile);
898
947
  if (existsSync(versionFile)) rmSync(versionFile);
948
+ } else if (hasRunningClusterPidfiles(config.cacheDir)) {
949
+ // No active marker, but a live process is still tracked — typically an
950
+ // orphan recorded only in the durable cache-root PID record after its
951
+ // install dir was replaced/removed (#560). Refuse rather than launch a
952
+ // second instance: a successful start would overwrite the record with a
953
+ // fresh snapshot (losing the orphan's PID), and on the default ports it
954
+ // would collide with the still-running process. Preserve the record so
955
+ // "c8ctl cluster stop" can still find and reap the orphan.
956
+ logger.warn(
957
+ 'A cluster process appears to be running already (no active marker, but a live tracked process was found).',
958
+ );
959
+ const record = readRunningClusterRecord(config.cacheDir);
960
+ if (record?.version) {
961
+ logger.info(`Detected running version from the durable PID record: ${record.version}`);
962
+ }
963
+ logger.info('Stop it first with "c8ctl cluster stop".');
964
+ return;
899
965
  }
900
966
 
901
967
  logger.info('Starting Camunda 8 local cluster...');
@@ -960,6 +1026,28 @@ async function startC8Run(config, debug = false) {
960
1026
  const isReady = await waitForClusterReady();
961
1027
 
962
1028
  if (isReady) {
1029
+ // Publish the durable PID record BEFORE the active marker. If c8ctl is
1030
+ // interrupted between these writes, a record-without-marker is recoverable
1031
+ // (status/stop still see the live process via the record), whereas a
1032
+ // marker-without-record would let the stale-marker cleanup path drop the
1033
+ // markers and leave the process orphaned with no handle to reap it (#560).
1034
+ //
1035
+ // The record write is nevertheless best-effort: if it throws (e.g. the
1036
+ // cache root is unwritable / disk full), we must NOT abort here and leave a
1037
+ // just-started, healthy cluster with NEITHER a record NOR markers — that
1038
+ // strands it for both `status` and `stop`. The install dir still exists at
1039
+ // this point, so the markers + c8run's own `.process` pidfiles keep the
1040
+ // cluster fully trackable and stoppable; only the extra orphan-recovery
1041
+ // handle (needed later, if the dir is removed) is missing, which we warn on.
1042
+ try {
1043
+ recordRunningClusterPids(config);
1044
+ } catch (error) {
1045
+ logger.warn(
1046
+ `Could not persist the durable cluster PID record (${
1047
+ error instanceof Error ? error.message : String(error)
1048
+ }); the cluster is still tracked via its markers and pidfiles.`,
1049
+ );
1050
+ }
963
1051
  writeFileSync(markerFile, 'running');
964
1052
  writeFileSync(versionFile, config.version);
965
1053
  printSummary(startupOutput, config.version);
@@ -973,21 +1061,161 @@ async function startC8Run(config, debug = false) {
973
1061
  }
974
1062
  }
975
1063
 
976
- export function hasRunningClusterPidfiles(cacheDir) {
977
- if (!existsSync(cacheDir)) {
1064
+ /** True when a PID refers to a live process. EPERM (owned by another user) counts as alive. */
1065
+ export function isPidAlive(pid) {
1066
+ if (!Number.isInteger(pid) || pid <= 0) {
978
1067
  return false;
979
1068
  }
1069
+ try {
1070
+ process.kill(pid, 0);
1071
+ return true;
1072
+ } catch (error) {
1073
+ return Boolean(error && error.code === 'EPERM');
1074
+ }
1075
+ }
980
1076
 
981
- const versionDirs = readdirSync(cacheDir, { withFileTypes: true })
982
- .filter(
983
- (entry) =>
984
- entry.isDirectory() && entry.name.startsWith('c8run-'),
985
- )
986
- .map((entry) => join(cacheDir, entry.name));
1077
+ /**
1078
+ * A best-effort, platform-native "start signature" for a PID — enough to tell
1079
+ * the ORIGINAL process apart from an unrelated one that reused the same numeric
1080
+ * PID after the original exited. Returns a stable string, or null when the
1081
+ * platform/environment gives us nothing to fingerprint with (in which case
1082
+ * callers fall back to a liveness-only check). Never throws.
1083
+ */
1084
+ /**
1085
+ * True on platforms where `processStartSignature()` can produce a real
1086
+ * fingerprint (Linux, macOS/BSD, Windows). On any other platform no PID can be
1087
+ * fingerprinted, so callers must degrade to a liveness-only reuse guard rather
1088
+ * than dropping otherwise-trackable PIDs (#560).
1089
+ */
1090
+ export function platformSupportsProcessSignature() {
1091
+ const platform = osPlatform();
1092
+ return (
1093
+ platform === 'linux' ||
1094
+ platform === 'darwin' ||
1095
+ platform.endsWith('bsd') ||
1096
+ platform === 'win32'
1097
+ );
1098
+ }
1099
+
1100
+ export function processStartSignature(pid) {
1101
+ if (!Number.isInteger(pid) || pid <= 0) {
1102
+ return null;
1103
+ }
1104
+ const platform = osPlatform();
1105
+ try {
1106
+ if (platform === 'linux') {
1107
+ // /proc/<pid>/stat field 22 is the process start time (clock ticks since
1108
+ // boot) — fixed for the life of the process and re-assigned with the PID,
1109
+ // so it distinguishes a reused PID. `comm` (field 2) can contain spaces
1110
+ // and parentheses, so parse the numeric fields from the LAST ')'.
1111
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf-8');
1112
+ const rparen = stat.lastIndexOf(')');
1113
+ if (rparen === -1) return null;
1114
+ const fields = stat.slice(rparen + 1).trim().split(/\s+/);
1115
+ // After ')' the fields are state(3), ppid(4), …; starttime is field 22,
1116
+ // i.e. index 19 of this remainder (22 - 3).
1117
+ const starttime = fields[19];
1118
+ return starttime ? `linux:${starttime}` : null;
1119
+ }
1120
+ if (platform === 'darwin' || platform.endsWith('bsd')) {
1121
+ // `ps -o lstart=` prints the process start timestamp, but only at
1122
+ // ONE-SECOND resolution — a PID reused within that same second would
1123
+ // reproduce it, and macOS `ps` exposes no higher-resolution creation
1124
+ // time. Pair it with the executable path (`comm=`), which is fixed for
1125
+ // the life of the process and an unrelated process that reused the PID
1126
+ // will not share. The combined fingerprint means `recordedPidIsLive()`
1127
+ // rejects such a replacement instead of signalling an unrelated process.
1128
+ const out = execFileSync('ps', ['-o', 'lstart=,comm=', '-p', String(pid)], {
1129
+ encoding: 'utf-8',
1130
+ timeout: 3000,
1131
+ // `lstart` is rendered in the process locale, so a start under one
1132
+ // LC_TIME and a stop under another would produce different strings for
1133
+ // the SAME live process — `recordedPidIsLive()` would then reject the
1134
+ // orphan as gone and never reap it. Pin a fixed C/POSIX locale so the
1135
+ // signature is locale-independent and stable across invocations (#560).
1136
+ env: { ...process.env, LC_ALL: 'C', LC_TIME: 'C', LANG: 'C' },
1137
+ }).trim();
1138
+ return out ? `ps:${out}` : null;
1139
+ }
1140
+ if (platform === 'win32') {
1141
+ // Windows is a supported platform (#560): fingerprint with the process
1142
+ // creation time from CIM/WMI. Paired with the PID it distinguishes the
1143
+ // original process from an unrelated one that reused the numeric PID.
1144
+ // Guard the null case so a missing PID yields empty output (→ null) rather
1145
+ // than a property access on $null throwing.
1146
+ const out = execFileSync(
1147
+ 'powershell',
1148
+ [
1149
+ '-NoProfile',
1150
+ '-NonInteractive',
1151
+ '-Command',
1152
+ `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; ` +
1153
+ `if ($p) { $p.CreationDate.ToString('o') }`,
1154
+ ],
1155
+ { encoding: 'utf-8', timeout: 5000 },
1156
+ ).trim();
1157
+ return out ? `win:${out}` : null;
1158
+ }
1159
+ } catch {
1160
+ // No signature available — the caller falls back to a liveness-only check.
1161
+ }
1162
+ return null;
1163
+ }
1164
+
1165
+ /**
1166
+ * True when `pid` is alive AND, where we captured a start signature for it, that
1167
+ * signature still matches — i.e. it is the ORIGINAL recorded process, not an
1168
+ * unrelated one that reused the PID after the original exited. A recorded entry
1169
+ * with NO signature is trusted (liveness only) ONLY on platforms that cannot
1170
+ * fingerprint at all; on a fingerprinting platform our writer never persists a
1171
+ * signature-less PID (#568), so a signature-less entry there can only be a
1172
+ * stale/legacy/hand-edited `cluster.pids` and is rejected rather than risk
1173
+ * signalling a reused, unrelated process. When a signature WAS recorded but the
1174
+ * platform cannot reproduce one now (transient `ps` failure), the guard still
1175
+ * degrades to liveness only, never inventing a false negative that would strand
1176
+ * a real orphan.
1177
+ */
1178
+ export function recordedPidIsLive(pid, signature) {
1179
+ if (!isPidAlive(pid)) {
1180
+ return false;
1181
+ }
1182
+ if (!signature) {
1183
+ // No signature recorded. On a fingerprinting platform this can only be a
1184
+ // stale/legacy/hand-edited record (our writer always signs live PIDs there
1185
+ // now), whose bare numeric liveness could match a reused unrelated process
1186
+ // — refuse it. Only non-fingerprinting platforms keep the liveness-only
1187
+ // degrade, since there no recorded PID can ever carry a signature and
1188
+ // rejecting would strand every real orphan (#560/#568).
1189
+ return !platformSupportsProcessSignature();
1190
+ }
1191
+ const current = processStartSignature(pid);
1192
+ return current === null || current === signature;
1193
+ }
1194
+
1195
+ /**
1196
+ * Collect the PIDs recorded in c8run `.process` pidfiles under `cacheDir`.
1197
+ * When `version` is given only that version's install dir is scanned;
1198
+ * otherwise every `c8run-*` install dir is scanned. Each install dir and its
1199
+ * immediate subdirectories are scanned (max depth 1) rather than a full
1200
+ * recursive DFS — c8run installs can contain large extracted trees, logs, and
1201
+ * data that would make a deep walk slow. Returns parsed positive integers
1202
+ * (alive or not); the caller decides liveness.
1203
+ */
1204
+ export function collectPidfilePids(cacheDir, { version } = {}) {
1205
+ const pids = [];
1206
+ if (!existsSync(cacheDir)) {
1207
+ return pids;
1208
+ }
1209
+
1210
+ let versionDirs;
1211
+ if (version) {
1212
+ versionDirs = [join(cacheDir, `c8run-${version}`)];
1213
+ } else {
1214
+ versionDirs = readdirSync(cacheDir, { withFileTypes: true })
1215
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('c8run-'))
1216
+ .map((entry) => join(cacheDir, entry.name));
1217
+ }
987
1218
 
988
- // Scan each version dir and its immediate subdirectories (max depth 1)
989
- // rather than a full recursive DFS — c8run installs can contain large
990
- // extracted trees, logs, and data that would make a deep walk slow.
991
1219
  for (const versionDir of versionDirs) {
992
1220
  let entries;
993
1221
  try {
@@ -1016,34 +1244,299 @@ export function hasRunningClusterPidfiles(cacheDir) {
1016
1244
  if (!entry.isFile() || !entry.name.endsWith('.process')) {
1017
1245
  continue;
1018
1246
  }
1019
-
1020
- const entryPath = join(dir, entry.name);
1021
-
1022
1247
  let pid;
1023
1248
  try {
1024
- pid = Number.parseInt(readFileSync(entryPath, 'utf-8').trim(), 10);
1249
+ pid = Number.parseInt(readFileSync(join(dir, entry.name), 'utf-8').trim(), 10);
1025
1250
  } catch {
1026
1251
  // Pidfile may have been removed between listing and reading.
1027
1252
  continue;
1028
1253
  }
1029
-
1030
- if (!Number.isInteger(pid) || pid <= 0) {
1031
- continue;
1254
+ if (Number.isInteger(pid) && pid > 0) {
1255
+ pids.push(pid);
1032
1256
  }
1257
+ }
1258
+ }
1259
+ }
1033
1260
 
1034
- try {
1035
- process.kill(pid, 0);
1036
- return true;
1037
- } catch (error) {
1038
- if (error && error.code === 'EPERM') {
1039
- return true;
1040
- }
1041
- }
1261
+ return pids;
1262
+ }
1263
+
1264
+ function getPidRecordPath(cacheDir) {
1265
+ return join(cacheDir, PID_RECORD_FILE);
1266
+ }
1267
+
1268
+ /**
1269
+ * Read the durable running-cluster PID record (see PID_RECORD_FILE). Returns
1270
+ * `{ version, pids }` or null when absent/unparseable. This record lives at
1271
+ * the cache root, so it survives a running version's install dir being
1272
+ * replaced or deleted — the case that otherwise orphans the process (#560).
1273
+ */
1274
+ export function readRunningClusterRecord(cacheDir) {
1275
+ const filePath = getPidRecordPath(cacheDir);
1276
+ if (!existsSync(filePath)) {
1277
+ return null;
1278
+ }
1279
+ let parsed;
1280
+ try {
1281
+ parsed = JSON.parse(readFileSync(filePath, 'utf-8'));
1282
+ } catch {
1283
+ return null;
1284
+ }
1285
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1286
+ return null;
1287
+ }
1288
+ const version = typeof parsed.version === 'string' && parsed.version ? parsed.version : null;
1289
+ const pids = Array.isArray(parsed.pids)
1290
+ ? parsed.pids.filter((pid) => Number.isInteger(pid) && pid > 0)
1291
+ : [];
1292
+ const signatures =
1293
+ parsed.signatures && typeof parsed.signatures === 'object' && !Array.isArray(parsed.signatures)
1294
+ ? Object.fromEntries(
1295
+ Object.entries(parsed.signatures).filter(
1296
+ ([pid, sig]) => Number.isInteger(Number(pid)) && typeof sig === 'string' && sig,
1297
+ ),
1298
+ )
1299
+ : {};
1300
+ // Reject any record that lacks a non-empty version attribution. A record
1301
+ // with no version but stray PIDs (e.g. a malformed/hand-edited cluster.pids)
1302
+ // would otherwise let liveRecordedPids()/reapClusterProcesses() treat those
1303
+ // PIDs as cluster-owned and signal them with no version to attribute them to
1304
+ // — a path to killing an unrelated live process during `cluster stop` (#560).
1305
+ if (!version) {
1306
+ return null;
1307
+ }
1308
+ // Reject a record whose version fails the same path-traversal guard applied
1309
+ // to CLI-supplied versions. `version` is later interpolated into join() paths
1310
+ // by getC8RunBinaryPath during `cluster stop`, so a malformed record such as
1311
+ // `foo/../../tmp` could otherwise bypass validateVersionSpec and make stop
1312
+ // inspect/execute a binary outside the cache root (#560). Treat an invalid
1313
+ // record as unusable rather than trusting on-disk state.
1314
+ try {
1315
+ validateVersionSpec(version);
1316
+ } catch {
1317
+ return null;
1318
+ }
1319
+ return { version, pids, signatures };
1320
+ }
1321
+
1322
+ /** Persist the durable running-cluster PID record. */
1323
+ export function writeRunningClusterRecord(cacheDir, { version, pids, signatures }) {
1324
+ mkdirSync(cacheDir, { recursive: true });
1325
+ const cleanPids = Array.isArray(pids)
1326
+ ? [...new Set(pids.filter((pid) => Number.isInteger(pid) && pid > 0))]
1327
+ : [];
1328
+ const cleanSignatures = {};
1329
+ if (signatures && typeof signatures === 'object' && !Array.isArray(signatures)) {
1330
+ for (const pid of cleanPids) {
1331
+ const sig = signatures[pid];
1332
+ if (typeof sig === 'string' && sig) {
1333
+ cleanSignatures[pid] = sig;
1042
1334
  }
1043
1335
  }
1044
1336
  }
1337
+ // `cluster.pids` is the ONLY recovery handle once an install dir disappears,
1338
+ // so the write must be crash-safe: serialise to a sibling temp file and
1339
+ // atomically rename it into place. An interruption then leaves either the
1340
+ // previous valid record or the new one — never a truncated/unparseable file
1341
+ // that would make status/stop lose the orphan PID (#560).
1342
+ const finalPath = getPidRecordPath(cacheDir);
1343
+ const tmpPath = `${finalPath}.${process.pid}.${Date.now()}.tmp`;
1344
+ const payload = JSON.stringify({
1345
+ version: version ?? null,
1346
+ pids: cleanPids,
1347
+ signatures: cleanSignatures,
1348
+ });
1349
+ try {
1350
+ writeFileSync(tmpPath, payload);
1351
+ renameSync(tmpPath, finalPath);
1352
+ } catch (error) {
1353
+ try {
1354
+ if (existsSync(tmpPath)) rmSync(tmpPath);
1355
+ } catch {
1356
+ // best effort — nothing more we can do about a leftover temp file
1357
+ }
1358
+ throw error;
1359
+ }
1360
+ }
1045
1361
 
1046
- return false;
1362
+ /** Remove the durable running-cluster PID record if present. */
1363
+ export function clearRunningClusterRecord(cacheDir) {
1364
+ const filePath = getPidRecordPath(cacheDir);
1365
+ if (existsSync(filePath)) {
1366
+ rmSync(filePath);
1367
+ }
1368
+ }
1369
+
1370
+ /**
1371
+ * Retire the durable record when it no longer tracks any LIVE process. A stale
1372
+ * record left by a crash, a forced kill, or an already-stopped cluster keeps
1373
+ * dead PIDs in `cluster.pids`; on a platform where signature capture is
1374
+ * unavailable the liveness-only fallback would later mistake a reused PID for
1375
+ * this cluster — blocking a start and risking an unrelated process during stop
1376
+ * (#560). Safe to call from any cleanup / no-running path: a no-op when the
1377
+ * record is absent or still has at least one live recorded PID.
1378
+ */
1379
+ export function clearStaleRunningClusterRecord(cacheDir) {
1380
+ if (readRunningClusterRecord(cacheDir) && liveRecordedPids(cacheDir).length === 0) {
1381
+ clearRunningClusterRecord(cacheDir);
1382
+ }
1383
+ }
1384
+
1385
+ /** The still-live PIDs from the durable running-cluster record. */
1386
+ export function liveRecordedPids(cacheDir) {
1387
+ const record = readRunningClusterRecord(cacheDir);
1388
+ if (!record) {
1389
+ return [];
1390
+ }
1391
+ return record.pids.filter((pid) => recordedPidIsLive(pid, record.signatures?.[pid]));
1392
+ }
1393
+
1394
+ /**
1395
+ * Snapshot the live c8run PIDs for the just-started version into the durable
1396
+ * cache-root record, so the cluster stays trackable (status/stop) even if its
1397
+ * install dir is later replaced or removed (#560). Each PID is fingerprinted
1398
+ * with a start signature so a later stop/status can tell the recorded process
1399
+ * apart from an unrelated one that reused its PID.
1400
+ */
1401
+ export function recordRunningClusterPids(config, { signatureOf = processStartSignature } = {}) {
1402
+ const canFingerprint = platformSupportsProcessSignature();
1403
+ const pids = [];
1404
+ const signatures = {};
1405
+ for (const pid of collectPidfilePids(config.cacheDir, { version: config.version })) {
1406
+ if (canFingerprint) {
1407
+ // Capture identity with a SINGLE combined liveness+fingerprint operation.
1408
+ // processStartSignature runs one `ps`/PowerShell query that already
1409
+ // returns null for a dead PID, so — unlike a separate isPidAlive()
1410
+ // pre-check followed by a later signature capture — there is no window in
1411
+ // which the liveness probe and the fingerprint could observe two
1412
+ // different processes and record a reused PID's identity as c8run's
1413
+ // (#560). A null result means the PID is not a live, fingerprintable
1414
+ // process, so it is omitted: persisting it without a signature would let
1415
+ // a later reuse of the number fall back to numeric liveness and let the
1416
+ // reap path signal an unrelated process.
1417
+ const sig = signatureOf(pid);
1418
+ if (sig) {
1419
+ signatures[pid] = sig;
1420
+ pids.push(pid);
1421
+ }
1422
+ } else if (isPidAlive(pid)) {
1423
+ // This platform can't fingerprint any process, so no recorded PID can
1424
+ // carry a signature; keep the live PID so the cluster stays trackable
1425
+ // (the reuse guard degrades to a liveness-only check everywhere).
1426
+ pids.push(pid);
1427
+ }
1428
+ }
1429
+ writeRunningClusterRecord(config.cacheDir, { version: config.version, pids, signatures });
1430
+ }
1431
+
1432
+ /**
1433
+ * True when an instance started from the given version is still running,
1434
+ * either via a live `.process` pidfile in its install dir or via the durable
1435
+ * PID record attributing a live process to that version.
1436
+ */
1437
+ export function isVersionInstanceRunning(cacheDir, version) {
1438
+ if (collectPidfilePids(cacheDir, { version }).some((pid) => isPidAlive(pid))) {
1439
+ return true;
1440
+ }
1441
+ const record = readRunningClusterRecord(cacheDir);
1442
+ return Boolean(
1443
+ record &&
1444
+ record.version === version &&
1445
+ record.pids.some((pid) => recordedPidIsLive(pid, record.signatures?.[pid])),
1446
+ );
1447
+ }
1448
+
1449
+ /**
1450
+ * Send SIGTERM to a PID, wait up to `graceMs` for it to exit, then SIGKILL.
1451
+ * Returns true once the process is confirmed gone.
1452
+ */
1453
+ async function terminatePid(pid, { signature, graceMs = 5000, pollMs = 200 } = {}) {
1454
+ // Revalidate the recorded identity before EVERY signal, not just numeric
1455
+ // liveness. If the original process exits and its PID is reused (e.g. during
1456
+ // the SIGTERM grace window), the captured start signature no longer matches
1457
+ // and we must NOT escalate to an unrelated process (#560). recordedPidIsLive
1458
+ // degrades to a liveness-only check when no signature was captured.
1459
+ if (!recordedPidIsLive(pid, signature)) {
1460
+ return false;
1461
+ }
1462
+ try {
1463
+ process.kill(pid, 'SIGTERM');
1464
+ } catch {
1465
+ // Already exited or not permitted — fall through to the liveness check.
1466
+ }
1467
+ const deadline = Date.now() + graceMs;
1468
+ // Poll for exit with a CHEAP liveness probe (signal 0 — no subprocess). A
1469
+ // process' start signature is immutable while it lives, so re-running the
1470
+ // external `ps`/PowerShell signature query on every 200 ms poll would spawn
1471
+ // dozens of subprocesses (each with a multi-second timeout) and make stop
1472
+ // block far beyond graceMs on a slow host. We still revalidate the recorded
1473
+ // IDENTITY (signature) immediately before the SIGKILL escalation below, so a
1474
+ // PID reused during the grace window can never be signalled as if it were the
1475
+ // tracked process (#560).
1476
+ while (isPidAlive(pid) && Date.now() < deadline) {
1477
+ await sleep(pollMs);
1478
+ }
1479
+ if (recordedPidIsLive(pid, signature)) {
1480
+ try {
1481
+ process.kill(pid, 'SIGKILL');
1482
+ } catch {
1483
+ // Best effort — nothing more we can do.
1484
+ }
1485
+ await sleep(pollMs);
1486
+ }
1487
+ // Confirmed gone once the ORIGINAL recorded process is no longer live — a
1488
+ // signature mismatch (PID reuse) counts as gone: the process we tracked ended.
1489
+ return !recordedPidIsLive(pid, signature);
1490
+ }
1491
+
1492
+ /**
1493
+ * Terminate any cluster processes still alive under `cacheDir` — those named
1494
+ * by the durable PID record, each of which is validated against its recorded
1495
+ * start signature before we signal it. This is the stop backstop for the
1496
+ * orphan case (#560), where `c8run stop` cannot reach a process whose install
1497
+ * dir / pidfiles were removed. We deliberately do NOT scan raw `.process`
1498
+ * pidfiles here: they carry no start-signature, span every cached version, and
1499
+ * a stale pidfile whose numeric PID was reused would make us SIGTERM/SIGKILL an
1500
+ * unrelated process. Raw pidfiles remain c8run's own responsibility. Never
1501
+ * targets this process (or its parent). Returns the count actually terminated.
1502
+ */
1503
+ export async function reapClusterProcesses(cacheDir) {
1504
+ const record = readRunningClusterRecord(cacheDir);
1505
+ const signatures = record?.signatures ?? {};
1506
+ const targets = new Set(liveRecordedPids(cacheDir));
1507
+ // Guard against ever signalling the c8ctl process itself (or its parent) —
1508
+ // a cluster's Java process is never c8ctl, and tests stand in with own PIDs.
1509
+ targets.delete(process.pid);
1510
+ if (typeof process.ppid === 'number') {
1511
+ targets.delete(process.ppid);
1512
+ }
1513
+
1514
+ let reaped = 0;
1515
+ for (const pid of targets) {
1516
+ // Carry the recorded start signature into termination so each signal is
1517
+ // gated on the ORIGINAL identity, not bare numeric liveness (#560).
1518
+ if (await terminatePid(pid, { signature: signatures[pid] })) {
1519
+ reaped += 1;
1520
+ }
1521
+ }
1522
+ return reaped;
1523
+ }
1524
+
1525
+ export function hasRunningClusterPidfiles(cacheDir) {
1526
+ if (!existsSync(cacheDir)) {
1527
+ return false;
1528
+ }
1529
+
1530
+ // Primary signal: c8run's own .process pidfiles inside the install dirs.
1531
+ if (collectPidfilePids(cacheDir).some((pid) => isPidAlive(pid))) {
1532
+ return true;
1533
+ }
1534
+
1535
+ // Fallback: the durable cache-root PID record. This still resolves after a
1536
+ // running version's install dir (and with it the .process pidfiles) has been
1537
+ // replaced or deleted, which would otherwise make c8ctl report the live
1538
+ // cluster as stopped and leave its process orphaned (#560).
1539
+ return liveRecordedPids(cacheDir).length > 0;
1047
1540
  }
1048
1541
 
1049
1542
  export async function stopC8Run(config, debug = false) {
@@ -1055,6 +1548,9 @@ export async function stopC8Run(config, debug = false) {
1055
1548
  const clusterAppearsRunning = hasRunningClusterPidfiles(config.cacheDir);
1056
1549
 
1057
1550
  if (!markerExists && !clusterAppearsRunning) {
1551
+ // Nothing live to stop. Retire any stale record left by a crash/kill so its
1552
+ // dead PIDs cannot later be mistaken for this cluster (#560).
1553
+ clearStaleRunningClusterRecord(config.cacheDir);
1058
1554
  logger.warn(
1059
1555
  'No cluster is currently running.',
1060
1556
  );
@@ -1076,6 +1572,7 @@ export async function stopC8Run(config, debug = false) {
1076
1572
  if (existsSync(markerFile)) {
1077
1573
  rmSync(markerFile);
1078
1574
  }
1575
+ clearRunningClusterRecord(config.cacheDir);
1079
1576
  return staleVersion;
1080
1577
  }
1081
1578
 
@@ -1106,6 +1603,16 @@ export async function stopC8Run(config, debug = false) {
1106
1603
  }
1107
1604
  }
1108
1605
 
1606
+ // Fall back to the durable PID record's version when the marker is gone —
1607
+ // this is the version whose install dir may have been removed (#560).
1608
+ if (versionsToTry.length === 0) {
1609
+ const record = readRunningClusterRecord(config.cacheDir);
1610
+ if (record?.version) {
1611
+ stoppedVersion = record.version;
1612
+ versionsToTry.push(record.version);
1613
+ }
1614
+ }
1615
+
1109
1616
  if (versionsToTry.length === 0) {
1110
1617
  if (installedVersions.length === 0) {
1111
1618
  versionsToTry.push(config.version);
@@ -1195,25 +1702,69 @@ export async function stopC8Run(config, debug = false) {
1195
1702
  }
1196
1703
  }
1197
1704
 
1198
- // Always clean up markers, even if stop failed — a stale marker
1199
- // would permanently block future starts.
1705
+ // Reap any cluster processes still alive after the c8run stop attempt(s).
1706
+ // In the orphan case (#560) the version's install dir — and with it the
1707
+ // .process pidfiles c8run's own stop relies on — was replaced or removed
1708
+ // while the process kept running, so `c8run stop` cannot see it. The durable
1709
+ // cache-root PID record lets us find and terminate the process directly.
1710
+ const reaped = await reapClusterProcesses(config.cacheDir);
1711
+ if (reaped > 0) {
1712
+ hadSuccessfulStop = true;
1713
+ logger.warn(
1714
+ `Terminated ${reaped} orphaned cluster process${reaped === 1 ? '' : 'es'} that c8run no longer tracked.`,
1715
+ );
1716
+ }
1717
+
1718
+ // Markers are always cleared (a stale marker or version file would block
1719
+ // future starts), but the durable PID record is the ONLY handle to an orphan.
1720
+ // If reaping could not confirm every recorded process dead — e.g. signalling
1721
+ // returned EPERM, or the kill did not land — keep the record so a later
1722
+ // "c8ctl cluster stop" can retry. Only clear it once every recorded PID is
1723
+ // confirmed gone (#560).
1200
1724
  if (existsSync(markerFile)) {
1201
1725
  rmSync(markerFile);
1202
1726
  }
1203
1727
  if (existsSync(versionFile)) {
1204
1728
  rmSync(versionFile);
1205
1729
  }
1206
-
1207
- if (attempted === 0) {
1208
- throw new Error(
1209
- 'Could not find an installed c8run binary to execute stop.',
1730
+ const remainingPids = liveRecordedPids(config.cacheDir);
1731
+ if (remainingPids.length === 0) {
1732
+ clearRunningClusterRecord(config.cacheDir);
1733
+ } else {
1734
+ logger.warn(
1735
+ 'Some recorded cluster processes could not be confirmed stopped; keeping the durable ' +
1736
+ 'PID record so "c8ctl cluster stop" can retry.',
1210
1737
  );
1211
1738
  }
1212
1739
 
1213
- if (!hadSuccessfulStop && lastError) {
1740
+ if (attempted === 0 && !hadSuccessfulStop) {
1741
+ // ...but only when there is nothing left to reap. If a recorded process is
1742
+ // still alive (e.g. reaping hit EPERM), the incomplete-stop diagnostic
1743
+ // below carries the actionable PID/retry guidance and must win over this
1744
+ // generic "no binary" message even though the install dir is gone (#560).
1745
+ if (remainingPids.length === 0) {
1746
+ throw new Error(
1747
+ 'Could not find an installed c8run binary to execute stop.',
1748
+ );
1749
+ }
1750
+ } else if (!hadSuccessfulStop && lastError && remainingPids.length === 0) {
1214
1751
  throw lastError;
1215
1752
  }
1216
1753
 
1754
+ // A partial stop is still a FAILED stop: if any recorded PID is confirmed
1755
+ // alive after reaping, the cluster may still hold its ports, so a fresh start
1756
+ // would collide. Surface it as an error (the record was retained above) so
1757
+ // the CLI exits non-zero and the user retries, rather than reporting success
1758
+ // while an orphan lingers (#560).
1759
+ if (remainingPids.length > 0) {
1760
+ throw new Error(
1761
+ `Stop incomplete: ${remainingPids.length} recorded cluster process${
1762
+ remainingPids.length === 1 ? '' : 'es'
1763
+ } could not be confirmed stopped (PID${remainingPids.length === 1 ? '' : 's'}: ${remainingPids.join(', ')}). ` +
1764
+ 'The durable PID record was kept — retry with "c8ctl cluster stop".',
1765
+ );
1766
+ }
1767
+
1217
1768
  logger.info('Cluster stopped.');
1218
1769
  return stoppedVersion;
1219
1770
  }
@@ -1529,9 +2080,15 @@ export async function clusterStatus(cacheDir) {
1529
2080
  const versionFile = join(cacheDir, VERSION_MARKER_FILE);
1530
2081
 
1531
2082
  const markerExists = existsSync(markerFile);
1532
- const version = markerExists && existsSync(versionFile)
2083
+ const record = readRunningClusterRecord(cacheDir);
2084
+ // A live process may exist without (or despite) a marker — e.g. after its
2085
+ // install dir was replaced/removed, orphaning it (#560). Detect it so status
2086
+ // never reports "stopped" while a tracked cluster process is still alive.
2087
+ const processesRunning = hasRunningClusterPidfiles(cacheDir);
2088
+ const markerVersion = markerExists && existsSync(versionFile)
1533
2089
  ? readFileSync(versionFile, 'utf-8').trim() || null
1534
2090
  : null;
2091
+ const version = markerVersion ?? record?.version ?? null;
1535
2092
 
1536
2093
  // Check live health endpoint regardless of marker
1537
2094
  let isHealthy = false;
@@ -1551,8 +2108,18 @@ export async function clusterStatus(cacheDir) {
1551
2108
  // Health endpoint not reachable
1552
2109
  }
1553
2110
 
2111
+ // A cluster process is alive but not tracked by a marker — typically an
2112
+ // orphan left after its install dir was replaced/removed (#560).
2113
+ const untracked = !markerExists && processesRunning;
2114
+
2115
+ // `untracked` takes precedence over a healthy probe: an orphaned process can
2116
+ // still serve the health endpoint while holding its ports, and the operator
2117
+ // must be told it is no longer tracked (and how to recover) rather than shown
2118
+ // a plain "running". Healthy connection URLs are still surfaced below.
1554
2119
  let status;
1555
- if (isHealthy) {
2120
+ if (untracked) {
2121
+ status = 'running (untracked)';
2122
+ } else if (isHealthy) {
1556
2123
  status = 'running';
1557
2124
  } else if (markerExists) {
1558
2125
  status = 'starting or unresponsive';
@@ -1561,11 +2128,21 @@ export async function clusterStatus(cacheDir) {
1561
2128
  }
1562
2129
 
1563
2130
  if (globalThis.c8ctl?.getLogger().mode === 'json') {
1564
- logger.json({ status, version, urls: isHealthy ? CLUSTER_URLS : undefined });
2131
+ // Machine-readable status must carry the SAME recovery guidance the text
2132
+ // renderer prints below for an orphan, otherwise a `--json` consumer sees
2133
+ // `running (untracked)` with no actionable instruction (#560).
2134
+ logger.json({
2135
+ status,
2136
+ version,
2137
+ urls: isHealthy ? CLUSTER_URLS : undefined,
2138
+ recovery: untracked
2139
+ ? 'A cluster process is still running but is no longer tracked by c8ctl (its install directory was likely replaced or removed while running). Stop it with: c8ctl cluster stop'
2140
+ : undefined,
2141
+ });
1565
2142
  return;
1566
2143
  }
1567
2144
 
1568
- if (!markerExists && !isHealthy) {
2145
+ if (!markerExists && !isHealthy && !processesRunning) {
1569
2146
  console.log('Cluster status: stopped');
1570
2147
  console.log('');
1571
2148
  console.log(' Start with: c8ctl cluster start');
@@ -1586,7 +2163,15 @@ export async function clusterStatus(cacheDir) {
1586
2163
  console.log(' - Health: ' + CLUSTER_URLS.health);
1587
2164
  console.log('');
1588
2165
  console.log(' Default credentials: demo / demo');
1589
- } else {
2166
+ }
2167
+
2168
+ if (untracked) {
2169
+ // Shown even when the orphan is healthy: it is still not tracked by c8ctl.
2170
+ console.log('');
2171
+ console.log(' A cluster process is still running but is no longer tracked by c8ctl');
2172
+ console.log(' (its install directory was likely replaced or removed while running).');
2173
+ console.log(' Stop it with: c8ctl cluster stop');
2174
+ } else if (!isHealthy) {
1590
2175
  console.log('');
1591
2176
  console.log(' The cluster appears to have been started but is not yet responding.');
1592
2177
  console.log(' Run "c8ctl cluster status" again in a moment, or check the logs.');
@@ -1767,6 +2352,9 @@ export async function deleteVersion(cacheDir, versionSpec) {
1767
2352
  }
1768
2353
 
1769
2354
  purgeInstalledVersion(config, { reason: 'as requested' });
2355
+ // Retire a stale durable record with no live PIDs so its dead (possibly
2356
+ // reused) PIDs are not later mistaken for this cluster (#560).
2357
+ clearStaleRunningClusterRecord(cacheDir);
1770
2358
  logger.info(`Version ${versionSpec} has been deleted.`);
1771
2359
  }
1772
2360
 
@@ -1803,31 +2391,45 @@ export async function purgeClusterData(cacheDir, versionSpec) {
1803
2391
  }
1804
2392
 
1805
2393
  const config = { cacheDir, version: resolvedVersion };
1806
- if (!isC8RunInstalled(config)) {
2394
+ const installDir = join(cacheDir, `c8run-${resolvedVersion}`);
2395
+ if (!existsSync(installDir)) {
1807
2396
  logger.error(`Version ${resolvedVersion} is not installed locally.`);
1808
2397
  process.exit(1);
1809
2398
  }
1810
2399
 
1811
- const binaryPath = getC8RunBinaryPath(config);
1812
- const binaryDir = dirname(binaryPath);
2400
+ // Runtime data normally sits next to the c8run binary. If the binary itself
2401
+ // is missing but the install dir survives — a partial/corrupt install, or the
2402
+ // orphan case where the binary was removed out from under a running cluster
2403
+ // (#560) — fall back to scanning the install dir and its immediate subdirs so
2404
+ // leftover data is still purged instead of being silently left behind.
2405
+ const binaryPath = findC8RunBinaryPath(config);
2406
+ const dataRoots = binaryPath
2407
+ ? [dirname(binaryPath)]
2408
+ : [
2409
+ installDir,
2410
+ ...readdirSync(installDir, { withFileTypes: true })
2411
+ .filter((entry) => entry.isDirectory())
2412
+ .map((entry) => join(installDir, entry.name)),
2413
+ ];
1813
2414
 
1814
2415
  const deleted = [];
2416
+ for (const dataRoot of dataRoots) {
2417
+ // Delete camunda-data (history data + application state)
2418
+ const camundaDataDir = join(dataRoot, 'camunda-data');
2419
+ if (existsSync(camundaDataDir)) {
2420
+ rmSync(camundaDataDir, { recursive: true });
2421
+ deleted.push('camunda-data');
2422
+ }
1815
2423
 
1816
- // Delete camunda-data (history data + application state)
1817
- const camundaDataDir = join(binaryDir, 'camunda-data');
1818
- if (existsSync(camundaDataDir)) {
1819
- rmSync(camundaDataDir, { recursive: true });
1820
- deleted.push('camunda-data');
1821
- }
1822
-
1823
- // Delete Zeebe journal data inside camunda-zeebe-* subdirectory
1824
- if (existsSync(binaryDir)) {
1825
- for (const entry of readdirSync(binaryDir, { withFileTypes: true })) {
1826
- if (!entry.isDirectory() || !entry.name.startsWith('camunda-zeebe-')) continue;
1827
- const dataDir = join(binaryDir, entry.name, 'data');
1828
- if (existsSync(dataDir)) {
1829
- rmSync(dataDir, { recursive: true });
1830
- deleted.push(join(entry.name, 'data'));
2424
+ // Delete Zeebe journal data inside camunda-zeebe-* subdirectory
2425
+ if (existsSync(dataRoot)) {
2426
+ for (const entry of readdirSync(dataRoot, { withFileTypes: true })) {
2427
+ if (!entry.isDirectory() || !entry.name.startsWith('camunda-zeebe-')) continue;
2428
+ const dataDir = join(dataRoot, entry.name, 'data');
2429
+ if (existsSync(dataDir)) {
2430
+ rmSync(dataDir, { recursive: true });
2431
+ deleted.push(join(entry.name, 'data'));
2432
+ }
1831
2433
  }
1832
2434
  }
1833
2435
  }
@@ -1840,6 +2442,9 @@ export async function purgeClusterData(cacheDir, versionSpec) {
1840
2442
  } else {
1841
2443
  logger.info(`No runtime data found for ${resolvedVersion} — nothing to delete.`);
1842
2444
  }
2445
+ // Retire a stale durable record with no live PIDs so its dead (possibly
2446
+ // reused) PIDs are not later mistaken for this cluster (#560).
2447
+ clearStaleRunningClusterRecord(cacheDir);
1843
2448
  logger.info(`Binary and installed files preserved. Start fresh with: c8ctl cluster start ${resolvedVersion}`);
1844
2449
  }
1845
2450
 
@@ -2203,6 +2808,17 @@ export const commands = {
2203
2808
  if (!stoppedVersion) {
2204
2809
  logger.warn('Cannot determine which version to purge (version marker is missing). ' +
2205
2810
  'To purge manually, run: c8ctl cluster purge <version>');
2811
+ } else if (!existsSync(join(theCacheDir, `c8run-${stoppedVersion}`))) {
2812
+ // The install dir itself is already gone — e.g. the orphan case
2813
+ // where it was removed out from under a running cluster (#560).
2814
+ // There is genuinely no runtime data left to purge, so treat it as
2815
+ // already purged rather than letting purgeClusterData exit "not
2816
+ // installed" and fail the combined command. If the install dir
2817
+ // still exists (even with its binary missing), fall through to
2818
+ // purgeClusterData so any leftover data is not silently retained.
2819
+ logger.info(
2820
+ `Version ${stoppedVersion} is no longer installed; its runtime data is already gone. Nothing to purge.`,
2821
+ );
2206
2822
  } else {
2207
2823
  await purgeClusterData(theCacheDir, stoppedVersion);
2208
2824
  }