@virtbase/proxmox-api 3.0.0 → 5.0.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +21 -53
  2. package/LICENSE +22 -0
  3. package/README.md +81 -82
  4. package/dist/client.d.ts +13 -7
  5. package/dist/client.js +23 -23
  6. package/dist/errors.d.ts +364 -0
  7. package/dist/errors.js +372 -0
  8. package/dist/index.d.ts +5 -3
  9. package/dist/index.js +3 -18
  10. package/dist/model.d.ts +28875 -28491
  11. package/dist/model.js +4 -16
  12. package/dist/proxmox-engine.d.ts +273 -54
  13. package/dist/proxmox-engine.js +772 -248
  14. package/dist/proxy.d.ts +61 -19
  15. package/dist/proxy.js +118 -33
  16. package/dist/qm-monitor.d.ts +225 -25
  17. package/dist/qm-monitor.js +152 -52
  18. package/dist/schema-info.d.ts +12 -0
  19. package/dist/schema-info.js +13 -0
  20. package/dist/tasks.d.ts +129 -0
  21. package/dist/tasks.js +132 -0
  22. package/package.json +33 -34
  23. package/dist/client.d.ts.map +0 -1
  24. package/dist/client.js.map +0 -1
  25. package/dist/index.d.ts.map +0 -1
  26. package/dist/index.js.map +0 -1
  27. package/dist/model.d.ts.map +0 -1
  28. package/dist/model.js.map +0 -1
  29. package/dist/proxmox-engine.d.ts.map +0 -1
  30. package/dist/proxmox-engine.js.map +0 -1
  31. package/dist/proxy.d.ts.map +0 -1
  32. package/dist/proxy.js.map +0 -1
  33. package/dist/qm-monitor.d.ts.map +0 -1
  34. package/dist/qm-monitor.js.map +0 -1
  35. package/src/__tests__/helpers.ts +0 -39
  36. package/src/__tests__/proxmox-engine.test.ts +0 -393
  37. package/src/__tests__/proxy.test.ts +0 -190
  38. package/src/__tests__/qm-monitor.test.ts +0 -215
  39. package/src/client.ts +0 -58
  40. package/src/index.ts +0 -34
  41. package/src/model.ts +0 -32101
  42. package/src/proxmox-engine.ts +0 -452
  43. package/src/proxy.ts +0 -195
  44. package/src/qm-monitor.ts +0 -303
@@ -1,21 +1,11 @@
1
- // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
- // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
- //
4
- // This program is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // This program is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
- // 'mem', // ERROR: VM XXX qmp command 'human-monitor-command' failed - got timeout
17
- // 'tlb', // ERROR: VM XXX qmp command 'human-monitor-command' failed - got timeout
18
- export const VALID_QEMU_INFO_SIMPLE = [
1
+ import { ProxmoxError } from "./errors.js";
2
+ /**
3
+ * `info` subcommands that take no argument.
4
+ *
5
+ * `mem` and `tlb` are left out on purpose: both time out through the PVE
6
+ * monitor endpoint.
7
+ */
8
+ const VALID_QEMU_INFO_SIMPLE = [
19
9
  "backup",
20
10
  "balloon",
21
11
  "block-jobs",
@@ -66,7 +56,10 @@ export const VALID_QEMU_INFO_SIMPLE = [
66
56
  "vm-generation-id",
67
57
  "vnc",
68
58
  ];
69
- export const VALID_QEMU_INFO_OPTION = [
59
+ /**
60
+ * `info` subcommands that accept optional arguments.
61
+ */
62
+ const VALID_QEMU_INFO_OPTION = [
70
63
  "block",
71
64
  "lapic",
72
65
  "mtree",
@@ -75,50 +68,106 @@ export const VALID_QEMU_INFO_OPTION = [
75
68
  "sync-profile",
76
69
  "trace-events",
77
70
  ];
78
- export const VALID_QEMU_INFO_PARAM = [
71
+ /**
72
+ * `info` subcommands that need at least one argument.
73
+ */
74
+ const VALID_QEMU_INFO_PARAM = [
79
75
  "rocker-of-dpa-flows",
80
76
  "rocker-of-dpa-groups",
81
77
  "rocker-ports",
82
78
  ];
83
- // Device 1.1, Port 1, Speed 1.5 Mb/s, Product USB OPTICAL MOUSE , ID: mouse
84
- // Device 1.0, Port 2, Speed 12 Mb/s, Product Gaming KB , ID: keyboard
79
+ /**
80
+ * Matches one device in the reply to `info usb`, capturing device, port,
81
+ * speed and - when present - product and id.
82
+ *
83
+ * ```text
84
+ * Device 1.1, Port 1, Speed 1.5 Mb/s, Product USB OPTICAL MOUSE , ID: mouse
85
+ * Device 1.0, Port 2, Speed 12 Mb/s, Product Gaming KB , ID: keyboard
86
+ * ```
87
+ */
85
88
  const GUEST_USB = /Device ([\d.]+), Port ([\d.]+), Speed ([\d KMGTbfs/.]+)(?:, Product (.+), ID: (.+))?/g;
86
- // Bus 1, Addr 4, Port 2, Speed 480 Mb/s
87
- // Class 00: USB device 1234:5678, Some Device
89
+ /**
90
+ * Matches one device in the reply to `info usbhost`, which spans two lines,
91
+ * capturing bus, address, port, speed, class, vendor id, product id and
92
+ * name.
93
+ *
94
+ * ```text
95
+ * Bus 1, Addr 4, Port 2, Speed 480 Mb/s
96
+ * Class 00: USB device 1234:5678, Some Device
97
+ * ```
98
+ */
88
99
  const HOST_USB = /Bus (\d+), Addr (\d+), Port ([\d.]+), Speed ([\d KMGTbfs/.]+)[\r\n]\s+Class (\d+): USB device ([0-9a-f]{4}):([0-9a-f]{4}), (.*)/gm;
89
- /** Strip an optional `0x` prefix from a USB vendor or product id. */
100
+ /**
101
+ * Strips an optional `0x` prefix, in either case, from a USB vendor or
102
+ * product id.
103
+ */
90
104
  function bareHexId(value) {
91
105
  return value.replace(/^0x/i, "");
92
106
  }
93
107
  /**
94
- * QEMU monitor access for one guest, over
95
- * `POST /nodes/{node}/qemu/{vmid}/monitor`.
108
+ * Gives access to the QEMU monitor of one guest, over
109
+ * `POST /nodes/{node}/qemu/{vmid}/monitor`; use it for monitor commands that
110
+ * have no endpoint of their own.
96
111
  *
112
+ * @remarks
97
113
  * The monitor is a debugging interface: commands are passed through
98
114
  * unvalidated and replies are unstructured text whose format is not stable
99
115
  * across QEMU versions. Prefer a real endpoint wherever one exists.
116
+ *
117
+ * Every method sends at least one request and fails with the error of that
118
+ * request - a {@link ProxmoxError} when the client is backed by a
119
+ * {@link ProxmoxEngine}. Nothing here is retried, as the requests are
120
+ * `POST`s.
100
121
  */
101
122
  export class QmMonitor {
123
+ /**
124
+ * Name of the node the guest runs on.
125
+ */
102
126
  node;
127
+ /**
128
+ * Id of the guest.
129
+ */
103
130
  vmid;
104
- /** Send a raw monitor command and return its unparsed reply. */
131
+ /**
132
+ * Sends a raw monitor command and returns its unparsed reply.
133
+ *
134
+ * @param command - The command line, handed to the monitor as it is.
135
+ * @returns The monitor's reply as text.
136
+ * @throws A {@link ProxmoxError} if the request fails.
137
+ */
105
138
  monitor;
139
+ /**
140
+ * Binds a monitor to one guest, without sending anything.
141
+ *
142
+ * @param proxmox - Client to send the monitor commands through.
143
+ * @param node - Name of the node the guest runs on.
144
+ * @param vmid - Id of the guest.
145
+ * @throws A {@link ProxmoxConfigError} if `node` is empty, `.` or `..`.
146
+ */
106
147
  constructor(proxmox, node, vmid) {
107
148
  this.node = node;
108
149
  this.vmid = vmid;
109
- const post = proxmox.nodes.$(node).qemu.$(vmid).monitor.$post;
110
- this.monitor = (command) => post({ command });
150
+ const endpoint = proxmox.nodes.$(node).qemu.$(vmid).monitor;
151
+ this.monitor = (command) => endpoint.$post({ command });
111
152
  }
112
- /** Run `info <type>` and return the raw reply. */
153
+ /**
154
+ * Joins the subcommand and its arguments into one `info` command and
155
+ * sends it; the overloads above say which arguments each subcommand
156
+ * takes.
157
+ */
113
158
  async info(type, ...args) {
114
159
  const suffix = args.length > 0 ? ` ${args.join(" ")}` : "";
115
160
  return this.monitor(`info ${type}${suffix}`);
116
161
  }
117
162
  /**
118
- * USB devices currently attached to the guest.
163
+ * Lists the USB devices currently attached to the guest, from `info usb`.
119
164
  *
120
- * @throws if the reply has lines the device pattern did not match, which
121
- * means QEMU changed the format and the result would be silently short.
165
+ * @returns One entry per device, in the order of the reply. Empty for an
166
+ * empty reply.
167
+ * @throws A {@link ProxmoxError} with code `response` if the number of
168
+ * devices recognised differs from the number of lines in the reply, which
169
+ * means the output format changed and the result would be silently short.
170
+ * @throws A {@link ProxmoxError} if the request fails.
122
171
  */
123
172
  async infoUsb() {
124
173
  const text = await this.info("usb");
@@ -129,14 +178,24 @@ export class QmMonitor {
129
178
  devices.push({ device, port, speed, product, id });
130
179
  }
131
180
  if (devices.length !== expected) {
132
- throw new Error(`Parsed ${devices.length} USB devices but the reply has ${expected} lines. ` +
181
+ throw new ProxmoxError("response", `Parsed ${devices.length} USB devices but the reply has ${expected} lines. ` +
133
182
  `The monitor output format may have changed:\n${text}`);
134
183
  }
135
184
  return devices;
136
185
  }
137
186
  /**
138
- * USB devices present on the host, optionally narrowed by
139
- * vendor id, product id or name.
187
+ * Lists the USB devices present on the host, from `info usbhost`,
188
+ * optionally narrowed by vendor id, product id or name.
189
+ *
190
+ * @remarks
191
+ * Unlike {@link QmMonitor.infoUsb}, this does not verify that the whole
192
+ * reply was understood: an entry the pattern does not recognise is left
193
+ * out without an error.
194
+ *
195
+ * @param filter - Keeps only the devices that match every pattern given.
196
+ * All devices are returned when it is omitted.
197
+ * @returns The devices, in the order of the reply.
198
+ * @throws A {@link ProxmoxError} if the request fails.
140
199
  */
141
200
  async infoUsbhost(filter) {
142
201
  const text = await this.info("usbhost");
@@ -157,15 +216,25 @@ export class QmMonitor {
157
216
  if (!filter)
158
217
  return devices;
159
218
  return devices.filter((usb) => (!filter.name || filter.name.test(usb.name)) &&
160
- // Each of these tested `usb.name` before, so filtering by vendor or
161
- // product id matched on the wrong field entirely.
162
219
  (!filter.vendorId || filter.vendorId.test(usb.vendorId)) &&
163
220
  (!filter.productId || filter.productId.test(usb.productId)));
164
221
  }
165
222
  /**
166
- * Attach a host USB device by vendor and product id.
223
+ * Attaches a host USB device to the guest by vendor and product id.
224
+ *
225
+ * @remarks
226
+ * Sends `device_add usb-host,vendorid=0x...,productid=0x...,id=...`. The
227
+ * values are inserted into the command as given, without validation or
228
+ * escaping.
167
229
  *
168
- * @param id Identifier for the new device, used to detach it later.
230
+ * @param id - Identifier for the new device, used to detach it later.
231
+ * @param params - The device to attach.
232
+ * @param params.vendorId - Vendor id in hexadecimal, with or without a
233
+ * `0x` prefix.
234
+ * @param params.productId - Product id in hexadecimal, with or without a
235
+ * `0x` prefix.
236
+ * @returns The monitor's unparsed reply.
237
+ * @throws A {@link ProxmoxError} if the request fails.
169
238
  */
170
239
  async deviceAddById(id, params) {
171
240
  const vendorId = bareHexId(params.vendorId);
@@ -173,34 +242,66 @@ export class QmMonitor {
173
242
  return this.monitor(`device_add usb-host,vendorid=0x${vendorId},productid=0x${productId},id=${id}`);
174
243
  }
175
244
  /**
176
- * Attach a host USB device by physical port, which survives swapping a
177
- * device for another of the same model.
245
+ * Attaches a host USB device to the guest by physical port, which survives
246
+ * swapping a device for another of the same model.
247
+ *
248
+ * @remarks
249
+ * Sends `device_add usb-host,hostbus=...,hostport=...,id=...`. The values
250
+ * are inserted into the command as given, without validation or escaping.
251
+ *
252
+ * @param id - Identifier for the new device, used to detach it later.
253
+ * @param params - The port to attach; a {@link USBHostInfo} fits.
254
+ * @param params.bus - Number of the host bus.
255
+ * @param params.port - Port on that bus.
256
+ * @returns The monitor's unparsed reply.
257
+ * @throws A {@link ProxmoxError} if the request fails.
178
258
  */
179
259
  async deviceAddByPort(id, params) {
180
260
  return this.monitor(`device_add usb-host,hostbus=${params.bus},hostport=${params.port},id=${id}`);
181
261
  }
182
- /** Detach a device previously added under `id`. */
262
+ /**
263
+ * Detaches a device previously added under `id`, by sending
264
+ * `device_del <id>`.
265
+ *
266
+ * @param id - Identifier the device was added under. It is inserted into
267
+ * the command as given.
268
+ * @returns The monitor's unparsed reply.
269
+ * @throws A {@link ProxmoxError} if the request fails.
270
+ */
183
271
  async deviceDel(id) {
184
272
  return this.monitor(`device_del ${id}`);
185
273
  }
186
274
  /**
187
- * Attach every host device matching `filter` that is not already present.
275
+ * Attaches every host USB device matching `filter`, by physical port,
276
+ * provided nothing is attached to the guest under `id` yet.
188
277
  *
278
+ * @remarks
189
279
  * The first is added as `id`, subsequent ones as `id-1`, `id-2` and so on.
280
+ * The check against the guest covers `id` alone: whether a matching host
281
+ * device is already attached under another identifier is not looked at.
282
+ *
283
+ * The devices are attached one at a time, after one `info usb` and one
284
+ * `info usbhost` request. When a request fails, the devices attached
285
+ * before it stay attached.
190
286
  *
191
- * @returns the ids that were attached.
192
- * @throws if `id` is already attached to the guest.
287
+ * @param id - Identifier for the first device and stem for the others.
288
+ * @param filter - Selects the host devices. An empty filter selects every
289
+ * USB device on the host.
290
+ * @returns The ids that were attached, in order. Empty when no host device
291
+ * matches.
292
+ * @throws A {@link ProxmoxError} with code `config` if a device is already
293
+ * attached to the guest under `id`, with code `response` if the reply to
294
+ * `info usb` cannot be parsed in full, and with the request's own code if
295
+ * a request fails.
193
296
  */
194
297
  async deviceAddMissing(id, filter) {
195
298
  const attached = await this.infoUsb();
196
299
  if (attached.some((device) => device.id === id)) {
197
- throw new Error(`USB device ${id} already present`);
300
+ throw new ProxmoxError("config", `USB device ${id} already present`);
198
301
  }
199
302
  const candidates = await this.infoUsbhost(filter);
200
303
  const added = [];
201
- // Sequential, not concurrent: these were previously fired without being
202
- // awaited at all, so failures vanished and the guest saw an unbounded
203
- // burst of monitor commands.
304
+ // One at a time: the monitor is a single channel into a running guest.
204
305
  for (const [index, device] of candidates.entries()) {
205
306
  const deviceId = index ? `${id}-${index}` : id;
206
307
  await this.deviceAddByPort(deviceId, device);
@@ -209,4 +310,3 @@ export class QmMonitor {
209
310
  return added;
210
311
  }
211
312
  }
212
- //# sourceMappingURL=qm-monitor.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The Proxmox VE release the bundled API model describes, e.g. `9.2`.
3
+ */
4
+ export declare const PVE_VERSION = "9.2";
5
+ /**
6
+ * The exact `pve-docs` package version the API schema was taken from.
7
+ */
8
+ export declare const PVE_SCHEMA_VERSION = "9.2.15";
9
+ /**
10
+ * Number of operations the model covers.
11
+ */
12
+ export declare const PVE_OPERATION_COUNT = 688;
@@ -0,0 +1,13 @@
1
+ // Generated by @virtbase/proxmox-api-generator. Do not edit.
2
+ /**
3
+ * The Proxmox VE release the bundled API model describes, e.g. `9.2`.
4
+ */
5
+ export const PVE_VERSION = "9.2";
6
+ /**
7
+ * The exact `pve-docs` package version the API schema was taken from.
8
+ */
9
+ export const PVE_SCHEMA_VERSION = "9.2.15";
10
+ /**
11
+ * Number of operations the model covers.
12
+ */
13
+ export const PVE_OPERATION_COUNT = 688;
@@ -0,0 +1,129 @@
1
+ import type { Proxmox } from "./model.js";
2
+ /**
3
+ * The fields packed into a task identifier, as returned by
4
+ * {@link parseUpid}.
5
+ */
6
+ export interface ParsedUpid {
7
+ /**
8
+ * The node the task runs on - the only node that can report its status.
9
+ */
10
+ node: string;
11
+ /**
12
+ * Process id of the task's worker on that node.
13
+ */
14
+ pid: number;
15
+ /**
16
+ * The identifier's `pstart` field as a number: the start time of the
17
+ * worker process in the node's own units. It is not a timestamp; see
18
+ * {@link ParsedUpid.startTime} for that.
19
+ */
20
+ pstart: number;
21
+ /**
22
+ * When the task started. The identifier records it in whole seconds.
23
+ */
24
+ startTime: Date;
25
+ /**
26
+ * What the task does, e.g. `qmstart` or `vzdump`.
27
+ */
28
+ type: string;
29
+ /**
30
+ * What it acts on, usually a guest id. Empty for node-wide tasks.
31
+ */
32
+ id: string;
33
+ /**
34
+ * Who started it: `user@realm`, or `user@realm!token`.
35
+ */
36
+ user: string;
37
+ }
38
+ /**
39
+ * Splits a UPID, the identifier Proxmox gives a background task, into its
40
+ * fields.
41
+ *
42
+ * @param upid - The identifier, exactly as Proxmox returned it.
43
+ * @returns The fields of the identifier, with its hexadecimal numbers
44
+ * decoded.
45
+ * @throws A {@link ProxmoxConfigError} if the string is not a UPID.
46
+ * @example
47
+ * ```ts
48
+ * parseUpid("UPID:pve1:0001E240:0A1B2C3D:6553F100:qmstart:100:root@pam:");
49
+ * // { node: "pve1", pid: 123456, type: "qmstart", id: "100",
50
+ * // user: "root@pam", startTime: 2023-11-14T22:13:20.000Z,
51
+ * // pstart: 169552957 }
52
+ * ```
53
+ */
54
+ export declare function parseUpid(upid: string): ParsedUpid;
55
+ /**
56
+ * Controls how {@link waitForTask} polls and when it gives up.
57
+ */
58
+ export interface WaitForTaskOptions {
59
+ /**
60
+ * Milliseconds between the answer to one status check and the start of
61
+ * the next.
62
+ *
63
+ * @defaultValue `1000`
64
+ */
65
+ interval?: number;
66
+ /**
67
+ * Milliseconds to wait before giving up. Without it there is no limit.
68
+ *
69
+ * The limit is looked at after each status check that finds the task
70
+ * running: the wait ends as soon as the next check would fall past it,
71
+ * which can be up to one `interval` early. A status check in flight is
72
+ * not cut short. The task itself keeps running.
73
+ */
74
+ timeout?: number;
75
+ /**
76
+ * Stops waiting. The task itself keeps running. The signal is also passed
77
+ * to each status check, so it cancels one that is in flight.
78
+ */
79
+ signal?: AbortSignal;
80
+ /**
81
+ * Treat a task that finished with `WARNINGS: <n>` as failed. By default it
82
+ * counts as success, which is how Proxmox's own tools read it.
83
+ *
84
+ * @defaultValue `false`
85
+ */
86
+ failOnWarnings?: boolean;
87
+ }
88
+ /**
89
+ * The state of a task as its status endpoint returns it.
90
+ * {@link waitForTask} resolves with the final one.
91
+ */
92
+ export type TaskStatus = Proxmox.NodesTasksStatusReadTaskStatus;
93
+ /**
94
+ * Waits for a background task to finish and settles with its outcome.
95
+ *
96
+ * @remarks
97
+ * Most calls that change something return a UPID straight away and do the
98
+ * work afterwards, so a resolved request says nothing about the outcome.
99
+ * This polls the task's status on the node that runs it: the first check is
100
+ * made at once, each further one `interval` milliseconds after the previous
101
+ * answer. It settles with the task: the final status on success, a
102
+ * {@link ProxmoxTaskError} carrying Proxmox's exit status on failure.
103
+ *
104
+ * Waiting has no effect on the task. When the wait ends early - by timeout,
105
+ * signal or a failed status check - the task keeps running.
106
+ *
107
+ * @param proxmox - Client to send the status checks through.
108
+ * @param upid - Identifier of the task, as returned by the call that started
109
+ * it.
110
+ * @param options - How often to check, how long to wait and whether
111
+ * warnings count as failure.
112
+ * @returns The final status of a task that succeeded: one whose
113
+ * `exitstatus` is `OK` or, unless `failOnWarnings` is set, starts with
114
+ * `WARNINGS`.
115
+ * @throws A {@link ProxmoxTaskError} if the task stopped with any other exit
116
+ * status, or with none, which is reported as `unknown`.
117
+ * @throws A {@link ProxmoxConfigError} if `upid` is not a task identifier.
118
+ * @throws A {@link ProxmoxError} with the code `timeout` if the task is
119
+ * still running when `timeout` runs out, and with the code `aborted` if
120
+ * `signal` aborts between two status checks. A status check that fails
121
+ * ends the wait with the error of that request, which is a
122
+ * {@link ProxmoxAbortError} when `signal` aborts it in flight.
123
+ * @example
124
+ * ```ts
125
+ * const upid = await proxmox.nodes.$("pve1").qemu.$(100).status.start.$post();
126
+ * await waitForTask(proxmox, upid);
127
+ * ```
128
+ */
129
+ export declare function waitForTask(proxmox: Proxmox.Api, upid: string, options?: WaitForTaskOptions): Promise<TaskStatus>;
package/dist/tasks.js ADDED
@@ -0,0 +1,132 @@
1
+ import { ProxmoxConfigError, ProxmoxError, ProxmoxTaskError, } from "./errors.js";
2
+ /**
3
+ * Matches a task identifier and captures its fields:
4
+ * `UPID:<node>:<pid>:<pstart>:<starttime>:<type>:<id>:<user>:`.
5
+ *
6
+ * The three numbers are hexadecimal - eight digits each, with a ninth
7
+ * allowed for `pstart` - and `id` may be empty.
8
+ */
9
+ const UPID = /^UPID:([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/;
10
+ /**
11
+ * Splits a UPID, the identifier Proxmox gives a background task, into its
12
+ * fields.
13
+ *
14
+ * @param upid - The identifier, exactly as Proxmox returned it.
15
+ * @returns The fields of the identifier, with its hexadecimal numbers
16
+ * decoded.
17
+ * @throws A {@link ProxmoxConfigError} if the string is not a UPID.
18
+ * @example
19
+ * ```ts
20
+ * parseUpid("UPID:pve1:0001E240:0A1B2C3D:6553F100:qmstart:100:root@pam:");
21
+ * // { node: "pve1", pid: 123456, type: "qmstart", id: "100",
22
+ * // user: "root@pam", startTime: 2023-11-14T22:13:20.000Z,
23
+ * // pstart: 169552957 }
24
+ * ```
25
+ */
26
+ export function parseUpid(upid) {
27
+ const match = UPID.exec(upid);
28
+ if (!match) {
29
+ throw new ProxmoxConfigError(`Not a task identifier: ${JSON.stringify(upid)}`);
30
+ }
31
+ const [, node = "", pid = "", pstart = "", start = "", type = "", id = "", user = "",] = match;
32
+ return {
33
+ node,
34
+ pid: Number.parseInt(pid, 16),
35
+ pstart: Number.parseInt(pstart, 16),
36
+ startTime: new Date(Number.parseInt(start, 16) * 1000),
37
+ type,
38
+ id,
39
+ user,
40
+ };
41
+ }
42
+ /**
43
+ * Builds the error for a wait that the caller's signal ended.
44
+ *
45
+ * @param upid - Identifier of the task that was being waited for.
46
+ * @param signal - The aborted signal, whose `reason` becomes the `cause`.
47
+ * @returns A plain {@link ProxmoxError} with the code `aborted`.
48
+ */
49
+ function stopped(upid, signal) {
50
+ return new ProxmoxError("aborted", `Stopped waiting for task ${upid}`, {
51
+ cause: signal.reason,
52
+ });
53
+ }
54
+ /**
55
+ * Waits between two status checks, ending early when the signal aborts.
56
+ *
57
+ * @remarks
58
+ * Never rejects: the caller checks the signal afterwards.
59
+ *
60
+ * @param ms - Milliseconds to wait.
61
+ * @param signal - Ends the wait when it aborts. An abort that happened
62
+ * before the call goes unnoticed and the full time is waited.
63
+ */
64
+ function pause(ms, signal) {
65
+ return new Promise((resolve) => {
66
+ const done = () => {
67
+ clearTimeout(timer);
68
+ signal?.removeEventListener("abort", done);
69
+ resolve();
70
+ };
71
+ const timer = setTimeout(done, ms);
72
+ signal?.addEventListener("abort", done, { once: true });
73
+ });
74
+ }
75
+ /**
76
+ * Waits for a background task to finish and settles with its outcome.
77
+ *
78
+ * @remarks
79
+ * Most calls that change something return a UPID straight away and do the
80
+ * work afterwards, so a resolved request says nothing about the outcome.
81
+ * This polls the task's status on the node that runs it: the first check is
82
+ * made at once, each further one `interval` milliseconds after the previous
83
+ * answer. It settles with the task: the final status on success, a
84
+ * {@link ProxmoxTaskError} carrying Proxmox's exit status on failure.
85
+ *
86
+ * Waiting has no effect on the task. When the wait ends early - by timeout,
87
+ * signal or a failed status check - the task keeps running.
88
+ *
89
+ * @param proxmox - Client to send the status checks through.
90
+ * @param upid - Identifier of the task, as returned by the call that started
91
+ * it.
92
+ * @param options - How often to check, how long to wait and whether
93
+ * warnings count as failure.
94
+ * @returns The final status of a task that succeeded: one whose
95
+ * `exitstatus` is `OK` or, unless `failOnWarnings` is set, starts with
96
+ * `WARNINGS`.
97
+ * @throws A {@link ProxmoxTaskError} if the task stopped with any other exit
98
+ * status, or with none, which is reported as `unknown`.
99
+ * @throws A {@link ProxmoxConfigError} if `upid` is not a task identifier.
100
+ * @throws A {@link ProxmoxError} with the code `timeout` if the task is
101
+ * still running when `timeout` runs out, and with the code `aborted` if
102
+ * `signal` aborts between two status checks. A status check that fails
103
+ * ends the wait with the error of that request, which is a
104
+ * {@link ProxmoxAbortError} when `signal` aborts it in flight.
105
+ * @example
106
+ * ```ts
107
+ * const upid = await proxmox.nodes.$("pve1").qemu.$(100).status.start.$post();
108
+ * await waitForTask(proxmox, upid);
109
+ * ```
110
+ */
111
+ export async function waitForTask(proxmox, upid, options = {}) {
112
+ const { interval = 1000, timeout, signal, failOnWarnings = false } = options;
113
+ const { node } = parseUpid(upid);
114
+ const status = proxmox.nodes.$(node).tasks.$(upid).status;
115
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
116
+ for (;;) {
117
+ if (signal?.aborted)
118
+ throw stopped(upid, signal);
119
+ const task = await status.$get(null, { signal });
120
+ if (task.status === "stopped") {
121
+ const exitstatus = task.exitstatus ?? "unknown";
122
+ const warned = exitstatus.startsWith("WARNINGS");
123
+ if (exitstatus === "OK" || (warned && !failOnWarnings))
124
+ return task;
125
+ throw new ProxmoxTaskError(upid, exitstatus);
126
+ }
127
+ if (deadline !== undefined && Date.now() + interval > deadline) {
128
+ throw new ProxmoxError("timeout", `Task ${upid} was still running after ${timeout} ms`);
129
+ }
130
+ await pause(interval, signal);
131
+ }
132
+ }