Compare commits

..

750 Commits

Author SHA1 Message Date
Julien Fontanet
c03a2f5812 feat(xo-web-6): initial config 2021-11-04 10:35:57 +01:00
Julien Fontanet
dbb4f34015 chore(xapi/VDI_destroy): decorate with retry.wrap()
- more efficient than creating a function at each call
- better logging
2021-11-03 23:10:58 +01:00
Julien Fontanet
8f15a4c29d feat(ISSUE_TEMPLATE/bug_report): add hypervisor version 2021-11-03 16:55:17 +01:00
Florent BEAUCHAMP
1b0a885ac3 feat(vhd-cli): use any remote for copy and compare (#5927) 2021-11-03 15:45:52 +01:00
Nicolas Raynaud
f7195bad88 fix(xo-server): fix ova multipart upload (#5976)
Introduced by 0451aaeb5c
2021-11-02 17:43:45 +01:00
Julien Fontanet
15630aee5e chore: update dev deps 2021-11-02 13:43:49 +01:00
Florent BEAUCHAMP
a950a1fe24 refactor(vhd-lib): centralize test methods (#5968) 2021-11-02 09:53:30 +01:00
Julien Fontanet
71b8e625fe chore: update issue templates (#5974) 2021-10-30 15:06:51 +02:00
Julien Fontanet
e7391675fb feat(@xen-orchestra/proxy): 0.15.2 2021-10-29 17:41:02 +02:00
Julien Fontanet
84fdd3fe4b fix(proxy/api/ndJsonStream): send header for empty iterables
Introduced by ed987e161
2021-10-29 17:05:05 +02:00
Julien Fontanet
4dc4b635f2 feat(@xen-orchestra/proxy): 0.15.1 2021-10-29 15:50:42 +02:00
Julien Fontanet
ee0c6d7f8b feat(xen-api): 0.35.1 2021-10-29 15:50:05 +02:00
Julien Fontanet
a637af395d fix(xen-api): add missing dep proxy-agent
Introduced by 2412f8b1e
2021-10-29 15:40:25 +02:00
Julien Fontanet
59fb612315 feat(@xen-orchestra/proxy): 0.15.0 2021-10-29 15:20:09 +02:00
Mathieu
59b21c7a3e feat: release 5.64 (#5971) 2021-10-29 11:40:16 +02:00
Mathieu
40f881c2ac feat: technical release (#5970) 2021-10-28 16:30:00 +02:00
Rajaa.BARHTAOUI
1d069683ca feat(xo-web/host): manage evacuation failure during host shutdown (#5966) 2021-10-28 14:23:43 +02:00
Julien Fontanet
de1d942b90 fix(xo-server/listPoolsMatchingCriteria): check{Sr,Pool}Name is not a function
Fixes xoa-support#4193

Introduced by cd8c618f0
2021-10-28 13:29:32 +02:00
Rajaa.BARHTAOUI
fc73971d63 feat(xo-server,xo-web/menu): proxy upgrade notification (#5930)
See xoa-support#4105
2021-10-28 10:52:23 +02:00
Rajaa.BARHTAOUI
eb238bf107 feat(xo-web/pool/advanced, xen-api/{get,put}Resource): introduce backup network (#5957) 2021-10-28 10:21:48 +02:00
Florent BEAUCHAMP
2412f8b1e2 feat(xen-api): add HTTP proxy support (#5958)
See #5436

Using an IP address as HTTPS proxy show this warning: `DeprecationWarning: Setting the TLS ServerName to an IP address is not permitted by RFC 6066`

The corresponding issue is there : TooTallNate/node-https-proxy-agent#127
2021-10-27 17:30:41 +02:00
Pierre Donias
0c87dee31c fix(xo-web/xoa): handle string expiration dates (#5967)
See xoa-support#4114
See xoa-support#4192

www-xo may return a string instead of a number in some rare cases
2021-10-27 16:59:59 +02:00
Mathieu
215146f663 feat(xo-web/vm/export): allow to copy the export URL (#5948) 2021-10-27 16:58:09 +02:00
Mathieu
9fe1069df0 feat(xo-web/host): format logs (#5943)
See xoa-support#4100
2021-10-27 15:41:29 +02:00
Julien Fontanet
d2c5b52bf1 feat(backups): enable merge worker by default
Related to 47f9da216

It can still be disabled in case of problems:

```toml
[backups]
disableMergeWorker = true
```
2021-10-27 09:29:50 +02:00
Pierre Donias
12153a414d fix(xo-server/{clone,copy}Vm): force is_a_template to false on the new VM (#5955)
See xoa-support#4137
2021-10-26 16:53:09 +02:00
Pierre Donias
5ec1092a83 fix(xo-server-netbox/test): perform test with a 50-character name (#5963)
See https://xcp-ng.org/forum/topic/5111
See https://netbox.readthedocs.io/en/stable/release-notes/version-2.10/#other-changes > #5011

Versions of Netbox <2.10 only allow cluster type names of length <= 50.
2021-10-26 15:55:11 +02:00
Julien Fontanet
284169a2f2 chore(vhd-lib/VhdAbstract): format with Prettier
Introduced by 7ef89d504
2021-10-25 16:12:49 +02:00
Julien Fontanet
838bfbb75f fix(backups/cleanVm): wait for merge to finish
Introduced by 9c83e70a2
2021-10-25 09:14:38 +02:00
Julien Fontanet
a448da77c9 fix(backups/cleanVm): mergeLimiter support
Introduced by 9c83e70a2
2021-10-25 09:13:58 +02:00
Rajaa.BARHTAOUI
268fb22d5f feat(xo-web/host/advanced): add button to disable/enable host (#5952) 2021-10-20 16:39:54 +02:00
Julien Fontanet
07cc4c853d fix(vhd-lib): fix block table properties & accessors
Fixes #5956

Introduced by 7ef89d504
2021-10-18 23:13:55 +02:00
Florent BEAUCHAMP
c62d727cbe feat(vhd-cli compare): compare metadata and content of two VHDs (#5920) 2021-10-18 16:21:40 +02:00
Florent BEAUCHAMP
7ef89d5043 feat(vhd-{cli,lib}): implement chunking and copy command (#5919) 2021-10-18 14:56:58 +02:00
Mathieu
9ceba1d6e8 feat(xo-web/jobs): add button to copy jobs IDs (#5951)
Useful to create a `job.runSequence` job. Follow-up of #5944.
2021-10-15 14:25:02 +02:00
Pierre Donias
e2e453985f fix(xo-web/job): properly handle array arguments (#5944)
See https://xcp-ng.org/forum/topic/5010

When creating/editing a job, properties of type `array` must not go through the
cross product builder, they must be saved as arrays.
2021-10-15 10:42:33 +02:00
Florent BEAUCHAMP
84dccd800f feat(backups): clean up other schedules snapshots (#5949)
Fixes xoa-support#4129
2021-10-14 14:44:40 +02:00
Julien Fontanet
f9734d202b chore(backups/_VmBackup): remove unused import 2021-10-14 13:51:29 +02:00
Julien Fontanet
d3cb0f4672 feat(xo-server): 5.82.4 2021-10-14 09:47:39 +02:00
Julien Fontanet
c198bbb6fa feat(@xen-orchestra/backups): 0.14.0 2021-10-14 09:45:20 +02:00
Julien Fontanet
c965a89509 feat(xo-server-netbox): 0.3.2 2021-10-14 09:43:38 +02:00
Julien Fontanet
47f9da2160 feat(backups/MixinBackupWriter): use merge worker if not disabled 2021-10-13 16:26:12 +02:00
Julien Fontanet
348a75adb4 feat(backups): merge worker implementation
This CLI must be run directly in the directory where the remote is mounted.

It's only compatible with local remote at the moment.

To start the worker:

```js
const MergeWorker = require('@xen-orchestra/backups/merge-worker/index.js')

await MergeWorker.run(remotePath)
```

To register a VM backup dir to be clean (thus merging its unused VHD), create a file in the queue directory containing the VM UUID:

```
> echo cc700fe2-724e-44a5-8663-5f8f88e05e34 > .queue/clean-vm/20211013T142401Z
```

The queue directory is available as `MergeWorker.CLEAN_VM_QUEUE`.
2021-10-13 16:25:21 +02:00
Julien Fontanet
332218a7f7 feat(backups): move merge responsability to cleanVm 2021-10-13 16:10:19 +02:00
Julien Fontanet
6d7a26d2b9 chore(backups/MixinBackupWriter): use private fields 2021-10-13 10:02:57 +02:00
Pierre Donias
d19a748f0c fix(xo-server-netbox): support older versions of Netbox (#5946)
Fixes #5898
See https://netbox.readthedocs.io/en/stable/release-notes/version-2.7/#api-choice-fields-now-use-string-values-3569
2021-10-13 09:28:46 +02:00
Julien Fontanet
9c83e70a28 feat(backups/RemoteAdapter#cleanVm): configurable merge limiter 2021-10-12 09:17:42 +02:00
Rajaa.BARHTAOUI
abcabb736b feat(xo-web/tasks): filter out short tasks with a default filter (#5941)
See xoa-support#4096
2021-10-08 16:42:16 +02:00
Julien Fontanet
0451aaeb5c fix(xo-server/vm.import): restore non-multipart upload (#5936)
See xoa-support#4085

Introduced by fdf52a3d5

Required by `xo-cli`.
2021-10-08 15:24:21 +02:00
Julien Fontanet
880c45830c fix(xo-cli): http-request-plus@0.12 has no longer default export
Introduced by 62e5ab699
2021-10-07 17:11:54 +02:00
Julien Fontanet
5fa16d2344 chore: format with Prettier 2021-10-07 14:40:41 +02:00
Julien Fontanet
9e50b5dd83 feat(proxy): logging is now dynamically configurable
It was done for xo-server in f20d5cd8d
2021-10-06 16:54:57 +02:00
Julien Fontanet
29d8753574 chore(backups/VmBackup#_selectBaseVm): add debug logs 2021-10-06 16:48:42 +02:00
Pierre Donias
f93e1e1695 feat: release 5.63.0 (#5925) 2021-09-30 15:25:34 +02:00
Pierre Donias
0eaac8fd7a feat: technical release (#5924) 2021-09-30 11:17:45 +02:00
Julien Fontanet
06c71154b9 fix(xen-api/_setHostAddressInUrl): pass params in array
Introduced in fb21e4d58
2021-09-30 10:32:12 +02:00
Julien Fontanet
0e8f314dd6 fix(xo-web/new-vm): don't send default networkConfig (#5923)
Fixes #5918
2021-09-30 09:37:12 +02:00
Florent BEAUCHAMP
f53ec8968b feat(xo-web/SortedTable): move filter and pagination to top (#5914) 2021-09-29 17:35:46 +02:00
Mathieu
919d118f21 feat(xo-web/health): filter duplicated MAC addresses by running VMs (#5917)
See xoa-support#4054
2021-09-24 17:25:42 +02:00
Mathieu
216b759df1 feat(xo-web/health): hide CR VMs duplicated MAC addresses (#5916)
See xoa-support#4054
2021-09-24 15:52:34 +02:00
Julien Fontanet
01450db71e fix(proxy/backup.run): clear error on license issue
Fixes https://xcp-ng.org/forum/topic/4901/backups-silently-fail-with-invalid-xo-proxy-license
2021-09-24 13:15:32 +02:00
Julien Fontanet
ed987e1610 fix(proxy/api/ndJsonStream): send JSON-RPC error if whole iteration failed
See https://xcp-ng.org/forum/topic/4901/backups-silently-fail-with-invalid-xo-proxy-license
2021-09-24 13:15:24 +02:00
Florent BEAUCHAMP
2773591e1f feat(xo-web): add go back to ActionButton and use it when saving a backup (#5913)
See xoa-support#2149
2021-09-24 11:38:37 +02:00
Pierre Donias
a995276d1e fix(xo-server-netbox): better handle missing uuid custom field (#5909)
Fixes #5905
See #5806
See #5834
See xoa-support#3812

- Check if `uuid` custom field has correctly been configured before synchronizing
- Delete VMs that don't have a UUID before synchronizing VMs to avoid conflicts
2021-09-22 18:08:09 +02:00
Nicolas Raynaud
ffb6a8fa3f feat(VHD import): ensure uploaded file is a VHD (#5906) 2021-09-21 16:25:50 +02:00
Pierre Donias
0966efb7f2 fix(xo-server-netbox): handle nested prefixes (#5908)
See xoa-support#4018

When assigning prefixes to VMs, always pick the smallest prefix that the IP
matches
2021-09-21 09:55:47 +02:00
Julien Fontanet
4a0a708092 feat: release 5.62.1 2021-09-17 10:04:36 +02:00
Julien Fontanet
6bf3b6f3e0 feat(xo-server): 5.82.2 2021-09-17 09:24:32 +02:00
Julien Fontanet
8f197fe266 feat(@xen-orchestra/proxy): 0.14.6 2021-09-17 09:24:05 +02:00
Julien Fontanet
e1a3f680f2 feat(xen-api): 0.34.2 2021-09-17 09:23:28 +02:00
Julien Fontanet
e89cca7e90 feat: technical release 2021-09-17 09:19:26 +02:00
Nicolas Raynaud
5bb2767d62 fix(xo-server/{disk,vm}.import): fix import of very small VMDK files (#5903) 2021-09-17 09:17:34 +02:00
Julien Fontanet
95f029e0e7 fix(xen-api/putResource): fix non-stream use case
Introduced by ea10df8a92
2021-09-14 17:42:20 +02:00
Julien Fontanet
fb21e4d585 chore(xen-api/_setHostAddressInUrl): use _roCall to fetch network ref
Introduced by a84fac1b6
2021-09-14 17:42:20 +02:00
Julien Fontanet
633805cec9 fix(xen-api/_setHostAddressInUrl): correctly fetch network ref
Introduced by a84fac1b6
2021-09-14 17:42:20 +02:00
Marc Ungeschikts
b8801d7d2a "rentention" instead of "retention" (#5904) 2021-09-14 16:30:10 +02:00
Julien Fontanet
a84fac1b6a fix(xen-api/{get,put}Resource): use provided address when possible
Fixes #5896

Introduced by ea10df8a92

Don't use the address provided by XAPI when connecting to the pool master and without a default migration network as it will unnecessarily break NATted hosts.
2021-09-14 13:52:34 +02:00
Julien Fontanet
a9de4ceb30 chore(xo-server/config.toml): explicit auth delay is per user 2021-09-12 10:55:31 +02:00
Julien Fontanet
827b55d60c fix(xo-server/config.toml): typo 2021-09-12 10:54:49 +02:00
Julien Fontanet
0e1fe76b46 chore: update dev deps 2021-09-09 13:48:15 +02:00
Julien Fontanet
097c9e8e12 feat(@xen-orchestra/proxy): 0.14.5 2021-09-07 19:02:57 +02:00
Pierre Donias
266356cb20 fix(xo-server/xapi-objects-to-xo/VM/addresses): handle newline-delimited IPs (#5897)
See xoa-support#3812
See #5860

This is related to a505cd9 which handled space delimited IPs, but apparently,
IPs can also be newline delimited depending on which Xen tools version is used.
2021-09-03 12:30:47 +02:00
Julien Fontanet
6dba39a804 fix(xo-server/vm.set): fix converting to BIOS (#5895)
Fixes xoa-support#3991
2021-09-02 14:11:39 +02:00
Olivier Lambert
3ddafa7aca fix(docs/xoa): clarify first console connection (#5894) 2021-09-01 12:51:33 +02:00
Julien Fontanet
9d8e232684 chore(xen-api): dont import promise-toolbox/retry twice
Introduced by ea10df8a9
2021-08-31 12:28:23 +02:00
Anthony Stivers
bf83c269c4 fix(xo-web/user): SSH key formatting (#5892)
Fixes #5891

Allow SSH key to be broken anywhere to avoid breaking page formatting.
2021-08-31 11:42:25 +02:00
Pierre Donias
54e47c98cc feat: release 5.62.0 (#5893) 2021-08-31 10:59:07 +02:00
Pierre Donias
118f2594ea feat: technical release (#5889) 2021-08-30 15:40:26 +02:00
Julien Fontanet
ab4fcd6ac4 fix(xen-api/{get,put}Resource): correctly fetch host
Introduced by ea10df8a9
2021-08-30 15:23:42 +02:00
Pierre Donias
ca6f345429 feat: technical release (#5888) 2021-08-30 12:08:10 +02:00
Pierre Donias
79b8e1b4e4 fix(xo-server-auth-ldap): ensure-array dependency (#5887) 2021-08-30 12:01:06 +02:00
Pierre Donias
cafa1ffa14 feat: technical release (#5886) 2021-08-30 11:01:14 +02:00
Mathieu
ea10df8a92 feat(xen-api/{get,put}Resource): use default migration network if available (#5883) 2021-08-30 00:14:31 +02:00
Julien Fontanet
85abc42100 chore(xo-web): use sass instead of node-sass
Fixes build with Node 16
2021-08-27 14:22:00 +02:00
Mathieu
4747eb4386 feat(host): display warning for eol host version (#5847)
Fixes #5840
2021-08-24 14:43:01 +02:00
tisteagle
ad9cc900b8 feat(docs/updater): add nodejs.org to required domains (#5881) 2021-08-22 16:33:16 +02:00
Pierre Donias
6cd93a7bb0 feat(xo-server-netbox): add primary IPs to VMs (#5879)
See xoa-support#3812
See #5633
2021-08-20 12:47:29 +02:00
Julien Fontanet
3338a02afb feat(fs/getSyncedHandler): returns disposable to an already synced remote
Also, no need to forget it.
2021-08-20 10:14:39 +02:00
Julien Fontanet
31cfe82224 chore: update to index-modules@0.4.3
Fixes #5877

Introduced by 030477454

This new version fixes the `--auto` mode used by `xo-web`.
2021-08-18 10:08:10 +02:00
Pierre Donias
70a191336b fix(CHANGELOG): missing PR link (#5876) 2021-08-17 10:13:22 +02:00
Julien Fontanet
030477454c chore: update deps 2021-08-17 09:59:42 +02:00
Pierre Donias
2a078d1572 fix(xo-server/host): clearHost argument needs to have a $pool property (#5875)
See xoa-support#3118
Introduced by b2a56c047c
2021-08-17 09:51:36 +02:00
Julien Fontanet
3c1f96bc69 chore: update dev deps 2021-08-16 14:10:18 +02:00
Mathieu
7d30bdc148 fix(xo-web/TabButtonLink): should not be empty on small screens (#5874) 2021-08-16 09:45:44 +02:00
Mathieu
5d42961761 feat(xo-server/network.create): allow pool admins (#5873) 2021-08-13 14:22:58 +02:00
Julien Fontanet
f20d5cd8d3 feat(xo-server): logging is now dynamically configurable 2021-08-12 17:30:56 +02:00
Julien Fontanet
f5111c0f41 fix(mixins/Config#watch): use deep equality to check changes
Because objects (and arrays) will always be new ones and thus different.
2021-08-12 17:29:57 +02:00
Pierre Donias
f5473236d0 fix(xo-web): dont warn when restoring XO config (#5872) 2021-08-12 09:52:45 +02:00
Julien Fontanet
d3cb31f1a7 feat(log/configure): filter can be an array 2021-08-11 18:09:42 +02:00
Pierre Donias
d5f5cdd27a fix(xo-server-auth-ldap): create logger inside plugin (#5864)
The plugin was wrongly expecting a logger instance to be passed on instantiation
2021-08-11 11:21:22 +02:00
Pierre Donias
656dc8fefc fix(xo-server-ldap): handle groups with no members (#5862)
See xoa-support#3906
2021-08-10 14:12:39 +02:00
Pierre Donias
a505cd9567 fix(xo-server/xapi-objects-to-xo/VM/addresses): handle old tools alias properties (#5860)
See https://xcp-ng.org/forum/topic/4810
See #5805
2021-08-10 10:22:13 +02:00
Pierre Donias
f2a860b01a feat: release 5.61.0 (#5867) 2021-07-30 16:48:13 +02:00
Pierre Donias
1a5b93de9c feat: technical release (#5866) 2021-07-30 16:31:16 +02:00
Pierre Donias
0f165b33a6 feat: technical release (#5865) 2021-07-30 15:21:49 +02:00
Pierre Donias
4f53555f09 Revert "chore(backups/DeltaReplication): unify base VM detection" (#5861)
This reverts commit 9139c5e9d6.
See https://xcp-ng.org/forum/topic/4817
2021-07-30 14:55:00 +02:00
Pierre Donias
175be44823 feat(xo-web/VM/advanced): handle pv_in_pvh virtualization mode (#5857)
And handle unknown virtualization modes by showing the raw string
2021-07-28 18:41:22 +02:00
Julien Fontanet
20a6428290 fix(xo-server/xen-servers): fix lodash/pick import
Introduced by 4b4bea5f3

Fixes #5858
2021-07-28 08:48:17 +02:00
Julien Fontanet
4b4bea5f3b chore(xo-server): log ids on xapiObjectToXo errors 2021-07-27 15:05:00 +02:00
Pierre Donias
c82f860334 feat: technical release (#5856) 2021-07-27 11:08:53 +02:00
Pierre Donias
b2a56c047c feat(xo-server/clearHost): use pool's default migration network (#5851)
Fixes #5802
See xoa-support#3118
2021-07-27 10:44:30 +02:00
Julien Fontanet
bc6afc3933 fix(xo-server): don't fail on invalid pool pattern
Fixes #5849
2021-07-27 05:13:45 +02:00
Pierre Donias
280e4b65c3 feat(xo-web/VM/{shutdown,reboot}): ask user if they want to force when no tools (#5855)
Fixes #5838
2021-07-26 17:22:31 +02:00
Julien Fontanet
c6f22f4d75 fix(backups): block start_on operation on replicated VMs (#5852) 2021-07-26 15:01:11 +02:00
Pierre Donias
4bed8eb86f feat(xo-server-netbox): optionally allow self-signed certificates (#5850)
See https://xcp-ng.org/forum/topic/4786/netbox-plugin-does-not-allow-self-signed-certificate
2021-07-23 09:53:02 +02:00
Julien Fontanet
c482f18572 chore(xo-web/vm/tab-advanced): shutdown is a valid operation 2021-07-23 09:49:32 +02:00
Mathieu
d7668acd9b feat(xo-web/sr/tab-disks): display the active vdi of the basecopy (#5826)
See xoa-support#3446
2021-07-21 09:32:24 +02:00
Julien Fontanet
05b978c568 chore: update dev deps 2021-07-20 10:20:52 +02:00
Julien Fontanet
62e5ab6990 chore: update to http-request-plus@0.12.0 2021-07-20 10:03:16 +02:00
Mathieu
12216f1463 feat(xo-web/vm): rescan ISO SRs available in console view (#5841)
See xoa-support#3896
See xoa-support#3888
See xoa-support#3909
Continuity of d7940292d0
Introduced by f3501acb64
2021-07-16 17:02:10 +02:00
Pierre Donias
cbfa13a8b4 docs(netbox): make it clear that the uuid custom field needs to be lower case (#5843)
Fixes #5831
2021-07-15 09:45:05 +02:00
Pierre Donias
03ec0cab1e feat(xo-server-netbox): add data field to Netbox API errors (#5842)
Fixes #5834
2021-07-13 17:22:51 +02:00
mathieuRA
d7940292d0 feat(xo-web/vm): rescan ISO SRs available in console view 2021-07-12 11:55:02 +02:00
Julien Fontanet
9139c5e9d6 chore(backups/DeltaReplication): unify base VM detection
Might help avoiding the *unable to find base VM* error.
2021-07-09 15:14:37 +02:00
Julien Fontanet
65e62018e6 chore(backups/importDeltaVm): dont explicitly wait for export tasks
Might be related to stuck importation issues.
2021-07-08 09:56:06 +02:00
Julien Fontanet
138a3673ce fix(xo-server/importConfig): fix this._app.clean is not a function
Fixes #5836
2021-07-05 17:57:47 +02:00
Pierre Donias
096f443b56 feat: release 5.60.0 (#5833) 2021-06-30 15:49:52 +02:00
Pierre Donias
b37f30393d feat: technical release (#5832) 2021-06-30 11:07:14 +02:00
Ronan Abhamon
f095a05c42 feat(docs/load_balancing): add doc about VM anti-affinity mode (#5830)
* feat(docs/load_balancing): add doc about VM anti-affinity mode

Signed-off-by: Ronan Abhamon <ronan.abhamon@vates.fr>

* grammar edits for anti-affinity

Co-authored-by: Jon Sands <fohdeesha@gmail.com>
2021-06-30 10:37:25 +02:00
Pierre Donias
3d15a73f1b feat(xo-web/vm/new disk): generate random name (#5828) 2021-06-28 11:26:09 +02:00
Julien Fontanet
bbd571e311 chore(xo-web/vm/tab-disks.js): format with Prettier 2021-06-28 11:25:31 +02:00
Pierre Donias
a7c554f033 feat(xo-web/snapshots): identify VM's parent snapshot (#5824)
See xoa-support#3775
2021-06-25 12:07:50 +02:00
Pierre Donias
25b4532ce3 feat: technical release (#5825) 2021-06-25 11:13:23 +02:00
Pierre Donias
a304f50a6b fix(xo-server-netbox): compare compact notations of IPv6 (#5822)
XAPI doesn't use IPv6 compact notation while Netbox automatically compacts them
on creation. Comparing those 2 notations makes XO believe that the IPs in
Netbox should be deleted and new ones should be created, even though they're
actually the same IPs. This change compacts the IPs before comparing them.
2021-06-24 17:00:07 +02:00
Pierre Donias
e75f476965 fix(xo-server-netbox): filter out devices' interfaces (#5821)
See xoa-support#3812

In Netbox, a device interface and a VM interface can have the same ID `x`,
which means that listing IPs with `assigned_object_id=x` won't only get the
VM's interface's IPs but also the device's interface's IPs. This made XO
believe that those extra IPs shouldn't exist and delete them. This change
makes sure to only grab VM interface IPs.
2021-06-23 15:27:11 +02:00
Julien Fontanet
1c31460d27 fix(xo-server/disconnectXenServer): delete pool association
This should prevent the *server is already connected* issue after reinstalling host.
2021-06-23 10:11:12 +02:00
Julien Fontanet
19db468bf0 fix(CHANGELOG.unreleased): vhd-lib
Introduced by aa4f1b834
2021-06-23 09:26:23 +02:00
Julien Fontanet
5fe05578c4 fix(xo-server/backupNg.importVmBackup): returns id of imported VM
Fixes #5820

Introduced by d9ce1b3a9.
2021-06-22 18:26:01 +02:00
Julien Fontanet
956f5a56cf feat(backups/RemoteAdapter#cleanVm): fix backup size if necessary
Fixes #5810
Fixes #5815
2021-06-22 18:16:52 +02:00
Julien Fontanet
a3f589d740 feat(@xen-orchestra/proxy): 0.14.3 2021-06-21 14:36:55 +02:00
Julien Fontanet
beef09bb6d feat(@xen-orchestra/backups): 0.11.2 2021-06-21 14:30:32 +02:00
Julien Fontanet
ff0a246c28 feat(proxy/api/ndJsonStream): handle iterable error 2021-06-21 14:26:55 +02:00
Julien Fontanet
f1459a1a52 fix(backups/VmBackup#_callWriters): writers.delete
Introduced by 56e4847b6
2021-06-21 14:26:55 +02:00
Mathieu
f3501acb64 feat(xo-web/vm/tab-disks): rescan ISO SRs (#5814)
See https://xcp-ng.org/forum/topic/4588/add-rescan-iso-sr-from-vm-menu
2021-06-18 16:15:33 +02:00
Ronan Abhamon
2238c98e95 feat(load-balancer): log vm and host names when a VM is migrated + category (density, performance, ...) (#5808)
Co-authored-by: Julien Fontanet <julien.fontanet@isonoe.net>
2021-06-18 09:49:33 +02:00
Julien Fontanet
9658d43f1f feat(xo-server-load-balancer): use @xen-orchestra/log 2021-06-18 09:44:37 +02:00
Julien Fontanet
1748a0c3e5 chore(xen-api): remove unused inject-events 2021-06-17 16:41:04 +02:00
Julien Fontanet
4463d81758 feat(@xen-orchestra/proxy): 0.14.2 2021-06-17 15:58:00 +02:00
Julien Fontanet
74221a4ab5 feat(@xen-orchestra/backups): 0.11.1 2021-06-17 15:57:10 +02:00
Julien Fontanet
0d998ed342 feat(@xen-orchestra/xapi): 0.6.4 2021-06-17 15:56:21 +02:00
Julien Fontanet
7d5a01756e feat(xen-api): 0.33.1 2021-06-17 15:55:20 +02:00
Pierre Donias
d66313406b fix(xo-web/new-vm): show correct amount of memory in summary (#5817) 2021-06-17 14:36:44 +02:00
Pierre Donias
d96a267191 docs(web-hooks): add "wait for response" and backup related doc (#5819)
See #5420
See #5360
2021-06-17 14:34:03 +02:00
Julien Fontanet
5467583bb3 fix(backups/_VmBackup#_callWriters): dont run single writer twice
Introduced by 56e4847b6

See https://xcp-ng.org/forum/topic/4659/backup-failed
2021-06-17 14:14:48 +02:00
Rajaa.BARHTAOUI
9a8138d07b fix(xo-server-perf-alert): smart mode: select only running VMs and hosts (#5811) 2021-06-17 11:56:04 +02:00
Pierre Donias
36c290ffea feat(xo-web/jobs): add host.emergencyShutdownHost to the methods list (#5818) 2021-06-17 11:55:51 +02:00
Julien Fontanet
3413bf9f64 fix(xen-api/{get,put}Resource): distinguish cancelation and connection issue (2)
Follow up of 057a1cbab
2021-06-17 10:12:09 +02:00
Julien Fontanet
3c352a3545 fix(backups/_VmBackup#_callWriters): missing writer var
Fixes #5816
2021-06-17 08:53:38 +02:00
Julien Fontanet
56e4847b6b feat(backups/_VmBackup#_callWriters): dont use generic error when only one writer 2021-06-16 10:15:10 +02:00
Julien Fontanet
033b671d0b fix(xo-server): limit number of xapiObjectToXo logs
See xoa-support#3830
2021-06-16 09:59:07 +02:00
Julien Fontanet
51f013851d feat(xen-api): limit concurrent calls to 20
Fixes xoa-support#3767

Can be changed via `callConcurrency` option.
2021-06-14 18:37:58 +02:00
Yannick Achy
dafa4ced27 feat(docs/backups): new concurrency model (#5701) 2021-06-14 16:38:29 +02:00
Pierre Donias
05fe154749 fix(xo-server/xapi): don't silently swallow errors on _callInstallationPlugin (#5809)
See xoa-support#3738

Introduced by a73acedc4d

This was done to prevent triggering an error when the pack was already
installed but a XENAPI_PLUGIN_FAILURE error can happen for other reasons
2021-06-14 16:01:02 +02:00
Nick Zana
5ddceb4660 fix(docs/from sources): change GitHub URL to use TLS (#5813) 2021-06-14 00:34:42 +02:00
Julien Fontanet
341a1b195c fix(docs): filenames in how to update self-signed cert
See xoa-support#3821
2021-06-11 17:09:23 +02:00
Julien Fontanet
29c3d1f9a6 feat(xo-web/debug): add timing 2021-06-11 10:08:14 +02:00
Rajaa.BARHTAOUI
734d4fb92b fix(xo-server#listPoolsMatchingCriteria): fix "unknown error from the peer" error (#5807)
See xoa-support#3489

Introduced by cd8c618f08
2021-06-08 17:00:45 +02:00
Julien Fontanet
057a1cbab6 feat(xen-api/{get,put}Resource): distringuish cancelation and connection issue
See xoa-support#3643
2021-06-05 01:15:36 +02:00
Pierre Donias
d44509b2cd fix(xo-server/xapi-object-to-xo/vm): handle space-delimited IP addresses (#5805)
Fixes #5801
2021-06-04 10:01:08 +02:00
Julien Fontanet
58cf69795a fix(xo-server): remove broken API methods
Introduced bybdb0ca836

These methods were linked to the legacy backups which are no longer supported.
2021-06-03 14:49:18 +02:00
Julien Fontanet
6d39512576 chore: format with Prettier
Introduced by 059843f03
2021-06-03 14:49:14 +02:00
Julien Fontanet
ec4dde86f5 fix(CHANGELOG.unreleased): add missing entries
Introduced by 1c91fb9dd
2021-06-02 16:55:45 +02:00
Nicolas Raynaud
1c91fb9dd5 feat(xo-{server,web}): improve OVA import error reporting (#5797) 2021-06-02 16:23:08 +02:00
Yannick Achy
cbd650c5ef feat(docs/troubleshooting): set xoa SSH password (#5798) 2021-06-02 09:50:29 +02:00
Julien Fontanet
c5a769cb29 fix(xo-server/glob-matcher): fix micromatch import
Introduced by 254558e9d
2021-05-31 17:36:47 +02:00
Julien Fontanet
00a7277377 feat(xo-server-sdn-controller): 1.0.5 2021-05-31 14:33:21 +02:00
BenjiReis
b8c32d41f5 fix(sdn-controller): dont assume all tunnels in private networks use the same device/vlan (#5793)
Fixes xoa-support#3771
2021-05-31 14:30:58 +02:00
Rajaa.BARHTAOUI
49c9fc79c7 feat(@vates/decorate-with): 0.1.0 (#5795) 2021-05-31 14:29:23 +02:00
Rajaa.BARHTAOUI
1284a7708e feat: release 5.59 (#5796) 2021-05-31 12:07:46 +02:00
Julien Fontanet
0dd8d15a9a fix(xo-web): use terser instead of uglify-es
Fixes https://xcp-ng.org/forum/topic/4638/yarn-build-failure

Better maintenance and support of modern ES features.
2021-05-28 15:38:25 +02:00
Julien Fontanet
90f59e954a fix(docs/from sources): clarify that Node >=14.17 is required
Related to 00beb6170
2021-05-28 15:14:28 +02:00
Julien Fontanet
03d7ec55a7 feat(decorate-with): decorateMethodsWith() 2021-05-28 12:15:22 +02:00
Julien Fontanet
1929b69145 chore(decorate-with): improve doc 2021-05-28 12:06:45 +02:00
Julien Fontanet
fbf194e4be chore(decorate-with): named function 2021-05-28 12:06:00 +02:00
Julien Fontanet
a20927343a chore: remove now unnecessary core-js deps
BREAKING CHANGE: @xen-orchestra/audit-core now requires Node >=10
2021-05-28 09:44:44 +02:00
Julien Fontanet
3b465dc09e fix: dont use deprecated fs-extra
BREAKING CHANGE: vhd-lib and xo-vmdk-to-vhd now require Node >=10
2021-05-28 09:39:51 +02:00
Julien Fontanet
fb8ca00ad1 fix: dont use deprecated event-to-promise 2021-05-28 09:34:49 +02:00
Julien Fontanet
dd7dddaa2b chore(xo-import-servers-csv): remove unmaintained tslint conf 2021-05-28 09:28:40 +02:00
Julien Fontanet
f41903c2a1 fix(xo-cli,xo-upload-ova}: dont use deprecated nice-pipe
BREAKING CHANGE: they now require Node >=10
2021-05-28 09:25:19 +02:00
Julien Fontanet
9984b5882d feat(@xen-orchestra/proxy): 0.14.1 2021-05-27 15:15:34 +02:00
Julien Fontanet
9ff20bee5a fix(proxy/package.json): fix bin and start script
Introduced by df9689854
2021-05-27 15:15:13 +02:00
Julien Fontanet
53caa11bc4 chore(proxy/package.json): remove useless main entry
This package is not a library.
2021-05-27 15:13:26 +02:00
Julien Fontanet
f6ac08567c feat(@xen-orchestra/xapi): 0.6.3 2021-05-27 15:04:13 +02:00
Julien Fontanet
040c6375c0 chore(xo-server/config.toml): remove unnecessary quotes 2021-05-27 15:00:59 +02:00
Julien Fontanet
a03266aaad feat(@xen-orchestra/proxy): 0.14.0 2021-05-27 14:28:29 +02:00
Julien Fontanet
3479064348 feat(xo-server-netbox): 0.1.1 2021-05-27 10:37:35 +02:00
Julien Fontanet
b02d823b30 fix(xo-server-netbox): fix dependencies 2021-05-27 10:37:35 +02:00
Julien Fontanet
a204b6fb3f feat(xo-server): 5.79.5 2021-05-26 17:51:07 +02:00
Rajaa.BARHTAOUI
c2450843a5 feat: technical release (#5790) 2021-05-26 16:52:20 +02:00
Julien Fontanet
00beb6170e fix(xo-server): require Node >=14.17
Fixes #5789

Better import of CommonJS modules.
2021-05-26 16:07:34 +02:00
Julien Fontanet
9f1a300d2a fix(backups): properly close streams are destroyed in case of failure
Fixes xoa-support#3753
2021-05-26 14:39:56 +02:00
Julien Fontanet
05aefa1d5c chore: update to http-request-plus@0.10.0 2021-05-25 14:35:52 +02:00
Julien Fontanet
059843f030 chore: update dev deps 2021-05-25 14:22:58 +02:00
Julien Fontanet
e202dc9851 fix(docs): use correct bin with forever-service 2021-05-23 18:53:26 +02:00
Pierre Donias
18ae664ba7 feat(xo-server-netbox): new plugin to synchronize pools with Netbox (#5783)
Fixes #5633
2021-05-21 19:39:02 +02:00
Julien Fontanet
76b563fa88 feat(xo-web/vm/console): make multiline clipboard input monospaced 2021-05-21 14:21:33 +02:00
Julien Fontanet
2553f4c161 feat(xo-web/host/install-certificate): make inputs monospaced 2021-05-21 14:20:56 +02:00
Julien Fontanet
f35c865348 feat(xo-web): SSH key input monospaced 2021-05-21 14:19:50 +02:00
Julien Fontanet
b873ba3a75 feat(xo-web): make CloudConfig inputs monospaced
Fixed #5786
2021-05-21 14:15:12 +02:00
Julien Fontanet
d49e388ea3 feat(xo-server/registerPlugin): log plugin metadata errors 2021-05-21 14:00:25 +02:00
Julien Fontanet
b931699175 feat(xo-server/registerPlugin): don't fail on JSON parsing errors 2021-05-21 14:00:06 +02:00
Julien Fontanet
55fd58efd8 fix(xo-server): reading plugin metadata
Fixes #5782
2021-05-21 13:58:32 +02:00
Julien Fontanet
773847e139 feat(xo-server,xo-proxy): add backupId to restore tasks 2021-05-21 13:50:27 +02:00
Julien Fontanet
3a52944f21 fix(docs): use correct bin with forever 2021-05-20 18:49:36 +02:00
Julien Fontanet
cc9d741275 fix(xo-server): fix plugins import
Fixes #5782 part 2

Introduced by 254558e9d
2021-05-20 12:07:00 +02:00
Julien Fontanet
f0096cf0e2 chore(xo-server): remove useless imports
Introduced by 254558e9d
2021-05-20 10:21:26 +02:00
Julien Fontanet
1d673bf6ff chore(xo-server): remove useless entry point
Introduced by 254558e9d

Due to ESM, it's no longer easy to alter `DEBUG` before all instances of `debug` are loaded, which makes it useless.
2021-05-20 10:16:23 +02:00
Julien Fontanet
d986f00b6a chore(xo-server): remove rimraf dev dep 2021-05-19 17:43:12 +02:00
Julien Fontanet
01c3ca4f37 chore(proxy): remove unused dev dep rimraf
Introduced by df9689854
2021-05-19 17:36:26 +02:00
Julien Fontanet
497bd7dad5 fix(xo-server): fix executables
Fixes #5782

Remove `bin` dir in favor of explicit listing, this allows to use ESM with executables without extensions.
2021-05-19 17:33:30 +02:00
Julien Fontanet
1d6a0ae8f1 chore(lint): apply overrides to .cjs and .mjs files 2021-05-19 17:29:09 +02:00
Julien Fontanet
c5e6b5ec7a chore(xo-server/recover-account): remove unused import
Introduced by 254558e9d
2021-05-19 17:28:41 +02:00
Julien Fontanet
ca26b4b30d chore(xo-server): remove unused run-vhd-test 2021-05-19 17:17:42 +02:00
Julien Fontanet
254558e9de chore(xo-server): convert to ESM 2021-05-19 15:53:21 +02:00
Julien Fontanet
da0cd0b99c chore: update to limit-concurrency-decorator@0.5.0 2021-05-19 15:08:53 +02:00
Julien Fontanet
2e49c685cc chore(emit-async): remove build step
It also helps with compatibility with Native ESM for default exports.
2021-05-19 15:00:59 +02:00
Julien Fontanet
a64af4da7c chore(defined): remove build step
It also helps with compatibility with Native ESM for default exports.
2021-05-19 12:07:18 +02:00
Julien Fontanet
68bb2fa7f0 feat(xo-collection): named instead of default exports
Behave better with Babel and native ESM.
2021-05-19 10:58:22 +02:00
Julien Fontanet
8bc2710380 chore(xo-collection/view.example): fix lint error 2021-05-19 10:51:57 +02:00
Julien Fontanet
1691e7ad83 chore(xo-collection): event-to-promise → promise-toolbox/fromEvent 2021-05-19 10:51:08 +02:00
Julien Fontanet
6c2cb31923 fix(proxy/api): fix JsonRpcWebSocketClient import
Introduced by 84b3162bc
2021-05-18 22:11:13 +02:00
Julien Fontanet
0c6d920682 chore(log): remove build step
It also helps with compatibility with native ESM for default exports.
2021-05-18 21:24:42 +02:00
Pierre Donias
a126b5b61b feat(xo-server-auth-saml): use registerUser2 (#5781) 2021-05-18 11:28:49 +02:00
Pierre Donias
dadb16bb04 feat(xen-api): ability to connect using a session ID (#5763) 2021-05-18 11:21:39 +02:00
Pierre Donias
f29473ef4c fix(xo-server/isHostServerTimeConsistent): change host permission from administrate to view (#5780) 2021-05-18 10:22:24 +02:00
Julien Fontanet
84b3162bcd fix(proxy/api): fix JsonRpcWebSocketClient import
Introduced by df9689854
2021-05-17 16:45:27 +02:00
Julien Fontanet
c7f1469e1f fix(proxy/backup.run): handle multiple self licenses
See xoa-support#3730

Previous code would fail if the first license returned was already expired.
2021-05-16 16:51:32 +02:00
Julien Fontanet
d1dfd93e15 feat(xen-api): 0.32.0 2021-05-12 17:57:06 +02:00
Julien Fontanet
4ef55b8d1f feat(xen-api): reverseHostIpAddresses option
See xoa-support#3727

When enabled, will attempt to get a FQDN from the host address returned by XAPI when using `getResource()` or `putResource()`.
2021-05-12 12:18:05 +02:00
Yannick Achy
7da22094f3 feat(docs/proxy): SSH connection and second nic (#5777) 2021-05-12 09:03:44 +02:00
Julien Fontanet
cf45cb56ad feat(npmignore): ignore /coverage/ 2021-05-11 09:04:35 +02:00
Julien Fontanet
df96898543 chore(proxy): convert to ESM 2021-05-10 23:23:37 +02:00
Julien Fontanet
a58bf66dea feat(scripts/travis-tests): handle .[cm]js files 2021-05-10 23:21:10 +02:00
Julien Fontanet
0f1fc0cc79 chore(proxy): remove rimraf dev dep 2021-05-10 18:17:40 +02:00
Julien Fontanet
dc41f60f52 feat(scripts/lint-staged): handle .[cm]js files 2021-05-10 14:50:19 +02:00
Julien Fontanet
3d21afb640 feat(package.json/scripts/prettify): handle cjs files 2021-05-10 14:48:32 +02:00
Julien Fontanet
79c3667fd4 fix(xo-server/api): never log pool.listMissingPatches or hosts.stats 2021-05-10 11:35:17 +02:00
Julien Fontanet
ab1549f60e feat(@xen-orchestra/backups-cli): 0.6.0 2021-05-08 10:44:49 +02:00
Julien Fontanet
5d32fa36ff feat(backups/_VmBackup#_callWriters): clearer error message
See xoa-support#3709
2021-05-08 10:43:39 +02:00
badrAZ
8ac17ab6e3 fix(xo-server): log missing pools (#5768)
Fixes #2844
2021-05-07 16:35:48 +02:00
badrAZ
2076141f47 feat(xo-web): add warning on restoring metadata backup (#5769)
See xoa-support#3691
2021-05-07 13:47:47 +02:00
badrAZ
6d0f479f81 fix(xo-server-backup-reports): don't take into account ignored tasks (#5770) 2021-05-07 11:09:38 +02:00
Julien Fontanet
f56a5a3de1 fix(xo-server/xapiObjectToXo/link): don't fail on array with missing objects
Fixes xoa-support#3691
2021-05-07 09:33:12 +02:00
Julien Fontanet
d0c34fd760 fix(CHANGELOG): update latest badge
Introduced by 9e7afd67b
2021-05-06 18:52:06 +02:00
Julien Fontanet
9e7afd67bc feat: release 5.58.1 2021-05-06 16:17:41 +02:00
Julien Fontanet
964810858b fix(fs/fs.spec): remove .only modifiers
Introduced by 48af5c7ed
2021-05-06 16:17:05 +02:00
Julien Fontanet
7a51361099 fix(CHANGELOG): typo
Introduced in e6f8fd923
2021-05-06 16:16:58 +02:00
Julien Fontanet
ec2e71a22f feat(CHANGELOG.unreleased): add better handling of remotes' errors
Introduced in 5b188f35b
2021-05-06 16:09:45 +02:00
Julien Fontanet
5b188f35b5 fix(backups/_VmBackup): better handling of writers' failures
- always wait for writers to finish their action
- log all writers' failures
- only interrupt process if all writers have failed
2021-05-05 14:32:39 +02:00
Julien Fontanet
5683571577 fix(xo-server): revert to schema-inspector@1
Fixes https://xcp-ng.org/forum/topic/4556/can-t-edit-xo-metatata-backup-config

See  schema-inspector/schema-inspector#119
2021-05-05 10:10:03 +02:00
badrAZ
db75568905 feat(backups/writers#beforeBackup): continue interrupted merges 2021-05-05 09:57:05 +02:00
badrAZ
5517305973 feat(backups/RemoteAdapter#cleanVm): optional lock 2021-05-05 09:57:05 +02:00
badrAZ
57ef531be0 feat(backups/cleanVm): detection of interrupted merges 2021-05-05 09:57:05 +02:00
Julien Fontanet
b590e29608 feat(@vates/parse-duration): 0.1.1 2021-05-05 09:51:44 +02:00
Julien Fontanet
569d575a96 fix(parse-duration): ISC license
Unrelated to XO code.
2021-05-05 09:49:50 +02:00
Julien Fontanet
dd8bf3776e fix(parse-duration): show original value in error message 2021-05-05 09:48:30 +02:00
Julien Fontanet
d4ea9c8892 fix(backups/_VmBackup#_selectBaseVm): typo
Fixes #5766

Introduced in 1d1bf504d
2021-05-04 16:39:32 +02:00
Julien Fontanet
793c6b4a5a chore(backups/_VmBackup#_copyDelta): remove useless check
All delta writers now have a `prepare()` method since e0d6b501c
2021-05-04 11:56:12 +02:00
Julien Fontanet
917c9dabc7 chore(backups/_VmBackup#copy{Delta,Full}): don't log writer errors
These errors are already logged in tasks.
2021-05-04 11:47:54 +02:00
Julien Fontanet
1d1bf504de chore(backups/VmBackup): make _writers a set
It will be easier to remove some writers in case of error.
2021-05-04 11:43:58 +02:00
Julien Fontanet
d0c07e1e97 chore: update promise-toolbox to 0.19.2 2021-05-03 15:41:53 +02:00
Julien Fontanet
dfff520259 fix(proxy/api): backup.{importVm,restoreMetadata}Backup
Fixes xoa-support#3688

Issue with `Disposable.use()` when returning an iterator like `runWithLogs()`.

Fixes by `promise-toolbox@0.19.2`.
2021-05-03 15:27:40 +02:00
Julien Fontanet
bb928bbd73 fix(backups/RemoteAdapter#cleanVm): don't fail if no vdis dir
Detected in #5756

Necessary to handle VMs with only full backups.
2021-05-02 11:22:01 +02:00
Julien Fontanet
f86ec98e05 fix(fs/list): ignoreMissing option
Introduced by 48af5c7ed

I messed up while renaming the option.
2021-05-02 11:22:01 +02:00
badrAZ
48af5c7ed6 feat(fs/abstract#list): ignore ENOENT error 2021-05-02 10:22:16 +02:00
Julien Fontanet
cfaf336597 feat(@xen-orchestra/proxy): 0.13.0 2021-04-30 23:11:25 +02:00
Julien Fontanet
b52345236d chore(fs): remove unused deps 2021-04-30 23:10:19 +02:00
Julien Fontanet
87ebaf62c1 fix(openflow): fix incorrect dev dep 2021-04-30 23:10:11 +02:00
Julien Fontanet
c7721d6100 feat(xo-server): 5.79.2 2021-04-30 22:53:05 +02:00
Julien Fontanet
40a722a7ff feat(@xen-orchestra/fs): 0.16.1 2021-04-30 22:52:25 +02:00
Julien Fontanet
d41fbb9216 fix(fs/_outputStream): validator should receive tmp path 2021-04-30 22:51:21 +02:00
Julien Fontanet
8bee0925d0 chore(fs/outputStream): remove incorrect await 2021-04-30 22:45:53 +02:00
Julien Fontanet
b8edca53cb feat: release 5.58.0 2021-04-30 22:28:17 +02:00
Julien Fontanet
34a13dd293 feat(xo-server): 5.79.1 2021-04-30 22:23:51 +02:00
Julien Fontanet
f72e582a80 feat(@xen-orchestra/backups): 0.10.1 2021-04-30 22:23:22 +02:00
Julien Fontanet
6da2865781 feat(@xen-orchestra/fs): 0.16.0 2021-04-30 22:22:19 +02:00
Julien Fontanet
a0ea12cf6c feat(CHANGELOG.unreleased): add S3 fix 2021-04-30 22:18:45 +02:00
Julien Fontanet
317bfde574 fix(fs/S3#_mkdir): throw ENOTDIR if file exists 2021-04-30 22:16:51 +02:00
Julien Fontanet
5f53ebdf12 chore(fs/S3#_rmdir): use _isNotEmptyDir 2021-04-30 22:16:51 +02:00
Julien Fontanet
cb835b7b6a fix(fs/S3#_unlink): throw EISDIR if dir
This fix `rmtree()`.
2021-04-30 22:16:51 +02:00
Julien Fontanet
bf76787e49 fix(fs/S3#_createReadStream): throw ENOENT if file doesn't exist 2021-04-30 22:16:51 +02:00
Julien Fontanet
15a4f7e273 fix(fs/S3): basic rmdir implementation 2021-04-30 22:16:51 +02:00
Julien Fontanet
dc3e5ffa4b chore(backups/RemoteAdapter#outputStream): use fs/outputStream
`createOutputStream` is deprecated and does not work with S3 remote.
2021-04-30 22:16:51 +02:00
Julien Fontanet
b84c7cc2bb feat(fs/outputStream): validator support 2021-04-30 22:16:51 +02:00
Julien Fontanet
049717260d chore(fs/outputStream): JsDoc 2021-04-30 19:50:00 +02:00
Julien Fontanet
a50a96de82 feat(fs/outputStream): remove support for promise input 2021-04-30 19:42:10 +02:00
Julien Fontanet
8ff8c0d176 chore(fs/outputStream): remove input.task handling
This should be handled at a higher level, not in this lib.
2021-04-30 19:38:31 +02:00
Julien Fontanet
a29b63c7d1 chore(fs/outputStream): move checksum handling to public wrapper 2021-04-30 19:31:56 +02:00
Julien Fontanet
a8400c77fb feat(fs/Abstract#outputStream): use stream.pipeline()
BREAKING CHANGE: requires Node >=14

- properly detect both input and output errors
- properly destroy streams in case of errors
2021-04-30 18:42:45 +02:00
Julien Fontanet
e1c40bd218 fix(fs/S3#mkdir): noop implementation 2021-04-30 18:26:50 +02:00
Julien Fontanet
757224683f chore(xo-server-audit): remove unused dep 2021-04-30 12:30:49 +02:00
Julien Fontanet
95d982f3f3 chore(xo-server-transport-icinga2): remove unused dep 2021-04-30 12:30:39 +02:00
Julien Fontanet
7bfdfe5e41 chore(xapi): remove unused dep 2021-04-30 12:10:14 +02:00
Julien Fontanet
8888b1a89a fix(proxy): add missing dep 2021-04-30 12:10:04 +02:00
Julien Fontanet
c6ba48be10 chore(proxy): remove unused deps 2021-04-30 12:09:51 +02:00
Julien Fontanet
f132c4b5d1 chore(log): remove unused dev dep 2021-04-30 12:08:03 +02:00
Julien Fontanet
87f5a8f6f2 chore(backups-cli): remove unused dep 2021-04-30 12:06:51 +02:00
Julien Fontanet
de500af30d fix(backups): add missing dep 2021-04-30 12:06:40 +02:00
Julien Fontanet
8b5607ac89 chore(audit-core): remove unused dep 2021-04-30 12:04:42 +02:00
Julien Fontanet
22727f68c1 fix(audit-core): fix incorrect dev dep 2021-04-30 12:04:30 +02:00
Julien Fontanet
ba64f8e5b5 fix(disposable): add missing dep 2021-04-30 12:02:39 +02:00
Julien Fontanet
b3bde5857e chore(xo-vmdk-to-vhd): remove unused dev dep 2021-04-30 12:01:29 +02:00
Julien Fontanet
6e36a21d18 chore(xo-server-web-hooks): remove unused deps 2021-04-30 12:01:07 +02:00
Julien Fontanet
968ebeb5a3 chore(xo-import-servers-csv): remove unused deps 2021-04-30 11:59:45 +02:00
Julien Fontanet
47e11652fb chore(vhd-lib): remove unused dev dep 2021-04-30 11:53:26 +02:00
Julien Fontanet
84019ed4e7 chore(vhd-cli): remove unused dep 2021-04-30 11:53:14 +02:00
Julien Fontanet
37befd89e7 chore(xo-server): remove unused deps 2021-04-30 11:48:28 +02:00
badrAZ
aa4f1b834a feat(vhd-lib/mergeVhd): continuable (#5749) 2021-04-30 09:18:21 +02:00
Rajaa.BARHTAOUI
e6f8fd9234 feat: technical release (#5761) 2021-04-29 10:40:55 +02:00
Rajaa.BARHTAOUI
86904892f2 fix(xo-server-perf-alert): fix 'Invalid parameters' error (#5755)
Introduced by 7c9850ada
2021-04-29 09:48:05 +02:00
badrAZ
d176dd6533 fix(xo-server-test/backupNg): remove obsolete snapshots (#5760) 2021-04-29 09:38:51 +02:00
badrAZ
283efe0eac fix(backups/cleanVm): pass handler to mergeVhdChain (#5758)
Introduced by 20f4c952fe
2021-04-28 18:21:23 +02:00
badrAZ
0e361cb105 fix(backups/cleanVm): correctly wait VHD deletions (#5757)
Introduced by c955da9bc6
2021-04-28 18:20:01 +02:00
Julien Fontanet
53aeb085ac fix(backups/MixinBackupWriter): ensure dir exist before locking 2021-04-28 17:52:46 +02:00
Rajaa.BARHTAOUI
cd8c618f08 feat(xo-server/pool.listPoolsMatchingCriteria): new API method (#5715)
See xoa-support#3489
2021-04-28 15:48:22 +02:00
Julien Fontanet
18b74d9797 fix(backups/RemoteAdapter#cleanVm): correctly rename/remove VHDs after merge 2021-04-28 15:06:22 +02:00
Ronan Abhamon
4008934bbb feat(load-balancer): improve migration (perf mode) regarding memory and cpu usage
- ensure we optimize CPU first instead of free memory
- use low threshold now to forbid bad migration based on cpu usage
- add a tolerance on the VM CPU usage to migrate VM with the most memory used
- do not migrate if we create an unbalanced configuration (only if high tresholds are not reached)
- change factors to take into account the new algorithm
2021-04-28 14:22:30 +02:00
Ronan Abhamon
8ae432554e fix(load-balancer): memory free limit must be expressed in B instead of KiB (bad calculations otherwise) 2021-04-28 14:22:30 +02:00
Ronan Abhamon
337b26176a fix(load-balancer): ensure anti-affinity tag array is always defined 2021-04-28 14:22:30 +02:00
Julien Fontanet
2e643fce28 fix(backups/MixinBackupWriter): clean VM dir after backup
Otherwise, it might trigger a chain reaction which will force all VDIs to be fully exported:

1. a single VDI chain is corrupted
2. it gets removed
3. the linked backups are removed
4. all other VDIs are now unused and are removed as well
5. all VDIs must now be fully exported
2021-04-28 13:20:56 +02:00
Julien Fontanet
5edd271975 fix(backups/RemoteAdapter#cleanVms): restore action logs
Introduced by 20f4c952fe

They are necessary because `cleanVms` can run in diagnostic or cleaning mode and the difference must be visible in logs.
2021-04-28 13:07:29 +02:00
Nicolas Raynaud
c219ea06bf feat(backup/s3): add http and region parameters to S3 (#5658) 2021-04-28 11:30:23 +02:00
badrAZ
ffacc0d8d0 fix(xo-server-test/backupNg): follow the new backup implementation (#5732) 2021-04-28 11:23:12 +02:00
Julien Fontanet
70fff77a28 fix(backups/_MixinBackupWriter): warn issues detected in cleanVm
`debug` is not good enough because not shown by default.
2021-04-28 10:43:48 +02:00
Rajaa.BARHTAOUI
bcc52d586e fix(xo-server-perf-alert): fix "required property uuids is not defined" warning (#5752)
See https://github.com/vatesfr/xen-orchestra/pull/5692#discussion_r611984364
2021-04-27 22:46:27 +02:00
Mathieu
521ded5079 feat(xo-web/host/network): identify management network (#5743)
Fixes #5731
2021-04-27 14:50:05 +02:00
Pierre Donias
73b6b59ec9 fix(xen-api/_sessionOpen): prevent deadlock (#5751)
Dead lock loop:
- `_sessionOpen`
- `getAllRecords`
- `_roCall`
- `_sessionCall` → `onRetry: _sessionOpen`

This triggers a dead lock because `_sessionOpen`'s calls are coalesced. Without `coalesceCalls`, this would be an infinite loop instead.
2021-04-27 14:00:00 +02:00
badrAZ
157c81b0e9 fix(@xen-orchestra/xapi#VM_import): ensure onVmCreation is called (#5747)
It was not called if the import task was not received (for instance because the import was very fast).
2021-04-26 17:29:14 +02:00
Rajaa.BARHTAOUI
233096354c feat(xo-web/xoa): notify user when proxies need to be upgraded (#5717)
See xoa-support#3597
2021-04-26 16:38:59 +02:00
Julien Fontanet
01ac23162f fix(xapi/watchObject): dont break potential promise chain 2021-04-26 16:12:30 +02:00
Julien Fontanet
4e3628c6fb fix(xapi/watchObject): correctly register generic watcher 2021-04-26 16:12:00 +02:00
Julien Fontanet
d6bea8aed8 feat(xapi/waitObject): simpler API
Align the API of `watchObject`, take a callback as param and return a function to stop waiting.
2021-04-26 15:30:45 +02:00
Julien Fontanet
a254097092 feat(xapi/watchObject): split from waitObject 2021-04-26 15:26:06 +02:00
Julien Fontanet
b2a3d224a5 feat(xapi/waitObject): make public 2021-04-26 14:29:52 +02:00
Julien Fontanet
b495c2b60b fix(xo-server/Xapi#importDeltaVm): remove transferSize in result
Not necessary and broken since bdb0ca836
2021-04-26 14:27:11 +02:00
Julien Fontanet
452f76cbef fix(xo-server/xapi): remove _waitObject
It was shadowing the parent implementation.
2021-04-26 14:23:43 +02:00
Julien Fontanet
3a0690bfee chore(proxy/api): dont access to stream private state 2021-04-26 11:44:55 +02:00
Julien Fontanet
29fd2ff5e9 feat(backups): lock VM dir during backup (#5746)
May fix xoa-support#3387
2021-04-26 09:23:20 +02:00
Julien Fontanet
a344b3b76d feat(xapi/_waitObject): cancelation support
Related to #5747
2021-04-25 16:01:32 +02:00
Julien Fontanet
14cf955cb9 chore(xapi): use extensions for file imports
Will be necessary for ESM.
2021-04-25 14:40:06 +02:00
badrAZ
31193d5b40 fix(xo-server/backup-ng#deleteVmBackupNg): pass remote obj to deleteVmBackup (#5744) 2021-04-23 16:34:23 +02:00
Julien Fontanet
d6dc63c491 chore(CHANGELOG.unreleased): format with Prettier 2021-04-23 16:04:38 +02:00
Julien Fontanet
263f693542 chore(xen-api): remove unused memory test 2021-04-23 14:59:02 +02:00
Julien Fontanet
3f42199f8f feat(normalize-packages): dont use files field
A centralized npmignore is easier to use and maintain.
2021-04-23 14:47:34 +02:00
Julien Fontanet
251ccd2e38 chore(npmignore): dont publish docs directories 2021-04-23 14:47:34 +02:00
Julien Fontanet
82ccf5886e chore(npmignore): dont publish hidden files 2021-04-23 14:47:34 +02:00
Julien Fontanet
6acb1e3853 chore(eslint): only use @babel/eslint-parser for pkgs using Babel 2021-04-23 14:47:34 +02:00
Mathieu
8c0238e98f feat(xo-server/pif.reconfigureIp): reconfigure on host if management (#5745)
Fixes #5730
2021-04-23 14:07:18 +02:00
Mathieu
e7779c3d55 feat(xo-server/template): ability to create a template from snapshot (#5736)
Fixes #4891
2021-04-23 10:52:35 +02:00
Julien Fontanet
bdb0ca836c feat(xo-server): remove legacy backups (#5735)
BREAKING: all `backup.*` API methods removed
2021-04-23 09:40:46 +02:00
Rajaa.BARHTAOUI
53038a0372 feat(xo-web): remove legacy backups (#5718) 2021-04-23 09:39:12 +02:00
Julien Fontanet
1b0eb91d58 chore(backups/writers): remove unnecessary index 2021-04-22 14:22:03 +02:00
Julien Fontanet
5814ba38ac chore(ackups,proxy,xo-server): use extensions for file imports
Follow-up on 7f570c074, 5171378be and b2ec0d288

Will be necessary for ESM.
2021-04-22 13:43:57 +02:00
Julien Fontanet
b2ec0d288b chore(xo-server): use extensions for file imports
Will be necessary for ESM.
2021-04-22 13:24:06 +02:00
Julien Fontanet
5171378bea chore(proxy): use extensions for file imports
Will be necessary for ESM.
2021-04-22 13:16:47 +02:00
Julien Fontanet
7f570c074b chore(backups): use extensions for file imports
Will be necessary for ESM.
2021-04-22 13:12:14 +02:00
Julien Fontanet
dac675143f chore(proxy): backups/index.js → backups.js 2021-04-22 13:10:30 +02:00
Julien Fontanet
72a5f0e220 chore: use decorateWith instead of defer decorator syntax
`golike-defer` built-in decorator syntax will be removed in future versions.
2021-04-21 17:47:40 +02:00
Julien Fontanet
375aaa8430 chore: dont use default export from golike-defer
- will be removed in future version
- not compatible with ESM implementation in Node
2021-04-21 17:20:16 +02:00
Julien Fontanet
4c704a8a3a chore(proxy/appliance): dont import log from dist/ 2021-04-21 16:59:50 +02:00
Julien Fontanet
78c0f2c7e9 chore: remove Flow
It was not used nor maintained by XO devs, and was causing issues with editors.

JSDoc or TypeScript should be used instead.
2021-04-21 16:55:03 +02:00
badrAZ
c262dd06e6 fix(@xen-orchestra/backups/isValidXva): move as RemoteAdapter method (#5741) 2021-04-21 16:27:13 +02:00
badrAZ
e0d6b501c7 feat(@xen-orchestra/backups): clean VM backups on run (#5727) 2021-04-21 13:27:33 +02:00
Julien Fontanet
efc3f45ef6 feat(babel-config): use top level targets option
See https://babeljs.io/blog/2021/02/22/7.13.0#top-level-targets-option-12189httpsgithubcombabelbabelpull12189-rfchttpsgithubcombabelrfcspull2
2021-04-20 16:24:44 +02:00
Julien Fontanet
24d8ef25bb feat(backups/VmBackup#run): assert offlineBackup not with snapshotRetention
See #5740
2021-04-20 15:03:17 +02:00
Julien Fontanet
2aca775907 fix(backups/VmBackup#_snapshot): dont fail on !offlineBackup && !snapshotRetention
Introduced by 7aa10ef4be
2021-04-20 14:59:18 +02:00
badrAZ
7aa10ef4be fix(backups): don't snapshot in case of offline backup (#5739)
Introduced by 0811da9014
2021-04-20 11:01:39 +02:00
Julien Fontanet
17ad622ce3 chore: update dev deps 2021-04-20 10:58:25 +02:00
Julien Fontanet
cc7431a092 chore(xo-server-test): update jest to 24.6.3 2021-04-20 10:51:57 +02:00
Julien Fontanet
4199d02d98 chore(xo-server-{auth-saml,transport-nagios}): remove unused dep babel-preset-env 2021-04-20 10:44:02 +02:00
badrAZ
8c434760fb fix(@xen-orchestra/backups/_cleanVm): don't resolve paths relatively to cwd (#5738) 2021-04-20 10:35:28 +02:00
Julien Fontanet
5f63b99dc8 feat(backups/_backupWorker): log global errors 2021-04-19 20:13:57 +02:00
Julien Fontanet
edd0ae4c59 fix(xapi/VM_snapshot): correctly delete broken snapshot
Introduced by 6b1c30157
2021-04-19 18:35:05 +02:00
Pierre Donias
3944e6450d feat(fs/nfs): remove vers=3 default option (#5725) 2021-04-19 15:29:17 +02:00
Julien Fontanet
a8e5ad42ba chore(xo-web): migrate to babel 7
Fix linting.
2021-04-19 15:18:09 +02:00
Julien Fontanet
d3bfb0b87b fix(xapi/VM_destroy): ensure all VDIs deletion errors are caught/logged
Related to 6b1c30157
2021-04-19 10:45:46 +02:00
Pierre Donias
75e3e36aa8 feat(xo-web/new VM): only send memory param so that it doesn't enable DMC (#5729)
Fixes xoa-support#3591
See 70d1537ecc

- If only "RAM" field is filled: only send `memory` param
- If any of the advanced memory fields are filled:
  - only send those
  - if "Dynamic memory max" field is empty, use the "RAM" field value for
  `memoryDynamicMax` param
2021-04-19 10:16:56 +02:00
Julien Fontanet
9102b4aa1b fix(fs): coalesce calls to sync/forget (#4770)
Might help with xoa-support#3637

It does not makes sense to call them multiple times and can create issues.
2021-04-17 14:55:21 +02:00
badrAZ
e744d90dbb fix(xo-server/backups-ng): continue execution when VM/SR is missing (#5733)
Introduced by 60ecfbfb8e
2021-04-16 23:33:20 +02:00
badrAZ
c38b957d7c fix(xo-{server,proxy}/config): add copyRetention default value (#5737)
Introduced in xo-server by 0811da901
2021-04-16 14:56:43 +02:00
Julien Fontanet
282bb26da9 chore(xapi/VM_{destroy,snapshot}): delete → destroy
Introduced by 6b1c30157
2021-04-16 10:35:48 +02:00
Julien Fontanet
6b1c30157f feat(xapi/VM_{destroy,snapshot}): warn instead of ignoring errors 2021-04-16 10:32:04 +02:00
Julien Fontanet
e433251420 fix(xo-server/recover-account): pass config as named param
Introduced by 7024c7d59
2021-04-15 15:52:56 +02:00
Julien Fontanet
49ed9c7f7f fix(xo-server/api): fix config name entry verboseApiLogsOnErrors 2021-04-15 13:34:05 +02:00
Julien Fontanet
5a5c0326b7 fix(xapi/VM_destroy): correctly check *other* VM is not control domain 2021-04-15 11:52:56 +02:00
Julien Fontanet
a25708be2b fix(xapi/VM_create): default actions_after_{crash,reboot} is restart
See https://xapi-project.github.io/xen-api/classes/vm.html

`reboot` is not valid.
2021-04-15 11:48:40 +02:00
Julien Fontanet
e8f2934534 feat(xo-server/getBackupNgLogs): expose proxyId
Follow up on b454b4dff
2021-04-15 11:43:34 +02:00
badrAZ
37f8ac9da9 fix(fs/LocalHandler#_lock): correctly resolve path (#5726) 2021-04-14 15:59:11 +02:00
badrAZ
0ded95ce48 fix(xo-server/backup-ng): add slash between backup and remote ids (#5723)
This is symmetric to the parsing: 052aafd7cb/packages/xo-server/src/xo-mixins/backups-ng/index.js (L88-L94)
2021-04-14 14:43:28 +02:00
Julien Fontanet
108e769833 fix(CHANGELOG.unreleased): @xen-orchestra/xapi
Introduced by 864946477
2021-04-14 11:46:12 +02:00
Julien Fontanet
5b2313ee56 feat(xapi): warn on retry 2021-04-14 11:10:20 +02:00
Julien Fontanet
368b84b7ff chore(xapi/VDI_destroy): move retry condition in constructor 2021-04-14 10:30:11 +02:00
Julien Fontanet
864946477b fix(xapi/VDI_destroy): respect vdiDestroyRetryWhenInUse option 2021-04-14 10:23:53 +02:00
Julien Fontanet
da67298b43 chore: update promise-toolbox to 0.19.0 2021-04-14 00:12:34 +02:00
Julien Fontanet
db5cb8b3a9 chore(disposables): using → Disposable.use 2021-04-13 23:35:10 +02:00
Julien Fontanet
9643292be6 fix(babel): dont ignore test files when linting 2021-04-13 18:09:40 +02:00
Julien Fontanet
a651e34206 fix(xo-server/math): fix ESLint directive 2021-04-13 18:09:40 +02:00
Julien Fontanet
a4e7fd3209 feat(xo-server): use @xen-orchestra/mixins/Config 2021-04-13 18:09:40 +02:00
Julien Fontanet
d1113d40aa chore(mixins): use PascalCase as they are classes 2021-04-13 18:09:40 +02:00
Julien Fontanet
dcd834d3e4 chore(xo-server/xo-mixins): xo → app
- already used in some mixins
- used in xo-proxy
2021-04-13 18:09:40 +02:00
badrAZ
c0be8a2c04 fix(@xen-orchestra/backups/_cleanVm): VHDs not correctly listed (#5720)
Introduced by 20f4c95
2021-04-13 16:09:42 +02:00
Julien Fontanet
09182172cf chore(xo-server): use @xen-orchestra/mixins/hooks 2021-04-13 13:41:22 +02:00
Julien Fontanet
56e903e359 feat(mixins): mixins shared between xo-proxy and xo-server 2021-04-13 13:17:50 +02:00
Julien Fontanet
9922d60e5b feat(@xen-orchestra/mixin): 0.1.0 2021-04-13 13:01:24 +02:00
Julien Fontanet
09ea42439e chore(mixin): remove build step 2021-04-13 12:31:11 +02:00
Julien Fontanet
ce1acf1adc feat(@xen-orchestra/proxy): 0.12.1 2021-04-13 10:46:44 +02:00
Julien Fontanet
fe00badb0f feat: release 5.57.1 2021-04-13 10:27:38 +02:00
Julien Fontanet
2146d67dc2 fix(CHANGELOG{,.unreleased}): move backup dev notes
Introduced by e7b846155
2021-04-13 10:26:26 +02:00
Julien Fontanet
6728768b3e feat(xo-server): 5.78.4 2021-04-12 23:43:33 +02:00
Julien Fontanet
48db3de08c feat(@xen-orchestra/backups): 0.9.3 2021-04-12 23:43:16 +02:00
Julien Fontanet
b944364d1e fix(backups/_copyDelta): dont pass extra params to watchStreamSize
Introduced by 9b1fbf0fb
2021-04-12 23:42:29 +02:00
Julien Fontanet
39c2fbe8c3 feat(xo-web): 5.80.1 2021-04-12 22:56:48 +02:00
Julien Fontanet
c7ba640ecb feat(xo-server): 5.78.3 2021-04-12 22:56:29 +02:00
Julien Fontanet
f749f6be72 feat(xo-server-load-balancer): 0.5.0 2021-04-12 22:56:09 +02:00
Julien Fontanet
ccdd384c6e feat(@xen-orchestra/backups): 0.9.2 2021-04-12 22:55:36 +02:00
Julien Fontanet
4061e2c149 feat(@xen-orchestra/xapi): 0.6.1 2021-04-12 22:55:19 +02:00
Julien Fontanet
e7b8461555 chore(CHANGELOG): update next 2021-04-12 22:54:51 +02:00
Julien Fontanet
70d1537ecc feat(xo-server/vm.set): dont switch to DMC when changing memory
Fixes #4983
2021-04-12 21:15:55 +02:00
Julien Fontanet
cb37f85d8e fix(xo-web/proxies): fix force ugprade
Introduced by a4d90e8aff

See xoa-support#3613

Forward options in `upgradeAppliance` effect.
2021-04-12 12:16:18 +02:00
Julien Fontanet
9becf565a4 fix(CHANGELOG.unreleased): add missing entriy
Introduced by 4bbe8488f
2021-04-12 11:12:54 +02:00
Julien Fontanet
b1a4e5467d feat(xo-server/xapi/startVm): move hostId into options 2021-04-12 11:01:42 +02:00
Julien Fontanet
4bbe8488fc fix(xo-server/xapi/startVm): dont destructure options without default value
See xoa-support#3613
2021-04-12 10:52:41 +02:00
Jon Sands
54a0d126b5 fix(xo-web/en): more grammar fixes (#5714) 2021-04-10 10:30:39 +02:00
Julien Fontanet
9b1fbf0fbf fix(backups/ImportVmBackup): use transfered size instead of backup size
Backup size is smaller in case of delta VHDs.
2021-04-09 15:33:50 +02:00
Julien Fontanet
6f626974ac chore(backups/readDeltaVmBackup): remove unused value 2021-04-09 15:02:26 +02:00
Julien Fontanet
5c47beb1c4 fix(CHANGELOG.unreleased): add missing entry
Related to 3cc9fd278
2021-04-09 11:35:49 +02:00
Julien Fontanet
b4fbe8df07 feat(xo-server/api): explicitely allow $type and enumNames in schemas 2021-04-09 11:16:17 +02:00
Julien Fontanet
3cc9fd2782 fix(xo-server/api): log instead of rejecting non-strict schemas
Fixes https://xcp-ng.org/forum/topic/4439/plugin-transport-email-v0-6-0-broken
2021-04-09 11:03:13 +02:00
Julien Fontanet
eaecba7ec8 fix(xo-server/api): dont log pool.listMissingPatches & host.stats errors
Introduced by 9226c6cac
2021-04-09 10:47:01 +02:00
Julien Fontanet
42a43be092 feat(backups/Task.wrapFn): opts can be a function 2021-04-09 01:27:54 +02:00
Julien Fontanet
052aafd7cb fix(backups/DeltaBackupWriter): merge should be subtask of export
Introduced by f5024f0e7
2021-04-09 01:25:01 +02:00
Julien Fontanet
4abae578f4 feat(backups/Task): new implementation
- no longer requires logging
- supports cancelation (`Task.cancelToken` and `Task#cancel()`)
- supports running multiple functions in the same task
2021-04-09 01:19:09 +02:00
Julien Fontanet
4132d96591 chore(backups): remove unused deps 2021-04-09 01:13:22 +02:00
Julien Fontanet
8e4c90129e fix(backups/DeltaBackupWriter): dont overwrite prepare/cleanup in constructor
Introduced in e69b6c4dc
2021-04-08 23:52:21 +02:00
Julien Fontanet
31406927e6 chore: disable unused Jest coverage 2021-04-08 22:25:10 +02:00
Julien Fontanet
303646efd3 chore: remove unnecessary Jest transform setting 2021-04-08 22:25:10 +02:00
Julien Fontanet
9efc4f9113 chore: remove unnecessary babel-core 2021-04-08 22:25:10 +02:00
Julien Fontanet
31a5a42ec7 chore: use @babel/eslint-parser instead of babel-eslint
babel-eslint is no longer maintained and has issues with some recent syntaxes like private methods.
2021-04-08 22:25:10 +02:00
Yannick Achy
2d0ed3ec8a feat(doc): Host update revision (#5716)
* Host update revision

Co-authored-by: yannick Achy <yannick.achy@vates.fr>
2021-04-08 16:54:06 +02:00
Julien Fontanet
de288a008d fix(proxy): upgrade to koa-compress@5
Fix a koa-compress@4 bug which compress the reply when no accept-encoding header has been passed.
2021-04-07 17:21:10 +02:00
Julien Fontanet
3c5d73224a feat(normalize-packages): delete empty dependencies, description and keywords fields 2021-04-07 15:14:48 +02:00
Julien Fontanet
05f9c07836 chore: add descriptions to all pkgs (but mixin) 2021-04-07 15:13:18 +02:00
Julien Fontanet
a7ba6add39 feat(read-chunk): ensure function is properly named 2021-04-07 14:02:50 +02:00
Julien Fontanet
479973bf06 fix(xapi): add missing cli.js
Introduced by be9b5332d9
2021-04-07 14:00:40 +02:00
Julien Fontanet
854c9fe794 fix(.gitignore): handle @vates/* pkgs 2021-04-07 13:59:07 +02:00
Julien Fontanet
5a17c75fe4 feat: unified .npmignore for all packages
Ensure sources, tests and USAGE.Md files will not be published.
2021-04-07 13:58:14 +02:00
Julien Fontanet
4dc5eff252 chore(normalize-packages): remove unused require 2021-04-07 13:39:12 +02:00
Julien Fontanet
7fe0d78154 fix(compose/USAGE): typo 2021-04-07 13:36:24 +02:00
Julien Fontanet
2c709dc205 fix(xo-server/proxies): readChunk import
Introduced by 538253cdc
2021-04-07 13:09:29 +02:00
Julien Fontanet
9353349a39 chore(vhd-lib): use @vates/read-chunk 2021-04-07 13:08:44 +02:00
Julien Fontanet
d3049b2bfa feat(@vates/read-chunk): 0.1.2 2021-04-07 13:07:57 +02:00
Julien Fontanet
61cb2529bd feat(read-chunk/package.json): only publish index.js 2021-04-07 13:05:49 +02:00
Julien Fontanet
e6c6e4395f chore(read-chunk): add tests 2021-04-07 13:03:56 +02:00
Julien Fontanet
959c955616 feat(read-chunk): handle 0 size 2021-04-07 12:51:27 +02:00
Julien Fontanet
538253cdc1 chore(xo-server/proxies): use @vates/read-chunk 2021-04-07 12:31:16 +02:00
Julien Fontanet
b4c6594333 chore(xo-server/utils): remove unused wrap 2021-04-07 12:25:47 +02:00
Julien Fontanet
a7f5f8889c chore(xo-server/http): use @xen-orchestra/defined 2021-04-07 12:15:33 +02:00
Julien Fontanet
1c9b4cf552 feat(xo-server/Xo): pass appDir, AppName and httpServer
As done in xo-proxy.

This may allow sharing mixins in the future.
2021-04-07 10:41:50 +02:00
Julien Fontanet
ce09f487bd feat(xo-server/XenServers): dont auto connect on safe mode 2021-04-07 10:41:50 +02:00
Julien Fontanet
a5d1decf40 feat(xo-server/Xo): safeMode param 2021-04-07 10:41:50 +02:00
Julien Fontanet
7024c7d598 chore(xo-server/Xo): pass config as named param
As done in xo-proxy.
2021-04-07 10:41:50 +02:00
Jon Sands
8109253eeb fix(xo-web/en): grammar fixes (#5713) 2021-04-06 10:31:52 +02:00
Julien Fontanet
b61f1e3803 fix(xapi/VM_snapshot): VM#refresh_snapshots does not exist
Fixes xoa-support#3587
2021-04-04 22:41:46 +02:00
Julien Fontanet
db40f80be7 chore(CHANGELOG.unreleased): formatting 2021-04-04 22:36:35 +02:00
Mathieu
26eaf97032 fix(xo-web/restore): generateNewMACAddresses disabled by default (#5707) 2021-04-04 18:41:37 +02:00
Ronan Abhamon
da349374bf feat(load-balancer): add option to disable migration (#5706) 2021-04-02 17:32:26 +02:00
Julien Fontanet
0ffa925fee chore(xo-server-load-balancer): format with Prettier 2021-04-02 15:34:38 +02:00
Julien Fontanet
082787c4cf chore: update dependencies 2021-04-02 15:34:19 +02:00
Julien Fontanet
be9b5332d9 feat(xapi): add xo-xapi CLI
Allows to easily test @xen-orchestra/xapi features.
2021-04-01 14:47:04 +02:00
Julien Fontanet
97ae3ba7d3 feat(@xen-orchestra/proxy): 0.12.0 2021-04-01 14:09:09 +02:00
Julien Fontanet
d047f401c2 fix(CHANGELOG): move Highlights title under badge
Introduced by 1e9e78223
2021-04-01 14:08:12 +02:00
Julien Fontanet
1e9e78223b fix(CHANGELOG): missing Highlights title 2021-04-01 13:44:21 +02:00
Julien Fontanet
6d5baebd08 feat: release 5.57.0 2021-04-01 13:29:58 +02:00
Pierre Donias
4e758dbb85 feat: technical release (#5705) 2021-04-01 11:28:09 +02:00
Julien Fontanet
40d943c620 feat(backups/CR writer): delete interrupted copies in prepare() 2021-04-01 10:52:06 +02:00
Julien Fontanet
e69b6c4dc8 fix(backups/delta writers): compute old entries before run 2021-04-01 10:48:39 +02:00
Julien Fontanet
23444f7083 fix(xo-server): Backup/getConnectedRecord receive XAPI not XO type 2021-03-31 16:48:20 +02:00
Julien Fontanet
8c077b96df chore(xo-server/getXapiObject): clarify that second param is an XO type 2021-03-31 16:31:56 +02:00
Pierre Donias
4b1a055a88 feat: technical release (#5704) 2021-03-31 11:15:41 +02:00
Rajaa.BARHTAOUI
b4ddcc1dec feat(xo-server,xo-web/startVm): avoid booting VM if there's an identical MAC address elsewhere (#5655)
Fixes #5601
2021-03-31 10:50:32 +02:00
badrAZ
271d2e3abc feat(fs): expose highWaterMark stream option (#5676) 2021-03-31 10:34:42 +02:00
Julien Fontanet
37b6399398 fix(backups/importDeltaVm): reverse newMacAddresses condition for VIF creation
Introduced by 4df8c9610
2021-03-30 21:26:08 +02:00
Julien Fontanet
ebf19b1506 fix(proxy/backup.importVmBackup): settings param is optional
Introduced by b475b265a
2021-03-30 21:26:08 +02:00
Julien Fontanet
e4dd773644 fix(proxy/api/ndJsonStream): dont fail if one message cannot be JSONified 2021-03-30 21:26:08 +02:00
Mathieu
f9b3a1f293 feat(xo-web/restore): support new mac addresses (#5697) 2021-03-30 17:48:45 +02:00
Rajaa.BARHTAOUI
7c9850ada8 feat(xo-server-perf-alert): ability to choose all hosts, VMs and SRs (#5692)
Fixes #2987
2021-03-30 17:26:48 +02:00
Ronan Abhamon
9ef05b8afe feat(load-balancer): add new anti-affinity mode (#5652)
Fixes #5600
2021-03-30 17:25:41 +02:00
Mathieu
efdd196441 feat(xo-web/proxies): move proxy actions to dropdown (#5688) 2021-03-30 16:56:10 +02:00
Julien Fontanet
6e780a3876 fix(xapi/call{,Async}): fix call to retry
Introduced by 3bb7d2c29
2021-03-30 15:42:05 +02:00
Julien Fontanet
b475b265ae feat(import VM backup): newMacAddresses setting
Related to #5697
2021-03-30 14:31:08 +02:00
Julien Fontanet
3bb7d2c294 feat(xapi/call{,Async}): retry if too many pending tasks
Logic from xo-server/xapi/call
2021-03-30 14:21:19 +02:00
Julien Fontanet
594a148a39 feat(xo-server): VDI_destroy instead of deleteVdi 2021-03-30 14:08:25 +02:00
Julien Fontanet
779591db36 feat(xapi/VDI_destroy): dont fail if VDI not found
Aligned with xo-server/xapi/deleteVdi.
2021-03-30 13:59:10 +02:00
Julien Fontanet
c002eeffb7 chore(proxy): remove unused Node test
The proxy now requires Node >=12
2021-03-30 09:23:15 +02:00
Julien Fontanet
1dac973d70 feat(backups/Task.wrapFn): compatibility with @decorateWith 2021-03-30 09:20:30 +02:00
Julien Fontanet
f5024f0e75 feat(backups/delta writers): split run method in prepare/transfer/cleanup
Fixes xoa-support#3523

This avoids starting the transfer before the writers are ready, which caused it to failed with `deleteFirst` when deletion was so long that the transfer stalled.
2021-03-30 09:20:30 +02:00
Pierre Donias
cf320c08c5 feat: technical release (#5702) 2021-03-29 16:45:00 +02:00
Rajaa.BARHTAOUI
8973c9550c fix(xo-web/vm/advanced): remove noop (#5700)
See https://github.com/vatesfr/xen-orchestra/pull/3774/files#r602860699
2021-03-29 15:10:48 +02:00
Julien Fontanet
bb671f0e93 feat(xapi): update to xo-common@0.7.0 2021-03-29 15:01:12 +02:00
Julien Fontanet
a8774b5011 chore(log/transport/console): remove unused code 2021-03-29 14:59:14 +02:00
Julien Fontanet
f092cd41bc chore: named import from @xen-orchestra/log 2021-03-29 14:06:29 +02:00
Julien Fontanet
b17ec9731a fix(xapi/task_create): dont use super
Introduced by 021810201b

It cannot be used due to our mixin architecture.
2021-03-28 23:29:17 +02:00
Julien Fontanet
021810201b fix(xapi/task_create): remove duplicate [XO] prefix
Found while investigating xoa-support#3553
2021-03-28 14:30:36 +02:00
Julien Fontanet
6038dc9c8a fix(xo-web/vm/advanced): RTL819 → RTL8139
Fixes #5698
2021-03-28 12:23:52 +02:00
Julien Fontanet
4df8c9610a fix(backups/importDeltaVm): new mac_seed when using newMacAddresses 2021-03-26 17:14:37 +01:00
Julien Fontanet
6c12dd4f16 feat(xapi/VM_create): generateMacSeed option 2021-03-26 17:14:37 +01:00
badrAZ
ad3b8fa59f feat(xo-server-usage-report): add VM IP addresses to the report (#5696) 2021-03-26 14:39:35 +01:00
Mathieu
cb52a8b51b feat(xo-server): VM_destroy instead of deleteVm (#5693)
Continuation of 5f1c127
2021-03-26 14:23:04 +01:00
badrAZ
22ba1302d2 fix(xo-server-backup-reports): support failed targets (#5694)
Introduced by d282d8dd5
2021-03-26 10:27:08 +01:00
Mathieu
7d04559921 fix(xo-web/disk import): an error has occurred (#5683)
Fixes #5663

undefined files in collection due to unhandled disk formats
2021-03-26 09:37:31 +01:00
Julien Fontanet
e40e35d30c fix(xo-server): dont provide mac_send when importing OVA VM
Fixes xoa-support#3544
2021-03-25 15:51:02 +01:00
Julien Fontanet
d1af9f236c feat(backup/importDeltaVm): restoreMacAddresses option 2021-03-24 16:39:08 +01:00
Julien Fontanet
45a0ff26c5 feat(xapi/VIF_create): MAC must be passed explicitely 2021-03-24 16:38:19 +01:00
Julien Fontanet
1fd330d7a4 fix(CHANGELOG.unreleased): @vates/disposable 2021-03-24 16:03:49 +01:00
Julien Fontanet
09833f31cf fix(xapi/VM_export): correctly destroy snapshot after export 2021-03-24 16:00:45 +01:00
Julien Fontanet
20e7a036cf feat(xapi): no longer use promise-toolbox/cancelable 2021-03-24 15:34:47 +01:00
Julien Fontanet
e6667c1782 fix(xapi/VM_destroy): only update blocked operations when bypassBlockedOperation 2021-03-24 15:13:09 +01:00
Julien Fontanet
657935eba5 feat(xapi/VM_destroy): split bypassBlockedOperation out of force 2021-03-24 15:12:25 +01:00
Julien Fontanet
67b905a757 feat(xapi/VM_destroy): forceDeleteDefaultTemplate default to force 2021-03-24 15:11:49 +01:00
Julien Fontanet
55cede0434 fix(xapi/VM_destroy): ignore missing VM.set_is_default_template
Introduced by 5f1c1278e
2021-03-24 15:09:09 +01:00
Julien Fontanet
c7677d6d1e fix(xapi/VM_destroy): only update default template when forceDeleteDefaultTemplate 2021-03-24 15:07:30 +01:00
Mathieu
d191ca54ad feat(xo-server/xapi-object-to-xo): display full driver version (#5691) 2021-03-24 13:38:49 +01:00
badrAZ
20f4c952fe feat(@xen-orchestra/backups#RemoteAdapter): ability to clean broken backups (#5684) 2021-03-24 10:00:47 +01:00
Julien Fontanet
0bd09896f3 feat(docs/xoa): network config for other interfaces 2021-03-24 09:49:59 +01:00
badrAZ
60ecfbfb8e feat(xo-server, proxy, @xen-orchestra/backups): execute backup jobs on different processes (#5660) 2021-03-24 09:25:52 +01:00
Julien Fontanet
8921d78610 fix(disposable/deduped): call dispose with disposable context 2021-03-24 00:27:25 +01:00
Julien Fontanet
b243ff94e9 feat(fs/lock): returns a disposable 2021-03-23 23:04:49 +01:00
Mathieu
5f1c1278e3 fix(xapi/VM_destroy): handle is_default_template (#5644) 2021-03-23 17:28:18 +01:00
badrAZ
fa56e594b1 feat(xo-server-transport-email): ability to customize transport settings (#5681)
See xoa-support#3327

This functionnality can help users to get more info about their SMTP issues
2021-03-23 15:47:31 +01:00
badrAZ
c9b64927be feat(@xen-orchestra/fs): ability to lock a path (#5689)
Related to #5684
2021-03-23 13:00:15 +01:00
Julien Fontanet
3689cb2a99 chore(fs/outputStream): dont normalize path twice 2021-03-23 12:53:17 +01:00
Julien Fontanet
3bb7541361 fix(fs/local): opts is optional 2021-03-23 12:53:17 +01:00
Julien Fontanet
7b15aa5f83 fix(package.json/jest.moduleNameMapper): dont map sub-modules
For instance `@xen-orchestra/async-map/legacy`.
2021-03-23 12:53:17 +01:00
Julien Fontanet
690d3036db chore(xo-server): use native Promise#finally() (#5687) 2021-03-22 17:25:40 +01:00
Julien Fontanet
416e8d02a1 chore(xo-server): usingDisposable.use (#5686)
`using` is deprecated.
2021-03-22 17:25:28 +01:00
Julien Fontanet
a968c2d2b7 chore(xo-server): remove promise-toolbox/all uses (#5685) 2021-03-22 15:58:13 +01:00
Julien Fontanet
b4787bf444 fix(xo-server/(re)deployProxy): works whith missing bound VM 2021-03-22 14:44:39 +01:00
Julien Fontanet
a4d90e8aff fix(xo-web/proxies): ignore running jobs on force upgrade
See #3527
2021-03-22 14:37:34 +01:00
Julien Fontanet
32d0606ee4 feat(@xen-orchestra/proxy): 0.11.6 2021-03-22 13:41:28 +01:00
Julien Fontanet
4541f7c758 chore(xo-server): remove pSettle (#5682) 2021-03-22 10:37:07 +01:00
Julien Fontanet
65428d629c feat: release 5.56.2 2021-03-22 10:36:24 +01:00
Julien Fontanet
bdfd9cc617 feat: technical release 2021-03-22 09:56:31 +01:00
Julien Fontanet
6d324921a0 fix(CHANGELOG.unreleased): add xapi to packages to release
Introduced by dcf0f5c5a
2021-03-19 14:53:29 +01:00
Julien Fontanet
dcf0f5c5a3 fix(xapi/VM_create): ignore missing VM.set_bios_strings
Fixes xoa-support#3516
2021-03-19 14:51:51 +01:00
Julien Fontanet
d98f851a2c fix(xo-web/restore): dont break if log is missing result
Found when investigating xoa-support#3516
2021-03-19 13:46:22 +01:00
Julien Fontanet
a95b102396 fix(backups/ImportVmBackup#run): dont swallow errors
Found when investigating xoa-support#3516
2021-03-19 13:38:17 +01:00
Julien Fontanet
7e2fbbaae6 fix(xo-server/createAuthenticationToken): parse expiresIn param
Introduced by 92cf6bb887
2021-03-19 13:02:19 +01:00
Julien Fontanet
070e8b0b54 fix(docs): restore full_backups.md
Introduced by 078f40281
2021-03-19 11:04:42 +01:00
Yannick Achy
7b49a1296c feat(doc): various changes (#5679) 2021-03-19 11:02:24 +01:00
Julien Fontanet
1e278bde92 feat(xo-common/Error.is): apply predicate only on data
See #5644
2021-03-19 10:30:35 +01:00
Yannick Achy
078f402819 feat(doc): check dead links and duplicate (#5664) 2021-03-18 09:35:07 +01:00
Mathieu
52af565f77 fix(fs/localHandler): resource temporarily unavailable (#5612)
Fixes xoa-support#3414
2021-03-17 15:28:04 +01:00
Julien Fontanet
853905e52f feat(xen-api): automatically retry ro calls on ECONNRESET (#5674)
See xoa-support#3266
2021-03-16 17:31:18 +01:00
Julien Fontanet
2e0e1d2aac fix(xo-server/xen-servers): fix autoconnection
Fixes #5675

Introduced by 2fbfc97cca
2021-03-16 13:59:01 +01:00
Julien Fontanet
7f33a62bb5 fix(async-map/asyncMap): fix typing of first param 2021-03-16 11:32:39 +01:00
Julien Fontanet
bdb59ea429 fix(Travis CI): use Node 14 2021-03-15 18:26:22 +01:00
Julien Fontanet
1c0ffe39f7 fix(xapi): merge vdiDestroyRetryWhenInUse after defaults 2021-03-15 13:22:41 +01:00
Julien Fontanet
2fbfc97cca fix(xo-server): connect servers after config import (#5672)
Fixes #5670
2021-03-15 11:49:41 +01:00
Pierre Donias
482299e765 fix(xo-web/pool): disconnectServer → disableServer (#5671)
Fixes #5669
Introduced c7aaeca530
2021-03-15 09:53:34 +01:00
Julien Fontanet
54f4734847 chore: remove babel-plugin-lodash where unnecessary 2021-03-13 20:47:20 +01:00
Julien Fontanet
0fb6cef577 chore(defined): remove Flow 2021-03-13 20:47:20 +01:00
badrAZ
7eec264961 chore(@xen-orchestra/backups): fix logger names (#5666) 2021-03-12 13:53:43 +01:00
Julien Fontanet
aff874c68a chore(xo-server,xo-server-load-balancer): phase out mapToArray (#5662)
Use native `Array#map` or `Object.values` where possible and import directly from `lodash`.

Reasons:
- less dependencies
- more idiomatic
- better example for new code
2021-03-11 15:17:28 +01:00
Julien Fontanet
27abee0850 chore(xo-server-load-balancer): typo ressource → resource 2021-03-11 14:17:02 +01:00
Julien Fontanet
bcfb19f7c5 feat(normalize-packages): delete empty bin field 2021-03-11 12:15:53 +01:00
Julien Fontanet
306a8ce0df feat(@xen-orchestra/proxy): 0.11.5 2021-03-10 13:48:15 +01:00
Julien Fontanet
d9ea8d2c9c feat: release 5.56.1 2021-03-10 13:04:11 +01:00
Julien Fontanet
b479956bb2 feat: technical release (#5657) 2021-03-10 11:11:27 +01:00
Julien Fontanet
b32dc0e450 fix(xen-api/call): allow *.get_all_records in read only 2021-03-10 09:41:49 +01:00
badrAZ
5cca5d69af fix(@xen-orchestra/backups/Backup.js): fix rolling snapshot not ran if alone (#5656) 2021-03-09 18:24:58 +01:00
badrAZ
e0e89213d3 chore(xo-server): delete unused workers mixin (#5654)
Due to 0811da9014
2021-03-09 15:26:21 +01:00
Julien Fontanet
e246c19eb3 feat(xen-api/Ref): introduce new utils to manipulate refs (#5650)
Fixes xoa-support#3463

See xapi-project/xen-api#4338
2021-03-09 14:59:32 +01:00
badrAZ
d282d8dd52 fix(@xen-orchestra/backups): missing targets no longer prevent runs (#5651)
Fixes #5353
2021-03-09 14:37:52 +01:00
badrAZ
9601ad13ee fix(xo-web/proxies): fix "invalid parameters" error on canceling proxy deploy (#5649)
Issue: fetchProxyUpgrades called with an undefined proxy in the proxies collection.

Solution: Interrupt the deployment process on cancel, in order to not fetch updates in this case.
2021-03-09 10:37:59 +01:00
badrAZ
b7603e109d feat(xo-web/backup/new): ability to force full backup per schedule in case of CR (#5648)
Fixes #5541
2021-03-09 09:38:56 +01:00
Julien Fontanet
066f54906b chore: format with Prettier 2021-03-08 17:41:10 +01:00
Julien Fontanet
ea0aa9df70 chore(xen-api): disable problematic ESLint rules on specific lines 2021-03-08 14:23:57 +01:00
badrAZ
0811da9014 feat(xo-server): use @xen-orchestra/backups lib to run VM backups (#5642) 2021-03-08 14:05:41 +01:00
Julien Fontanet
d601290c46 fix(destroy VM): try harder to destroy VDIs (#5645)
Should fix #4926

Work-around XCP-ng/XenServer unmount from control-domain delay, especially with iSCSI SRs.

This issue impacts a lot XO backups which create snapshots, export them and delete them.
2021-03-08 09:46:51 +01:00
badrAZ
64357aff55 fix(@xen-orchestra/xapi): fix full VM backup imported as a template (#5646) 2021-03-05 17:41:50 +01:00
badrAZ
a20a3311b5 fix(xo-server/backup-ng): fix "xapi._assertHealthyVdiChains is not a function" error (#5647)
Introduced by 4c27562650
2021-03-05 17:33:24 +01:00
Julien Fontanet
ffce5d4bb5 chore(@xen-orchestra/xapi): make xen-api a peer dep 2021-03-05 16:17:02 +01:00
badrAZ
cbfadc019a fix(@xen-orchestra/backups): fix "asyncMapSettled is not a function" error (#5643) 2021-03-05 12:23:25 +01:00
Julien Fontanet
bf5427f3e8 feat(@xen-orchestra/proxy): 0.11.4 2021-03-05 11:39:06 +01:00
badrAZ
4c27562650 fix(xo-server/xapi): dont override @xen-orchestra/xapi#_assertHealthyVdiChain (#5641) 2021-03-05 11:38:49 +01:00
badrAZ
e8d20532ba feat(xo-server): use @xen-orchestra/backups lib to run metadata backups (#5616) 2021-03-05 10:51:00 +01:00
Mathieu
d928157569 fix(xo-web/vm/tab-network): an error has occurred when trying to sort empty network (#5639)
This issue happens when you have an ACL role on one VM, but you don't have an ACL role on the network of this VM.
2021-03-05 09:37:40 +01:00
Mathieu
872b05a7de feat(xo-server/VIF): set MAC address requires Admin ACL on network (#5631)
Fixes #4700
2021-03-05 09:27:22 +01:00
Julien Fontanet
6ea71ec6a2 chore(xapi/VM_destroy): add new lines 2021-03-04 16:11:08 +01:00
Julien Fontanet
139cb72209 chore(xapi/VM_destroy): use VM_getDisks 2021-03-04 16:11:08 +01:00
Julien Fontanet
855a15e696 fix(xapi/VM_getDisks): sync iteration 2021-03-04 16:11:08 +01:00
Mathieu
eeebd3fc1b fix(xo-web/DropdownButton): add required id prop (#5628)
See https://react-bootstrap.netlify.app/components/dropdowns/#dropdown-button-props
2021-03-04 15:56:01 +01:00
Julien Fontanet
a4b209c654 fix(disposable/deduped): race condition when disposed during acquisition
Introduced in 43aad3d11
2021-03-04 10:46:03 +01:00
Julien Fontanet
43aad3d117 feat(disposable/deduped): works with sync factories 2021-03-03 17:43:39 +01:00
Mathieu
f2d4fdd4d2 fix(xo-web/editable/number): throw error if onChange fails (#5634) 2021-03-03 16:33:41 +01:00
Julien Fontanet
a630106d80 feat(@xen-orchestra/backups): 0.6.1 2021-03-03 12:05:33 +01:00
Julien Fontanet
c7acd455c5 feat(@xen-orchestra/async-map): 0.1.2 2021-03-03 12:05:05 +01:00
Julien Fontanet
555a9d4883 fix(async-map/asyncMapSettled): issue when latest promise rejects 2021-03-03 11:58:51 +01:00
Julien Fontanet
ec4ce0c70c fix(async-map/test): missing await 2021-03-03 11:57:51 +01:00
Julien Fontanet
edf275badc fix(backups/RemoteAdapter#readDeltaVmBackup): new asyncMapSettled does not support plain objects
Introduced by 20377e9c56
2021-03-03 11:49:21 +01:00
Julien Fontanet
2e91285f02 feat(xo-web/debug): similar display for success and result 2021-03-03 10:06:36 +01:00
Julien Fontanet
ec69ba7e0e feat(xo-web/debug): display API call result 2021-03-03 10:06:03 +01:00
Julien Fontanet
3804ca18cb feat(@xen-orchestra/proxy): 0.11.3 2021-03-03 09:19:14 +01:00
Julien Fontanet
9ea3222da8 feat(@xen-orchestra/xapi): 0.4.3 2021-03-03 09:18:58 +01:00
Julien Fontanet
df48524ca5 feat(@xen-orchestra/async-map): 0.1.1 2021-03-03 09:17:08 +01:00
Julien Fontanet
b3aff1162c feat(@xen-orchestra/proxy): 0.11.2 2021-03-03 08:58:42 +01:00
Julien Fontanet
891ca8a31b feat(@xen-orchestra/xapi): 0.4.2 2021-03-03 08:58:30 +01:00
Julien Fontanet
ba99ac8b17 fix(package.json): support non-transpiled @xen-orchestra/* and xo-* 2021-03-02 16:53:02 +01:00
badrAZ
1ff25943dc fix(xo-server): enable async_hooks support in Bluebird (#5635)
Necessary for `@xen-orchestra/backups`.
2021-03-02 13:22:47 +01:00
Julien Fontanet
deb58e40d5 chore(xo-server/bin): format with Prettier 2021-03-02 11:39:42 +01:00
Julien Fontanet
eab6eb8fab chore(xen-api): event-to-promise → promise-toolbox/fromEvent 2021-03-02 10:20:38 +01:00
Julien Fontanet
ff65367851 chore(async-map): add basic tests 2021-03-01 17:25:08 +01:00
Julien Fontanet
f16e29c63e fix(async-map/asyncMapSettled): fix hasError condition 2021-03-01 17:22:05 +01:00
Julien Fontanet
cdfeb094b3 chore(async-map/package.json): remove unused browserslist 2021-03-01 17:01:48 +01:00
Julien Fontanet
b63c5d2987 chore: dont import @xen-orchestra/log/dist 2021-03-01 17:00:42 +01:00
Julien Fontanet
015309c882 chore(backups-cli): use @xen-orchestra/async-map 2021-03-01 16:55:06 +01:00
Julien Fontanet
20377e9c56 feat(async-map): new implementations
These implementations are no longer compatible with plain objects but support iterables.

The previous implementation is still available as `@xen-orchestra/async-map/legacy`.
2021-03-01 16:55:06 +01:00
Mathieu
08857a6198 fix(xo-server): fix asyncMap is not defined (#5632)
Introduced by 57612ee
2021-03-01 16:54:53 +01:00
badrAZ
d9ce1b3a97 feat(xo-server#importVmBackupNg): use @xen-orchestra/backups lib (#5630) 2021-03-01 13:36:23 +01:00
Julien Fontanet
d166073b16 chore(xo-server/package.json): fix deps sorting
Introduced by 624f32826

Sorting values is different than sorting JSON text.
2021-03-01 09:48:13 +01:00
Julien Fontanet
f858c196f4 chore: rename asyncMap → asyncMapSettled
To express more clearly this function's behavior.
2021-03-01 09:45:56 +01:00
Julien Fontanet
57612eeced feat(async-map): remove build step 2021-02-28 23:32:23 +01:00
Julien Fontanet
be2257153c feat(proxy-cli): clearer call headers 2021-02-26 17:50:47 +01:00
Julien Fontanet
d920a97f4f feat(proxy-cli): supports nested sequences 2021-02-26 17:23:49 +01:00
Julien Fontanet
322f2a1728 chore(xo-server/runJob): group runningJobs logic 2021-02-26 16:52:43 +01:00
Julien Fontanet
cfe6b0d9ab fix(xo-server/runJob): emit job:terminated and forward error
Introduced in fd560c351
2021-02-26 16:52:43 +01:00
Pierre Donias
e229deb238 feat: release 5.56.0 (#5629) 2021-02-26 16:50:00 +01:00
Julien Fontanet
8cdde947bc feat(@xen-orchestra/proxy): 0.11.1 2021-02-26 16:07:47 +01:00
Julien Fontanet
c1b3ddf87a fix(proxy): add missing peerdep xen-api 2021-02-26 16:07:47 +01:00
Pierre Donias
27d97add1e feat: technical release (#5627) 2021-02-26 16:07:15 +01:00
Mathieu
3783724c40 fix(xo-web/task): items-per-page dropdown position (#5584) 2021-02-26 15:21:45 +01:00
Julien Fontanet
67bc4ffe68 feat(@xen-orchestra/proxy): 0.11.0 2021-02-26 15:15:05 +01:00
Julien Fontanet
453bbfbbde feat(@xen-orchestra/backups): 0.6.0 2021-02-26 15:11:35 +01:00
Julien Fontanet
ff463c4261 chore(proxy-cli): mutualize request options 2021-02-26 15:10:42 +01:00
Damien Thenot
748b77ae7a fix(docs/advanced): typo telemtry → telemetry (#5625) 2021-02-26 14:57:11 +01:00
Rajaa.BARHTAOUI
58c1005657 fix(xo-web/migrateVms): explicit main SR (#5615)
See #5577

So that when there's no default SR on the pool and the VM's snapshot has orphan
VDI-snapshots, xo-server knows where to migrate them
2021-02-26 14:01:48 +01:00
Rajaa.BARHTAOUI
9271eb61ac fix(xo-web/vm/advanced): fix 'an error has occurred' (#5604)
Fixes #5592
2021-02-26 13:39:34 +01:00
Rajaa.BARHTAOUI
c82cee25a5 fix(xo-web): fix 'mapVdisSrs is assigned a value but never used' error (#5617)
Introduced by 90cafa126f
2021-02-26 13:34:33 +01:00
badrAZ
2e5dfa5845 fix(xo-server#deleteVmBackupNg): pass remote record to getBackupsRemoteAdapter instead of ID (#5624)
Introduced by baa5847949
2021-02-26 12:07:04 +01:00
Julien Fontanet
693c07b927 chore: update app-conf to 0.9.0 2021-02-26 12:02:39 +01:00
Julien Fontanet
71a6f70f46 chore: update promise-toolbox to 0.17.0
Allow using `Disposable.use()`.
2021-02-26 12:02:39 +01:00
badrAZ
2952b5a7ec feat(xo-server#deleteVmBackupNg): use @xen-orchestra/backups lib (#5623) 2021-02-26 11:40:28 +01:00
badrAZ
baa5847949 feat(xo-server#_listVmBackupsOnRemote): use @xen-orchestra/backups lib (#5622) 2021-02-26 11:17:45 +01:00
Rajaa.BARHTAOUI
b9ce0bd99d fix(xo-web): fix 'mapValues is defined but never used' error (#5618)
Introduced by 062fb3ba30
2021-02-26 10:11:04 +01:00
Julien Fontanet
aac61d8120 chore: update golike-defer to 0.5.1 2021-02-25 18:41:11 +01:00
Julien Fontanet
1f6edfdbcc fix(xo-server/runJob): upgrade defer to fix import
Introduced by fd560c351
2021-02-25 18:40:55 +01:00
Mathieu
9d1ce7fadf fix(backups/importDeltaVm): restore the bios_strings (#5598)
Aligned with XAPI behavior for XVA exports/imports.
2021-02-25 17:26:43 +01:00
Julien Fontanet
fd560c351f fix(xo-server/runJob): register job as soon as job.start (#5620) 2021-02-25 17:00:07 +01:00
badrAZ
b45556062d fix(@xen-orchestra/backups): don't double JSON config (#5621)
Config returned by `Xo#exportConfig` is already a string, it must not be JSON encoded again.
2021-02-25 16:49:45 +01:00
badrAZ
5be45599ed fix(xo-server/metadata-backup): XO config not restored (#5619)
Introduced by 61c3057060

`log.taskId` cannot be compared with the `rootTaskId` because it's generated by the Task lib and the `rootTaskId` is generated by the `xo-server` logger.
2021-02-25 16:41:39 +01:00
Julien Fontanet
9b2533dbc9 chore(yarn.lock): update 2021-02-25 14:43:16 +01:00
Julien Fontanet
ec1a4b1974 fix(proxy/backup.run): bind getConnectedRecord
Introduced in 4eb9aa9cc
2021-02-25 11:19:20 +01:00
Julien Fontanet
bb9fde17c9 chore(xo-server/_backupVm): update todo list 2021-02-25 11:03:54 +01:00
Rajaa.BARHTAOUI
8cb524080c fix(xo-server#_migrateVmWithStorageMotion): don't migrate VM VDIs to default SR (#5577)
See xoa-support#3248
See xoa-support#3355
2021-02-25 10:35:14 +01:00
badrAZ
171ec54781 feat(xo-server#restoreMetadataBackup): use @xen-orchestra/backups lib (#5611) 2021-02-25 09:43:15 +01:00
Julien Fontanet
5d9503b78c feat(backups/Backup): getAdapter accepts ids instead of remotes
This should make it easier to interface with xo-server.
2021-02-24 17:33:26 +01:00
Julien Fontanet
f56cb69c2e chore(backups/Backup): remove unused property 2021-02-24 17:30:43 +01:00
Julien Fontanet
4eb9aa9ccb feat(backups/Backup): pass directly getConnectedRecord (#5614)
This should make it easier to interface with xo-server.
2021-02-24 17:25:46 +01:00
Pierre Donias
11801f306c feat: technical release (#5613) 2021-02-24 15:54:37 +01:00
badrAZ
95c2944f30 feat(xo-server#deleteMetadataBackup): use @xen-orchestra/backups lib (#5610) 2021-02-24 11:38:27 +01:00
badrAZ
5bd4c54ab6 feat(xo-server#_listXoMetadataBackups): use @xen-orchestra/backups lib (#5609) 2021-02-24 10:16:27 +01:00
Julien Fontanet
95d6d0a0fe chore(backups/formatVmBackup): ensure function is nammed 2021-02-24 10:08:59 +01:00
Julien Fontanet
7941be083a chore(backups): rename task.js → Task.js
To be in line with other modules in this lib.
2021-02-24 10:07:36 +01:00
badrAZ
e36efaec08 feat(xo-server#_listPoolMetadataBackups): use @xen-orchestra/backups lib (#5607) 2021-02-24 10:02:57 +01:00
Julien Fontanet
637afdb540 feat(@vates/toggle-scripts): 1.0.0 2021-02-24 08:55:38 +01:00
Julien Fontanet
dafdedef9a feat(toggle-scripts): supports npm < 7 2021-02-24 08:54:29 +01:00
Julien Fontanet
ce17ee2ae6 fix(toggle-scripts/package.json): fix files entry 2021-02-24 08:48:33 +01:00
Julien Fontanet
e74daa97d2 fix(toggle-scripts): fix usage 2021-02-23 21:54:31 +01:00
Julien Fontanet
44d64d1b80 fix(proxy): dont run systemd-service-installer in dev
See ronivay/XenOrchestraInstallerUpdater#62
2021-02-23 21:37:26 +01:00
Julien Fontanet
1a4731aa83 feat(@vates/toggle-scripts): 0.1.0 2021-02-23 21:32:58 +01:00
Julien Fontanet
a75e1c52b7 feat(toggle-scripts): CLI to enable/disable package.json scripts 2021-02-23 21:28:23 +01:00
Julien Fontanet
1b97cb263c feat(proxy/config): resourceDebouce → resourceCacheDelay
Similar to xo-server.
2021-02-23 19:54:20 +01:00
badrAZ
5c9a47b6b7 feat(xo-server#fetchBackupNgPartitionFiles): use @xen-orchestra/backups lib (#5606) 2021-02-23 17:48:11 +01:00
badrAZ
8a5fe86193 feat(xo-server#listBackupNgPartitionFiles): use @xen-orchestra/backups lib (#5605) 2021-02-23 17:40:02 +01:00
badrAZ
d9531e24a3 feat(xo-server/listBackupNgDiskPartitions): use @xen-orchestra/backups lib (#5599) 2021-02-23 17:34:55 +01:00
Julien Fontanet
624f328269 chore(xo-server/package.json): sort deps 2021-02-23 16:29:46 +01:00
badrAZ
a6f4e6771d fix(xo-server/package.json): missing dependency (#5603)
Introduced by a958fe86d7

Used in a506c21b80/%40xen-orchestra/backups/RemoteAdapter.js (L14)
2021-02-23 15:34:31 +01:00
Julien Fontanet
a506c21b80 feat(docs/installation): XO now requires Node >=14.5 2021-02-23 15:26:21 +01:00
Julien Fontanet
981193ed23 feat(docs/from the sources): XO now requires Node >=14.5 2021-02-23 15:12:42 +01:00
Julien Fontanet
85a6204db2 feat(@xen-orchestra/backups-cli): 0.4.0 2021-02-23 14:41:47 +01:00
Julien Fontanet
b82aba1181 chore(backups-cli): add usage to README 2021-02-23 14:40:15 +01:00
Julien Fontanet
0a6dea2c79 feat(backups-cli/clean-vms): better usage 2021-02-23 14:32:16 +01:00
Julien Fontanet
69b6d75927 feat(CHANGELOG.unreleased): release backups 2021-02-23 12:35:04 +01:00
Julien Fontanet
eff2d48cc5 feat(backups/RemoteAdapter#outputStream): make path first param
Similar to `fs/Abstract#outputStream()`.
2021-02-23 12:34:26 +01:00
Julien Fontanet
ca5af2505c fix(fs/outputStream): always make path first param
Introduced by 7a1377119
2021-02-23 11:47:19 +01:00
Julien Fontanet
a958fe86d7 feat(proxy): version 1 (#4495)
Co-authored-by: badrAZ <azizbibadr@gmail.com>
Co-authored-by: Mathieu <70369997+MathieuRA@users.noreply.github.com>
2021-02-23 08:58:10 +01:00
Julien Fontanet
3ed488e10f chore(compose): regenerate README 2021-02-22 15:09:23 +01:00
Julien Fontanet
dcc11f16b1 feat(@vates/compose): 2.0.0 2021-02-22 14:42:45 +01:00
Julien Fontanet
209706b70d feat(compose): forwards this to all functions 2021-02-22 14:42:18 +01:00
badrAZ
1bc80eb485 fix(package.json#moduleNameMapper): fix tests for non-transpiled @vates/ packages (#5593) 2021-02-19 16:34:14 +01:00
badrAZ
9ab9e3fe46 feat(vates/disposable): utilities for disposables (#5590) 2021-02-19 16:22:41 +01:00
Mathieu
d654c096ed feat(xo-web/menu): xoa.check sync between menu and support page (#5534) 2021-02-19 10:21:52 +01:00
Olivier Lambert
f5d5884988 feat(docs/advanced): add a section about terraform provider (#5589) 2021-02-19 09:22:05 +01:00
Julien Fontanet
2c016204bf feat(@vates/compose): 1.2.0 2021-02-18 17:03:17 +01:00
Julien Fontanet
04fd625bde feat(compose): this and args passed to first function 2021-02-18 17:03:17 +01:00
Mathieu
8455d4a49f fix(xo-web/select): wrapping text if label is too long (#5580)
See https://xcp-ng.org/forum/topic/4072/create-vm-network-names-too-large
2021-02-18 16:51:52 +01:00
Yannick Achy
a3960bb7c5 feat(docs/full backup): document offline backup (#5582)
Co-authored-by: yannick Achy <yannick.achy@vates.fr>
2021-02-18 15:15:21 +01:00
Mathieu
769262d60e fix(changelog): add # to PR reference (#5585) 2021-02-18 14:49:14 +01:00
Julien Fontanet
942567586f feat(@vates/compose): 1.1.1 2021-02-18 11:29:10 +01:00
Julien Fontanet
ba6baaec0a fix(compose): update README 2021-02-18 11:27:24 +01:00
Julien Fontanet
a8ac6fc738 fix(compose): require Node 7.6 2021-02-18 11:26:00 +01:00
Julien Fontanet
b027d3b1d6 feat(@vates/compose): 1.1.0 2021-02-18 11:25:33 +01:00
Julien Fontanet
71f9d268c9 feat(compose): async functions support 2021-02-18 11:25:14 +01:00
Julien Fontanet
2b91d4af99 feat(compose): right to left support 2021-02-18 11:25:14 +01:00
Julien Fontanet
0ec0e286ba feat(compose/README): document functions in an array 2021-02-18 11:25:14 +01:00
Rajaa.BARHTAOUI
258ae64568 fix(xo-web/home/vm): bulk intra pool migration: fix map VDI -> SR (#5578)
See xoa-support#3355
See xoa-support#3248
2021-02-18 11:04:47 +01:00
Rajaa.BARHTAOUI
90cafa126f feat(xo-web/migrateVm): show error when no main SR selected (#5568)
See xoa-support#3355
2021-02-18 10:57:00 +01:00
Julien Fontanet
43d31e285c feat(@vates/compose): 1.0.0 2021-02-18 10:40:27 +01:00
Julien Fontanet
57945e6751 feat(compose): new lib to compose functions 2021-02-18 10:39:57 +01:00
Rajaa.BARHTAOUI
fce56cbf4c fix(xo-server/utils/parseXml): keep all values as strings (#5581)
Fixes #5497

All values must be kept as strings because that's what the previous implementation used to do.

Introduced by 525369e0ce

See https://github.com/vatesfr/xen-orchestra/issues/5497#issuecomment-780314187

```
{
  'iscsi-target': {
    LUN: {
      vendor: 'TrueNAS',
      serial: '9eaa394581f3003',
      LUNid: 55,
      size: 10995116277760,
      SCSIid: '36589cfc000000581d40d6d5140d9b9da'
    }
  }
}
```
2021-02-18 09:46:17 +01:00
Julien Fontanet
7a13771198 fix(fs/outputStream): make path the first param
From #5373
2021-02-17 17:11:55 +01:00
Julien Fontanet
819c798e99 chore: format mardown files with Prettier 2021-02-17 16:04:22 +01:00
Julien Fontanet
8560ca0661 chore(vhd-lib/Vhd#_getBatEntry): name param blockId
Because it's not a full block but an identifier.
2021-02-17 14:39:02 +01:00
Julien Fontanet
82cdfe7014 chore(vhd-lib): fix a test
From #5481
2021-02-17 14:30:40 +01:00
Julien Fontanet
52642f5854 chore(vhd-lib): move tests into src
From #5481

Fix Jest module mapping.
2021-02-17 14:29:40 +01:00
Julien Fontanet
6c6f9f5a44 feat(backups-cli/clean-vms): rename force flag to remove 2021-02-17 14:01:14 +01:00
Julien Fontanet
039ce15253 chore(xo-server/backups-ng): use invalidParameter.is() 2021-02-17 14:01:14 +01:00
badrAZ
695a4c785c feat(xo-server/backups-ng): handle proxy VM restoration logs (#5576) 2021-02-17 11:03:52 +01:00
Rajaa.BARHTAOUI
7d7f160159 fix(xo-web/migrateVm): don't automatically select migration network (#5564)
See xoa-support#3355
2021-02-17 10:06:03 +01:00
Julien Fontanet
b454b4dff1 feat(xo-server/backups): add proxy id to logs 2021-02-17 09:53:00 +01:00
Nicolas Raynaud
e5d711dd28 fix(fs/S3Handler#_write): work when file doesn't exist (#5561) 2021-02-16 13:45:01 +01:00
badrAZ
10b127ca55 feat(xo-web/backup): ability to force full backup per schedule (#5546)
Fixes #5541
2021-02-16 11:31:17 +01:00
Julien Fontanet
fb4dff4fca chore(xo-cli/USAGE): clearer JSON param explanation 2021-02-16 10:52:22 +01:00
badrAZ
ef25b364ec fix(xo-server/metadata-backups): fix interrupted status on backup running (#5573)
Introduced by 8a3ae59f77
2021-02-15 14:31:01 +01:00
Nicolas Raynaud
9394db986d fix(import/disk): allow uppercase extensions (#5574)
See https://xcp-ng.org/forum/topic/4216/cannot-import-a-large-vhd-using-import-disk-option
2021-02-15 12:05:49 +01:00
Rajaa.BARHTAOUI
9226c6cac1 fix(xo-server/api): don't log host.stats errors (#5553)
See xoa-support#3323

This avoids flooding the logs with ECONNREFUSED errors when the host's toolstack
is restarted
2021-02-12 11:29:16 +01:00
Julien Fontanet
283193e992 feat(complex-matcher): 0.7.0 2021-02-11 13:54:29 +01:00
Julien Fontanet
72f8a6d220 chore(complex-matcher): add test for non-ASCII raw strings
Related to f5e4fb49c
2021-02-11 13:53:54 +01:00
Albin Hedman
f5e4fb49c3 feat(complex-matcher): allow most letters to be unquoted (#5555) 2021-02-11 11:14:44 +01:00
Olivier Lambert
3cd15c783c fix(docs): update the deploy script to fix an issue (#5565) 2021-02-11 10:17:42 +01:00
717 changed files with 22297 additions and 18918 deletions

View File

@@ -1,13 +1,5 @@
module.exports = {
extends: [
'plugin:eslint-comments/recommended',
'standard',
'standard-jsx',
'prettier',
'prettier/standard',
'prettier/react',
],
extends: ['plugin:eslint-comments/recommended', 'standard', 'standard-jsx', 'prettier'],
globals: {
__DEV__: true,
$Dict: true,
@@ -21,19 +13,13 @@ module.exports = {
overrides: [
{
files: ['cli.js', '*-cli.js', '**/*cli*/**/*.js'],
files: ['cli.{,c,m}js', '*-cli.{,c,m}js', '**/*cli*/**/*.{,c,m}js'],
rules: {
'no-console': 'off',
},
},
],
parser: 'babel-eslint',
parserOptions: {
ecmaFeatures: {
legacyDecorators: true,
},
},
rules: {
// disabled because XAPI objects are using camel case
camelcase: ['off'],

33
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,33 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'status: triaging :triangular_flag_on_post:, type: bug :bug:'
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- Node: [e.g. 16.12.1]
- xo-server: [e.g. 5.82.3]
- xo-web: [e.g. 5.87.0]
- hypervisor: [e.g. XCP-ng 8.2.0]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

10
.gitignore vendored
View File

@@ -4,20 +4,24 @@
/lerna-debug.log
/lerna-debug.log.*
/@vates/*/dist/
/@vates/*/node_modules/
/@xen-orchestra/*/dist/
/@xen-orchestra/*/node_modules/
/packages/*/dist/
/packages/*/node_modules/
/@xen-orchestra/proxy/src/app/mixins/index.mjs
/packages/vhd-cli/src/commands/index.js
/packages/xen-api/examples/node_modules/
/packages/xen-api/plot.dat
/packages/xo-server/.xo-server.*
/packages/xo-server/src/api/index.js
/packages/xo-server/src/xapi/mixins/index.js
/packages/xo-server/src/xo-mixins/index.js
/packages/xo-server/src/api/index.mjs
/packages/xo-server/src/xapi/mixins/index.mjs
/packages/xo-server/src/xo-mixins/index.mjs
/packages/xo-server-auth-ldap/ldap.cache.conf

View File

@@ -1,6 +1,6 @@
language: node_js
node_js:
- 12
- 14
# Use containers.
# http://docs.travis-ci.com/user/workers/container-based-infrastructure/

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -20,9 +20,6 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"files": [
"index.js"
],
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"

1
@vates/compose/.npmignore Symbolic link
View File

@@ -0,0 +1 @@
../../scripts/npmignore

81
@vates/compose/README.md Normal file
View File

@@ -0,0 +1,81 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @vates/compose
[![Package Version](https://badgen.net/npm/v/@vates/compose)](https://npmjs.org/package/@vates/compose) ![License](https://badgen.net/npm/license/@vates/compose) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@vates/compose)](https://bundlephobia.com/result?p=@vates/compose) [![Node compatibility](https://badgen.net/npm/node/@vates/compose)](https://npmjs.org/package/@vates/compose)
> Compose functions from left to right
## Install
Installation of the [npm package](https://npmjs.org/package/@vates/compose):
```
> npm install --save @vates/compose
```
## Usage
```js
import { compose } from '@vates/compose'
const add2 = x => x + 2
const mul3 = x => x * 3
// const f = x => mul3(add2(x))
const f = compose(add2, mul3)
console.log(f(5))
// → 21
```
> The call context (`this`) of the composed function is forwarded to all functions.
The first function is called with all arguments of the composed function:
```js
const add = (x, y) => x + y
const mul3 = x => x * 3
// const f = (x, y) => mul3(add(x, y))
const f = compose(add, mul3)
console.log(f(4, 5))
// → 27
```
Functions may also be passed in an array:
```js
const f = compose([add2, mul3])
```
Options can be passed as first parameter:
```js
const f = compose(
{
// compose async functions
async: true,
// compose from right to left
right: true,
},
[add2, mul3]
)
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

48
@vates/compose/USAGE.md Normal file
View File

@@ -0,0 +1,48 @@
```js
import { compose } from '@vates/compose'
const add2 = x => x + 2
const mul3 = x => x * 3
// const f = x => mul3(add2(x))
const f = compose(add2, mul3)
console.log(f(5))
// → 21
```
> The call context (`this`) of the composed function is forwarded to all functions.
The first function is called with all arguments of the composed function:
```js
const add = (x, y) => x + y
const mul3 = x => x * 3
// const f = (x, y) => mul3(add(x, y))
const f = compose(add, mul3)
console.log(f(4, 5))
// → 27
```
Functions may also be passed in an array:
```js
const f = compose([add2, mul3])
```
Options can be passed as first parameter:
```js
const f = compose(
{
// compose async functions
async: true,
// compose from right to left
right: true,
},
[add2, mul3]
)
```

46
@vates/compose/index.js Normal file
View File

@@ -0,0 +1,46 @@
'use strict'
const defaultOpts = { async: false, right: false }
exports.compose = function compose(opts, fns) {
if (Array.isArray(opts)) {
fns = opts
opts = defaultOpts
} else if (typeof opts === 'object') {
opts = Object.assign({}, defaultOpts, opts)
if (!Array.isArray(fns)) {
fns = Array.prototype.slice.call(arguments, 1)
}
} else {
fns = Array.from(arguments)
opts = defaultOpts
}
const n = fns.length
if (n === 0) {
throw new TypeError('at least one function must be passed')
}
if (n === 1) {
return fns[0]
}
if (opts.right) {
fns.reverse()
}
return opts.async
? async function () {
let value = await fns[0].apply(this, arguments)
for (let i = 1; i < n; ++i) {
value = await fns[i].call(this, value)
}
return value
}
: function () {
let value = fns[0].apply(this, arguments)
for (let i = 1; i < n; ++i) {
value = fns[i].call(this, value)
}
return value
}
}

View File

@@ -0,0 +1,66 @@
/* eslint-env jest */
const { compose } = require('./')
const add2 = x => x + 2
const mul3 = x => x * 3
describe('compose()', () => {
it('throws when no functions is passed', () => {
expect(() => compose()).toThrow(TypeError)
expect(() => compose([])).toThrow(TypeError)
})
it('applies from left to right', () => {
expect(compose(add2, mul3)(5)).toBe(21)
})
it('accepts functions in an array', () => {
expect(compose([add2, mul3])(5)).toBe(21)
})
it('can apply from right to left', () => {
expect(compose({ right: true }, add2, mul3)(5)).toBe(17)
})
it('accepts options with functions in an array', () => {
expect(compose({ right: true }, [add2, mul3])(5)).toBe(17)
})
it('can compose async functions', async () => {
expect(
await compose(
{ async: true },
async x => x + 2,
async x => x * 3
)(5)
).toBe(21)
})
it('forwards all args to first function', () => {
expect.assertions(1)
const expectedArgs = [Math.random(), Math.random()]
compose(
(...args) => {
expect(args).toEqual(expectedArgs)
},
// add a second function to avoid the one function special case
Function.prototype
)(...expectedArgs)
})
it('forwards context to all functions', () => {
expect.assertions(2)
const expectedThis = {}
compose(
function () {
expect(this).toBe(expectedThis)
},
function () {
expect(this).toBe(expectedThis)
}
).call(expectedThis)
})
})

View File

@@ -0,0 +1,24 @@
{
"private": false,
"name": "@vates/compose",
"description": "Compose functions from left to right",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/compose",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@vates/compose",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "ISC",
"version": "2.0.0",
"engines": {
"node": ">=7.6"
},
"scripts": {
"postversion": "npm publish --access public"
}
}

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -16,7 +16,9 @@ Installation of the [npm package](https://npmjs.org/package/@vates/decorate-with
## Usage
For instance, allows using Lodash's functions as decorators:
### `decorateWith(fn, ...args)`
Creates a new ([legacy](https://babeljs.io/docs/en/babel-plugin-syntax-decorators#legacy)) method decorator from a function decorator, for instance, allows using Lodash's functions as decorators:
```js
import { decorateWith } from '@vates/decorate-with'
@@ -29,6 +31,34 @@ class Foo {
}
```
### `decorateMethodsWith(class, map)`
Decorates a number of methods directly, without using the decorator syntax:
```js
import { decorateMethodsWith } from '@vates/decorate-with'
class Foo {
bar() {
// body
}
baz() {
// body
}
}
decorateMethodsWith(Foo, {
// without arguments
bar: lodash.curry,
// with arguments
baz: [lodash.debounce, 150],
})
```
The decorated class is returned, so you can export it directly.
## Contributions
Contributions are _very_ welcomed, either on the documentation or on

View File

@@ -1,4 +1,6 @@
For instance, allows using Lodash's functions as decorators:
### `decorateWith(fn, ...args)`
Creates a new ([legacy](https://babeljs.io/docs/en/babel-plugin-syntax-decorators#legacy)) method decorator from a function decorator, for instance, allows using Lodash's functions as decorators:
```js
import { decorateWith } from '@vates/decorate-with'
@@ -10,3 +12,31 @@ class Foo {
}
}
```
### `decorateMethodsWith(class, map)`
Decorates a number of methods directly, without using the decorator syntax:
```js
import { decorateMethodsWith } from '@vates/decorate-with'
class Foo {
bar() {
// body
}
baz() {
// body
}
}
decorateMethodsWith(Foo, {
// without arguments
bar: lodash.curry,
// with arguments
baz: [lodash.debounce, 150],
})
```
The decorated class is returned, so you can export it directly.

View File

@@ -1,4 +1,21 @@
exports.decorateWith = (fn, ...args) => (target, name, descriptor) => ({
...descriptor,
value: fn(descriptor.value, ...args),
})
exports.decorateWith = function decorateWith(fn, ...args) {
return (target, name, descriptor) => ({
...descriptor,
value: fn(descriptor.value, ...args),
})
}
const { getOwnPropertyDescriptor, defineProperty } = Object
exports.decorateMethodsWith = function decorateMethodsWith(klass, map) {
const { prototype } = klass
for (const name of Object.keys(map)) {
const descriptor = getOwnPropertyDescriptor(prototype, name)
const { value } = descriptor
const decorator = map[name]
descriptor.value = typeof decorator === 'function' ? decorator(value) : decorator[0](value, ...decorator.slice(1))
defineProperty(prototype, name, descriptor)
}
return klass
}

View File

@@ -20,7 +20,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.0.1",
"version": "0.1.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1,89 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @vates/disposable
[![Package Version](https://badgen.net/npm/v/@vates/disposable)](https://npmjs.org/package/@vates/disposable) ![License](https://badgen.net/npm/license/@vates/disposable) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@vates/disposable)](https://bundlephobia.com/result?p=@vates/disposable) [![Node compatibility](https://badgen.net/npm/node/@vates/disposable)](https://npmjs.org/package/@vates/disposable)
> Utilities for disposables
## Install
Installation of the [npm package](https://npmjs.org/package/@vates/disposable):
```
> npm install --save @vates/disposable
```
## Usage
This library contains utilities for disposables as defined by the [`promise-toolbox` library](https://github.com/JsCommunity/promise-toolbox#resource-management).
### `deduped(fn, keyFn)`
Creates a new function that wraps `fn` and instead of creating a new disposables at each call, returns copies of the same one when `keyFn` returns the same keys.
Those copies contains the same value and can be disposed independently, the source disposable will only be disposed when all copies are disposed.
`keyFn` is called with the same context and arguments as the wrapping function and must returns an array of keys which will be used to identify which disposables should be grouped together.
```js
import { deduped } from '@vates/disposable/deduped'
// the connection with the passed host will be established once at the first call, then, it will be shared with the next calls
const getConnection = deduped(async function (host)) {
const connection = new Connection(host)
return new Disposabe(connection, () => connection.close())
}, host => [host])
```
### `debounceResource(disposable, delay)`
Creates a new disposable with the same value and with a delayed disposer.
On calling this disposer, the source disposable will be disposed when the `delay` is passed.
```js
import { createDebounceResource } from '@vates/disposable/debounceResource'
const debounceResource = createDebounceResource()
// it will wait for 10 seconds before calling the disposer
Disposable.use(debounceResource(getConnection(host), 10e3), connection => {})
```
### `debounceResource.flushAll()`
Disposes all delayed disposers and cancels the delaying of the disposables that are in usage.
```js
import { createDebounceResource } from '@vates/disposable/debounceResource'
const debounceResource = createDebounceResource()
const res1 = await debounceResource(res, 10e3)
const res2 = await debounceResource(res, 10e3)
const res3 = await debounceResource(res, 10e3)
rest1.dispose()
rest2.dispose()
// res3 is in usage
debounceResource.flushAll()
// res1 and res2 are immediately disposed
// res3 will be disposed immediately when its disposer will be called
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

View File

@@ -0,0 +1,56 @@
This library contains utilities for disposables as defined by the [`promise-toolbox` library](https://github.com/JsCommunity/promise-toolbox#resource-management).
### `deduped(fn, keyFn)`
Creates a new function that wraps `fn` and instead of creating a new disposables at each call, returns copies of the same one when `keyFn` returns the same keys.
Those copies contains the same value and can be disposed independently, the source disposable will only be disposed when all copies are disposed.
`keyFn` is called with the same context and arguments as the wrapping function and must returns an array of keys which will be used to identify which disposables should be grouped together.
```js
import { deduped } from '@vates/disposable/deduped'
// the connection with the passed host will be established once at the first call, then, it will be shared with the next calls
const getConnection = deduped(async function (host)) {
const connection = new Connection(host)
return new Disposabe(connection, () => connection.close())
}, host => [host])
```
### `debounceResource(disposable, delay)`
Creates a new disposable with the same value and with a delayed disposer.
On calling this disposer, the source disposable will be disposed when the `delay` is passed.
```js
import { createDebounceResource } from '@vates/disposable/debounceResource'
const debounceResource = createDebounceResource()
// it will wait for 10 seconds before calling the disposer
Disposable.use(debounceResource(getConnection(host), 10e3), connection => {})
```
### `debounceResource.flushAll()`
Disposes all delayed disposers and cancels the delaying of the disposables that are in usage.
```js
import { createDebounceResource } from '@vates/disposable/debounceResource'
const debounceResource = createDebounceResource()
const res1 = await debounceResource(res, 10e3)
const res2 = await debounceResource(res, 10e3)
const res3 = await debounceResource(res, 10e3)
rest1.dispose()
rest2.dispose()
// res3 is in usage
debounceResource.flushAll()
// res1 and res2 are immediately disposed
// res3 will be disposed immediately when its disposer will be called
```

View File

@@ -0,0 +1,56 @@
const { asyncMap } = require('@xen-orchestra/async-map')
const { createLogger } = require('@xen-orchestra/log')
const { warn } = createLogger('vates:disposable:debounceResource')
exports.createDebounceResource = () => {
const flushers = new Set()
async function debounceResource(pDisposable, delay = debounceResource.defaultDelay) {
if (delay === 0) {
return pDisposable
}
const disposable = await pDisposable
let timeoutId
const disposeWrapper = async () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId)
timeoutId = undefined
flushers.delete(flusher)
try {
await disposable.dispose()
} catch (error) {
warn(error)
}
}
}
const flusher = () => {
const shouldDisposeNow = timeoutId !== undefined
if (shouldDisposeNow) {
return disposeWrapper()
} else {
// will dispose ASAP
delay = 0
}
}
flushers.add(flusher)
return {
dispose() {
timeoutId = setTimeout(disposeWrapper, delay)
},
value: disposable.value,
}
}
debounceResource.flushAll = () => {
// iterate on a sync way in order to not remove a flusher added on processing flushers
const promise = asyncMap(flushers, flush => flush())
flushers.clear()
return promise
}
return debounceResource
}

View File

@@ -0,0 +1,29 @@
/* eslint-env jest */
const { createDebounceResource } = require('./debounceResource')
jest.useFakeTimers()
describe('debounceResource()', () => {
it('calls the resource disposer after 10 seconds', async () => {
const debounceResource = createDebounceResource()
const delay = 10e3
const dispose = jest.fn()
const resource = await debounceResource(
Promise.resolve({
value: '',
dispose,
}),
delay
)
resource.dispose()
expect(dispose).not.toBeCalled()
jest.advanceTimersByTime(delay)
expect(dispose).toBeCalled()
})
})

View File

@@ -0,0 +1,52 @@
const ensureArray = require('ensure-array')
const { MultiKeyMap } = require('@vates/multi-key-map')
function State(factory) {
this.factory = factory
this.users = 0
}
const call = fn => fn()
exports.deduped = (factory, keyFn = (...args) => args) =>
(function () {
const states = new MultiKeyMap()
return function () {
const keys = ensureArray(keyFn.apply(this, arguments))
let state = states.get(keys)
if (state === undefined) {
const result = factory.apply(this, arguments)
const createFactory = disposable => {
const wrapper = {
dispose() {
if (--state.users === 0) {
states.delete(keys)
return disposable.dispose()
}
},
value: disposable.value,
}
return () => {
return wrapper
}
}
if (typeof result.then !== 'function') {
state = new State(createFactory(result))
} else {
result.catch(() => {
states.delete(keys)
})
const pFactory = result.then(createFactory)
state = new State(() => pFactory.then(call))
}
states.set(keys, state)
}
++state.users
return state.factory()
}
})()

View File

@@ -0,0 +1,76 @@
/* eslint-env jest */
const { deduped } = require('./deduped')
describe('deduped()', () => {
it('calls the resource function only once', async () => {
const value = {}
const getResource = jest.fn(async () => ({
value,
dispose: Function.prototype,
}))
const dedupedGetResource = deduped(getResource)
const { value: v1 } = await dedupedGetResource()
const { value: v2 } = await dedupedGetResource()
expect(getResource).toHaveBeenCalledTimes(1)
expect(v1).toBe(value)
expect(v2).toBe(value)
})
it('only disposes the source disposable when its all copies dispose', async () => {
const dispose = jest.fn()
const getResource = async () => ({
value: '',
dispose,
})
const dedupedGetResource = deduped(getResource)
const { dispose: d1 } = await dedupedGetResource()
const { dispose: d2 } = await dedupedGetResource()
d1()
expect(dispose).not.toHaveBeenCalled()
d2()
expect(dispose).toHaveBeenCalledTimes(1)
})
it('works with sync factory', () => {
const value = {}
const dispose = jest.fn()
const dedupedGetResource = deduped(() => ({ value, dispose }))
const d1 = dedupedGetResource()
expect(d1.value).toBe(value)
const d2 = dedupedGetResource()
expect(d2.value).toBe(value)
d1.dispose()
expect(dispose).not.toHaveBeenCalled()
d2.dispose()
expect(dispose).toHaveBeenCalledTimes(1)
})
it('no race condition on dispose before async acquisition', async () => {
const dispose = jest.fn()
const dedupedGetResource = deduped(async () => ({ value: 42, dispose }))
const d1 = await dedupedGetResource()
dedupedGetResource()
d1.dispose()
expect(dispose).not.toHaveBeenCalled()
})
})

View File

@@ -0,0 +1,30 @@
{
"private": false,
"name": "@vates/disposable",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/disposable",
"description": "Utilities for disposables",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@vates/disposable",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.1",
"engines": {
"node": ">=8.10"
},
"scripts": {
"postversion": "npm publish --access public"
},
"dependencies": {
"@vates/multi-key-map": "^0.1.0",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/log": "^0.3.0",
"ensure-array": "^1.0.0"
}
}

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -44,4 +44,4 @@ You may:
## License
[AGPL-3.0-or-later](https://spdx.org/licenses/AGPL-3.0-or-later) © [Vates SAS](https://vates.fr)
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

View File

@@ -6,7 +6,7 @@ exports.parseDuration = value => {
}
const duration = ms(value)
if (duration === undefined) {
throw new TypeError(`not a valid duration: ${duration}`)
throw new TypeError(`not a valid duration: ${value}`)
}
return duration
}

View File

@@ -18,8 +18,8 @@
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "AGPL-3.0-or-later",
"version": "0.1.0",
"license": "ISC",
"version": "0.1.1",
"engines": {
"node": ">=8.10"
},

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -1,27 +1,30 @@
exports.readChunk = (stream, size) =>
new Promise((resolve, reject) => {
function onEnd() {
resolve(null)
removeListeners()
}
function onError(error) {
reject(error)
removeListeners()
}
function onReadable() {
const data = stream.read(size)
if (data !== null) {
resolve(data)
removeListeners()
}
}
function removeListeners() {
stream.removeListener('end', onEnd)
stream.removeListener('error', onError)
stream.removeListener('readable', onReadable)
}
stream.on('end', onEnd)
stream.on('error', onError)
stream.on('readable', onReadable)
onReadable()
})
const readChunk = (stream, size) =>
size === 0
? Promise.resolve(Buffer.alloc(0))
: new Promise((resolve, reject) => {
function onEnd() {
resolve(null)
removeListeners()
}
function onError(error) {
reject(error)
removeListeners()
}
function onReadable() {
const data = stream.read(size)
if (data !== null) {
resolve(data)
removeListeners()
}
}
function removeListeners() {
stream.removeListener('end', onEnd)
stream.removeListener('error', onError)
stream.removeListener('readable', onReadable)
}
stream.on('end', onEnd)
stream.on('error', onError)
stream.on('readable', onReadable)
onReadable()
})
exports.readChunk = readChunk

View File

@@ -0,0 +1,43 @@
/* eslint-env jest */
const { Readable } = require('stream')
const { readChunk } = require('./')
const makeStream = it => Readable.from(it, { objectMode: false })
makeStream.obj = Readable.from
describe('readChunk', () => {
it('returns null if stream is empty', async () => {
expect(await readChunk(makeStream([]))).toBe(null)
})
describe('with binary stream', () => {
it('returns the first chunk of data', async () => {
expect(await readChunk(makeStream(['foo', 'bar']))).toEqual(Buffer.from('foo'))
})
it('returns a chunk of the specified size (smaller than first)', async () => {
expect(await readChunk(makeStream(['foo', 'bar']), 2)).toEqual(Buffer.from('fo'))
})
it('returns a chunk of the specified size (larger than first)', async () => {
expect(await readChunk(makeStream(['foo', 'bar']), 4)).toEqual(Buffer.from('foob'))
})
it('returns less data if stream ends', async () => {
expect(await readChunk(makeStream(['foo', 'bar']), 10)).toEqual(Buffer.from('foobar'))
})
it('returns an empty buffer if the specified size is 0', async () => {
expect(await readChunk(makeStream(['foo', 'bar']), 0)).toEqual(Buffer.alloc(0))
})
})
describe('with object stream', () => {
it('returns the first chunk of data verbatim', async () => {
const chunks = [{}, {}]
expect(await readChunk(makeStream.obj(chunks))).toBe(chunks[0])
})
})
})

View File

@@ -19,7 +19,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.1.1",
"version": "0.1.2",
"engines": {
"node": ">=8.10"
},

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1,59 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @vates/toggle-scripts
[![Package Version](https://badgen.net/npm/v/@vates/toggle-scripts)](https://npmjs.org/package/@vates/toggle-scripts) ![License](https://badgen.net/npm/license/@vates/toggle-scripts) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@vates/toggle-scripts)](https://bundlephobia.com/result?p=@vates/toggle-scripts) [![Node compatibility](https://badgen.net/npm/node/@vates/toggle-scripts)](https://npmjs.org/package/@vates/toggle-scripts)
> Easily enable/disable scripts in package.json
## Install
Installation of the [npm package](https://npmjs.org/package/@vates/toggle-scripts):
```
> npm install --save @vates/toggle-scripts
```
## Usage
```
Usage: toggle-scripts options...
Easily enable/disable scripts in package.json
Options
+<script> Enable the script <script>, ie remove the prefix `_`
-<script> Disable the script <script>, ie prefix it with `_`
Examples
toggle-scripts +postinstall +preuninstall
toggle-scripts -postinstall -preuninstall
```
For example, if you want `postinstall` hook only in dev:
```json
// package.json
{
"scripts": {
"postinstall": "<some dev only command>",
"prepublishOnly": "toggle-scripts -postinstall",
"postpublish": "toggle-scripts +postinstall"
}
}
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

View File

@@ -0,0 +1,26 @@
```
Usage: toggle-scripts options...
Easily enable/disable scripts in package.json
Options
+<script> Enable the script <script>, ie remove the prefix `_`
-<script> Disable the script <script>, ie prefix it with `_`
Examples
toggle-scripts +postinstall +preuninstall
toggle-scripts -postinstall -preuninstall
```
For example, if you want `postinstall` hook only in dev:
```json
// package.json
{
"scripts": {
"postinstall": "<some dev only command>",
"prepublishOnly": "toggle-scripts -postinstall",
"postpublish": "toggle-scripts +postinstall"
}
}
```

60
@vates/toggle-scripts/index.js Executable file
View File

@@ -0,0 +1,60 @@
#!/usr/bin/env node
const fs = require('fs')
const mapKeys = (object, iteratee) => {
const result = {}
for (const key of Object.keys(object)) {
result[iteratee(key, object)] = object[key]
}
return result
}
const args = process.argv.slice(2)
if (args.length === 0) {
const { description, name, version } = require('./package.json')
const bin = 'toggle-scripts'
process.stdout.write(`Usage: ${bin} options...
${description}
Options
+<script> Enable the script <script>, ie remove the prefix \`_\`
-<script> Disable the script <script>, ie prefix it with \`_\`
Examples
${bin} +postinstall +preuninstall
${bin} -postinstall -preuninstall
${name} v${version}
`)
process.exit()
}
const plan = { __proto__: null }
for (const arg of args) {
const action = arg[0]
const script = arg.slice(1)
if (action === '+') {
plan['_' + script] = script
} else if (action === '-') {
plan[script] = '_' + script
} else {
throw new Error('invalid param: ' + arg)
}
}
const pkgPath = process.env.npm_package_json || './package.json'
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
pkg.scripts = mapKeys(pkg.scripts, (name, scripts) => {
const newName = plan[name]
if (newName === undefined) {
return name
}
if (newName in scripts) {
throw new Error('script already defined: ' + name)
}
return newName
})
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')

View File

@@ -0,0 +1,38 @@
{
"private": false,
"name": "@vates/toggle-scripts",
"description": "Easily enable/disable scripts in package.json",
"keywords": [
"dev",
"disable",
"enable",
"lifecycle",
"npm",
"package.json",
"pinst",
"postinstall",
"script",
"scripts",
"toggle"
],
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/toggle-scripts",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@vates/toggle-scripts",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "ISC",
"version": "1.0.0",
"engines": {
"node": ">=6"
},
"bin": "./index.js",
"scripts": {
"postversion": "npm publish --access public"
}
}

View File

@@ -1,24 +0,0 @@
/benchmark/
/benchmarks/
*.bench.js
*.bench.js.map
/examples/
example.js
example.js.map
*.example.js
*.example.js.map
/fixture/
/fixtures/
*.fixture.js
*.fixture.js.map
*.fixtures.js
*.fixtures.js.map
/test/
/tests/
*.spec.js
*.spec.js.map
__snapshots__/

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -4,7 +4,7 @@
[![Package Version](https://badgen.net/npm/v/@xen-orchestra/async-map)](https://npmjs.org/package/@xen-orchestra/async-map) ![License](https://badgen.net/npm/license/@xen-orchestra/async-map) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@xen-orchestra/async-map)](https://bundlephobia.com/result?p=@xen-orchestra/async-map) [![Node compatibility](https://badgen.net/npm/node/@xen-orchestra/async-map)](https://npmjs.org/package/@xen-orchestra/async-map)
> Similar to Promise.all + lodash.map but wait for all promises to be settled
> Promise.all + map for all iterables
## Install
@@ -16,10 +16,61 @@ Installation of the [npm package](https://npmjs.org/package/@xen-orchestra/async
## Usage
```js
import asyncMap from '@xen-orchestra/async-map'
### `asyncMap(iterable, iteratee, thisArg = iterable)`
const array = await asyncMap(collection, iteratee)
Similar to `Promise.all + Array#map` for all iterables: calls `iteratee` for each item in `iterable`, and returns a promise of an array containing the awaited result of each calls to `iteratee`.
It rejects as soon as te first call to `iteratee` rejects.
```js
import { asyncMap } from '@xen-orchestra/async-map'
const array = await asyncMap(iterable, iteratee, thisArg)
```
It can be used with any iterables (`Array`, `Map`, etc.):
```js
const map = new Map()
map.set('foo', 42)
map.set('bar', 3.14)
const array = await asyncMap(map, async function ([key, value]) {
// TODO: do async computation
//
// the map can be accessed via `this`
})
```
#### Use with plain objects
Plain objects are not iterable, but you can use `Object.keys`, `Object.values` or `Object.entries` to help:
```js
const object = {
foo: 42,
bar: 3.14,
}
const array = await asyncMap(
Object.entries(object),
async function ([key, value]) {
// TODO: do async computation
//
// the object can be accessed via `this` because it's been passed as third arg
},
object
)
```
### `asyncMapSettled(iterable, iteratee, thisArg = iterable)`
Similar to `asyncMap` but waits for all promises to settle before rejecting.
```js
import { asyncMapSettled } from '@xen-orchestra/async-map'
const array = await asyncMapSettled(iterable, iteratee, thisArg)
```
## Contributions

View File

@@ -1,5 +1,56 @@
```js
import asyncMap from '@xen-orchestra/async-map'
### `asyncMap(iterable, iteratee, thisArg = iterable)`
const array = await asyncMap(collection, iteratee)
Similar to `Promise.all + Array#map` for all iterables: calls `iteratee` for each item in `iterable`, and returns a promise of an array containing the awaited result of each calls to `iteratee`.
It rejects as soon as te first call to `iteratee` rejects.
```js
import { asyncMap } from '@xen-orchestra/async-map'
const array = await asyncMap(iterable, iteratee, thisArg)
```
It can be used with any iterables (`Array`, `Map`, etc.):
```js
const map = new Map()
map.set('foo', 42)
map.set('bar', 3.14)
const array = await asyncMap(map, async function ([key, value]) {
// TODO: do async computation
//
// the map can be accessed via `this`
})
```
#### Use with plain objects
Plain objects are not iterable, but you can use `Object.keys`, `Object.values` or `Object.entries` to help:
```js
const object = {
foo: 42,
bar: 3.14,
}
const array = await asyncMap(
Object.entries(object),
async function ([key, value]) {
// TODO: do async computation
//
// the object can be accessed via `this` because it's been passed as third arg
},
object
)
```
### `asyncMapSettled(iterable, iteratee, thisArg = iterable)`
Similar to `asyncMap` but waits for all promises to settle before rejecting.
```js
import { asyncMapSettled } from '@xen-orchestra/async-map'
const array = await asyncMapSettled(iterable, iteratee, thisArg)
```

View File

@@ -0,0 +1,71 @@
const wrapCall = (fn, arg, thisArg) => {
try {
return Promise.resolve(fn.call(thisArg, arg))
} catch (error) {
return Promise.reject(error)
}
}
/**
* Similar to Promise.all + Array#map but supports all iterables and does not trigger ESLint array-callback-return
*
* WARNING: Does not handle plain objects
*
* @template Item,This
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
*/
exports.asyncMap = function asyncMap(iterable, mapFn, thisArg = iterable) {
return Promise.all(Array.from(iterable, mapFn, thisArg))
}
/**
* Like `asyncMap` but wait for all promises to settle before rejecting
*
* @template Item,This
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
*/
exports.asyncMapSettled = function asyncMapSettled(iterable, mapFn, thisArg = iterable) {
return new Promise((resolve, reject) => {
const onError = e => {
if (result !== undefined) {
error = e
result = undefined
}
if (--n === 0) {
reject(error)
}
}
const onValue = (i, value) => {
const hasError = result === undefined
if (!hasError) {
result[i] = value
}
if (--n === 0) {
if (hasError) {
reject(error)
} else {
resolve(result)
}
}
}
let n = 0
for (const item of iterable) {
const i = n++
wrapCall(mapFn, item, thisArg).then(value => onValue(i, value), onError)
}
if (n === 0) {
return resolve([])
}
let error
let result = new Array(n)
})
}

View File

@@ -0,0 +1,71 @@
/* eslint-env jest */
const { asyncMapSettled } = require('./')
const noop = Function.prototype
describe('asyncMapSettled', () => {
it('works', async () => {
const values = [Math.random(), Math.random()]
const spy = jest.fn(async v => v * 2)
const iterable = new Set(values)
// returns an array containing the result of each calls
expect(await asyncMapSettled(iterable, spy)).toEqual(values.map(value => value * 2))
for (let i = 0, n = values.length; i < n; ++i) {
// each call receive the current item as sole argument
expect(spy.mock.calls[i]).toEqual([values[i]])
// each call as this bind to the iterable
expect(spy.mock.instances[i]).toBe(iterable)
}
})
it('can use a specified thisArg', () => {
const thisArg = {}
const spy = jest.fn()
asyncMapSettled(['foo'], spy, thisArg)
expect(spy.mock.instances[0]).toBe(thisArg)
})
it('rejects only when all calls as resolved', async () => {
const defers = []
const promise = asyncMapSettled([1, 2], () => {
let resolve, reject
// eslint-disable-next-line promise/param-names
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
defers.push({ promise, resolve, reject })
return promise
})
let hasSettled = false
promise.catch(noop).then(() => {
hasSettled = true
})
const error = new Error()
defers[0].reject(error)
// wait for all microtasks to settle
await new Promise(resolve => setImmediate(resolve))
expect(hasSettled).toBe(false)
defers[1].resolve()
// wait for all microtasks to settle
await new Promise(resolve => setImmediate(resolve))
expect(hasSettled).toBe(true)
await expect(promise).rejects.toBe(error)
})
it('issues when latest promise rejects', async () => {
const error = new Error()
await expect(asyncMapSettled([1], () => Promise.reject(error))).rejects.toBe(error)
})
})

View File

@@ -9,14 +9,18 @@
// (V1, K) => MaybePromise<V2>
// ): Promise<V2[]>
import map from 'lodash/map'
const map = require('lodash/map')
// Similar to map() + Promise.all() but wait for all promises to
// settle before rejecting (with the first error)
const asyncMap = (collection, iteratee) => {
/**
* Similar to map() + Promise.all() but wait for all promises to settle before
* rejecting (with the first error)
*
* @deprecated Don't support iterables, please use new implementations
*/
module.exports = function asyncMapLegacy(collection, iteratee) {
let then
if (collection != null && typeof (then = collection.then) === 'function') {
return then.call(collection, collection => asyncMap(collection, iteratee))
return then.call(collection, collection => asyncMapLegacy(collection, iteratee))
}
let errorContainer
@@ -39,5 +43,3 @@ const asyncMap = (collection, iteratee) => {
return values
})
}
export { asyncMap as default }

View File

@@ -1,10 +1,17 @@
{
"private": false,
"name": "@xen-orchestra/async-map",
"version": "0.0.0",
"version": "0.1.2",
"license": "ISC",
"description": "Similar to Promise.all + lodash.map but wait for all promises to be settled",
"keywords": [],
"description": "Promise.all + map for all iterables",
"keywords": [
"array",
"async",
"iterable",
"map",
"settled",
"typescript"
],
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/async-map",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
@@ -17,36 +24,13 @@
"url": "https://vates.fr"
},
"preferGlobal": false,
"main": "dist/",
"bin": {},
"files": [
"dist/"
],
"browserslist": [
">2%"
],
"engines": {
"node": ">=6"
},
"dependencies": {
"lodash": "^4.17.4"
},
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-flow": "^7.0.0",
"babel-plugin-lodash": "^3.3.2",
"cross-env": "^7.0.2",
"rimraf": "^3.0.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production babel --source-maps --out-dir=dist/ src/",
"clean": "rimraf dist/",
"dev": "cross-env NODE_ENV=development babel --watch --source-maps --out-dir=dist/ src/",
"prebuild": "yarn run clean",
"predev": "yarn run prebuild",
"prepublishOnly": "yarn run build",
"postversion": "npm publish"
}
}

View File

@@ -0,0 +1 @@
../../scripts/babel-eslintrc.js

View File

@@ -1,24 +0,0 @@
/benchmark/
/benchmarks/
*.bench.js
*.bench.js.map
/examples/
example.js
example.js.map
*.example.js
*.example.js.map
/fixture/
/fixtures/
*.fixture.js
*.fixture.js.map
*.fixtures.js
*.fixtures.js.map
/test/
/tests/
*.spec.js
*.spec.js.map
__snapshots__/

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -9,7 +9,7 @@
},
"version": "0.2.0",
"engines": {
"node": ">=8.10"
"node": ">=10"
},
"main": "dist/",
"scripts": {
@@ -26,14 +26,13 @@
"@babel/plugin-proposal-decorators": "^7.8.0",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.8.0",
"@babel/preset-env": "^7.7.4",
"cross": "^1.0.0",
"cross-env": "^7.0.2",
"rimraf": "^3.0.0"
},
"dependencies": {
"@xen-orchestra/log": "^0.2.0",
"core-js": "^3.6.4",
"golike-defer": "^0.4.1",
"lodash": "^4.17.15",
"@vates/decorate-with": "^0.1.0",
"@xen-orchestra/log": "^0.3.0",
"golike-defer": "^0.5.1",
"object-hash": "^2.0.1"
},
"private": false,

View File

@@ -1,10 +1,8 @@
// see https://github.com/babel/babel/issues/8450
import 'core-js/features/symbol/async-iterator'
import assert from 'assert'
import createLogger from '@xen-orchestra/log'
import defer from 'golike-defer'
import hash from 'object-hash'
import { createLogger } from '@xen-orchestra/log'
import { decorateWith } from '@vates/decorate-with'
import { defer } from 'golike-defer'
const log = createLogger('xo:audit-core')
@@ -65,7 +63,7 @@ export class AuditCore {
this._storage = storage
}
@defer
@decorateWith(defer)
async add($defer, subject, event, data) {
const time = Date.now()
$defer(await this._storage.acquireLock())
@@ -150,7 +148,7 @@ export class AuditCore {
}
}
@defer
@decorateWith(defer)
async deleteRangeAndRewrite($defer, newest, oldest) {
assert.notStrictEqual(newest, undefined)
assert.notStrictEqual(oldest, undefined)

View File

@@ -17,10 +17,10 @@ interface Record {
}
export class AuditCore {
constructor(storage: Storage) { }
public add(subject: any, event: string, data: any): Promise<Record> { }
public checkIntegrity(oldest: string, newest: string): Promise<number> { }
public getFrom(newest?: string): AsyncIterator { }
public deleteFrom(newest: string): Promise<void> { }
public deleteRangeAndRewrite(newest: string, oldest: string): Promise<void> { }
constructor(storage: Storage) {}
public add(subject: any, event: string, data: any): Promise<Record> {}
public checkIntegrity(oldest: string, newest: string): Promise<number> {}
public getFrom(newest?: string): AsyncIterator {}
public deleteFrom(newest: string): Promise<void> {}
public deleteRangeAndRewrite(newest: string, oldest: string): Promise<void> {}
}

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -14,25 +14,13 @@ const configs = {
'@babel/plugin-proposal-pipeline-operator': {
proposal: 'minimal',
},
'@babel/preset-env'(pkg) {
return {
debug: !__TEST__,
'@babel/preset-env': {
debug: !__TEST__,
// disabled until https://github.com/babel/babel/issues/8323 is resolved
// loose: true,
// disabled until https://github.com/babel/babel/issues/8323 is resolved
// loose: true,
shippedProposals: true,
targets: (() => {
let node = (pkg.engines || {}).node
if (node !== undefined) {
const trimChars = '^=>~'
while (trimChars.includes(node[0])) {
node = node.slice(1)
}
}
return { browsers: pkg.browserslist, node }
})(),
}
shippedProposals: true,
},
}
@@ -44,21 +32,21 @@ const getConfig = (key, ...args) => {
// some plugins must be used in a specific order
const pluginsOrder = ['@babel/plugin-proposal-decorators', '@babel/plugin-proposal-class-properties']
module.exports = function (pkg, plugins, presets) {
plugins === undefined && (plugins = {})
presets === undefined && (presets = {})
module.exports = function (pkg, configs = {}) {
const plugins = {}
const presets = {}
Object.keys(pkg.devDependencies || {}).forEach(name => {
if (!(name in presets) && PLUGINS_RE.test(name)) {
plugins[name] = getConfig(name, pkg)
plugins[name] = { ...getConfig(name, pkg), ...configs[name] }
} else if (!(name in presets) && PRESETS_RE.test(name)) {
presets[name] = getConfig(name, pkg)
presets[name] = { ...getConfig(name, pkg), ...configs[name] }
}
})
return {
comments: !__PROD__,
ignore: __TEST__ ? undefined : [/\.spec\.js$/],
ignore: __PROD__ ? [/\btests?\//, /\.spec\.js$/] : undefined,
plugins: Object.keys(plugins)
.map(plugin => [plugin, plugins[plugin]])
.sort(([a], [b]) => {
@@ -67,5 +55,15 @@ module.exports = function (pkg, plugins, presets) {
return oA !== -1 && oB !== -1 ? oA - oB : a < b ? -1 : 1
}),
presets: Object.keys(presets).map(preset => [preset, presets[preset]]),
targets: (() => {
let node = (pkg.engines || {}).node
if (node !== undefined) {
const trimChars = '^=>~'
while (trimChars.includes(node[0])) {
node = node.slice(1)
}
}
return { browsers: pkg.browserslist, node }
})(),
}
}

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -12,6 +12,26 @@ Installation of the [npm package](https://npmjs.org/package/@xen-orchestra/backu
> npm install --global @xen-orchestra/backups-cli
```
## Usage
```
> xo-backups --help
Usage:
xo-backups clean-vms [--merge] [--remove] xo-vm-backups/*
Detects and repair issues with VM backups.
Options:
-m, --merge Merge (or continue merging) VHD files that are unused
-r, --remove Remove unused, incomplete, orphan, or corrupted files
xo-backups create-symlink-index xo-vm-backups <field path>
xo-backups info xo-vm-backups/*
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on

View File

@@ -0,0 +1,17 @@
```
> xo-backups --help
Usage:
xo-backups clean-vms [--merge] [--remove] xo-vm-backups/*
Detects and repair issues with VM backups.
Options:
-m, --merge Merge (or continue merging) VHD files that are unused
-r, --remove Remove unused, incomplete, orphan, or corrupted files
xo-backups create-symlink-index xo-vm-backups <field path>
xo-backups info xo-vm-backups/*
```

View File

@@ -1,5 +0,0 @@
const curryRight = require('lodash/curryRight')
module.exports = curryRight((iterable, fn) =>
Promise.all(Array.isArray(iterable) ? iterable.map(fn) : Array.from(iterable, fn))
)

View File

@@ -1,336 +1,34 @@
#!/usr/bin/env node
// assigned when options are parsed by the main function
let force, merge
// -----------------------------------------------------------------------------
const assert = require('assert')
const flatten = require('lodash/flatten')
const asyncMap = require('lodash/curryRight')(require('@xen-orchestra/async-map').asyncMap)
const getopts = require('getopts')
const limitConcurrency = require('limit-concurrency-decorator').default
const lockfile = require('proper-lockfile')
const pipe = require('promise-toolbox/pipe')
const { default: Vhd, mergeVhd } = require('vhd-lib')
const { dirname, resolve } = require('path')
const { DISK_TYPE_DIFFERENCING } = require('vhd-lib/dist/_constants')
const { isValidXva } = require('@xen-orchestra/backups/isValidXva')
const { RemoteAdapter } = require('@xen-orchestra/backups/RemoteAdapter')
const { resolve } = require('path')
const asyncMap = require('../_asyncMap')
const fs = require('../_fs')
const handler = require('@xen-orchestra/fs').getHandler({ url: 'file://' })
// -----------------------------------------------------------------------------
// chain is an array of VHDs from child to parent
//
// the whole chain will be merged into parent, parent will be renamed to child
// and all the others will deleted
const mergeVhdChain = limitConcurrency(1)(async function mergeVhdChain(chain) {
assert(chain.length >= 2)
let child = chain[0]
const parent = chain[chain.length - 1]
const children = chain.slice(0, -1).reverse()
console.warn('Unused parents of VHD', child)
chain
.slice(1)
.reverse()
.forEach(parent => {
console.warn(' ', parent)
})
merge && console.warn(' merging…')
console.warn('')
if (merge) {
// `mergeVhd` does not work with a stream, either
// - make it accept a stream
// - or create synthetic VHD which is not a stream
if (children.length !== 1) {
console.warn('TODO: implement merging multiple children')
children.length = 1
child = children[0]
}
let done, total
const handle = setInterval(() => {
if (done !== undefined) {
console.log('merging %s: %s/%s', child, done, total)
}
}, 10e3)
await mergeVhd(
handler,
parent,
handler,
child,
// children.length === 1
// ? child
// : await createSyntheticStream(handler, children),
{
onProgress({ done: d, total: t }) {
done = d
total = t
},
}
)
clearInterval(handle)
}
await Promise.all([
force && fs.rename(parent, child),
asyncMap(children.slice(0, -1), child => {
console.warn('Unused VHD', child)
force && console.warn(' deleting…')
console.warn('')
return force && handler.unlink(child)
}),
])
})
const listVhds = pipe([
vmDir => vmDir + '/vdis',
fs.readdir2,
asyncMap(fs.readdir2),
flatten,
asyncMap(fs.readdir2),
flatten,
_ => _.filter(_ => _.endsWith('.vhd')),
])
async function handleVm(vmDir) {
const vhds = new Set()
const vhdParents = { __proto__: null }
const vhdChildren = { __proto__: null }
// remove broken VHDs
await asyncMap(await listVhds(vmDir), async path => {
try {
const vhd = new Vhd(handler, path)
await vhd.readHeaderAndFooter()
vhds.add(path)
if (vhd.footer.diskType === DISK_TYPE_DIFFERENCING) {
const parent = resolve(dirname(path), vhd.header.parentUnicodeName)
vhdParents[path] = parent
if (parent in vhdChildren) {
const error = new Error('this script does not support multiple VHD children')
error.parent = parent
error.child1 = vhdChildren[parent]
error.child2 = path
throw error // should we throw?
}
vhdChildren[parent] = path
}
} catch (error) {
console.warn('Error while checking VHD', path)
console.warn(' ', error)
if (error != null && error.code === 'ERR_ASSERTION') {
force && console.warn(' deleting…')
console.warn('')
force && (await handler.unlink(path))
}
}
})
// remove VHDs with missing ancestors
{
const deletions = []
// return true if the VHD has been deleted or is missing
const deleteIfOrphan = vhd => {
const parent = vhdParents[vhd]
if (parent === undefined) {
return
}
// no longer needs to be checked
delete vhdParents[vhd]
deleteIfOrphan(parent)
if (!vhds.has(parent)) {
vhds.delete(vhd)
console.warn('Error while checking VHD', vhd)
console.warn(' missing parent', parent)
force && console.warn(' deleting…')
console.warn('')
force && deletions.push(handler.unlink(vhd))
}
}
// > A property that is deleted before it has been visited will not be
// > visited later.
// >
// > -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Deleted_added_or_modified_properties
for (const child in vhdParents) {
deleteIfOrphan(child)
}
await Promise.all(deletions)
}
const [jsons, xvas, xvaSums] = await fs
.readdir2(vmDir)
.then(entries => [
entries.filter(_ => _.endsWith('.json')),
new Set(entries.filter(_ => _.endsWith('.xva'))),
entries.filter(_ => _.endsWith('.xva.cheksum')),
])
await asyncMap(xvas, async path => {
// check is not good enough to delete the file, the best we can do is report
// it
if (!(await isValidXva(path))) {
console.warn('Potential broken XVA', path)
console.warn('')
}
})
const unusedVhds = new Set(vhds)
const unusedXvas = new Set(xvas)
// compile the list of unused XVAs and VHDs, and remove backup metadata which
// reference a missing XVA/VHD
await asyncMap(jsons, async json => {
const metadata = JSON.parse(await fs.readFile(json))
const { mode } = metadata
if (mode === 'full') {
const linkedXva = resolve(vmDir, metadata.xva)
if (xvas.has(linkedXva)) {
unusedXvas.delete(linkedXva)
} else {
console.warn('Error while checking backup', json)
console.warn(' missing file', linkedXva)
force && console.warn(' deleting…')
console.warn('')
force && (await handler.unlink(json))
}
} else if (mode === 'delta') {
const linkedVhds = (() => {
const { vhds } = metadata
return Object.keys(vhds).map(key => resolve(vmDir, vhds[key]))
})()
// FIXME: find better approach by keeping as much of the backup as
// possible (existing disks) even if one disk is missing
if (linkedVhds.every(_ => vhds.has(_))) {
linkedVhds.forEach(_ => unusedVhds.delete(_))
} else {
console.warn('Error while checking backup', json)
const missingVhds = linkedVhds.filter(_ => !vhds.has(_))
console.warn(' %i/%i missing VHDs', missingVhds.length, linkedVhds.length)
missingVhds.forEach(vhd => {
console.warn(' ', vhd)
})
force && console.warn(' deleting…')
console.warn('')
force && (await handler.unlink(json))
}
}
})
// TODO: parallelize by vm/job/vdi
const unusedVhdsDeletion = []
{
// VHD chains (as list from child to ancestor) to merge indexed by last
// ancestor
const vhdChainsToMerge = { __proto__: null }
const toCheck = new Set(unusedVhds)
const getUsedChildChainOrDelete = vhd => {
if (vhd in vhdChainsToMerge) {
const chain = vhdChainsToMerge[vhd]
delete vhdChainsToMerge[vhd]
return chain
}
if (!unusedVhds.has(vhd)) {
return [vhd]
}
// no longer needs to be checked
toCheck.delete(vhd)
const child = vhdChildren[vhd]
if (child !== undefined) {
const chain = getUsedChildChainOrDelete(child)
if (chain !== undefined) {
chain.push(vhd)
return chain
}
}
console.warn('Unused VHD', vhd)
force && console.warn(' deleting…')
console.warn('')
force && unusedVhdsDeletion.push(handler.unlink(vhd))
}
toCheck.forEach(vhd => {
vhdChainsToMerge[vhd] = getUsedChildChainOrDelete(vhd)
})
Object.keys(vhdChainsToMerge).forEach(key => {
const chain = vhdChainsToMerge[key]
if (chain !== undefined) {
unusedVhdsDeletion.push(mergeVhdChain(chain))
}
})
}
await Promise.all([
unusedVhdsDeletion,
asyncMap(unusedXvas, path => {
console.warn('Unused XVA', path)
force && console.warn(' deleting…')
console.warn('')
return force && handler.unlink(path)
}),
asyncMap(xvaSums, path => {
// no need to handle checksums for XVAs deleted by the script, they will be handled by `unlink()`
if (!xvas.has(path.slice(0, -'.checksum'.length))) {
console.warn('Unused XVA checksum', path)
force && console.warn(' deleting…')
console.warn('')
return force && handler.unlink(path)
}
}),
])
}
// -----------------------------------------------------------------------------
const adapter = new RemoteAdapter(require('@xen-orchestra/fs').getHandler({ url: 'file://' }))
module.exports = async function main(args) {
const opts = getopts(args, {
const { _, fix, remove, merge } = getopts(args, {
alias: {
force: 'f',
fix: 'f',
remove: 'r',
merge: 'm',
},
boolean: ['force', 'merge'],
boolean: ['fix', 'merge', 'remove'],
default: {
force: false,
merge: false,
remove: false,
},
})
;({ force, merge } = opts)
await asyncMap(opts._, async vmDir => {
await asyncMap(_, async vmDir => {
vmDir = resolve(vmDir)
// TODO: implement this in `xo-server`, not easy because not compatible with
// `@xen-orchestra/fs`.
const release = await lockfile.lock(vmDir)
try {
await handleVm(vmDir)
await adapter.cleanVm(vmDir, { fixMetadata: fix, remove, merge, onLog: (...args) => console.warn(...args) })
} catch (error) {
console.error('handleVm', vmDir, error)
} finally {
await release()
console.error('adapter.cleanVm', vmDir, error)
}
})
}

View File

@@ -1,8 +1,8 @@
const filenamify = require('filenamify')
const get = require('lodash/get')
const { asyncMap } = require('@xen-orchestra/async-map')
const { dirname, join, relative } = require('path')
const asyncMap = require('../_asyncMap')
const { mktree, readdir2, readFile, symlink2 } = require('../_fs')
module.exports = async function createSymlinkIndex([backupDir, fieldPath]) {

View File

@@ -1,8 +1,8 @@
const groupBy = require('lodash/groupBy')
const { asyncMap } = require('@xen-orchestra/async-map')
const { createHash } = require('crypto')
const { dirname, resolve } = require('path')
const asyncMap = require('../_asyncMap')
const { readdir2, readFile, getSize } = require('../_fs')
const sha512 = str => createHash('sha512').update(str).digest('hex')

View File

@@ -5,7 +5,15 @@ require('./_composeCommands')({
get main() {
return require('./commands/clean-vms')
},
usage: '[--force] [--merge] xo-vm-backups/*',
usage: `[--fix] [--merge] [--remove] xo-vm-backups/*
Detects and repair issues with VM backups.
Options:
-f, --fix Fix metadata issues (like size)
-m, --merge Merge (or continue merging) VHD files that are unused
-r, --remove Remove unused, incomplete, orphan, or corrupted files
`,
},
'create-symlink-index': {
get main() {

View File

@@ -6,23 +6,17 @@
"preferGlobal": true,
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@xen-orchestra/backups": "^0.1.1",
"@xen-orchestra/fs": "^0.12.1",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/backups": "^0.15.1",
"@xen-orchestra/fs": "^0.18.0",
"filenamify": "^4.1.0",
"getopts": "^2.2.5",
"limit-concurrency-decorator": "^0.4.0",
"lodash": "^4.17.15",
"promise-toolbox": "^0.16.0",
"proper-lockfile": "^4.1.1",
"vhd-lib": "^1.0.0"
"promise-toolbox": "^0.20.0"
},
"engines": {
"node": ">=7.10.1"
},
"files": [
"commands",
"*.js"
],
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/backups-cli",
"name": "@xen-orchestra/backups-cli",
"repository": {
@@ -33,7 +27,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "0.3.0",
"version": "0.6.0",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1,263 @@
const { asyncMap, asyncMapSettled } = require('@xen-orchestra/async-map')
const Disposable = require('promise-toolbox/Disposable.js')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const { compileTemplate } = require('@xen-orchestra/template')
const { limitConcurrency } = require('limit-concurrency-decorator')
const { extractIdsFromSimplePattern } = require('./_extractIdsFromSimplePattern.js')
const { PoolMetadataBackup } = require('./_PoolMetadataBackup.js')
const { Task } = require('./Task.js')
const { VmBackup } = require('./_VmBackup.js')
const { XoMetadataBackup } = require('./_XoMetadataBackup.js')
const noop = Function.prototype
const getAdaptersByRemote = adapters => {
const adaptersByRemote = {}
adapters.forEach(({ adapter, remoteId }) => {
adaptersByRemote[remoteId] = adapter
})
return adaptersByRemote
}
const runTask = (...args) => Task.run(...args).catch(noop) // errors are handled by logs
exports.Backup = class Backup {
constructor({ config, getAdapter, getConnectedRecord, job, schedule }) {
this._config = config
this._getRecord = getConnectedRecord
this._job = job
this._schedule = schedule
this._getAdapter = Disposable.factory(function* (remoteId) {
return {
adapter: yield getAdapter(remoteId),
remoteId,
}
})
this._getSnapshotNameLabel = compileTemplate(config.snapshotNameLabelTpl, {
'{job.name}': job.name,
'{vm.name_label}': vm => vm.name_label,
})
}
run() {
const type = this._job.type
if (type === 'backup') {
return this._runVmBackup()
} else if (type === 'metadataBackup') {
return this._runMetadataBackup()
} else {
throw new Error(`No runner for the backup type ${type}`)
}
}
async _runMetadataBackup() {
const schedule = this._schedule
const job = this._job
const remoteIds = extractIdsFromSimplePattern(job.remotes)
if (remoteIds.length === 0) {
throw new Error('metadata backup job cannot run without remotes')
}
const config = this._config
const settings = {
...config.defaultSettings,
...config.metadata.defaultSettings,
...job.settings[''],
...job.settings[schedule.id],
}
const poolIds = extractIdsFromSimplePattern(job.pools)
const isEmptyPools = poolIds.length === 0
const isXoMetadata = job.xoMetadata !== undefined
if (!isXoMetadata && isEmptyPools) {
throw new Error('no metadata mode found')
}
const { retentionPoolMetadata, retentionXoMetadata } = settings
if (
(retentionPoolMetadata === 0 && retentionXoMetadata === 0) ||
(!isXoMetadata && retentionPoolMetadata === 0) ||
(isEmptyPools && retentionXoMetadata === 0)
) {
throw new Error('no retentions corresponding to the metadata modes found')
}
await Disposable.use(
Disposable.all(
poolIds.map(id =>
this._getRecord('pool', id).catch(error => {
// See https://github.com/vatesfr/xen-orchestra/commit/6aa6cfba8ec939c0288f0fa740f6dfad98c43cbb
runTask(
{
name: 'get pool record',
data: { type: 'pool', id },
},
() => Promise.reject(error)
)
})
)
),
Disposable.all(
remoteIds.map(id =>
this._getAdapter(id).catch(error => {
// See https://github.com/vatesfr/xen-orchestra/commit/6aa6cfba8ec939c0288f0fa740f6dfad98c43cbb
runTask(
{
name: 'get remote adapter',
data: { type: 'remote', id },
},
() => Promise.reject(error)
)
})
)
),
async (pools, remoteAdapters) => {
// remove adapters that failed (already handled)
remoteAdapters = remoteAdapters.filter(_ => _ !== undefined)
if (remoteAdapters.length === 0) {
return
}
remoteAdapters = getAdaptersByRemote(remoteAdapters)
// remove pools that failed (already handled)
pools = pools.filter(_ => _ !== undefined)
const promises = []
if (pools.length !== 0 && settings.retentionPoolMetadata !== 0) {
promises.push(
asyncMap(pools, async pool =>
runTask(
{
name: `Starting metadata backup for the pool (${pool.$id}). (${job.id})`,
data: {
id: pool.$id,
pool,
poolMaster: await ignoreErrors.call(pool.$xapi.getRecord('host', pool.master)),
type: 'pool',
},
},
() =>
new PoolMetadataBackup({
config,
job,
pool,
remoteAdapters,
schedule,
settings,
}).run()
)
)
)
}
if (job.xoMetadata !== undefined && settings.retentionXoMetadata !== 0) {
promises.push(
runTask(
{
name: `Starting XO metadata backup. (${job.id})`,
data: {
type: 'xo',
},
},
() =>
new XoMetadataBackup({
config,
job,
remoteAdapters,
schedule,
settings,
}).run()
)
)
}
await Promise.all(promises)
}
)
}
async _runVmBackup() {
const job = this._job
// FIXME: proper SimpleIdPattern handling
const getSnapshotNameLabel = this._getSnapshotNameLabel
const schedule = this._schedule
const config = this._config
const { settings } = job
const scheduleSettings = {
...config.defaultSettings,
...config.vm.defaultSettings,
...settings[''],
...settings[schedule.id],
}
await Disposable.use(
Disposable.all(
extractIdsFromSimplePattern(job.srs).map(id =>
this._getRecord('SR', id).catch(error => {
runTask(
{
name: 'get SR record',
data: { type: 'SR', id },
},
() => Promise.reject(error)
)
})
)
),
Disposable.all(
extractIdsFromSimplePattern(job.remotes).map(id =>
this._getAdapter(id).catch(error => {
runTask(
{
name: 'get remote adapter',
data: { type: 'remote', id },
},
() => Promise.reject(error)
)
})
)
),
async (srs, remoteAdapters) => {
// remove adapters that failed (already handled)
remoteAdapters = remoteAdapters.filter(_ => _ !== undefined)
// remove srs that failed (already handled)
srs = srs.filter(_ => _ !== undefined)
if (remoteAdapters.length === 0 && srs.length === 0 && scheduleSettings.snapshotRetention === 0) {
return
}
const vmIds = extractIdsFromSimplePattern(job.vms)
Task.info('vms', { vms: vmIds })
remoteAdapters = getAdaptersByRemote(remoteAdapters)
const handleVm = vmUuid =>
runTask({ name: 'backup VM', data: { type: 'VM', id: vmUuid } }, () =>
Disposable.use(this._getRecord('VM', vmUuid), vm =>
new VmBackup({
config,
getSnapshotNameLabel,
job,
// remotes,
remoteAdapters,
schedule,
settings: { ...scheduleSettings, ...settings[vmUuid] },
srs,
vm,
}).run()
)
)
const { concurrency } = scheduleSettings
await asyncMapSettled(vmIds, concurrency === 0 ? handleVm : limitConcurrency(concurrency)(handleVm))
}
)
}
}

View File

@@ -0,0 +1,40 @@
const { asyncMap } = require('@xen-orchestra/async-map')
exports.DurablePartition = class DurablePartition {
// private resource API is used exceptionally to be able to separate resource creation and release
#partitionDisposers = {}
flushAll() {
const partitionDisposers = this.#partitionDisposers
return asyncMap(Object.keys(partitionDisposers), path => {
const disposers = partitionDisposers[path]
delete partitionDisposers[path]
return asyncMap(disposers, d => d(path).catch(noop => {}))
})
}
async mount(adapter, diskId, partitionId) {
const { value: path, dispose } = await adapter.getPartition(diskId, partitionId)
const partitionDisposers = this.#partitionDisposers
if (partitionDisposers[path] === undefined) {
partitionDisposers[path] = []
}
partitionDisposers[path].push(dispose)
return path
}
async unmount(path) {
const partitionDisposers = this.#partitionDisposers
const disposers = partitionDisposers[path]
if (disposers === undefined) {
throw new Error(`No partition corresponding to the path ${path} found`)
}
await disposers.pop()()
if (disposers.length === 0) {
delete partitionDisposers[path]
}
}
}

View File

@@ -0,0 +1,66 @@
const assert = require('assert')
const { formatFilenameDate } = require('./_filenameDate.js')
const { importDeltaVm } = require('./_deltaVm.js')
const { Task } = require('./Task.js')
const { watchStreamSize } = require('./_watchStreamSize.js')
exports.ImportVmBackup = class ImportVmBackup {
constructor({ adapter, metadata, srUuid, xapi, settings: { newMacAddresses } = {} }) {
this._adapter = adapter
this._importDeltaVmSettings = { newMacAddresses }
this._metadata = metadata
this._srUuid = srUuid
this._xapi = xapi
}
async run() {
const adapter = this._adapter
const metadata = this._metadata
const isFull = metadata.mode === 'full'
const sizeContainer = { size: 0 }
let backup
if (isFull) {
backup = await adapter.readFullVmBackup(metadata)
watchStreamSize(backup, sizeContainer)
} else {
assert.strictEqual(metadata.mode, 'delta')
backup = await adapter.readDeltaVmBackup(metadata)
Object.values(backup.streams).forEach(stream => watchStreamSize(stream, sizeContainer))
}
return Task.run(
{
name: 'transfer',
},
async () => {
const xapi = this._xapi
const srRef = await xapi.call('SR.get_by_uuid', this._srUuid)
const vmRef = isFull
? await xapi.VM_import(backup, srRef)
: await importDeltaVm(backup, await xapi.getRecord('SR', srRef), {
...this._importDeltaVmSettings,
detectBase: false,
})
await Promise.all([
xapi.call('VM.add_tags', vmRef, 'restored from backup'),
xapi.call(
'VM.set_name_label',
vmRef,
`${metadata.vm.name_label} (${formatFilenameDate(metadata.timestamp)})`
),
])
return {
size: sizeContainer.size,
id: await xapi.getField('VM', vmRef, 'uuid'),
}
}
)
}
}

View File

@@ -0,0 +1,552 @@
const { asyncMap, asyncMapSettled } = require('@xen-orchestra/async-map')
const Disposable = require('promise-toolbox/Disposable.js')
const fromCallback = require('promise-toolbox/fromCallback.js')
const fromEvent = require('promise-toolbox/fromEvent.js')
const pDefer = require('promise-toolbox/defer.js')
const pump = require('pump')
const { basename, dirname, join, normalize, resolve } = require('path')
const { createLogger } = require('@xen-orchestra/log')
const { createSyntheticStream, mergeVhd, VhdFile } = require('vhd-lib')
const { deduped } = require('@vates/disposable/deduped.js')
const { execFile } = require('child_process')
const { readdir, stat } = require('fs-extra')
const { ZipFile } = require('yazl')
const { BACKUP_DIR } = require('./_getVmBackupDir.js')
const { cleanVm } = require('./_cleanVm.js')
const { getTmpDir } = require('./_getTmpDir.js')
const { isMetadataFile, isVhdFile } = require('./_backupType.js')
const { isValidXva } = require('./_isValidXva.js')
const { listPartitions, LVM_PARTITION_TYPE } = require('./_listPartitions.js')
const { lvs, pvs } = require('./_lvm.js')
const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
exports.DIR_XO_CONFIG_BACKUPS = DIR_XO_CONFIG_BACKUPS
const DIR_XO_POOL_METADATA_BACKUPS = 'xo-pool-metadata-backups'
exports.DIR_XO_POOL_METADATA_BACKUPS = DIR_XO_POOL_METADATA_BACKUPS
const { warn } = createLogger('xo:backups:RemoteAdapter')
const compareTimestamp = (a, b) => a.timestamp - b.timestamp
const noop = Function.prototype
const resolveRelativeFromFile = (file, path) => resolve('/', dirname(file), path).slice(1)
const resolveSubpath = (root, path) => resolve(root, `.${resolve('/', path)}`)
const RE_VHDI = /^vhdi(\d+)$/
async function addDirectory(files, realPath, metadataPath) {
try {
const subFiles = await readdir(realPath)
await asyncMap(subFiles, file => addDirectory(files, realPath + '/' + file, metadataPath + '/' + file))
} catch (error) {
if (error == null || error.code !== 'ENOTDIR') {
throw error
}
files.push({
realPath,
metadataPath,
})
}
}
const createSafeReaddir = (handler, methodName) => (path, options) =>
handler.list(path, options).catch(error => {
if (error?.code !== 'ENOENT') {
warn(`${methodName} ${path}`, { error })
}
return []
})
const debounceResourceFactory = factory =>
function () {
return this._debounceResource(factory.apply(this, arguments))
}
class RemoteAdapter {
constructor(handler, { debounceResource = res => res, dirMode } = {}) {
this._debounceResource = debounceResource
this._dirMode = dirMode
this._handler = handler
}
get handler() {
return this._handler
}
async _deleteVhd(path) {
const handler = this._handler
const vhds = await asyncMapSettled(
await handler.list(dirname(path), {
filter: isVhdFile,
prependDir: true,
}),
async path => {
try {
const vhd = new VhdFile(handler, path)
await vhd.readHeaderAndFooter()
return {
footer: vhd.footer,
header: vhd.header,
path,
}
} catch (error) {
// Do not fail on corrupted VHDs (usually uncleaned temporary files),
// they are probably inconsequent to the backup process and should not
// fail it.
warn(`BackupNg#_deleteVhd ${path}`, { error })
}
}
)
const base = basename(path)
const child = vhds.find(_ => _ !== undefined && _.header.parentUnicodeName === base)
if (child === undefined) {
await handler.unlink(path)
return 0
}
try {
const childPath = child.path
const mergedDataSize = await mergeVhd(handler, path, handler, childPath)
await handler.rename(path, childPath)
return mergedDataSize
} catch (error) {
handler.unlink(path).catch(warn)
throw error
}
}
async _findPartition(devicePath, partitionId) {
const partitions = await listPartitions(devicePath)
const partition = partitions.find(_ => _.id === partitionId)
if (partition === undefined) {
throw new Error(`partition ${partitionId} not found`)
}
return partition
}
_getLvmLogicalVolumes = Disposable.factory(this._getLvmLogicalVolumes)
_getLvmLogicalVolumes = deduped(this._getLvmLogicalVolumes, (devicePath, pvId, vgName) => [devicePath, pvId, vgName])
_getLvmLogicalVolumes = debounceResourceFactory(this._getLvmLogicalVolumes)
async *_getLvmLogicalVolumes(devicePath, pvId, vgName) {
yield this._getLvmPhysicalVolume(devicePath, pvId && (await this._findPartition(devicePath, pvId)))
await fromCallback(execFile, 'vgchange', ['-ay', vgName])
try {
yield lvs(['lv_name', 'lv_path'], vgName)
} finally {
await fromCallback(execFile, 'vgchange', ['-an', vgName])
}
}
_getLvmPhysicalVolume = Disposable.factory(this._getLvmPhysicalVolume)
_getLvmPhysicalVolume = deduped(this._getLvmPhysicalVolume, (devicePath, partition) => [devicePath, partition?.id])
_getLvmPhysicalVolume = debounceResourceFactory(this._getLvmPhysicalVolume)
async *_getLvmPhysicalVolume(devicePath, partition) {
const args = []
if (partition !== undefined) {
args.push('-o', partition.start * 512, '--sizelimit', partition.size)
}
args.push('--show', '-f', devicePath)
const path = (await fromCallback(execFile, 'losetup', args)).trim()
try {
await fromCallback(execFile, 'pvscan', ['--cache', path])
yield path
} finally {
try {
const vgNames = await pvs('vg_name', path)
await fromCallback(execFile, 'vgchange', ['-an', ...vgNames])
} finally {
await fromCallback(execFile, 'losetup', ['-d', path])
}
}
}
_getPartition = Disposable.factory(this._getPartition)
_getPartition = deduped(this._getPartition, (devicePath, partition) => [devicePath, partition?.id])
_getPartition = debounceResourceFactory(this._getPartition)
async *_getPartition(devicePath, partition) {
const options = ['loop', 'ro']
if (partition !== undefined) {
const { size, start } = partition
options.push(`sizelimit=${size}`)
if (start !== undefined) {
options.push(`offset=${start * 512}`)
}
}
const path = yield getTmpDir()
const mount = options => {
return fromCallback(execFile, 'mount', [
`--options=${options.join(',')}`,
`--source=${devicePath}`,
`--target=${path}`,
])
}
// `norecovery` option is used for ext3/ext4/xfs, if it fails it might be
// another fs, try without
try {
await mount([...options, 'norecovery'])
} catch (error) {
await mount(options)
}
try {
yield path
} finally {
await fromCallback(execFile, 'umount', ['--lazy', path])
}
}
_listLvmLogicalVolumes(devicePath, partition, results = []) {
return Disposable.use(this._getLvmPhysicalVolume(devicePath, partition), async path => {
const lvs = await pvs(['lv_name', 'lv_path', 'lv_size', 'vg_name'], path)
const partitionId = partition !== undefined ? partition.id : ''
lvs.forEach((lv, i) => {
const name = lv.lv_name
if (name !== '') {
results.push({
id: `${partitionId}/${lv.vg_name}/${name}`,
name,
size: lv.lv_size,
})
}
})
return results
})
}
_usePartitionFiles = Disposable.factory(this._usePartitionFiles)
async *_usePartitionFiles(diskId, partitionId, paths) {
const path = yield this.getPartition(diskId, partitionId)
const files = []
await asyncMap(paths, file =>
addDirectory(files, resolveSubpath(path, file), normalize('./' + file).replace(/\/+$/, ''))
)
return files
}
fetchPartitionFiles(diskId, partitionId, paths) {
const { promise, reject, resolve } = pDefer()
Disposable.use(
async function* () {
const files = yield this._usePartitionFiles(diskId, partitionId, paths)
const zip = new ZipFile()
files.forEach(({ realPath, metadataPath }) => zip.addFile(realPath, metadataPath))
zip.end()
const { outputStream } = zip
resolve(outputStream)
await fromEvent(outputStream, 'end')
}.bind(this)
).catch(error => {
warn(error)
reject(error)
})
return promise
}
async deleteDeltaVmBackups(backups) {
const handler = this._handler
// unused VHDs will be detected by `cleanVm`
await asyncMapSettled(backups, ({ _filename }) => handler.unlink(_filename))
}
async deleteMetadataBackup(backupId) {
const uuidReg = '\\w{8}(-\\w{4}){3}-\\w{12}'
const metadataDirReg = 'xo-(config|pool-metadata)-backups'
const timestampReg = '\\d{8}T\\d{6}Z'
const regexp = new RegExp(`^${metadataDirReg}/${uuidReg}(/${uuidReg})?/${timestampReg}`)
if (!regexp.test(backupId)) {
throw new Error(`The id (${backupId}) not correspond to a metadata folder`)
}
await this._handler.rmtree(backupId)
}
async deleteOldMetadataBackups(dir, retention) {
const handler = this.handler
let list = await handler.list(dir)
list.sort()
list = list.filter(timestamp => /^\d{8}T\d{6}Z$/.test(timestamp)).slice(0, -retention)
await asyncMapSettled(list, timestamp => handler.rmtree(`${dir}/${timestamp}`))
}
async deleteFullVmBackups(backups) {
const handler = this._handler
await asyncMapSettled(backups, ({ _filename, xva }) =>
Promise.all([handler.unlink(_filename), handler.unlink(resolveRelativeFromFile(_filename, xva))])
)
}
async deleteVmBackup(filename) {
const metadata = JSON.parse(String(await this._handler.readFile(filename)))
metadata._filename = filename
if (metadata.mode === 'delta') {
await this.deleteDeltaVmBackups([metadata])
} else if (metadata.mode === 'full') {
await this.deleteFullVmBackups([metadata])
} else {
throw new Error(`no deleter for backup mode ${metadata.mode}`)
}
}
getDisk = Disposable.factory(this.getDisk)
getDisk = deduped(this.getDisk, diskId => [diskId])
getDisk = debounceResourceFactory(this.getDisk)
async *getDisk(diskId) {
const handler = this._handler
const diskPath = handler._getFilePath('/' + diskId)
const mountDir = yield getTmpDir()
await fromCallback(execFile, 'vhdimount', [diskPath, mountDir])
try {
let max = 0
let maxEntry
const entries = await readdir(mountDir)
entries.forEach(entry => {
const matches = RE_VHDI.exec(entry)
if (matches !== null) {
const value = +matches[1]
if (value > max) {
max = value
maxEntry = entry
}
}
})
if (max === 0) {
throw new Error('no disks found')
}
yield `${mountDir}/${maxEntry}`
} finally {
await fromCallback(execFile, 'fusermount', ['-uz', mountDir])
}
}
// partitionId values:
//
// - undefined: raw disk
// - `<partitionId>`: partitioned disk
// - `<pvId>/<vgName>/<lvName>`: LVM on a partitioned disk
// - `/<vgName>/lvName>`: LVM on a raw disk
getPartition = Disposable.factory(this.getPartition)
async *getPartition(diskId, partitionId) {
const devicePath = yield this.getDisk(diskId)
if (partitionId === undefined) {
return yield this._getPartition(devicePath)
}
const isLvmPartition = partitionId.includes('/')
if (isLvmPartition) {
const [pvId, vgName, lvName] = partitionId.split('/')
const lvs = yield this._getLvmLogicalVolumes(devicePath, pvId !== '' ? pvId : undefined, vgName)
return yield this._getPartition(lvs.find(_ => _.lv_name === lvName).lv_path)
}
return yield this._getPartition(devicePath, await this._findPartition(devicePath, partitionId))
}
async listAllVmBackups() {
const handler = this._handler
const backups = { __proto__: null }
await asyncMap(await handler.list(BACKUP_DIR), async vmUuid => {
const vmBackups = await this.listVmBackups(vmUuid)
backups[vmUuid] = vmBackups
})
return backups
}
listPartitionFiles(diskId, partitionId, path) {
return Disposable.use(this.getPartition(diskId, partitionId), async rootPath => {
path = resolveSubpath(rootPath, path)
const entriesMap = {}
await asyncMap(await readdir(path), async name => {
try {
const stats = await stat(`${path}/${name}`)
entriesMap[stats.isDirectory() ? `${name}/` : name] = {}
} catch (error) {
if (error == null || error.code !== 'ENOENT') {
throw error
}
}
})
return entriesMap
})
}
listPartitions(diskId) {
return Disposable.use(this.getDisk(diskId), async devicePath => {
const partitions = await listPartitions(devicePath)
if (partitions.length === 0) {
try {
// handle potential raw LVM physical volume
return await this._listLvmLogicalVolumes(devicePath, undefined, partitions)
} catch (error) {
return []
}
}
const results = []
await asyncMapSettled(partitions, partition =>
partition.type === LVM_PARTITION_TYPE
? this._listLvmLogicalVolumes(devicePath, partition, results)
: results.push(partition)
)
return results
})
}
async listPoolMetadataBackups() {
const handler = this._handler
const safeReaddir = createSafeReaddir(handler, 'listPoolMetadataBackups')
const backupsByPool = {}
await asyncMap(await safeReaddir(DIR_XO_POOL_METADATA_BACKUPS, { prependDir: true }), async scheduleDir =>
asyncMap(await safeReaddir(scheduleDir), async poolId => {
const backups = backupsByPool[poolId] ?? (backupsByPool[poolId] = [])
return asyncMap(await safeReaddir(`${scheduleDir}/${poolId}`, { prependDir: true }), async backupDir => {
try {
backups.push({
id: backupDir,
...JSON.parse(String(await handler.readFile(`${backupDir}/metadata.json`))),
})
} catch (error) {
warn(`listPoolMetadataBackups ${backupDir}`, {
error,
})
}
})
})
)
// delete empty entries and sort backups
Object.keys(backupsByPool).forEach(poolId => {
const backups = backupsByPool[poolId]
if (backups.length === 0) {
delete backupsByPool[poolId]
} else {
backups.sort(compareTimestamp)
}
})
return backupsByPool
}
async listVmBackups(vmUuid, predicate) {
const handler = this._handler
const backups = []
try {
const files = await handler.list(`${BACKUP_DIR}/${vmUuid}`, {
filter: isMetadataFile,
prependDir: true,
})
await asyncMap(files, async file => {
try {
const metadata = await this.readVmBackupMetadata(file)
if (predicate === undefined || predicate(metadata)) {
// inject an id usable by importVmBackupNg()
metadata.id = metadata._filename
backups.push(metadata)
}
} catch (error) {
warn(`listVmBackups ${file}`, { error })
}
})
} catch (error) {
let code
if (error == null || ((code = error.code) !== 'ENOENT' && code !== 'ENOTDIR')) {
throw error
}
}
return backups.sort(compareTimestamp)
}
async listXoMetadataBackups() {
const handler = this._handler
const safeReaddir = createSafeReaddir(handler, 'listXoMetadataBackups')
const backups = []
await asyncMap(await safeReaddir(DIR_XO_CONFIG_BACKUPS, { prependDir: true }), async scheduleDir =>
asyncMap(await safeReaddir(scheduleDir, { prependDir: true }), async backupDir => {
try {
backups.push({
id: backupDir,
...JSON.parse(String(await handler.readFile(`${backupDir}/metadata.json`))),
})
} catch (error) {
warn(`listXoMetadataBackups ${backupDir}`, { error })
}
})
)
return backups.sort(compareTimestamp)
}
async outputStream(path, input, { checksum = true, validator = noop } = {}) {
await this._handler.outputStream(path, input, {
checksum,
dirMode: this._dirMode,
async validator() {
await input.task
return validator.apply(this, arguments)
},
})
}
async readDeltaVmBackup(metadata) {
const handler = this._handler
const { vbds, vdis, vhds, vifs, vm } = metadata
const dir = dirname(metadata._filename)
const streams = {}
await asyncMapSettled(Object.keys(vdis), async id => {
streams[`${id}.vhd`] = await createSyntheticStream(handler, join(dir, vhds[id]))
})
return {
streams,
vbds,
vdis,
version: '1.0.0',
vifs,
vm,
}
}
readFullVmBackup(metadata) {
return this._handler.createReadStream(resolve('/', dirname(metadata._filename), metadata.xva))
}
async readVmBackupMetadata(path) {
return Object.defineProperty(JSON.parse(await this._handler.readFile(path)), '_filename', { value: path })
}
}
Object.assign(RemoteAdapter.prototype, {
cleanVm(vmDir, { lock = true } = {}) {
if (lock) {
return Disposable.use(this._handler.lock(vmDir), () => cleanVm.apply(this, arguments))
} else {
return cleanVm.apply(this, arguments)
}
},
isValidXva,
})
exports.RemoteAdapter = RemoteAdapter

View File

@@ -0,0 +1,24 @@
const { DIR_XO_POOL_METADATA_BACKUPS } = require('./RemoteAdapter.js')
const { PATH_DB_DUMP } = require('./_PoolMetadataBackup.js')
exports.RestoreMetadataBackup = class RestoreMetadataBackup {
constructor({ backupId, handler, xapi }) {
this._backupId = backupId
this._handler = handler
this._xapi = xapi
}
async run() {
const backupId = this._backupId
const handler = this._handler
const xapi = this._xapi
if (backupId.split('/')[0] === DIR_XO_POOL_METADATA_BACKUPS) {
return xapi.putResource(await handler.createReadStream(`${backupId}/data`), PATH_DB_DUMP, {
task: xapi.task_create('Import pool metadata'),
})
} else {
return String(await handler.readFile(`${backupId}/data.json`))
}
}
}

View File

@@ -0,0 +1,151 @@
const CancelToken = require('promise-toolbox/CancelToken.js')
const Zone = require('node-zone')
const logAfterEnd = () => {
throw new Error('task has already ended')
}
const noop = Function.prototype
// Create a serializable object from an error.
//
// Otherwise some fields might be non-enumerable and missing from logs.
const serializeError = error =>
error instanceof Error
? {
...error, // Copy enumerable properties.
code: error.code,
message: error.message,
name: error.name,
stack: error.stack,
}
: error
const $$task = Symbol('@xen-orchestra/backups/Task')
class Task {
static get cancelToken() {
const task = Zone.current.data[$$task]
return task !== undefined ? task.#cancelToken : CancelToken.none
}
static run(opts, fn) {
return new this(opts).run(fn, true)
}
static wrapFn(opts, fn) {
// compatibility with @decorateWith
if (typeof fn !== 'function') {
;[fn, opts] = [opts, fn]
}
return function () {
return Task.run(typeof opts === 'function' ? opts.apply(this, arguments) : opts, () => fn.apply(this, arguments))
}
}
#cancelToken
#id = Math.random().toString(36).slice(2)
#onLog
#zone
constructor({ name, data, onLog }) {
let parentCancelToken, parentId
if (onLog === undefined) {
const parent = Zone.current.data[$$task]
if (parent === undefined) {
onLog = noop
} else {
onLog = log => parent.#onLog(log)
parentCancelToken = parent.#cancelToken
parentId = parent.#id
}
}
const zone = Zone.current.fork('@xen-orchestra/backups/Task')
zone.data[$$task] = this
this.#zone = zone
const { cancel, token } = CancelToken.source(parentCancelToken && [parentCancelToken])
this.#cancelToken = token
this.cancel = cancel
this.#onLog = onLog
this.#log('start', {
data,
message: name,
parentId,
})
}
failure(error) {
this.#end('failure', serializeError(error))
}
info(message, data) {
this.#log('info', { data, message })
}
/**
* Run a function in the context of this task
*
* In case of error, the task will be failed.
*
* @typedef Result
* @param {() => Result)} fn
* @param {boolean} last - Whether the task should succeed if there is no error
* @returns Result
*/
run(fn, last = false) {
return this.#zone.run(() => {
try {
const result = fn()
let then
if (result != null && typeof (then = result.then) === 'function') {
then.call(result, last && (value => this.success(value)), error => this.failure(error))
} else if (last) {
this.success(result)
}
return result
} catch (error) {
this.failure(error)
throw error
}
})
}
success(value) {
this.#end('success', value)
}
warning(message, data) {
this.#log('warning', { data, message })
}
wrapFn(fn, last) {
const task = this
return function () {
return task.run(() => fn.apply(this, arguments), last)
}
}
#end(status, result) {
this.#log('end', { result, status })
this.#onLog = logAfterEnd
}
#log(event, props) {
this.#onLog({
...props,
event,
taskId: this.#id,
timestamp: Date.now(),
})
}
}
exports.Task = Task
for (const method of ['info', 'warning']) {
Task[method] = (...args) => Zone.current.data[$$task]?.[method](...args)
}

View File

@@ -0,0 +1,75 @@
const { asyncMap } = require('@xen-orchestra/async-map')
const { DIR_XO_POOL_METADATA_BACKUPS } = require('./RemoteAdapter.js')
const { forkStreamUnpipe } = require('./_forkStreamUnpipe.js')
const { formatFilenameDate } = require('./_filenameDate.js')
const { Task } = require('./Task.js')
const PATH_DB_DUMP = '/pool/xmldbdump'
exports.PATH_DB_DUMP = PATH_DB_DUMP
exports.PoolMetadataBackup = class PoolMetadataBackup {
constructor({ config, job, pool, remoteAdapters, schedule, settings }) {
this._config = config
this._job = job
this._pool = pool
this._remoteAdapters = remoteAdapters
this._schedule = schedule
this._settings = settings
}
_exportPoolMetadata() {
const xapi = this._pool.$xapi
return xapi.getResource(PATH_DB_DUMP, {
task: xapi.task_create('Export pool metadata'),
})
}
async run() {
const timestamp = Date.now()
const { _job: job, _schedule: schedule, _pool: pool } = this
const poolDir = `${DIR_XO_POOL_METADATA_BACKUPS}/${schedule.id}/${pool.$id}`
const dir = `${poolDir}/${formatFilenameDate(timestamp)}`
const stream = await this._exportPoolMetadata()
const fileName = `${dir}/data`
const metadata = JSON.stringify(
{
jobId: job.id,
jobName: job.name,
pool,
poolMaster: pool.$master,
scheduleId: schedule.id,
scheduleName: schedule.name,
timestamp,
},
null,
2
)
const metaDataFileName = `${dir}/metadata.json`
await asyncMap(
Object.entries(this._remoteAdapters),
([remoteId, adapter]) =>
Task.run(
{
name: `Starting metadata backup for the pool (${pool.$id}) for the remote (${remoteId}). (${job.id})`,
data: {
id: remoteId,
type: 'remote',
},
},
async () => {
// forkStreamUnpipe should be used in a sync way, do not wait for a promise before using it
await adapter.outputStream(fileName, forkStreamUnpipe(stream), { checksum: false })
await adapter.handler.outputFile(metaDataFileName, metadata, {
dirMode: this._config.dirMode,
})
await adapter.deleteOldMetadataBackups(poolDir, this._settings.retentionPoolMetadata)
}
).catch(() => {}) // errors are handled by logs
)
}
}

View File

@@ -0,0 +1,421 @@
const assert = require('assert')
const findLast = require('lodash/findLast.js')
const groupBy = require('lodash/groupBy.js')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const keyBy = require('lodash/keyBy.js')
const mapValues = require('lodash/mapValues.js')
const { asyncMap } = require('@xen-orchestra/async-map')
const { createLogger } = require('@xen-orchestra/log')
const { defer } = require('golike-defer')
const { formatDateTime } = require('@xen-orchestra/xapi')
const { DeltaBackupWriter } = require('./writers/DeltaBackupWriter.js')
const { DeltaReplicationWriter } = require('./writers/DeltaReplicationWriter.js')
const { exportDeltaVm } = require('./_deltaVm.js')
const { forkStreamUnpipe } = require('./_forkStreamUnpipe.js')
const { FullBackupWriter } = require('./writers/FullBackupWriter.js')
const { FullReplicationWriter } = require('./writers/FullReplicationWriter.js')
const { getOldEntries } = require('./_getOldEntries.js')
const { Task } = require('./Task.js')
const { watchStreamSize } = require('./_watchStreamSize.js')
const { debug, warn } = createLogger('xo:backups:VmBackup')
const asyncEach = async (iterable, fn, thisArg = iterable) => {
for (const item of iterable) {
await fn.call(thisArg, item)
}
}
const forkDeltaExport = deltaExport =>
Object.create(deltaExport, {
streams: {
value: mapValues(deltaExport.streams, forkStreamUnpipe),
},
})
exports.VmBackup = class VmBackup {
constructor({ config, getSnapshotNameLabel, job, remoteAdapters, remotes, schedule, settings, srs, vm }) {
this.config = config
this.job = job
this.remoteAdapters = remoteAdapters
this.remotes = remotes
this.scheduleId = schedule.id
this.timestamp = undefined
// VM currently backed up
this.vm = vm
const { tags } = this.vm
// VM (snapshot) that is really exported
this.exportedVm = undefined
this._fullVdisRequired = undefined
this._getSnapshotNameLabel = getSnapshotNameLabel
this._isDelta = job.mode === 'delta'
this._jobId = job.id
this._jobSnapshots = undefined
this._xapi = vm.$xapi
// Base VM for the export
this._baseVm = undefined
// Settings for this specific run (job, schedule, VM)
if (tags.includes('xo-memory-backup')) {
settings.checkpointSnapshot = true
}
if (tags.includes('xo-offline-backup')) {
settings.offlineSnapshot = true
}
this._settings = settings
// Create writers
{
const writers = new Set()
this._writers = writers
const [BackupWriter, ReplicationWriter] = this._isDelta
? [DeltaBackupWriter, DeltaReplicationWriter]
: [FullBackupWriter, FullReplicationWriter]
const allSettings = job.settings
Object.keys(remoteAdapters).forEach(remoteId => {
const targetSettings = {
...settings,
...allSettings[remoteId],
}
if (targetSettings.exportRetention !== 0) {
writers.add(new BackupWriter({ backup: this, remoteId, settings: targetSettings }))
}
})
srs.forEach(sr => {
const targetSettings = {
...settings,
...allSettings[sr.uuid],
}
if (targetSettings.copyRetention !== 0) {
writers.add(new ReplicationWriter({ backup: this, sr, settings: targetSettings }))
}
})
}
}
// calls fn for each function, warns of any errors, and throws only if there are no writers left
async _callWriters(fn, warnMessage, parallel = true) {
const writers = this._writers
const n = writers.size
if (n === 0) {
return
}
if (n === 1) {
const [writer] = writers
try {
await fn(writer)
} catch (error) {
writers.delete(writer)
throw error
}
return
}
await (parallel ? asyncMap : asyncEach)(writers, async function (writer) {
try {
await fn(writer)
} catch (error) {
this.delete(writer)
warn(warnMessage, { error, writer: writer.constructor.name })
}
})
if (writers.size === 0) {
throw new Error('all targets have failed, step: ' + warnMessage)
}
}
// ensure the VM itself does not have any backup metadata which would be
// copied on manual snapshots and interfere with the backup jobs
async _cleanMetadata() {
const { vm } = this
if ('xo:backup:job' in vm.other_config) {
await vm.update_other_config({
'xo:backup:datetime': null,
'xo:backup:deltaChainLength': null,
'xo:backup:exported': null,
'xo:backup:job': null,
'xo:backup:schedule': null,
'xo:backup:vm': null,
})
}
}
async _snapshot() {
const { vm } = this
const xapi = this._xapi
const settings = this._settings
const doSnapshot =
this._isDelta || (!settings.offlineBackup && vm.power_state === 'Running') || settings.snapshotRetention !== 0
if (doSnapshot) {
await Task.run({ name: 'snapshot' }, async () => {
if (!settings.bypassVdiChainsCheck) {
await vm.$assertHealthyVdiChains()
}
const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
name_label: this._getSnapshotNameLabel(vm),
})
this.timestamp = Date.now()
await xapi.setFieldEntries('VM', snapshotRef, 'other_config', {
'xo:backup:datetime': formatDateTime(this.timestamp),
'xo:backup:job': this._jobId,
'xo:backup:schedule': this.scheduleId,
'xo:backup:vm': vm.uuid,
})
this.exportedVm = await xapi.getRecord('VM', snapshotRef)
return this.exportedVm.uuid
})
} else {
this.exportedVm = vm
this.timestamp = Date.now()
}
}
async _copyDelta() {
const { exportedVm } = this
const baseVm = this._baseVm
const fullVdisRequired = this._fullVdisRequired
const isFull = fullVdisRequired === undefined || fullVdisRequired.size !== 0
await this._callWriters(writer => writer.prepare({ isFull }), 'writer.prepare()')
const deltaExport = await exportDeltaVm(exportedVm, baseVm, {
fullVdisRequired,
})
const sizeContainers = mapValues(deltaExport.streams, stream => watchStreamSize(stream))
const timestamp = Date.now()
await this._callWriters(
writer =>
writer.transfer({
deltaExport: forkDeltaExport(deltaExport),
sizeContainers,
timestamp,
}),
'writer.transfer()'
)
this._baseVm = exportedVm
if (baseVm !== undefined) {
await exportedVm.update_other_config(
'xo:backup:deltaChainLength',
String(+(baseVm.other_config['xo:backup:deltaChainLength'] ?? 0) + 1)
)
}
// not the case if offlineBackup
if (exportedVm.is_a_snapshot) {
await exportedVm.update_other_config('xo:backup:exported', 'true')
}
const size = Object.values(sizeContainers).reduce((sum, { size }) => sum + size, 0)
const end = Date.now()
const duration = end - timestamp
debug('transfer complete', {
duration,
speed: duration !== 0 ? (size * 1e3) / 1024 / 1024 / duration : 0,
size,
})
await this._callWriters(writer => writer.cleanup(), 'writer.cleanup()')
}
async _copyFull() {
const { compression } = this.job
const stream = await this._xapi.VM_export(this.exportedVm.$ref, {
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
useSnapshot: false,
})
const sizeContainer = watchStreamSize(stream)
const timestamp = Date.now()
await this._callWriters(
writer =>
writer.run({
sizeContainer,
stream: forkStreamUnpipe(stream),
timestamp,
}),
'writer.run()'
)
const { size } = sizeContainer
const end = Date.now()
const duration = end - timestamp
debug('transfer complete', {
duration,
speed: duration !== 0 ? (size * 1e3) / 1024 / 1024 / duration : 0,
size,
})
}
async _fetchJobSnapshots() {
const jobId = this._jobId
const vmRef = this.vm.$ref
const xapi = this._xapi
const snapshotsRef = await xapi.getField('VM', vmRef, 'snapshots')
const snapshotsOtherConfig = await asyncMap(snapshotsRef, ref => xapi.getField('VM', ref, 'other_config'))
const snapshots = []
snapshotsOtherConfig.forEach((other_config, i) => {
if (other_config['xo:backup:job'] === jobId) {
snapshots.push({ other_config, $ref: snapshotsRef[i] })
}
})
snapshots.sort((a, b) => (a.other_config['xo:backup:datetime'] < b.other_config['xo:backup:datetime'] ? -1 : 1))
this._jobSnapshots = snapshots
}
async _removeUnusedSnapshots() {
const jobSettings = this.job.settings
const baseVmRef = this._baseVm?.$ref
const { config } = this
const baseSettings = {
...config.defaultSettings,
...config.metadata.defaultSettings,
...jobSettings[''],
}
const snapshotsPerSchedule = groupBy(this._jobSnapshots, _ => _.other_config['xo:backup:schedule'])
const xapi = this._xapi
await asyncMap(Object.entries(snapshotsPerSchedule), ([scheduleId, snapshots]) => {
const settings = {
...baseSettings,
...jobSettings[scheduleId],
...jobSettings[this.vm.uuid],
}
return asyncMap(getOldEntries(settings.snapshotRetention, snapshots), ({ $ref }) => {
if ($ref !== baseVmRef) {
return xapi.VM_destroy($ref)
}
})
})
}
async _selectBaseVm() {
const xapi = this._xapi
let baseVm = findLast(this._jobSnapshots, _ => 'xo:backup:exported' in _.other_config)
if (baseVm === undefined) {
debug('no base VM found')
return
}
const fullInterval = this._settings.fullInterval
const deltaChainLength = +(baseVm.other_config['xo:backup:deltaChainLength'] ?? 0) + 1
if (!(fullInterval === 0 || fullInterval > deltaChainLength)) {
debug('not using base VM becaust fullInterval reached')
return
}
const srcVdis = keyBy(await xapi.getRecords('VDI', await this.vm.$getDisks()), '$ref')
// resolve full record
baseVm = await xapi.getRecord('VM', baseVm.$ref)
const baseUuidToSrcVdi = new Map()
await asyncMap(await baseVm.$getDisks(), async baseRef => {
const snapshotOf = await xapi.getField('VDI', baseRef, 'snapshot_of')
const srcVdi = srcVdis[snapshotOf]
if (srcVdi !== undefined) {
baseUuidToSrcVdi.set(await xapi.getField('VDI', baseRef, 'uuid'), srcVdi)
} else {
debug('no base VDI found', {
vdi: srcVdi.uuid,
})
}
})
const presentBaseVdis = new Map(baseUuidToSrcVdi)
await this._callWriters(
writer => presentBaseVdis.size !== 0 && writer.checkBaseVdis(presentBaseVdis, baseVm),
'writer.checkBaseVdis()',
false
)
const fullVdisRequired = new Set()
baseUuidToSrcVdi.forEach((srcVdi, baseUuid) => {
if (presentBaseVdis.has(baseUuid)) {
debug('found base VDI', {
base: baseUuid,
vdi: srcVdi.uuid,
})
} else {
debug('missing base VDI', {
base: baseUuid,
vdi: srcVdi.uuid,
})
fullVdisRequired.add(srcVdi.uuid)
}
})
this._baseVm = baseVm
this._fullVdisRequired = fullVdisRequired
}
run = defer(this.run)
async run($defer) {
const settings = this._settings
assert(
!settings.offlineBackup || settings.snapshotRetention === 0,
'offlineBackup is not compatible with snapshotRetention'
)
await this._callWriters(async writer => {
await writer.beforeBackup()
$defer(() => writer.afterBackup())
}, 'writer.beforeBackup()')
await this._fetchJobSnapshots()
if (this._isDelta) {
await this._selectBaseVm()
}
await this._cleanMetadata()
await this._removeUnusedSnapshots()
const { vm } = this
const isRunning = vm.power_state === 'Running'
const startAfter = isRunning && (settings.offlineBackup ? 'backup' : settings.offlineSnapshot && 'snapshot')
if (startAfter) {
await vm.$callAsync('clean_shutdown')
}
try {
await this._snapshot()
if (startAfter === 'snapshot') {
ignoreErrors.call(vm.$callAsync('start', false, false))
}
if (this._writers.size !== 0) {
await (this._isDelta ? this._copyDelta() : this._copyFull())
}
} finally {
if (startAfter) {
ignoreErrors.call(vm.$callAsync('start', false, false))
}
await this._fetchJobSnapshots()
await this._removeUnusedSnapshots()
}
}
}

View File

@@ -0,0 +1,62 @@
const { asyncMap } = require('@xen-orchestra/async-map')
const { DIR_XO_CONFIG_BACKUPS } = require('./RemoteAdapter.js')
const { formatFilenameDate } = require('./_filenameDate.js')
const { Task } = require('./Task.js')
exports.XoMetadataBackup = class XoMetadataBackup {
constructor({ config, job, remoteAdapters, schedule, settings }) {
this._config = config
this._job = job
this._remoteAdapters = remoteAdapters
this._schedule = schedule
this._settings = settings
}
async run() {
const timestamp = Date.now()
const { _job: job, _schedule: schedule } = this
const scheduleDir = `${DIR_XO_CONFIG_BACKUPS}/${schedule.id}`
const dir = `${scheduleDir}/${formatFilenameDate(timestamp)}`
const data = job.xoMetadata
const fileName = `${dir}/data.json`
const metadata = JSON.stringify(
{
jobId: job.id,
jobName: job.name,
scheduleId: schedule.id,
scheduleName: schedule.name,
timestamp,
},
null,
2
)
const metaDataFileName = `${dir}/metadata.json`
await asyncMap(
Object.entries(this._remoteAdapters),
([remoteId, adapter]) =>
Task.run(
{
name: `Starting XO metadata backup for the remote (${remoteId}). (${job.id})`,
data: {
id: remoteId,
type: 'remote',
},
},
async () => {
const handler = adapter.handler
const dirMode = this._config.dirMode
await handler.outputFile(fileName, data, { dirMode })
await handler.outputFile(metaDataFileName, metadata, {
dirMode,
})
await adapter.deleteOldMetadataBackups(scheduleDir, this._settings.retentionXoMetadata)
}
).catch(() => {}) // errors are handled by logs
)
}
}

View File

@@ -0,0 +1,4 @@
exports.isMetadataFile = filename => filename.endsWith('.json')
exports.isVhdFile = filename => filename.endsWith('.vhd')
exports.isXvaFile = filename => filename.endsWith('.xva')
exports.isXvaSumFile = filename => filename.endsWith('.xva.cheksum')

View File

@@ -0,0 +1,155 @@
require('@xen-orchestra/log/configure.js').catchGlobalErrors(
require('@xen-orchestra/log').createLogger('xo:backups:worker')
)
const Disposable = require('promise-toolbox/Disposable.js')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const { compose } = require('@vates/compose')
const { createDebounceResource } = require('@vates/disposable/debounceResource.js')
const { deduped } = require('@vates/disposable/deduped.js')
const { getHandler } = require('@xen-orchestra/fs')
const { parseDuration } = require('@vates/parse-duration')
const { Xapi } = require('@xen-orchestra/xapi')
const { Backup } = require('./Backup.js')
const { RemoteAdapter } = require('./RemoteAdapter.js')
const { Task } = require('./Task.js')
class BackupWorker {
#config
#job
#recordToXapi
#remoteOptions
#remotes
#schedule
#xapiOptions
#xapis
constructor({ config, job, recordToXapi, remoteOptions, remotes, resourceCacheDelay, schedule, xapiOptions, xapis }) {
this.#config = config
this.#job = job
this.#recordToXapi = recordToXapi
this.#remoteOptions = remoteOptions
this.#remotes = remotes
this.#schedule = schedule
this.#xapiOptions = xapiOptions
this.#xapis = xapis
const debounceResource = createDebounceResource()
debounceResource.defaultDelay = parseDuration(resourceCacheDelay)
this.debounceResource = debounceResource
}
run() {
return new Backup({
config: this.#config,
getAdapter: remoteId => this.getAdapter(this.#remotes[remoteId]),
getConnectedRecord: Disposable.factory(async function* getConnectedRecord(type, uuid) {
const xapiId = this.#recordToXapi[uuid]
if (xapiId === undefined) {
throw new Error('no XAPI associated to ' + uuid)
}
const xapi = yield this.getXapi(this.#xapis[xapiId])
return xapi.getRecordByUuid(type, uuid)
}).bind(this),
job: this.#job,
schedule: this.#schedule,
}).run()
}
getAdapter = Disposable.factory(this.getAdapter)
getAdapter = deduped(this.getAdapter, remote => [remote.url])
getAdapter = compose(this.getAdapter, function (resource) {
return this.debounceResource(resource)
})
async *getAdapter(remote) {
const handler = getHandler(remote, this.#remoteOptions)
await handler.sync()
try {
yield new RemoteAdapter(handler, {
debounceResource: this.debounceResource,
dirMode: this.#config.dirMode,
})
} finally {
await handler.forget()
}
}
getXapi = Disposable.factory(this.getXapi)
getXapi = deduped(this.getXapi, ({ url }) => [url])
getXapi = compose(this.getXapi, function (resource) {
return this.debounceResource(resource)
})
async *getXapi({ credentials: { username: user, password }, ...opts }) {
const xapi = new Xapi({
...this.#xapiOptions,
...opts,
auth: {
user,
password,
},
})
await xapi.connect()
try {
await xapi.objectsFetched
yield xapi
} finally {
await xapi.disconnect()
}
}
}
// Received message:
//
// Message {
// action: 'run'
// data: object
// runWithLogs: boolean
// }
//
// Sent message:
//
// Message {
// type: 'log' | 'result'
// data?: object
// status?: 'success' | 'failure'
// result?: any
// }
process.on('message', async message => {
if (message.action === 'run') {
const backupWorker = new BackupWorker(message.data)
try {
const result = message.runWithLogs
? await Task.run(
{
name: 'backup run',
onLog: data =>
process.send({
data,
type: 'log',
}),
},
() => backupWorker.run()
)
: await backupWorker.run()
process.send({
type: 'result',
result,
status: 'success',
})
} catch (error) {
process.send({
type: 'result',
result: error,
status: 'failure',
})
} finally {
await ignoreErrors.call(backupWorker.debounceResource.flushAll())
process.disconnect()
}
}
})

View File

@@ -0,0 +1,20 @@
const cancelable = require('promise-toolbox/cancelable.js')
const CancelToken = require('promise-toolbox/CancelToken.js')
// Similar to `Promise.all` + `map` but pass a cancel token to the callback
//
// If any of the executions fails, the cancel token will be triggered and the
// first reason will be rejected.
exports.cancelableMap = cancelable(async function cancelableMap($cancelToken, iterable, callback) {
const { cancel, token } = CancelToken.source([$cancelToken])
try {
return await Promise.all(
Array.from(iterable, function (item) {
return callback.call(this, token, item)
})
)
} catch (error) {
await cancel()
throw error
}
})

View File

@@ -0,0 +1,378 @@
const assert = require('assert')
const sum = require('lodash/sum')
const { asyncMap } = require('@xen-orchestra/async-map')
const { VhdFile, mergeVhd } = require('vhd-lib')
const { dirname, resolve } = require('path')
const { DISK_TYPE_DIFFERENCING } = require('vhd-lib/dist/_constants.js')
const { isMetadataFile, isVhdFile, isXvaFile, isXvaSumFile } = require('./_backupType.js')
const { limitConcurrency } = require('limit-concurrency-decorator')
const { Task } = require('./Task.js')
// chain is an array of VHDs from child to parent
//
// the whole chain will be merged into parent, parent will be renamed to child
// and all the others will deleted
async function mergeVhdChain(chain, { handler, onLog, remove, merge }) {
assert(chain.length >= 2)
let child = chain[0]
const parent = chain[chain.length - 1]
const children = chain.slice(0, -1).reverse()
chain
.slice(1)
.reverse()
.forEach(parent => {
onLog(`the parent ${parent} of the child ${child} is unused`)
})
if (merge) {
// `mergeVhd` does not work with a stream, either
// - make it accept a stream
// - or create synthetic VHD which is not a stream
if (children.length !== 1) {
// TODO: implement merging multiple children
children.length = 1
child = children[0]
}
onLog(`merging ${child} into ${parent}`)
let done, total
const handle = setInterval(() => {
if (done !== undefined) {
onLog(`merging ${child}: ${done}/${total}`)
}
}, 10e3)
const mergedSize = await mergeVhd(
handler,
parent,
handler,
child,
// children.length === 1
// ? child
// : await createSyntheticStream(handler, children),
{
onProgress({ done: d, total: t }) {
done = d
total = t
},
}
)
clearInterval(handle)
await Promise.all([
handler.rename(parent, child),
asyncMap(children.slice(0, -1), child => {
onLog(`the VHD ${child} is unused`)
if (remove) {
onLog(`deleting unused VHD ${child}`)
return handler.unlink(child)
}
}),
])
return mergedSize
}
}
const noop = Function.prototype
const INTERRUPTED_VHDS_REG = /^(?:(.+)\/)?\.(.+)\.merge.json$/
const listVhds = async (handler, vmDir) => {
const vhds = []
const interruptedVhds = new Set()
await asyncMap(
await handler.list(`${vmDir}/vdis`, {
ignoreMissing: true,
prependDir: true,
}),
async jobDir =>
asyncMap(
await handler.list(jobDir, {
prependDir: true,
}),
async vdiDir => {
const list = await handler.list(vdiDir, {
filter: file => isVhdFile(file) || INTERRUPTED_VHDS_REG.test(file),
prependDir: true,
})
list.forEach(file => {
const res = INTERRUPTED_VHDS_REG.exec(file)
if (res === null) {
vhds.push(file)
} else {
const [, dir, file] = res
interruptedVhds.add(`${dir}/${file}`)
}
})
}
)
)
return { vhds, interruptedVhds }
}
const defaultMergeLimiter = limitConcurrency(1)
exports.cleanVm = async function cleanVm(
vmDir,
{ fixMetadata, remove, merge, mergeLimiter = defaultMergeLimiter, onLog = noop }
) {
const limitedMergeVhdChain = mergeLimiter(mergeVhdChain)
const handler = this._handler
const vhds = new Set()
const vhdParents = { __proto__: null }
const vhdChildren = { __proto__: null }
const vhdsList = await listVhds(handler, vmDir)
// remove broken VHDs
await asyncMap(vhdsList.vhds, async path => {
try {
const vhd = new VhdFile(handler, path)
await vhd.readHeaderAndFooter(!vhdsList.interruptedVhds.has(path))
vhds.add(path)
if (vhd.footer.diskType === DISK_TYPE_DIFFERENCING) {
const parent = resolve('/', dirname(path), vhd.header.parentUnicodeName)
vhdParents[path] = parent
if (parent in vhdChildren) {
const error = new Error('this script does not support multiple VHD children')
error.parent = parent
error.child1 = vhdChildren[parent]
error.child2 = path
throw error // should we throw?
}
vhdChildren[parent] = path
}
} catch (error) {
onLog(`error while checking the VHD with path ${path}`, { error })
if (error?.code === 'ERR_ASSERTION' && remove) {
onLog(`deleting broken ${path}`)
await handler.unlink(path)
}
}
})
// remove VHDs with missing ancestors
{
const deletions = []
// return true if the VHD has been deleted or is missing
const deleteIfOrphan = vhd => {
const parent = vhdParents[vhd]
if (parent === undefined) {
return
}
// no longer needs to be checked
delete vhdParents[vhd]
deleteIfOrphan(parent)
if (!vhds.has(parent)) {
vhds.delete(vhd)
onLog(`the parent ${parent} of the VHD ${vhd} is missing`)
if (remove) {
onLog(`deleting orphan VHD ${vhd}`)
deletions.push(handler.unlink(vhd))
}
}
}
// > A property that is deleted before it has been visited will not be
// > visited later.
// >
// > -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Deleted_added_or_modified_properties
for (const child in vhdParents) {
deleteIfOrphan(child)
}
await Promise.all(deletions)
}
const jsons = []
const xvas = new Set()
const xvaSums = []
const entries = await handler.list(vmDir, {
prependDir: true,
})
entries.forEach(path => {
if (isMetadataFile(path)) {
jsons.push(path)
} else if (isXvaFile(path)) {
xvas.add(path)
} else if (isXvaSumFile(path)) {
xvaSums.push(path)
}
})
await asyncMap(xvas, async path => {
// check is not good enough to delete the file, the best we can do is report
// it
if (!(await this.isValidXva(path))) {
onLog(`the XVA with path ${path} is potentially broken`)
}
})
const unusedVhds = new Set(vhds)
const unusedXvas = new Set(xvas)
// compile the list of unused XVAs and VHDs, and remove backup metadata which
// reference a missing XVA/VHD
await asyncMap(jsons, async json => {
const metadata = JSON.parse(await handler.readFile(json))
const { mode } = metadata
let size
if (mode === 'full') {
const linkedXva = resolve('/', vmDir, metadata.xva)
if (xvas.has(linkedXva)) {
unusedXvas.delete(linkedXva)
size = await handler.getSize(linkedXva).catch(error => {
onLog(`failed to get size of ${json}`, { error })
})
} else {
onLog(`the XVA linked to the metadata ${json} is missing`)
if (remove) {
onLog(`deleting incomplete backup ${json}`)
await handler.unlink(json)
}
}
} else if (mode === 'delta') {
const linkedVhds = (() => {
const { vhds } = metadata
return Object.keys(vhds).map(key => resolve('/', vmDir, vhds[key]))
})()
// FIXME: find better approach by keeping as much of the backup as
// possible (existing disks) even if one disk is missing
if (linkedVhds.every(_ => vhds.has(_))) {
linkedVhds.forEach(_ => unusedVhds.delete(_))
size = await asyncMap(linkedVhds, vhd => handler.getSize(vhd)).then(sum, error => {
onLog(`failed to get size of ${json}`, { error })
})
} else {
onLog(`Some VHDs linked to the metadata ${json} are missing`)
if (remove) {
onLog(`deleting incomplete backup ${json}`)
await handler.unlink(json)
}
}
}
const metadataSize = metadata.size
if (size !== undefined && metadataSize !== size) {
onLog(`incorrect size in metadata: ${metadataSize ?? 'none'} instead of ${size}`)
// don't update if the the stored size is greater than found files,
// it can indicates a problem
if (fixMetadata && (metadataSize === undefined || metadataSize < size)) {
try {
metadata.size = size
await handler.writeFile(json, JSON.stringify(metadata), { flags: 'w' })
} catch (error) {
onLog(`failed to update size in backup metadata ${json}`, { error })
}
}
}
})
// TODO: parallelize by vm/job/vdi
const unusedVhdsDeletion = []
const toMerge = []
{
// VHD chains (as list from child to ancestor) to merge indexed by last
// ancestor
const vhdChainsToMerge = { __proto__: null }
const toCheck = new Set(unusedVhds)
const getUsedChildChainOrDelete = vhd => {
if (vhd in vhdChainsToMerge) {
const chain = vhdChainsToMerge[vhd]
delete vhdChainsToMerge[vhd]
return chain
}
if (!unusedVhds.has(vhd)) {
return [vhd]
}
// no longer needs to be checked
toCheck.delete(vhd)
const child = vhdChildren[vhd]
if (child !== undefined) {
const chain = getUsedChildChainOrDelete(child)
if (chain !== undefined) {
chain.push(vhd)
return chain
}
}
onLog(`the VHD ${vhd} is unused`)
if (remove) {
onLog(`deleting unused VHD ${vhd}`)
unusedVhdsDeletion.push(handler.unlink(vhd))
}
}
toCheck.forEach(vhd => {
vhdChainsToMerge[vhd] = getUsedChildChainOrDelete(vhd)
})
// merge interrupted VHDs
vhdsList.interruptedVhds.forEach(parent => {
vhdChainsToMerge[parent] = [vhdChildren[parent], parent]
})
Object.values(vhdChainsToMerge).forEach(chain => {
if (chain !== undefined) {
toMerge.push(chain)
}
})
}
const doMerge = () => {
const promise = asyncMap(toMerge, async chain => limitedMergeVhdChain(chain, { handler, onLog, remove, merge }))
return merge ? promise.then(sizes => ({ size: sum(sizes) })) : promise
}
await Promise.all([
...unusedVhdsDeletion,
toMerge.length !== 0 && (merge ? Task.run({ name: 'merge' }, doMerge) : doMerge()),
asyncMap(unusedXvas, path => {
onLog(`the XVA ${path} is unused`)
if (remove) {
onLog(`deleting unused XVA ${path}`)
return handler.unlink(path)
}
}),
asyncMap(xvaSums, path => {
// no need to handle checksums for XVAs deleted by the script, they will be handled by `unlink()`
if (!xvas.has(path.slice(0, -'.checksum'.length))) {
onLog(`the XVA checksum ${path} is unused`)
if (remove) {
onLog(`deleting unused XVA checksum ${path}`)
return handler.unlink(path)
}
}
}),
])
return {
// boolean whether some VHDs were merged (or should be merged)
merge: toMerge.length !== 0,
}
}

View File

@@ -0,0 +1,347 @@
const compareVersions = require('compare-versions')
const find = require('lodash/find.js')
const groupBy = require('lodash/groupBy.js')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const omit = require('lodash/omit.js')
const { asyncMap } = require('@xen-orchestra/async-map')
const { CancelToken } = require('promise-toolbox')
const { createVhdStreamWithLength } = require('vhd-lib')
const { defer } = require('golike-defer')
const { cancelableMap } = require('./_cancelableMap.js')
const TAG_BASE_DELTA = 'xo:base_delta'
exports.TAG_BASE_DELTA = TAG_BASE_DELTA
const TAG_COPY_SRC = 'xo:copy_of'
exports.TAG_COPY_SRC = TAG_COPY_SRC
const ensureArray = value => (value === undefined ? [] : Array.isArray(value) ? value : [value])
exports.exportDeltaVm = async function exportDeltaVm(
vm,
baseVm,
{
cancelToken = CancelToken.none,
// Sets of UUIDs of VDIs that must be exported as full.
fullVdisRequired = new Set(),
disableBaseTags = false,
} = {}
) {
// refs of VM's VDIs → base's VDIs.
const baseVdis = {}
baseVm &&
baseVm.$VBDs.forEach(vbd => {
let vdi, snapshotOf
if ((vdi = vbd.$VDI) && (snapshotOf = vdi.$snapshot_of) && !fullVdisRequired.has(snapshotOf.uuid)) {
baseVdis[vdi.snapshot_of] = vdi
}
})
const streams = {}
const vdis = {}
const vbds = {}
await cancelableMap(cancelToken, vm.$VBDs, async (cancelToken, vbd) => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
return
}
// If the VDI name start with `[NOBAK]`, do not export it.
if (vdi.name_label.startsWith('[NOBAK]')) {
// FIXME: find a way to not create the VDI snapshot in the
// first time.
//
// The snapshot must not exist otherwise it could break the
// next export.
ignoreErrors.call(vdi.$destroy())
return
}
vbds[vbd.$ref] = vbd
const vdiRef = vdi.$ref
if (vdiRef in vdis) {
// This VDI has already been managed.
return
}
// Look for a snapshot of this vdi in the base VM.
const baseVdi = baseVdis[vdi.snapshot_of]
vdis[vdiRef] = {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: baseVdi && !disableBaseTags ? baseVdi.uuid : undefined,
},
$snapshot_of$uuid: vdi.$snapshot_of?.uuid,
$SR$uuid: vdi.$SR.uuid,
}
streams[`${vdiRef}.vhd`] = await vdi.$exportContent({
baseRef: baseVdi?.$ref,
cancelToken,
format: 'vhd',
})
})
const suspendVdi = vm.$suspend_VDI
if (suspendVdi !== undefined) {
const vdiRef = suspendVdi.$ref
vdis[vdiRef] = {
...suspendVdi,
$SR$uuid: suspendVdi.$SR.uuid,
}
streams[`${vdiRef}.vhd`] = await suspendVdi.$exportContent({
cancelToken,
format: 'vhd',
})
}
const vifs = {}
vm.$VIFs.forEach(vif => {
const network = vif.$network
vifs[vif.$ref] = {
...vif,
$network$uuid: network.uuid,
$network$name_label: network.name_label,
$network$VLAN: network.$PIFs[0]?.VLAN,
}
})
return Object.defineProperty(
{
version: '1.1.0',
vbds,
vdis,
vifs,
vm: {
...vm,
other_config:
baseVm && !disableBaseTags
? {
...vm.other_config,
[TAG_BASE_DELTA]: baseVm.uuid,
}
: omit(vm.other_config, TAG_BASE_DELTA),
},
},
'streams',
{
configurable: true,
value: streams,
writable: true,
}
)
}
exports.importDeltaVm = defer(async function importDeltaVm(
$defer,
deltaVm,
sr,
{ cancelToken = CancelToken.none, detectBase = true, mapVdisSrs = {}, newMacAddresses = false } = {}
) {
const { version } = deltaVm
if (compareVersions(version, '1.0.0') < 0) {
throw new Error(`Unsupported delta backup version: ${version}`)
}
const vmRecord = deltaVm.vm
const xapi = sr.$xapi
let baseVm
if (detectBase) {
const remoteBaseVmUuid = vmRecord.other_config[TAG_BASE_DELTA]
if (remoteBaseVmUuid) {
baseVm = find(xapi.objects.all, obj => (obj = obj.other_config) && obj[TAG_COPY_SRC] === remoteBaseVmUuid)
if (!baseVm) {
throw new Error(`could not find the base VM (copy of ${remoteBaseVmUuid})`)
}
}
}
const baseVdis = {}
baseVm &&
baseVm.$VBDs.forEach(vbd => {
const vdi = vbd.$VDI
if (vdi !== undefined) {
baseVdis[vbd.VDI] = vbd.$VDI
}
})
const vdiRecords = deltaVm.vdis
// 0. Create suspend_VDI
let suspendVdi
if (vmRecord.power_state === 'Suspended') {
const vdi = vdiRecords[vmRecord.suspend_VDI]
suspendVdi = await xapi.getRecord(
'VDI',
await xapi.VDI_create({
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid,
},
sr: mapVdisSrs[vdi.uuid] ?? sr.$ref,
})
)
$defer.onFailure(() => suspendVdi.$destroy())
}
// 1. Create the VM.
const vmRef = await xapi.VM_create(
{
...vmRecord,
affinity: undefined,
blocked_operations: {
...vmRecord.blocked_operations,
start: 'Importing…',
start_on: 'Importing…',
},
ha_always_run: false,
is_a_template: false,
name_label: '[Importing…] ' + vmRecord.name_label,
other_config: {
...vmRecord.other_config,
[TAG_COPY_SRC]: vmRecord.uuid,
},
},
{
bios_strings: vmRecord.bios_strings,
generateMacSeed: newMacAddresses,
suspend_VDI: suspendVdi?.$ref,
}
)
$defer.onFailure.call(xapi, 'VM_destroy', vmRef)
// 2. Delete all VBDs which may have been created by the import.
await asyncMap(await xapi.getField('VM', vmRef, 'VBDs'), ref => ignoreErrors.call(xapi.call('VBD.destroy', ref)))
// 3. Create VDIs & VBDs.
const vbdRecords = deltaVm.vbds
const vbds = groupBy(vbdRecords, 'VDI')
const newVdis = {}
await asyncMap(Object.keys(vdiRecords), async vdiRef => {
const vdi = vdiRecords[vdiRef]
let newVdi
const remoteBaseVdiUuid = detectBase && vdi.other_config[TAG_BASE_DELTA]
if (remoteBaseVdiUuid) {
const baseVdi = find(baseVdis, vdi => vdi.other_config[TAG_COPY_SRC] === remoteBaseVdiUuid)
if (!baseVdi) {
throw new Error(`missing base VDI (copy of ${remoteBaseVdiUuid})`)
}
newVdi = await xapi.getRecord('VDI', await baseVdi.$clone())
$defer.onFailure(() => newVdi.$destroy())
await newVdi.update_other_config(TAG_COPY_SRC, vdi.uuid)
} else if (vdiRef === vmRecord.suspend_VDI) {
// suspendVDI has already created
newVdi = suspendVdi
} else {
newVdi = await xapi.getRecord(
'VDI',
await xapi.VDI_create({
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid,
},
SR: mapVdisSrs[vdi.uuid] ?? sr.$ref,
})
)
$defer.onFailure(() => newVdi.$destroy())
}
const vdiVbds = vbds[vdiRef]
if (vdiVbds !== undefined) {
await asyncMap(Object.values(vdiVbds), vbd =>
xapi.VBD_create({
...vbd,
VDI: newVdi.$ref,
VM: vmRef,
})
)
}
newVdis[vdiRef] = newVdi
})
const networksByNameLabelByVlan = {}
let defaultNetwork
Object.values(xapi.objects.all).forEach(object => {
if (object.$type === 'network') {
const pif = object.$PIFs[0]
if (pif === undefined) {
// ignore network
return
}
const vlan = pif.VLAN
const networksByNameLabel = networksByNameLabelByVlan[vlan] || (networksByNameLabelByVlan[vlan] = {})
defaultNetwork = networksByNameLabel[object.name_label] = object
}
})
const { streams } = deltaVm
await Promise.all([
// Import VDI contents.
cancelableMap(cancelToken, Object.entries(newVdis), async (cancelToken, [id, vdi]) => {
for (let stream of ensureArray(streams[`${id}.vhd`])) {
if (typeof stream === 'function') {
stream = await stream()
}
if (stream.length === undefined) {
stream = await createVhdStreamWithLength(stream)
}
await vdi.$importContent(stream, { cancelToken, format: 'vhd' })
}
}),
// Create VIFs.
asyncMap(Object.values(deltaVm.vifs), vif => {
let network = vif.$network$uuid && xapi.getObjectByUuid(vif.$network$uuid, undefined)
if (network === undefined) {
const { $network$VLAN: vlan = -1 } = vif
const networksByNameLabel = networksByNameLabelByVlan[vlan]
if (networksByNameLabel !== undefined) {
network = networksByNameLabel[vif.$network$name_label]
if (network === undefined) {
network = networksByNameLabel[Object.keys(networksByNameLabel)[0]]
}
} else {
network = defaultNetwork
}
}
if (network) {
return xapi.VIF_create(
{
...vif,
network: network.$ref,
VM: vmRef,
},
{
MAC: newMacAddresses ? undefined : vif.MAC,
}
)
}
}),
])
await Promise.all([
deltaVm.vm.ha_always_run && xapi.setField('VM', vmRef, 'ha_always_run', true),
xapi.setField('VM', vmRef, 'name_label', deltaVm.vm.name_label),
])
return vmRef
})

View File

@@ -1,4 +1,4 @@
function extractIdsFromSimplePattern(pattern) {
exports.extractIdsFromSimplePattern = function extractIdsFromSimplePattern(pattern) {
if (pattern === undefined) {
return []
}
@@ -27,4 +27,3 @@ function extractIdsFromSimplePattern(pattern) {
throw new Error('invalid pattern')
}
exports.extractIdsFromSimplePattern = extractIdsFromSimplePattern

View File

@@ -0,0 +1,28 @@
const eos = require('end-of-stream')
const { PassThrough } = require('stream')
// create a new readable stream from an existing one which may be piped later
//
// in case of error in the new readable stream, it will simply be unpiped
// from the original one
exports.forkStreamUnpipe = function forkStreamUnpipe(stream) {
const { forks = 0 } = stream
stream.forks = forks + 1
const proxy = new PassThrough()
stream.pipe(proxy)
eos(stream, error => {
if (error !== undefined) {
proxy.destroy(error)
}
})
eos(proxy, _ => {
stream.forks--
stream.unpipe(proxy)
if (stream.forks === 0) {
stream.destroy(new Error('no more consumers for this stream'))
}
})
return proxy
}

View File

@@ -0,0 +1,4 @@
// returns all entries but the last retention-th
exports.getOldEntries = function getOldEntries(retention, entries) {
return entries === undefined ? [] : retention > 0 ? entries.slice(0, -retention) : entries
}

View File

@@ -0,0 +1,20 @@
const Disposable = require('promise-toolbox/Disposable.js')
const { join } = require('path')
const { mkdir, rmdir } = require('fs-extra')
const { tmpdir } = require('os')
const MAX_ATTEMPTS = 3
exports.getTmpDir = async function getTmpDir() {
for (let i = 0; true; ++i) {
const path = join(tmpdir(), Math.random().toString(36).slice(2))
try {
await mkdir(path)
return new Disposable(() => rmdir(path), path)
} catch (error) {
if (i === MAX_ATTEMPTS) {
throw error
}
}
}
}

View File

@@ -0,0 +1,6 @@
const BACKUP_DIR = 'xo-vm-backups'
exports.BACKUP_DIR = BACKUP_DIR
exports.getVmBackupDir = function getVmBackupDir(uuid) {
return `${BACKUP_DIR}/${uuid}`
}

View File

@@ -1,10 +1,10 @@
const assert = require('assert')
const fs = require('fs-extra')
const isGzipFile = async fd => {
const isGzipFile = async (handler, fd) => {
// https://tools.ietf.org/html/rfc1952.html#page-5
const magicNumber = Buffer.allocUnsafe(2)
assert.strictEqual((await fs.read(fd, magicNumber, 0, magicNumber.length, 0)).bytesRead, magicNumber.length)
assert.strictEqual((await handler.read(fd, magicNumber, 0)).bytesRead, magicNumber.length)
return magicNumber[0] === 31 && magicNumber[1] === 139
}
@@ -21,32 +21,33 @@ const isGzipFile = async fd => {
// /^Ref:\d+/\d+\.checksum$/ and then validating the tar structure from it
//
// https://github.com/npm/node-tar/issues/234#issuecomment-538190295
const isValidTar = async (size, fd) => {
const isValidTar = async (handler, size, fd) => {
if (size <= 1024 || size % 512 !== 0) {
return false
}
const buf = Buffer.allocUnsafe(1024)
assert.strictEqual((await fs.read(fd, buf, 0, buf.length, size - buf.length)).bytesRead, buf.length)
assert.strictEqual((await handler.read(fd, buf, size - buf.length)).bytesRead, buf.length)
return buf.every(_ => _ === 0)
}
// TODO: find an heuristic for compressed files
const isValidXva = async path => {
async function isValidXva(path) {
const handler = this._handler
try {
const fd = await fs.open(path, 'r')
const fd = await handler.openFile(path, 'r')
try {
const { size } = await fs.fstat(fd)
const size = await handler.getSize(fd)
if (size < 20) {
// neither a valid gzip not tar
return false
}
return (await isGzipFile(fd))
return (await isGzipFile(handler, fd))
? true // gzip files cannot be validated at this time
: await isValidTar(size, fd)
: await isValidTar(handler, size, fd)
} finally {
fs.close(fd).catch(noop)
handler.closeFile(fd).catch(noop)
}
} catch (error) {
// never throw, log and report as valid to avoid side effects

View File

@@ -0,0 +1,52 @@
const fromCallback = require('promise-toolbox/fromCallback.js')
const { createLogger } = require('@xen-orchestra/log')
const { createParser } = require('parse-pairs')
const { execFile } = require('child_process')
const { debug } = createLogger('xo:backups:listPartitions')
const IGNORED_PARTITION_TYPES = {
// https://github.com/jhermsmeier/node-mbr/blob/master/lib/partition.js#L38
0x05: true,
0x0f: true,
0x15: true,
0x5e: true,
0x5f: true,
0x85: true,
0x91: true,
0x9b: true,
0xc5: true,
0xcf: true,
0xd5: true,
0x82: true, // swap
}
const LVM_PARTITION_TYPE = 0x8e
exports.LVM_PARTITION_TYPE = LVM_PARTITION_TYPE
const parsePartxLine = createParser({
keyTransform: key => (key === 'UUID' ? 'id' : key.toLowerCase()),
valueTransform: (value, key) => (key === 'start' || key === 'size' || key === 'type' ? +value : value),
})
// returns an empty array in case of a non-partitioned disk
exports.listPartitions = async function listPartitions(devicePath) {
const parts = await fromCallback(execFile, 'partx', [
'--bytes',
'--output=NR,START,SIZE,NAME,UUID,TYPE',
'--pairs',
devicePath,
]).catch(error => {
// partx returns 1 since v2.33 when failing to read partitions.
//
// Prior versions are correctly handled by the nominal case.
debug('listPartitions', { error })
return ''
})
return parts
.split(/\r?\n/)
.map(parsePartxLine)
.filter(({ type }) => type != null && !(type in IGNORED_PARTITION_TYPES))
}

View File

@@ -0,0 +1,31 @@
const fromCallback = require('promise-toolbox/fromCallback.js')
const { createParser } = require('parse-pairs')
const { execFile } = require('child_process')
// ===================================================================
const parse = createParser({
keyTransform: key => key.slice(5).toLowerCase(),
})
const makeFunction =
command =>
async (fields, ...args) => {
const info = await fromCallback(execFile, command, [
'--noheading',
'--nosuffix',
'--nameprefixes',
'--unbuffered',
'--units',
'b',
'-o',
String(fields),
...args,
])
return info
.trim()
.split(/\r?\n/)
.map(Array.isArray(fields) ? parse : line => parse(line)[fields])
}
exports.lvs = makeFunction('lvs')
exports.pvs = makeFunction('pvs')

View File

@@ -0,0 +1,7 @@
exports.watchStreamSize = function watchStreamSize(stream, container = { size: 0 }) {
stream.on('data', data => {
container.size += data.length
})
stream.pause()
return container
}

View File

@@ -0,0 +1,34 @@
const mapValues = require('lodash/mapValues.js')
const { dirname } = require('path')
function formatVmBackup(backup) {
return {
disks:
backup.vhds === undefined
? []
: Object.keys(backup.vhds).map(vdiId => {
const vdi = backup.vdis[vdiId]
return {
id: `${dirname(backup._filename)}/${backup.vhds[vdiId]}`,
name: vdi.name_label,
uuid: vdi.uuid,
}
}),
id: backup.id,
jobId: backup.jobId,
mode: backup.mode,
scheduleId: backup.scheduleId,
size: backup.size,
timestamp: backup.timestamp,
vm: {
name_description: backup.vm.name_description,
name_label: backup.vm.name_label,
},
}
}
// format all backups as returned by RemoteAdapter#listAllVmBackups()
exports.formatVmBackups = function formatVmBackups(backupsByVM) {
return mapValues(backupsByVM, backups => backups.map(formatVmBackup))
}

View File

@@ -1,3 +0,0 @@
// returns all entries but the last retention-th
exports.getOldEntries = (retention, entries) =>
entries === undefined ? [] : retention > 0 ? entries.slice(0, -retention) : entries

View File

@@ -0,0 +1,69 @@
#!/usr/bin/env node
const { catchGlobalErrors } = require('@xen-orchestra/log/configure.js')
const { createLogger } = require('@xen-orchestra/log')
const { getSyncedHandler } = require('@xen-orchestra/fs')
const { join } = require('path')
const Disposable = require('promise-toolbox/Disposable')
const min = require('lodash/min')
const { getVmBackupDir } = require('../_getVmBackupDir.js')
const { RemoteAdapter } = require('../RemoteAdapter.js')
const { CLEAN_VM_QUEUE } = require('./index.js')
// -------------------------------------------------------------------
catchGlobalErrors(createLogger('xo:backups:mergeWorker'))
const { fatal, info, warn } = createLogger('xo:backups:mergeWorker')
// -------------------------------------------------------------------
const main = Disposable.wrap(async function* main(args) {
const handler = yield getSyncedHandler({ url: 'file://' + process.cwd() })
yield handler.lock(CLEAN_VM_QUEUE)
const adapter = new RemoteAdapter(handler)
const listRetry = async () => {
const timeoutResolver = resolve => setTimeout(resolve, 10e3)
for (let i = 0; i < 10; ++i) {
const entries = await handler.list(CLEAN_VM_QUEUE)
if (entries.length !== 0) {
return entries
}
await new Promise(timeoutResolver)
}
}
let taskFiles
while ((taskFiles = await listRetry()) !== undefined) {
const taskFileBasename = min(taskFiles)
const taskFile = join(CLEAN_VM_QUEUE, '_' + taskFileBasename)
// move this task to the end
await handler.rename(join(CLEAN_VM_QUEUE, taskFileBasename), taskFile)
try {
const vmDir = getVmBackupDir(String(await handler.readFile(taskFile)))
await adapter.cleanVm(vmDir, { merge: true, onLog: info, remove: true })
handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
} catch (error) {
warn('failure handling task', { error })
}
}
})
info('starting')
main(process.argv.slice(2)).then(
() => {
info('bye :-)')
},
error => {
fatal(error)
process.exit(1)
}
)

View File

@@ -0,0 +1,25 @@
const { join, resolve } = require('path')
const { spawn } = require('child_process')
const { check } = require('proper-lockfile')
const CLEAN_VM_QUEUE = (exports.CLEAN_VM_QUEUE = '/xo-vm-backups/.queue/clean-vm/')
const CLI_PATH = resolve(__dirname, 'cli.js')
exports.run = async function runMergeWorker(remotePath) {
try {
// TODO: find a way to pass the acquire the lock and then pass it down the worker
if (await check(join(remotePath, CLEAN_VM_QUEUE))) {
// already locked, don't start another worker
return
}
spawn(CLI_PATH, {
cwd: remotePath,
detached: true,
stdio: 'inherit',
}).unref()
} catch (error) {
// we usually don't want to throw if the merge worker failed to start
return error
}
}

View File

@@ -8,16 +8,38 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.1.1",
"version": "0.15.1",
"engines": {
"node": ">=8.10"
"node": ">=14.6"
},
"scripts": {
"postversion": "npm publish --access public"
},
"dependencies": {
"@vates/compose": "^2.0.0",
"@vates/disposable": "^0.1.1",
"@vates/parse-duration": "^0.1.1",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/fs": "^0.18.0",
"@xen-orchestra/log": "^0.3.0",
"@xen-orchestra/template": "^0.1.0",
"compare-versions": "^4.0.1",
"d3-time-format": "^3.0.0",
"fs-extra": "^9.0.0"
"end-of-stream": "^1.4.4",
"fs-extra": "^10.0.0",
"golike-defer": "^0.5.1",
"limit-concurrency-decorator": "^0.5.0",
"lodash": "^4.17.20",
"node-zone": "^0.4.0",
"parse-pairs": "^1.1.0",
"promise-toolbox": "^0.20.0",
"proper-lockfile": "^4.1.2",
"pump": "^3.0.0",
"vhd-lib": "^1.3.0",
"yazl": "^2.5.1"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^0.8.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -0,0 +1,23 @@
const { DIR_XO_CONFIG_BACKUPS, DIR_XO_POOL_METADATA_BACKUPS } = require('./RemoteAdapter.js')
exports.parseMetadataBackupId = function parseMetadataBackupId(backupId) {
const [dir, ...rest] = backupId.split('/')
if (dir === DIR_XO_CONFIG_BACKUPS) {
const [scheduleId, timestamp] = rest
return {
type: 'xoConfig',
scheduleId,
timestamp,
}
} else if (dir === DIR_XO_POOL_METADATA_BACKUPS) {
const [scheduleId, poolUuid, timestamp] = rest
return {
type: 'pool',
poolUuid,
scheduleId,
timestamp,
}
}
throw new Error(`not supported backup dir (${dir})`)
}

View File

@@ -0,0 +1,38 @@
const path = require('path')
const { createLogger } = require('@xen-orchestra/log')
const { fork } = require('child_process')
const { warn } = createLogger('xo:backups:backupWorker')
const PATH = path.resolve(__dirname, '_backupWorker.js')
exports.runBackupWorker = function runBackupWorker(params, onLog) {
return new Promise((resolve, reject) => {
const worker = fork(PATH)
worker.on('exit', code => reject(new Error(`worker exited with code ${code}`)))
worker.on('error', reject)
worker.on('message', message => {
try {
if (message.type === 'result') {
if (message.status === 'success') {
resolve(message.result)
} else {
reject(message.result)
}
} else if (message.type === 'log') {
onLog(message.data)
}
} catch (error) {
warn(error)
}
})
worker.send({
action: 'run',
data: params,
runWithLogs: onLog !== undefined,
})
})
}

View File

@@ -1,11 +0,0 @@
exports.watchStreamSize = stream => {
const container = { size: 0 }
const isPaused = stream.isPaused()
stream.on('data', data => {
container.size += data.length
})
if (isPaused) {
stream.pause()
}
return container
}

View File

@@ -0,0 +1,221 @@
const assert = require('assert')
const map = require('lodash/map.js')
const mapValues = require('lodash/mapValues.js')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const { asyncMap } = require('@xen-orchestra/async-map')
const { chainVhd, checkVhdChain, VhdFile } = require('vhd-lib')
const { createLogger } = require('@xen-orchestra/log')
const { dirname } = require('path')
const { formatFilenameDate } = require('../_filenameDate.js')
const { getOldEntries } = require('../_getOldEntries.js')
const { getVmBackupDir } = require('../_getVmBackupDir.js')
const { Task } = require('../Task.js')
const { MixinBackupWriter } = require('./_MixinBackupWriter.js')
const { AbstractDeltaWriter } = require('./_AbstractDeltaWriter.js')
const { checkVhd } = require('./_checkVhd.js')
const { packUuid } = require('./_packUuid.js')
const { warn } = createLogger('xo:backups:DeltaBackupWriter')
exports.DeltaBackupWriter = class DeltaBackupWriter extends MixinBackupWriter(AbstractDeltaWriter) {
async checkBaseVdis(baseUuidToSrcVdi) {
const { handler } = this._adapter
const backup = this._backup
const backupDir = getVmBackupDir(backup.vm.uuid)
const vdisDir = `${backupDir}/vdis/${backup.job.id}`
await asyncMap(baseUuidToSrcVdi, async ([baseUuid, srcVdi]) => {
let found = false
try {
const vhds = await handler.list(`${vdisDir}/${srcVdi.uuid}`, {
filter: _ => _[0] !== '.' && _.endsWith('.vhd'),
prependDir: true,
})
await asyncMap(vhds, async path => {
try {
await checkVhdChain(handler, path)
const vhd = new VhdFile(handler, path)
await vhd.readHeaderAndFooter()
found = found || vhd.footer.uuid.equals(packUuid(baseUuid))
} catch (error) {
warn('checkBaseVdis', { error })
await ignoreErrors.call(handler.unlink(path))
}
})
} catch (error) {
warn('checkBaseVdis', { error })
}
if (!found) {
baseUuidToSrcVdi.delete(baseUuid)
}
})
}
async beforeBackup() {
await super.beforeBackup()
return this._cleanVm({ merge: true })
}
prepare({ isFull }) {
// create the task related to this export and ensure all methods are called in this context
const task = new Task({
name: 'export',
data: {
id: this._remoteId,
isFull,
type: 'remote',
},
})
this.transfer = task.wrapFn(this.transfer)
this.cleanup = task.wrapFn(this.cleanup, true)
return task.run(() => this._prepare())
}
async _prepare() {
const adapter = this._adapter
const settings = this._settings
const { scheduleId, vm } = this._backup
const oldEntries = getOldEntries(
settings.exportRetention - 1,
await adapter.listVmBackups(vm.uuid, _ => _.mode === 'delta' && _.scheduleId === scheduleId)
)
this._oldEntries = oldEntries
// FIXME: implement optimized multiple VHDs merging with synthetic
// delta
//
// For the time being, limit the number of deleted backups by run
// because it can take a very long time and can lead to
// interrupted backup with broken VHD chain.
//
// The old backups will be eventually merged in future runs of the
// job.
const { maxMergedDeltasPerRun } = this._settings
if (oldEntries.length > maxMergedDeltasPerRun) {
oldEntries.length = maxMergedDeltasPerRun
}
if (settings.deleteFirst) {
await this._deleteOldEntries()
}
}
async cleanup() {
if (!this._settings.deleteFirst) {
await this._deleteOldEntries()
}
}
async _deleteOldEntries() {
const adapter = this._adapter
const oldEntries = this._oldEntries
// delete sequentially from newest to oldest to avoid unnecessary merges
for (let i = oldEntries.length; i-- > 0; ) {
await adapter.deleteDeltaVmBackups([oldEntries[i]])
}
}
async _transfer({ timestamp, deltaExport, sizeContainers }) {
const adapter = this._adapter
const backup = this._backup
const { job, scheduleId, vm } = backup
const jobId = job.id
const handler = adapter.handler
const backupDir = getVmBackupDir(vm.uuid)
// TODO: clean VM backup directory
const basename = formatFilenameDate(timestamp)
const vhds = mapValues(
deltaExport.vdis,
vdi =>
`vdis/${jobId}/${
vdi.type === 'suspend'
? // doesn't make sense to group by parent for memory because we
// don't do delta for it
vdi.uuid
: vdi.$snapshot_of$uuid
}/${basename}.vhd`
)
const metadataFilename = `${backupDir}/${basename}.json`
const metadataContent = {
jobId,
mode: job.mode,
scheduleId,
timestamp,
vbds: deltaExport.vbds,
vdis: deltaExport.vdis,
version: '2.0.0',
vifs: deltaExport.vifs,
vhds,
vm,
vmSnapshot: this._backup.exportedVm,
}
const { size } = await Task.run({ name: 'transfer' }, async () => {
await Promise.all(
map(deltaExport.vdis, async (vdi, id) => {
const path = `${backupDir}/${vhds[id]}`
const isDelta = vdi.other_config['xo:base_delta'] !== undefined
let parentPath
if (isDelta) {
const vdiDir = dirname(path)
parentPath = (
await handler.list(vdiDir, {
filter: filename => filename[0] !== '.' && filename.endsWith('.vhd'),
prependDir: true,
})
)
.sort()
.pop()
assert.notStrictEqual(parentPath, undefined, `missing parent of ${id}`)
parentPath = parentPath.slice(1) // remove leading slash
// TODO remove when this has been done before the export
await checkVhd(handler, parentPath)
}
await adapter.outputStream(path, deltaExport.streams[`${id}.vhd`], {
// no checksum for VHDs, because they will be invalidated by
// merges and chainings
checksum: false,
validator: tmpPath => checkVhd(handler, tmpPath),
})
if (isDelta) {
await chainVhd(handler, parentPath, handler, path)
}
// set the correct UUID in the VHD
const vhd = new VhdFile(handler, path)
await vhd.readHeaderAndFooter()
vhd.footer.uuid = packUuid(vdi.uuid)
await vhd.readBlockAllocationTable() // required by writeFooter()
await vhd.writeFooter()
})
)
return {
size: Object.values(sizeContainers).reduce((sum, { size }) => sum + size, 0),
}
})
metadataContent.size = size
await handler.outputFile(metadataFilename, JSON.stringify(metadataContent), {
dirMode: backup.config.dirMode,
})
// TODO: run cleanup?
}
}

View File

@@ -0,0 +1,126 @@
const { asyncMap, asyncMapSettled } = require('@xen-orchestra/async-map')
const ignoreErrors = require('promise-toolbox/ignoreErrors.js')
const { formatDateTime } = require('@xen-orchestra/xapi')
const { formatFilenameDate } = require('../_filenameDate.js')
const { getOldEntries } = require('../_getOldEntries.js')
const { importDeltaVm, TAG_COPY_SRC } = require('../_deltaVm.js')
const { Task } = require('../Task.js')
const { AbstractDeltaWriter } = require('./_AbstractDeltaWriter.js')
const { MixinReplicationWriter } = require('./_MixinReplicationWriter.js')
const { listReplicatedVms } = require('./_listReplicatedVms.js')
exports.DeltaReplicationWriter = class DeltaReplicationWriter extends MixinReplicationWriter(AbstractDeltaWriter) {
async checkBaseVdis(baseUuidToSrcVdi, baseVm) {
const sr = this._sr
const replicatedVm = listReplicatedVms(sr.$xapi, this._backup.job.id, sr.uuid, this._backup.vm.uuid).find(
vm => vm.other_config[TAG_COPY_SRC] === baseVm.uuid
)
if (replicatedVm === undefined) {
return baseUuidToSrcVdi.clear()
}
const xapi = replicatedVm.$xapi
const replicatedVdis = new Set(
await asyncMap(await replicatedVm.$getDisks(), async vdiRef => {
const otherConfig = await xapi.getField('VDI', vdiRef, 'other_config')
return otherConfig[TAG_COPY_SRC]
})
)
for (const uuid of baseUuidToSrcVdi.keys()) {
if (!replicatedVdis.has(uuid)) {
baseUuidToSrcVdi.delete(uuid)
}
}
}
prepare({ isFull }) {
// create the task related to this export and ensure all methods are called in this context
const task = new Task({
name: 'export',
data: {
id: this._sr.uuid,
isFull,
type: 'SR',
},
})
this.transfer = task.wrapFn(this.transfer)
this.cleanup = task.wrapFn(this.cleanup, true)
return task.run(() => this._prepare())
}
async _prepare() {
const settings = this._settings
const { uuid: srUuid, $xapi: xapi } = this._sr
const { scheduleId, vm } = this._backup
// delete previous interrupted copies
ignoreErrors.call(asyncMapSettled(listReplicatedVms(xapi, scheduleId, undefined, vm.uuid), vm => vm.$destroy))
this._oldEntries = getOldEntries(settings.copyRetention - 1, listReplicatedVms(xapi, scheduleId, srUuid, vm.uuid))
if (settings.deleteFirst) {
await this._deleteOldEntries()
}
}
async cleanup() {
if (!this._settings.deleteFirst) {
await this._deleteOldEntries()
}
}
async _deleteOldEntries() {
return asyncMapSettled(this._oldEntries, vm => vm.$destroy())
}
async _transfer({ timestamp, deltaExport, sizeContainers }) {
const sr = this._sr
const { job, scheduleId, vm } = this._backup
const { uuid: srUuid, $xapi: xapi } = sr
let targetVmRef
await Task.run({ name: 'transfer' }, async () => {
targetVmRef = await importDeltaVm(
{
__proto__: deltaExport,
vm: {
...deltaExport.vm,
tags: [...deltaExport.vm.tags, 'Continuous Replication'],
},
},
sr
)
return {
size: Object.values(sizeContainers).reduce((sum, { size }) => sum + size, 0),
}
})
const targetVm = await xapi.getRecord('VM', targetVmRef)
await Promise.all([
targetVm.ha_restart_priority !== '' &&
Promise.all([targetVm.set_ha_restart_priority(''), targetVm.add_tags('HA disabled')]),
targetVm.set_name_label(`${vm.name_label} - ${job.name} - (${formatFilenameDate(timestamp)})`),
asyncMap(['start', 'start_on'], op =>
targetVm.update_blocked_operations(
op,
'Start operation for this vm is blocked, clone it if you want to use it.'
)
),
targetVm.update_other_config({
'xo:backup:sr': srUuid,
// these entries need to be added in case of offline backup
'xo:backup:datetime': formatDateTime(timestamp),
'xo:backup:job': job.id,
'xo:backup:schedule': scheduleId,
'xo:backup:vm': vm.uuid,
}),
])
}
}

Some files were not shown because too many files have changed in this diff Show More