dsh-apk-vm 0.12.4 → 0.13.0
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 +126 -10
- package/CHANGELOG.zh-CN.md +191 -0
- package/README.md +188 -36
- package/client.js +358 -22
- package/cordis.patch.yml +56 -0
- package/docs/AGENTS.md +62 -12
- package/docs/PRIVACY.md +11 -1
- package/docs/RELEASING.md +11 -5
- package/index.js +389 -26
- package/lib/activity-log.js +22 -0
- package/lib/android.js +290 -2
- package/lib/autosetup.js +211 -13
- package/lib/http-owner.js +101 -10
- package/lib/instances.js +484 -11
- package/lib/jdk.js +90 -11
- package/lib/lease-store.js +67 -0
- package/lib/memory.js +272 -0
- package/lib/setup.js +444 -30
- package/lib/storage.js +125 -4
- package/lib/vm-ownership.js +233 -20
- package/package.json +7 -4
package/lib/autosetup.js
CHANGED
|
@@ -37,6 +37,15 @@
|
|
|
37
37
|
* minutes are treated as abandoned and removed.
|
|
38
38
|
* - The JDK and system-image steps first check for at least 3 GB of free disk
|
|
39
39
|
* space and fail with an actionable error instead of a truncated download.
|
|
40
|
+
* The whole queued plan is also checked once against a cumulative
|
|
41
|
+
* free-space estimate before the first step starts (best effort; the target
|
|
42
|
+
* is the configured SDK root, the AVD home's parent, or the home directory).
|
|
43
|
+
* - Transient step failures (timeouts, stalled/hung transfers, ECONNRESET/
|
|
44
|
+
* ECONNREFUSED/5xx, DNS/network errors) are retried up to `stepRetries`
|
|
45
|
+
* times with exponential backoff; the retry attempt and next delay are
|
|
46
|
+
* visible in the status message and `detail`. Permanent failures (4xx,
|
|
47
|
+
* checksum mismatch, missing tools, invalid options) fail immediately.
|
|
48
|
+
* Cancellation requested during the backoff wait is honored.
|
|
40
49
|
*
|
|
41
50
|
* Status snapshot (JSON-safe, small):
|
|
42
51
|
* { state, step, totalSteps, stepId, message, detail, error, warnings,
|
|
@@ -44,6 +53,7 @@
|
|
|
44
53
|
*/
|
|
45
54
|
|
|
46
55
|
import { promises as fsp } from 'node:fs';
|
|
56
|
+
import os from 'node:os';
|
|
47
57
|
import path from 'node:path';
|
|
48
58
|
|
|
49
59
|
import { defaultJdkRoot } from './jdk.js';
|
|
@@ -96,6 +106,48 @@ const STEP_HINTS = Object.freeze({
|
|
|
96
106
|
/** An accel/hypervisor report item: the host requirement this plugin cannot install. */
|
|
97
107
|
const ACCEL_MISSING_RE = /(accel|hypervisor|kvm|aehd|whpx|hvf|haxm)/i;
|
|
98
108
|
|
|
109
|
+
/** Per-step retry policy: transient network failures are retried with backoff. */
|
|
110
|
+
const DEFAULT_STEP_RETRIES = 3;
|
|
111
|
+
const MIN_STEP_RETRIES = 1;
|
|
112
|
+
const MAX_STEP_RETRIES = 10;
|
|
113
|
+
const DEFAULT_RETRY_DELAY_MS = 2000;
|
|
114
|
+
const MAX_RETRY_DELAY_MS = 30 * 1000;
|
|
115
|
+
|
|
116
|
+
/** Rough per-step download/install footprint used by the cumulative disk precheck. */
|
|
117
|
+
const STEP_DISK_ESTIMATES = Object.freeze({
|
|
118
|
+
jdk: 650 * 1024 ** 2,
|
|
119
|
+
bootstrap: 200 * 1024 ** 2,
|
|
120
|
+
tools: 1.6 * 1024 ** 3,
|
|
121
|
+
image: 4.0 * 1024 ** 3,
|
|
122
|
+
avd: 400 * 1024 ** 2,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Permanent (do not retry) failures win over transient keywords: a 4xx from
|
|
127
|
+
* sdkmanager, a checksum mismatch, a missing tool or an invalid option is not
|
|
128
|
+
* going to fix itself by waiting.
|
|
129
|
+
*/
|
|
130
|
+
const PERMANENT_ERROR_RE =
|
|
131
|
+
/HTTP 4\d\d|checksum mismatch|not found: install|sdkmanager not found|java \(jdk 17\+\) is required|android sdk not found|unsupported platform|invalid |must be |must not /i;
|
|
132
|
+
/** Transient failures worth retrying with exponential backoff. */
|
|
133
|
+
const TRANSIENT_ERROR_RE =
|
|
134
|
+
/timed out|timeout|stalled|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ESOCKETTIMEDOUT|ENETUNREACH|ENOTFOUND|EAI_AGAIN|socket hang up|fetch failed|network|HTTP 5\d\d/i;
|
|
135
|
+
|
|
136
|
+
/** Classify a step error message: true when retrying may succeed. */
|
|
137
|
+
function isTransientSetupError(message) {
|
|
138
|
+
const text = limitText(message, MAX_ERROR_CHARS);
|
|
139
|
+
if (!text) return false;
|
|
140
|
+
if (PERMANENT_ERROR_RE.test(text)) return false;
|
|
141
|
+
return TRANSIENT_ERROR_RE.test(text);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Clamp an integer option into [min, max], falling back when not a number. */
|
|
145
|
+
function clampIntegerOption(value, fallback, min, max) {
|
|
146
|
+
const number = Number(value);
|
|
147
|
+
if (!Number.isFinite(number)) return fallback;
|
|
148
|
+
return Math.min(max, Math.max(min, Math.floor(number)));
|
|
149
|
+
}
|
|
150
|
+
|
|
99
151
|
const unavailable = (name) => async () => ({ ok: false, error: `${name} dependency is not wired` });
|
|
100
152
|
|
|
101
153
|
function nowIso() {
|
|
@@ -217,6 +269,14 @@ function normalizeJdkMirror(value) {
|
|
|
217
269
|
* @param {string} [options.home] home directory for jdkRoot discovery (default `os.homedir()`).
|
|
218
270
|
* @param {object} [options.env] environment map passed to JDK discovery (tests/hermetic runs).
|
|
219
271
|
* @param {Function} [options.statfs] injected `fs.statfs`-shaped free-space probe (tests).
|
|
272
|
+
* @param {number} [options.stepRetries=3] attempts per step on transient failures (clamped to 1..10).
|
|
273
|
+
* @param {number} [options.retryDelayMs=2000] first retry delay (ms); doubles per attempt, capped at 30 s.
|
|
274
|
+
* @param {number} [options.minFreeDiskBytes] override the cumulative free-space budget for the queued plan.
|
|
275
|
+
* @param {Function} [options.sleep] injected `(ms) => Promise` wait used by the retry backoff (tests).
|
|
276
|
+
* @param {string[]} [options.sdkManagerArgs] extra sdkmanager argv forwarded to bootstrap/tools/image.
|
|
277
|
+
* @param {Record<string,string>} [options.sdkManagerEnv] extra sdkmanager child env forwarded to those steps.
|
|
278
|
+
* @param {{host:string,port:number,user?:string,password?:string}} [options.networkProxy] sdkmanager proxy.
|
|
279
|
+
* @param {string} [options.commandLineToolsUrl] cmdline-tools archive override (bootstrap step only).
|
|
220
280
|
* @param {(line: string) => void} [options.log] progress log sink.
|
|
221
281
|
* @param {(snapshot: object) => void} [options.onUpdate] status observer (receives copies).
|
|
222
282
|
* @param {object} [options.deps] injected environment operations (all six optional).
|
|
@@ -243,6 +303,27 @@ export function createAutoSetup(options = {}) {
|
|
|
243
303
|
const env = raw.env && typeof raw.env === 'object' ? raw.env : undefined;
|
|
244
304
|
const log = typeof raw.log === 'function' ? raw.log : null;
|
|
245
305
|
const onUpdate = typeof raw.onUpdate === 'function' ? raw.onUpdate : null;
|
|
306
|
+
const stepRetries = clampIntegerOption(raw.stepRetries, DEFAULT_STEP_RETRIES, MIN_STEP_RETRIES, MAX_STEP_RETRIES);
|
|
307
|
+
const retryDelayMs = clampIntegerOption(raw.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 1, MAX_RETRY_DELAY_MS);
|
|
308
|
+
const minFreeDiskBytes =
|
|
309
|
+
Number.isFinite(Number(raw.minFreeDiskBytes)) && Number(raw.minFreeDiskBytes) > 0
|
|
310
|
+
? Math.floor(Number(raw.minFreeDiskBytes))
|
|
311
|
+
: null;
|
|
312
|
+
const sleep =
|
|
313
|
+
typeof raw.sleep === 'function'
|
|
314
|
+
? raw.sleep
|
|
315
|
+
: (ms) =>
|
|
316
|
+
new Promise((resolve) => {
|
|
317
|
+
const timer = setTimeout(resolve, ms);
|
|
318
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
319
|
+
});
|
|
320
|
+
// sdkmanager hardening options forwarded to the steps that run sdkmanager.
|
|
321
|
+
const sdkManagerOptions = {};
|
|
322
|
+
if (raw.sdkManagerArgs !== undefined) sdkManagerOptions.sdkManagerArgs = raw.sdkManagerArgs;
|
|
323
|
+
if (raw.sdkManagerEnv !== undefined) sdkManagerOptions.sdkManagerEnv = raw.sdkManagerEnv;
|
|
324
|
+
if (raw.networkProxy !== undefined) sdkManagerOptions.networkProxy = raw.networkProxy;
|
|
325
|
+
const commandLineToolsUrl =
|
|
326
|
+
typeof raw.commandLineToolsUrl === 'string' && raw.commandLineToolsUrl ? raw.commandLineToolsUrl : undefined;
|
|
246
327
|
|
|
247
328
|
const injected = raw.deps && typeof raw.deps === 'object' ? raw.deps : {};
|
|
248
329
|
const statfs =
|
|
@@ -297,9 +378,15 @@ export function createAutoSetup(options = {}) {
|
|
|
297
378
|
};
|
|
298
379
|
}
|
|
299
380
|
|
|
300
|
-
/**
|
|
301
|
-
|
|
381
|
+
/**
|
|
382
|
+
* Record a status message, then notify observers with an immutable copy.
|
|
383
|
+
* `extraDetail` is merged shallowly into `detail` (retry attempt metadata).
|
|
384
|
+
*/
|
|
385
|
+
function publish(text, extraDetail) {
|
|
302
386
|
message = text;
|
|
387
|
+
if (extraDetail && typeof extraDetail === 'object') {
|
|
388
|
+
detail = { ...(detail && typeof detail === 'object' ? detail : {}), ...extraDetail };
|
|
389
|
+
}
|
|
303
390
|
updatedAt = nowIso();
|
|
304
391
|
const snap = snapshot();
|
|
305
392
|
if (log) {
|
|
@@ -433,6 +520,48 @@ export function createAutoSetup(options = {}) {
|
|
|
433
520
|
};
|
|
434
521
|
}
|
|
435
522
|
|
|
523
|
+
/**
|
|
524
|
+
* Disk that will receive the queued plan: the configured SDK root, else the
|
|
525
|
+
* parent of the AVD home, else the user's home directory. The last fallback
|
|
526
|
+
* keeps the cumulative precheck active for a zero-config first run (the
|
|
527
|
+
* managed JDK/SDK/AVD all live under the home directory by default).
|
|
528
|
+
*/
|
|
529
|
+
function provisioningDiskTarget() {
|
|
530
|
+
if (sdkRoot) return sdkRoot;
|
|
531
|
+
if (env && typeof env.ANDROID_AVD_HOME === 'string' && env.ANDROID_AVD_HOME.trim()) {
|
|
532
|
+
return path.dirname(path.resolve(env.ANDROID_AVD_HOME.trim()));
|
|
533
|
+
}
|
|
534
|
+
return home || os.homedir();
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Cumulative free-space precheck for the whole queued plan (best effort: a
|
|
539
|
+
* filesystem that cannot report free space never blocks provisioning).
|
|
540
|
+
* `minFreeDiskBytes` overrides the sum of the per-step estimates.
|
|
541
|
+
*/
|
|
542
|
+
async function checkCumulativeDiskSpace(needed) {
|
|
543
|
+
if (!Array.isArray(needed) || needed.length === 0) return { ok: true };
|
|
544
|
+
const target = provisioningDiskTarget();
|
|
545
|
+
if (!target) return { ok: true };
|
|
546
|
+
const estimated = needed.reduce((total, id) => total + (STEP_DISK_ESTIMATES[id] || 0), 0);
|
|
547
|
+
const required = minFreeDiskBytes !== null ? minFreeDiskBytes : estimated;
|
|
548
|
+
if (!(required > 0)) return { ok: true };
|
|
549
|
+
let measured;
|
|
550
|
+
try {
|
|
551
|
+
measured = await freeDiskBytes(target);
|
|
552
|
+
} catch {
|
|
553
|
+
return { ok: true };
|
|
554
|
+
}
|
|
555
|
+
if (!measured || measured.free >= required) return { ok: true };
|
|
556
|
+
return {
|
|
557
|
+
ok: false,
|
|
558
|
+
error:
|
|
559
|
+
`not enough free disk space to provision the Android VM environment: ${measured.path} has ` +
|
|
560
|
+
`${formatMegabytes(measured.free)} free, but the ${needed.length} queued step(s) need about ` +
|
|
561
|
+
`${formatMegabytes(required)}; free up disk space and retry`,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
436
565
|
/** Read an existing lock file; tolerate truncated content via mtime fallback. */
|
|
437
566
|
async function readLockFile(lockPath) {
|
|
438
567
|
let payload = null;
|
|
@@ -539,6 +668,8 @@ export function createAutoSetup(options = {}) {
|
|
|
539
668
|
case 'bootstrap':
|
|
540
669
|
return {
|
|
541
670
|
...java,
|
|
671
|
+
...sdkManagerOptions,
|
|
672
|
+
...(commandLineToolsUrl ? { commandLineToolsUrl } : {}),
|
|
542
673
|
sdkRoot: sdkRoot || undefined,
|
|
543
674
|
systemImage,
|
|
544
675
|
platform,
|
|
@@ -547,6 +678,7 @@ export function createAutoSetup(options = {}) {
|
|
|
547
678
|
case 'tools':
|
|
548
679
|
return {
|
|
549
680
|
...java,
|
|
681
|
+
...sdkManagerOptions,
|
|
550
682
|
sdkRoot: sdkRoot || undefined,
|
|
551
683
|
packages: [
|
|
552
684
|
'platform-tools',
|
|
@@ -560,6 +692,7 @@ export function createAutoSetup(options = {}) {
|
|
|
560
692
|
case 'image':
|
|
561
693
|
return {
|
|
562
694
|
...java,
|
|
695
|
+
...sdkManagerOptions,
|
|
563
696
|
sdkRoot: sdkRoot || undefined,
|
|
564
697
|
systemImage,
|
|
565
698
|
platform,
|
|
@@ -604,10 +737,43 @@ export function createAutoSetup(options = {}) {
|
|
|
604
737
|
return report;
|
|
605
738
|
}
|
|
606
739
|
|
|
607
|
-
/**
|
|
740
|
+
/** Single-line error text for the retry status message. */
|
|
741
|
+
function oneLine(value) {
|
|
742
|
+
return limitText(String(value === undefined || value === null ? '' : value).replace(/\s+/g, ' ').trim(), 160);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* Publish the retry notice, then wait for the exponential backoff delay in
|
|
747
|
+
* small slices so an in-flight cancel is honored without a long sleep.
|
|
748
|
+
* @returns {Promise<boolean>} false when cancellation was requested.
|
|
749
|
+
*/
|
|
750
|
+
async function waitForRetry(id, attempt, errorText) {
|
|
751
|
+
const delay = Math.min(MAX_RETRY_DELAY_MS, retryDelayMs * 2 ** (attempt - 1));
|
|
752
|
+
const label = STEP_LABELS[id] || id;
|
|
753
|
+
publish(
|
|
754
|
+
`step ${step}/${totalSteps}: ${label} (retry ${attempt + 1}/${stepRetries} in ` +
|
|
755
|
+
`${Math.round(delay / 1000)}s: ${oneLine(errorText)})`,
|
|
756
|
+
{ attempt: attempt + 1, maxAttempts: stepRetries, nextDelayMs: delay },
|
|
757
|
+
);
|
|
758
|
+
let waited = 0;
|
|
759
|
+
while (waited < delay) {
|
|
760
|
+
if (cancelRequested) return false;
|
|
761
|
+
const slice = Math.min(250, delay - waited);
|
|
762
|
+
await sleep(slice);
|
|
763
|
+
waited += slice;
|
|
764
|
+
}
|
|
765
|
+
return !cancelRequested;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Run one dependency with transient-failure retries; resolve
|
|
770
|
+
* {ok,error,warnings} — never reject. The JDK provisioning lock is acquired
|
|
771
|
+
* once and held across retry attempts (released in `finally`).
|
|
772
|
+
*/
|
|
608
773
|
async function runStep(id) {
|
|
609
774
|
let stepLock = null;
|
|
610
|
-
let
|
|
775
|
+
let lastError = `${id} failed`;
|
|
776
|
+
let attempts = 0;
|
|
611
777
|
try {
|
|
612
778
|
// Fail fast with an actionable message instead of a truncated download.
|
|
613
779
|
const disk = await checkDiskSpace(id);
|
|
@@ -618,17 +784,44 @@ export function createAutoSetup(options = {}) {
|
|
|
618
784
|
if (!lock.ok) return lock;
|
|
619
785
|
stepLock = lock;
|
|
620
786
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
787
|
+
while (attempts < stepRetries) {
|
|
788
|
+
if (cancelRequested) return { ok: false, error: lastError, cancelled: true };
|
|
789
|
+
attempts += 1;
|
|
790
|
+
let result;
|
|
791
|
+
try {
|
|
792
|
+
result = await deps[STEP_DEP_NAMES[id]](stepOptions(id));
|
|
793
|
+
} catch (err) {
|
|
794
|
+
result = { ok: false, error: `${id} failed: ${limitText(err && err.message ? err.message : err)}` };
|
|
795
|
+
}
|
|
796
|
+
if (result && typeof result === 'object' && result.ok === false) {
|
|
797
|
+
lastError = limitText(result.error || `${id} returned ok:false`);
|
|
798
|
+
if (cancelRequested) return { ok: false, error: lastError, cancelled: true };
|
|
799
|
+
const canRetry = attempts < stepRetries && isTransientSetupError(lastError);
|
|
800
|
+
if (!canRetry) {
|
|
801
|
+
// Budget exhausted by a transient error: say so, so the operator
|
|
802
|
+
// knows the retry policy already ran; permanent errors stay plain.
|
|
803
|
+
const exhausted = attempts >= stepRetries && isTransientSetupError(lastError);
|
|
804
|
+
const error = exhausted
|
|
805
|
+
? `${lastError} (still failing after ${attempts} attempt${attempts === 1 ? '' : 's'})`
|
|
806
|
+
: lastError;
|
|
807
|
+
return { ok: false, error, attempts };
|
|
808
|
+
}
|
|
809
|
+
const proceed = await waitForRetry(id, attempts, lastError);
|
|
810
|
+
if (!proceed) return { ok: false, error: lastError, cancelled: true, attempts };
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
const stepWarnings =
|
|
814
|
+
result && typeof result === 'object' && Array.isArray(result.warnings) ? result.warnings : [];
|
|
815
|
+
return { ok: true, warnings: stepWarnings, attempts };
|
|
816
|
+
}
|
|
817
|
+
return {
|
|
818
|
+
ok: false,
|
|
819
|
+
error: `${lastError} (still failing after ${attempts} attempt${attempts === 1 ? '' : 's'})`,
|
|
820
|
+
attempts,
|
|
821
|
+
};
|
|
624
822
|
} finally {
|
|
625
823
|
if (stepLock) await releaseJdkLock(stepLock);
|
|
626
824
|
}
|
|
627
|
-
if (result && typeof result === 'object' && result.ok === false) {
|
|
628
|
-
return { ok: false, error: limitText(result.error || `${id} returned ok:false`) };
|
|
629
|
-
}
|
|
630
|
-
const stepWarnings = result && typeof result === 'object' && Array.isArray(result.warnings) ? result.warnings : [];
|
|
631
|
-
return { ok: true, warnings: stepWarnings };
|
|
632
825
|
}
|
|
633
826
|
|
|
634
827
|
function finishReady(report, text) {
|
|
@@ -702,6 +895,10 @@ export function createAutoSetup(options = {}) {
|
|
|
702
895
|
? `environment incomplete: ${needed.length} step(s) queued (${needed.join(' -> ')})`
|
|
703
896
|
: 'environment incomplete: no installable steps remain',
|
|
704
897
|
);
|
|
898
|
+
// Best-effort combined disk precheck so a big plan fails before any
|
|
899
|
+
// partial download starts (per-step checks below still run).
|
|
900
|
+
const cumulativeDisk = await checkCumulativeDiskSpace(needed);
|
|
901
|
+
if (!cumulativeDisk.ok) return finishFailed(cumulativeDisk.error);
|
|
705
902
|
|
|
706
903
|
for (let index = 0; index < needed.length; index += 1) {
|
|
707
904
|
if (cancelRequested) return finishCancelled();
|
|
@@ -752,7 +949,8 @@ export function createAutoSetup(options = {}) {
|
|
|
752
949
|
|
|
753
950
|
/**
|
|
754
951
|
* Request cancellation. An in-flight step (e.g. a download) is not
|
|
755
|
-
* interrupted;
|
|
952
|
+
* interrupted; a retry backoff wait is interruptible. The state becomes
|
|
953
|
+
* 'cancelled' once the current step returns or the backoff is interrupted.
|
|
756
954
|
*/
|
|
757
955
|
function cancel() {
|
|
758
956
|
if (state === 'running') {
|
package/lib/http-owner.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* the InstanceManager lease book.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { OWNER_ROLE, normalizeRole } from './vm-ownership.js';
|
|
7
|
+
import { OWNER_ROLE, normalizeRole, shortKey } from './vm-ownership.js';
|
|
8
8
|
|
|
9
9
|
const HEADER_NAMES = [
|
|
10
10
|
['key', 'x-apk-vm-owner'],
|
|
@@ -15,6 +15,9 @@ const HEADER_NAMES = [
|
|
|
15
15
|
['role', 'x-apk-vm-role'],
|
|
16
16
|
];
|
|
17
17
|
|
|
18
|
+
/** Explicit takeover marker used by the local panel and by HTTP clients. */
|
|
19
|
+
export const TAKEOVER_HEADER = 'x-apk-vm-takeover';
|
|
20
|
+
|
|
18
21
|
function decodeHeaderValue(value) {
|
|
19
22
|
const text = String(value);
|
|
20
23
|
if (!/%[0-9A-Fa-f]{2}/.test(text)) return text;
|
|
@@ -54,36 +57,124 @@ export function ownerFromHttp(headers, query) {
|
|
|
54
57
|
};
|
|
55
58
|
}
|
|
56
59
|
|
|
57
|
-
/**
|
|
58
|
-
export function
|
|
60
|
+
/** True when the request carries an explicit takeover marker. */
|
|
61
|
+
export function takeoverFromHttp(headers, query) {
|
|
62
|
+
const raw = firstValue(headers, query, TAKEOVER_HEADER).toLowerCase();
|
|
63
|
+
return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Describe a lease for a 409 response. Reserved/dedicated leases include the
|
|
68
|
+
* owner short id and the reservation deadline so the conflict is actionable.
|
|
69
|
+
*/
|
|
70
|
+
function describeLeaseConflict(lease, id) {
|
|
71
|
+
const label = (lease && (lease.label || lease.key)) || 'another owner';
|
|
72
|
+
const key = lease && lease.key ? String(lease.key) : '';
|
|
73
|
+
const short = key ? ` (${shortKey(key, 16)})` : '';
|
|
74
|
+
const reservedUntil = lease && Number(lease.reservedUntil) > 0 ? Number(lease.reservedUntil) : null;
|
|
75
|
+
if (reservedUntil) {
|
|
76
|
+
const until = new Date(reservedUntil).toISOString().replace('.000Z', 'Z');
|
|
77
|
+
return {
|
|
78
|
+
text: `VM ${id} is reserved by ${label}${short} until ${until}`,
|
|
79
|
+
reserved: true,
|
|
80
|
+
reservedUntil,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return { text: `VM ${id} is in use by ${label}${short}`, reserved: false, reservedUntil: null };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Compare an incoming owner with the current lease; never mutate state.
|
|
88
|
+
*
|
|
89
|
+
* `options.mutating` marks operations that change a VM (start/stop/tap/...)
|
|
90
|
+
* rather than read-only queries. `options.takeover` is the explicit takeover
|
|
91
|
+
* opt-in (`x-apk-vm-takeover: 1`). The local panel is a human administrator:
|
|
92
|
+
* it may run read-only queries on any VM without stealing the lease, but a
|
|
93
|
+
* mutating request against a lease owned by someone else requires an explicit
|
|
94
|
+
* takeover (409 `vm-takeover-required`).
|
|
95
|
+
*/
|
|
96
|
+
export function checkOwnerAccess(lease, incoming, instanceId = 'default', options = {}) {
|
|
59
97
|
const id = String(instanceId || 'default');
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
//
|
|
63
|
-
|
|
64
|
-
|
|
98
|
+
const mutating = options.mutating === true;
|
|
99
|
+
const takeover = options.takeover === true;
|
|
100
|
+
// Lock policy: 'all' (default) blocks every other mutating client, 'agents'
|
|
101
|
+
// blocks other agents but lets the local panel/admin operate, 'off' treats
|
|
102
|
+
// the lock as advisory only (no enforcement).
|
|
103
|
+
const lockMode = options.lockMode === 'agents' || options.lockMode === 'off' ? options.lockMode : 'all';
|
|
104
|
+
const isAdmin = Boolean(incoming && normalizeRole(incoming.role) === OWNER_ROLE.ADMIN);
|
|
105
|
+
// A lock is a hard block: even an admin takeover cannot control a locked VM
|
|
106
|
+
// (unless the operator chose the 'agents' policy, where the human panel is exempt).
|
|
107
|
+
if (lease && lease.locked === true && lockMode !== 'off') {
|
|
108
|
+
const sameOwner = Boolean(incoming && incoming.key === lease.key);
|
|
109
|
+
if (!mutating) {
|
|
110
|
+
return { ok: true, admin: isAdmin, autoClaim: false, touch: false, locked: true, lockOwner: lease };
|
|
111
|
+
}
|
|
112
|
+
if (sameOwner) {
|
|
113
|
+
return { ok: true, autoClaim: false, touch: true, locked: true };
|
|
114
|
+
}
|
|
115
|
+
if (lockMode === 'agents' && isAdmin) {
|
|
116
|
+
// The local panel is the human operator: 'agents' locks are for agents.
|
|
117
|
+
return { ok: true, admin: true, autoClaim: false, touch: false, locked: true, lockOwner: lease };
|
|
118
|
+
}
|
|
119
|
+
const label = lease.label || lease.key || 'another owner';
|
|
120
|
+
const short = lease.key ? ` (${shortKey(String(lease.key), 16)})` : '';
|
|
121
|
+
const lockedAt = Number(lease.lockedAt) > 0 ? new Date(Number(lease.lockedAt)).toISOString() : null;
|
|
122
|
+
return {
|
|
123
|
+
ok: false,
|
|
124
|
+
status: 409,
|
|
125
|
+
code: 'vm-locked',
|
|
126
|
+
error: `VM ${id} is locked by ${label}${short}${lockedAt ? ` since ${lockedAt}` : ''}; only the lock owner can control it. Unlock it in the panel (POST /apk-vm/ownership action=unlock) or ask the lock owner to unlock it.`,
|
|
127
|
+
owner: lease,
|
|
128
|
+
locked: true,
|
|
129
|
+
lockedAt: lease.lockedAt || null,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (isAdmin) {
|
|
133
|
+
if (!mutating || !lease || !incoming || incoming.key === lease.key) {
|
|
134
|
+
// Read-only access, unleased VM, or the admin's own lease.
|
|
135
|
+
return { ok: true, admin: true, autoClaim: false, touch: false };
|
|
136
|
+
}
|
|
137
|
+
if (takeover) {
|
|
138
|
+
return { ok: true, admin: true, takeover: true, autoClaim: false, touch: false };
|
|
139
|
+
}
|
|
140
|
+
const info = describeLeaseConflict(lease, id);
|
|
141
|
+
return {
|
|
142
|
+
ok: false,
|
|
143
|
+
status: 409,
|
|
144
|
+
code: 'vm-takeover-required',
|
|
145
|
+
error: `${info.text}; send ${TAKEOVER_HEADER}: 1 (or click “Take over” in the panel) to take it over`,
|
|
146
|
+
owner: lease,
|
|
147
|
+
reserved: info.reserved,
|
|
148
|
+
reservedUntil: info.reservedUntil,
|
|
149
|
+
};
|
|
65
150
|
}
|
|
66
151
|
if (!lease) {
|
|
67
152
|
return { ok: true, autoClaim: Boolean(incoming), touch: false };
|
|
68
153
|
}
|
|
69
154
|
if (!incoming) {
|
|
155
|
+
const info = describeLeaseConflict(lease, id);
|
|
70
156
|
return {
|
|
71
157
|
ok: false,
|
|
72
158
|
status: 409,
|
|
73
159
|
code: 'vm-busy',
|
|
74
|
-
error:
|
|
160
|
+
error: `${info.text}; include x-apk-vm-owner or claim it first`,
|
|
75
161
|
owner: lease,
|
|
162
|
+
reserved: info.reserved,
|
|
163
|
+
reservedUntil: info.reservedUntil,
|
|
76
164
|
};
|
|
77
165
|
}
|
|
78
166
|
if (incoming.key === lease.key) {
|
|
79
167
|
return { ok: true, autoClaim: false, touch: true };
|
|
80
168
|
}
|
|
169
|
+
const info = describeLeaseConflict(lease, id);
|
|
81
170
|
return {
|
|
82
171
|
ok: false,
|
|
83
172
|
status: 409,
|
|
84
173
|
code: 'vm-busy',
|
|
85
|
-
error:
|
|
174
|
+
error: `${info.text}; owner ${incoming.key} cannot control it; pass ownerForce:true (alias force:true) to take it over`,
|
|
86
175
|
owner: lease,
|
|
176
|
+
reserved: info.reserved,
|
|
177
|
+
reservedUntil: info.reservedUntil,
|
|
87
178
|
};
|
|
88
179
|
}
|
|
89
180
|
|