@xen-orchestra/backups 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Backup.js CHANGED
@@ -6,7 +6,7 @@ const ignoreErrors = require('promise-toolbox/ignoreErrors')
6
6
  const { compileTemplate } = require('@xen-orchestra/template')
7
7
  const { limitConcurrency } = require('limit-concurrency-decorator')
8
8
 
9
- const { extractIdsFromSimplePattern } = require('./_extractIdsFromSimplePattern.js')
9
+ const { extractIdsFromSimplePattern } = require('./extractIdsFromSimplePattern.js')
10
10
  const { PoolMetadataBackup } = require('./_PoolMetadataBackup.js')
11
11
  const { Task } = require('./Task.js')
12
12
  const { VmBackup } = require('./_VmBackup.js')
@@ -24,6 +24,34 @@ const getAdaptersByRemote = adapters => {
24
24
 
25
25
  const runTask = (...args) => Task.run(...args).catch(noop) // errors are handled by logs
26
26
 
27
+ const DEFAULT_SETTINGS = {
28
+ reportWhen: 'failure',
29
+ }
30
+
31
+ const DEFAULT_VM_SETTINGS = {
32
+ bypassVdiChainsCheck: false,
33
+ checkpointSnapshot: false,
34
+ concurrency: 2,
35
+ copyRetention: 0,
36
+ deleteFirst: false,
37
+ exportRetention: 0,
38
+ fullInterval: 0,
39
+ healthCheckSr: undefined,
40
+ healthCheckVmsWithTags: [],
41
+ maxMergedDeltasPerRun: 2,
42
+ offlineBackup: false,
43
+ offlineSnapshot: false,
44
+ snapshotRetention: 0,
45
+ timeout: 0,
46
+ unconditionalSnapshot: false,
47
+ vmTimeout: 0,
48
+ }
49
+
50
+ const DEFAULT_METADATA_SETTINGS = {
51
+ retentionPoolMetadata: 0,
52
+ retentionXoMetadata: 0,
53
+ }
54
+
27
55
  exports.Backup = class Backup {
28
56
  constructor({ config, getAdapter, getConnectedRecord, job, schedule }) {
29
57
  this._config = config
@@ -42,17 +70,22 @@ exports.Backup = class Backup {
42
70
  '{job.name}': job.name,
43
71
  '{vm.name_label}': vm => vm.name_label,
44
72
  })
45
- }
46
73
 
47
- run() {
48
- const type = this._job.type
74
+ const { type } = job
75
+ const baseSettings = { ...DEFAULT_SETTINGS }
49
76
  if (type === 'backup') {
50
- return this._runVmBackup()
77
+ Object.assign(baseSettings, DEFAULT_VM_SETTINGS, config.defaultSettings, config.vm?.defaultSettings)
78
+ this.run = this._runVmBackup
51
79
  } else if (type === 'metadataBackup') {
52
- return this._runMetadataBackup()
80
+ Object.assign(baseSettings, DEFAULT_METADATA_SETTINGS, config.defaultSettings, config.metadata?.defaultSettings)
81
+ this.run = this._runMetadataBackup
53
82
  } else {
54
83
  throw new Error(`No runner for the backup type ${type}`)
55
84
  }
85
+ Object.assign(baseSettings, job.settings[''])
86
+
87
+ this._baseSettings = baseSettings
88
+ this._settings = { ...baseSettings, ...job.settings[schedule.id] }
56
89
  }
57
90
 
58
91
  async _runMetadataBackup() {
@@ -64,13 +97,6 @@ exports.Backup = class Backup {
64
97
  }
65
98
 
66
99
  const config = this._config
67
- const settings = {
68
- ...config.defaultSettings,
69
- ...config.metadata.defaultSettings,
70
- ...job.settings[''],
71
- ...job.settings[schedule.id],
72
- }
73
-
74
100
  const poolIds = extractIdsFromSimplePattern(job.pools)
75
101
  const isEmptyPools = poolIds.length === 0
76
102
  const isXoMetadata = job.xoMetadata !== undefined
@@ -78,6 +104,8 @@ exports.Backup = class Backup {
78
104
  throw new Error('no metadata mode found')
79
105
  }
80
106
 
107
+ const settings = this._settings
108
+
81
109
  const { retentionPoolMetadata, retentionXoMetadata } = settings
82
110
 
83
111
  if (
@@ -189,14 +217,7 @@ exports.Backup = class Backup {
189
217
  const schedule = this._schedule
190
218
 
191
219
  const config = this._config
192
- const { settings } = job
193
- const scheduleSettings = {
194
- ...config.defaultSettings,
195
- ...config.vm.defaultSettings,
196
- ...settings[''],
197
- ...settings[schedule.id],
198
- }
199
-
220
+ const settings = this._settings
200
221
  await Disposable.use(
201
222
  Disposable.all(
202
223
  extractIdsFromSimplePattern(job.srs).map(id =>
@@ -224,14 +245,15 @@ exports.Backup = class Backup {
224
245
  })
225
246
  )
226
247
  ),
227
- async (srs, remoteAdapters) => {
248
+ () => settings.healthCheckSr !== undefined ? this._getRecord('SR', settings.healthCheckSr) : undefined,
249
+ async (srs, remoteAdapters, healthCheckSr) => {
228
250
  // remove adapters that failed (already handled)
229
251
  remoteAdapters = remoteAdapters.filter(_ => _ !== undefined)
230
252
 
231
253
  // remove srs that failed (already handled)
232
254
  srs = srs.filter(_ => _ !== undefined)
233
255
 
234
- if (remoteAdapters.length === 0 && srs.length === 0 && scheduleSettings.snapshotRetention === 0) {
256
+ if (remoteAdapters.length === 0 && srs.length === 0 && settings.snapshotRetention === 0) {
235
257
  return
236
258
  }
237
259
 
@@ -241,23 +263,27 @@ exports.Backup = class Backup {
241
263
 
242
264
  remoteAdapters = getAdaptersByRemote(remoteAdapters)
243
265
 
266
+ const allSettings = this._job.settings
267
+ const baseSettings = this._baseSettings
268
+
244
269
  const handleVm = vmUuid =>
245
270
  runTask({ name: 'backup VM', data: { type: 'VM', id: vmUuid } }, () =>
246
271
  Disposable.use(this._getRecord('VM', vmUuid), vm =>
247
272
  new VmBackup({
273
+ baseSettings,
248
274
  config,
249
275
  getSnapshotNameLabel,
276
+ healthCheckSr,
250
277
  job,
251
- // remotes,
252
278
  remoteAdapters,
253
279
  schedule,
254
- settings: { ...scheduleSettings, ...settings[vmUuid] },
280
+ settings: { ...settings, ...allSettings[vm.uuid] },
255
281
  srs,
256
282
  vm,
257
283
  }).run()
258
284
  )
259
285
  )
260
- const { concurrency } = scheduleSettings
286
+ const { concurrency } = settings
261
287
  await asyncMapSettled(vmIds, concurrency === 0 ? handleVm : limitConcurrency(concurrency)(handleVm))
262
288
  }
263
289
  )
@@ -0,0 +1,64 @@
1
+ 'use strict'
2
+
3
+ const { Task } = require('./Task')
4
+
5
+ exports.HealthCheckVmBackup = class HealthCheckVmBackup {
6
+ #xapi
7
+ #restoredVm
8
+
9
+ constructor({ restoredVm, xapi }) {
10
+ this.#restoredVm = restoredVm
11
+ this.#xapi = xapi
12
+ }
13
+
14
+ async run() {
15
+ return Task.run(
16
+ {
17
+ name: 'vmstart',
18
+ },
19
+ async () => {
20
+ let restoredVm = this.#restoredVm
21
+ const xapi = this.#xapi
22
+ const restoredId = restoredVm.uuid
23
+
24
+ // remove vifs
25
+ await Promise.all(restoredVm.$VIFs.map(vif => xapi.callAsync('VIF.destroy', vif.$ref)))
26
+
27
+ const start = new Date()
28
+ // start Vm
29
+
30
+ await xapi.callAsync(
31
+ 'VM.start',
32
+ restoredVm.$ref,
33
+ false, // Start paused?
34
+ false // Skip pre-boot checks?
35
+ )
36
+ const started = new Date()
37
+ const timeout = 10 * 60 * 1000
38
+ const startDuration = started - start
39
+
40
+ let remainingTimeout = timeout - startDuration
41
+
42
+ if (remainingTimeout < 0) {
43
+ throw new Error(`VM ${restoredId} not started after ${timeout / 1000} second`)
44
+ }
45
+
46
+ // wait for the 'Running' event to be really stored in local xapi object cache
47
+ restoredVm = await xapi.waitObjectState(restoredVm.$ref, vm => vm.power_state === 'Running', {
48
+ timeout: remainingTimeout,
49
+ })
50
+
51
+ const running = new Date()
52
+ remainingTimeout -= running - started
53
+
54
+ if (remainingTimeout < 0) {
55
+ throw new Error(`local xapi did not get Runnig state for VM ${restoredId} after ${timeout / 1000} second`)
56
+ }
57
+ // wait for the guest tool version to be defined
58
+ await xapi.waitObjectState(restoredVm.guest_metrics, gm => gm?.PV_drivers_version?.major !== undefined, {
59
+ timeout: remainingTimeout,
60
+ })
61
+ }
62
+ )
63
+ }
64
+ }
package/RemoteAdapter.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { asyncMap, asyncMapSettled } = require('@xen-orchestra/async-map')
4
+ const { synchronized } = require('decorator-synchronized')
4
5
  const Disposable = require('promise-toolbox/Disposable')
5
6
  const fromCallback = require('promise-toolbox/fromCallback')
6
7
  const fromEvent = require('promise-toolbox/fromEvent')
@@ -9,7 +10,7 @@ const groupBy = require('lodash/groupBy.js')
9
10
  const pickBy = require('lodash/pickBy.js')
10
11
  const { dirname, join, normalize, resolve } = require('path')
11
12
  const { createLogger } = require('@xen-orchestra/log')
12
- const { Constants, createVhdDirectoryFromStream, openVhd, VhdAbstract, VhdDirectory, VhdSynthetic } = require('vhd-lib')
13
+ const { createVhdDirectoryFromStream, openVhd, VhdAbstract, VhdDirectory, VhdSynthetic } = require('vhd-lib')
13
14
  const { deduped } = require('@vates/disposable/deduped.js')
14
15
  const { decorateMethodsWith } = require('@vates/decorate-with')
15
16
  const { compose } = require('@vates/compose')
@@ -17,6 +18,7 @@ const { execFile } = require('child_process')
17
18
  const { readdir, stat } = require('fs-extra')
18
19
  const { v4: uuidv4 } = require('uuid')
19
20
  const { ZipFile } = require('yazl')
21
+ const zlib = require('zlib')
20
22
 
21
23
  const { BACKUP_DIR } = require('./_getVmBackupDir.js')
22
24
  const { cleanVm } = require('./_cleanVm.js')
@@ -78,6 +80,7 @@ class RemoteAdapter {
78
80
  this._dirMode = dirMode
79
81
  this._handler = handler
80
82
  this._vhdDirectoryCompression = vhdDirectoryCompression
83
+ this._readCacheListVmBackups = synchronized.withKey()(this._readCacheListVmBackups)
81
84
  }
82
85
 
83
86
  get handler() {
@@ -261,7 +264,8 @@ class RemoteAdapter {
261
264
  }
262
265
 
263
266
  async deleteVmBackups(files) {
264
- const { delta, full, ...others } = groupBy(await asyncMap(files, file => this.readVmBackupMetadata(file)), 'mode')
267
+ const metadatas = await asyncMap(files, file => this.readVmBackupMetadata(file))
268
+ const { delta, full, ...others } = groupBy(metadatas, 'mode')
265
269
 
266
270
  const unsupportedModes = Object.keys(others)
267
271
  if (unsupportedModes.length !== 0) {
@@ -278,6 +282,9 @@ class RemoteAdapter {
278
282
  // don't merge in main process, unused VHDs will be merged in the next backup run
279
283
  await this.cleanVm(dir, { remove: true, onLog: warn })
280
284
  }
285
+
286
+ const dedupedVmUuid = new Set(metadatas.map(_ => _.vm.uuid))
287
+ await asyncMap(dedupedVmUuid, vmUuid => this.invalidateVmBackupListCache(vmUuid))
281
288
  }
282
289
 
283
290
  #getCompressionType() {
@@ -448,34 +455,94 @@ class RemoteAdapter {
448
455
  return backupsByPool
449
456
  }
450
457
 
451
- async listVmBackups(vmUuid, predicate) {
458
+ async invalidateVmBackupListCache(vmUuid) {
459
+ await this.handler.unlink(`${BACKUP_DIR}/${vmUuid}/cache.json.gz`)
460
+ }
461
+
462
+ async #getCachabledDataListVmBackups(dir) {
452
463
  const handler = this._handler
453
- const backups = []
464
+ const backups = {}
454
465
 
455
466
  try {
456
- const files = await handler.list(`${BACKUP_DIR}/${vmUuid}`, {
467
+ const files = await handler.list(dir, {
457
468
  filter: isMetadataFile,
458
469
  prependDir: true,
459
470
  })
460
471
  await asyncMap(files, async file => {
461
472
  try {
462
473
  const metadata = await this.readVmBackupMetadata(file)
463
- if (predicate === undefined || predicate(metadata)) {
464
- // inject an id usable by importVmBackupNg()
465
- metadata.id = metadata._filename
466
-
467
- backups.push(metadata)
468
- }
474
+ // inject an id usable by importVmBackupNg()
475
+ metadata.id = metadata._filename
476
+ backups[file] = metadata
469
477
  } catch (error) {
470
- warn(`listVmBackups ${file}`, { error })
478
+ warn(`can't read vm backup metadata`, { error, file, dir })
471
479
  }
472
480
  })
481
+ return backups
473
482
  } catch (error) {
474
483
  let code
475
484
  if (error == null || ((code = error.code) !== 'ENOENT' && code !== 'ENOTDIR')) {
476
485
  throw error
477
486
  }
478
487
  }
488
+ }
489
+
490
+ // use _ to mark this method as private by convention
491
+ // since we decorate it with synchronized.withKey in the constructor
492
+ // and # function are not writeable.
493
+ //
494
+ // read the list of backup of a Vm from cache
495
+ // if cache is missing or broken => regenerate it and return
496
+
497
+ async _readCacheListVmBackups(vmUuid) {
498
+ const dir = `${BACKUP_DIR}/${vmUuid}`
499
+ const path = `${dir}/cache.json.gz`
500
+
501
+ try {
502
+ const gzipped = await this.handler.readFile(path)
503
+ const text = await fromCallback(zlib.gunzip, gzipped)
504
+ return JSON.parse(text)
505
+ } catch (error) {
506
+ if (error.code !== 'ENOENT') {
507
+ warn('Cache file was unreadable', { vmUuid, error })
508
+ }
509
+ }
510
+
511
+ // nothing cached, or cache unreadable => regenerate it
512
+ const backups = await this.#getCachabledDataListVmBackups(dir)
513
+ if (backups === undefined) {
514
+ return
515
+ }
516
+
517
+ // detached async action, will not reject
518
+ this.#writeVmBackupsCache(path, backups)
519
+
520
+ return backups
521
+ }
522
+
523
+ async #writeVmBackupsCache(cacheFile, backups) {
524
+ try {
525
+ const text = JSON.stringify(backups)
526
+ const zipped = await fromCallback(zlib.gzip, text)
527
+ await this.handler.writeFile(cacheFile, zipped, { flags: 'w' })
528
+ } catch (error) {
529
+ warn('writeVmBackupsCache', { cacheFile, error })
530
+ }
531
+ }
532
+
533
+ async listVmBackups(vmUuid, predicate) {
534
+ const backups = []
535
+ const cached = await this._readCacheListVmBackups(vmUuid)
536
+
537
+ if (cached === undefined) {
538
+ return []
539
+ }
540
+
541
+ Object.values(cached).forEach(metadata => {
542
+ if (predicate === undefined || predicate(metadata)) {
543
+ backups.push(metadata)
544
+ }
545
+ })
479
546
 
480
547
  return backups.sort(compareTimestamp)
481
548
  }
@@ -531,46 +598,27 @@ class RemoteAdapter {
531
598
  })
532
599
  }
533
600
 
534
- async _createSyntheticStream(handler, paths) {
535
- let disposableVhds = []
536
-
537
- // if it's a path : open all hierarchy of parent
538
- if (typeof paths === 'string') {
539
- let vhd
540
- let vhdPath = paths
541
- do {
542
- const disposable = await openVhd(handler, vhdPath)
543
- vhd = disposable.value
544
- disposableVhds.push(disposable)
545
- vhdPath = resolveRelativeFromFile(vhdPath, vhd.header.parentUnicodeName)
546
- } while (vhd.footer.diskType !== Constants.DISK_TYPES.DYNAMIC)
547
- } else {
548
- // only open the list of path given
549
- disposableVhds = paths.map(path => openVhd(handler, path))
550
- }
551
-
601
+ // open the hierarchy of ancestors until we find a full one
602
+ async _createSyntheticStream(handler, path) {
603
+ const disposableSynthetic = await VhdSynthetic.fromVhdChain(handler, path)
552
604
  // I don't want the vhds to be disposed on return
553
605
  // but only when the stream is done ( or failed )
554
- const disposables = await Disposable.all(disposableVhds)
555
- const vhds = disposables.value
556
606
 
557
607
  let disposed = false
558
608
  const disposeOnce = async () => {
559
609
  if (!disposed) {
560
610
  disposed = true
561
-
562
611
  try {
563
- await disposables.dispose()
612
+ await disposableSynthetic.dispose()
564
613
  } catch (error) {
565
- warn('_createSyntheticStream: failed to dispose VHDs', { error })
614
+ warn('openVhd: failed to dispose VHDs', { error })
566
615
  }
567
616
  }
568
617
  }
569
-
570
- const synthetic = new VhdSynthetic(vhds)
571
- await synthetic.readHeaderAndFooter()
618
+ const synthetic = disposableSynthetic.value
572
619
  await synthetic.readBlockAllocationTable()
573
620
  const stream = await synthetic.stream()
621
+
574
622
  stream.on('end', disposeOnce)
575
623
  stream.on('close', disposeOnce)
576
624
  stream.on('error', disposeOnce)
@@ -603,7 +651,10 @@ class RemoteAdapter {
603
651
  }
604
652
 
605
653
  async readVmBackupMetadata(path) {
606
- return Object.defineProperty(JSON.parse(await this._handler.readFile(path)), '_filename', { value: path })
654
+ // _filename is a private field used to compute the backup id
655
+ //
656
+ // it's enumerable to make it cacheable
657
+ return { ...JSON.parse(await this._handler.readFile(path)), _filename: path }
607
658
  }
608
659
  }
609
660
 
package/_VmBackup.js CHANGED
@@ -45,7 +45,18 @@ const forkDeltaExport = deltaExport =>
45
45
  })
46
46
 
47
47
  class VmBackup {
48
- constructor({ config, getSnapshotNameLabel, job, remoteAdapters, remotes, schedule, settings, srs, vm }) {
48
+ constructor({
49
+ config,
50
+ getSnapshotNameLabel,
51
+ healthCheckSr,
52
+ job,
53
+ remoteAdapters,
54
+ remotes,
55
+ schedule,
56
+ settings,
57
+ srs,
58
+ vm,
59
+ }) {
49
60
  if (vm.other_config['xo:backup:job'] === job.id && 'start' in vm.blocked_operations) {
50
61
  // don't match replicated VMs created by this very job otherwise they
51
62
  // will be replicated again and again
@@ -55,7 +66,6 @@ class VmBackup {
55
66
  this.config = config
56
67
  this.job = job
57
68
  this.remoteAdapters = remoteAdapters
58
- this.remotes = remotes
59
69
  this.scheduleId = schedule.id
60
70
  this.timestamp = undefined
61
71
 
@@ -69,6 +79,7 @@ class VmBackup {
69
79
  this._fullVdisRequired = undefined
70
80
  this._getSnapshotNameLabel = getSnapshotNameLabel
71
81
  this._isDelta = job.mode === 'delta'
82
+ this._healthCheckSr = healthCheckSr
72
83
  this._jobId = job.id
73
84
  this._jobSnapshots = undefined
74
85
  this._xapi = vm.$xapi
@@ -95,7 +106,6 @@ class VmBackup {
95
106
  : [FullBackupWriter, FullReplicationWriter]
96
107
 
97
108
  const allSettings = job.settings
98
-
99
109
  Object.keys(remoteAdapters).forEach(remoteId => {
100
110
  const targetSettings = {
101
111
  ...settings,
@@ -173,7 +183,10 @@ class VmBackup {
173
183
  const settings = this._settings
174
184
 
175
185
  const doSnapshot =
176
- this._isDelta || (!settings.offlineBackup && vm.power_state === 'Running') || settings.snapshotRetention !== 0
186
+ settings.unconditionalSnapshot ||
187
+ this._isDelta ||
188
+ (!settings.offlineBackup && vm.power_state === 'Running') ||
189
+ settings.snapshotRetention !== 0
177
190
  if (doSnapshot) {
178
191
  await Task.run({ name: 'snapshot' }, async () => {
179
192
  if (!settings.bypassVdiChainsCheck) {
@@ -183,6 +196,7 @@ class VmBackup {
183
196
  const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
184
197
  ignoreNobakVdis: true,
185
198
  name_label: this._getSnapshotNameLabel(vm),
199
+ unplugVusbs: true,
186
200
  })
187
201
  this.timestamp = Date.now()
188
202
 
@@ -304,22 +318,17 @@ class VmBackup {
304
318
  }
305
319
 
306
320
  async _removeUnusedSnapshots() {
307
- const jobSettings = this.job.settings
321
+ const allSettings = this.job.settings
322
+ const baseSettings = this._baseSettings
308
323
  const baseVmRef = this._baseVm?.$ref
309
- const { config } = this
310
- const baseSettings = {
311
- ...config.defaultSettings,
312
- ...config.metadata.defaultSettings,
313
- ...jobSettings[''],
314
- }
315
324
 
316
325
  const snapshotsPerSchedule = groupBy(this._jobSnapshots, _ => _.other_config['xo:backup:schedule'])
317
326
  const xapi = this._xapi
318
327
  await asyncMap(Object.entries(snapshotsPerSchedule), ([scheduleId, snapshots]) => {
319
328
  const settings = {
320
329
  ...baseSettings,
321
- ...jobSettings[scheduleId],
322
- ...jobSettings[this.vm.uuid],
330
+ ...allSettings[scheduleId],
331
+ ...allSettings[this.vm.uuid],
323
332
  }
324
333
  return asyncMap(getOldEntries(settings.snapshotRetention, snapshots), ({ $ref }) => {
325
334
  if ($ref !== baseVmRef) {
@@ -398,6 +407,24 @@ class VmBackup {
398
407
  this._fullVdisRequired = fullVdisRequired
399
408
  }
400
409
 
410
+ async _healthCheck() {
411
+ const settings = this._settings
412
+
413
+ if (this._healthCheckSr === undefined) {
414
+ return
415
+ }
416
+
417
+ // check if current VM has tags
418
+ const { tags } = this.vm
419
+ const intersect = settings.healthCheckVmsWithTags.some(t => tags.includes(t))
420
+
421
+ if (settings.healthCheckVmsWithTags.length !== 0 && !intersect) {
422
+ return
423
+ }
424
+
425
+ await this._callWriters(writer => writer.healthCheck(this._healthCheckSr), 'writer.healthCheck()')
426
+ }
427
+
401
428
  async run($defer) {
402
429
  const settings = this._settings
403
430
  assert(
@@ -407,7 +434,9 @@ class VmBackup {
407
434
 
408
435
  await this._callWriters(async writer => {
409
436
  await writer.beforeBackup()
410
- $defer(() => writer.afterBackup())
437
+ $defer(async () => {
438
+ await writer.afterBackup()
439
+ })
411
440
  }, 'writer.beforeBackup()')
412
441
 
413
442
  await this._fetchJobSnapshots()
@@ -443,6 +472,7 @@ class VmBackup {
443
472
  await this._fetchJobSnapshots()
444
473
  await this._removeUnusedSnapshots()
445
474
  }
475
+ await this._healthCheck()
446
476
  }
447
477
  }
448
478
  exports.VmBackup = VmBackup