@nosana/node 1.1.84 → 1.1.85-rc

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.
Files changed (180) hide show
  1. package/dist/.env +2 -1
  2. package/dist/package.json +1 -1
  3. package/dist/packages/job-runtime/src/host/HostClient.d.ts +20 -4
  4. package/dist/packages/job-runtime/src/host/HostClient.js +35 -2
  5. package/dist/packages/job-runtime/src/host/contract.d.ts +27 -7
  6. package/dist/packages/job-runtime/src/host/contract.js +43 -7
  7. package/dist/packages/job-runtime/src/runtime/runJob.d.ts +8 -5
  8. package/dist/packages/job-runtime/src/runtime/runJob.js +44 -17
  9. package/dist/packages/vm-orchestrator/src/CidRegistry.d.ts +67 -0
  10. package/dist/packages/vm-orchestrator/src/CidRegistry.js +168 -0
  11. package/dist/packages/vm-orchestrator/src/GpuPool.d.ts +27 -0
  12. package/dist/packages/vm-orchestrator/src/GpuPool.js +41 -0
  13. package/dist/packages/vm-orchestrator/src/Hypervisor.d.ts +66 -0
  14. package/dist/packages/vm-orchestrator/src/Hypervisor.js +7 -0
  15. package/dist/packages/vm-orchestrator/src/QemuHypervisor.d.ts +62 -0
  16. package/dist/packages/vm-orchestrator/src/QemuHypervisor.js +185 -0
  17. package/dist/packages/vm-orchestrator/src/QemuHypervisorConfig.d.ts +61 -0
  18. package/dist/packages/vm-orchestrator/src/QemuHypervisorConfig.js +37 -0
  19. package/dist/packages/vm-orchestrator/src/QemuVmInstance.d.ts +37 -0
  20. package/dist/packages/vm-orchestrator/src/QemuVmInstance.js +44 -0
  21. package/dist/packages/vm-orchestrator/src/QmpClient.d.ts +43 -0
  22. package/dist/packages/vm-orchestrator/src/QmpClient.js +103 -0
  23. package/dist/packages/vm-orchestrator/src/VmSpec.d.ts +21 -0
  24. package/dist/packages/vm-orchestrator/src/VmSpec.js +30 -0
  25. package/dist/packages/vm-orchestrator/src/VmStateManager.d.ts +16 -0
  26. package/dist/packages/vm-orchestrator/src/VmStateManager.js +30 -0
  27. package/dist/packages/vm-orchestrator/src/bootAttempt.d.ts +31 -0
  28. package/dist/packages/vm-orchestrator/src/bootAttempt.js +193 -0
  29. package/dist/packages/vm-orchestrator/src/bootErrors.d.ts +33 -0
  30. package/dist/packages/vm-orchestrator/src/bootErrors.js +67 -0
  31. package/dist/packages/vm-orchestrator/src/buildCloudInit.d.ts +33 -0
  32. package/dist/packages/vm-orchestrator/src/buildCloudInit.js +55 -0
  33. package/dist/packages/vm-orchestrator/src/buildQemuArgs.d.ts +33 -0
  34. package/dist/packages/vm-orchestrator/src/buildQemuArgs.js +127 -0
  35. package/dist/packages/vm-orchestrator/src/diskSizing.d.ts +18 -0
  36. package/dist/packages/vm-orchestrator/src/diskSizing.js +41 -0
  37. package/dist/packages/vm-orchestrator/src/firmware.d.ts +5 -0
  38. package/dist/packages/vm-orchestrator/src/firmware.js +18 -0
  39. package/dist/packages/vm-orchestrator/src/hostAccess/VmHostAccess.d.ts +22 -0
  40. package/dist/packages/vm-orchestrator/src/hostAccess/VmHostAccess.js +33 -0
  41. package/dist/packages/vm-orchestrator/src/hostAccess/deviceProblems.d.ts +3 -0
  42. package/dist/packages/vm-orchestrator/src/hostAccess/deviceProblems.js +17 -0
  43. package/dist/packages/vm-orchestrator/src/hostAccess/findVmHostAccessProblems.d.ts +9 -0
  44. package/dist/packages/vm-orchestrator/src/hostAccess/findVmHostAccessProblems.js +17 -0
  45. package/dist/packages/vm-orchestrator/src/hostAccess/gpuProblems.d.ts +6 -0
  46. package/dist/packages/vm-orchestrator/src/hostAccess/gpuProblems.js +42 -0
  47. package/dist/packages/vm-orchestrator/src/hostAccess/index.d.ts +1 -0
  48. package/dist/packages/vm-orchestrator/src/hostAccess/index.js +1 -0
  49. package/dist/packages/vm-orchestrator/src/hostAccess/memlockProblems.d.ts +6 -0
  50. package/dist/packages/vm-orchestrator/src/hostAccess/memlockProblems.js +18 -0
  51. package/dist/packages/vm-orchestrator/src/hostAccess/workRootProblems.d.ts +7 -0
  52. package/dist/packages/vm-orchestrator/src/hostAccess/workRootProblems.js +30 -0
  53. package/dist/packages/vm-orchestrator/src/hostDevices.d.ts +12 -0
  54. package/dist/packages/vm-orchestrator/src/hostDevices.js +12 -0
  55. package/dist/packages/vm-orchestrator/src/hostTools.d.ts +25 -0
  56. package/dist/packages/vm-orchestrator/src/hostTools.js +39 -0
  57. package/dist/packages/vm-orchestrator/src/imageCache.d.ts +25 -0
  58. package/dist/packages/vm-orchestrator/src/imageCache.js +73 -0
  59. package/dist/packages/vm-orchestrator/src/imageDownload.d.ts +31 -0
  60. package/dist/packages/vm-orchestrator/src/imageDownload.js +85 -0
  61. package/dist/packages/vm-orchestrator/src/index.d.ts +19 -0
  62. package/dist/packages/vm-orchestrator/src/index.js +15 -0
  63. package/dist/packages/vm-orchestrator/src/memlockLimit.d.ts +5 -0
  64. package/dist/packages/vm-orchestrator/src/memlockLimit.js +23 -0
  65. package/dist/packages/vm-orchestrator/src/nvidiaHolders.d.ts +11 -0
  66. package/dist/packages/vm-orchestrator/src/nvidiaHolders.js +74 -0
  67. package/dist/packages/vm-orchestrator/src/pciNuma.d.ts +7 -0
  68. package/dist/packages/vm-orchestrator/src/pciNuma.js +18 -0
  69. package/dist/packages/vm-orchestrator/src/pciSysfs.d.ts +21 -0
  70. package/dist/packages/vm-orchestrator/src/pciSysfs.js +47 -0
  71. package/dist/packages/vm-orchestrator/src/processes.d.ts +37 -0
  72. package/dist/packages/vm-orchestrator/src/processes.js +102 -0
  73. package/dist/packages/vm-orchestrator/src/sockets.d.ts +21 -0
  74. package/dist/packages/vm-orchestrator/src/sockets.js +58 -0
  75. package/dist/packages/vm-orchestrator/src/sweepVmImageCache.d.ts +19 -0
  76. package/dist/packages/vm-orchestrator/src/sweepVmImageCache.js +132 -0
  77. package/dist/packages/vm-orchestrator/src/util.d.ts +14 -0
  78. package/dist/packages/vm-orchestrator/src/util.js +33 -0
  79. package/dist/packages/vm-orchestrator/src/vfioBinding.d.ts +27 -0
  80. package/dist/packages/vm-orchestrator/src/vfioBinding.js +163 -0
  81. package/dist/packages/vm-orchestrator/src/vmImageResolver.d.ts +20 -0
  82. package/dist/packages/vm-orchestrator/src/vmImageResolver.js +62 -0
  83. package/dist/packages/vm-orchestrator/src/vsockBridge.d.ts +20 -0
  84. package/dist/packages/vm-orchestrator/src/vsockBridge.js +27 -0
  85. package/dist/packages/vm-orchestrator/src/workDirs.d.ts +49 -0
  86. package/dist/packages/vm-orchestrator/src/workDirs.js +79 -0
  87. package/dist/src/NodeManager/configs/configs.d.ts +4 -0
  88. package/dist/src/NodeManager/configs/configs.js +3 -0
  89. package/dist/src/NodeManager/db/index.d.ts +10 -0
  90. package/dist/src/NodeManager/db/index.js +4 -0
  91. package/dist/src/NodeManager/monitoring/log/NodeLog.d.ts +2 -0
  92. package/dist/src/NodeManager/monitoring/log/NodeLog.js +21 -0
  93. package/dist/src/NodeManager/monitoring/log/console/ConsoleLogger.d.ts +8 -0
  94. package/dist/src/NodeManager/monitoring/log/console/ConsoleLogger.js +29 -5
  95. package/dist/src/NodeManager/monitoring/log/vmSetupLog.d.ts +11 -0
  96. package/dist/src/NodeManager/monitoring/log/vmSetupLog.js +33 -0
  97. package/dist/src/NodeManager/node/Node.d.ts +2 -0
  98. package/dist/src/NodeManager/node/Node.js +12 -5
  99. package/dist/src/NodeManager/node/job/ContainerJobRuntime.d.ts +141 -0
  100. package/dist/src/NodeManager/node/job/ContainerJobRuntime.js +419 -0
  101. package/dist/src/NodeManager/node/job/JobRuntimeEnvironment.d.ts +74 -0
  102. package/dist/src/NodeManager/node/job/JobRuntimeEnvironment.js +1 -0
  103. package/dist/src/NodeManager/node/job/JobRuntimeHost.d.ts +6 -2
  104. package/dist/src/NodeManager/node/job/JobRuntimeHost.js +13 -2
  105. package/dist/src/NodeManager/node/job/JobRuntimeSession.d.ts +12 -9
  106. package/dist/src/NodeManager/node/job/JobRuntimeSession.js +42 -71
  107. package/dist/src/NodeManager/node/job/VmJobRuntime.d.ts +109 -0
  108. package/dist/src/NodeManager/node/job/VmJobRuntime.js +258 -0
  109. package/dist/src/NodeManager/node/job/VmJobRuntimeConfig.d.ts +33 -0
  110. package/dist/src/NodeManager/node/job/VmJobRuntimeConfig.js +1 -0
  111. package/dist/src/NodeManager/node/job/buildJobRuntimeEnv.d.ts +41 -0
  112. package/dist/src/NodeManager/node/job/buildJobRuntimeEnv.js +25 -0
  113. package/dist/src/NodeManager/node/job/followFile.d.ts +14 -0
  114. package/dist/src/NodeManager/node/job/followFile.js +57 -0
  115. package/dist/src/NodeManager/node/job/jobHandler.d.ts +3 -3
  116. package/dist/src/NodeManager/node/job/jobHandler.js +7 -7
  117. package/dist/src/NodeManager/node/job/keepFailedConsole.d.ts +7 -0
  118. package/dist/src/NodeManager/node/job/keepFailedConsole.js +52 -0
  119. package/dist/src/NodeManager/node/job/selectJobRuntimeEnvironment.d.ts +50 -0
  120. package/dist/src/NodeManager/node/job/selectJobRuntimeEnvironment.js +117 -0
  121. package/dist/src/NodeManager/node/market/benchmark.d.ts +3 -3
  122. package/dist/src/NodeManager/node/market/benchmark.js +3 -3
  123. package/dist/src/NodeManager/node/market/marketHandler.d.ts +3 -3
  124. package/dist/src/NodeManager/node/market/marketHandler.js +3 -3
  125. package/dist/src/NodeManager/node/resource/resourceManager.d.ts +1 -1
  126. package/dist/src/NodeManager/node/resource/resourceManager.js +1 -1
  127. package/dist/src/NodeManager/provider/Provider.d.ts +3 -121
  128. package/dist/src/NodeManager/provider/Provider.js +3 -369
  129. package/dist/src/NodeManager/provider/vmHost/VmNodeOptions.d.ts +14 -0
  130. package/dist/src/NodeManager/provider/vmHost/VmNodeOptions.js +1 -0
  131. package/dist/src/NodeManager/provider/vmHost/capacity.d.ts +16 -0
  132. package/dist/src/NodeManager/provider/vmHost/capacity.js +47 -0
  133. package/dist/src/NodeManager/provider/vmHost/gpus.d.ts +19 -0
  134. package/dist/src/NodeManager/provider/vmHost/gpus.js +83 -0
  135. package/dist/src/NodeManager/provider/vmHost/index.d.ts +5 -0
  136. package/dist/src/NodeManager/provider/vmHost/index.js +4 -0
  137. package/dist/src/NodeManager/provider/vmHost/readVmSpec.d.ts +11 -0
  138. package/dist/src/NodeManager/provider/vmHost/readVmSpec.js +22 -0
  139. package/dist/src/NodeManager/provider/vmHost/setup/PrepareVmHostSystem.d.ts +27 -0
  140. package/dist/src/NodeManager/provider/vmHost/setup/PrepareVmHostSystem.js +25 -0
  141. package/dist/src/NodeManager/provider/vmHost/setup/fileOwnership.d.ts +6 -0
  142. package/dist/src/NodeManager/provider/vmHost/setup/fileOwnership.js +22 -0
  143. package/dist/src/NodeManager/provider/vmHost/setup/hostUser.d.ts +15 -0
  144. package/dist/src/NodeManager/provider/vmHost/setup/hostUser.js +25 -0
  145. package/dist/src/NodeManager/provider/vmHost/setup/index.d.ts +2 -0
  146. package/dist/src/NodeManager/provider/vmHost/setup/index.js +2 -0
  147. package/dist/src/NodeManager/provider/vmHost/setup/memlockLimits.d.ts +6 -0
  148. package/dist/src/NodeManager/provider/vmHost/setup/memlockLimits.js +12 -0
  149. package/dist/src/NodeManager/provider/vmHost/setup/prepareVmHost.d.ts +17 -0
  150. package/dist/src/NodeManager/provider/vmHost/setup/prepareVmHost.js +90 -0
  151. package/dist/src/NodeManager/provider/vmHost/setup/sudoCaller.d.ts +5 -0
  152. package/dist/src/NodeManager/provider/vmHost/setup/sudoCaller.js +35 -0
  153. package/dist/src/NodeManager/provider/vmHost/vmHostEnv.d.ts +20 -0
  154. package/dist/src/NodeManager/provider/vmHost/vmHostEnv.js +24 -0
  155. package/dist/src/NodeManager/provider/vmHost/workRoot.d.ts +14 -0
  156. package/dist/src/NodeManager/provider/vmHost/workRoot.js +84 -0
  157. package/dist/src/NodeManager/repository/NodeRepository.d.ts +12 -2
  158. package/dist/src/NodeManager/repository/NodeRepository.js +21 -1
  159. package/dist/src/cli/commands/prune/command.js +2 -1
  160. package/dist/src/cli/commands/run/action.d.ts +2 -2
  161. package/dist/src/cli/commands/run/action.js +15 -34
  162. package/dist/src/cli/commands/run/command.js +7 -2
  163. package/dist/src/cli/commands/sharedOptions/--config.d.ts +2 -0
  164. package/dist/src/cli/commands/sharedOptions/--config.js +2 -0
  165. package/dist/src/cli/commands/sharedOptions/--environment.d.ts +6 -0
  166. package/dist/src/cli/commands/sharedOptions/--environment.js +6 -0
  167. package/dist/src/cli/commands/sharedOptions/--gpu.js +5 -2
  168. package/dist/src/cli/commands/sharedOptions/--node-limits.d.ts +9 -0
  169. package/dist/src/cli/commands/sharedOptions/--node-limits.js +24 -0
  170. package/dist/src/cli/commands/sharedOptions/index.d.ts +3 -0
  171. package/dist/src/cli/commands/sharedOptions/index.js +3 -0
  172. package/dist/src/cli/commands/start/command.js +7 -2
  173. package/dist/src/cli/commands/vm-setup/action.d.ts +10 -0
  174. package/dist/src/cli/commands/vm-setup/action.js +14 -0
  175. package/dist/src/cli/commands/vm-setup/command.d.ts +3 -0
  176. package/dist/src/cli/commands/vm-setup/command.js +11 -0
  177. package/dist/src/cli/createNosanaCli.d.ts +1 -0
  178. package/dist/src/cli/createNosanaCli.js +4 -1
  179. package/npm-shrinkwrap.json +10 -2
  180. package/package.json +1 -1
@@ -0,0 +1,21 @@
1
+ import net from 'net';
2
+ import { QmpClient } from './QmpClient.js';
3
+ import type { WorkDirPaths } from './workDirs.js';
4
+ /** A VM's QMP control and serial console connections. */
5
+ export interface VmConnection {
6
+ qmp: QmpClient;
7
+ serial: net.Socket;
8
+ }
9
+ /** How a VM's sockets are connected; injectable for tests. */
10
+ export interface VmSocketConnectors {
11
+ connectQmp: (socketPath: string) => Promise<QmpClient>;
12
+ connectSerial: (socketPath: string) => Promise<net.Socket>;
13
+ }
14
+ /** Connect a VM's QMP and serial console sockets. */
15
+ export declare function connectVmSockets(connectors: VmSocketConnectors, paths: Pick<WorkDirPaths, 'qmpSocket' | 'serialSocket'>): Promise<VmConnection>;
16
+ /** Ask the OS for a free TCP port by binding to 0 and releasing it. */
17
+ export declare function allocateFreePort(): Promise<number>;
18
+ /** Connect QEMU's QMP control socket, retrying while QEMU has not made it yet. */
19
+ export declare function connectQmpWithRetry(socketPath: string): Promise<QmpClient>;
20
+ /** Connect QEMU's serial console socket, retrying while QEMU has not made it yet. */
21
+ export declare function connectSerialWithRetry(socketPath: string): Promise<net.Socket>;
@@ -0,0 +1,58 @@
1
+ import net from 'net';
2
+ import { QmpClient } from './QmpClient.js';
3
+ import { sleep } from './util.js';
4
+ /** Attempts (and the delay between them) at a QEMU socket while QEMU comes up. */
5
+ const CONNECT_RETRIES = 50;
6
+ const CONNECT_RETRY_DELAY_MS = 100;
7
+ /** Connect a VM's QMP and serial console sockets. */
8
+ export async function connectVmSockets(connectors, paths) {
9
+ const [qmp, serial] = await Promise.all([
10
+ connectors.connectQmp(paths.qmpSocket),
11
+ connectors.connectSerial(paths.serialSocket),
12
+ ]);
13
+ return { qmp, serial };
14
+ }
15
+ /** Ask the OS for a free TCP port by binding to 0 and releasing it. */
16
+ export function allocateFreePort() {
17
+ return new Promise((resolve, reject) => {
18
+ const server = net.createServer();
19
+ server.once('error', reject);
20
+ server.listen(0, '127.0.0.1', () => {
21
+ const address = server.address();
22
+ const port = address && typeof address === 'object' ? address.port : 0;
23
+ server.close(() => resolve(port));
24
+ });
25
+ });
26
+ }
27
+ /** Connect QEMU's QMP control socket, retrying while QEMU has not made it yet. */
28
+ export function connectQmpWithRetry(socketPath) {
29
+ return connectWithRetry(async () => {
30
+ const client = new QmpClient();
31
+ await client.connect(socketPath);
32
+ return client;
33
+ });
34
+ }
35
+ /** Connect QEMU's serial console socket, retrying while QEMU has not made it yet. */
36
+ export function connectSerialWithRetry(socketPath) {
37
+ return connectWithRetry(() => connectUnixSocket(socketPath));
38
+ }
39
+ async function connectWithRetry(attempt) {
40
+ let lastError;
41
+ for (let i = 0; i <= CONNECT_RETRIES; i++) {
42
+ try {
43
+ return await attempt();
44
+ }
45
+ catch (error) {
46
+ lastError = error;
47
+ await sleep(CONNECT_RETRY_DELAY_MS);
48
+ }
49
+ }
50
+ throw lastError;
51
+ }
52
+ function connectUnixSocket(socketPath) {
53
+ return new Promise((resolve, reject) => {
54
+ const socket = net.createConnection(socketPath);
55
+ socket.once('connect', () => resolve(socket));
56
+ socket.once('error', reject);
57
+ });
58
+ }
@@ -0,0 +1,19 @@
1
+ import { type RunForOutput } from './processes.js';
2
+ export interface SweepVmImageCacheOptions {
3
+ /** Runs `qemu-img info` (default: execFile); injectable for tests. */
4
+ run?: RunForOutput;
5
+ /** The qemu-img binary (default: `qemu-img` on the PATH). */
6
+ qemuImgBinary?: string;
7
+ /** Logs what the sweep removed or why it stopped. */
8
+ log?: (message: string) => void;
9
+ }
10
+ /**
11
+ * Delete every cached image the host no longer needs: each image dir under
12
+ * `cacheDir` whose image is not in `keep` (image references, as resolved) and
13
+ * whose disk file backs no VM overlay under `workRoot`. Each dir's locks are
14
+ * taken first (one held by a live process, a download or a boot, spares the
15
+ * dir), the backing files are read again under them, and the dir is emptied;
16
+ * the locks are released last. An overlay that cannot be read stops the
17
+ * sweep: deleting nothing is the safe answer.
18
+ */
19
+ export declare function sweepVmImageCache(cacheDir: string, keep: string[], workRoot: string, opts?: SweepVmImageCacheOptions): Promise<void>;
@@ -0,0 +1,132 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { QEMU_IMG_BINARY } from './hostTools.js';
4
+ import { cacheDirName, DISK_IMAGE_PATTERN, tryLockFile } from './imageCache.js';
5
+ import { runForOutput } from './processes.js';
6
+ import { describeError, pathExists } from './util.js';
7
+ import { OVERLAY_FILE, WORK_DIR_PREFIX } from './workDirs.js';
8
+ /**
9
+ * Delete every cached image the host no longer needs: each image dir under
10
+ * `cacheDir` whose image is not in `keep` (image references, as resolved) and
11
+ * whose disk file backs no VM overlay under `workRoot`. Each dir's locks are
12
+ * taken first (one held by a live process, a download or a boot, spares the
13
+ * dir), the backing files are read again under them, and the dir is emptied;
14
+ * the locks are released last. An overlay that cannot be read stops the
15
+ * sweep: deleting nothing is the safe answer.
16
+ */
17
+ export async function sweepVmImageCache(cacheDir, keep, workRoot, opts = {}) {
18
+ const { run = runForOutput, qemuImgBinary = QEMU_IMG_BINARY, log } = opts;
19
+ const scanBacked = () => scanBackingFiles(workRoot, run, qemuImgBinary, log);
20
+ const candidates = await listCandidates(cacheDir, keep);
21
+ // Nothing to delete: skip reading every VM overlay.
22
+ if (candidates.length === 0)
23
+ return;
24
+ const backed = await scanBacked();
25
+ if (!backed)
26
+ return;
27
+ for (const name of candidates) {
28
+ await sweepImageDir(path.join(cacheDir, name), backed, scanBacked);
29
+ }
30
+ }
31
+ /** The image dirs not in `keep`; [] when there is no cache. */
32
+ async function listCandidates(cacheDir, keep) {
33
+ const keepDirs = new Set(keep.map(cacheDirName));
34
+ const names = await fs.readdir(cacheDir).catch(() => []);
35
+ return names.filter((name) => !keepDirs.has(name));
36
+ }
37
+ /** Empty and remove one image dir unless a VM backs its image or a live process holds a lock. */
38
+ async function sweepImageDir(dir, backed, scanBacked) {
39
+ const files = await fs.readdir(dir).catch(() => undefined);
40
+ if (!files)
41
+ return;
42
+ const disks = await diskRealPaths(dir, files);
43
+ if (disks.some((disk) => backed.has(disk)))
44
+ return;
45
+ const locks = lockFileNames(files);
46
+ const held = [];
47
+ try {
48
+ if (!(await tryLockEach(dir, locks, held)))
49
+ return;
50
+ // A boot may have put an overlay over it before the locks were held.
51
+ const backedNow = await scanBacked();
52
+ if (!backedNow || disks.some((disk) => backedNow.has(disk)))
53
+ return;
54
+ await removeAllBut(dir, locks);
55
+ }
56
+ finally {
57
+ for (const release of held)
58
+ await release();
59
+ }
60
+ await fs.rmdir(dir).catch(() => undefined);
61
+ }
62
+ /** The real paths of the disk images in an image dir. */
63
+ function diskRealPaths(dir, files) {
64
+ const disks = files.filter((file) => DISK_IMAGE_PATTERN.test(file));
65
+ return Promise.all(disks.map((file) => realPath(path.join(dir, file))));
66
+ }
67
+ /** Every lock in an image dir: each disk's, and any left by a download whose disk is not there yet. */
68
+ function lockFileNames(files) {
69
+ return new Set([
70
+ ...files.filter((file) => DISK_IMAGE_PATTERN.test(file)).map((file) => `${file}.lock`),
71
+ ...files.filter((file) => file.endsWith('.lock')),
72
+ ]);
73
+ }
74
+ /** Take each lock in turn into `held`; false at the first one someone else holds. */
75
+ async function tryLockEach(dir, locks, held) {
76
+ for (const lock of locks) {
77
+ const release = await tryLockFile(path.join(dir, lock));
78
+ if (!release)
79
+ return false;
80
+ held.push(release);
81
+ }
82
+ return true;
83
+ }
84
+ async function removeAllBut(dir, keep) {
85
+ for (const file of await fs.readdir(dir)) {
86
+ if (keep.has(file))
87
+ continue;
88
+ await fs.rm(path.join(dir, file), { recursive: true, force: true });
89
+ }
90
+ }
91
+ /** {@link readBackingFiles}, or undefined (logged) when an overlay cannot be read. */
92
+ async function scanBackingFiles(workRoot, run, qemuImg, log) {
93
+ try {
94
+ return await readBackingFiles(workRoot, run, qemuImg);
95
+ }
96
+ catch (error) {
97
+ log?.(`VM image cache sweep skipped: cannot read a VM overlay (${describeError(error).message})`);
98
+ return undefined;
99
+ }
100
+ }
101
+ /**
102
+ * The base images the VMs on this host still back: the backing file of every
103
+ * `<workRoot>/nosana-vm-*\/overlay.qcow2`, real paths. Throws when an overlay
104
+ * cannot be read, since what it backs is then unknown.
105
+ */
106
+ async function readBackingFiles(workRoot, run, qemuImg) {
107
+ const backed = new Set();
108
+ const names = await fs.readdir(workRoot).catch(() => []);
109
+ for (const name of names) {
110
+ if (!name.startsWith(WORK_DIR_PREFIX))
111
+ continue;
112
+ const overlay = path.join(workRoot, name, OVERLAY_FILE);
113
+ if (!(await pathExists(overlay)))
114
+ continue;
115
+ const backing = await readBackingFile(run, qemuImg, overlay);
116
+ if (backing)
117
+ backed.add(backing);
118
+ }
119
+ return backed;
120
+ }
121
+ /** An overlay's backing file, as a real path. `--force-share` reads one a running QEMU holds open. */
122
+ async function readBackingFile(run, qemuImg, overlay) {
123
+ const output = await run(qemuImg, ['info', '--force-share', '--output=json', overlay]);
124
+ const info = JSON.parse(output);
125
+ const backing = info['full-backing-filename'] ?? info['backing-filename'];
126
+ if (!backing)
127
+ return undefined;
128
+ return realPath(path.resolve(path.dirname(overlay), backing));
129
+ }
130
+ async function realPath(target) {
131
+ return fs.realpath(target).catch(() => target);
132
+ }
@@ -0,0 +1,14 @@
1
+ /** What a thrown value says about itself. */
2
+ export interface ErrorDetails {
3
+ message: string;
4
+ /** The errno code (`EEXIST`, `ESRCH`, ...) of a system error. */
5
+ code?: string;
6
+ }
7
+ /** Resolve after `ms` milliseconds. */
8
+ export declare function sleep(ms: number): Promise<void>;
9
+ /** Resolve once `promise` settles or `ms` elapses, whichever comes first. */
10
+ export declare function waitAtMost(promise: Promise<unknown>, ms: number): Promise<void>;
11
+ /** Does anything exist at `target`? */
12
+ export declare function pathExists(target: string): Promise<boolean>;
13
+ /** The message and errno code of a thrown value, whatever was thrown. */
14
+ export declare function describeError(error: unknown): ErrorDetails;
@@ -0,0 +1,33 @@
1
+ import fs from 'fs/promises';
2
+ /** Resolve after `ms` milliseconds. */
3
+ export function sleep(ms) {
4
+ return new Promise((resolve) => setTimeout(resolve, ms));
5
+ }
6
+ /** Resolve once `promise` settles or `ms` elapses, whichever comes first. */
7
+ export function waitAtMost(promise, ms) {
8
+ return new Promise((resolve) => {
9
+ const timer = setTimeout(resolve, ms);
10
+ const done = () => {
11
+ clearTimeout(timer);
12
+ resolve();
13
+ };
14
+ promise.then(done, done);
15
+ });
16
+ }
17
+ /** Does anything exist at `target`? */
18
+ export async function pathExists(target) {
19
+ try {
20
+ await fs.stat(target);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ /** The message and errno code of a thrown value, whatever was thrown. */
28
+ export function describeError(error) {
29
+ if (!(error instanceof Error))
30
+ return { message: String(error) };
31
+ const { code } = error;
32
+ return { message: error.message, code };
33
+ }
@@ -0,0 +1,27 @@
1
+ /** Where and how GPUs are bound to vfio-pci; tests inject a fake host. */
2
+ export interface VfioHost {
3
+ /** The sysfs PCI root (`/sys/bus/pci`). */
4
+ pciRoot: string;
5
+ /** The iommufd device (`/dev/iommu`), present once the iommufd module is loaded. */
6
+ iommufdDevice: string;
7
+ /** Loads a kernel module (`modprobe`). */
8
+ loadModule: (name: string) => Promise<void>;
9
+ /** Writes `value` to a sysfs file, failing when the write does not finish in time. */
10
+ writeSysfs: (file: string, value: string) => Promise<void>;
11
+ /** The processes holding an NVIDIA GPU's device open, as `<pid> (<command>)`. */
12
+ findHolders: (bdf: string) => Promise<string[]>;
13
+ /** Asks the NVIDIA persistence daemon to let go of a GPU; best effort. */
14
+ releasePersistence: (bdf: string) => Promise<void>;
15
+ }
16
+ /** Binds GPUs to vfio-pci; the hypervisor's default. */
17
+ export type VfioBinder = (gpus: string[]) => Promise<void>;
18
+ /**
19
+ * Makes each GPU passable to a VM: every function of its PCI slot (the GPU and its HDMI audio)
20
+ * moved to vfio-pci, the modules QEMU needs loaded. A GPU already there is left as is. Throws,
21
+ * naming the device, when the IOMMU is off, when the GPU's IOMMU group holds a device of another
22
+ * slot on a host driver, or when a process still uses the GPU; nothing but the GPU's own
23
+ * functions is ever unbound. The binding outlives the VM: the GPU stays on vfio-pci.
24
+ */
25
+ export declare function bindGpusToVfio(gpus: string[], host?: VfioHost): Promise<void>;
26
+ /** The real host: sysfs, modprobe, procfs and nvidia-smi. */
27
+ export declare function defaultVfioHost(): VfioHost;
@@ -0,0 +1,163 @@
1
+ import { execFile } from 'child_process';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { IOMMUFD_DEVICE, SYSFS_PCI_ROOT, VFIO_DRIVER } from './hostDevices.js';
5
+ import { findNvidiaHolders, releaseNvidiaPersistence } from './nvidiaHolders.js';
6
+ import { isInSlot, pciSlot, readPciDriver } from './pciSysfs.js';
7
+ import { runToCompletion } from './processes.js';
8
+ import { describeError, pathExists } from './util.js';
9
+ /** The driver whose GPUs are checked for users before they are taken. */
10
+ const NVIDIA_DRIVER = 'nvidia';
11
+ /** PCI class prefix of a PCI bridge, which VFIO lets share a group with a passed device. */
12
+ const BRIDGE_CLASS_PREFIX = '0x0604';
13
+ /** How long a sysfs write may take: a driver's unbind blocks while its device is held. */
14
+ const SYSFS_WRITE_TIMEOUT_MS = 30_000;
15
+ /**
16
+ * Makes each GPU passable to a VM: every function of its PCI slot (the GPU and its HDMI audio)
17
+ * moved to vfio-pci, the modules QEMU needs loaded. A GPU already there is left as is. Throws,
18
+ * naming the device, when the IOMMU is off, when the GPU's IOMMU group holds a device of another
19
+ * slot on a host driver, or when a process still uses the GPU; nothing but the GPU's own
20
+ * functions is ever unbound. The binding outlives the VM: the GPU stays on vfio-pci.
21
+ */
22
+ export async function bindGpusToVfio(gpus, host = defaultVfioHost()) {
23
+ for (const bdf of gpus) {
24
+ await bindGpuToVfio(bdf, host);
25
+ }
26
+ if (gpus.length > 0)
27
+ await ensureIommufd(host);
28
+ }
29
+ /** The real host: sysfs, modprobe, procfs and nvidia-smi. */
30
+ export function defaultVfioHost() {
31
+ return {
32
+ pciRoot: SYSFS_PCI_ROOT,
33
+ iommufdDevice: IOMMUFD_DEVICE,
34
+ loadModule: (name) => runToCompletion('modprobe', [name]),
35
+ writeSysfs: writeSysfsWithTimeout,
36
+ findHolders: findNvidiaHolders,
37
+ releasePersistence: releaseNvidiaPersistence,
38
+ };
39
+ }
40
+ async function bindGpuToVfio(bdf, host) {
41
+ const functions = await functionsToBind(bdf, host.pciRoot);
42
+ if (functions.length === 0)
43
+ return;
44
+ await ensureVfioDriver(host);
45
+ await assertNotInUse(functions, host);
46
+ for (const device of functions) {
47
+ await bindDevice(device, host);
48
+ }
49
+ }
50
+ /**
51
+ * The devices of the GPU's IOMMU group not yet on vfio-pci, all of them functions of its own
52
+ * slot. VFIO passes a device only when every device in its group is on vfio-pci, has no driver,
53
+ * or is a bridge; a device of another slot on a host driver is the host's, and refused.
54
+ */
55
+ async function functionsToBind(bdf, pciRoot) {
56
+ const group = await readIommuGroup(bdf, pciRoot);
57
+ const slot = pciSlot(bdf);
58
+ const functions = [];
59
+ for (const device of group) {
60
+ const driver = readPciDriver(pciRoot, device);
61
+ if (driver === VFIO_DRIVER || (await isBridge(pciRoot, device)))
62
+ continue;
63
+ if (isInSlot(device, slot)) {
64
+ functions.push(device);
65
+ }
66
+ else if (driver !== undefined) {
67
+ throw new Error(`GPU ${bdf} shares its IOMMU group with ${device} (driver ${driver}), which a VM cannot ` +
68
+ 'take from the host: pass another GPU with --gpu');
69
+ }
70
+ }
71
+ return functions.sort();
72
+ }
73
+ async function readIommuGroup(bdf, pciRoot) {
74
+ try {
75
+ return await fs.readdir(path.join(pciRoot, 'devices', bdf, 'iommu_group', 'devices'));
76
+ }
77
+ catch {
78
+ throw new Error(`GPU ${bdf} has no IOMMU group: turn the IOMMU on (intel_iommu=on or amd_iommu=on ` +
79
+ 'on the kernel command line) and reboot');
80
+ }
81
+ }
82
+ /** Loads vfio-pci when its driver is not there yet. */
83
+ async function ensureVfioDriver(host) {
84
+ if (await pathExists(path.join(host.pciRoot, 'drivers', VFIO_DRIVER)))
85
+ return;
86
+ await loadModule(host, 'vfio-pci');
87
+ }
88
+ /** Loads iommufd when its device is not there yet: QEMU's passthrough opens it. */
89
+ async function ensureIommufd(host) {
90
+ if (await pathExists(host.iommufdDevice))
91
+ return;
92
+ await loadModule(host, 'iommufd');
93
+ }
94
+ async function loadModule(host, name) {
95
+ try {
96
+ await host.loadModule(name);
97
+ }
98
+ catch (error) {
99
+ throw new Error(`Failed to load the ${name} kernel module: ${describeError(error).message}`);
100
+ }
101
+ }
102
+ /**
103
+ * Refuses a GPU a process still uses (a display server, a container, a CUDA program): taking
104
+ * it from the nvidia driver would block until they let go. The persistence daemon, which holds
105
+ * every GPU, is asked to let go of it first.
106
+ */
107
+ async function assertNotInUse(functions, host) {
108
+ for (const device of functions) {
109
+ if (readPciDriver(host.pciRoot, device) !== NVIDIA_DRIVER)
110
+ continue;
111
+ await host.releasePersistence(device);
112
+ const holders = await host.findHolders(device);
113
+ if (holders.length > 0) {
114
+ throw new Error(`GPU ${device} is in use by ${holders.join(', ')}: stop them, or pass another GPU ` +
115
+ 'with --gpu');
116
+ }
117
+ }
118
+ }
119
+ /**
120
+ * Moves one device to vfio-pci: the override makes vfio-pci the only driver that may take it
121
+ * (now and at any later probe), the unbind frees it from its driver, the probe binds it.
122
+ */
123
+ async function bindDevice(device, host) {
124
+ const deviceDir = path.join(host.pciRoot, 'devices', device);
125
+ await host.writeSysfs(path.join(deviceDir, 'driver_override'), VFIO_DRIVER);
126
+ if (readPciDriver(host.pciRoot, device) !== undefined) {
127
+ await host.writeSysfs(path.join(deviceDir, 'driver', 'unbind'), device);
128
+ }
129
+ await host.writeSysfs(path.join(host.pciRoot, 'drivers_probe'), device);
130
+ const driver = readPciDriver(host.pciRoot, device);
131
+ if (driver !== VFIO_DRIVER) {
132
+ throw new Error(`Failed to bind ${device} to vfio-pci: its driver is ${driver ?? 'none'}`);
133
+ }
134
+ }
135
+ async function isBridge(pciRoot, device) {
136
+ try {
137
+ const cls = await fs.readFile(path.join(pciRoot, 'devices', device, 'class'), 'utf8');
138
+ return cls.trim().startsWith(BRIDGE_CLASS_PREFIX);
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /**
145
+ * A sysfs write in a child process, given up on after SYSFS_WRITE_TIMEOUT_MS: a driver's
146
+ * unbind can block for as long as its device is held, which must not hang the node.
147
+ */
148
+ function writeSysfsWithTimeout(file, value) {
149
+ return new Promise((resolve, reject) => {
150
+ const timer = setTimeout(() => {
151
+ const seconds = SYSFS_WRITE_TIMEOUT_MS / 1000;
152
+ reject(new Error(`Writing ${value} to ${file} did not finish in ${seconds}s: is it held?`));
153
+ }, SYSFS_WRITE_TIMEOUT_MS);
154
+ const child = execFile('sh', ['-c', 'printf "%s" "$1" > "$2"', 'sh', value, file], (error) => {
155
+ clearTimeout(timer);
156
+ if (error)
157
+ reject(new Error(`Failed to write ${value} to ${file}: ${error.message}`));
158
+ else
159
+ resolve();
160
+ });
161
+ child.unref();
162
+ });
163
+ }
@@ -0,0 +1,20 @@
1
+ import { type DownloadLike, type FetchChecksumLike } from './imageDownload.js';
2
+ export interface VmImageResolverOptions {
3
+ /** Where downloaded images are cached. */
4
+ cacheDir: string;
5
+ /** URL downloader; injectable so the resolver is testable without the network. */
6
+ download?: DownloadLike;
7
+ /**
8
+ * Fetch the published sha256 hex for an https image (the sibling
9
+ * `<url>.sha256` publish.sh writes), or undefined when none is published.
10
+ * Injectable so the resolver is testable without the network.
11
+ */
12
+ fetchChecksum?: FetchChecksumLike;
13
+ }
14
+ /**
15
+ * Resolve a VM `image` reference to a local disk-image path: a local path is
16
+ * passed straight through (for dev); an `http(s)://` URL is downloaded,
17
+ * verified against its published sha256 when there is one, and cached in
18
+ * `cacheDir`.
19
+ */
20
+ export declare function createVmImageResolver(opts: VmImageResolverOptions): (image: string) => Promise<string>;
@@ -0,0 +1,62 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { cachedImagePath, lockVmImage } from './imageCache.js';
4
+ import { cachedDigest, downloadToFile, downloadVerified, fetchPublishedSha256, } from './imageDownload.js';
5
+ import { pathExists } from './util.js';
6
+ /**
7
+ * Resolve a VM `image` reference to a local disk-image path: a local path is
8
+ * passed straight through (for dev); an `http(s)://` URL is downloaded,
9
+ * verified against its published sha256 when there is one, and cached in
10
+ * `cacheDir`.
11
+ */
12
+ export function createVmImageResolver(opts) {
13
+ const { cacheDir, download = downloadToFile, fetchChecksum = fetchPublishedSha256 } = opts;
14
+ return async (image) => {
15
+ if (isLocalPath(image))
16
+ return image;
17
+ if (!/^https?:\/\//i.test(image)) {
18
+ throw new Error(`unsupported VM image '${image}': expected a local path or an https URL`);
19
+ }
20
+ return resolveUrl(image, cachedImagePath(cacheDir, image), { download, fetchChecksum });
21
+ };
22
+ }
23
+ /**
24
+ * The cached copy of an image URL, downloaded when missing or stale. Node
25
+ * processes on a host share the cache: one downloads under the image's lock
26
+ * while the others wait, then they take its verified copy instead of racing
27
+ * it for the same temp file.
28
+ */
29
+ async function resolveUrl(url, imagePath, sources) {
30
+ // The published checksum is the source of truth for freshness: fetched up
31
+ // front so a cache hit is validated against the cached bytes, which is what
32
+ // detects a same-URL re-publish.
33
+ const expected = await sources.fetchChecksum(url);
34
+ if (await isCacheFresh(imagePath, expected))
35
+ return imagePath;
36
+ await fs.mkdir(path.dirname(imagePath), { recursive: true });
37
+ const release = await lockVmImage(imagePath);
38
+ try {
39
+ if (await isCacheFresh(imagePath, expected))
40
+ return imagePath;
41
+ await downloadVerified(sources.download, url, imagePath, expected);
42
+ return imagePath;
43
+ }
44
+ finally {
45
+ await release();
46
+ }
47
+ }
48
+ /**
49
+ * Is the cached image there and, when a checksum is published, the published
50
+ * bytes? With no published checksum a stale cache cannot be told from a fresh
51
+ * one, so presence is enough.
52
+ */
53
+ async function isCacheFresh(imagePath, expected) {
54
+ if (!(await pathExists(imagePath)))
55
+ return false;
56
+ if (!expected)
57
+ return true;
58
+ return (await cachedDigest(imagePath)) === expected;
59
+ }
60
+ function isLocalPath(image) {
61
+ return image.startsWith('/') || image.startsWith('./') || image.startsWith('../');
62
+ }
@@ -0,0 +1,20 @@
1
+ import type { ChildProcess } from 'child_process';
2
+ import { type SpawnLike } from './processes.js';
3
+ /**
4
+ * The host vsock port a VM's guest bridges its `host.sock` to is this plus the
5
+ * VM's guest CID, so co-tenant VMs (distinct CIDs) never share a listener.
6
+ */
7
+ export declare const HOST_VSOCK_PORT_BASE = 9500;
8
+ /** The host vsock port the guest with this CID connects out to. */
9
+ export declare function hostVsockPort(cid: number): number;
10
+ /**
11
+ * What the bridge for `hostPort` has in its command line, so a live bridge is
12
+ * told from a recycled pid.
13
+ */
14
+ export declare function bridgeCommandMarker(hostPort: number): string;
15
+ /**
16
+ * Spawn the host `socat` the guest's `host.sock` connections arrive through,
17
+ * detached, its output to `bridgeLog`. socat binds its VSOCK listener at once;
18
+ * the UNIX-CONNECT happens per connection, so this never blocks a boot.
19
+ */
20
+ export declare function spawnBridge(spawn: SpawnLike, bridgeLog: string, hostPort: number, hostSocket: string): ChildProcess;
@@ -0,0 +1,27 @@
1
+ import { SOCAT_BINARY } from './hostTools.js';
2
+ import { spawnDetached } from './processes.js';
3
+ /**
4
+ * The host vsock port a VM's guest bridges its `host.sock` to is this plus the
5
+ * VM's guest CID, so co-tenant VMs (distinct CIDs) never share a listener.
6
+ */
7
+ export const HOST_VSOCK_PORT_BASE = 9500;
8
+ /** The host vsock port the guest with this CID connects out to. */
9
+ export function hostVsockPort(cid) {
10
+ return HOST_VSOCK_PORT_BASE + cid;
11
+ }
12
+ /**
13
+ * What the bridge for `hostPort` has in its command line, so a live bridge is
14
+ * told from a recycled pid.
15
+ */
16
+ export function bridgeCommandMarker(hostPort) {
17
+ return `VSOCK-LISTEN:${hostPort},`;
18
+ }
19
+ /**
20
+ * Spawn the host `socat` the guest's `host.sock` connections arrive through,
21
+ * detached, its output to `bridgeLog`. socat binds its VSOCK listener at once;
22
+ * the UNIX-CONNECT happens per connection, so this never blocks a boot.
23
+ */
24
+ export function spawnBridge(spawn, bridgeLog, hostPort, hostSocket) {
25
+ const args = [`VSOCK-LISTEN:${hostPort},reuseaddr,fork`, `UNIX-CONNECT:${hostSocket}`];
26
+ return spawnDetached(spawn, SOCAT_BINARY, args, bridgeLog);
27
+ }
@@ -0,0 +1,49 @@
1
+ /** Work dirs are `<workRoot>/nosana-vm-<random>`. */
2
+ export declare const WORK_DIR_PREFIX = "nosana-vm-";
3
+ /** The qcow2 overlay in a VM's work dir, over the (immutable) base image. */
4
+ export declare const OVERLAY_FILE = "overlay.qcow2";
5
+ /** The VM's serial console, as VmStateManager keeps it in the work dir. */
6
+ export declare const VM_CONSOLE_LOG = "console.log";
7
+ /** The files in one VM's work dir. */
8
+ export interface WorkDirPaths {
9
+ /** The work dir itself. */
10
+ workdir: string;
11
+ /** The qcow2 overlay the VM boots from. */
12
+ overlay: string;
13
+ /** The cloud-init NoCloud seed ISO, packed from `userData` and `metaData`. */
14
+ seedIso: string;
15
+ /** cloud-init user-data: the files written into the guest. */
16
+ userData: string;
17
+ /** cloud-init meta-data: the instance id. */
18
+ metaData: string;
19
+ /** QEMU's QMP control socket. */
20
+ qmpSocket: string;
21
+ /** QEMU's serial console socket. */
22
+ serialSocket: string;
23
+ /** QEMU's own output. */
24
+ qemuLog: string;
25
+ /** The vsock bridge's output. */
26
+ bridgeLog: string;
27
+ /** The guest's serial console, streamed by VmStateManager. */
28
+ consoleLog: string;
29
+ }
30
+ /** Lists every running process's command line; undefined when they cannot be listed. */
31
+ export type CommandLinesLike = () => Promise<string[] | undefined>;
32
+ /** The paths of the files in a VM work dir. */
33
+ export declare function workDirPaths(workdir: string): WorkDirPaths;
34
+ /** Make a fresh VM work dir under `workRoot`. */
35
+ export declare function makeWorkDir(workRoot: string): Promise<WorkDirPaths>;
36
+ /**
37
+ * Remove a VM work dir. Refuses anything not named like one, so a bad record
38
+ * can never point it elsewhere.
39
+ */
40
+ export declare function removeWorkDir(workdir: string): Promise<void>;
41
+ /**
42
+ * Remove every VM work dir under `workRoot` that a node booted but never
43
+ * recorded: not in `keep`, with an overlay (the image cache has none), last
44
+ * changed at least {@link ORPHAN_WORKDIR_MIN_AGE_MS} ago, and named by no
45
+ * running process (`<dir>/` in its command line). The processes are listed
46
+ * once, and only when there is something to remove; when they cannot be
47
+ * listed, nothing is removed. A dir that will not go is logged and left.
48
+ */
49
+ export declare function sweepWorkDirs(workRoot: string, keep: string[], listCommandLines: CommandLinesLike): Promise<void>;