-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathhost.controller.mts
More file actions
445 lines (410 loc) · 14.4 KB
/
Copy pathhost.controller.mts
File metadata and controls
445 lines (410 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import {
Body,
Delete,
Example,
Get,
Middlewares,
Path,
Post,
Put,
Query,
Request,
Response,
Route,
Security,
SuccessResponse,
Tags,
} from 'tsoa'
import { asyncEach } from '@vates/async-each'
import { type Defer, defer } from 'golike-defer'
import { json } from 'express'
import type { Request as ExRequest, Response as ExResponse } from 'express'
import { inject } from 'inversify'
import { invalidParameters } from 'xo-common/api-errors.js'
import { pipeline } from 'node:stream/promises'
import { provide } from 'inversify-binding-decorators'
import type {
XapiHostStats,
XapiStatsGranularity,
XcpPatches,
XoAlarm,
XoHost,
XoMessage,
XoPif,
XoTask,
XoVm,
XsPatches,
} from '@vates/types'
import { AlarmService } from '../alarms/alarm.service.mjs'
import { escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
import { genericAlarmsExample } from '../open-api/oa-examples/alarm.oa-example.mjs'
import {
host,
hostIds,
hostSmt,
hostMissingPatches,
hostStats,
partialHosts,
} from '../open-api/oa-examples/host.oa-example.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
import type { SendObjects } from '../helpers/helper.type.mjs'
import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
import {
asynchronousActionResp,
badRequestResp,
featureUnauthorized,
internalServerErrorResp,
invalidParameters as invalidParametersResp,
noContentResp,
notFoundResp,
unauthorizedResp,
type Unbrand,
} from '../open-api/common/response.common.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import { HostService } from './host.service.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import { partialTasks, taskIds, taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
@Route('hosts')
@Security('*')
@Response(badRequestResp.status, badRequestResp.description)
@Response(unauthorizedResp.status, unauthorizedResp.description)
@Tags('hosts')
@provide(HostController)
export class HostController extends XapiXoController<XoHost> {
#alarmService: AlarmService
#hostService: HostService
constructor(
@inject(RestApi) restApi: RestApi,
@inject(AlarmService) alarmService: AlarmService,
@inject(HostService) hostService: HostService
) {
super('host', restApi)
this.#alarmService = alarmService
this.#hostService = hostService
}
/**
* @example fields "id,name_label,productBrand"
* @example filter "productBrand:XCP-ng"
* @example limit 42
*/
@Example(hostIds)
@Example(partialHosts)
@Get('')
getHosts(
@Request() req: ExRequest,
@Query() fields?: string,
@Query() ndjson?: boolean,
@Query() filter?: string,
@Query() limit?: number
): SendObjects<Partial<Unbrand<XoHost>>> {
return this.sendObjects(Object.values(this.getObjects({ filter, limit })), req)
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*/
@Example(host)
@Get('{id}')
@Response(notFoundResp.status, notFoundResp.description)
getHost(@Path() id: string): Unbrand<XoHost> {
return this.getObject(id as XoHost['id'])
}
/**
* Host must be running
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*/
@Example(hostStats)
@Get('{id}/stats')
@Response(notFoundResp.status, notFoundResp.description)
@Response(422, 'Invalid granularity')
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
getHostStats(@Path() id: string, @Query() granularity?: XapiStatsGranularity): Promise<XapiHostStats> {
return this.restApi.xoApp.getXapiHostStats(id as XoHost['id'], granularity)
}
/**
* Host must be running
*
* Download the audit log of a host.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*
*/
@Get('{id}/audit.txt')
@SuccessResponse(200, 'Download started', 'application/octet-stream')
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async getAuditLog(@Request() req: ExRequest, @Path() id: string) {
const xapiHost = this.getXapiObject(id as XoHost['id'])
const res = req.res as ExResponse
const response = await xapiHost.$xapi.getResource('/audit_log', { host: xapiHost })
const date = new Date().toISOString()
const headers = new Headers({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${host.name_label}-${date}-audit.txt"`,
})
res.setHeaders(headers)
await pipeline(response.body, this.maybeCompressResponse(req, res))
}
/**
* Host must be running
*
* Download all logs of a host.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*
*/
@Get('{id}/logs.tgz')
@SuccessResponse(200, 'Download started', 'application/gzip')
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async getHostLogs(@Request() req: ExRequest, @Path() id: string) {
const xapiHost = this.getXapiObject(id as XoHost['id'])
const res = req.res as ExResponse
const response = await xapiHost.$xapi.getResource('/host_logs_download', { host: xapiHost })
res.setHeader('Content-Type', 'application/gzip')
await pipeline(response.body, res)
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example fields "id,time"
* @example filter "time:>1747053793"
* @example limit 42
*/
@Example(genericAlarmsExample)
@Get('{id}/alarms')
@Tags('alarms')
@Response(notFoundResp.status, notFoundResp.description)
getHostAlarms(
@Request() req: ExRequest,
@Path() id: string,
@Query() fields?: string,
@Query() ndjson?: boolean,
@Query() filter?: string,
@Query() limit?: number
): SendObjects<Partial<Unbrand<XoAlarm>>> {
const host = this.getObject(id as XoHost['id'])
const alarms = this.#alarmService.getAlarms({
filter: `${escapeUnsafeComplexMatcher(filter) ?? ''} object:uuid:${host.uuid}`,
limit,
})
return this.sendObjects(Object.values(alarms), req, 'alarms')
}
/**
* Returns a boolean indicating whether SMT (Simultaneous Multi-Threading) is enabled
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*/
@Example(hostSmt)
@Get('{id}/smt')
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async gethostSmt(@Path() id: string): Promise<{ enabled: boolean }> {
const hostId = id as XoHost['id']
const xapiHost = this.getXapiObject(hostId)
const enabled = Boolean(await xapiHost.$xapi.isHyperThreadingEnabled(hostId))
return { enabled }
}
/**
* Host must be running
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*/
@Example(hostMissingPatches)
@Get('{id}/missing_patches')
@Response(notFoundResp.status, notFoundResp.description)
@Response(featureUnauthorized.status, featureUnauthorized.description)
async getMissingPatches(@Path() id: string): Promise<XcpPatches[] | XsPatches[]> {
const { missingPatches } = await this.#hostService.getMissingPatchesInfo({ filter: host => host.id === id })
return missingPatches
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example fields "name,id,$object"
* @example filter "name:PBD_PLUG_FAILED_ON_SERVER_START"
* @example limit 42
*/
@Example(messageIds)
@Example(partialMessages)
@Get('{id}/messages')
@Tags('messages')
@Response(notFoundResp.status, notFoundResp.description)
getHostMessages(
@Request() req: ExRequest,
@Path() id: string,
@Query() fields?: string,
@Query() ndjson?: boolean,
@Query() filter?: string,
@Query() limit?: number
): SendObjects<Partial<Unbrand<XoMessage>>> {
const messages = this.getMessagesForObject(id as XoHost['id'], { filter, limit })
return this.sendObjects(Object.values(messages), req, 'messages')
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example fields "id,status,properties"
* @example filter "status:failure"
* @example limit 42
*/
@Example(taskIds)
@Example(partialTasks)
@Get('{id}/tasks')
@Tags('tasks')
@Response(notFoundResp.status, notFoundResp.description)
async getHostTasks(
@Request() req: ExRequest,
@Path() id: string,
@Query() fields?: string,
@Query() ndjson?: boolean,
@Query() filter?: string,
@Query() limit?: number
): Promise<SendObjects<Partial<Unbrand<XoTask>>>> {
const tasks = await this.getTasksForObject(id as XoHost['id'], { filter, limit })
return this.sendObjects(Object.values(tasks), req, 'tasks')
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example tag "from-rest-api"
*/
@Put('{id}/tags/{tag}')
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
async putHostTag(@Path() id: string, @Path() tag: string): Promise<void> {
const host = this.getXapiObject(id as XoHost['id'])
await host.$call('add_tags', tag)
}
/**
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example tag "from-rest-api"
*/
@Delete('{id}/tags/{tag}')
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
async deleteHostTag(@Path() id: string, @Path() tag: string): Promise<void> {
const host = this.getXapiObject(id as XoHost['id'])
await host.$call('remove_tags', tag)
}
/**
* Reconfigure the management interface of the host to use the given PIF.
*
* The target PIF must already have an IP address configured.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example body { "pif": "d9e42451-3794-089f-de81-4ee0e6137bee" }
*/
@Example(taskLocation)
@Post('{id}/actions/management_reconfigure')
@Middlewares(json())
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(badRequestResp.status, badRequestResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
managementReconfigure(
@Path() id: string,
@Body() body: { pif: string },
@Query() sync?: boolean
): CreateActionReturnType<void> {
const hostId = id as XoHost['id']
const action = async () => {
const host = this.getObject(hostId)
const pif = this.restApi.getObject<XoPif>(body.pif as XoPif['id'], 'PIF')
if (pif.$host !== host.id) {
throw invalidParameters(`the PIF ${pif.uuid} does not belong to host ${host.uuid}`)
}
const xapiHost = this.getXapiObject(hostId)
await xapiHost.$xapi.callAsync('host.management_reconfigure', pif._xapiRef)
}
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: 'reconfigure host management interface',
objectId: hostId,
params: body,
},
})
}
/**
* Disable a host.
*
* Set `evacuate` to `true` to also evacuate all running VMs to other hosts in the pool.
*
* Use `vmIdsToForceMigrate` to unblock VMs whose migration is currently blocked (e.g. by `pool_migrate` or `migrate_send` blocked operations).
*
* Use `force` to ignore evacuation errors.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example body { "evacuate": true, "vmIdsToForceMigrate": ["f07ab729-c0e8-721c-45ec-f11276377030"] }
*/
@Example(taskLocation)
@Post('{id}/actions/disable')
@Middlewares(json())
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
disable(
@Path() id: string,
// mark `evacuate` as optional to workaround a TSOA issue. See https://github.com/lukeautry/tsoa/pull/1840
@Body() body?: { evacuate?: false } | { evacuate: true; force?: boolean; vmIdsToForceMigrate?: string[] },
@Query() sync?: boolean
): CreateActionReturnType<void> {
const hostId = id as XoHost['id']
const action = defer(async ($defer: Defer) => {
const xapiHost = this.getXapiObject(hostId)
const xapi = xapiHost.$xapi
if (body?.evacuate !== true) {
await xapi.call('host.disable', xapiHost.$ref)
return
}
if (body.vmIdsToForceMigrate !== undefined) {
await asyncEach(body.vmIdsToForceMigrate, async vmId => {
const xoVm = this.restApi.getObject<XoVm>(vmId as XoVm['id'], 'VM')
for (const operation of ['pool_migrate', 'migrate_send'] as const) {
const reason = xoVm.blockedOperations[operation]
if (reason !== undefined) {
await xapi.call('VM.remove_from_blocked_operations', xoVm._xapiRef, operation)
$defer(() => xapi.call('VM.add_to_blocked_operations', xoVm._xapiRef, operation, reason))
}
}
})
}
await xapi.clearHost(xapiHost, body.force)
})
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: body?.evacuate === true ? 'disable and evacuate host' : 'disable host',
objectId: hostId,
params: body,
},
})
}
/**
* Enable a host, taking it out of disabled state.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
*/
@Example(taskLocation)
@Post('{id}/actions/enable')
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
enable(@Path() id: string, @Query() sync?: boolean): CreateActionReturnType<void> {
const hostId = id as XoHost['id']
const action = async () => {
await this.getXapiObject(hostId).$xapi.enableHost(hostId)
}
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: 'enable host',
objectId: hostId,
},
})
}
}