@nosana/node 1.1.84-rc → 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,419 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { configs } from '../../configs/configs.js';
4
+ import { applyLoggingProxyToClass } from '../../../../packages/common/src/index.js';
5
+ import { parseLogFrames, } from '../../../../packages/container-orchestrator/src/index.js';
6
+ import { JOB_LABEL, NODE_LABEL, SERVICE_LABEL, } from '../../../../packages/container-orchestrator/src/index.js';
7
+ import { isKnownVersion, JOB_RUNTIME_CONTAINER_PREFIX, JOB_RUNTIME_DATA_DIR, JOB_RUNTIME_FILES, JOB_RUNTIME_GID, JOB_RUNTIME_HOST_DIR, JOB_RUNTIME_PORT, JOB_RUNTIME_UID, readJson, RESOURCE_CHANGES_VERSION, } from '../../../../packages/job-runtime/src/host/index.js';
8
+ import { getKit, nodeAddress } from '../../sdk/index.js';
9
+ import { pkg } from '../../../static/index.js';
10
+ import { buildJobRuntimeEnv } from './buildJobRuntimeEnv.js';
11
+ /** How long a job runtime's address is used before it is looked up again. */
12
+ const JOB_RUNTIME_URL_TTL_MS = 5_000;
13
+ /** How long to wait before asking a container runtime that failed again. */
14
+ const JOB_RUNTIME_RETRY_MS = 5_000;
15
+ /**
16
+ * How many times a job's sidecar is looked for before the runtime is given
17
+ * up on: about two minutes, long enough for a daemon coming back after a
18
+ * host restart.
19
+ */
20
+ const JOB_RUNTIME_LOOKUP_ATTEMPTS = 24;
21
+ /**
22
+ * Whether a container runtime error says there is no such container: a 404,
23
+ * from Docker or from Podman's compatible API alike.
24
+ */
25
+ function isNoSuchContainer(error) {
26
+ return error?.statusCode === 404;
27
+ }
28
+ function sleep(ms) {
29
+ return new Promise((resolve) => setTimeout(resolve, ms));
30
+ }
31
+ /**
32
+ * Each job's runtime as a sidecar container beside the node, which runs the
33
+ * job's own containers.
34
+ */
35
+ export class ContainerJobRuntime {
36
+ constructor(containerOrchestration, repository,
37
+ /** The node's image and resource cache, which a job's sidecar starts from. */
38
+ resourceManager) {
39
+ this.containerOrchestration = containerOrchestration;
40
+ this.repository = repository;
41
+ this.resourceManager = resourceManager;
42
+ this.jobRuntimeVolumesSwept = false;
43
+ this.jobRuntimeUrls = new Map();
44
+ applyLoggingProxyToClass(this);
45
+ }
46
+ /** The sidecar shares the node's cache: it starts from the node's records. */
47
+ cacheSnapshot() {
48
+ return this.resourceManager.jobCacheSnapshot();
49
+ }
50
+ /**
51
+ * Writes what the job's sidecar changed in the cache records back to the
52
+ * node's. Whole or not at all: changes of a version the node does not know
53
+ * are left out of the records rather than half applied.
54
+ */
55
+ writeBackCache(hostDir, jobAddress) {
56
+ const changes = readJson(path.join(hostDir, JOB_RUNTIME_FILES.resources));
57
+ if (!changes)
58
+ return;
59
+ if (!isKnownVersion(changes.version, RESOURCE_CHANGES_VERSION)) {
60
+ console.error(`Ignoring the cache changes of job ${jobAddress}: version ` +
61
+ `${String(changes.version)}, this node reads up to ${RESOURCE_CHANGES_VERSION}`);
62
+ return;
63
+ }
64
+ this.resourceManager.applyJobCacheChanges(changes);
65
+ }
66
+ /**
67
+ * Starts the job's runtime sidecar (packages/job-runtime) with the job's
68
+ * address and the host it runs on, nothing about the job itself: an
69
+ * onchain job it resolves onchain, runs, publishes its job API for at
70
+ * https://<jobId>.<frp server> and pins the result of; an inline run's
71
+ * definition is in the seed in `hostDir`, the job's directory, where the
72
+ * node also serves it its socket (JobRuntimeHost).
73
+ *
74
+ * A sidecar a previous node left behind is replaced; the new one resumes
75
+ * the job from the data volume they share. The sidecar has no restart
76
+ * policy: the node starts it again if it exits before its result (see
77
+ * JobRuntimeSession).
78
+ */
79
+ async start(jobAddress, hostDir, kind,
80
+ /** What its console carries; `entries` for `nosana node run` to render. */
81
+ consoleOutput = 'text') {
82
+ const { jobRuntime, frp, network } = configs();
83
+ const name = JOB_RUNTIME_CONTAINER_PREFIX + jobAddress;
84
+ // A sidecar replaced comes back at another address.
85
+ this.jobRuntimeUrls.delete(jobAddress);
86
+ if (!this.jobRuntimeVolumesSwept) {
87
+ await this.removeOrphanedJobRuntimeVolumes(jobAddress);
88
+ this.jobRuntimeVolumesSwept = true;
89
+ }
90
+ await Promise.all([
91
+ // The sidecar's network, which a node runs on but `nosana node run`
92
+ // may be the first to need.
93
+ this.containerOrchestration.createNetwork('NOSANA_GATEWAY'),
94
+ this.containerOrchestration.stopAndDeleteContainer(name),
95
+ // Cached by prepare before the job loop, so normally no pull.
96
+ this.containerOrchestration.pullImage(jobRuntime.containerImage),
97
+ ]);
98
+ // A use, so the cache's resync keeps the image while jobs run on it.
99
+ await this.resourceManager.images.setImage(jobRuntime.containerImage);
100
+ // The same socket path as the SSH sidecar (see withSshSidecar).
101
+ const socketDest = this.containerOrchestration.name === 'podman'
102
+ ? '/run/podman/podman.sock'
103
+ : '/var/run/docker.sock';
104
+ const rpc = getKit().config.solana.rpcEndpoint;
105
+ const node = nodeAddress();
106
+ const { teeRuntime, gpu } = this.containerOrchestration;
107
+ const labels = {
108
+ [JOB_LABEL]: jobAddress,
109
+ [NODE_LABEL]: node,
110
+ [SERVICE_LABEL]: 'job-runtime',
111
+ };
112
+ const socketGroup = await this.jobRuntimeSocketGroup();
113
+ await this.ownJobRuntimeVolume(name, jobRuntime.containerImage, labels);
114
+ await this.containerOrchestration.runFlowContainer(jobRuntime.containerImage, {
115
+ name,
116
+ // The image's unprivileged user, in the runtime socket's group so it
117
+ // can use the socket; root only where the socket cannot be shared.
118
+ ...(socketGroup === undefined
119
+ ? { user: '0:0' }
120
+ : { group_add: [String(socketGroup)] }),
121
+ // GPU stats need the device; a node without GPUs (which may have no
122
+ // GPU driver either) gives its sidecar none.
123
+ ...(this.repository.getNodeInfo().gpus.devices.length > 0 ? { gpu: true } : {}),
124
+ networks: { NOSANA_GATEWAY: {} },
125
+ aliases: [name],
126
+ env: {
127
+ ...buildJobRuntimeEnv({
128
+ jobAddress,
129
+ kind,
130
+ consoleOutput,
131
+ nodeAddress: node,
132
+ network,
133
+ rpc,
134
+ frp,
135
+ resourceManagerImage: this.resourceManager.volumes.resourceManagerImage,
136
+ nodeVersion: pkg.version,
137
+ }),
138
+ CONTAINER_RUNTIME: this.containerOrchestration.name,
139
+ DOCKER_SOCKET: socketDest,
140
+ GPU: gpu,
141
+ ...(teeRuntime ? { TEE_RUNTIME: teeRuntime } : {}),
142
+ },
143
+ volumes: [
144
+ {
145
+ type: 'bind',
146
+ name: await this.resolveHostSocketPath(),
147
+ dest: socketDest,
148
+ readonly: true,
149
+ },
150
+ { name, dest: JOB_RUNTIME_DATA_DIR },
151
+ {
152
+ type: 'bind',
153
+ name: await this.containerOrchestration.resolveHostPath(hostDir),
154
+ dest: JOB_RUNTIME_HOST_DIR,
155
+ },
156
+ ],
157
+ labels,
158
+ // The socket makes a compromised sidecar root on the host whatever
159
+ // runs inside it, so the container itself gets nothing it does not
160
+ // need: no capabilities (the API, nvidia-smi and /proc need none), no
161
+ // privilege escalation, and a pid budget that fits node plus its
162
+ // nvidia-smi spawns.
163
+ security: {
164
+ capDrop: ['ALL'],
165
+ noNewPrivileges: true,
166
+ pidsLimit: 256,
167
+ },
168
+ });
169
+ }
170
+ /**
171
+ * The group a sidecar needs to use the runtime socket: the socket's own,
172
+ * which is opened to its group where it is root's alone (podman serves its
173
+ * socket that way; docker's is its `docker` group's already). The socket
174
+ * is the one the node itself uses, bound into its container read-write,
175
+ * so the change reaches the socket the sidecar gets bound. Undefined when
176
+ * the socket cannot be read or changed (a TCP endpoint, a dev socket the
177
+ * user does not own), in which case the sidecar runs as root, as it did
178
+ * before, rather than not at all.
179
+ */
180
+ async jobRuntimeSocketGroup() {
181
+ const { socketPath } = this.containerOrchestration;
182
+ try {
183
+ const { gid, mode } = await fs.stat(socketPath);
184
+ if ((mode & 0o060) !== 0o060) {
185
+ await fs.chmod(socketPath, (mode & 0o777) | 0o060);
186
+ }
187
+ return gid;
188
+ }
189
+ catch (error) {
190
+ console.warn(`The runtime socket at ${socketPath} cannot be shared with the job runtime (${error}); the job runtime runs as root.`);
191
+ return undefined;
192
+ }
193
+ }
194
+ /**
195
+ * Makes the job's data volume the sidecar user's. A volume created as the
196
+ * sidecar starts takes the ownership of the image's mount point, which is
197
+ * the user's; one that is already there (a sidecar a previous node left,
198
+ * one that may have run as root) is chowned first, by a one-shot container
199
+ * on the same image, so that the sidecar can write its records.
200
+ */
201
+ async ownJobRuntimeVolume(volume, image, labels) {
202
+ if (!(await this.containerOrchestration.hasVolume(volume)))
203
+ return;
204
+ const name = `${volume}-chown`;
205
+ await this.containerOrchestration.stopAndDeleteContainer(name);
206
+ const container = await this.containerOrchestration.runFlowContainer(image, {
207
+ name,
208
+ user: '0:0',
209
+ entrypoint: [
210
+ 'chown',
211
+ '-R',
212
+ `${JOB_RUNTIME_UID}:${JOB_RUNTIME_GID}`,
213
+ JOB_RUNTIME_DATA_DIR,
214
+ ],
215
+ volumes: [{ name: volume, dest: JOB_RUNTIME_DATA_DIR }],
216
+ labels: { ...labels, [SERVICE_LABEL]: 'job-runtime-chown' },
217
+ });
218
+ const { StatusCode } = await container.wait({ condition: 'not-running' });
219
+ await this.containerOrchestration.stopAndDeleteContainer(name);
220
+ if (StatusCode !== 0) {
221
+ throw new Error(`The data volume ${volume} could not be made the job runtime's (chown exited ${StatusCode})`);
222
+ }
223
+ }
224
+ /**
225
+ * Whether the job has a sidecar, running or exited: one that outlived the
226
+ * node's last process, to take over. Only the runtime saying there is no
227
+ * such container answers false; a runtime that fails to answer (its daemon
228
+ * still starting after a host restart, say) is asked again, for about two
229
+ * minutes, before its last error is thrown.
230
+ */
231
+ async has(jobAddress) {
232
+ const name = JOB_RUNTIME_CONTAINER_PREFIX + jobAddress;
233
+ for (let attempt = 1;; attempt++) {
234
+ try {
235
+ return await this.containerOrchestration.doesContainerExist(name);
236
+ }
237
+ catch (error) {
238
+ if (attempt >= JOB_RUNTIME_LOOKUP_ATTEMPTS)
239
+ throw error;
240
+ if (attempt === 1) {
241
+ console.error(`The container runtime failed to say whether job ${jobAddress} has a runtime, asking again: ${error}`);
242
+ }
243
+ await sleep(JOB_RUNTIME_RETRY_MS);
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * Whether the job's sidecar runs on an image other than the configured one
249
+ * as the node has it locally (pulled by prepare before the job
250
+ * loop): a node updated mid-job meets the sidecar of the version before it.
251
+ * An exited sidecar is not outdated, nor is one whose image or the
252
+ * configured one cannot be read: an image the node does not have is no
253
+ * reason to replace a sidecar that runs.
254
+ */
255
+ async isOutdated(jobAddress) {
256
+ try {
257
+ const [sidecar, image] = await Promise.all([
258
+ this.containerOrchestration
259
+ .getContainer(JOB_RUNTIME_CONTAINER_PREFIX + jobAddress)
260
+ .inspect(),
261
+ this.containerOrchestration
262
+ .getImage(configs().jobRuntime.containerImage)
263
+ .then((image) => image.inspect()),
264
+ ]);
265
+ return sidecar.State.Running && sidecar.Image !== image.Id;
266
+ }
267
+ catch {
268
+ return false;
269
+ }
270
+ }
271
+ /**
272
+ * Waits for the job's sidecar to exit, and answers its exit code;
273
+ * undefined once it is gone. A wait the runtime drops (its daemon
274
+ * restarting) is waited again. Only the runtime saying there is no such
275
+ * container means gone: one that fails to answer is asked again for as
276
+ * long as it takes, since answering gone would have the node remove a
277
+ * sidecar that may still run. The job's expiry is enforced apart from
278
+ * this, and removing the sidecar ends the wait.
279
+ */
280
+ async wait(jobAddress) {
281
+ const container = this.containerOrchestration.getContainer(JOB_RUNTIME_CONTAINER_PREFIX + jobAddress);
282
+ let failing = false;
283
+ for (;;) {
284
+ let info;
285
+ try {
286
+ info = await container.inspect();
287
+ }
288
+ catch (error) {
289
+ if (isNoSuchContainer(error))
290
+ return undefined;
291
+ if (!failing) {
292
+ console.error(`The container runtime failed to inspect the runtime of job ${jobAddress}, asking again: ${error}`);
293
+ }
294
+ failing = true;
295
+ await sleep(JOB_RUNTIME_RETRY_MS);
296
+ continue;
297
+ }
298
+ failing = false;
299
+ if (!info.State.Running && !info.State.Restarting) {
300
+ return { exitCode: info.State.ExitCode };
301
+ }
302
+ await container
303
+ .wait({ condition: 'not-running' })
304
+ .catch(() => new Promise((resolve) => setTimeout(resolve, 1_000)));
305
+ }
306
+ }
307
+ /** Starts the job's exited sidecar again, as it was. */
308
+ async restart(jobAddress) {
309
+ await this.containerOrchestration
310
+ .getContainer(JOB_RUNTIME_CONTAINER_PREFIX + jobAddress)
311
+ .start();
312
+ }
313
+ /**
314
+ * Removes what job sidecars of this node left behind, the sidecars
315
+ * themselves included, for every job but `liveJob`, which this node still
316
+ * runs. A sidecar stamps its job and this node on everything it starts, so
317
+ * this finds what a sidecar that died never removed, and no other node's.
318
+ */
319
+ async sweep(liveJob) {
320
+ const node = nodeAddress();
321
+ const containers = await this.containerOrchestration.listContainersByLabels([`${NODE_LABEL}=${node}`], { all: true });
322
+ await Promise.allSettled(containers
323
+ .filter(({ Labels }) => Labels?.[JOB_LABEL] !== liveJob)
324
+ .map(({ Id }) => this.containerOrchestration.stopAndDeleteContainer(Id)));
325
+ }
326
+ /**
327
+ * Where the job's sidecar serves its job API: its address on the gateway
328
+ * network, which a node on the network and one on the host both reach.
329
+ * Undefined while it is not running. An address is looked up again after
330
+ * a few seconds, since a restarted sidecar may come back with another; a
331
+ * miss is not kept, so a sidecar that is starting is found once it is up.
332
+ */
333
+ async url(jobAddress) {
334
+ const cached = this.jobRuntimeUrls.get(jobAddress);
335
+ if (cached && Date.now() - cached.at < JOB_RUNTIME_URL_TTL_MS)
336
+ return cached.url;
337
+ const info = await this.containerOrchestration
338
+ .getContainer(JOB_RUNTIME_CONTAINER_PREFIX + jobAddress)
339
+ .inspect()
340
+ .catch(() => undefined);
341
+ const ip = info?.State?.Running
342
+ ? info.NetworkSettings?.Networks?.NOSANA_GATEWAY?.IPAddress
343
+ : undefined;
344
+ if (!ip)
345
+ return undefined;
346
+ const url = `http://${ip}:${JOB_RUNTIME_PORT}`;
347
+ this.jobRuntimeUrls.set(jobAddress, { url, at: Date.now() });
348
+ return url;
349
+ }
350
+ /**
351
+ * Follows the sidecar's console as it runs (its phases, then the summary of
352
+ * the operations): its log from the start, followed. Undefined when the
353
+ * runtime cannot give it.
354
+ */
355
+ async output(jobAddress, read) {
356
+ try {
357
+ const output = (await this.containerOrchestration
358
+ .getContainer(JOB_RUNTIME_CONTAINER_PREFIX + jobAddress)
359
+ .logs({ follow: true, stdout: true, stderr: true }));
360
+ let rest = Buffer.alloc(0);
361
+ output.on('data', (chunk) => {
362
+ const parsed = parseLogFrames(Buffer.concat([rest, chunk]));
363
+ rest = parsed.rest;
364
+ for (const { type, log } of parsed.logs) {
365
+ read(type === 'stderr' ? 'stderr' : 'stdout', log ?? '');
366
+ }
367
+ });
368
+ output.on('error', () => undefined);
369
+ return () => output.destroy();
370
+ }
371
+ catch {
372
+ return undefined;
373
+ }
374
+ }
375
+ /**
376
+ * Pulls the sidecar image `.env` names and records it in the image cache,
377
+ * where the resync between jobs ages out what goes unused, so a bump's
378
+ * predecessor goes the way of any other image.
379
+ */
380
+ async prepare() {
381
+ const image = configs().jobRuntime.containerImage;
382
+ await this.containerOrchestration.pullImage(image);
383
+ await this.resourceManager.images.setImage(image);
384
+ }
385
+ /**
386
+ * Removes the job's sidecar, then whatever else of the job is left: its
387
+ * frpc, and any operation container a sidecar that died never removed.
388
+ * Then the sidecar's data volume. Throws on failure; what will not go is
389
+ * swept again by the next resync (sweep).
390
+ */
391
+ async remove(jobAddress) {
392
+ this.jobRuntimeUrls.delete(jobAddress);
393
+ const name = JOB_RUNTIME_CONTAINER_PREFIX + jobAddress;
394
+ await this.containerOrchestration.stopAndDeleteContainer(name);
395
+ const leftovers = await this.containerOrchestration.getContainersByLabels([`${JOB_LABEL}=${jobAddress}`], { all: true });
396
+ await Promise.all(leftovers.map((container) => this.containerOrchestration.stopAndDeleteContainer(container.id)));
397
+ await this.containerOrchestration.deleteVolume(name);
398
+ }
399
+ /**
400
+ * Removes job-runtime-<jobId> volumes left by a job whose stop never ran (the
401
+ * node died mid-job). The volume resync does not know them, and a reaped
402
+ * sidecar container leaves its named volume behind. Runs once, on the first
403
+ * sidecar start after boot. The job starting keeps its volume, to resume
404
+ * from, and a volume still in use fails to delete and is kept for the next
405
+ * boot.
406
+ */
407
+ async removeOrphanedJobRuntimeVolumes(jobAddress) {
408
+ const orphans = (await this.containerOrchestration.listVolumes())
409
+ .map(({ Name }) => Name)
410
+ .filter((name) => name?.startsWith(JOB_RUNTIME_CONTAINER_PREFIX) &&
411
+ name !== JOB_RUNTIME_CONTAINER_PREFIX + jobAddress);
412
+ // One in use or already gone fails to delete, and is left.
413
+ await Promise.allSettled(orphans.map((name) => this.containerOrchestration.deleteVolume(name)));
414
+ }
415
+ /** The runtime socket as a host path, which is what a bind source must be. */
416
+ resolveHostSocketPath() {
417
+ return (this.hostSocketPath ??= this.containerOrchestration.resolveHostPath(this.containerOrchestration.socketPath));
418
+ }
419
+ }
@@ -0,0 +1,74 @@
1
+ import type { JobRuntimeConsole, JobRuntimeKind } from '../../../../packages/job-runtime/src/host/index.js';
2
+ import type { ResourceCacheSnapshot } from '../../../../packages/job-runtime/src/resources/index.js';
3
+ /** How a job's runtime exited. */
4
+ export interface JobRuntimeExit {
5
+ /** Its exit code; 0 is a clean end. */
6
+ exitCode: number;
7
+ }
8
+ /**
9
+ * Where a job's runtime runs, as the node sees it: it starts the runtime on
10
+ * the job's directory, takes over the one a previous node process left,
11
+ * waits for it to exit and removes it with whatever is left of the job.
12
+ * JobRuntimeSession drives it; the node's composition roots (Node,
13
+ * `nosana node run`) choose it. ContainerJobRuntime runs the runtime as a
14
+ * sidecar container beside the node, VmJobRuntime in a VM.
15
+ */
16
+ export interface JobRuntimeEnvironment {
17
+ /**
18
+ * The cache records a job's runtime starts from: the node's, where the
19
+ * runtime shares its image and volume cache; none where it has its own.
20
+ */
21
+ cacheSnapshot(): ResourceCacheSnapshot;
22
+ /**
23
+ * Takes up what the job's runtime changed in the shared cache records
24
+ * (`resources.json` in `hostDir`, the job's directory), however the job
25
+ * ended; nothing where the runtime shares none.
26
+ */
27
+ writeBackCache(hostDir: string, jobAddress: string): void;
28
+ /**
29
+ * Readies what the next job's runtime starts from (the runtime image),
30
+ * before each job loop.
31
+ */
32
+ prepare(): Promise<void>;
33
+ /**
34
+ * Removes what earlier runtimes of this node left behind, for every job but
35
+ * `liveJob`, which this node still runs.
36
+ */
37
+ sweep(liveJob?: string): Promise<void>;
38
+ /**
39
+ * Starts the job's runtime on `hostDir`, the job's directory, replacing
40
+ * one there is; one started where one ran before takes the job up again.
41
+ */
42
+ start(jobAddress: string, hostDir: string, kind: JobRuntimeKind, consoleOutput?: JobRuntimeConsole): Promise<void>;
43
+ /** Whether the job has a runtime, running or exited, to take over. */
44
+ has(jobAddress: string): Promise<boolean>;
45
+ /**
46
+ * Whether the job's running runtime is older than the one the node starts,
47
+ * where a runtime can be replaced mid-job (a sidecar container); a VM runs
48
+ * out on what it booted.
49
+ */
50
+ isOutdated?(jobAddress: string): Promise<boolean>;
51
+ /**
52
+ * Waits for the job's runtime to exit: its exit code, undefined once gone.
53
+ * `result` resolves once the job's status carries its result, for a
54
+ * runtime that does not end by itself on it (a VM is powered down then).
55
+ */
56
+ wait(jobAddress: string, result: Promise<void>): Promise<JobRuntimeExit | undefined>;
57
+ /**
58
+ * Starts the job's exited runtime again, as it was, where a runtime that
59
+ * exits before its result is started again (a sidecar container); absent,
60
+ * the runtime's exit is the job's end (a VM: the workload cannot bring the
61
+ * VM down from its container).
62
+ */
63
+ restart?(jobAddress: string): Promise<void>;
64
+ /** Removes the job's runtime and whatever else of the job is left. */
65
+ remove(jobAddress: string): Promise<void>;
66
+ /** Where the job's runtime serves its job API; undefined while it is not running. */
67
+ url(jobAddress: string): Promise<string | undefined>;
68
+ /**
69
+ * Follows the console of the job's runtime from its start as it runs,
70
+ * handing what it writes to `read` (for `nosana node run`). Answers what
71
+ * stops following, or undefined when there is nothing to follow.
72
+ */
73
+ output(jobAddress: string, read: (stream: 'stdout' | 'stderr', text: string) => void): Promise<(() => void) | undefined>;
74
+ }
@@ -1,4 +1,4 @@
1
- import { type StopReason } from '../../../../packages/job-runtime/src/host/index.js';
1
+ import { type JobRuntimeStatus, type StopReason } from '../../../../packages/job-runtime/src/host/index.js';
2
2
  export interface JobRuntimeHostOptions {
3
3
  /** The socket the server listens on, in the directory the sidecar binds. */
4
4
  socketPath: string;
@@ -6,11 +6,15 @@ export interface JobRuntimeHostOptions {
6
6
  jobAddress: string;
7
7
  /** Signs an authorization header for the job address with the node wallet. */
8
8
  sign: (jobAddress: string) => Promise<string>;
9
+ /** Where the sidecar's status is kept, in the job's directory. */
10
+ statusFile: string;
11
+ /** Each status the sidecar sends, once it is kept. */
12
+ onStatus?: (status: JobRuntimeStatus) => void;
9
13
  }
10
14
  /**
11
15
  * The node's side of a job's runtime socket (see @nosana/job-runtime/host):
12
16
  * what the job's sidecar needs of the node live, for the one job it was made
13
- * for: the node's signature, and the job's stop.
17
+ * for: the node's signature, the job's stop, and keeping its status.
14
18
  */
15
19
  export declare class JobRuntimeHost {
16
20
  private readonly options;
@@ -3,9 +3,11 @@ import fs from 'fs/promises';
3
3
  import path from 'path';
4
4
  import express from 'express';
5
5
  import { describeError } from '../../../../packages/common/src/index.js';
6
- import { JOB_RUNTIME_HOST_PATHS as PATHS, } from '../../../../packages/job-runtime/src/host/index.js';
6
+ import { isReadableStatus, JOB_RUNTIME_HOST_PATHS as PATHS, writeJsonAtomic, } from '../../../../packages/job-runtime/src/host/index.js';
7
7
  /** The longest unix socket path every platform takes (macOS: 104 with the NUL). */
8
8
  const MAX_SOCKET_PATH_BYTES = 103;
9
+ /** The largest status taken: an inline run's last carries its whole flow state. */
10
+ const STATUS_BODY_LIMIT = '256mb';
9
11
  /** A handler whose rejection goes to the error handler. */
10
12
  function handle(fn) {
11
13
  return (req, res, next) => {
@@ -15,7 +17,7 @@ function handle(fn) {
15
17
  /**
16
18
  * The node's side of a job's runtime socket (see @nosana/job-runtime/host):
17
19
  * what the job's sidecar needs of the node live, for the one job it was made
18
- * for: the node's signature, and the job's stop.
20
+ * for: the node's signature, the job's stop, and keeping its status.
19
21
  */
20
22
  export class JobRuntimeHost {
21
23
  constructor(options) {
@@ -76,6 +78,15 @@ export class JobRuntimeHost {
76
78
  this.stopWaiters.add(res);
77
79
  res.once('close', () => this.stopWaiters.delete(res));
78
80
  });
81
+ app.put(PATHS.status, express.json({ limit: STATUS_BODY_LIMIT }), (req, res) => {
82
+ const status = req.body;
83
+ if (!isReadableStatus(status)) {
84
+ return res.status(400).json({ error: 'not a job runtime status' });
85
+ }
86
+ writeJsonAtomic(options.statusFile, status);
87
+ res.status(204).end();
88
+ options.onStatus?.(status);
89
+ });
79
90
  app.use((_req, res) => {
80
91
  res.status(404).json({ error: 'not found' });
81
92
  });
@@ -1,11 +1,11 @@
1
1
  import type { JobDefinition, NosanaClient } from '@nosana/kit';
2
2
  import { type JobRuntimeConsole, type JobRuntimeStatus, type StopReason } from '../../../../packages/job-runtime/src/host/index.js';
3
- import type { Provider } from '../../provider/Provider.js';
4
- import type { ResourceManager } from '../resource/resourceManager.js';
3
+ import type { JobRuntimeEnvironment } from './JobRuntimeEnvironment.js';
5
4
  export interface JobRuntimeSessionOptions {
6
5
  /** The node's client: it signs what the sidecar asks it to. */
7
6
  sdk: NosanaClient;
8
- provider: Provider;
7
+ /** Where the job's runtime runs. */
8
+ environment: JobRuntimeEnvironment;
9
9
  /** The node's data directory; the job's directory is made under it. */
10
10
  dataDir: string;
11
11
  jobAddress: string;
@@ -16,7 +16,7 @@ export interface JobRuntimeSessionOptions {
16
16
  project: string;
17
17
  /** An inline run's definition; absent for an onchain job. */
18
18
  inline?: JobDefinition;
19
- /** The sidecar's status as it changes, while it runs. */
19
+ /** The sidecar's status as it sends it, while the socket is served. */
20
20
  onStatus?: (status: JobRuntimeStatus) => void;
21
21
  /** What the sidecar's console carries (see JobRuntimeConsole). */
22
22
  console?: JobRuntimeConsole;
@@ -34,11 +34,13 @@ export declare class JobRuntimeSession {
34
34
  private readonly dir;
35
35
  private exited;
36
36
  private removing;
37
- private statusPoll;
37
+ /** Resolves once the sidecar's status carries the job's result. */
38
+ private readonly result;
38
39
  constructor(options: JobRuntimeSessionOptions);
39
40
  /**
40
- * The sidecar's latest status, undefined until it wrote one, or when what
41
- * it wrote is not one the node can read.
41
+ * The sidecar's latest status, as the socket kept it (or a sidecar of an
42
+ * earlier release wrote it); undefined until there is one, or when what is
43
+ * there is not one the node can read.
42
44
  */
43
45
  get status(): JobRuntimeStatus | undefined;
44
46
  /**
@@ -101,14 +103,15 @@ export declare class JobRuntimeSession {
101
103
  * What each job changed in the cache records is written back first, so the
102
104
  * volumes it made are known.
103
105
  */
104
- static removeLeftovers(dataDir: string, resourceManager: ResourceManager, liveJob?: string): Promise<void>;
106
+ static removeLeftovers(dataDir: string, environment: JobRuntimeEnvironment, liveJob?: string): Promise<void>;
105
107
  private follow;
106
108
  /**
107
109
  * Waits for the sidecar to exit with its result. One that exits without
108
110
  * it (a crash, the runtime restarting) is started again, and one that is
109
111
  * gone without it (removed from under the node) is started anew; either
110
112
  * takes the job up from its data volume. One that keeps going is given up
111
- * on. Only this session removing the sidecar makes it gone for good.
113
+ * on, and a runtime its environment does not restart (a VM) at once. Only
114
+ * this session removing the sidecar makes it gone for good.
112
115
  */
113
116
  private waitForExit;
114
117
  }