mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-12-05 14:42:25 -06:00
Compare commits
431 Commits
docs-fixes
...
feat_rolli
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d311d9b11 | ||
|
|
06547f0a6f | ||
|
|
e1b7077dc1 | ||
|
|
790201ef8b | ||
|
|
8e2d9f1022 | ||
|
|
566bdeda63 | ||
|
|
e86d71fc31 | ||
|
|
4827f33305 | ||
|
|
9b6d1089f4 | ||
|
|
d1f8f61791 | ||
|
|
dbf00ba0cd | ||
|
|
44a0d14e88 | ||
|
|
0b52a05bb3 | ||
|
|
407591d74d | ||
|
|
0b29586626 | ||
|
|
42eb8664be | ||
|
|
1d8c429532 | ||
|
|
c51df2239f | ||
|
|
b89c26459c | ||
|
|
a1333c07d7 | ||
|
|
5e8e5beba1 | ||
|
|
9169e11f35 | ||
|
|
6908001bd8 | ||
|
|
53ec9a62a8 | ||
|
|
4a0590b7e9 | ||
|
|
d358aed897 | ||
|
|
5fcb6db32e | ||
|
|
1de60c52b4 | ||
|
|
55243b65a2 | ||
|
|
0247b3b9b3 | ||
|
|
6dae628e0d | ||
|
|
7827b27d63 | ||
|
|
86ddff46a9 | ||
|
|
476f4e5f1f | ||
|
|
8448b4d5a6 | ||
|
|
28952a0a4a | ||
|
|
19f973fcd3 | ||
|
|
d9fe9b603f | ||
|
|
13a462429e | ||
|
|
bfe788e096 | ||
|
|
980e4b5887 | ||
|
|
0d8cb990c6 | ||
|
|
7794adfb89 | ||
|
|
fb67e8eea7 | ||
|
|
1316a811f5 | ||
|
|
c6f47f9ef3 | ||
|
|
c2a95467f8 | ||
|
|
4d58ff885a | ||
|
|
3892eee7a0 | ||
|
|
15b9e13ed2 | ||
|
|
e504b8af0f | ||
|
|
efc751c54e | ||
|
|
8b4c953ab0 | ||
|
|
32b3c0b5fc | ||
|
|
7c1764a39e | ||
|
|
b248cddece | ||
|
|
df2dc3a710 | ||
|
|
227063341e | ||
|
|
a4ab2e8b06 | ||
|
|
9f3872a5f1 | ||
|
|
e2d727abe5 | ||
|
|
11720d96f1 | ||
|
|
859ebb892d | ||
|
|
035ee8fb8e | ||
|
|
bc69046bdd | ||
|
|
debde3f16e | ||
|
|
3eb9efe1f2 | ||
|
|
7cf9726876 | ||
|
|
64d9f8c39e | ||
|
|
03cea8b24d | ||
|
|
4b4c9b91f3 | ||
|
|
907ee7d88c | ||
|
|
dbdc4cac4a | ||
|
|
19c0b958fc | ||
|
|
e5d2e83de6 | ||
|
|
85596da792 | ||
|
|
230749a3f3 | ||
|
|
b667bc8a23 | ||
|
|
76abf1ed73 | ||
|
|
54930ee07f | ||
|
|
90295ca924 | ||
|
|
e281c536d3 | ||
|
|
efa5b1a71e | ||
|
|
62aaa21ced | ||
|
|
dfbf654159 | ||
|
|
4bc614ffd1 | ||
|
|
1640a6ae00 | ||
|
|
66b677af28 | ||
|
|
655bda4789 | ||
|
|
07e605162a | ||
|
|
ce98c3deba | ||
|
|
71fa8924d7 | ||
|
|
9c78018662 | ||
|
|
72f31d412d | ||
|
|
ef60450dc8 | ||
|
|
f4988c00af | ||
|
|
43c9f574fd | ||
|
|
a15eeeed5b | ||
|
|
14a72a2612 | ||
|
|
68554b3e0a | ||
|
|
91d5107e1d | ||
|
|
8e46b83d3e | ||
|
|
6105681df2 | ||
|
|
05713d16c0 | ||
|
|
1c6bc86794 | ||
|
|
21b4d1ee34 | ||
|
|
0c92bf559a | ||
|
|
5d28710ab3 | ||
|
|
3126688d5e | ||
|
|
e70fe39934 | ||
|
|
0af02941ed | ||
|
|
779876ede9 | ||
|
|
dd8bb763e5 | ||
|
|
5e6c19b39f | ||
|
|
dbb76cce6e | ||
|
|
5cf1de5356 | ||
|
|
bed27e5ffa | ||
|
|
bff4e4d4e2 | ||
|
|
97d202dae0 | ||
|
|
460bbc4569 | ||
|
|
708089622d | ||
|
|
1818a031af | ||
|
|
5cc6154bd2 | ||
|
|
6cd0710f89 | ||
|
|
65858c9ce7 | ||
|
|
6277a12c4a | ||
|
|
16de2e9fca | ||
|
|
39fa0f041f | ||
|
|
ca3a7540f4 | ||
|
|
0bac1d3e0e | ||
|
|
99f221ccbf | ||
|
|
f24952f967 | ||
|
|
566b210d1e | ||
|
|
5fc2e4e8e5 | ||
|
|
65de89c7ee | ||
|
|
1c55ca61e2 | ||
|
|
ed5bd4d42e | ||
|
|
488eec9d1c | ||
|
|
89d45caac9 | ||
|
|
2592f2fc2c | ||
|
|
87547a2130 | ||
|
|
5349f2ad09 | ||
|
|
d34025fd25 | ||
|
|
c53758ddc5 | ||
|
|
90d1207a3c | ||
|
|
9f478f97a2 | ||
|
|
e86bd71819 | ||
|
|
53c1a33106 | ||
|
|
7c06abc99f | ||
|
|
2a5b0ffd1a | ||
|
|
e494007b2a | ||
|
|
c2fb0470fc | ||
|
|
5fb5e639cd | ||
|
|
da3733a3a9 | ||
|
|
bd7ba64b68 | ||
|
|
436e2ea168 | ||
|
|
dcbd550961 | ||
|
|
8811bb4bac | ||
|
|
2d06677887 | ||
|
|
6cfefc91e4 | ||
|
|
8dc7254128 | ||
|
|
18a41cd055 | ||
|
|
a7ad70bbed | ||
|
|
fa0202f5b3 | ||
|
|
88b88187e9 | ||
|
|
ade825df55 | ||
|
|
042c9c645b | ||
|
|
6bf5f4b7d4 | ||
|
|
063f499ee0 | ||
|
|
e4d484e84f | ||
|
|
05c6f87a12 | ||
|
|
8a390057b6 | ||
|
|
82d65e3c68 | ||
|
|
58f029dcbe | ||
|
|
7112c33142 | ||
|
|
08c2923386 | ||
|
|
ed5be40099 | ||
|
|
8c038bac34 | ||
|
|
961b505cfb | ||
|
|
32556029cd | ||
|
|
65013190e3 | ||
|
|
2dd451a7d9 | ||
|
|
73a8ba59ba | ||
|
|
285d1da361 | ||
|
|
4d77b79ce9 | ||
|
|
268033439b | ||
|
|
df3a365eb7 | ||
|
|
61ee81ea3a | ||
|
|
2789b339cb | ||
|
|
c895f05486 | ||
|
|
ed3f50cb1a | ||
|
|
6bb90082b9 | ||
|
|
c870bb653a | ||
|
|
b11484ce6d | ||
|
|
cfb64f8e0d | ||
|
|
d6e0f70510 | ||
|
|
b47a7055a2 | ||
|
|
a101e9e02d | ||
|
|
e547447bb4 | ||
|
|
5d92f813f6 | ||
|
|
ab4e20b0a5 | ||
|
|
ff4b087be8 | ||
|
|
09208ba0fb | ||
|
|
896e9386a9 | ||
|
|
87471d90c4 | ||
|
|
740fc03a04 | ||
|
|
45ef65b251 | ||
|
|
bf705e0a98 | ||
|
|
989864314f | ||
|
|
0a377f9568 | ||
|
|
cb96de6d11 | ||
|
|
7e032e9f84 | ||
|
|
51855c22d4 | ||
|
|
676b059485 | ||
|
|
81d0d28819 | ||
|
|
9123921676 | ||
|
|
544590a860 | ||
|
|
63e7eb881c | ||
|
|
030d697392 | ||
|
|
af56933587 | ||
|
|
ec0bdb3286 | ||
|
|
70055960d0 | ||
|
|
a9ab882b75 | ||
|
|
bce7408f1f | ||
|
|
c8abbb259e | ||
|
|
35cc755bf0 | ||
|
|
5750b58362 | ||
|
|
8a95941297 | ||
|
|
8289150460 | ||
|
|
87df162944 | ||
|
|
e9eda42d7d | ||
|
|
d942d144ca | ||
|
|
d829816f62 | ||
|
|
8b3b23e995 | ||
|
|
52807ed15f | ||
|
|
596f9ac536 | ||
|
|
d58efc7b2d | ||
|
|
73aa66a219 | ||
|
|
93c8903953 | ||
|
|
dc8c455a0b | ||
|
|
d601558bf4 | ||
|
|
d5cee13e25 | ||
|
|
151d7ed22a | ||
|
|
3d29348337 | ||
|
|
62ab5a2f5b | ||
|
|
c2d1c66a59 | ||
|
|
730d0ff41d | ||
|
|
64d164300b | ||
|
|
04eeb78df7 | ||
|
|
6bdfbfb953 | ||
|
|
e6573e26a9 | ||
|
|
5f5cb9b45d | ||
|
|
940e879a1c | ||
|
|
861567d0db | ||
|
|
8e536a4c32 | ||
|
|
e100736349 | ||
|
|
98e4bcccfa | ||
|
|
938b34343d | ||
|
|
e1ecc2d6d4 | ||
|
|
afabf35c66 | ||
|
|
8e0f48bddd | ||
|
|
70dc82e621 | ||
|
|
2928813613 | ||
|
|
a86d07adea | ||
|
|
a282e10069 | ||
|
|
8a70196fa9 | ||
|
|
1d8ae5eea8 | ||
|
|
055bce7d91 | ||
|
|
1ee07eb06f | ||
|
|
6a5eb12051 | ||
|
|
fbf3f1bc7f | ||
|
|
dedfa91669 | ||
|
|
f3480f6939 | ||
|
|
e48166846c | ||
|
|
f7a79a0be3 | ||
|
|
f0f1fd1715 | ||
|
|
2e4c45b207 | ||
|
|
72a3f0a9da | ||
|
|
2d6f784f0a | ||
|
|
614449d540 | ||
|
|
53ff333778 | ||
|
|
4207954982 | ||
|
|
6af64c7095 | ||
|
|
7d03560a3e | ||
|
|
9f9519ef15 | ||
|
|
0838b112de | ||
|
|
d6e4456538 | ||
|
|
022dc0bf2e | ||
|
|
49909df1d2 | ||
|
|
7c7d7a938e | ||
|
|
a67ad48012 | ||
|
|
6c6d7a377f | ||
|
|
d3006026ca | ||
|
|
62cdd56691 | ||
|
|
775e8a8b12 | ||
|
|
f5676705cc | ||
|
|
0bad96418b | ||
|
|
3222025088 | ||
|
|
86f3096c1b | ||
|
|
d7fe4f1729 | ||
|
|
64a2666645 | ||
|
|
3b7f623f9e | ||
|
|
16cdbc16fa | ||
|
|
52510ed03c | ||
|
|
bbec7d4532 | ||
|
|
cf0449c034 | ||
|
|
9e93ba14ae | ||
|
|
bf330311a1 | ||
|
|
481ef5e585 | ||
|
|
a5debf3241 | ||
|
|
d8c106fc5d | ||
|
|
8d2af27896 | ||
|
|
893cdcbc86 | ||
|
|
241c37b35c | ||
|
|
57e1b94115 | ||
|
|
7c670b479e | ||
|
|
a1103f6da9 | ||
|
|
4c5b5f603b | ||
|
|
d77d6d0d9f | ||
|
|
93be967459 | ||
|
|
a62ac1ab82 | ||
|
|
55f51184c2 | ||
|
|
f7ae461337 | ||
|
|
3f57f2b8ec | ||
|
|
2786c9c392 | ||
|
|
332b4d6197 | ||
|
|
8fa7a77fab | ||
|
|
a0046fa19f | ||
|
|
692f60c323 | ||
|
|
9e4fe7a2a3 | ||
|
|
bcee503a77 | ||
|
|
29af04b8f2 | ||
|
|
c00659ba61 | ||
|
|
d7afda4c52 | ||
|
|
d07732119b | ||
|
|
396ba3868f | ||
|
|
4453bbc16c | ||
|
|
b01adbe2e1 | ||
|
|
46f5e7bc0d | ||
|
|
d76e7744e2 | ||
|
|
b6100980fc | ||
|
|
b8a839068e | ||
|
|
d2fd68df74 | ||
|
|
5d03dc3c10 | ||
|
|
1c01f1c7fe | ||
|
|
8135148217 | ||
|
|
067ee26715 | ||
|
|
c8827ab076 | ||
|
|
ba4b9b6cb3 | ||
|
|
44d93b90b3 | ||
|
|
7bb6592be4 | ||
|
|
8f2b8791cc | ||
|
|
b56ffbdb8d | ||
|
|
b4e05b3183 | ||
|
|
c2c8d1b1ea | ||
|
|
857d038316 | ||
|
|
b16d568b7a | ||
|
|
1471ab0c7c | ||
|
|
ee74a640b4 | ||
|
|
44bfc28a44 | ||
|
|
de0c535976 | ||
|
|
3fdc97b690 | ||
|
|
ec042d1089 | ||
|
|
a459015ca9 | ||
|
|
4944ea902f | ||
|
|
4c93609bfe | ||
|
|
c2144947c9 | ||
|
|
0d481ffb18 | ||
|
|
b4c22f623d | ||
|
|
e84e34efa5 | ||
|
|
878e8ceea7 | ||
|
|
876c28d392 | ||
|
|
6a08b82d86 | ||
|
|
9dda9be6f0 | ||
|
|
98ddd115fd | ||
|
|
39cb465941 | ||
|
|
f28181b07c | ||
|
|
31bbf0bdff | ||
|
|
a509a7c6b7 | ||
|
|
02b732b9da | ||
|
|
89e4f051fc | ||
|
|
d36d64380d | ||
|
|
1dc2d2b6fa | ||
|
|
348dfab021 | ||
|
|
fbc5e3e071 | ||
|
|
f7feaaa4f9 | ||
|
|
a96865198d | ||
|
|
114df4e18e | ||
|
|
3676ce9764 | ||
|
|
3512a2f768 | ||
|
|
d68c8c7ee0 | ||
|
|
0c2c948712 | ||
|
|
c9d053e70d | ||
|
|
c3905bc10d | ||
|
|
ba30ca08d9 | ||
|
|
4dfd4829ad | ||
|
|
e0fccacc2f | ||
|
|
3937eadbce | ||
|
|
043387a913 | ||
|
|
88f2e3b7eb | ||
|
|
ea6410e711 | ||
|
|
e1ce9eca7b | ||
|
|
b0cfd9e7f9 | ||
|
|
4f44af6763 | ||
|
|
384bb37dd4 | ||
|
|
a4410a3c82 | ||
|
|
e900f61ed6 | ||
|
|
a65f6cd42d | ||
|
|
aee55234ea | ||
|
|
5ddb78fdf6 | ||
|
|
f8cb07596b | ||
|
|
6c32155327 | ||
|
|
c6d8ccf85a | ||
|
|
659e636657 | ||
|
|
d15776e44a | ||
|
|
e9ba0bd494 | ||
|
|
f1e3e6968a | ||
|
|
354284f6ca | ||
|
|
f53b78bef1 | ||
|
|
769dc19baa | ||
|
|
9d3cffd211 | ||
|
|
c1c3b56441 | ||
|
|
e0748796eb | ||
|
|
4ac481e311 | ||
|
|
05847ca1fc | ||
|
|
dd7538b82b | ||
|
|
b665bb3e6e | ||
|
|
a324da30bc | ||
|
|
5911d266f9 | ||
|
|
2090898ce2 | ||
|
|
5d66e6de5f |
@@ -233,7 +233,7 @@ module.exports = {
|
||||
'@intlify/vue-i18n/no-duplicate-keys-in-locale': 'error',
|
||||
'@intlify/vue-i18n/no-missing-keys-in-other-locales': [
|
||||
'error',
|
||||
{ ignoreLocales: ['de', 'fa', 'cs', 'es', 'sv', 'it', 'ru', 'uk', 'nl'] },
|
||||
{ ignoreLocales: ['de', 'fa', 'cs', 'es', 'sv', 'it', 'ru', 'uk', 'nl', 'pt-BR', 'da', 'ko', 'nb-NO', 'ja'] },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -73,20 +73,20 @@ exports.asyncEach = function asyncEach(iterable, iteratee, { concurrency = 10, s
|
||||
}
|
||||
nextIsRunning = true
|
||||
if (running < concurrency) {
|
||||
const cursor = await it.next()
|
||||
if (cursor.done) {
|
||||
next = () => {
|
||||
if (running === 0) {
|
||||
if (errors.length === 0) {
|
||||
resolve()
|
||||
} else {
|
||||
reject(new AggregateError(errors))
|
||||
try {
|
||||
const cursor = await it.next()
|
||||
if (cursor.done) {
|
||||
next = () => {
|
||||
if (running === 0) {
|
||||
if (errors.length === 0) {
|
||||
resolve()
|
||||
} else {
|
||||
reject(new AggregateError(errors))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
++running
|
||||
try {
|
||||
} else {
|
||||
++running
|
||||
const result = iteratee.call(this, cursor.value, index++, iterable)
|
||||
let then
|
||||
if (result != null && typeof result === 'object' && typeof (then = result.then) === 'function') {
|
||||
@@ -94,9 +94,9 @@ exports.asyncEach = function asyncEach(iterable, iteratee, { concurrency = 10, s
|
||||
} else {
|
||||
onFulfilled(result)
|
||||
}
|
||||
} catch (error) {
|
||||
onRejected(error)
|
||||
}
|
||||
} catch (error) {
|
||||
onRejected(error)
|
||||
}
|
||||
nextIsRunning = false
|
||||
return next()
|
||||
|
||||
@@ -114,6 +114,20 @@ describe('asyncEach', () => {
|
||||
|
||||
tracker.verify()
|
||||
})
|
||||
|
||||
it('handle error on iterable', async () => {
|
||||
const iteratee = spy(async () => {})
|
||||
const iterable = async function* () {
|
||||
for (const value of [1, 2, 3]) {
|
||||
if (value === 2) {
|
||||
throw new Error('iterator error')
|
||||
}
|
||||
await randomDelay()
|
||||
yield value
|
||||
}
|
||||
}
|
||||
await assert.rejects(() => asyncEach(iterable(), iteratee, { concurrency: 1 }), { message: 'iterator error' })
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"engines": {
|
||||
"node": ">=8.10"
|
||||
},
|
||||
|
||||
@@ -62,7 +62,7 @@ exports.parseFlags = function (flags) {
|
||||
case 'ax': info = {read:false, write:true, create:true, append:true, exclusive:true}; break;
|
||||
case 'a+': info = {read:true, write:true, create:true, append:true}; break;
|
||||
case 'ax+': info = {read:true, write:true, create:true, append:true, exclusive:true}; break;
|
||||
default: throw Error("Uknown mode: "+flags); // TODO: throw as `S.err.INVAL`
|
||||
default: throw Error("Unknown mode: "+flags); // TODO: throw as `S.err.INVAL`
|
||||
}
|
||||
if (info.sync) throw Error("Mode not implemented."); // TODO: what would this require of us?
|
||||
if (_dir) info._openDir = true;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@vates/fatfs",
|
||||
"version": "0.11.0",
|
||||
"version": "0.11.1",
|
||||
"description": "fs implementation on top of raw FAT16/FAT32 block source",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -90,7 +90,7 @@ function startTests(vol, waitTime) {
|
||||
assert(path === file, "Fixed fluffy path matches normal one.");
|
||||
});
|
||||
fs.realpath([BASE_DIR,"non","existent","path"].join('/'), function (e) {
|
||||
assert(e, "Expected error calling fs.realpath on non-existent file.");
|
||||
assert(e, "Expected error calling fs.realpath on nonexistent file.");
|
||||
});
|
||||
|
||||
fs.readdir(BASE_DIR, function (e, arr) {
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"dependencies": {
|
||||
"@xen-orchestra/fs": "^4.6.2",
|
||||
"@xen-orchestra/fs": "^4.6.5",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"fuse-native": "^2.2.6",
|
||||
"lru-cache": "^7.14.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.14.0"
|
||||
"vhd-lib": "^4.14.6"
|
||||
},
|
||||
"bin": {
|
||||
"xo-fuse-vhd": "./cli.mjs"
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "@vates/generator-toolbox",
|
||||
"version": "1.0.4",
|
||||
"version": "1.1.0",
|
||||
"main": "dist/index.mjs",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"rimraf": "^5.0.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"@types/node": "^20.6",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.23.0"
|
||||
|
||||
@@ -19,7 +19,7 @@ export class Throttle {
|
||||
} else {
|
||||
speed = this.#bytesPerSecond
|
||||
}
|
||||
assert.ok(speed > 0, `speed must be greater than zero, ${speed} computed`)
|
||||
assert.ok(speed >= 0, `speed must be positive, ${speed} computed`)
|
||||
return speed
|
||||
}
|
||||
constructor(speed: number | (() => number)) {
|
||||
@@ -29,7 +29,9 @@ export class Throttle {
|
||||
getNextSlot(length: number): { timeout?: ReturnType<typeof setTimeout>; promise?: Promise<unknown> } {
|
||||
assert.notStrictEqual(length, undefined, `throttled stream need to expose a length property }`)
|
||||
assert.ok(length > 0, `throttled stream must expose a positive length property , ${length} given }`)
|
||||
|
||||
if (this.speed === 0) {
|
||||
return {}
|
||||
}
|
||||
const previous = this.#previousSlot
|
||||
const nextSlot = Math.round(previous + (length * 1000) / this.speed)
|
||||
if (nextSlot < Date.now()) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "es2023",
|
||||
"module": "ESNext",
|
||||
"types": ["node"], // Only use types from Node.js and packages that are explicitly imported
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"declaration": true, // Generates `.d.ts` files for type safety
|
||||
|
||||
132
@vates/nbd-client/NbdDisk.mjs
Normal file
132
@vates/nbd-client/NbdDisk.mjs
Normal file
@@ -0,0 +1,132 @@
|
||||
import { RandomAccessDisk } from '@xen-orchestra/disk-transform'
|
||||
import NbdClient from '@vates/nbd-client'
|
||||
|
||||
/**
|
||||
* @typedef {{ offset: number, length: number }} DataRange
|
||||
*/
|
||||
|
||||
/**
|
||||
* @extends {RandomAccessDisk}
|
||||
*/
|
||||
export class NbdDisk extends RandomAccessDisk {
|
||||
#nbdInfos
|
||||
/** @type {NbdClient|undefined} */
|
||||
#nbdClient
|
||||
|
||||
/** @type {Array<DataRange> | undefined} */
|
||||
#dataMap
|
||||
|
||||
/** @type {number} */
|
||||
#blockSize
|
||||
|
||||
constructor(nbdInfos, blockSize, { dataMap } = {}) {
|
||||
super()
|
||||
this.#blockSize = blockSize
|
||||
this.#nbdInfos = nbdInfos
|
||||
this.#dataMap = dataMap && this.#processDatamap(dataMap)
|
||||
}
|
||||
|
||||
#processDatamap(rawDataMap) {
|
||||
return rawDataMap
|
||||
.filter(({ type }) => type === 0)
|
||||
.map(({ offset, length }) => ({ offset, length }))
|
||||
.sort(({ offset: offset1 }, { offset: offset2 }) => offset1 - offset2)
|
||||
}
|
||||
/**
|
||||
* @param {number} index
|
||||
* @returns {Promise<DiskBlock>}
|
||||
*/
|
||||
async readBlock(index) {
|
||||
if (!this.#nbdClient) {
|
||||
throw new Error("can't readBlock before init")
|
||||
}
|
||||
let data = await this.#nbdClient.readBlock(index, this.getBlockSize())
|
||||
if (data.length !== this.getBlockSize()) {
|
||||
// this condition only work on non aligned disks
|
||||
// we won't accept truncated block from unaligned disks
|
||||
if (index === Math.ceil(this.getVirtualSize() / this.getBlockSize()) - 1) {
|
||||
// last block add zeros at the end
|
||||
data = Buffer.concat([data], this.getBlockSize())
|
||||
} else {
|
||||
throw new Error(`Block ${index} is not at the right size, expecting ${this.getBlockSize()}, got ${data.length}`)
|
||||
}
|
||||
}
|
||||
return {
|
||||
index,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {number}
|
||||
*/
|
||||
getVirtualSize() {
|
||||
if (!this.#nbdClient) {
|
||||
throw new Error("can't get size before init")
|
||||
}
|
||||
return Number(this.#nbdClient.exportSize)
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {number}
|
||||
*/
|
||||
getBlockSize() {
|
||||
return this.#blockSize
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async init() {
|
||||
this.#nbdClient = new NbdClient(this.#nbdInfos)
|
||||
await this.#nbdClient.connect()
|
||||
if (this.#dataMap === undefined) {
|
||||
this.#dataMap = this.#processDatamap(await this.#nbdClient.getMap())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close() {
|
||||
await this.#nbdClient?.disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isDifferencing() {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array<number>}
|
||||
*/
|
||||
getBlockIndexes() {
|
||||
const indexes = new Set()
|
||||
this.#dataMap?.forEach(({ offset, length }) => {
|
||||
if (length === 0) return
|
||||
|
||||
const firstBlockIndex = Math.floor(offset / this.getBlockSize())
|
||||
const lastBlockIndex = Math.floor((offset + length - 1) / this.getBlockSize())
|
||||
|
||||
for (let blockIndex = firstBlockIndex; blockIndex <= lastBlockIndex; blockIndex++) {
|
||||
indexes.add(blockIndex)
|
||||
}
|
||||
})
|
||||
return [...indexes].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} index
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasBlock(index) {
|
||||
if (!this.#dataMap) {
|
||||
throw new Error("can't hasBlock before init")
|
||||
}
|
||||
const blockStart = index * this.getBlockSize()
|
||||
const blockEnd = (index + 1) * this.getBlockSize()
|
||||
return this.#dataMap.some(({ offset, length }) => offset + length > blockStart && blockEnd >= offset)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
OPTS_MAGIC,
|
||||
NBD_CMD_DISC,
|
||||
} from './constants.mjs'
|
||||
import { spawn } from 'node:child_process'
|
||||
|
||||
const { warn } = createLogger('vates:nbd-client')
|
||||
|
||||
@@ -358,4 +359,40 @@ export default class NbdClient {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the map of the file with holes, zeros and data, useful to handle efficiently sparse source
|
||||
* to implement this internally: use structure response if the server supports it, and then ask for BLOCK_STATUS *
|
||||
*
|
||||
* @returns {Promise<{ offset: number, length: number, type: number }[]>}
|
||||
* A promise that resolves to an array where each object represents a segment:
|
||||
* - `offset` — The byte offset from the start.
|
||||
* - `length` — The size of the segment in bytes.
|
||||
* - `type` — A numeric code indicating the segment type ( 0 means data).
|
||||
*/
|
||||
/* async */ getMap() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const process = spawn('nbdinfo', [
|
||||
'--json',
|
||||
'--map',
|
||||
`nbd://${this.#serverAddress}:${this.#serverPort}/${encodeURIComponent(this.#exportName)}`,
|
||||
])
|
||||
let text = ''
|
||||
let errText = ''
|
||||
process.stdout.on('data', data => (text += data))
|
||||
process.stderr.on('data', data => (errText += data))
|
||||
process.on('error', reject)
|
||||
process.on('close', code => {
|
||||
if (code !== 0) {
|
||||
return reject(new Error(`Error during getMap (code: ${code}): ${errText}`))
|
||||
}
|
||||
try {
|
||||
const json = JSON.parse(text)
|
||||
resolve(json)
|
||||
} catch (error) {
|
||||
reject(new Error(`${error} ${text}`))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,4 +129,17 @@ export default class MultiNbdClient {
|
||||
yield readAhead.shift()
|
||||
}
|
||||
}
|
||||
/**
|
||||
* returns the map of the file with holes, zeros and data, useful to handle efficiently sparse source *
|
||||
*
|
||||
* @returns {Promise<{ offset: number, length: number, type: number }[]>}
|
||||
* A promise that resolves to an array where each object represents a segment:
|
||||
* - `offset` — The byte offset from the start.
|
||||
* - `length` — The size of the segment in bytes.
|
||||
* - `type` — A numeric code indicating the segment type (0 means no data).
|
||||
*/
|
||||
async getMap() {
|
||||
// ask the map from one of the connected client
|
||||
return this.#clients[Math.floor(this.#clients.length * Math.random())].getMap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,18 +13,19 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "3.1.4",
|
||||
"version": "3.2.2",
|
||||
"engines": {
|
||||
"node": ">=14.0"
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.0",
|
||||
"@vates/read-chunk": "^1.2.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/async-map": "^0.1.2",
|
||||
"@xen-orchestra/disk-transform": "^1.2.1",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"xen-api": "^4.7.3"
|
||||
"xen-api": "^4.7.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tap": "^18.7.0",
|
||||
|
||||
@@ -71,13 +71,17 @@ exports.readChunk = readChunk
|
||||
* If `size` bytes are not available to be read, the returned promise is rejected.
|
||||
*
|
||||
* @param {Readable} stream - A readable stream to read from.
|
||||
* @param {number} [size] - The number of bytes to read for binary streams (ignored for object streams).
|
||||
* @param {number?} [size] - The number of bytes to read for binary streams (ignored for object streams).
|
||||
* @returns {Promise<Buffer|string|unknown>} - A Promise that resolves to the read chunk.
|
||||
*/
|
||||
exports.readChunkStrict = async function readChunkStrict(stream, size) {
|
||||
const chunk = await readChunk(stream, size)
|
||||
if (chunk === null) {
|
||||
throw new Error('stream has ended without data')
|
||||
if (size === undefined) {
|
||||
throw new Error(`stream has ended without data`)
|
||||
} else {
|
||||
throw new Error(`stream has ended without data, was looking for ${size} bytes`)
|
||||
}
|
||||
}
|
||||
|
||||
if (size !== undefined && chunk.length !== size) {
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"engines": {
|
||||
"node": ">=8.10"
|
||||
},
|
||||
|
||||
@@ -2,8 +2,17 @@
|
||||
|
||||
import eslint from '@eslint/js'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
export default tseslint.config(eslint.configs.recommended, tseslint.configs.recommended, {
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
},
|
||||
ignores: ['dist'],
|
||||
rules: {
|
||||
// Allow empty interface for recursive generic typing (E.g. interface XenApiNetworkWrapped)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@vates/types",
|
||||
"private": false,
|
||||
"version": "1.10.0",
|
||||
"version": "1.16.0",
|
||||
"main": "./dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
@@ -21,6 +21,10 @@
|
||||
"./lib/xen-orchestra/*": {
|
||||
"default": "./dist/lib/xen-orchestra-*.mjs",
|
||||
"type": "./dist/lib/xen-orchestra-*.d.mts"
|
||||
},
|
||||
"./lib/complex-matcher": {
|
||||
"default": "./dist/lib/complex-matcher.mjs",
|
||||
"type": "./dist/lib/complex-matcher.d.mts"
|
||||
}
|
||||
},
|
||||
"type": "module",
|
||||
|
||||
@@ -655,6 +655,14 @@ export const BACKUP_TYPE = { backup: 'backup', metadata: 'metadataBackup', mirro
|
||||
|
||||
export type BACKUP_TYPE = (typeof BACKUP_TYPE)[keyof typeof BACKUP_TYPE]
|
||||
|
||||
export const SUPPORTED_VDI_FORMAT = {
|
||||
raw: 'raw',
|
||||
vhd: 'vhd',
|
||||
qcow2: 'qcow2',
|
||||
} as const
|
||||
|
||||
export type SUPPORTED_VDI_FORMAT = (typeof SUPPORTED_VDI_FORMAT)[keyof typeof SUPPORTED_VDI_FORMAT]
|
||||
|
||||
// ----- XAPI Stats
|
||||
|
||||
type XapiStatsResponse<T> = {
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './common.mjs'
|
||||
export * from './xen-api.mjs'
|
||||
export * from './xo.mjs'
|
||||
export * from './lib/xen-orchestra-xapi.mjs'
|
||||
export * from './lib/complex-matcher.mjs'
|
||||
|
||||
5
@vates/types/src/lib/complex-matcher.mts
Normal file
5
@vates/types/src/lib/complex-matcher.mts
Normal file
@@ -0,0 +1,5 @@
|
||||
export type Or<T> = Id<{ __or: T[] }>
|
||||
|
||||
export type Id<T> = { id: T }
|
||||
|
||||
export type IdOr<T> = Id<T> | Or<T>
|
||||
@@ -1,7 +1,21 @@
|
||||
import { Branded } from '../common.mjs'
|
||||
|
||||
export type Task = {
|
||||
id: Branded<'task'>
|
||||
export interface VatesTask {
|
||||
_abortController: AbortController
|
||||
_onProgress(data?: unknown): void
|
||||
|
||||
run: <T>(fn: () => T) => Promise<T>
|
||||
id: Branded<'vates-task'>
|
||||
status: 'failure' | 'pending' | 'success'
|
||||
|
||||
abort(reason?: unknown): void
|
||||
failure(error?: unknown): void
|
||||
info(message: string, data: unknown): void
|
||||
run<T>(fn: () => T | (() => Promise<T>)): Promise<T>
|
||||
runInside<T>(fn: () => T | (() => Promise<T>)): Promise<T>
|
||||
set(name: string, value: unknown): void
|
||||
start(): void
|
||||
success(result?: unknown): void
|
||||
warning(message: string, data: unknown): void
|
||||
wrap<T>(fn: () => T | (() => Promise<T>)): Promise<T>
|
||||
wrapInside<T>(fn: () => T | (() => Promise<T>)): Promise<T>
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
XenApiVm,
|
||||
XenApiVmWrapped,
|
||||
} from '../xen-api.mjs'
|
||||
import type { Readable } from 'node:stream'
|
||||
import type { PassThrough, Readable } from 'node:stream'
|
||||
import type {
|
||||
XoGpuGroup,
|
||||
XoVgpuType,
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
XoVm,
|
||||
XoVmTemplate,
|
||||
} from '../xo.mjs'
|
||||
import type { SUPPORTED_VDI_FORMAT } from '../common.mjs'
|
||||
|
||||
export type XcpPatches = {
|
||||
changelog?: {
|
||||
@@ -78,10 +79,28 @@ export interface Xapi {
|
||||
}
|
||||
): Promise<XenApiNetworkWrapped>
|
||||
deleteNetwork(id: XoNetwork['id']): Promise<void>
|
||||
exportVmOva(vmRef: XenApiVm['$ref']): Promise<PassThrough>
|
||||
listMissingPatches(host: XoHost['id']): Promise<XcpPatches[] | XsPatches[]>
|
||||
pool_emergencyShutdown(): Promise<void>
|
||||
resumeVm(id: XoVm['id']): Promise<void>
|
||||
unpauseVm(id: XoVm['id']): Promise<void>
|
||||
SR_importVdi(
|
||||
ref: XenApiSr['$ref'],
|
||||
stream: Readable,
|
||||
opts?: {
|
||||
format?: SUPPORTED_VDI_FORMAT
|
||||
name_description?: XoVdi['name_description']
|
||||
name_label?: XoVdi['name_label']
|
||||
other_config?: XoVdi['other_config']
|
||||
read_only?: boolean
|
||||
sharable?: boolean
|
||||
SR?: XenApiSr['$ref']
|
||||
tags?: XoVdi['tags']
|
||||
type?: XoVdi['type']
|
||||
virtual_size?: XoVdi['size']
|
||||
xenstore_data?: Record<string, string>
|
||||
}
|
||||
): Promise<XenApiVdi['$ref']>
|
||||
startVm(
|
||||
id: XoVm['id'],
|
||||
opts?: {
|
||||
@@ -97,6 +116,10 @@ export interface Xapi {
|
||||
startOnly?: boolean
|
||||
}
|
||||
): Promise<void>
|
||||
VM_export(
|
||||
vmRef: XenApiVm['$ref'],
|
||||
opts?: { cancelToken?: unknown; compress?: boolean; useSnapshot?: boolean }
|
||||
): ReturnType<Xapi['getResource']>
|
||||
VM_import(
|
||||
stream: Readable,
|
||||
srRef?: XenApiSr['$ref'],
|
||||
@@ -148,12 +171,23 @@ export interface Xapi {
|
||||
vgpuType?: XoVgpuType['id']
|
||||
gpuGroup?: XoGpuGroup['id']
|
||||
copyHostBiosStrings?: boolean
|
||||
hvmBootFirmware?: 'uefi' | 'bios'
|
||||
},
|
||||
checkLimits?: boolean,
|
||||
creatorId?: XoUser['id'],
|
||||
opts?: { destroyAllVifs: boolean }
|
||||
): Promise<XenApiVmWrapped>
|
||||
VDI_destroy(vdiRef: XenApiVdi['$ref']): Promise<void>
|
||||
VDI_destroyCloudInitConfig(vdiRef: XenApiVdi['$ref'], opts?: { timeLimit?: number }): Promise<void>
|
||||
VDI_exportContent(
|
||||
vdiRef: XenApiVdi['$ref'],
|
||||
opts: { baseRef?: string; cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
|
||||
): Promise<Readable & { length?: number }>
|
||||
VDI_importContent(
|
||||
vdiRef: XenApiVdi['$ref'],
|
||||
stream: Readable,
|
||||
opts: { cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
|
||||
): Promise<void>
|
||||
VM_createCloudInitConfig(
|
||||
vmRef: XenApiVm['$ref'],
|
||||
cloudConfig: string,
|
||||
|
||||
@@ -70,6 +70,11 @@ import type { Xapi } from './lib/xen-orchestra-xapi.mjs'
|
||||
// https://github.com/vatesfr/xen-orchestra/tree/wip-xapi-types-generator/%40xen-orchestra/xapi-generator
|
||||
// All properties added after XenServer 7.0 (dundee) release have been marked as optional
|
||||
|
||||
type TagCallMethods = {
|
||||
(method: 'add_tags', tag: string): Promise<void>
|
||||
(method: 'remove_tags', tag: string): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Add properties injected by `xen-api`.
|
||||
* $ref property is also injected by XOLite, so she is not present here.
|
||||
@@ -162,6 +167,8 @@ export interface XenApiEvent {
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
type XenApiPoolCallMethods = TagCallMethods & {}
|
||||
|
||||
export interface XenApiPool {
|
||||
$ref: Branded<'pool'>
|
||||
allowed_operations: POOL_ALLOWED_OPERATIONS[]
|
||||
@@ -224,7 +231,7 @@ export interface XenApiPool {
|
||||
/** @deprecated */
|
||||
wlb_verify_cert?: boolean
|
||||
}
|
||||
export type XenApiPoolWrapped = WrapperXenApi<XenApiPool, 'pool'>
|
||||
export type XenApiPoolWrapped = WrapperXenApi<XenApiPool, 'pool', XenApiPoolCallMethods>
|
||||
|
||||
/** @deprecated */
|
||||
export interface XenApiPoolPatch {
|
||||
@@ -256,7 +263,7 @@ export interface XenApiPoolUpdate {
|
||||
version?: string
|
||||
}
|
||||
|
||||
type XenApiVmCallMethods = {
|
||||
type XenApiVmCallMethods = TagCallMethods & {
|
||||
(method: 'start', start_paused: boolean, force: boolean): Promise<void>
|
||||
(method: 'clean_shutdown'): Promise<void>
|
||||
(method: 'hard_shutdown'): Promise<void>
|
||||
@@ -483,6 +490,7 @@ export interface XenApiDrTask {
|
||||
uuid: string
|
||||
}
|
||||
|
||||
type XenApiHostCallMethods = TagCallMethods & {}
|
||||
export interface XenApiHost {
|
||||
$ref: Branded<'host'>
|
||||
address: string
|
||||
@@ -559,7 +567,7 @@ export interface XenApiHost {
|
||||
uuid: string
|
||||
virtual_hardware_platform_versions: number[]
|
||||
}
|
||||
export type XenApiHostWrapped = WrapperXenApi<XenApiHost, 'host'>
|
||||
export type XenApiHostWrapped = WrapperXenApi<XenApiHost, 'host', XenApiHostCallMethods>
|
||||
|
||||
export interface XenApiHostCrashdump {
|
||||
$ref: Branded<'host_crashdump'>
|
||||
@@ -614,6 +622,8 @@ export interface XenApiHostCpu {
|
||||
vendor: string
|
||||
}
|
||||
|
||||
type XenApiNetworkCallMethods = TagCallMethods & {}
|
||||
|
||||
export interface XenApiNetwork {
|
||||
$ref: Branded<'network'>
|
||||
allowed_operations: NETWORK_OPERATIONS[]
|
||||
@@ -633,8 +643,7 @@ export interface XenApiNetwork {
|
||||
uuid: string
|
||||
VIFs: XenApiVif['$ref'][]
|
||||
}
|
||||
export interface XenApiNetworkWrapped extends WrapperXenApi<XenApiNetwork, 'network'> {}
|
||||
|
||||
export interface XenApiNetworkWrapped extends WrapperXenApi<XenApiNetwork, 'network', XenApiNetworkCallMethods> {}
|
||||
export interface XenApiVif {
|
||||
$ref: Branded<'VIF'>
|
||||
allowed_operations: VIF_OPERATIONS[]
|
||||
@@ -782,6 +791,7 @@ export interface XenApiSm {
|
||||
}
|
||||
export type XenApiSmWrapped = WrapperXenApi<XenApiSm, 'SM'>
|
||||
|
||||
type XenApiSrCallMethods = TagCallMethods & {}
|
||||
export interface XenApiSr {
|
||||
$ref: Branded<'SR'>
|
||||
allowed_operations: STORAGE_OPERATIONS[]
|
||||
@@ -806,7 +816,7 @@ export interface XenApiSr {
|
||||
VDIs: XenApiVdi['$ref'][]
|
||||
virtual_allocation: number
|
||||
}
|
||||
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR'>
|
||||
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR', XenApiSrCallMethods>
|
||||
|
||||
export interface XenApiSrStat {
|
||||
$ref: Branded<'sr_stat'>
|
||||
@@ -832,6 +842,8 @@ export interface XenApiLvhd {
|
||||
uuid: string
|
||||
}
|
||||
|
||||
type XenApiVdiCallMethods = TagCallMethods & {}
|
||||
|
||||
export interface XenApiVdi {
|
||||
$ref: Branded<'VDI'>
|
||||
allow_caching: boolean
|
||||
@@ -868,7 +880,7 @@ export interface XenApiVdi {
|
||||
virtual_size: number
|
||||
xenstore_data: Record<string, string>
|
||||
}
|
||||
export type XenApiVdiWrapped = WrapperXenApi<XenApiVdi, 'VDI'>
|
||||
export type XenApiVdiWrapped = WrapperXenApi<XenApiVdi, 'VDI', XenApiVdiCallMethods>
|
||||
|
||||
export interface XenApiVbd {
|
||||
$ref: Branded<'VBD'>
|
||||
@@ -921,6 +933,7 @@ export interface XenApiPbd {
|
||||
SR: XenApiSr['$ref']
|
||||
uuid: string
|
||||
}
|
||||
export type XenApiPbdWrapped = WrapperXenApi<XenApiPbd, 'PBD'>
|
||||
|
||||
/** @deprecated */
|
||||
export interface XenApiCrashdump {
|
||||
@@ -1357,6 +1370,7 @@ export type XenApiRecord =
|
||||
export type WrappedXenApiRecord =
|
||||
| XenApiHostWrapped
|
||||
| XenApiNetworkWrapped
|
||||
| XenApiPbdWrapped
|
||||
| XenApiPifWrapped
|
||||
| XenApiPoolWrapped
|
||||
| XenApiSrWrapped
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Types based on xapi-object-to-xo
|
||||
|
||||
import type {
|
||||
BACKUP_TYPE,
|
||||
Branded,
|
||||
DOMAIN_TYPE,
|
||||
HOST_ALLOWED_OPERATIONS,
|
||||
@@ -19,6 +18,8 @@ import type {
|
||||
VM_OPERATIONS,
|
||||
VM_POWER_STATE,
|
||||
} from './common.mjs'
|
||||
import type * as CMType from './lib/complex-matcher.mjs'
|
||||
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
|
||||
|
||||
type BaseXapiXo = {
|
||||
$pool: XoPool['id']
|
||||
@@ -133,6 +134,67 @@ export type XoAlarm = Omit<XoMessage, '$object' | 'body'> & {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: to be typed when Bastien.N has finished working on the XO task
|
||||
type BaseXoLog = {
|
||||
id: Branded<'xo-log'>
|
||||
infos?: { data: unknown; message: string }[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
export type XoBackupLog = BaseXoLog & {
|
||||
status: 'success' | 'skipped' | 'interrupted' | 'failure' | 'pending'
|
||||
message: 'backup'
|
||||
start: number
|
||||
end?: number
|
||||
tasks?: XoTask[]
|
||||
jobId?: AnyXoBackupJob['id']
|
||||
}
|
||||
export type XoRestoreLog = BaseXoLog & {
|
||||
message: 'restore'
|
||||
}
|
||||
export type XoVmBackupArchive = {
|
||||
id: Branded<'vm-backup-archive'>
|
||||
type: 'xo-vm-backup'
|
||||
backupRepository: XoBackupRepository['id']
|
||||
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
|
||||
isImmutable?: boolean
|
||||
jobId: XoVmBackupJob['id']
|
||||
mode: XoVmBackupJob['mode']
|
||||
scheduleId: XoSchedule['id']
|
||||
size: number
|
||||
timestamp: number
|
||||
vm: {
|
||||
uuid: XoVm['uuid']
|
||||
name_description: string
|
||||
name_label: string
|
||||
tags: XoVm['tags']
|
||||
}
|
||||
differencingVhds?: number
|
||||
dynamicVhds?: number
|
||||
withMemory: boolean
|
||||
}
|
||||
|
||||
type XoMetadataBackupArchive = {
|
||||
id: Branded<'metadata-backup-archive'>
|
||||
backupRepository: XoBackupRepository['id']
|
||||
jobId: XoVmBackupJob['id']
|
||||
jobName: XoVmBackupJob['name']
|
||||
scheduleId: XoSchedule['id']
|
||||
scheduleName: XoSchedule['name']
|
||||
timestamp: number
|
||||
}
|
||||
export type XoConfigBackupArchive = XoMetadataBackupArchive & {
|
||||
id: Branded<'config-backup-archive'>
|
||||
data: string
|
||||
type: 'xo-config-backup'
|
||||
}
|
||||
|
||||
export type XoPoolBackupArchive = XoMetadataBackupArchive & {
|
||||
id: Branded<'pool-backup-archive'>
|
||||
pool: XenApiPool
|
||||
poolMaster: XenApiHost
|
||||
type: 'xo-pool-metadata-backup'
|
||||
}
|
||||
|
||||
export type XoBackupRepository = {
|
||||
benchmarks?: { readRate: number; timestamp: number; writeRate: number }[]
|
||||
enabled: boolean
|
||||
@@ -173,7 +235,7 @@ export type XoHost = BaseXapiXo & {
|
||||
|
||||
address: string
|
||||
agentStartTime: null | number
|
||||
bios_string: Record<string, string>
|
||||
bios_strings: Record<string, string>
|
||||
build: string
|
||||
certificates?: {
|
||||
fingerprint: string
|
||||
@@ -182,7 +244,7 @@ export type XoHost = BaseXapiXo & {
|
||||
chipset_info: {
|
||||
iommu?: boolean
|
||||
}
|
||||
controlDomain?: XoVm['id']
|
||||
controlDomain?: XoVmController['id']
|
||||
cpus: {
|
||||
cores?: number
|
||||
sockets?: number
|
||||
@@ -277,7 +339,19 @@ export type XoNetwork = BaseXapiXo & {
|
||||
}
|
||||
|
||||
export type XoPbd = BaseXapiXo & {
|
||||
attached: boolean
|
||||
device_config:
|
||||
| { device: string }
|
||||
| { location: string }
|
||||
| { path: string; location: string; legacy_mode: string }
|
||||
| { provisioning: string; redundancy: string; 'group-name': string }
|
||||
| { server: string; serverpath: string }
|
||||
| { type: string; location: string }
|
||||
| Record<string, string>
|
||||
host: XoHost['id']
|
||||
id: Branded<'PBD'>
|
||||
otherConfig: Record<string, string>
|
||||
SR: XoSr['id']
|
||||
type: 'PBD'
|
||||
}
|
||||
|
||||
@@ -318,7 +392,7 @@ export type XoPif = BaseXapiXo & {
|
||||
|
||||
attached: boolean
|
||||
bondMaster?: XoPif['id']
|
||||
bondSalves?: XoPif['id'][]
|
||||
bondSlaves?: XoPif['id'][]
|
||||
carrier: boolean
|
||||
device: string
|
||||
deviceName?: string
|
||||
@@ -351,7 +425,7 @@ export type XoPool = BaseXapiXo & {
|
||||
}
|
||||
crashDumpSr?: XoSr['id']
|
||||
current_operations: Record<string, POOL_ALLOWED_OPERATIONS>
|
||||
defaultSr?: XoSr['id']
|
||||
default_SR?: XoSr['id']
|
||||
HA_enabled: boolean
|
||||
haSrs: XoSr['id'][]
|
||||
id: Branded<'pool'>
|
||||
@@ -365,69 +439,132 @@ export type XoPool = BaseXapiXo & {
|
||||
tags: string[]
|
||||
type: 'pool'
|
||||
vtpmSupported: boolean
|
||||
xosanPackInstallationTime: number | null
|
||||
zstdSupported: boolean
|
||||
}
|
||||
|
||||
export type XoProxy = {
|
||||
id: Branded<'proxy'>
|
||||
}
|
||||
url: string
|
||||
version?: string
|
||||
name: string
|
||||
} & (
|
||||
| { address?: undefined; vmUuid: XoVm['id'] }
|
||||
| { address: string; vmUuid?: undefined }
|
||||
| { address: string; vmUuid: XoVm['id'] }
|
||||
)
|
||||
|
||||
type BaseXoJob = {
|
||||
id: Branded<'job'>
|
||||
name?: string
|
||||
}
|
||||
// @TODO: create type for complex matcher
|
||||
export type XoBackupJob = BaseXoJob & {
|
||||
|
||||
type XoBackupJobGeneralSettings = {
|
||||
backupReportTpl?: 'compactMjml' | 'mjml'
|
||||
reportWhen?: 'always' | 'error' | 'failure' | 'never'
|
||||
reportRecipients?: string[]
|
||||
hideSuccessfulItems?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
cbtDestroySnapshotData?: boolean
|
||||
concurrency?: number
|
||||
longTermRetention?: {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
checkpointSnapshot?: boolean
|
||||
offlineSnapshot?: boolean
|
||||
maxExportRate?: number
|
||||
nbdConcurrency?: number
|
||||
nRetriesVmBackupFailures?: number
|
||||
preferNbd?: boolean
|
||||
timezone?: string
|
||||
mergeBackupsSynchronously?: boolean
|
||||
offlineBackup?: boolean
|
||||
timeout?: number
|
||||
}
|
||||
export type XoVmBackupJobScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
fullInterval?: number
|
||||
copyRetention?: number
|
||||
snapshotRetention?: number
|
||||
cbtDestroySnapshotData?: boolean
|
||||
healthCheckSr?: XoSr['id']
|
||||
[key: string]: unknown
|
||||
}
|
||||
export type XoVmBackupJob = BaseXoJob & {
|
||||
compression?: 'native' | 'zstd' | ''
|
||||
proxy?: XoProxy['id']
|
||||
mode: 'full' | 'delta'
|
||||
name?: string
|
||||
remotes?: {
|
||||
id: XoBackupRepository['id'] | { __or: XoBackupRepository['id'][] }
|
||||
}
|
||||
vms?: {
|
||||
id: XoVm['id'] | { __or: XoVm['id'][] } | Record<string, unknown>
|
||||
}
|
||||
srs: {
|
||||
id: XoSr['id'] | { __or: XoSr['id'][] }
|
||||
}
|
||||
type: BACKUP_TYPE
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']>
|
||||
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
|
||||
srs?: CMType.IdOr<XoSr['id']>
|
||||
type: 'backup'
|
||||
settings: {
|
||||
'': {
|
||||
cbtDestroySnapshotData?: boolean
|
||||
concurrency?: number
|
||||
longTermRetention?: {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
maxExportRate?: number
|
||||
nbdConcurrency?: number
|
||||
nRetriesVmBackupFailures?: number
|
||||
preferNbd?: boolean
|
||||
timezone?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
[key: XoSchedule['id']]: {
|
||||
exportRetention?: number
|
||||
healthCheckSr?: XoSr['id']
|
||||
healthCheckVmsWithTags?: string[]
|
||||
fullInterval?: number
|
||||
copyRetention?: number
|
||||
snapshotRetention?: number
|
||||
cbtDestroySnapshotData?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
'': XoVmBackupJobGeneralSettings
|
||||
[key: XoSchedule['id']]: XoVmBackupJobScheduleSettings | undefined
|
||||
}
|
||||
}
|
||||
export type XoJob = BaseXoJob & {}
|
||||
|
||||
export type XoMetadataBackupJobGeneralSettings = XoBackupJobGeneralSettings
|
||||
export type XoMetadataBackupJobScheduleSettings = {
|
||||
retentionPoolMetadata?: number
|
||||
retentionXoMetadata?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
export type XoMetadataBackupJob = BaseXoJob & {
|
||||
type: 'metadataBackup'
|
||||
pools?: CMType.IdOr<XoPool['id']>
|
||||
remotes: CMType.IdOr<XoBackupRepository['id']>
|
||||
settings: {
|
||||
''?: XoMetadataBackupJobGeneralSettings
|
||||
[scheduleId: XoSchedule['id']]: XoMetadataBackupJobScheduleSettings | undefined
|
||||
}
|
||||
xoMetadata?: boolean
|
||||
userId: XoUser['id']
|
||||
proxy?: XoProxy['id']
|
||||
}
|
||||
|
||||
export type XoMirrorBackupGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
concurrency?: number
|
||||
nRetriesVmBackupFailures?: number
|
||||
mergeBackupsSynchronously?: boolean
|
||||
timeout?: number
|
||||
maxExportRate?: number
|
||||
backupReportTpl?: 'compactMjml'
|
||||
reportWhen: 'failure'
|
||||
}
|
||||
export type XoMirrorBackupScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
healthCheckSr?: XoSr['id']
|
||||
[key: string]: unknown
|
||||
}
|
||||
export type XoMirrorBackupJob = BaseXoJob & {
|
||||
type: 'mirrorBackup'
|
||||
mode: 'full' | 'delta'
|
||||
sourceRemote: XoBackupRepository['id']
|
||||
remotes: CMType.IdOr<XoBackupRepository['id']>
|
||||
proxy?: XoProxy['id']
|
||||
settings: {
|
||||
'': XoMirrorBackupGeneralSettings
|
||||
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined
|
||||
}
|
||||
}
|
||||
|
||||
export type XoJob = BaseXoJob & {
|
||||
type: 'call'
|
||||
}
|
||||
|
||||
export type XoSchedule = {
|
||||
cron: string
|
||||
enabled: boolean
|
||||
id: Branded<'schedule'>
|
||||
jobId: (XoJob | XoBackupJob)['id']
|
||||
jobId: AnyXoJob['id']
|
||||
name?: string
|
||||
timezone?: string
|
||||
}
|
||||
@@ -456,7 +593,7 @@ export type XoSr = BaseXapiXo & {
|
||||
|
||||
VDIs: AnyXoVdi['id'][]
|
||||
|
||||
allocationStrategy: 'thin' | 'thick' | 'unknown'
|
||||
allocationStrategy?: 'thin' | 'thick' | 'unknown'
|
||||
content_type: string
|
||||
current_operations: Record<string, STORAGE_OPERATIONS>
|
||||
id: Branded<'SR'>
|
||||
@@ -489,6 +626,31 @@ export type XoSm = BaseXapiXo & {
|
||||
type: 'SM'
|
||||
}
|
||||
|
||||
export type XoTask = {
|
||||
abortionRequestedAt?: number
|
||||
data?: Record<string, string>
|
||||
end?: number
|
||||
id: Branded<'task'>
|
||||
infos?: { data: unknown; message: string }[]
|
||||
progress?: number
|
||||
properties: {
|
||||
method?: string
|
||||
name?: string
|
||||
objectId?: string
|
||||
params?: Record<string, unknown>
|
||||
progress?: number
|
||||
type?: string
|
||||
userId?: string
|
||||
[key: string]: unknown | undefined
|
||||
}
|
||||
result: Record<string, unknown>
|
||||
start: number
|
||||
status: 'failure' | 'interrupted' | 'pending' | 'success'
|
||||
tasks?: XoTask[]
|
||||
updatedAt?: number
|
||||
warnings?: { data: unknown; message: string }[]
|
||||
}
|
||||
|
||||
export type XoUser = {
|
||||
authProviders?: Record<string, string>
|
||||
email: string
|
||||
@@ -500,6 +662,19 @@ export type XoUser = {
|
||||
preferences: Record<string, string>
|
||||
}
|
||||
|
||||
export type XoAuthenticationToken = {
|
||||
client?: {
|
||||
id: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
created_at?: number
|
||||
description?: string
|
||||
user_id: XoUser['id']
|
||||
expiration: number
|
||||
last_uses?: Record<string, { timestamp: number }>
|
||||
id: Branded<'authentication-token'>
|
||||
}
|
||||
|
||||
export type XoVbd = BaseXapiXo & {
|
||||
attached: boolean
|
||||
bootable: boolean
|
||||
@@ -635,6 +810,7 @@ export type XapiXoRecord =
|
||||
| XoHost
|
||||
| XoMessage
|
||||
| XoNetwork
|
||||
| XoPbd
|
||||
| XoPci
|
||||
| XoPgpu
|
||||
| XoPif
|
||||
@@ -654,7 +830,20 @@ export type XapiXoRecord =
|
||||
| XoVtpm
|
||||
| XoSm
|
||||
|
||||
export type NonXapiXoRecord = XoGroup | XoProxy | XoJob | XoBackupRepository | XoSchedule | XoServer | XoUser
|
||||
export type NonXapiXoRecord =
|
||||
| AnyXoBackupArchive
|
||||
| AnyXoJob
|
||||
| AnyXoLog
|
||||
| XoGroup
|
||||
| XoProxy
|
||||
| XoGroup
|
||||
| XoProxy
|
||||
| XoJob
|
||||
| XoBackupRepository
|
||||
| XoSchedule
|
||||
| XoServer
|
||||
| XoTask
|
||||
| XoUser
|
||||
|
||||
export type XoRecord = XapiXoRecord | NonXapiXoRecord
|
||||
|
||||
@@ -662,4 +851,10 @@ export type AnyXoVm = XoVm | XoVmSnapshot | XoVmTemplate | XoVmController
|
||||
|
||||
export type AnyXoVdi = XoVdi | XoVdiSnapshot | XoVdiUnmanaged
|
||||
|
||||
export type AnyXoJob = XoJob | XoBackupJob
|
||||
export type AnyXoJob = XoJob | AnyXoBackupJob
|
||||
|
||||
export type AnyXoBackupJob = XoVmBackupJob | XoMetadataBackupJob | XoMirrorBackupJob
|
||||
|
||||
export type AnyXoLog = XoBackupLog | XoRestoreLog
|
||||
|
||||
export type AnyXoBackupArchive = XoVmBackupArchive | XoConfigBackupArchive | XoPoolBackupArchive
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
"strict": true,
|
||||
"module": "ESNext",
|
||||
"target": "ES2022",
|
||||
"skipLibCheck": true
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"] // Only use types from Node.js and packages that are explicitly imported
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
"preferGlobal": true,
|
||||
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"@xen-orchestra/async-map": "^0.1.2",
|
||||
"@xen-orchestra/backups": "^0.63.0",
|
||||
"@xen-orchestra/fs": "^4.6.2",
|
||||
"@xen-orchestra/backups": "^0.67.2",
|
||||
"@xen-orchestra/fs": "^4.6.5",
|
||||
"filenamify": "^6.0.0",
|
||||
"getopts": "^2.2.5",
|
||||
"lodash": "^4.17.15",
|
||||
@@ -28,7 +28,7 @@
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public"
|
||||
},
|
||||
"version": "1.1.2",
|
||||
"version": "1.1.6",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
|
||||
@@ -11,6 +11,7 @@ import pickBy from 'lodash/pickBy.js'
|
||||
import { defer } from 'golike-defer'
|
||||
import { NegativeDisk } from '@xen-orchestra/disk-transform'
|
||||
import { openDiskChain } from './disks/openDiskChain.mjs'
|
||||
import { resetVmOtherConfig } from './_otherConfig.mjs'
|
||||
|
||||
const { debug, info, warn } = createLogger('xo:backups:importVmBackup')
|
||||
async function resolveUuid(xapi, cache, uuid, type) {
|
||||
@@ -29,10 +30,10 @@ export class ImportVmBackup {
|
||||
metadata,
|
||||
srUuid,
|
||||
xapi,
|
||||
settings: { additionnalVmTag, newMacAddresses, mapVdisSrs = {}, useDifferentialRestore = false } = {},
|
||||
settings: { additionalVmTag, newMacAddresses, mapVdisSrs = {}, useDifferentialRestore = false } = {},
|
||||
}) {
|
||||
this._adapter = adapter
|
||||
this._importIncrementalVmSettings = { additionnalVmTag, newMacAddresses, mapVdisSrs, useDifferentialRestore }
|
||||
this._importIncrementalVmSettings = { additionalVmTag, newMacAddresses, mapVdisSrs, useDifferentialRestore }
|
||||
this._metadata = metadata
|
||||
this._srUuid = srUuid
|
||||
this._xapi = xapi
|
||||
@@ -61,11 +62,11 @@ export class ImportVmBackup {
|
||||
const { mapVdisSrs } = this._importIncrementalVmSettings
|
||||
const { vbds, vhds, vifs, vm, vmSnapshot, vtpms } = metadata
|
||||
const disks = {}
|
||||
const metdataDir = dirname(metadata._filename)
|
||||
const metadataDir = dirname(metadata._filename)
|
||||
const vdis = ignoredVdis === undefined ? metadata.vdis : pickBy(metadata.vdis, vdi => !ignoredVdis.has(vdi.uuid))
|
||||
|
||||
for (const [vdiRef, vdi] of Object.entries(vdis)) {
|
||||
const vhdPath = join(metdataDir, vhds[vdiRef])
|
||||
const vhdPath = join(metadataDir, vhds[vdiRef])
|
||||
|
||||
let xapiDisk
|
||||
try {
|
||||
@@ -77,7 +78,7 @@ export class ImportVmBackup {
|
||||
|
||||
let snapshotCandidate, backupCandidate
|
||||
if (xapiDisk !== undefined) {
|
||||
debug('found disks, wlll search its snapshots', { snapshots: xapiDisk.snapshots })
|
||||
debug('found disks, will search its snapshots', { snapshots: xapiDisk.snapshots })
|
||||
for (const snapshotRef of xapiDisk.snapshots) {
|
||||
const snapshot = await this._xapi.getRecord('VDI', snapshotRef)
|
||||
|
||||
@@ -96,7 +97,7 @@ export class ImportVmBackup {
|
||||
// have a corresponding backup more recent than metadata ?
|
||||
const pathToSnapshotData = await this.#getPathOfVdiSnapshot(snapshot.uuid)
|
||||
if (pathToSnapshotData === undefined) {
|
||||
debug('no backup linked to this snaphot')
|
||||
debug('no backup linked to this snapshot')
|
||||
continue
|
||||
}
|
||||
if (snapshot.$SR.uuid !== (mapVdisSrs[vdi.$snapshot_of$uuid] ?? this._srUuid)) {
|
||||
@@ -112,7 +113,7 @@ export class ImportVmBackup {
|
||||
}
|
||||
|
||||
let disk
|
||||
const backupWithSnapshotPath = join(metdataDir, backupCandidate ?? '')
|
||||
const backupWithSnapshotPath = join(metadataDir, backupCandidate ?? '')
|
||||
if (vhdPath === backupWithSnapshotPath) {
|
||||
// all the data are already on the host
|
||||
debug('direct reuse of a snapshot')
|
||||
@@ -194,7 +195,7 @@ export class ImportVmBackup {
|
||||
}
|
||||
|
||||
async #decorateIncrementalVmMetadata() {
|
||||
const { additionnalVmTag, mapVdisSrs, useDifferentialRestore } = this._importIncrementalVmSettings
|
||||
const { additionalVmTag, mapVdisSrs, useDifferentialRestore } = this._importIncrementalVmSettings
|
||||
|
||||
const ignoredVdis = new Set(
|
||||
Object.entries(mapVdisSrs)
|
||||
@@ -211,8 +212,8 @@ export class ImportVmBackup {
|
||||
|
||||
const cache = new Map()
|
||||
const mapVdisSrRefs = {}
|
||||
if (additionnalVmTag !== undefined) {
|
||||
backup.vm.tags.push(additionnalVmTag)
|
||||
if (additionalVmTag !== undefined) {
|
||||
backup.vm.tags.push(additionalVmTag)
|
||||
}
|
||||
for (const [vdiUuid, srUuid] of Object.entries(mapVdisSrs)) {
|
||||
mapVdisSrRefs[vdiUuid] = await resolveUuid(xapi, cache, srUuid, 'SR')
|
||||
@@ -270,6 +271,7 @@ export class ImportVmBackup {
|
||||
`${metadata.vm.name_label} (${formatFilenameDate(metadata.timestamp)})`
|
||||
),
|
||||
xapi.call('VM.set_name_description', vmRef, desc),
|
||||
resetVmOtherConfig(xapi, vmRef),
|
||||
])
|
||||
|
||||
return {
|
||||
|
||||
@@ -27,7 +27,7 @@ import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
import { getTmpDir } from './_getTmpDir.mjs'
|
||||
import { isMetadataFile } from './_backupType.mjs'
|
||||
import { isValidXva } from './_isValidXva.mjs'
|
||||
import { listPartitions, LVM_PARTITION_TYPE } from './_listPartitions.mjs'
|
||||
import { listPartitions, LVM_PARTITION_TYPE_MBR, LVM_PARTITION_TYPE_GPT } from './_listPartitions.mjs'
|
||||
import { lvs, pvs } from './_lvm.mjs'
|
||||
import { watchStreamSize } from './_watchStreamSize.mjs'
|
||||
|
||||
@@ -40,7 +40,7 @@ export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
|
||||
|
||||
export const DIR_XO_POOL_METADATA_BACKUPS = 'xo-pool-metadata-backups'
|
||||
|
||||
const IMMUTABILTY_METADATA_FILENAME = '/immutability.json'
|
||||
const IMMUTABILITY_METADATA_FILENAME = '/immutability.json'
|
||||
|
||||
const { debug, warn } = createLogger('xo:backups:RemoteAdapter')
|
||||
|
||||
@@ -312,8 +312,8 @@ export class RemoteAdapter {
|
||||
}
|
||||
|
||||
async deleteVmBackups(files) {
|
||||
const metadatas = await asyncMap(files, file => this.readVmBackupMetadata(file))
|
||||
const { delta, full, ...others } = groupBy(metadatas, 'mode')
|
||||
const metadata = await asyncMap(files, file => this.readVmBackupMetadata(file))
|
||||
const { delta, full, ...others } = groupBy(metadata, 'mode')
|
||||
|
||||
const unsupportedModes = Object.keys(others)
|
||||
if (unsupportedModes.length !== 0) {
|
||||
@@ -498,7 +498,7 @@ export class RemoteAdapter {
|
||||
|
||||
const results = []
|
||||
await asyncMapSettled(partitions, partition =>
|
||||
partition.type === LVM_PARTITION_TYPE
|
||||
partition.type === LVM_PARTITION_TYPE_MBR || partition.type === LVM_PARTITION_TYPE_GPT
|
||||
? this._listLvmLogicalVolumes(devicePath, partition, results)
|
||||
: results.push(partition)
|
||||
)
|
||||
@@ -575,7 +575,7 @@ export class RemoteAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
async #getCachabledDataListVmBackups(dir) {
|
||||
async #getCacheableDataListVmBackups(dir) {
|
||||
debug('generating cache', { path: dir })
|
||||
|
||||
const handler = this._handler
|
||||
@@ -622,7 +622,7 @@ export class RemoteAdapter {
|
||||
}
|
||||
|
||||
// nothing cached, or cache unreadable => regenerate it
|
||||
const backups = await this.#getCachabledDataListVmBackups(`${BACKUP_DIR}/${vmUuid}`)
|
||||
const backups = await this.#getCacheableDataListVmBackups(`${BACKUP_DIR}/${vmUuid}`)
|
||||
if (backups === undefined) {
|
||||
return
|
||||
}
|
||||
@@ -709,7 +709,7 @@ export class RemoteAdapter {
|
||||
})
|
||||
} else {
|
||||
const stream = await toVhdStream(disk)
|
||||
await this.outputStream(path, stream, { validator })
|
||||
await this.outputStream(path, stream, { validator, checksum: false })
|
||||
await validator(path)
|
||||
}
|
||||
}
|
||||
@@ -779,7 +779,7 @@ export class RemoteAdapter {
|
||||
// if the remote is immutable, check if this metadata is also immutable
|
||||
try {
|
||||
// this file is not encrypted
|
||||
await this._handler._readFile(IMMUTABILTY_METADATA_FILENAME)
|
||||
await this._handler._readFile(IMMUTABILITY_METADATA_FILENAME)
|
||||
remoteIsImmutable = true
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const isMetadataFile = filename => filename.endsWith('.json')
|
||||
export const isVhdFile = filename => filename.endsWith('.vhd')
|
||||
export const isVhdSumFile = filename => filename.endsWith('.vhd.checksum')
|
||||
export const isXvaFile = filename => filename.endsWith('.xva')
|
||||
export const isXvaSumFile = filename => filename.endsWith('.xva.checksum')
|
||||
|
||||
@@ -83,12 +83,12 @@ test('It remove broken vhd', async () => {
|
||||
|
||||
await handler.writeFile(`${basePath}/notReallyAVhd.vhd`, 'I AM NOT A VHD')
|
||||
assert.equal((await handler.list(basePath)).length, 1)
|
||||
let loggued = ''
|
||||
let logged = ''
|
||||
const logInfo = message => {
|
||||
loggued += message
|
||||
logged += message
|
||||
}
|
||||
await adapter.cleanVm(rootPath, { remove: false, logInfo, logWarn: logInfo, lock: false })
|
||||
assert.equal(loggued, `VHD check error`)
|
||||
assert.equal(logged, `VHD check error`)
|
||||
// not removed
|
||||
assert.deepEqual(await handler.list(basePath), ['notReallyAVhd.vhd'])
|
||||
// really remove it
|
||||
@@ -98,7 +98,7 @@ test('It remove broken vhd', async () => {
|
||||
|
||||
test('it remove vhd with missing or multiple ancestors', async () => {
|
||||
// one with a broken parent, should be deleted
|
||||
await generateVhd(`${basePath}/abandonned.vhd`, {
|
||||
await generateVhd(`${basePath}/abandoned.vhd`, {
|
||||
header: {
|
||||
parentUnicodeName: 'gone.vhd',
|
||||
parentUuid: uniqueIdBuffer(),
|
||||
@@ -118,18 +118,18 @@ test('it remove vhd with missing or multiple ancestors', async () => {
|
||||
`metadata.json`,
|
||||
JSON.stringify({
|
||||
mode: 'delta',
|
||||
vhds: [`${basePath}/child.vhd`, `${basePath}/abandonned.vhd`],
|
||||
vhds: [`${basePath}/child.vhd`, `${basePath}/abandoned.vhd`],
|
||||
}),
|
||||
{ flags: 'w' }
|
||||
)
|
||||
// clean
|
||||
let loggued = ''
|
||||
let logged = ''
|
||||
const logInfo = message => {
|
||||
loggued += message + '\n'
|
||||
logged += message + '\n'
|
||||
}
|
||||
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
|
||||
|
||||
const deletedOrphanVhd = loggued.match(/deleting orphan VHD/g) || []
|
||||
const deletedOrphanVhd = logged.match(/deleting orphan VHD/g) || []
|
||||
assert.equal(deletedOrphanVhd.length, 1) // only one vhd should have been deleted
|
||||
|
||||
// we don't test the file on disk, since they will all be marker as unused and deleted without a metadata.json file
|
||||
@@ -144,12 +144,12 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
|
||||
vhds: [
|
||||
`${relativePath}/orphan.vhd`,
|
||||
`${relativePath}/child.vhd`,
|
||||
// abandonned.json is not here
|
||||
// abandoned.json is not here
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
await generateVhd(`${basePath}/abandonned.vhd`)
|
||||
await generateVhd(`${basePath}/abandoned.vhd`)
|
||||
|
||||
// one orphan, which is a full vhd, no parent
|
||||
const orphan = await generateVhd(`${basePath}/orphan.vhd`)
|
||||
@@ -162,12 +162,12 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
|
||||
},
|
||||
})
|
||||
|
||||
let loggued = ''
|
||||
let logged = ''
|
||||
const logInfo = message => {
|
||||
loggued += message + '\n'
|
||||
logged += message + '\n'
|
||||
}
|
||||
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
|
||||
let matched = loggued.match(/deleting unused VHD/g) || []
|
||||
let matched = logged.match(/deleting unused VHD/g) || []
|
||||
assert.equal(matched.length, 1) // only one vhd should have been deleted
|
||||
|
||||
// a missing vhd cause clean to remove all vhds
|
||||
@@ -179,14 +179,14 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
|
||||
`deleted.vhd`, // in metadata but not in vhds
|
||||
`orphan.vhd`,
|
||||
`child.vhd`,
|
||||
// abandonned.vhd is not here anymore
|
||||
// abandoned.vhd is not here anymore
|
||||
],
|
||||
}),
|
||||
{ flags: 'w' }
|
||||
)
|
||||
loggued = ''
|
||||
logged = ''
|
||||
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: () => {}, lock: false })
|
||||
matched = loggued.match(/deleting unused VHD/g) || []
|
||||
matched = logged.match(/deleting unused VHD/g) || []
|
||||
assert.equal(matched.length, 2) // all vhds (orphan and child ) should have been deleted
|
||||
})
|
||||
|
||||
@@ -221,16 +221,16 @@ test('it merges delta of non destroyed chain', async () => {
|
||||
},
|
||||
})
|
||||
|
||||
let loggued = []
|
||||
let logged = []
|
||||
const logInfo = message => {
|
||||
loggued.push(message)
|
||||
logged.push(message)
|
||||
}
|
||||
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
|
||||
assert.equal(loggued[0], `unexpected number of entries in backup cache`)
|
||||
assert.equal(logged[0], `unexpected number of entries in backup cache`)
|
||||
|
||||
loggued = []
|
||||
logged = []
|
||||
await adapter.cleanVm(rootPath, { remove: true, merge: true, logInfo, logWarn: () => {}, lock: false })
|
||||
const [merging] = loggued
|
||||
const [merging] = logged
|
||||
assert.equal(merging, `merging VHD chain`)
|
||||
|
||||
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
|
||||
@@ -311,7 +311,7 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
|
||||
// a vhd non referenced in metadata
|
||||
await generateVhd(`${basePath}/nonreference.vhd`, { useAlias, mode: vhdMode })
|
||||
// an abandoned delta vhd without its parent
|
||||
await generateVhd(`${basePath}/abandonned.vhd`, {
|
||||
await generateVhd(`${basePath}/abandoned.vhd`, {
|
||||
useAlias,
|
||||
mode: vhdMode,
|
||||
header: {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { asyncMap } from '@xen-orchestra/async-map'
|
||||
import { Constants, openVhd, VhdAbstract, VhdFile } from 'vhd-lib'
|
||||
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
|
||||
import { basename, dirname, resolve } from 'node:path'
|
||||
import { isMetadataFile, isVhdFile, isXvaFile, isXvaSumFile } from './_backupType.mjs'
|
||||
import { isMetadataFile, isVhdFile, isVhdSumFile, isXvaFile, isXvaSumFile } from './_backupType.mjs'
|
||||
import { limitConcurrency } from 'limit-concurrency-decorator'
|
||||
import { mergeVhdChain } from 'vhd-lib/merge.js'
|
||||
|
||||
@@ -68,10 +68,12 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
|
||||
const noop = Function.prototype
|
||||
|
||||
const INTERRUPTED_VHDS_REG = /^\.(.+)\.merge.json$/
|
||||
|
||||
const listVhds = async (handler, vmDir, logWarn) => {
|
||||
const vhds = new Set()
|
||||
const aliases = {}
|
||||
const interruptedVhds = new Map()
|
||||
const checksums = new Set()
|
||||
|
||||
await asyncMap(
|
||||
await handler.list(`${vmDir}/vdis`, {
|
||||
@@ -85,11 +87,15 @@ const listVhds = async (handler, vmDir, logWarn) => {
|
||||
}),
|
||||
async vdiDir => {
|
||||
const list = await handler.list(vdiDir, {
|
||||
filter: file => isVhdFile(file) || INTERRUPTED_VHDS_REG.test(file),
|
||||
filter: file => isVhdFile(file) || INTERRUPTED_VHDS_REG.test(file) || isVhdSumFile(file),
|
||||
})
|
||||
aliases[vdiDir] = list.filter(vhd => isVhdAlias(vhd)).map(file => `${vdiDir}/${file}`)
|
||||
|
||||
await asyncMap(list, async file => {
|
||||
if (isVhdSumFile(file)) {
|
||||
checksums.add(`${vdiDir}/${file}`)
|
||||
return
|
||||
}
|
||||
const res = INTERRUPTED_VHDS_REG.exec(file)
|
||||
if (res === null) {
|
||||
vhds.add(`${vdiDir}/${file}`)
|
||||
@@ -111,7 +117,7 @@ const listVhds = async (handler, vmDir, logWarn) => {
|
||||
)
|
||||
)
|
||||
|
||||
return { vhds, interruptedVhds, aliases }
|
||||
return { vhds, interruptedVhds, aliases, checksums }
|
||||
}
|
||||
|
||||
export async function checkAliases(
|
||||
@@ -228,7 +234,16 @@ export async function cleanVm(
|
||||
const vhdParents = { __proto__: null }
|
||||
const vhdChildren = { __proto__: null }
|
||||
|
||||
const { vhds, interruptedVhds, aliases } = await listVhds(handler, vmDir, logWarn)
|
||||
const { vhds, interruptedVhds, aliases, checksums } = await listVhds(handler, vmDir, logWarn)
|
||||
|
||||
// from 5.110 to 5.113 we computed checksum for vhd file
|
||||
// but never used nor removed them
|
||||
await asyncMap(checksums, async path => {
|
||||
if (remove) {
|
||||
logInfo('deleting checksum file ', { path })
|
||||
return handler.unlink(path)
|
||||
}
|
||||
})
|
||||
|
||||
// remove broken VHDs
|
||||
await asyncMap(vhds, async path => {
|
||||
|
||||
@@ -97,40 +97,59 @@ export function getOldEntries(minRetentionCount, entries, { longTermRetention =
|
||||
remaining: retention,
|
||||
lastMatchingBucket: null,
|
||||
formatter: LTR_DEFINITIONS[duration].makeDateFormatter({ ...settings, dateCreator }),
|
||||
entries: {}, // bucket => entry id
|
||||
}
|
||||
}
|
||||
const nb = entries.length
|
||||
const oldEntries = []
|
||||
|
||||
const minDurationEntries = []
|
||||
let previousTimestamp = -1
|
||||
for (let i = nb - 1; i >= 0; i--) {
|
||||
const entry = entries[i]
|
||||
const entryDate = dateCreator(entry.timestamp)
|
||||
let shouldBeKept = false
|
||||
for (const [duration, { remaining, lastMatchingBucket, formatter }] of Object.entries(dateBuckets)) {
|
||||
if (remaining === 0) {
|
||||
continue
|
||||
}
|
||||
const bucket = formatter(entryDate)
|
||||
if (lastMatchingBucket !== bucket) {
|
||||
if (lastMatchingBucket !== null) {
|
||||
assert.strictEqual(
|
||||
lastMatchingBucket > bucket,
|
||||
true,
|
||||
`entries must be sorted in asc order ${lastMatchingBucket} ${bucket}`
|
||||
)
|
||||
if (entry.timestamp !== undefined) {
|
||||
// we go through the entries from the last (most recent) to the first (oldest)
|
||||
assert.ok(
|
||||
previousTimestamp === -1 || entry.timestamp < previousTimestamp,
|
||||
`entries must be sorted in desc order ${new Date(entry.timestamp)} , previous : > ${new Date(previousTimestamp)} `
|
||||
)
|
||||
previousTimestamp = entry.timestamp
|
||||
const entryDate = dateCreator(entry.timestamp)
|
||||
for (const [duration, { remaining, lastMatchingBucket, formatter }] of Object.entries(dateBuckets)) {
|
||||
const bucket = formatter(entryDate)
|
||||
if (lastMatchingBucket !== bucket) {
|
||||
if (remaining === 0) {
|
||||
continue
|
||||
}
|
||||
dateBuckets[duration].lastMatchingBucket = bucket
|
||||
dateBuckets[duration].remaining -= 1
|
||||
}
|
||||
shouldBeKept = true
|
||||
dateBuckets[duration].remaining -= 1
|
||||
dateBuckets[duration].lastMatchingBucket = bucket
|
||||
dateBuckets[duration].entries[bucket] = entry
|
||||
}
|
||||
} else {
|
||||
// replicated VM entries or snapshot retention don't have a timestamp
|
||||
// but also can't have LTR
|
||||
assert.deepStrictEqual(
|
||||
longTermRetention,
|
||||
{},
|
||||
"Can't compute long term retention if entries don't have a timestamp"
|
||||
)
|
||||
}
|
||||
|
||||
// also keep it on retention
|
||||
if (i >= nb - minRetentionCount) {
|
||||
shouldBeKept = true
|
||||
}
|
||||
if (!shouldBeKept) {
|
||||
oldEntries.push(entry)
|
||||
minDurationEntries.push(entry)
|
||||
}
|
||||
}
|
||||
// we expect the entries to be in the right order
|
||||
return oldEntries.reverse()
|
||||
const kept = new Set(minDurationEntries)
|
||||
for (const { entries } of Object.values(dateBuckets)) {
|
||||
for (const entry of Object.values(entries)) {
|
||||
kept.add(entry)
|
||||
}
|
||||
}
|
||||
|
||||
// ensure order is the same as the source
|
||||
const oldEntries = entries.filter(entry => {
|
||||
return !kept.has(entry)
|
||||
})
|
||||
|
||||
return oldEntries
|
||||
}
|
||||
|
||||
@@ -10,24 +10,29 @@ describe('_getOldEntries() should succeed', () => {
|
||||
1,
|
||||
[
|
||||
{ timestamp: 1, id: 1 },
|
||||
{ timestamp: 3, id: 2 },
|
||||
{ timestamp: 2, id: 3 },
|
||||
{ timestamp: 2, id: 2 },
|
||||
{ timestamp: 3, id: 3 },
|
||||
],
|
||||
],
|
||||
expectedIds: [1, 2],
|
||||
testLabel: 'should handle number based retention ',
|
||||
},
|
||||
{
|
||||
args: [3, [{ id: 1 }, 4, new Date(), 'whatever']],
|
||||
expectedIds: [1],
|
||||
testLabel: 'should handle number based retention without timestamp ',
|
||||
},
|
||||
|
||||
{
|
||||
args: [
|
||||
0,
|
||||
[
|
||||
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // too old
|
||||
{ timestamp: +new Date('2024-09-01 00:00:00'), id: 2 }, // too old
|
||||
{ timestamp: +new Date('2024-09-02 00:09:00'), id: 3 }, // too old in same day
|
||||
{ timestamp: +new Date('2024-09-01 00:00:00'), id: 1 }, // too old
|
||||
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 2 }, // too old
|
||||
{ timestamp: +new Date('2024-09-02 00:09:00'), id: 3 }, // oldest in same day
|
||||
{ timestamp: +new Date('2024-09-02 00:10:00'), id: 4 },
|
||||
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 5 },
|
||||
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // too old in same day
|
||||
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // oldest in same day
|
||||
{ timestamp: +new Date('2024-09-04 00:10:00'), id: 7 },
|
||||
],
|
||||
{
|
||||
@@ -37,22 +42,22 @@ describe('_getOldEntries() should succeed', () => {
|
||||
timezone: 'Europe/Paris',
|
||||
},
|
||||
],
|
||||
expectedIds: [1, 2, 3, 6],
|
||||
expectedIds: [1, 2, 4, 7],
|
||||
testLabel: 'should handle day based retention ',
|
||||
},
|
||||
{
|
||||
args: [
|
||||
0,
|
||||
[
|
||||
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // week n-3 too old
|
||||
{ timestamp: +new Date('2024-09-02 00:00:00'), id: 2 }, // week n-3 too old
|
||||
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 3 }, // week n-2
|
||||
{ timestamp: +new Date('2024-08-30 00:01:00'), id: 1 }, // week n-3 too old
|
||||
{ timestamp: +new Date('2024-08-31 00:00:00'), id: 2 }, // week n-3 too old
|
||||
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 3 }, // week n-2, oldest
|
||||
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 4 }, // week n-2
|
||||
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, // week n-2
|
||||
{ timestamp: +new Date('2024-09-06 00:09:00'), id: 6 }, // week n-2
|
||||
{ timestamp: +new Date('2024-09-07 00:09:00'), id: 7 }, // week n-2, most recent kept
|
||||
{ timestamp: +new Date('2024-09-09 00:09:00'), id: 8 }, // week n-1, too old
|
||||
{ timestamp: +new Date('2024-09-15 00:09:00'), id: 9 }, // week n-1 kept
|
||||
{ timestamp: +new Date('2024-09-07 00:09:00'), id: 7 }, // week n-2
|
||||
{ timestamp: +new Date('2024-09-15 00:09:00'), id: 8 }, // week n-1, oldest
|
||||
{ timestamp: +new Date('2024-09-21 00:09:00'), id: 9 }, // week n-1 most recent
|
||||
{ timestamp: +new Date('2024-09-22 00:09:00'), id: 10 }, // week n kept
|
||||
],
|
||||
{
|
||||
@@ -62,7 +67,7 @@ describe('_getOldEntries() should succeed', () => {
|
||||
timezone: 'Europe/Paris',
|
||||
},
|
||||
],
|
||||
expectedIds: [1, 2, 3, 4, 5, 6, 8],
|
||||
expectedIds: [1, 2, 4, 5, 6, 7, 9],
|
||||
testLabel: 'should handle week based retention ',
|
||||
},
|
||||
{
|
||||
@@ -85,26 +90,26 @@ describe('_getOldEntries() should succeed', () => {
|
||||
timezone: 'Europe/Paris',
|
||||
},
|
||||
],
|
||||
expectedIds: [1, 3, 4, 6, 7],
|
||||
expectedIds: [1, 4, 5, 7, 8],
|
||||
testLabel: 'should handle month based retention',
|
||||
},
|
||||
{
|
||||
args: [
|
||||
0,
|
||||
2,
|
||||
[
|
||||
{ timestamp: +new Date('2023-05-18 00:09:00'), id: 1 }, // too old
|
||||
{ timestamp: +new Date('2024-06-15 00:09:00'), id: 2 }, // too old in same year
|
||||
{ timestamp: +new Date('2024-07-04 00:09:00'), id: 3 }, // too old
|
||||
{ timestamp: +new Date('2024-08-12 00:09:00'), id: 4 }, // too old
|
||||
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, // too old
|
||||
{ timestamp: +new Date('2024-10-02 00:09:00'), id: 6 }, // new month,
|
||||
{ timestamp: +new Date('2024-11-01 00:09:00'), id: 7 }, // new month , week reached retention
|
||||
{ timestamp: +new Date('2024-12-17 00:09:00'), id: 8 }, // new week
|
||||
{ timestamp: +new Date('2024-12-24 00:09:00'), id: 9 }, // new week/month / year daily reach retention
|
||||
{ timestamp: +new Date('2025-01-01 00:09:00'), id: 10 }, // same day/week/month/year
|
||||
{ timestamp: +new Date('2025-01-01 00:10:00'), id: 11 }, // new day / week / month
|
||||
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 12 }, // same day/week/month/year
|
||||
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 13 }, // new month /year
|
||||
{ timestamp: +new Date('2023-05-18 00:09:00'), id: 1 }, //
|
||||
{ timestamp: +new Date('2024-06-15 00:09:00'), id: 2 }, // year n -1
|
||||
{ timestamp: +new Date('2024-07-04 00:09:00'), id: 3 }, //
|
||||
{ timestamp: +new Date('2024-08-12 00:09:00'), id: 4 }, //
|
||||
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, //
|
||||
{ timestamp: +new Date('2024-10-02 00:09:00'), id: 6 }, // month n-4
|
||||
{ timestamp: +new Date('2024-11-01 00:09:00'), id: 7 }, // month n-3
|
||||
{ timestamp: +new Date('2024-12-17 00:09:00'), id: 8 }, // week n-3
|
||||
{ timestamp: +new Date('2024-12-24 00:09:00'), id: 9 }, // week n-2, month n-2,
|
||||
{ timestamp: +new Date('2025-01-01 00:09:00'), id: 10 }, // week n-1, year n
|
||||
{ timestamp: +new Date('2025-01-02 00:10:00'), id: 11 }, // day n-1, month n-1,
|
||||
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 12 }, // day n , week n , month n
|
||||
{ timestamp: +new Date('2025-12-31 10:09:00'), id: 13 }, // min retention
|
||||
],
|
||||
{
|
||||
longTermRetention: {
|
||||
@@ -116,18 +121,18 @@ describe('_getOldEntries() should succeed', () => {
|
||||
timezone: 'Europe/Paris', // use a time zone here because week definition is timezone bound
|
||||
},
|
||||
],
|
||||
expectedIds: [1, 2, 3, 4, 5, 10, 12],
|
||||
expectedIds: [1, 3, 4, 5],
|
||||
testLabel: 'complete test ',
|
||||
},
|
||||
{
|
||||
args: [
|
||||
0,
|
||||
[
|
||||
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // thrid day too old
|
||||
{ timestamp: +new Date('2024-09-01 00:10:00'), id: 2 }, // thrid day
|
||||
{ timestamp: +new Date('2024-09-01 00:20:00'), id: 3 }, // second day, too old
|
||||
{ timestamp: +new Date('2024-09-02 00:22:00'), id: 4 }, // second day too old
|
||||
{ timestamp: +new Date('2024-09-03 00:20:00'), id: 5 }, // second day in NZ
|
||||
{ timestamp: +new Date('2024-08-31 09:01:00'), id: 1 }, // 4th day too old
|
||||
{ timestamp: +new Date('2024-09-01 00:10:00'), id: 2 }, // third day
|
||||
{ timestamp: +new Date('2024-09-01 14:20:00'), id: 3 }, // second day, oldest
|
||||
{ timestamp: +new Date('2024-09-02 00:22:00'), id: 4 }, // second day
|
||||
{ timestamp: +new Date('2024-09-03 14:00:00'), id: 5 }, // same day oldest
|
||||
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // same day in NZ
|
||||
{ timestamp: +new Date('2024-09-04 00:10:00'), id: 7 }, // most recent
|
||||
],
|
||||
@@ -135,10 +140,10 @@ describe('_getOldEntries() should succeed', () => {
|
||||
longTermRetention: {
|
||||
daily: { retention: 3 },
|
||||
},
|
||||
timezone: 'Pacific/Auckland', // GMT +6
|
||||
timezone: 'Pacific/Auckland', // GMT +13
|
||||
},
|
||||
],
|
||||
expectedIds: [1, 2, 3, 6],
|
||||
expectedIds: [1, 4, 6, 7],
|
||||
testLabel: 'should handle timezone ',
|
||||
},
|
||||
]
|
||||
@@ -149,13 +154,20 @@ describe('_getOldEntries() should succeed', () => {
|
||||
assert.strictEqual(
|
||||
oldEntries.length,
|
||||
expectedIds.length,
|
||||
`different length , ${JSON.stringify({ oldEntries, expectedIds })}`
|
||||
`different length , ${JSON.stringify({ expectedIds, oldEntries: oldEntries.map(({ id }) => id) })}`
|
||||
)
|
||||
for (let i = 0; i < expectedIds.length; i++) {
|
||||
if (i > 0) {
|
||||
assert.strictEqual(
|
||||
expectedIds[i - 1] < expectedIds[i],
|
||||
true,
|
||||
`expect ids in ascending order ${expectedIds[i - 1]} ${expectedIds[i]}`
|
||||
)
|
||||
}
|
||||
assert.strictEqual(
|
||||
oldEntries[i].id,
|
||||
expectedIds[i],
|
||||
`different id , ${JSON.stringify({ i, expectedIds, oldEntries })}`
|
||||
`different id , ${JSON.stringify({ i, expectedIds, oldEntries: oldEntries.map(({ id }) => id) })}`
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -272,6 +284,19 @@ describe('_getOldEntries() should fail when called incorrectly', () => {
|
||||
],
|
||||
testLabel: 'broken date ',
|
||||
},
|
||||
{
|
||||
args: [
|
||||
1,
|
||||
[{ obj: 1 }, 'toto', Date.now()],
|
||||
{
|
||||
longTermRetention: {
|
||||
daily: { retention: 5 },
|
||||
},
|
||||
timezone: 'Europe/Paris',
|
||||
},
|
||||
],
|
||||
testLabel: 'should fail if LTR without timestamp',
|
||||
},
|
||||
]
|
||||
|
||||
for (const { args, testLabel } of tests) {
|
||||
|
||||
@@ -10,10 +10,9 @@ import { Task } from './Task.mjs'
|
||||
import pick from 'lodash/pick.js'
|
||||
import { BASE_DELTA_VDI, COPY_OF, VM_UUID } from './_otherConfig.mjs'
|
||||
|
||||
import { XapiDiskSource } from '@xen-orchestra/xapi'
|
||||
import { VHD_MAX_SIZE, XapiDiskSource } from '@xen-orchestra/xapi'
|
||||
import { toVhdStream } from 'vhd-lib/disk-consumer/index.mjs'
|
||||
import { toQcow2Stream } from '@xen-orchestra/qcow2'
|
||||
import { VHD_MAX_SIZE } from '@xen-orchestra/xapi/disks/Xapi.mjs'
|
||||
|
||||
const ensureArray = value => (value === undefined ? [] : Array.isArray(value) ? value : [value])
|
||||
|
||||
@@ -94,11 +93,13 @@ export async function exportIncrementalVm(
|
||||
}
|
||||
})
|
||||
|
||||
// Get a fresh list of VM's VTPM to avoid `vm.VTPMs: [undefined]`
|
||||
const vmVtpms = await vm.$xapi.getField('VM', vm.$ref, 'VTPMs')
|
||||
const vtpms = await Promise.all(
|
||||
vm.$VTPMs.map(async vtpm => {
|
||||
vmVtpms.map(async vtpmRef => {
|
||||
let content
|
||||
try {
|
||||
content = await vm.$xapi.call('VTPM.get_contents', vtpm.$ref)
|
||||
content = await vm.$xapi.call('VTPM.get_contents', vtpmRef)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
|
||||
@@ -20,13 +20,31 @@ const IGNORED_PARTITION_TYPES = {
|
||||
0xd5: true,
|
||||
|
||||
0x82: true, // swap
|
||||
// GPT Linux swap GUID
|
||||
'0657fd6d-a4ab-43c4-84e5-0933c84b4f4f': true,
|
||||
}
|
||||
|
||||
export const LVM_PARTITION_TYPE = 0x8e
|
||||
// MBR LVM type
|
||||
export const LVM_PARTITION_TYPE_MBR = 0x8e
|
||||
// GPT LVM type
|
||||
export const LVM_PARTITION_TYPE_GPT = 'e6d6d379-f507-44c2-a23c-238f2a3df928'
|
||||
|
||||
const parsePartxLine = createParser({
|
||||
keyTransform: key => (key === 'UUID' ? 'id' : key.toLowerCase()),
|
||||
valueTransform: (value, key) => (key === 'start' || key === 'size' || key === 'type' ? +value : value),
|
||||
valueTransform: (value, key) => {
|
||||
if (key === 'start' || key === 'size') {
|
||||
return +value
|
||||
}
|
||||
// For GPT partitions, type is a UUID string
|
||||
if (key === 'type' && !value.startsWith('0x')) {
|
||||
return value.toLowerCase()
|
||||
}
|
||||
// For MBR partitions, type is a hex number as string (e.g., "0x8e")
|
||||
if (key === 'type' && value.startsWith('0x')) {
|
||||
return parseInt(value, 16)
|
||||
}
|
||||
return value
|
||||
},
|
||||
})
|
||||
|
||||
// returns an empty array in case of a non-partitioned disk
|
||||
|
||||
@@ -70,7 +70,8 @@ export async function getVmDeltaChainLength(xapi, vmRef) {
|
||||
|
||||
/**
|
||||
*
|
||||
* Reset the other_config field of a VM and its VDIs
|
||||
* Reset the other_config field related to backups of a VM and its VDIs
|
||||
*
|
||||
*
|
||||
* @param {Xapi} xapi
|
||||
* @param {String} vmRef
|
||||
|
||||
@@ -9,6 +9,7 @@ import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
|
||||
import { FullRemote } from './_vmRunners/FullRemote.mjs'
|
||||
import { IncrementalRemote } from './_vmRunners/IncrementalRemote.mjs'
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -41,7 +42,8 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
const schedule = this._schedule
|
||||
const settings = this._settings
|
||||
|
||||
const throttleGenerator = new Throttle()
|
||||
const throttleGenerator = new Throttle(settings.maxExportRate)
|
||||
const throttleStream = createStreamThrottle(settings.maxExportRate)
|
||||
|
||||
const config = this._config
|
||||
|
||||
@@ -89,7 +91,8 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
schedule,
|
||||
settings: vmSettings,
|
||||
sourceRemoteAdapter,
|
||||
throttleGenerator,
|
||||
throttleGenerator, // for incrementals
|
||||
throttleStream, // for full
|
||||
vmUuid,
|
||||
}
|
||||
let vmBackup
|
||||
|
||||
@@ -10,6 +10,7 @@ import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
|
||||
import { IncrementalXapi } from './_vmRunners/IncrementalXapi.mjs'
|
||||
import { FullXapi } from './_vmRunners/FullXapi.mjs'
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -55,7 +56,8 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
const schedule = this._schedule
|
||||
const settings = this._settings
|
||||
|
||||
const throttleGenerator = new Throttle()
|
||||
const throttleGenerator = new Throttle(settings.maxExportRate)
|
||||
const throttleStream = createStreamThrottle(settings.maxExportRate)
|
||||
|
||||
const config = this._config
|
||||
|
||||
@@ -148,6 +150,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
settings: vmSettings,
|
||||
srs,
|
||||
throttleGenerator,
|
||||
throttleStream,
|
||||
vm,
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
const transferList = await this._computeTransferList(({ mode }) => mode === 'full')
|
||||
|
||||
for (const metadata of transferList) {
|
||||
const stream = await this._sourceRemoteAdapter.readFullVmBackup(metadata)
|
||||
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
|
||||
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
|
||||
@@ -37,5 +37,6 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
// for healthcheck
|
||||
this._tags = metadata.vm.tags
|
||||
}
|
||||
this._hasTransferredData = transferList.length > 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,16 +49,14 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
|
||||
const { compression } = this.job
|
||||
const vm = this._vm
|
||||
const exportedVm = this._exportedVm
|
||||
// @todo put back throttle for full backup/Replication
|
||||
const stream =
|
||||
/* this._throttleStream( */
|
||||
const stream = this._throttleStream(
|
||||
(
|
||||
await this._xapi.VM_export(exportedVm.$ref, {
|
||||
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
|
||||
useSnapshot: false,
|
||||
})
|
||||
).body
|
||||
/* ) */
|
||||
)
|
||||
|
||||
const vdis = await exportedVm.$getDisks()
|
||||
let maxStreamLength = 1024 * 1024 // Ovf file and tar headers are a few KB, let's stay safe
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IncrementalRemoteWriter } from '../_writers/IncrementalRemoteWriter.mjs
|
||||
import { Disposable } from 'promise-toolbox'
|
||||
import { openVhd } from 'vhd-lib'
|
||||
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
|
||||
import { SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
|
||||
|
||||
const { warn } = createLogger('xo:backups:Incrementalremote')
|
||||
class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
@@ -71,8 +71,9 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
const isVhdDifferencing = {}
|
||||
|
||||
for (const key in incrementalExport.disks) {
|
||||
const disk = incrementalExport.disks[key]
|
||||
let disk = incrementalExport.disks[key]
|
||||
isVhdDifferencing[key] = disk.isDifferencing()
|
||||
disk = new ThrottledDisk(disk, this._throttleGenerator)
|
||||
incrementalExport.disks[key] = new SynchronizedDisk(disk)
|
||||
}
|
||||
|
||||
@@ -115,6 +116,7 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
// for healthcheck
|
||||
this._tags = metadata.vm.tags
|
||||
}
|
||||
this._hasTransferredData = transferList.length > 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
setVmDeltaChainLength,
|
||||
markExportSuccessfull,
|
||||
} from '../../_otherConfig.mjs'
|
||||
import { SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
import { ThrottledDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
|
||||
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
|
||||
|
||||
@@ -43,10 +43,14 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
const isVhdDifferencing = {}
|
||||
let useNbd = false
|
||||
for (const key in deltaExport.disks) {
|
||||
const disk = deltaExport.disks[key]
|
||||
let disk = deltaExport.disks[key]
|
||||
isVhdDifferencing[key] = disk.isDifferencing()
|
||||
deltaExport.disks[key] = new SynchronizedDisk(disk)
|
||||
if (!isFull && !isVhdDifferencing[key] && key !== exportedVm.$suspend_VDI?.$ref) {
|
||||
Task.warning('Backup fell back to a full')
|
||||
}
|
||||
useNbd = useNbd || disk.useNbd()
|
||||
disk = new ThrottledDisk(disk, this._throttleGenerator)
|
||||
deltaExport.disks[key] = new SynchronizedDisk(disk)
|
||||
}
|
||||
if (useNbd) {
|
||||
Task.info('Transfer data using NBD')
|
||||
|
||||
@@ -13,6 +13,8 @@ import { Task } from '../../Task.mjs'
|
||||
|
||||
export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstract {
|
||||
_filterPredicate
|
||||
_hasTransferredData
|
||||
|
||||
constructor({
|
||||
config,
|
||||
job,
|
||||
@@ -22,6 +24,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
settings,
|
||||
sourceRemoteAdapter,
|
||||
throttleGenerator,
|
||||
throttleStream,
|
||||
vmUuid,
|
||||
}) {
|
||||
super()
|
||||
@@ -35,6 +38,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
this._healthCheckSr = healthCheckSr
|
||||
this._sourceRemoteAdapter = sourceRemoteAdapter
|
||||
this._throttleGenerator = throttleGenerator
|
||||
this._throttleStream = throttleStream
|
||||
this._vmUuid = vmUuid
|
||||
|
||||
const allSettings = job.settings
|
||||
@@ -70,28 +74,28 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
}
|
||||
|
||||
async #computeTransferListPerJob(sourceBackups, remotesBackups) {
|
||||
const localMetada = new Map()
|
||||
const localMetadata = new Map()
|
||||
sourceBackups.forEach(metadata => {
|
||||
const timestamp = metadata.timestamp
|
||||
localMetada.set(timestamp, metadata)
|
||||
localMetadata.set(timestamp, metadata)
|
||||
})
|
||||
const nbRemotes = remotesBackups.length
|
||||
const remoteMetadatas = {}
|
||||
const remoteMetadata = {}
|
||||
remotesBackups.forEach(async remoteBackups => {
|
||||
remoteBackups.forEach(metadata => {
|
||||
const timestamp = metadata.timestamp
|
||||
remoteMetadatas[timestamp] = (remoteMetadatas[timestamp] ?? 0) + 1
|
||||
remoteMetadata[timestamp] = (remoteMetadata[timestamp] ?? 0) + 1
|
||||
})
|
||||
})
|
||||
|
||||
let transferList = []
|
||||
const timestamps = [...localMetada.keys()]
|
||||
const timestamps = [...localMetadata.keys()]
|
||||
timestamps.sort()
|
||||
for (const timestamp of timestamps) {
|
||||
if (remoteMetadatas[timestamp] !== nbRemotes) {
|
||||
if (remoteMetadata[timestamp] !== nbRemotes) {
|
||||
// this backup is not present in all the remote
|
||||
// should be retransferred if not found later
|
||||
transferList.push(localMetada.get(timestamp))
|
||||
transferList.push(localMetadata.get(timestamp))
|
||||
} else {
|
||||
// backup is present in local and remote : the chain has already been transferred
|
||||
transferList = []
|
||||
@@ -99,17 +103,10 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
}
|
||||
if (transferList.length > 0) {
|
||||
const filteredTransferList = this._filterTransferList(transferList)
|
||||
if (filteredTransferList.length > 0) {
|
||||
return filteredTransferList
|
||||
} else {
|
||||
Task.info('This VM is excluded by the job filter')
|
||||
return []
|
||||
}
|
||||
return { transferList: filteredTransferList, filtered: true }
|
||||
} else {
|
||||
Task.info('No new data to upload for this VM')
|
||||
return { transferList, filtered: false }
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,12 +120,21 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
Object.values(this.remoteAdapters).map(remoteAdapter => remoteAdapter.listVmBackups(this._vmUuid, vmPredicate))
|
||||
)
|
||||
const sourceBackupByJobId = groupBy(sourceBackups, 'jobId')
|
||||
const transferByJobs = await Promise.all(
|
||||
const transferObjectsList = await Promise.all(
|
||||
Object.values(sourceBackupByJobId).map(vmBackupsByJob =>
|
||||
this.#computeTransferListPerJob(vmBackupsByJob, remotesBackups)
|
||||
)
|
||||
)
|
||||
return transferByJobs.flat(1)
|
||||
const transferList = transferObjectsList.map(transferObject => transferObject.transferList).flat(1)
|
||||
if (transferList.length === 0 && Object.values(sourceBackupByJobId).length > 0) {
|
||||
if (transferObjectsList.some(transferObject => transferObject.filtered)) {
|
||||
// Happens if any job transfer list wasn't empty before filter and is empty after filter.
|
||||
Task.info('This VM is excluded by the job filter')
|
||||
} else {
|
||||
Task.info('No new data to upload for this VM')
|
||||
}
|
||||
}
|
||||
return transferList
|
||||
}
|
||||
|
||||
async run($defer) {
|
||||
@@ -141,7 +147,16 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
})
|
||||
}, 'writer.beforeBackup()')
|
||||
await this._run()
|
||||
await this._healthCheck()
|
||||
|
||||
if (this._hasTransferredData === undefined) {
|
||||
throw new Error('Missing tag to check there are some transferred data')
|
||||
}
|
||||
|
||||
if (this._hasTransferredData) {
|
||||
await this._healthCheck()
|
||||
} else {
|
||||
Task.info(`No healthCheck needed because no data was transferred.`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert'
|
||||
import groupBy from 'lodash/groupBy.js'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import ignoreErrors from 'promise-toolbox/ignoreErrors'
|
||||
import { asyncMap } from '@xen-orchestra/async-map'
|
||||
import { decorateMethodsWith } from '@vates/decorate-with'
|
||||
@@ -17,6 +18,8 @@ import {
|
||||
setVmOtherConfig,
|
||||
} from '../../_otherConfig.mjs'
|
||||
|
||||
const { warn } = createLogger('xo:backups:AbstractXapi')
|
||||
|
||||
export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
constructor({
|
||||
config,
|
||||
@@ -29,6 +32,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
settings,
|
||||
srs,
|
||||
throttleGenerator,
|
||||
throttleStream,
|
||||
vm,
|
||||
}) {
|
||||
super()
|
||||
@@ -63,6 +67,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
this._jobId = job.id
|
||||
this._jobSnapshotVdis = undefined
|
||||
this._throttleGenerator = throttleGenerator
|
||||
this._throttleStream = throttleStream
|
||||
this._xapi = vm.$xapi
|
||||
|
||||
// Base VM for the export
|
||||
@@ -253,28 +258,47 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
return
|
||||
}
|
||||
const vdis = snapshotPerDatetime[datetime]
|
||||
let vmRef
|
||||
let vm
|
||||
// if there is an attached VM => destroy the VM (Non CBT backups)
|
||||
for (const vdi of vdis) {
|
||||
const vbds = vdi.$VBDs.filter(({ $VM }) => $VM.is_control_domain === false)
|
||||
if (vbds.length > 0) {
|
||||
// only one VM linked to this vdi
|
||||
// this will throw error for VDI still attached to control domain
|
||||
// since we won't be able to remove an attached VDI
|
||||
assert.strictEqual(vbds.length, 1, 'VDI must be free or attached to exactly one VM')
|
||||
const vm = vbds[0].$VM
|
||||
assert.strictEqual(vm.is_a_snapshot, true, `VM must be a snapshot`) // don't delete a VM (especially a control domain)
|
||||
|
||||
const vmRefVdi = vm.$ref
|
||||
// same vm than other vdi of the same batch
|
||||
assert.ok(
|
||||
vmRef === undefined || vmRef === vmRefVdi,
|
||||
'_removeUnusedSnapshots don t handle vdi related to multiple VMs '
|
||||
)
|
||||
vmRef = vmRefVdi
|
||||
const vdiVm = vbds[0].$VM
|
||||
if (!vdiVm.is_a_snapshot) {
|
||||
// don't delete a VM (especially a control domain)
|
||||
warn(
|
||||
`VM ${vdiVm.uuid} (${vdiVm.name_label}) linked to VDI ${vdi.uuid} (${vdi.name_label}) should be a snapshot`
|
||||
)
|
||||
throw new Error(`VM must be a snapshot`)
|
||||
}
|
||||
if (vm !== undefined && vm.$ref !== vdiVm.$ref) {
|
||||
// this VDI is attached to another VM than the other vdi of
|
||||
// this batch
|
||||
// in doubt, do not delete anything
|
||||
warn("_removeUnusedSnapshots don't handle vdi related to multiple VMs ", {
|
||||
vm1: {
|
||||
label: vm.name_label,
|
||||
id: vm.$id,
|
||||
},
|
||||
vm2: {
|
||||
label: vdiVm.name_label,
|
||||
id: vdiVm.$id,
|
||||
},
|
||||
vdis: vdis.map(({ name_label, $id }) => ({ name_label, $id })),
|
||||
})
|
||||
throw new Error(
|
||||
`_removeUnusedSnapshots don't handle vdi related to multiple VMs ${vm.name_label} and ${vdiVm.name_label}`
|
||||
)
|
||||
}
|
||||
vm = vdiVm
|
||||
}
|
||||
}
|
||||
if (vmRef !== undefined) {
|
||||
return xapi.VM_destroy(vmRef)
|
||||
if (vm?.$ref !== undefined) {
|
||||
return xapi.VM_destroy(vm.$ref)
|
||||
} else {
|
||||
return asyncMap(
|
||||
vdis.map(async ({ $ref }) => {
|
||||
|
||||
@@ -33,7 +33,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
|
||||
let metadata = await this._isAlreadyTransferred(timestamp)
|
||||
if (metadata !== undefined) {
|
||||
// @todo : should skip backup while being vigilant to not stuck the forked stream
|
||||
Task.info('This backup has already been transfered')
|
||||
Task.info('This backup has already been transferred')
|
||||
}
|
||||
|
||||
const oldBackups = getOldEntries(
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AbstractIncrementalWriter } from './_AbstractIncrementalWriter.mjs'
|
||||
import { MixinXapiWriter } from './_MixinXapiWriter.mjs'
|
||||
import { listReplicatedVms } from './_listReplicatedVms.mjs'
|
||||
import { COPY_OF, setVmOtherConfig, BASE_DELTA_VDI } from '../../_otherConfig.mjs'
|
||||
import assert from 'node:assert'
|
||||
|
||||
export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWriter) {
|
||||
async checkBaseVdis(baseUuidToSrcVdi) {
|
||||
@@ -25,7 +26,11 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
const replicatedVdis = sr.$VDIs
|
||||
.filter(vdi => {
|
||||
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
|
||||
return baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
|
||||
return (
|
||||
vdi?.managed &&
|
||||
!vdi?.is_a_snapshot /* only look for real vdi */ &&
|
||||
baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
|
||||
)
|
||||
})
|
||||
.map(({ other_config }) => other_config?.[COPY_OF])
|
||||
.filter(_ => !!_)
|
||||
@@ -108,17 +113,21 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
|
||||
const replicatedVdis = sr.$VDIs.filter(vdi => {
|
||||
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
|
||||
return sourceVdiUuids.includes(vdi?.other_config[COPY_OF])
|
||||
return vdi?.managed && !vdi?.is_a_snapshot && sourceVdiUuids.includes(vdi?.other_config[COPY_OF])
|
||||
})
|
||||
|
||||
Object.values(backup.vdis).forEach(vdi => {
|
||||
vdi.other_config[COPY_OF] = vdi.uuid
|
||||
if (sourceVdiUuids.length > 0) {
|
||||
const baseReplicatedTo = replicatedVdis.find(
|
||||
const baseReplicatedTo = replicatedVdis.filter(
|
||||
replicatedVdi => replicatedVdi.other_config[COPY_OF] === vdi.other_config[BASE_DELTA_VDI]
|
||||
)
|
||||
assert.ok(
|
||||
baseReplicatedTo.length <= 1,
|
||||
`Target of a replication must be unique, got ${baseReplicatedTo.length} candidates`
|
||||
)
|
||||
// baseReplicatedTo can be undefined if a new disk is added and other are already replicated
|
||||
vdi.baseVdi = baseReplicatedTo
|
||||
vdi.baseVdi = baseReplicatedTo[0]
|
||||
} else {
|
||||
// first replication of this disk
|
||||
vdi.baseVdi = undefined
|
||||
|
||||
@@ -99,7 +99,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
|
||||
srUuid,
|
||||
xapi,
|
||||
settings: {
|
||||
additionnalVmTag: 'xo:no-bak=Health Check',
|
||||
additionalVmTag: 'xo:no-bak=Health Check',
|
||||
},
|
||||
}).run()
|
||||
let restoredVm
|
||||
|
||||
@@ -29,7 +29,7 @@ export const MixinXapiWriter = (BaseClass = Object) =>
|
||||
// the SR that the VM has been replicated on
|
||||
const sr = this._sr
|
||||
assert.notStrictEqual(sr, undefined, 'SR should be defined before making a health check')
|
||||
assert.notEqual(this._targetVmRef, undefined, 'A vm should have been transfered to be health checked')
|
||||
assert.notEqual(this._targetVmRef, undefined, 'A vm should have been transferred to be health checked')
|
||||
// copy VM
|
||||
return Task.run(
|
||||
{
|
||||
|
||||
@@ -18,6 +18,8 @@ function formatVmBackup(backup) {
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'xo-vm-backup',
|
||||
backupRepository: backup.backupRepositoryId,
|
||||
disks:
|
||||
backup.vhds === undefined
|
||||
? []
|
||||
@@ -38,8 +40,10 @@ function formatVmBackup(backup) {
|
||||
size: backup.size,
|
||||
timestamp: backup.timestamp,
|
||||
vm: {
|
||||
uuid: backup.vm.uuid,
|
||||
name_description: backup.vm.name_description,
|
||||
name_label: backup.vm.name_label,
|
||||
tags: backup.vm.tags,
|
||||
},
|
||||
|
||||
differencingVhds,
|
||||
@@ -48,7 +52,12 @@ function formatVmBackup(backup) {
|
||||
}
|
||||
}
|
||||
|
||||
// format all backups as returned by RemoteAdapter#listAllVmBackups()
|
||||
export function formatVmBackups(backupsByVM) {
|
||||
return mapValues(backupsByVM, backups => backups.map(formatVmBackup))
|
||||
/**
|
||||
* format all backups as returned by RemoteAdapter#listAllVmBackups()
|
||||
* @param {Record<string, object[]>} backupsByVM
|
||||
* @param {string} backupRepositoryId
|
||||
* @returns {Record<string, object[]>}
|
||||
*/
|
||||
export function formatVmBackups(backupsByVM, backupRepositoryId) {
|
||||
return mapValues(backupsByVM, backups => backups.map(backup => formatVmBackup({ ...backup, backupRepositoryId })))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "0.63.0",
|
||||
"version": "0.67.2",
|
||||
"engines": {
|
||||
"node": ">=14.18"
|
||||
},
|
||||
@@ -19,20 +19,20 @@
|
||||
"dependencies": {
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@kldzj/stream-throttle": "^1.1.1",
|
||||
"@vates/async-each": "^1.0.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"@vates/cached-dns.lookup": "^1.0.0",
|
||||
"@vates/compose": "^2.1.0",
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/fuse-vhd": "^2.1.2",
|
||||
"@vates/generator-toolbox": "^1.0.4",
|
||||
"@vates/nbd-client": "^3.1.4",
|
||||
"@vates/generator-toolbox": "^1.1.0",
|
||||
"@vates/nbd-client": "^3.2.2",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@xen-orchestra/async-map": "^0.1.2",
|
||||
"@xen-orchestra/disk-transform": "^1.1.0",
|
||||
"@xen-orchestra/fs": "^4.6.2",
|
||||
"@xen-orchestra/disk-transform": "^1.2.1",
|
||||
"@xen-orchestra/fs": "^4.6.5",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"@xen-orchestra/qcow2": "^1.0.0",
|
||||
"@xen-orchestra/qcow2": "^1.1.1",
|
||||
"@xen-orchestra/template": "^0.1.0",
|
||||
"app-conf": "^3.0.0",
|
||||
"compare-versions": "^6.0.0",
|
||||
@@ -51,18 +51,18 @@
|
||||
"tar": "^6.1.15",
|
||||
"uuid": "^9.0.0",
|
||||
"value-matcher": "^0.2.0",
|
||||
"vhd-lib": "^4.14.0",
|
||||
"xen-api": "^4.7.3",
|
||||
"vhd-lib": "^4.14.6",
|
||||
"xen-api": "^4.7.6",
|
||||
"yazl": "^2.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"fs-extra": "^11.1.0",
|
||||
"rimraf": "^5.0.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"sinon": "^18.0.0",
|
||||
"tmp": "^0.2.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@xen-orchestra/xapi": "^8.3.3"
|
||||
"@xen-orchestra/xapi": "^8.6.3"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"preferGlobal": true,
|
||||
"dependencies": {
|
||||
"golike-defer": "^0.5.1",
|
||||
"xen-api": "^4.7.3"
|
||||
"xen-api": "^4.7.6"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish"
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "@xen-orchestra/disk-transform",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.1",
|
||||
"main": "./dist/index.mjs",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"rimraf": "^5.0.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"@types/node": "^22.3.0",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.23.0"
|
||||
@@ -34,7 +34,7 @@
|
||||
"node": ">=20.17"
|
||||
},
|
||||
"dependencies": {
|
||||
"vhd-lib": "^4.14.0",
|
||||
"@vates/generator-toolbox": "^1.0.4"
|
||||
"vhd-lib": "^4.14.6",
|
||||
"@vates/generator-toolbox": "^1.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ export class DiskSmallerBlock extends DiskPassthrough {
|
||||
#blockSize
|
||||
#generatedDiskBlocks = 0
|
||||
#blockCache?: DiskBlock
|
||||
#blockRatio: number
|
||||
#maxBlockIndex: number
|
||||
|
||||
constructor(source: Disk, blockSize: number) {
|
||||
super(source)
|
||||
@@ -17,9 +19,11 @@ export class DiskSmallerBlock extends DiskPassthrough {
|
||||
assert.strictEqual(
|
||||
source.getBlockSize() % blockSize,
|
||||
0,
|
||||
`target block size ${blockSize} must be a multiple of the source block size ${source.getBlockSize()} `
|
||||
`source block size ${blockSize} must be a multiple of the target block size ${source.getBlockSize()} `
|
||||
)
|
||||
this.#blockSize = blockSize
|
||||
this.#blockRatio = source.getBlockSize() / blockSize
|
||||
this.#maxBlockIndex = Math.ceil(this.getVirtualSize() / this.getBlockSize())
|
||||
}
|
||||
|
||||
openSource(): Promise<Disk> {
|
||||
@@ -35,13 +39,19 @@ export class DiskSmallerBlock extends DiskPassthrough {
|
||||
try {
|
||||
const blockRatio = this.source.getBlockSize() / this.#blockSize
|
||||
const sourceGenerator = this.source.diskBlocks()
|
||||
// we don't reuse getBlockIndexes here since we want don't want to force
|
||||
// a use of source.readblock that would limit the use of this class to RandomeAccessDisk
|
||||
// thus we generate block based on the source block generator
|
||||
for await (const { data: sourceData, index: sourceIndex } of sourceGenerator) {
|
||||
for (let i = 0; i < blockRatio; i++) {
|
||||
this.#generatedDiskBlocks++
|
||||
const data = sourceData.subarray(i * this.#blockSize, (i + 1) * this.#blockSize)
|
||||
yield {
|
||||
index: sourceIndex * blockRatio + i,
|
||||
data,
|
||||
const index = sourceIndex * blockRatio + i
|
||||
if (this.#isBlockBeforeEnd(index)) {
|
||||
yield {
|
||||
index,
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,15 +64,22 @@ export class DiskSmallerBlock extends DiskPassthrough {
|
||||
getBlockSize(): number {
|
||||
return this.#blockSize
|
||||
}
|
||||
// changing the block size can lead
|
||||
// to the last block being incomplete
|
||||
// for example going for a block size of 1024 to 512
|
||||
// and a virtual size of 1200 means 2 blocks in source,
|
||||
// but 3 here
|
||||
#isBlockBeforeEnd(blockIndex: number): boolean {
|
||||
return blockIndex < this.#maxBlockIndex
|
||||
}
|
||||
getBlockIndexes(): Array<number> {
|
||||
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
|
||||
const sourceIndexes = this.source.getBlockIndexes()
|
||||
const indexes: Array<number> = []
|
||||
const maxIndex = Math.ceil(this.getVirtualSize() / this.getBlockSize())
|
||||
for (const sourceIndex of sourceIndexes) {
|
||||
for (let i = 0; i < blockRatio; i++) {
|
||||
const index = sourceIndex * blockRatio + i
|
||||
if (index < maxIndex) {
|
||||
if (this.#isBlockBeforeEnd(index)) {
|
||||
indexes.push(index)
|
||||
}
|
||||
}
|
||||
@@ -71,13 +88,28 @@ export class DiskSmallerBlock extends DiskPassthrough {
|
||||
}
|
||||
|
||||
hasBlock(index: number): boolean {
|
||||
// asking for a block after the end of the smaller disk => false
|
||||
if (!this.#isBlockBeforeEnd(index)) {
|
||||
return false
|
||||
}
|
||||
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
|
||||
const sourceIndex = Math.floor(index / blockRatio)
|
||||
return this.source.hasBlock(sourceIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
* handle gracefully readblock if the source is a RandomAccessDisk
|
||||
* @param index
|
||||
* @returns Promise<DiskBlock>
|
||||
*/
|
||||
|
||||
async readBlock(index: number): Promise<DiskBlock> {
|
||||
if (this.source instanceof RandomAccessDisk) {
|
||||
if (!this.#isBlockBeforeEnd(index)) {
|
||||
throw new Error(
|
||||
`Read after the end, asking for ${index}, last block is ${this.#maxBlockIndex - 1}, vitual size is ${this.getVirtualSize()}, blockSize : ${this.getBlockSize()}`
|
||||
)
|
||||
}
|
||||
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
|
||||
const sourceBlockIndex = Math.floor(index / blockRatio)
|
||||
const indexInblock = index % blockRatio
|
||||
|
||||
@@ -160,8 +160,8 @@ test('hasBlock behavior', async () => {
|
||||
|
||||
test('getBlockIndexes', async () => {
|
||||
const source = new MockDisk(512, 2048, [
|
||||
[0, Buffer.alloc(512)],
|
||||
[2, Buffer.alloc(512)],
|
||||
[0, Buffer.alloc(2048)],
|
||||
[2, Buffer.alloc(2048)],
|
||||
])
|
||||
await source.init()
|
||||
|
||||
@@ -182,3 +182,28 @@ test('close propagation', async () => {
|
||||
await disk.close()
|
||||
assert(source.closed)
|
||||
})
|
||||
|
||||
test('unaligned END ', async () => {
|
||||
const source = new MockDisk(1024, 2048 + 256, [
|
||||
[0, Buffer.alloc(1024)],
|
||||
[2, Buffer.alloc(1024)],
|
||||
])
|
||||
await source.init()
|
||||
|
||||
const disk = new DiskSmallerBlock(source, 256)
|
||||
await disk.init()
|
||||
assert.strictEqual(source.getVirtualSize(), disk.getVirtualSize())
|
||||
|
||||
const indexes = disk.getBlockIndexes()
|
||||
const expecteBlockIndex = [0, 1, 2, 3, 8]
|
||||
assert.deepStrictEqual(indexes, expecteBlockIndex)
|
||||
assert.strictEqual(disk.hasBlock(8), true)
|
||||
assert.strictEqual(disk.hasBlock(9), false) //After the end of small block disk
|
||||
assert.strictEqual(disk.hasBlock(12), false) //After the end of source disk
|
||||
|
||||
// ensure disk blocks also handle the unaligned part
|
||||
for await (const { index, data } of disk.diskBlocks()) {
|
||||
assert.ok(expecteBlockIndex.includes(index))
|
||||
assert.equal(data.length, 256)
|
||||
}
|
||||
})
|
||||
|
||||
26
@xen-orchestra/disk-transform/src/Throttled.mts
Normal file
26
@xen-orchestra/disk-transform/src/Throttled.mts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import { Disk, DiskBlock } from './Disk.mjs'
|
||||
import { DiskPassthrough } from './DiskPassthrough.mjs'
|
||||
|
||||
export class ThrottledDisk extends DiskPassthrough {
|
||||
#throttle: Throttle
|
||||
constructor(source: Disk, throttle: Throttle) {
|
||||
super(source)
|
||||
this.#throttle = throttle
|
||||
}
|
||||
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
|
||||
const generator = await this.source.buildDiskBlockGenerator()
|
||||
//throttle want to be able to know the length of the data
|
||||
async function* generatorWithLength() {
|
||||
for await (const { index, data } of generator) {
|
||||
yield {
|
||||
index,
|
||||
data,
|
||||
length: data.length,
|
||||
}
|
||||
}
|
||||
}
|
||||
const throttledGenerator = this.#throttle.createThrottledGenerator(generatorWithLength())
|
||||
return throttledGenerator as AsyncGenerator<DiskBlock>
|
||||
}
|
||||
}
|
||||
16
@xen-orchestra/disk-transform/src/Timeout.mts
Normal file
16
@xen-orchestra/disk-transform/src/Timeout.mts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Timeout } from '@vates/generator-toolbox'
|
||||
import { Disk, DiskBlock } from './Disk.mjs'
|
||||
import { DiskPassthrough } from './DiskPassthrough.mjs'
|
||||
|
||||
export class TimeoutDisk extends DiskPassthrough {
|
||||
#timeout: number
|
||||
constructor(source: Disk, timeout: number) {
|
||||
super(source)
|
||||
this.#timeout = timeout
|
||||
}
|
||||
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
|
||||
const generator = await this.source.buildDiskBlockGenerator()
|
||||
const timeoutedGenerator = new Timeout(generator, this.#timeout)
|
||||
return timeoutedGenerator
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,6 @@ export { DiskPassthrough, RandomDiskPassthrough } from './DiskPassthrough.mjs'
|
||||
export { RawDisk } from './RawDisk.mjs'
|
||||
export { ReadAhead } from './ReadAhead.mjs'
|
||||
export { SynchronizedDisk } from './SynchronizedDisk.mjs'
|
||||
export { TimeoutDisk } from './Timeout.mjs'
|
||||
export { ThrottledDisk } from './Throttled.mjs'
|
||||
export { ProgressHandler } from './ProgressHandler.mjs'
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"moduleResolution": "bundler",
|
||||
"target": "es2022",
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"], // Only use types from Node.js and packages that are explicitly imported
|
||||
"declaration": true // Generates `.d.ts` files for type safety
|
||||
},
|
||||
"include": ["./src/**/*"],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/fs",
|
||||
"version": "4.6.2",
|
||||
"version": "4.6.5",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "The File System for Xen Orchestra backups.",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
|
||||
@@ -26,10 +26,10 @@
|
||||
"@aws-sdk/middleware-apply-body-checksum": "^3.58.0",
|
||||
"@aws-sdk/node-http-handler": "^3.54.0",
|
||||
"@azure/storage-blob": "^12.26.0",
|
||||
"@vates/async-each": "^1.0.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"@vates/coalesce-calls": "^0.1.0",
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@vates/read-chunk": "^1.2.0",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"bind-property-descriptor": "^2.0.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
@@ -52,7 +52,7 @@
|
||||
"@babel/preset-env": "^7.8.0",
|
||||
"cross-env": "^7.0.2",
|
||||
"dotenv": "^16.0.0",
|
||||
"rimraf": "^5.0.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"sinon": "^18.0.0",
|
||||
"tmp": "^0.2.1"
|
||||
},
|
||||
|
||||
@@ -13,7 +13,8 @@ import { synchronized } from 'decorator-synchronized'
|
||||
import { withTimeout } from './utils'
|
||||
import { basename, dirname, normalize as normalizePath } from './path'
|
||||
import { createChecksumStream, validChecksumOfReadStream } from './checksum'
|
||||
import { DEFAULT_ENCRYPTION_ALGORITHM, UNENCRYPTED_ALGORITHM, _getEncryptor } from './_encryptor'
|
||||
import { UNENCRYPTED_ALGORITHM, _getEncryptor } from './_encryptor'
|
||||
import { FsEncryptor } from './encryptors/FsEncryptor'
|
||||
|
||||
const { info, warn } = createLogger('xo:fs:abstract')
|
||||
|
||||
@@ -23,12 +24,9 @@ const computeRate = (hrtime, size) => {
|
||||
return size / seconds
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT = 6e5 // 10 min
|
||||
const DEFAULT_TIMEOUT = 12e5 // 20 min
|
||||
const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
|
||||
|
||||
const ENCRYPTION_DESC_FILENAME = 'encryption.json'
|
||||
const ENCRYPTION_METADATA_FILENAME = 'metadata.json'
|
||||
|
||||
const WITH_LIMIT = [
|
||||
'closeFile',
|
||||
'copy',
|
||||
@@ -48,24 +46,31 @@ const WITH_LIMIT = [
|
||||
'writeFile',
|
||||
]
|
||||
|
||||
const WITH_RETRY = [
|
||||
'_closeFile',
|
||||
'_copy',
|
||||
'_getInfo',
|
||||
'_getSize',
|
||||
'_list',
|
||||
'_mkdir',
|
||||
'_openFile',
|
||||
'_outputFile',
|
||||
'_read',
|
||||
'_readFile',
|
||||
'_rename',
|
||||
'_rmdir',
|
||||
'_truncate',
|
||||
'_unlink',
|
||||
'_write',
|
||||
'_writeFile',
|
||||
]
|
||||
const WITH_RETRY = {
|
||||
_closeFile: {},
|
||||
_copy: {},
|
||||
_getInfo: {},
|
||||
_getSize: {},
|
||||
_list: {},
|
||||
_mkdir: {},
|
||||
_openFile: {},
|
||||
_read: {},
|
||||
_readFile: {},
|
||||
_rename: {},
|
||||
_rmdir: {},
|
||||
_truncate: {},
|
||||
_unlink: {},
|
||||
_write: {},
|
||||
_writeFile: {
|
||||
updateArguments(error, [file, data, options]) {
|
||||
options = options ?? {}
|
||||
if (options.flags === 'wx' && error.code !== 'EEXIST') {
|
||||
options.flags = 'w'
|
||||
}
|
||||
return [file, data, options]
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const WITH_TIMEOUT = [
|
||||
'_closeFile',
|
||||
@@ -157,7 +162,7 @@ export default class RemoteHandlerAbstract {
|
||||
this.#applySafeGuards(options)
|
||||
}
|
||||
|
||||
#conditionRetry(error) {
|
||||
_conditionRetry(error) {
|
||||
return !['EEXIST', 'EISDIR', 'ENOTEMPTY', 'ENOENT', 'ENOTDIR', 'SystemInUse', 'ERR_ASSERTION'].includes(error?.code)
|
||||
}
|
||||
|
||||
@@ -179,14 +184,14 @@ export default class RemoteHandlerAbstract {
|
||||
}
|
||||
})
|
||||
|
||||
this._withRetry.forEach(functionName => {
|
||||
Object.entries(this._withRetry).forEach(([functionName, retryOpts]) => {
|
||||
if (this[functionName] !== undefined) {
|
||||
// adding the retry on the top level method won't
|
||||
// cover when _functionName are called internally
|
||||
this[functionName] = pRetry.wrap(this[functionName], {
|
||||
delays: [100, 200, 500, 1000, 2000],
|
||||
// these errors should not change on retry
|
||||
when: err => this.#conditionRetry(err),
|
||||
when: err => this._conditionRetry(err),
|
||||
onRetry(error) {
|
||||
warn('retrying method on fs ', {
|
||||
method: functionName,
|
||||
@@ -194,7 +199,15 @@ export default class RemoteHandlerAbstract {
|
||||
delay: this.delay,
|
||||
error,
|
||||
file: this.arguments?.[0],
|
||||
retryOpts,
|
||||
})
|
||||
if (retryOpts.updateArguments) {
|
||||
warn('updating arguments ', {
|
||||
method: functionName,
|
||||
attemptNumber: this.attemptNumber,
|
||||
})
|
||||
this.arguments = retryOpts.updateArguments(error, this.arguments)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -357,7 +370,7 @@ export default class RemoteHandlerAbstract {
|
||||
}
|
||||
|
||||
async outputFile(file, data, { dirMode, flags = 'wx' } = {}) {
|
||||
const encryptedData = this.#encryptor.encryptData(data)
|
||||
const encryptedData = await this.#encryptor.encryptBuffer(data)
|
||||
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
|
||||
}
|
||||
|
||||
@@ -368,7 +381,7 @@ export default class RemoteHandlerAbstract {
|
||||
|
||||
async __readFile(file, { flags = 'r' } = {}) {
|
||||
const data = await this._readFile(normalizePath(file), { flags })
|
||||
return this.#encryptor.decryptData(data)
|
||||
return this.#encryptor.decryptBuffer(data)
|
||||
}
|
||||
|
||||
async #rename(oldPath, newPath, { checksum }, createTree = true) {
|
||||
@@ -419,75 +432,15 @@ export default class RemoteHandlerAbstract {
|
||||
async sync() {
|
||||
await this._sync()
|
||||
try {
|
||||
await this.#checkMetadata()
|
||||
const encryptor = new FsEncryptor(this)
|
||||
await encryptor.init()
|
||||
this.#rawEncryptor = encryptor
|
||||
console.log('UDPATE', encryptor)
|
||||
await encryptor.updateEncryptionMetadata()
|
||||
} catch (error) {
|
||||
await this._forget()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async #canWriteMetadata() {
|
||||
const list = await this.__list('/', {
|
||||
filter: e => !e.startsWith('.') && e !== ENCRYPTION_DESC_FILENAME && e !== ENCRYPTION_METADATA_FILENAME,
|
||||
})
|
||||
return list.length === 0
|
||||
}
|
||||
|
||||
async #createMetadata() {
|
||||
const encryptionAlgorithm = this._remote.encryptionKey === undefined ? 'none' : DEFAULT_ENCRYPTION_ALGORITHM
|
||||
this.#rawEncryptor = _getEncryptor(encryptionAlgorithm, this._remote.encryptionKey)
|
||||
|
||||
await Promise.all([
|
||||
this._writeFile(normalizePath(ENCRYPTION_DESC_FILENAME), JSON.stringify({ algorithm: encryptionAlgorithm }), {
|
||||
flags: 'w',
|
||||
}), // not encrypted
|
||||
this.__writeFile(ENCRYPTION_METADATA_FILENAME, `{"random":"${randomUUID()}"}`, { flags: 'w' }), // encrypted
|
||||
])
|
||||
}
|
||||
|
||||
async #checkMetadata() {
|
||||
let encryptionAlgorithm = 'none'
|
||||
let data
|
||||
try {
|
||||
// this file is not encrypted
|
||||
data = await this._readFile(normalizePath(ENCRYPTION_DESC_FILENAME))
|
||||
const json = JSON.parse(data)
|
||||
encryptionAlgorithm = json.algorithm
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
encryptionAlgorithm = this._remote.encryptionKey === undefined ? 'none' : DEFAULT_ENCRYPTION_ALGORITHM
|
||||
}
|
||||
|
||||
try {
|
||||
this.#rawEncryptor = _getEncryptor(encryptionAlgorithm, this._remote.encryptionKey)
|
||||
// this file is encrypted
|
||||
const data = await this.__readFile(ENCRYPTION_METADATA_FILENAME)
|
||||
JSON.parse(data)
|
||||
} catch (error) {
|
||||
// can be enoent, bad algorithm, or broken json ( bad key or algorithm)
|
||||
if (encryptionAlgorithm !== 'none') {
|
||||
if (await this.#canWriteMetadata()) {
|
||||
// any other error , but on empty remote => update with remote settings
|
||||
|
||||
info('will update metadata of this remote')
|
||||
return this.#createMetadata()
|
||||
} else {
|
||||
// to add a new encrypted fs remote, the remote directory must be empty; otherwise, metadata.json is not created
|
||||
if (error.code === 'ENOENT' && error.path.includes('metadata.json')) {
|
||||
throw new Error('Remote directory must be empty.')
|
||||
}
|
||||
|
||||
warn(
|
||||
`The encryptionKey settings of this remote does not match the key used to create it. You won't be able to read any data from this remote`,
|
||||
{ error }
|
||||
)
|
||||
// will probably send a ERR_OSSL_EVP_BAD_DECRYPT if key is incorrect
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async test() {
|
||||
@@ -546,7 +499,7 @@ export default class RemoteHandlerAbstract {
|
||||
}
|
||||
|
||||
async __writeFile(file, data, { flags = 'wx' } = {}) {
|
||||
const encryptedData = this.#encryptor.encryptData(data)
|
||||
const encryptedData = this.#encryptor.encryptBuffer(data)
|
||||
await this._writeFile(normalizePath(file), encryptedData, { flags })
|
||||
}
|
||||
|
||||
@@ -766,7 +719,7 @@ export default class RemoteHandlerAbstract {
|
||||
}
|
||||
|
||||
get isEncrypted() {
|
||||
return this.#encryptor.id !== 'NULL_ENCRYPTOR'
|
||||
return this.#encryptor.algorithm !== 'NULL_ENCRYPTOR'
|
||||
}
|
||||
|
||||
get encryptionAlgorithm() {
|
||||
|
||||
@@ -10,7 +10,7 @@ import AbstractHandler from './abstract'
|
||||
import fs from 'fs-extra'
|
||||
import tmp from 'tmp'
|
||||
|
||||
const TIMEOUT = 6e5
|
||||
const TIMEOUT = 12e5
|
||||
|
||||
class TestHandler extends AbstractHandler {
|
||||
constructor() {
|
||||
@@ -22,39 +22,32 @@ class TestHandler extends AbstractHandler {
|
||||
}
|
||||
|
||||
async _closeFile() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _getInfo() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _getSize() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _list() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _openFile() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _rename() {
|
||||
Promise(() => {})
|
||||
}
|
||||
async _rmdir() {
|
||||
Promise(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
const clock = sinon.useFakeTimers()
|
||||
|
||||
/*
|
||||
describe('closeFile()', () => {
|
||||
it(`throws in case of timeout`, async () => {
|
||||
const testHandler = new TestHandler()
|
||||
|
||||
const promise = testHandler.closeFile({ fd: undefined, path: '' })
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -64,7 +57,7 @@ describe('getInfo()', () => {
|
||||
|
||||
const promise = testHandler.getInfo()
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -74,7 +67,7 @@ describe('getSize()', () => {
|
||||
|
||||
const promise = testHandler.getSize('')
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -84,7 +77,7 @@ describe('list()', () => {
|
||||
|
||||
const promise = testHandler.list('.')
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -94,7 +87,7 @@ describe('openFile()', () => {
|
||||
|
||||
const promise = testHandler.openFile('path')
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -104,7 +97,7 @@ describe('rename()', () => {
|
||||
|
||||
const promise = testHandler.rename('oldPath', 'newPath')
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -114,10 +107,10 @@ describe('rmdir()', () => {
|
||||
|
||||
const promise = testHandler.rmdir('dir')
|
||||
clock.tick(TIMEOUT)
|
||||
await assert.rejects(promise, TimeoutError)
|
||||
await assert.rejects(promise, new TimeoutError())
|
||||
})
|
||||
})
|
||||
|
||||
*/
|
||||
describe('encryption', () => {
|
||||
let dir
|
||||
beforeEach(async () => {
|
||||
@@ -147,19 +140,22 @@ describe('encryption', () => {
|
||||
assert.rejects(async () => JSON.parse(await fs.readFile(`${dir}/metadata.json`)))
|
||||
})
|
||||
|
||||
it('sync should not modify existing metadata', async () => {
|
||||
it('sync should not modify existing metadata if check fails', async () => {
|
||||
await fs.writeFile(`${dir}/encryption.json`, `{"algorithm": "none"}`)
|
||||
await fs.writeFile(`${dir}/metadata.json`, `{"random": "NOTSORANDOM"}`)
|
||||
|
||||
await Disposable.use(await getSyncedHandler({ url: `file://${dir}` }), noop)
|
||||
|
||||
await assert.rejects(()=> getSyncedHandler({ url: `file://${dir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd00` }))
|
||||
const encryption = JSON.parse(await fs.readFile(`${dir}/encryption.json`, 'utf-8'))
|
||||
assert.equal(encryption.algorithm, 'none')
|
||||
const metadata = JSON.parse(await fs.readFile(`${dir}/metadata.json`, 'utf-8'))
|
||||
assert.equal(metadata.random, 'NOTSORANDOM')
|
||||
})
|
||||
|
||||
it('should modify metadata if empty', async () => {
|
||||
|
||||
await assert.doesNotReject(()=> getSyncedHandler({ url: `file://${dir}` }))
|
||||
})
|
||||
|
||||
it('should modify metadata if empty and check fails', async () => {
|
||||
await Disposable.use(getSyncedHandler({ url: `file://${dir}` }), noop)
|
||||
// nothing created without encryption
|
||||
|
||||
@@ -174,6 +170,7 @@ describe('encryption', () => {
|
||||
encryption = JSON.parse(await fs.readFile(`${dir}/encryption.json`, 'utf-8'))
|
||||
assert.equal(encryption.algorithm, 'none')
|
||||
})
|
||||
/*
|
||||
|
||||
it(
|
||||
'sync should work with encrypted',
|
||||
@@ -224,5 +221,5 @@ describe('encryption', () => {
|
||||
await assert.rejects(
|
||||
Disposable.use(getSyncedHandler({ url: `file://${dir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd91"` }), noop)
|
||||
)
|
||||
})
|
||||
})
|
||||
})*/
|
||||
})
|
||||
140
@xen-orchestra/fs/src/encryptors/AbstractEncryptor.js
Normal file
140
@xen-orchestra/fs/src/encryptors/AbstractEncryptor.js
Normal file
@@ -0,0 +1,140 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {import('node:stream').Readable} Readable
|
||||
*/
|
||||
import { randomUUID } from 'crypto'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
|
||||
export const CHACHA20 = 'chacha20-poly1305'
|
||||
export const AES256 = 'aes-256-gcm'
|
||||
export const DEFAULT_ENCRYPTION_ALGORITHM = CHACHA20
|
||||
export const UNENCRYPTED_ALGORITHM = 'none'
|
||||
export const SUPPORTED_ALGORITHM = new Set([UNENCRYPTED_ALGORITHM, AES256, CHACHA20, DEFAULT_ENCRYPTION_ALGORITHM])
|
||||
|
||||
export const LEGACY_UPDATE_MODE = 'single'
|
||||
export const ENCRYPTION_DESC_FILENAME = '/encryption.json'
|
||||
export const ENCRYPTION_METADATA_FILENAME = '/metadata.json'
|
||||
|
||||
const { warn } = createLogger('xo:fs:encryptor:abstract')
|
||||
export class AbstractEncryptor {
|
||||
#handler
|
||||
|
||||
constructor(handler) {
|
||||
this.#handler = handler
|
||||
}
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async init() {
|
||||
|
||||
}
|
||||
/**
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
encryptStream(stream) {
|
||||
throw new Error('not implemented')
|
||||
}
|
||||
/**
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
decryptStream(stream) {
|
||||
throw new Error('not implemented')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
encryptBuffer(buffer) {
|
||||
throw new Error('not implemented')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
decryptBuffer(buffer) {
|
||||
throw new Error('not implemented')
|
||||
}
|
||||
|
||||
/**
|
||||
*update the key and algorithm used
|
||||
* @param {Buffer} key
|
||||
* @param {string} algorithm
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async updateEncryptionKey(key, algorithm) {
|
||||
throw new Error('not implemented')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} algorithm
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async updateEncryptionMetadata( algorithm) {
|
||||
if(algorithm === 'none'){
|
||||
await Promise.all([
|
||||
// this one is not encrypted,but only contains the algorithm
|
||||
this.#handler.unlink(ENCRYPTION_DESC_FILENAME),
|
||||
// this one is encrypted and used as an encryption test
|
||||
this.#handler.unlink(ENCRYPTION_METADATA_FILENAME)
|
||||
])
|
||||
} else {
|
||||
await Promise.all([
|
||||
// this one is not encrypted,but only contains the algorithm
|
||||
this.#handler._writeFile(ENCRYPTION_DESC_FILENAME, JSON.stringify({ algorithm }), {
|
||||
flags: 'w',
|
||||
}),
|
||||
// this one is encrypted and used as an encryption test
|
||||
this.#handler.__writeFile(ENCRYPTION_METADATA_FILENAME, `{"random":"${randomUUID()}"}`, { flags: 'w' }),
|
||||
])
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async check() {
|
||||
try {
|
||||
const encryptedRawData = await this.#handler._readFile(ENCRYPTION_METADATA_FILENAME)
|
||||
const decrypted = this.decryptBuffer(encryptedRawData).toString()
|
||||
JSON.parse(decrypted)
|
||||
} catch (error) {
|
||||
if(error.code ==='ENOENT'){
|
||||
// an empty remote that has just been created
|
||||
return
|
||||
}
|
||||
console.log('ERROR', error.code)
|
||||
warn(
|
||||
`The encryptionKey settings of this remote does not match the key used to create it. You won't be able to read any data from this remote`,
|
||||
{ error } )
|
||||
// will probably send a ERR_OSSL_EVP_BAD_DECRYPT if key is incorrect
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<{algorithm:string, updateMode: string}>}
|
||||
*/
|
||||
async getEncryptionMetadata() {
|
||||
try {
|
||||
// read file unencrypted
|
||||
const data = await this.#handler._readFile(ENCRYPTION_DESC_FILENAME)
|
||||
const json = JSON.parse(data)
|
||||
console.log({json, data})
|
||||
return { algorithm: json.algorithm, updateMode: json.updateMode ?? LEGACY_UPDATE_MODE}
|
||||
} catch (error) {
|
||||
|
||||
if (error.code === 'ENOENT'){
|
||||
if(this.#handler._remote.encryptionKey){
|
||||
return { algorithm: DEFAULT_ENCRYPTION_ALGORITHM, updateMode: LEGACY_UPDATE_MODE }
|
||||
}
|
||||
return { algorithm: 'none', updateMode: LEGACY_UPDATE_MODE }
|
||||
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
64
@xen-orchestra/fs/src/encryptors/AbstractEncryptor.test.js
Normal file
64
@xen-orchestra/fs/src/encryptors/AbstractEncryptor.test.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import assert from 'node:assert'
|
||||
import { suite, test } from 'node:test'
|
||||
import { AbstractEncryptor, ENCRYPTION_DESC_FILENAME, ENCRYPTION_METADATA_FILENAME } from './AbstractEncryptor.js'
|
||||
|
||||
class MockFs {
|
||||
files = {}
|
||||
_remote = {
|
||||
encryptionKey: undefined,
|
||||
}
|
||||
async _readFile(path) {
|
||||
if (!this.files[path]) {
|
||||
const error = new Error('Not here')
|
||||
error.code = 'ENOENT'
|
||||
throw error
|
||||
}
|
||||
return Promise.resolve(Buffer.from(this.files[path]))
|
||||
}
|
||||
async _writeFile(path, buffer) {
|
||||
this.files[path] = buffer
|
||||
return Promise.resolve()
|
||||
}
|
||||
async __writeFile(path, buffer) {
|
||||
this.files[path] = 'encrypted' + buffer
|
||||
return Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
suite('it should handle metadata', async () => {
|
||||
test('it should return none on empty remote ', async () => {
|
||||
const encryptor = new AbstractEncryptor(new MockFs())
|
||||
const { algorithm } = await encryptor.getAlgorithm()
|
||||
assert.strictEqual(algorithm, 'none')
|
||||
})
|
||||
test('it should read the agorithm if set ', async () => {
|
||||
const fs = new MockFs()
|
||||
fs.files[ENCRYPTION_DESC_FILENAME] = JSON.stringify({ algorithm: 'securealgorithm' })
|
||||
const encryptor = new AbstractEncryptor(fs)
|
||||
const { algorithm } = await encryptor.getAlgorithm()
|
||||
assert.strictEqual(algorithm, 'securealgorithm')
|
||||
})
|
||||
test('it should fail if no metadata file on encrypted ', async () => {
|
||||
const fs = new MockFs()
|
||||
fs._remote.encryptionKey = 'mysecurekey'
|
||||
const encryptor = new AbstractEncryptor(fs)
|
||||
await assert.rejects(() => encryptor.getAlgorithm(), { code: 'ENOENT' })
|
||||
})
|
||||
test('it should fail if no metadata file on encrypted ', async () => {
|
||||
const fs = new MockFs()
|
||||
fs._remote.encryptionKey = 'mysecurekey'
|
||||
const encryptor = new AbstractEncryptor(fs)
|
||||
await assert.rejects(() => encryptor.getAlgorithm(), { code: 'ENOENT' })
|
||||
})
|
||||
|
||||
test('it should update the metadata files correctly', async () => {
|
||||
const fs = new MockFs()
|
||||
const encryptor = new AbstractEncryptor(fs)
|
||||
await encryptor.updateEncryptionMetadata('one GOOD key', 'secure algo')
|
||||
let content = JSON.parse(await fs._readFile(ENCRYPTION_DESC_FILENAME))
|
||||
|
||||
assert.strictEqual(content.algorithm, 'secure algo')
|
||||
|
||||
content = await fs._readFile(ENCRYPTION_METADATA_FILENAME)
|
||||
})
|
||||
})
|
||||
102
@xen-orchestra/fs/src/encryptors/FsEncryptor.js
Normal file
102
@xen-orchestra/fs/src/encryptors/FsEncryptor.js
Normal file
@@ -0,0 +1,102 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {import('node:stream').Readable} Readable
|
||||
*/
|
||||
import { AbstractEncryptor } from './AbstractEncryptor.js'
|
||||
import { RollingEncryptor } from './RollingEncryptor.js'
|
||||
import { SingleEncryptor } from './SingleEncryptor.js'
|
||||
|
||||
export class FsEncryptor extends AbstractEncryptor {
|
||||
#handler
|
||||
/**
|
||||
* @type {SingleEncryptor| RollingEncryptor|undefined}
|
||||
*/
|
||||
#encryptor
|
||||
get encryptor(){
|
||||
if(this.#encryptor === undefined){
|
||||
throw new Error("Can't access encryptor before init")
|
||||
}
|
||||
return this.#encryptor
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {*} handler
|
||||
*/
|
||||
constructor(handler) {
|
||||
super(handler)
|
||||
this.#handler = handler
|
||||
}
|
||||
|
||||
async init() {
|
||||
await super.init()
|
||||
const { algorithm, updateMode } = await this.getEncryptionMetadata()
|
||||
console.log('received', { algorithm, updateMode })
|
||||
let encryptor
|
||||
switch (updateMode) {
|
||||
case 'rolling': {
|
||||
const currentEncryptor = new SingleEncryptor(this.#handler, algorithm)
|
||||
encryptor = new RollingEncryptor(currentEncryptor)
|
||||
break
|
||||
}
|
||||
case 'single':
|
||||
encryptor = new SingleEncryptor(this.#handler, algorithm)
|
||||
break
|
||||
default:
|
||||
throw new Error(`remote encryption mode ${updateMode} is not supported`)
|
||||
}
|
||||
await encryptor.init()
|
||||
// check if
|
||||
await encryptor.check()
|
||||
console.log(('CHECK OK ', { algorithm, updateMode }))
|
||||
this.#encryptor = encryptor
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} key
|
||||
* @param {string} algorithm
|
||||
* @returns
|
||||
*/
|
||||
|
||||
updateEncryptionKey(key, algorithm) {
|
||||
return this.encryptor.updateEncryptionKey(key, algorithm)
|
||||
}
|
||||
|
||||
|
||||
updateEncryptionMetadata() {
|
||||
return this.encryptor.updateEncryptionMetadata()
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
encryptBuffer(buffer) {
|
||||
return this.encryptor.encryptBuffer(buffer)
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
decryptBuffer(buffer) {
|
||||
return this.encryptor.decryptBuffer(buffer)
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
encryptStream(stream) {
|
||||
return this.encryptor.encryptStream(stream)
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
decryptStream(stream) {
|
||||
return this.encryptor.decryptStream(stream)
|
||||
}
|
||||
}
|
||||
251
@xen-orchestra/fs/src/encryptors/RollingEncryptor.js
Normal file
251
@xen-orchestra/fs/src/encryptors/RollingEncryptor.js
Normal file
@@ -0,0 +1,251 @@
|
||||
// @ts-check
|
||||
import assert from 'node:assert'
|
||||
import path from 'node:path'
|
||||
import { readChunkStrict } from '@vates/read-chunk'
|
||||
import { AbstractEncryptor, DEFAULT_ENCRYPTION_ALGORITHM } from './AbstractEncryptor.js'
|
||||
import { SingleEncryptor } from './SingleEncryptor.js'
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
const ENCRYPTOR_METADATA_BASEPATH = 'encryptors'
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {any} source
|
||||
* @param {number} length
|
||||
* @returns {string}
|
||||
*/
|
||||
function pad(source, length) {
|
||||
let res = String(source)
|
||||
while (res.length < length) {
|
||||
res = '0' + res
|
||||
}
|
||||
return res
|
||||
}
|
||||
export class RollingEncryptor extends AbstractEncryptor {
|
||||
get handler() {
|
||||
return this.#currentEncryptor.handler
|
||||
}
|
||||
/**
|
||||
* @type {Map<number, SingleEncryptor}
|
||||
*/
|
||||
#encryptorCache = new Map()
|
||||
/**
|
||||
* @type {number|undefined}
|
||||
*/
|
||||
#currentEncryptorKey
|
||||
|
||||
#currentEncryptor
|
||||
|
||||
/**
|
||||
* the current encryptor is the key to unlock recursively the full chain
|
||||
* @param handler
|
||||
* @param {SingleEncryptor} currentEncryptor
|
||||
*/
|
||||
constructor(currentEncryptor) {
|
||||
super(currentEncryptor.handler)
|
||||
this.#currentEncryptor = currentEncryptor
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async init() {
|
||||
await super.init()
|
||||
const encryptorsList = (await this.handler.list(ENCRYPTOR_METADATA_BASEPATH))
|
||||
.filter(name => name.match(/[0-9]{4}/))
|
||||
this.#currentEncryptorKey = encryptorsList.length + 1
|
||||
this.#encryptorCache.set(this.#currentEncryptorKey, this.#currentEncryptor)
|
||||
await this.#instantiateEncryptor(1) // this will try to load the full chain of key
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} encryptorIndex
|
||||
* @returns {Promise<SingleEncryptor>}
|
||||
*/
|
||||
async #instantiateEncryptor(encryptorIndex) {
|
||||
assert.notEqual(this.#currentEncryptorKey, undefined, `Encryptor index must have been init`)
|
||||
assert.ok(encryptorIndex > 0, `Encryptor index must be over zero`)
|
||||
|
||||
const encryptorInCache = this.#encryptorCache.get(encryptorIndex)
|
||||
if(encryptorInCache !== undefined){
|
||||
return Promise.resolve(encryptorInCache)
|
||||
}
|
||||
// ensure we don't have an infinite recursion
|
||||
assert.ok(encryptorIndex < this.#currentEncryptorKey, `Can't reinstantiate current encryptor ${encryptorIndex}, ${this.#currentEncryptorKey} `)
|
||||
|
||||
|
||||
// past encryptors are store one dis
|
||||
// encrypted with the next more recent encryptor
|
||||
try {
|
||||
const indexStr = String(encryptorIndex).padStart(4, '0')
|
||||
const encryptedByIndex = encryptorIndex+1
|
||||
const encryptedBy = await this.#instantiateEncryptor(encryptedByIndex)
|
||||
|
||||
// read raw data
|
||||
const data = await this.handler._readFile(path.join(ENCRYPTOR_METADATA_BASEPATH, indexStr))
|
||||
const decrypted = encryptedBy.decryptBuffer(data).toString()
|
||||
const { algorithm, key } = JSON.parse(decrypted)
|
||||
const encryptor = new SingleEncryptor(this.handler, algorithm, key)
|
||||
return encryptor
|
||||
} catch (error) {
|
||||
const visibleError = new Error(`Can't instantiate key ${encryptorIndex}`)
|
||||
visibleError.cause = error
|
||||
throw visibleError
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} encryptorIndex
|
||||
* @returns {SingleEncryptor}
|
||||
*/
|
||||
#getEncryptor(encryptorIndex) {
|
||||
let encryptor = this.#encryptorCache.get(encryptorIndex)
|
||||
if (encryptor === undefined) {
|
||||
throw new Error(`Encryptor index ${encryptorIndex} doe snot exists `)
|
||||
}
|
||||
|
||||
return encryptor
|
||||
}
|
||||
|
||||
/**
|
||||
* use the current encrypt to encrypt a buffer
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
encryptBuffer(buffer) {
|
||||
if (typeof buffer === 'string') {
|
||||
buffer = Buffer.from(buffer)
|
||||
}
|
||||
const encryptor = this.#currentEncryptor
|
||||
const keyBuffer = Buffer.alloc(4)
|
||||
keyBuffer.writeUInt32BE(this.#currentEncryptorKey)
|
||||
return Buffer.concat([
|
||||
keyBuffer,
|
||||
encryptor.encryptBuffer(
|
||||
Buffer.concat([
|
||||
keyBuffer, // add keybuffer to encrypted data to ensure it is authenticated
|
||||
buffer,
|
||||
])
|
||||
),
|
||||
])
|
||||
}
|
||||
/**
|
||||
* decrypt a buffer with the right encryptor
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
decryptBuffer(buffer) {
|
||||
if (buffer.length < 4) {
|
||||
throw new Error(`Can't decrypt a buffer so small, size:${buffer.length}`)
|
||||
}
|
||||
const encryptorIndex = buffer.readUInt32BE(0)
|
||||
const encryptor = this.#getEncryptor(encryptorIndex)
|
||||
const decrypted = encryptor.decryptBuffer(buffer.slice(4))
|
||||
|
||||
// check that the encryptor index has not been tampered with
|
||||
const authenticatedEncryptorIndex = decrypted.readUInt32BE(0)
|
||||
assert.strictEqual(authenticatedEncryptorIndex, encryptorIndex)
|
||||
return decrypted.slice(4)
|
||||
}
|
||||
|
||||
/**
|
||||
* use the current encrypt to encrypt a stream
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
encryptStream(stream) {
|
||||
const keyBuffer = Buffer.alloc(4)
|
||||
keyBuffer.writeUInt32BE(this.#currentEncryptorKey)
|
||||
|
||||
const encryptor = this.currentEncryptor
|
||||
|
||||
async function* generator() {
|
||||
yield keyBuffer
|
||||
for await (const data of encryptor.encryptStream(stream)) {
|
||||
yield data
|
||||
}
|
||||
}
|
||||
|
||||
return Readable.from(generator(), { objectMode: false, highWaterMark: 10 * 1024 * 1024 })
|
||||
}
|
||||
|
||||
/**
|
||||
* decrypt a stream with the right encryptor
|
||||
*
|
||||
* @param {Readable} stream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
async decryptStream(stream) {
|
||||
/**
|
||||
* @type {Buffer}
|
||||
*/
|
||||
const keyBuffer = await readChunkStrict(stream, 4)
|
||||
const encryptorIndex = keyBuffer.readUInt32BE(0)
|
||||
|
||||
const encryptor = this.#getEncryptor(encryptorIndex)
|
||||
const decryptedStream = await encryptor.decryptStream(stream)
|
||||
/**
|
||||
* @type {Buffer}
|
||||
*/
|
||||
const authenticatedKeyBuffer = await readChunkStrict(decryptedStream, 4)
|
||||
const authenticatedEncryptorIndex = authenticatedKeyBuffer.readUInt32BE(0)
|
||||
|
||||
assert.strictEqual(authenticatedEncryptorIndex, encryptorIndex)
|
||||
|
||||
async function* generator() {
|
||||
for await (const data of decryptedStream) {
|
||||
yield data
|
||||
}
|
||||
}
|
||||
return Readable.from(generator(), { objectMode: false, highWaterMark: 10 * 1024 * 1024 })
|
||||
}
|
||||
|
||||
/**
|
||||
* add a new encryptor to the chain
|
||||
* the previous encryptor is saved, encrypted by the new key
|
||||
*
|
||||
* @param {Buffer} key
|
||||
* @param {string} algorithm
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async updateEncryptionKey(key, algorithm = DEFAULT_ENCRYPTION_ALGORITHM) {
|
||||
// can only update the key if the current one is ok
|
||||
await this.check()
|
||||
|
||||
const previousEncryptor = this.#currentEncryptor
|
||||
const encryptor = new SingleEncryptor(this.handler, algorithm, key)
|
||||
|
||||
// same key and algorithm, no need to grow the key chain
|
||||
// compare from encryptors to ensure every key is a buffer
|
||||
if(encryptor.key.equals(previousEncryptor.key) && encryptor.algorithm === previousEncryptor.algorithm){
|
||||
return
|
||||
}
|
||||
|
||||
// write the old encryptor data encrypted with the new encryptor
|
||||
const previousEncryptorIndex = pad(this.#currentEncryptorKey, 4)
|
||||
await this.handler.__writeFile(
|
||||
path.join(ENCRYPTOR_METADATA_BASEPATH, previousEncryptorIndex),
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
algorithm: previousEncryptor.algorithm,
|
||||
key: previousEncryptor.key,
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
)
|
||||
)
|
||||
// set the new encryptor as the current one
|
||||
this.#currentEncryptorKey++
|
||||
this.#encryptorCache.set(this.#currentEncryptorKey, encryptor)
|
||||
this.#currentEncryptor = encryptor
|
||||
|
||||
await this.updateEncryptionMetadata()
|
||||
}
|
||||
|
||||
async updateEncryptionMetadata(){
|
||||
const algorithm = this.#currentEncryptor.algorithm
|
||||
super.updateEncryptionMetadata(algorithm)
|
||||
}
|
||||
}
|
||||
117
@xen-orchestra/fs/src/encryptors/RollingEncryptor.test.js
Normal file
117
@xen-orchestra/fs/src/encryptors/RollingEncryptor.test.js
Normal file
@@ -0,0 +1,117 @@
|
||||
import assert from 'node:assert'
|
||||
import { suite, test } from 'node:test'
|
||||
import { SingleEncryptor } from './SingleEncryptor.js'
|
||||
import { RollingEncryptor } from './RollingEncryptor.js'
|
||||
|
||||
class MockFs {
|
||||
files = {}
|
||||
encryptor
|
||||
_remote = {
|
||||
encryptionKey: undefined,
|
||||
}
|
||||
async _readFile(path) {
|
||||
if (!this.files[path]) {
|
||||
const error = new Error('Not here')
|
||||
error.code = 'ENOENT'
|
||||
throw error
|
||||
}
|
||||
return Promise.resolve(Buffer.from(this.files[path]))
|
||||
}
|
||||
async __readFile(path) {
|
||||
const data = await this._readFile(path)
|
||||
return this.encryptor?.decryptBuffer(data) ?? data
|
||||
}
|
||||
async _writeFile(path, buffer) {
|
||||
this.files[path] = buffer
|
||||
return Promise.resolve()
|
||||
}
|
||||
async __writeFile(path, buffer) {
|
||||
const encrypted = (await this.encryptor?.encryptBuffer(buffer)) ?? buffer
|
||||
return this._writeFile(path, encrypted)
|
||||
}
|
||||
async list(dir) {
|
||||
return Promise.resolve(
|
||||
Object.keys(this.files)
|
||||
.filter(file => file.startsWith(dir))
|
||||
.map(file => file.substring(dir.length))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suite('it works with one key ', async()=>{
|
||||
test('encryption and decryption', async ()=>{
|
||||
const fs = new MockFs()
|
||||
const encryptor = new SingleEncryptor(fs, 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const rolling = new RollingEncryptor(encryptor)
|
||||
await rolling.init()
|
||||
|
||||
const buffer = Buffer.from(" GOT IT GUY")
|
||||
const encrypted = rolling.encryptBuffer(buffer)
|
||||
const decrypted = rolling.decryptBuffer(encrypted)
|
||||
assert.ok(decrypted.equals(buffer))
|
||||
})
|
||||
})
|
||||
|
||||
suite('it works with updated keys ', async () => {
|
||||
|
||||
test('mock works with buffer', async ()=>{
|
||||
const fs = new MockFs()
|
||||
const encryptor = new SingleEncryptor(fs, 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const rolling = new RollingEncryptor(encryptor)
|
||||
fs.encryptor = rolling
|
||||
await rolling.init()
|
||||
|
||||
const buffer = Buffer.from(" GOT IT GUY")
|
||||
await fs.__writeFile("encrytpion1", buffer)
|
||||
const encrypted = await fs._readFile("encrytpion1")
|
||||
const decrypted = await fs.__readFile("encrytpion1")
|
||||
assert.ok(decrypted.equals(buffer))
|
||||
assert.ok(!decrypted.equals(encrypted))
|
||||
})
|
||||
|
||||
|
||||
test('works with buffer ', async () => {
|
||||
const fs = new MockFs()
|
||||
const encryptor = new SingleEncryptor(fs, 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const rolling = new RollingEncryptor(encryptor)
|
||||
fs.encryptor = rolling
|
||||
await rolling.init()
|
||||
|
||||
const content = Buffer.from(' GOT IT GUY')
|
||||
// encrytped with first key
|
||||
await fs.__writeFile('encrytpion1', content)
|
||||
|
||||
await rolling.updateEncryptionKey('023456789ABCDEF0123456789ABCDEF1', 'chacha20-poly1305')
|
||||
// encrytped with second key and algorithm
|
||||
await fs.__writeFile('encrytpion2', content)
|
||||
|
||||
const encrypted1 = await fs._readFile('encrytpion1')
|
||||
assert.ok(!content.equals(encrypted1))
|
||||
const decrypted1 = await fs.__readFile('encrytpion1')
|
||||
assert.ok(content.equals(decrypted1))
|
||||
|
||||
const encrypted2 = await fs._readFile('encrytpion2')
|
||||
assert.ok(!content.equals(encrypted2))
|
||||
assert.ok(!encrypted1.equals(encrypted2))
|
||||
const decrypted2 = await fs.__readFile('encrytpion2')
|
||||
assert.ok(content.equals(decrypted2))
|
||||
|
||||
assert.equal((await fs.list('encryptors')).length, 1)
|
||||
|
||||
await rolling.updateEncryptionKey('023456789ABCDEF0123456789ABCDEF3', 'chacha20-poly1305')
|
||||
await fs.__writeFile('encrytpion3', content)
|
||||
|
||||
const encrypted3 = await fs._readFile('encrytpion3')
|
||||
assert.ok(!content.equals(encrypted3))
|
||||
assert.ok(!encrypted1.equals(encrypted3))
|
||||
const decrypted3 = await fs.__readFile('encrytpion3')
|
||||
assert.ok(content.equals(decrypted3))
|
||||
|
||||
assert.equal((await fs.list('encryptors')).length, 2)
|
||||
|
||||
|
||||
// ensure key length doesn't grow if we use the same key again
|
||||
await rolling.updateEncryptionMetadata('023456789ABCDEF0123456789ABCDEF3', 'chacha20-poly1305')
|
||||
assert.equal((await fs.list('encryptors')).length, 2)
|
||||
})
|
||||
})
|
||||
222
@xen-orchestra/fs/src/encryptors/SingleEncryptor.js
Normal file
222
@xen-orchestra/fs/src/encryptors/SingleEncryptor.js
Normal file
@@ -0,0 +1,222 @@
|
||||
// @ts-check
|
||||
/**
|
||||
*
|
||||
* @typedef {import('node:crypto').Cipheriv} Cipheriv
|
||||
* @typedef {import('node:crypto').Decipheriv} Decipheriv
|
||||
*
|
||||
* @typedef {import('node:stream').Readable} Readable
|
||||
*/
|
||||
import { AbstractEncryptor, CHACHA20, DEFAULT_ENCRYPTION_ALGORITHM, ENCRYPTION_DESC_FILENAME, ENCRYPTION_METADATA_FILENAME } from './AbstractEncryptor.js'
|
||||
import assert from 'node:assert'
|
||||
import crypto from 'node:crypto'
|
||||
import { Readable } from 'node:stream'
|
||||
import { readChunkStrict } from '@vates/read-chunk'
|
||||
|
||||
export class SingleEncryptor extends AbstractEncryptor {
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
#ivLength = 0
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
#authTagLength = 0
|
||||
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
#algorithm
|
||||
get algorithm() {
|
||||
return this.#algorithm
|
||||
}
|
||||
/**
|
||||
* @type {Buffer}
|
||||
*/
|
||||
#key
|
||||
get key() {
|
||||
return this.#key
|
||||
}
|
||||
#handler
|
||||
get handler() {
|
||||
return this.#handler
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {*} handler
|
||||
* @param {string} algorithm
|
||||
* @param {Buffer|undefined} key
|
||||
* @returns
|
||||
*/
|
||||
constructor(handler, algorithm, key = undefined) {
|
||||
super(handler)
|
||||
this.#handler = handler
|
||||
this.#key = Buffer.from(key ?? handler._remote.encryptionKey ?? '')
|
||||
if (!this.#key.length) {
|
||||
this.#algorithm = 'none'
|
||||
this.#ivLength = 0
|
||||
return
|
||||
} else {
|
||||
this.#algorithm = algorithm
|
||||
}
|
||||
const info = crypto.getCipherInfo(algorithm, { keyLength: this.#key.length })
|
||||
if (info === undefined) {
|
||||
const error = new Error(
|
||||
`Either the algorithm ${algorithm} is not available, or the key length ${
|
||||
this.#key.length
|
||||
} is incorrect. Supported algorithm are ${crypto.getCiphers()}`
|
||||
)
|
||||
error.code = 'BAD_ALGORITHM'
|
||||
throw error
|
||||
}
|
||||
const { ivLength, mode } = info
|
||||
this.#ivLength = ivLength ?? 0
|
||||
const authTagLength = ['gcm', 'ccm', 'ocb'].includes(mode) || algorithm === CHACHA20 ? 16 : 0
|
||||
this.#authTagLength = authTagLength
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
encryptBuffer(buffer) {
|
||||
if (this.#algorithm === 'none') {
|
||||
return buffer
|
||||
}
|
||||
|
||||
const iv = crypto.randomBytes(this.#ivLength)
|
||||
const cipher = crypto.createCipheriv(this.#algorithm, Buffer.from(this.#key), iv)
|
||||
const encrypted = cipher.update(buffer)
|
||||
return Buffer.concat([
|
||||
iv,
|
||||
encrypted,
|
||||
cipher.final(),
|
||||
this.#authTagLength > 0 ? cipher.getAuthTag() : Buffer.alloc(0),
|
||||
])
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
decryptBuffer(buffer) {
|
||||
if (this.#algorithm === 'none') {
|
||||
return buffer
|
||||
}
|
||||
const iv = buffer.slice(0, this.#ivLength)
|
||||
/**
|
||||
* @type {Decipheriv}
|
||||
*/
|
||||
const decipher = crypto.createDecipheriv(this.#algorithm, Buffer.from(this.#key), iv)
|
||||
let encrypted
|
||||
if (this.#authTagLength > 0) {
|
||||
const authTag = buffer.slice(buffer.length - this.#authTagLength)
|
||||
decipher.setAuthTag(authTag)
|
||||
encrypted = buffer.slice(this.#ivLength, buffer.length - this.#authTagLength)
|
||||
} else {
|
||||
encrypted = buffer.slice(this.#ivLength)
|
||||
}
|
||||
const decrypted = decipher.update(encrypted)
|
||||
return Buffer.concat([decrypted, decipher.final()])
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Readable} input
|
||||
* @returns {Readable}
|
||||
*/
|
||||
encryptStream(input) {
|
||||
if (this.#algorithm === 'none') {
|
||||
return input
|
||||
}
|
||||
const iv = crypto.randomBytes(this.#ivLength)
|
||||
const cipher = crypto.createCipheriv(this.#algorithm, Buffer.from(this.#key), iv)
|
||||
const authTagLength = this.#authTagLength
|
||||
async function* generator() {
|
||||
yield iv
|
||||
for await (const data of input) {
|
||||
const encrypted = cipher.update(data)
|
||||
yield encrypted
|
||||
}
|
||||
yield cipher.final()
|
||||
// must write the auth tag at the end of the encryption stream
|
||||
if (authTagLength > 0) {
|
||||
yield cipher.getAuthTag()
|
||||
}
|
||||
}
|
||||
return Readable.from(generator(), { objectMode: false, highWaterMark: 10 * 1024 * 1024 })
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Readable} encryptedStream
|
||||
* @returns {Readable}
|
||||
*/
|
||||
decryptStream(encryptedStream) {
|
||||
if (this.#algorithm === 'none') {
|
||||
return encryptedStream
|
||||
}
|
||||
const ivLength = this.#ivLength
|
||||
const algorithm = this.#algorithm
|
||||
const key = this.#key
|
||||
const authTagLength = this.#authTagLength
|
||||
async function* generator() {
|
||||
const iv = await readChunkStrict(encryptedStream, ivLength)
|
||||
const cipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv)
|
||||
let authTag = Buffer.alloc(0)
|
||||
for await (const data of encryptedStream) {
|
||||
// auth tag length is stored at the end of the stream
|
||||
// we want to keep it and use at the end to validate the decrypted stream
|
||||
if (data.length >= authTagLength) {
|
||||
// fast path, no buffer concat
|
||||
yield cipher.update(authTag)
|
||||
authTag = data.slice(data.length - authTagLength)
|
||||
yield cipher.update(data.slice(0, data.length - authTagLength))
|
||||
} else {
|
||||
// slower since there is a concat
|
||||
const fullData = Buffer.concat([authTag, data])
|
||||
const fullDataLength = fullData.length
|
||||
if (fullDataLength > authTagLength) {
|
||||
authTag = fullData.slice(fullDataLength - authTagLength)
|
||||
yield cipher.update(fullData.slice(0, fullDataLength - authTagLength))
|
||||
} else {
|
||||
authTag = fullData
|
||||
}
|
||||
}
|
||||
}
|
||||
if (authTagLength > 0) {
|
||||
assert.strictEqual(authTagLength, authTag.length)
|
||||
cipher.setAuthTag(authTag)
|
||||
}
|
||||
yield cipher.final()
|
||||
}
|
||||
return Readable.from(generator(), { objectMode: false, highWaterMark: 10 * 1024 * 1024 })
|
||||
}
|
||||
|
||||
async #isFsEmpty() {
|
||||
const list = await this.#handler.list('/', {
|
||||
filter: e => !e.startsWith('.') && e !== ENCRYPTION_DESC_FILENAME && e !== ENCRYPTION_METADATA_FILENAME,
|
||||
})
|
||||
console.log({list})
|
||||
return list.length === 0
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} key
|
||||
* @param {string} algorithm
|
||||
*/
|
||||
async updateEncryptionKey(key, algorithm = DEFAULT_ENCRYPTION_ALGORITHM) {
|
||||
if (!(await this.#isFsEmpty())) {
|
||||
throw new Error(`Can't update the encryption of a non empty remote`)
|
||||
}
|
||||
this.#algorithm = algorithm
|
||||
this.#key = key
|
||||
await this.updateEncryptionMetadata()
|
||||
}
|
||||
|
||||
async updateEncryptionMetadata(){
|
||||
super.updateEncryptionMetadata(this.#algorithm)
|
||||
}
|
||||
}
|
||||
93
@xen-orchestra/fs/src/encryptors/SingleEncryptor.test.js
Normal file
93
@xen-orchestra/fs/src/encryptors/SingleEncryptor.test.js
Normal file
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert'
|
||||
import { suite, test } from 'node:test'
|
||||
import { Readable } from 'node:stream'
|
||||
import { SingleEncryptor } from './SingleEncryptor'
|
||||
|
||||
class MockFs {
|
||||
files = {}
|
||||
_remote = {
|
||||
encryptionKey: undefined,
|
||||
}
|
||||
async _readFile(path) {
|
||||
if (!this.files[path]) {
|
||||
const error = new Error('Not here')
|
||||
error.code = 'ENOENT'
|
||||
throw error
|
||||
}
|
||||
return Promise.resolve(Buffer.from(this.files[path]))
|
||||
}
|
||||
async _writeFile(path, buffer) {
|
||||
this.files[path] = buffer
|
||||
return Promise.resolve()
|
||||
}
|
||||
async __writeFile(path, buffer) {
|
||||
this.files[path] = 'encrypted' + buffer
|
||||
return Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
suite('no encryption', async () => {
|
||||
test('it should not modify buffer on encrypt ', () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'none')
|
||||
const buffer = Buffer.from('MY SOURCE')
|
||||
const encrypted = encryptor.encryptBuffer(buffer)
|
||||
assert.ok(buffer.equals(encrypted))
|
||||
})
|
||||
test('it should not modify buffer on decrypt ', () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'none')
|
||||
const buffer = Buffer.from('MY SOURCE')
|
||||
const encrypted = encryptor.decryptBuffer(buffer)
|
||||
assert.ok(buffer.equals(encrypted))
|
||||
})
|
||||
})
|
||||
|
||||
suite('it can encrypt', async () => {
|
||||
test('it encrypts and decrypt a buffer', () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const buffer = Buffer.from('MY SOURCE')
|
||||
const encrypted = encryptor.encryptBuffer(buffer)
|
||||
const decrypted = encryptor.decryptBuffer(encrypted)
|
||||
assert.ok(buffer.equals(decrypted))
|
||||
assert.ok(!buffer.equals(encrypted))
|
||||
})
|
||||
|
||||
test('it encrypts and decrypt a stream', async () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
let sourceBuffer = Buffer.alloc(0)
|
||||
function* generator() {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const buffer = Buffer.alloc(1024, i)
|
||||
sourceBuffer = Buffer.concat([sourceBuffer, buffer])
|
||||
yield buffer
|
||||
}
|
||||
}
|
||||
const stream = Readable.from(generator(), { objectMode: false })
|
||||
|
||||
const encrypted = encryptor.encryptStream(stream)
|
||||
let result = Buffer.alloc(0)
|
||||
const decrypted = encryptor.decryptStream(encrypted)
|
||||
|
||||
for await (const buffer of decrypted) {
|
||||
result = Buffer.concat([result, buffer])
|
||||
}
|
||||
})
|
||||
|
||||
test('it authenticate a buffer', () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const buffer = Buffer.allocUnsafe(1024 * 1024)
|
||||
const encrypted = encryptor.encryptBuffer(buffer)
|
||||
encrypted.writeUInt8(2, 7) // modify a byte
|
||||
|
||||
assert.throws(() => encryptor.decryptBuffer(encrypted))
|
||||
})
|
||||
|
||||
|
||||
test('it authenticate a buffer', () => {
|
||||
const encryptor = new SingleEncryptor(new MockFs(), 'aes-256-gcm', '0123456789ABCDEF0123456789ABCDEF')
|
||||
const buffer = Buffer.allocUnsafe(1024 * 1024)
|
||||
const encrypted = encryptor.encryptBuffer(buffer)
|
||||
encrypted.writeUInt8(2, 7) // modify a byte
|
||||
|
||||
assert.throws(() => encryptor.decryptBuffer(encrypted))
|
||||
})
|
||||
})
|
||||
@@ -46,9 +46,9 @@ handlers.forEach(url => {
|
||||
describe(url, () => {
|
||||
let handler
|
||||
|
||||
const testWithFileDescriptor = (path, flags, fn) => {
|
||||
it('with path', { skip: skipFsNotInAzure() }, () => fn({ file: path, flags }))
|
||||
it('with file descriptor', { skip: skipFsNotInAzure() }, async () => {
|
||||
const testWithFileDescriptor = (path, flags, fn, skip = false) => {
|
||||
it('with path', { skip: skip || skipFsNotInAzure() }, () => fn({ file: path, flags }))
|
||||
it('with file descriptor', { skip: skip || skipFsNotInAzure() }, async () => {
|
||||
const file = await handler.openFile(path, flags)
|
||||
try {
|
||||
await fn({ file })
|
||||
@@ -198,15 +198,20 @@ handlers.forEach(url => {
|
||||
const start = random(TEST_DATA_LEN - 1)
|
||||
const size = random(TEST_DATA_LEN - start)
|
||||
|
||||
testWithFileDescriptor('file', 'r', async ({ file }) => {
|
||||
const buffer = Buffer.alloc(size)
|
||||
const result = await handler.read(file, buffer, start)
|
||||
assert.deepEqual(result.buffer, buffer)
|
||||
assert.deepEqual(result, {
|
||||
buffer,
|
||||
bytesRead: Math.min(size, TEST_DATA_LEN - start),
|
||||
})
|
||||
})
|
||||
testWithFileDescriptor(
|
||||
'file',
|
||||
'r',
|
||||
async ({ file }) => {
|
||||
const buffer = Buffer.alloc(size)
|
||||
const result = await handler.read(file, buffer, start)
|
||||
assert.deepEqual(result.buffer, buffer)
|
||||
assert.deepEqual(result, {
|
||||
buffer,
|
||||
bytesRead: Math.min(size, TEST_DATA_LEN - start),
|
||||
})
|
||||
},
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
describe('#readFile', () => {
|
||||
@@ -321,12 +326,21 @@ handlers.forEach(url => {
|
||||
})(),
|
||||
},
|
||||
({ offset, expected }, title) => {
|
||||
describe(title, () => {
|
||||
testWithFileDescriptor('file', 'r+', async ({ file }) => {
|
||||
await handler.write(file, PATCH_DATA, offset)
|
||||
assert.deepEqual(await handler.readFile('file'), expected)
|
||||
})
|
||||
})
|
||||
describe(
|
||||
title,
|
||||
() => {
|
||||
testWithFileDescriptor(
|
||||
'file',
|
||||
'r+',
|
||||
async ({ file }) => {
|
||||
await handler.write(file, PATCH_DATA, offset)
|
||||
assert.deepEqual(await handler.readFile('file'), expected)
|
||||
},
|
||||
true
|
||||
)
|
||||
},
|
||||
true
|
||||
)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CopyObjectCommand,
|
||||
CreateMultipartUploadCommand,
|
||||
DeleteObjectCommand,
|
||||
DeleteObjectsCommand,
|
||||
GetObjectCommand,
|
||||
GetObjectLockConfigurationCommand,
|
||||
HeadObjectCommand,
|
||||
@@ -24,7 +25,6 @@ import copyStreamToBuffer from './_copyStreamToBuffer.js'
|
||||
import guessAwsRegion from './_guessAwsRegion.js'
|
||||
import RemoteHandlerAbstract from './abstract'
|
||||
import { basename, join, split } from './path'
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
|
||||
// endpoints https://docs.aws.amazon.com/general/latest/gr/s3.html
|
||||
|
||||
@@ -139,6 +139,10 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
}
|
||||
}
|
||||
|
||||
_conditionRetry(error) {
|
||||
return ![401, 403, 404, 405].includes(error?.$metadata?.httpStatusCode) && super._conditionRetry(error)
|
||||
}
|
||||
|
||||
async _copy(oldPath, newPath) {
|
||||
const CopySource = this.#makeCopySource(oldPath)
|
||||
try {
|
||||
@@ -384,21 +388,13 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
)
|
||||
|
||||
NextContinuationToken = result.IsTruncated ? result.NextContinuationToken : undefined
|
||||
await asyncEach(
|
||||
result.Contents ?? [],
|
||||
async ({ Key }) => {
|
||||
// _unlink will add the prefix, but Key contains everything
|
||||
// also we don't need to check if we delete a directory, since the list only return files
|
||||
await this.#s3.send(
|
||||
new DeleteObjectCommand({
|
||||
Bucket: this.#bucket,
|
||||
Key,
|
||||
})
|
||||
)
|
||||
},
|
||||
{
|
||||
concurrency: 16,
|
||||
}
|
||||
await this.#s3.send(
|
||||
new DeleteObjectsCommand({
|
||||
Bucket: this.#bucket,
|
||||
Delete: {
|
||||
Objects: result.Contents ?? [],
|
||||
},
|
||||
})
|
||||
)
|
||||
} while (NextContinuationToken !== undefined)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from 'node:fs/promises'
|
||||
import * as Directory from './directory.mjs'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { listOlderTargets } from './fileIndex.mjs'
|
||||
@@ -10,9 +9,8 @@ import loadConfig from './_loadConfig.mjs'
|
||||
const { info, warn } = createLogger('xen-orchestra:immutable-backups:liftProtection')
|
||||
|
||||
async function liftRemoteImmutability(immutabilityCachePath, immutabilityDuration) {
|
||||
for await (const { index, target } of listOlderTargets(immutabilityCachePath, immutabilityDuration)) {
|
||||
for await (const { target } of listOlderTargets(immutabilityCachePath, immutabilityDuration)) {
|
||||
await Directory.liftImmutability(target, immutabilityCachePath)
|
||||
await fs.unlink(index)
|
||||
await cleanXoCache(target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,22 +17,22 @@
|
||||
"xo-lift-remote-immutability": "./liftProtection.mjs"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.27",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.0",
|
||||
"@xen-orchestra/backups": "^0.63.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"@xen-orchestra/backups": "^0.67.2",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"app-conf": "^3.0.0",
|
||||
"chokidar": "^3.6.0",
|
||||
"execa": "^5.0.0",
|
||||
"ms": "^2.1.3",
|
||||
"vhd-lib": "^4.14.0"
|
||||
"vhd-lib": "^4.14.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^5.0.5",
|
||||
"rimraf": "^6.0.1",
|
||||
"tap": "^18.6.1"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -2,8 +2,33 @@
|
||||
|
||||
## **next**
|
||||
|
||||
- [VM/New] Fix wording in "Memory" section (PR [#9309](https://github.com/vatesfr/xen-orchestra/pull/9309))
|
||||
|
||||
## **0.17.0** (2025-11-27)
|
||||
|
||||
- [Host/HostSystemResourceManagement] Fix display when control domain memory is undefined (PR [#9197](https://github.com/vatesfr/xen-orchestra/pull/9197))
|
||||
|
||||
## **0.16.0** (2025-10-30)
|
||||
|
||||
- [VM/New] Fix the default topology by setting the platform:cores-per-socket value correctly (PR [#9136](https://github.com/vatesfr/xen-orchestra/pull/9136))
|
||||
|
||||
## **0.15.0** (2025-09-30)
|
||||
|
||||
- [settigns] fix key-value alignement and refactor page (PR [#8981](https://github.com/vatesfr/xen-orchestra/pull/8981))
|
||||
- [Settings] Add icon for external links on settings page (PR [#8980](https://github.com/vatesfr/xen-orchestra/pull/8980))
|
||||
- [VM/dashboard] Update QuickInfo card in dashboard to show more information (PR [#8952](https://github.com/vatesfr/xen-orchestra/pull/8952))
|
||||
- [StateHero] Update VtsStateHero component and modify usages in every component (PR [#8910](https://github.com/vatesfr/pull/8910))
|
||||
|
||||
## **0.14.1** (2025-09-04)
|
||||
|
||||
- [VM/System] Correctly display enable/disable for secure boot (PR [#8925](https://github.com/vatesfr/xen-orchestra/pull/8925))
|
||||
|
||||
## **0.14.0** (2025-08-28)
|
||||
|
||||
- [Pool,Host,VM/Dashboard] Remember the last visited tab per object type (Pool/Host/VM) when navigating (PR [#8872](https://github.com/vatesfr/xen-orchestra/pull/8872))
|
||||
- Replace native `select` with a new custom component (PR [#8681](https://github.com/vatesfr/xen-orchestra/pull/8681))
|
||||
- Add i18n engage link on the settings page [Issue#8603](https://github.com/vatesfr/xen-orchestra/issues/8603) (PR [#8884](https://github.com/vatesfr/xen-orchestra/pull/8884))
|
||||
- Migrate progress bar usages to Web Core components and remove old Lite components (PR [#8899](https://github.com/vatesfr/xen-orchestra/pull/8899))
|
||||
|
||||
## **0.13.1** (2025-08-06)
|
||||
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
# Modal System Documentation
|
||||
|
||||
## Opening a modal
|
||||
|
||||
To open a modal, call `useModal(loader, props?)`.
|
||||
|
||||
- `loader`: The modal component loader (e.g. `() => import("path/to/MyModal.vue")`)
|
||||
- `props`: The optional props to pass to the modal component
|
||||
|
||||
This will return an object with the following methods:
|
||||
|
||||
- `onApprove(cb)`:
|
||||
- A function to register a callback to be called when the modal is approved.
|
||||
- The callback will receive the modal payload as first argument, if any.
|
||||
- The callback can return a Promise, in which case the modal will wait for it to resolve before closing.
|
||||
- `onDecline(cb)`:
|
||||
- A function to register a callback to be called when the modal is declined.
|
||||
- The callback can return a Promise, in which case the modal will wait for it to resolve before closing.
|
||||
|
||||
### Static modal
|
||||
|
||||
```ts
|
||||
useModal(MyModal)
|
||||
```
|
||||
|
||||
### Modal with props
|
||||
|
||||
```ts
|
||||
useModal(MyModal, { message: 'Hello world!' })
|
||||
```
|
||||
|
||||
### Handle modal approval
|
||||
|
||||
```ts
|
||||
const { onApprove } = useModal(MyModal, { message: 'Hello world!' })
|
||||
|
||||
onApprove(() => console.log('Modal approved'))
|
||||
```
|
||||
|
||||
### Handle modal approval with payload
|
||||
|
||||
```ts
|
||||
const { onApprove } = useModal(MyModal, { message: 'Hello world!' })
|
||||
|
||||
onApprove(payload => console.log('Modal approved with payload', payload))
|
||||
```
|
||||
|
||||
### Handle modal decline
|
||||
|
||||
```ts
|
||||
const { onDecline } = useModal(MyModal, { message: 'Hello world!' })
|
||||
|
||||
onDecline(() => console.log('Modal declined'))
|
||||
```
|
||||
|
||||
### Handle modal close
|
||||
|
||||
```ts
|
||||
const { onClose } = useModal(MyModal, { message: 'Hello world!' })
|
||||
|
||||
onClose(() => console.log('Modal closed'))
|
||||
```
|
||||
|
||||
## Modal controller
|
||||
|
||||
Inside the modal component, you can inject the modal controller with `inject(IK_MODAL)!`.
|
||||
|
||||
```ts
|
||||
const modal = inject(IK_MODAL)!
|
||||
```
|
||||
|
||||
You can then use the following properties and methods on the `modal` object:
|
||||
|
||||
- `isBusy`: Whether the modal is currently doing something (e.g. waiting for a promise to resolve).
|
||||
- `approve(payload?: any | Promise<any>)`: Approve the modal with an optional payload.
|
||||
- Set `isBusy` to `true`.
|
||||
- Wait for the `payload` to resolve (if any).
|
||||
- Wait for all callbacks registered with `onApprove` to resolve (if any).
|
||||
- Close the modal in case of success.
|
||||
- `decline()`: Decline the modal.
|
||||
- Set `isBusy` to `true`.
|
||||
- Wait for all callbacks registered with `onDecline` to resolve (if any).
|
||||
- Close the modal in case of success.
|
||||
|
||||
## Components
|
||||
|
||||
Some components are available for quick modal creation.
|
||||
|
||||
### `UiModal`
|
||||
|
||||
The root component of the modal which will display the backdrop.
|
||||
|
||||
A click on the backdrop will execute `modal.decline()`.
|
||||
|
||||
It accepts `color` and `disabled` props which will update the `ColorContext` and `DisabledContext`.
|
||||
|
||||
`DisabledContext` will also be set to `true` when `modal.isBusy` is `true`.
|
||||
|
||||
The component itself is a `form` and is meant to be used with `<UiModal @submit.prevent="modal.approve()">`.
|
||||
|
||||
### `ModalApproveButton`
|
||||
|
||||
A wrapper around `UiButton` with `type="submit"` and with the `busy` prop set to `modal.isBusy`.
|
||||
|
||||
### `ModalDeclineButton`
|
||||
|
||||
A wrapper around `UiButton` with an `outline` prop and with the `busy` prop set to `modal.isBusy`.
|
||||
|
||||
This button will call `modal.decline()` on click.
|
||||
|
||||
Default text is `t("cancel")`.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/lite",
|
||||
"version": "0.13.1",
|
||||
"version": "0.17.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
|
||||
@@ -28,14 +28,14 @@
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^18.19.80",
|
||||
"@vates/types": "^1.10.0",
|
||||
"@vates/types": "^1.16.0",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
"@vueuse/core": "^13.0.0",
|
||||
"@vueuse/math": "^13.0.0",
|
||||
"@vueuse/shared": "^13.0.0",
|
||||
"@xen-orchestra/web-core": "^0.27.0",
|
||||
"complex-matcher": "^0.7.1",
|
||||
"@xen-orchestra/web-core": "^0.39.1",
|
||||
"complex-matcher": "^1.0.0",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
"file-saver": "^2.0.5",
|
||||
|
||||
@@ -10,19 +10,19 @@
|
||||
<RouterView />
|
||||
</main>
|
||||
</div>
|
||||
<VtsTooltipList />
|
||||
</div>
|
||||
<ModalList />
|
||||
<VtsModalList />
|
||||
<VtsTooltipList />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
import AppLogin from '@/components/AppLogin.vue'
|
||||
import AppNavigation from '@/components/AppNavigation.vue'
|
||||
import ModalList from '@/components/ui/modals/ModalList.vue'
|
||||
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store'
|
||||
import VtsModalList from '@core/components/modal/VtsModalList.vue'
|
||||
import VtsTooltipList from '@core/components/tooltip-list/VtsTooltipList.vue'
|
||||
import { useChartTheme } from '@core/composables/chart-theme.composable'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
|
||||
@@ -2,16 +2,15 @@
|
||||
<header class="app-header">
|
||||
<div class="left">
|
||||
<UiButtonIcon
|
||||
v-if="!uiStore.isDesktopLarge"
|
||||
ref="navigationTrigger"
|
||||
:class="{ 'menu-to-right': !uiStore.isMobile }"
|
||||
:icon="faBars"
|
||||
accent="brand"
|
||||
icon="fa:bars"
|
||||
size="medium"
|
||||
/>
|
||||
<RouterLink :to="logoRoute" class="logo-container">
|
||||
<img v-if="uiStore.isMobile" alt="XO Lite" src="../assets/logo.svg" />
|
||||
<TextLogo v-else />
|
||||
<UiLogoText v-else :text="t('xo-lite')" />
|
||||
</RouterLink>
|
||||
</div>
|
||||
<slot />
|
||||
@@ -26,19 +25,20 @@
|
||||
<script lang="ts" setup>
|
||||
import AccountMenu from '@/components/account-menu/AccountMenu.vue'
|
||||
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
|
||||
import TextLogo from '@/components/TextLogo.vue'
|
||||
import XoaButton from '@/components/XoaButton.vue'
|
||||
import { useNavigationStore } from '@/stores/navigation.store'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiLogoText from '@core/components/ui/logo-text/UiLogoText.vue'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
import { faBars } from '@fortawesome/free-solid-svg-icons'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
|
||||
const uiStore = useUiStore()
|
||||
const { pool } = usePoolStore().getContext()
|
||||
const { t } = useI18n()
|
||||
|
||||
const navigationStore = useNavigationStore()
|
||||
const { trigger: navigationTrigger } = storeToRefs(navigationStore)
|
||||
@@ -80,7 +80,7 @@ const logoRoute = computed<RouteLocationRaw>(() =>
|
||||
.left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
gap: 1.6rem;
|
||||
|
||||
@media (max-width: 1023px) {
|
||||
flex: 1;
|
||||
@@ -96,6 +96,8 @@ const logoRoute = computed<RouteLocationRaw>(() =>
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
height: 2.5rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.right {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<img alt="XO Lite" src="../assets/logo-title.svg" />
|
||||
<PoolOverrideWarning />
|
||||
<p v-if="isHostIsSlaveErr(error)" class="error">
|
||||
<UiIcon :icon="faExclamationCircle" />
|
||||
<VtsIcon name="fa:exclamation-circle" size="medium" />
|
||||
{{ t('login-only-on-master') }}
|
||||
<a :href="masterUrl.href">{{ masterUrl.hostname }}</a>
|
||||
</p>
|
||||
@@ -42,14 +42,13 @@
|
||||
import FormInput from '@/components/form/FormInput.vue'
|
||||
import LoginError from '@/components/LoginError.vue'
|
||||
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import type { XenApiError } from '@/libs/xen-api/xen-api.types'
|
||||
import { usePageTitleStore } from '@/stores/page-title.store'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
|
||||
import { faExclamationCircle } from '@fortawesome/free-solid-svg-icons'
|
||||
import { useLocalStorage, whenever } from '@vueuse/core'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
<template>
|
||||
<Transition name="slide">
|
||||
<nav
|
||||
v-if="uiStore.isDesktopLarge || isOpen"
|
||||
ref="navElement"
|
||||
:class="{ collapsible: !uiStore.isDesktopLarge }"
|
||||
class="app-navigation"
|
||||
>
|
||||
<nav v-if="isOpen" ref="navElement" class="app-navigation">
|
||||
<StoryMenu v-if="route.meta.hasStoryNav" />
|
||||
<InfraPoolList v-else />
|
||||
</nav>
|
||||
@@ -16,34 +11,37 @@
|
||||
import StoryMenu from '@/components/component-story/StoryMenu.vue'
|
||||
import InfraPoolList from '@/components/infra/InfraPoolList.vue'
|
||||
import { useNavigationStore } from '@/stores/navigation.store'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
import { onClickOutside, whenever } from '@vueuse/core'
|
||||
import { onClickOutside } from '@vueuse/core'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const navigationStore = useNavigationStore()
|
||||
const { isOpen, trigger } = storeToRefs(navigationStore)
|
||||
const { isOpen } = storeToRefs(navigationStore)
|
||||
|
||||
const navElement = ref()
|
||||
|
||||
whenever(isOpen, () => {
|
||||
const unregisterEvent = onClickOutside(
|
||||
navElement,
|
||||
() => {
|
||||
isOpen.value = false
|
||||
unregisterEvent?.()
|
||||
},
|
||||
{
|
||||
ignore: [trigger],
|
||||
controls: false,
|
||||
watch(
|
||||
() => navigationStore.trigger?.value,
|
||||
triggerElement => {
|
||||
if (triggerElement && navElement.value) {
|
||||
onClickOutside(
|
||||
navElement,
|
||||
() => {
|
||||
if (isOpen.value) {
|
||||
isOpen.value = false
|
||||
}
|
||||
},
|
||||
{
|
||||
ignore: [triggerElement],
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
})
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
@@ -55,11 +53,6 @@ whenever(isOpen, () => {
|
||||
padding: 0.5rem;
|
||||
border-right: 1px solid var(--color-neutral-border);
|
||||
background-color: var(--color-neutral-background-primary);
|
||||
|
||||
&.collapsible {
|
||||
position: fixed;
|
||||
z-index: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.slide-enter-active,
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
<UiFilter
|
||||
v-for="filter in activeFilters"
|
||||
:key="filter"
|
||||
@edit="openModal(filter)"
|
||||
@edit="openFilterModal(filter)"
|
||||
@remove="emit('removeFilter', filter)"
|
||||
>
|
||||
{{ filter }}
|
||||
</UiFilter>
|
||||
|
||||
<UiActionButton :icon="faPlus" class="add-filter" @click="openModal()">
|
||||
{{ t('add-filter') }}
|
||||
<UiActionButton icon="fa:plus" class="add-filter" @click="openFilterModal()">
|
||||
{{ t('action:add-filter') }}
|
||||
</UiActionButton>
|
||||
</UiFilterGroup>
|
||||
</template>
|
||||
@@ -19,12 +19,12 @@
|
||||
import UiActionButton from '@/components/ui/UiActionButton.vue'
|
||||
import UiFilter from '@/components/ui/UiFilter.vue'
|
||||
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
|
||||
import { useModal } from '@/composables/modal.composable'
|
||||
import type { Filters } from '@/types/filter'
|
||||
import { faPlus } from '@fortawesome/free-solid-svg-icons'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
const { availableFilters } = defineProps<{
|
||||
activeFilters: string[]
|
||||
availableFilters: Filters
|
||||
}>()
|
||||
@@ -36,16 +36,18 @@ const emit = defineEmits<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const openModal = (editedFilter?: string) => {
|
||||
const { onApprove } = useModal<string>(() => import('@/components/modals/CollectionFilterModal.vue'), {
|
||||
availableFilters: props.availableFilters,
|
||||
const openFilterModal = useModal((editedFilter?: string) => ({
|
||||
component: import('@/components/modals/CollectionFilterModal.vue'),
|
||||
props: {
|
||||
editedFilter,
|
||||
})
|
||||
availableFilters: computed(() => availableFilters),
|
||||
},
|
||||
onConfirm: async newFilter => {
|
||||
if (editedFilter !== undefined) {
|
||||
emit('removeFilter', editedFilter)
|
||||
}
|
||||
|
||||
if (editedFilter !== undefined) {
|
||||
onApprove(() => emit('removeFilter', editedFilter))
|
||||
}
|
||||
|
||||
onApprove(newFilter => emit('addFilter', newFilter))
|
||||
}
|
||||
emit('addFilter', newFilter)
|
||||
},
|
||||
}))
|
||||
</script>
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
<template>
|
||||
<div class="collection-filter-row">
|
||||
<span class="or">{{ t('or') }}</span>
|
||||
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" />
|
||||
<template v-else>
|
||||
<VtsSelect :id="builderPropertySelectId" accent="brand" :icon="currentFilterIcon" />
|
||||
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
|
||||
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
|
||||
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
|
||||
</template>
|
||||
<UiActionButton v-if="!newFilter.isAdvanced" :icon="faPencil" @click="enableAdvancedMode" />
|
||||
<UiActionButton :icon="faRemove" @click="emit('remove', newFilter.id)" />
|
||||
<div class="inputs">
|
||||
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" class="advanced-input" />
|
||||
<template v-else>
|
||||
<VtsSelect :id="builderPropertySelectId" accent="brand" :icon="currentFilterIcon" />
|
||||
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
|
||||
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
|
||||
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
|
||||
</template>
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<UiActionButton v-if="!newFilter.isAdvanced" icon="fa:pencil" @click="enableAdvancedMode" />
|
||||
<UiActionButton icon="fa:remove" @click="emit('remove', newFilter.id)" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -21,11 +25,10 @@ import type { Filter, FilterComparisons, FilterComparisonType, Filters, FilterTy
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import UiInput from '@core/components/ui/input/UiInput.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { faPencil, faRemove } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
const { availableFilters } = defineProps<{
|
||||
availableFilters: Filters
|
||||
}>()
|
||||
|
||||
@@ -96,10 +99,10 @@ function getDefaultComparisonType(property: string) {
|
||||
enum: 'enumIs',
|
||||
}
|
||||
|
||||
return defaultTypes[props.availableFilters[property].type]
|
||||
return defaultTypes[availableFilters[property].type]
|
||||
}
|
||||
|
||||
const currentFilter = computed<Filter | undefined>(() => props.availableFilters[builderProperty.value])
|
||||
const currentFilter = computed<Filter | undefined>(() => availableFilters[builderProperty.value])
|
||||
|
||||
const currentFilterIcon = computed(() => getFilterIcon(currentFilter.value))
|
||||
|
||||
@@ -114,7 +117,7 @@ const enumChoices = computed(() => {
|
||||
return []
|
||||
}
|
||||
|
||||
const availableFilter = props.availableFilters[builderProperty.value]
|
||||
const availableFilter = availableFilters[builderProperty.value]
|
||||
|
||||
if (availableFilter.type !== 'enum') {
|
||||
return []
|
||||
@@ -163,20 +166,20 @@ watch(generatedFilter, value => {
|
||||
const comparisons = computed<FilterComparisons>(() => {
|
||||
const comparisonsByType = {
|
||||
string: {
|
||||
stringContains: t('filter.comparison.contains'),
|
||||
stringEquals: t('filter.comparison.equals'),
|
||||
stringStartsWith: t('filter.comparison.starts-with'),
|
||||
stringEndsWith: t('filter.comparison.ends-with'),
|
||||
stringMatchesRegex: t('filter.comparison.matches-regex'),
|
||||
stringDoesNotContain: t('filter.comparison.not-contain'),
|
||||
stringDoesNotEqual: t('filter.comparison.not-equal'),
|
||||
stringDoesNotStartWith: t('filter.comparison.not-start-with'),
|
||||
stringDoesNotEndWith: t('filter.comparison.not-end-with'),
|
||||
stringDoesNotMatchRegex: t('filter.comparison.not-match-regex'),
|
||||
stringContains: t('filter:comparison:contains'),
|
||||
stringEquals: t('filter:comparison:equals'),
|
||||
stringStartsWith: t('filter:comparison:starts-with'),
|
||||
stringEndsWith: t('filter:comparison:ends-with'),
|
||||
stringMatchesRegex: t('filter:comparison:matches-regex'),
|
||||
stringDoesNotContain: t('filter:comparison:not-contain'),
|
||||
stringDoesNotEqual: t('filter:comparison:not-equal'),
|
||||
stringDoesNotStartWith: t('filter:comparison:not-start-with'),
|
||||
stringDoesNotEndWith: t('filter:comparison:not-end-with'),
|
||||
stringDoesNotMatchRegex: t('filter:comparison:not-match-regex'),
|
||||
},
|
||||
boolean: {
|
||||
booleanTrue: t('filter.comparison.is-true'),
|
||||
booleanFalse: t('filter.comparison.is-false'),
|
||||
booleanTrue: t('filter:comparison:is-true'),
|
||||
booleanFalse: t('filter:comparison:is-false'),
|
||||
},
|
||||
number: {
|
||||
numberLessThan: '<',
|
||||
@@ -186,8 +189,8 @@ const comparisons = computed<FilterComparisons>(() => {
|
||||
numberGreaterThan: '>',
|
||||
},
|
||||
enum: {
|
||||
enumIs: t('filter.comparison.is'),
|
||||
enumIsNot: t('filter.comparison.is-not'),
|
||||
enumIs: t('filter:comparison:is'),
|
||||
enumIsNot: t('filter:comparison:is-not'),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -196,7 +199,7 @@ const comparisons = computed<FilterComparisons>(() => {
|
||||
|
||||
// BUILDER PROPERTY SELECT
|
||||
|
||||
const { id: builderPropertySelectId } = useFormSelect(Object.entries(props.availableFilters), {
|
||||
const { id: builderPropertySelectId } = useFormSelect(Object.entries(availableFilters), {
|
||||
model: builderProperty,
|
||||
placeholder: `- ${t('property')} -`,
|
||||
option: {
|
||||
@@ -251,9 +254,24 @@ const { id: builderValueSelectId } = useFormSelect(
|
||||
&:first-child .or {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.ui-action-button:first-of-type {
|
||||
margin-left: auto;
|
||||
.inputs,
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
|
||||
@media (--mobile) {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.inputs {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.buttons {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -7,48 +7,45 @@
|
||||
@remove="emit('removeSort', property)"
|
||||
>
|
||||
<span class="property">
|
||||
<UiIcon :icon="isAscending ? faCaretUp : faCaretDown" />
|
||||
<VtsIcon :name="isAscending ? 'fa:caret-up' : 'fa:caret-down'" size="medium" />
|
||||
{{ property }}
|
||||
</span>
|
||||
</UiFilter>
|
||||
|
||||
<UiActionButton :icon="faPlus" class="add-sort" @click="openModal()">
|
||||
{{ t('add-sort') }}
|
||||
<UiActionButton icon="fa:plus" class="add-sort" @click="openFormModal()">
|
||||
{{ t('action:add-sort') }}
|
||||
</UiActionButton>
|
||||
</UiFilterGroup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
<script lang="ts" setup generic="TProperty extends PropertyKey">
|
||||
import UiActionButton from '@/components/ui/UiActionButton.vue'
|
||||
import UiFilter from '@/components/ui/UiFilter.vue'
|
||||
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
|
||||
import { useModal } from '@/composables/modal.composable'
|
||||
import type { ActiveSorts, NewSort, Sorts } from '@/types/sort'
|
||||
import { faCaretDown, faCaretUp, faPlus } from '@fortawesome/free-solid-svg-icons'
|
||||
import type { ActiveSorts, Sorts } from '@/types/sort'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
const { availableSorts } = defineProps<{
|
||||
availableSorts: Sorts
|
||||
activeSorts: ActiveSorts<Record<string, any>>
|
||||
activeSorts: ActiveSorts<Record<TProperty, any>>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
toggleSortDirection: [property: string]
|
||||
addSort: [property: string, isAscending: boolean]
|
||||
removeSort: [property: string]
|
||||
toggleSortDirection: [property: TProperty]
|
||||
addSort: [property: TProperty, isAscending: boolean]
|
||||
removeSort: [property: TProperty]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const openModal = () => {
|
||||
const { onApprove } = useModal<NewSort>(() => import('@/components/modals/CollectionSorterModal.vue'), {
|
||||
availableSorts: computed(() => props.availableSorts),
|
||||
})
|
||||
|
||||
onApprove(({ property, isAscending }) => emit('addSort', property, isAscending))
|
||||
}
|
||||
const openFormModal = useModal({
|
||||
component: import('@/components/modals/CollectionSorterModal.vue'),
|
||||
props: { availableSorts: computed(() => availableSorts) },
|
||||
onConfirm: ({ property, isAscending }) => emit('addSort', property as TProperty, isAscending),
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
<template>
|
||||
<div class="filter-and-sort">
|
||||
<CollectionFilter
|
||||
v-if="availableFilters !== undefined"
|
||||
:active-filters="filters"
|
||||
:available-filters="availableFilters"
|
||||
@add-filter="addFilter"
|
||||
@remove-filter="removeFilter"
|
||||
/>
|
||||
|
||||
<CollectionSorter
|
||||
v-if="availableSorts !== undefined"
|
||||
:active-sorts="sorts"
|
||||
:available-sorts="availableSorts"
|
||||
@add-sort="addSort"
|
||||
@remove-sort="removeSort"
|
||||
@toggle-sort-direction="toggleSortDirection"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UiTable vertical-border>
|
||||
<thead>
|
||||
<tr>
|
||||
<td v-if="isSelectable">
|
||||
<input v-model="areAllSelected" type="checkbox" />
|
||||
</td>
|
||||
<slot name="head-row" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in filteredAndSortedCollection" :key="item.$ref">
|
||||
<td v-if="isSelectable">
|
||||
<input v-model="selected" :value="item.$ref" type="checkbox" />
|
||||
</td>
|
||||
<slot :item name="body-row" />
|
||||
</tr>
|
||||
</tbody>
|
||||
</UiTable>
|
||||
</template>
|
||||
|
||||
<script generic="T extends XenApiRecord<any>" lang="ts" setup>
|
||||
import CollectionFilter from '@/components/CollectionFilter.vue'
|
||||
import CollectionSorter from '@/components/CollectionSorter.vue'
|
||||
import UiTable from '@/components/ui/UiTable.vue'
|
||||
import useCollectionFilter from '@/composables/collection-filter.composable'
|
||||
import useCollectionSorter from '@/composables/collection-sorter.composable'
|
||||
import useFilteredCollection from '@/composables/filtered-collection.composable'
|
||||
import useMultiSelect from '@/composables/multi-select.composable'
|
||||
import useSortedCollection from '@/composables/sorted-collection.composable'
|
||||
import type { XenApiRecord } from '@/libs/xen-api/xen-api.types'
|
||||
import type { Filters } from '@/types/filter'
|
||||
import type { Sorts } from '@/types/sort'
|
||||
import { computed, toRef, watch } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: T['$ref'][]
|
||||
availableFilters?: Filters
|
||||
availableSorts?: Sorts
|
||||
collection: T[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [selectedRefs: T['$ref'][]]
|
||||
}>()
|
||||
|
||||
const isSelectable = computed(() => props.modelValue !== undefined)
|
||||
|
||||
const { filters, addFilter, removeFilter, predicate } = useCollectionFilter({
|
||||
queryStringParam: 'filter',
|
||||
})
|
||||
const { sorts, addSort, removeSort, toggleSortDirection, compareFn } = useCollectionSorter<Record<string, any>>({
|
||||
queryStringParam: 'sort',
|
||||
})
|
||||
|
||||
const filteredCollection = useFilteredCollection(toRef(props, 'collection'), predicate)
|
||||
|
||||
const filteredAndSortedCollection = useSortedCollection(filteredCollection, compareFn)
|
||||
|
||||
const usableRefs = computed(() => props.collection.map(item => item.$ref))
|
||||
|
||||
const selectableRefs = computed(() => filteredAndSortedCollection.value.map(item => item.$ref))
|
||||
|
||||
const { selected, areAllSelected } = useMultiSelect(usableRefs, selectableRefs)
|
||||
|
||||
watch(selected, selected => emit('update:modelValue', selected), {
|
||||
immediate: true,
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.filter-and-sort {
|
||||
display: flex;
|
||||
}
|
||||
</style>
|
||||
@@ -2,7 +2,7 @@
|
||||
<th>
|
||||
<div class="content">
|
||||
<span class="label">
|
||||
<UiIcon :icon />
|
||||
<VtsIcon :name="icon" size="medium" />
|
||||
<slot />
|
||||
</span>
|
||||
</div>
|
||||
@@ -10,11 +10,11 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import type { IconDefinition } from '@fortawesome/fontawesome-common-types'
|
||||
import type { IconName } from '@core/icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
|
||||
defineProps<{
|
||||
icon?: IconDefinition
|
||||
icon?: IconName
|
||||
}>()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,55 +1,38 @@
|
||||
<template>
|
||||
<UiCardSpinner v-if="!areSomeLoaded" />
|
||||
<UiTable v-else :class="{ desktop: isDesktop }" class="hosts-patches-table">
|
||||
<tr v-for="patch in sortedPatches" :key="patch.$id">
|
||||
<th>
|
||||
<span v-tooltip="{ placement: 'left', content: patch.version }">
|
||||
{{ patch.name }}
|
||||
</span>
|
||||
</th>
|
||||
<td v-if="hasMultipleHosts">
|
||||
<UiSpinner v-if="!areAllLoaded" />
|
||||
<UiCounter
|
||||
v-else
|
||||
v-tooltip="{
|
||||
placement: 'left',
|
||||
content: t('n-hosts-awaiting-patch', {
|
||||
n: patch.$hostRefs.size,
|
||||
}),
|
||||
}"
|
||||
:value="patch.$hostRefs.size"
|
||||
class="counter"
|
||||
accent="danger"
|
||||
variant="primary"
|
||||
size="small"
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
</UiTable>
|
||||
<VtsTable class="hosts-patches-table" :state :class="{ desktop: uiStore.isDesktop }">
|
||||
<thead>
|
||||
<tr>
|
||||
<HeadCells />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<VtsRow v-for="patch of sortedPatches" :key="patch.$id">
|
||||
<BodyCells :item="patch" />
|
||||
</VtsRow>
|
||||
</tbody>
|
||||
</VtsTable>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiCardSpinner from '@/components/ui/UiCardSpinner.vue'
|
||||
import UiSpinner from '@/components/ui/UiSpinner.vue'
|
||||
import UiTable from '@/components/ui/UiTable.vue'
|
||||
import type { XenApiPatchWithHostRefs } from '@/composables/host-patches.composable'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
import VtsTable from '@core/components/table/VtsTable.vue'
|
||||
import { useTableState } from '@core/composables/table-state.composable'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
import { usePatchColumns } from '@core/tables/column-sets/patch-columns'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
const { patches, busy } = defineProps<{
|
||||
patches: XenApiPatchWithHostRefs[]
|
||||
hasMultipleHosts: boolean
|
||||
areAllLoaded: boolean
|
||||
areSomeLoaded: boolean
|
||||
busy?: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const sortedPatches = computed(() =>
|
||||
[...props.patches].sort((patch1, patch2) => {
|
||||
[...patches].sort((patch1, patch2) => {
|
||||
if (patch1.changelog == null) {
|
||||
return 1
|
||||
} else if (patch2.changelog == null) {
|
||||
@@ -60,15 +43,21 @@ const sortedPatches = computed(() =>
|
||||
})
|
||||
)
|
||||
|
||||
const { isDesktop } = useUiStore()
|
||||
const state = useTableState({
|
||||
busy: () => busy,
|
||||
empty: () => (patches.length === 0 ? { type: 'all-good', message: t('patches-up-to-date') } : false),
|
||||
})
|
||||
|
||||
const { HeadCells, BodyCells } = usePatchColumns({
|
||||
body: (patch: XenApiPatchWithHostRefs) => ({
|
||||
name: r => r(patch.name),
|
||||
version: r => r(patch.version),
|
||||
}),
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.hosts-patches-table.desktop {
|
||||
max-width: 45rem;
|
||||
}
|
||||
|
||||
.counter {
|
||||
font-size: 1rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-if="error !== undefined" class="error typo-body-regular-small">
|
||||
<UiIcon :icon="faExclamationCircle" />
|
||||
<VtsIcon name="fa:exclamation-circle" size="medium" />
|
||||
<span v-if="error.message === 'SESSION_AUTHENTICATION_FAILED'">
|
||||
{{ t('password-invalid') }}
|
||||
</span>
|
||||
@@ -11,9 +11,8 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import type { XenApiError } from '@/libs/xen-api/xen-api.types'
|
||||
import { faExclamationCircle } from '@fortawesome/free-solid-svg-icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
<template>
|
||||
<div class="object-link">
|
||||
<UiSpinner v-if="!isReady" />
|
||||
<template v-else-if="record !== undefined">
|
||||
<RouterLink v-if="objectRoute" :to="objectRoute">
|
||||
{{ record.name_label }}
|
||||
</RouterLink>
|
||||
<span v-else>{{ record.name_label }}</span>
|
||||
</template>
|
||||
<span v-else class="unknown">{{ uuid }}</span>
|
||||
</div>
|
||||
<UiSpinner v-if="!isReady" />
|
||||
<template v-else-if="record !== undefined">
|
||||
<RouterLink v-if="objectRoute" :to="objectRoute">
|
||||
{{ record.name_label }}
|
||||
</RouterLink>
|
||||
<span v-else>{{ record.name_label }}</span>
|
||||
</template>
|
||||
<span v-else class="unknown">{{ uuid }}</span>
|
||||
</template>
|
||||
|
||||
<script generic="T extends ObjectType" lang="ts" setup>
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
<template>
|
||||
<UiStatusPanel
|
||||
:image-source="underConstruction"
|
||||
:subtitle="t('new-features-are-coming')"
|
||||
:title="t('xo-lite-under-construction')"
|
||||
>
|
||||
<VtsStateHero format="page" type="under-construction" size="large">
|
||||
<span>{{ t('xo-lite-under-construction') }}</span>
|
||||
<span class="typo-h3">{{ t('new-features-are-coming!') }}</span>
|
||||
<p class="contact typo-body-regular">
|
||||
{{ t('do-you-have-needs') }}
|
||||
<a
|
||||
@@ -14,12 +12,11 @@
|
||||
{{ `${t('here')} →` }}
|
||||
</a>
|
||||
</p>
|
||||
</UiStatusPanel>
|
||||
</VtsStateHero>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import underConstruction from '@/assets/under-construction.svg'
|
||||
import UiStatusPanel from '@/components/ui/UiStatusPanel.vue'
|
||||
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
@click="xenApi.resetPoolMasterIp"
|
||||
>
|
||||
<div class="wrapper">
|
||||
<UiIcon :icon="faWarning" />
|
||||
<VtsIcon name="fa:triangle-exclamation" size="medium" />
|
||||
<p v-if="!asTooltip">
|
||||
<I18nT keypath="you-are-currently-on">
|
||||
<strong>{{ masterSessionStorage }}</strong>
|
||||
@@ -27,10 +27,9 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { faWarning } from '@fortawesome/free-solid-svg-icons'
|
||||
import { useSessionStorage } from '@vueuse/core'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
|
||||
@@ -1,47 +1,23 @@
|
||||
<template>
|
||||
<UiIcon :class="className" :icon class="power-state-icon" />
|
||||
<VtsIcon :name="icon" size="medium" class="power-state-icon" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums'
|
||||
import { faMoon, faPause, faPlay, faQuestion, faStop } from '@fortawesome/free-solid-svg-icons'
|
||||
import type { IconName } from '@core/icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
state: VM_POWER_STATE
|
||||
}>()
|
||||
|
||||
const icons = {
|
||||
[VM_POWER_STATE.RUNNING]: faPlay,
|
||||
[VM_POWER_STATE.PAUSED]: faPause,
|
||||
[VM_POWER_STATE.SUSPENDED]: faMoon,
|
||||
[VM_POWER_STATE.HALTED]: faStop,
|
||||
const icons: Record<VM_POWER_STATE, IconName> = {
|
||||
[VM_POWER_STATE.RUNNING]: 'legacy:running',
|
||||
[VM_POWER_STATE.PAUSED]: 'legacy:paused',
|
||||
[VM_POWER_STATE.SUSPENDED]: 'legacy:suspended',
|
||||
[VM_POWER_STATE.HALTED]: 'legacy:halted',
|
||||
}
|
||||
|
||||
const icon = computed(() => icons[props.state] ?? faQuestion)
|
||||
|
||||
const className = computed(() => `state-${props.state.toLocaleLowerCase()}`)
|
||||
const icon = computed(() => icons[props.state])
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.power-state-icon {
|
||||
color: var(--color-brand-txt-item);
|
||||
|
||||
&.state-running {
|
||||
color: var(--color-success-item-base);
|
||||
}
|
||||
|
||||
&.state-paused {
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
}
|
||||
|
||||
&.state-suspended {
|
||||
color: var(--color-brand-txt-hover);
|
||||
}
|
||||
|
||||
&.state-halted {
|
||||
color: var(--color-danger-item-base);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<template>
|
||||
<span :title="date.toLocaleString()">{{ relativeTime }}</span>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { parseDateTime } from '@/libs/utils'
|
||||
import useRelativeTime from '@core/composables/relative-time.composable'
|
||||
import { useNow } from '@vueuse/core'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
date: Date | number | string
|
||||
}>()
|
||||
|
||||
const date = computed(() => new Date(parseDateTime(props.date)))
|
||||
const now = useNow({ interval: 1000 })
|
||||
const relativeTime = useRelativeTime(date, now)
|
||||
</script>
|
||||
@@ -1,33 +0,0 @@
|
||||
<template>
|
||||
<svg
|
||||
class="text-logo"
|
||||
viewBox="300.85 622.73 318.32 63.27"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="100"
|
||||
height="22"
|
||||
>
|
||||
<g>
|
||||
<polygon
|
||||
points="355.94 684.92 341.54 684.92 327.84 664.14 315.68 684.92 301.81 684.92 317.59 659.25 338.96 659.25 355.94 684.92"
|
||||
/>
|
||||
<path
|
||||
d="M406.2,627.17c4.62,2.64,8.27,6.33,10.94,11.07,2.67,4.74,4.01,10.1,4.01,16.07s-1.34,11.35-4.01,16.12c-2.67,4.77-6.32,8.48-10.94,11.12-4.63,2.64-9.78,3.97-15.47,3.97s-10.85-1.32-15.47-3.97c-4.63-2.64-8.27-6.35-10.95-11.12-2.67-4.77-4.01-10.14-4.01-16.12s1.34-11.33,4.01-16.07c2.67-4.74,6.32-8.43,10.95-11.07,4.62-2.64,9.78-3.97,15.47-3.97s10.84,1.32,15.47,3.97Zm-24.86,9.65c-2.7,1.61-4.81,3.92-6.33,6.94-1.52,3.02-2.28,6.54-2.28,10.56s.76,7.54,2.28,10.56c1.52,3.02,3.63,5.33,6.33,6.94,2.7,1.61,5.83,2.41,9.39,2.41s6.69-.8,9.39-2.41c2.7-1.61,4.81-3.92,6.33-6.94,1.52-3.02,2.28-6.53,2.28-10.56s-.76-7.54-2.28-10.56-3.63-5.33-6.33-6.94c-2.7-1.61-5.83-2.41-9.39-2.41s-6.69,.8-9.39,2.41Z"
|
||||
/>
|
||||
<polygon
|
||||
points="354.99 624.06 339.53 649.22 317.49 649.22 300.86 624.06 315.26 624.06 328.96 644.84 341.12 624.06 354.99 624.06"
|
||||
/>
|
||||
<g>
|
||||
<path d="M476.32,675.94h20.81v10.04h-33.47v-63.14h12.66v53.1Z" />
|
||||
<path d="M517.84,622.84v63.14h-12.66v-63.14h12.66Z" />
|
||||
<path d="M573.29,622.84v10.22h-16.82v52.92h-12.66v-52.92h-16.83v-10.22h46.31Z" />
|
||||
<path d="M595.18,633.06v15.83h21.26v10.04h-21.26v16.73h23.97v10.31h-36.64v-63.23h36.64v10.31h-23.97Z" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.text-logo {
|
||||
fill: var(--color-logo);
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="title-bar">
|
||||
<UiIcon :icon class="icon" />
|
||||
<VtsIcon :name="icon" class="icon" size="medium" />
|
||||
<div class="title typo-h4">
|
||||
<slot />
|
||||
</div>
|
||||
@@ -11,11 +11,11 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import type { IconDefinition } from '@fortawesome/fontawesome-common-types'
|
||||
import type { IconName } from '@core/icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
|
||||
defineProps<{
|
||||
icon: IconDefinition
|
||||
icon: IconName
|
||||
}>()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
<template>
|
||||
<div class="usage-bar">
|
||||
<div
|
||||
v-for="item in computedData.sortedArray"
|
||||
:key="item.id"
|
||||
:class="{
|
||||
warning: item.value > MIN_WARNING_VALUE,
|
||||
error: item.value > MIN_DANGEROUS_VALUE,
|
||||
}"
|
||||
class="progress-item"
|
||||
>
|
||||
<UiProgressBar :value="item.value" color="custom" />
|
||||
<UiProgressLegend :label="item.label" :value="item.badgeLabel ?? n(item.value / 100, 'percent')" />
|
||||
</div>
|
||||
<slot :total-percent="computedData.totalPercentUsage" name="footer" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiProgressBar from '@/components/ui/progress/UiProgressBar.vue'
|
||||
import UiProgressLegend from '@/components/ui/progress/UiProgressLegend.vue'
|
||||
import type { StatData } from '@/types/stat'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface Props {
|
||||
data: StatData[]
|
||||
nItems?: number
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const { n } = useI18n()
|
||||
|
||||
const MIN_WARNING_VALUE = 80
|
||||
const MIN_DANGEROUS_VALUE = 90
|
||||
|
||||
const computedData = computed(() => {
|
||||
const _data = props.data
|
||||
let totalPercentUsage = 0
|
||||
return {
|
||||
sortedArray: _data
|
||||
?.map(item => {
|
||||
const value = Math.round((item.value / (item.maxValue ?? 100)) * 100)
|
||||
totalPercentUsage += value
|
||||
return {
|
||||
...item,
|
||||
value,
|
||||
}
|
||||
})
|
||||
.sort((item, nextItem) => nextItem.value - item.value)
|
||||
.slice(0, props.nItems ?? _data.length),
|
||||
totalPercentUsage,
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.usage-bar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.progress-item:nth-child(1) {
|
||||
--progress-bar-color: var(--color-brand-txt-item);
|
||||
}
|
||||
|
||||
.progress-item:nth-child(2) {
|
||||
--progress-bar-color: var(--color-brand-txt-active);
|
||||
}
|
||||
|
||||
.progress-item:nth-child(3) {
|
||||
--progress-bar-color: var(--color-brand-txt-hover);
|
||||
}
|
||||
|
||||
.progress-item {
|
||||
--progress-bar-height: 1.2rem;
|
||||
--progress-bar-color: var(--color-brand-item-hover);
|
||||
--progress-bar-background-color: var(--color-neutral-background-disabled);
|
||||
|
||||
&.warning {
|
||||
--progress-bar-color: var(--color-warning-item-base);
|
||||
}
|
||||
|
||||
&.error {
|
||||
--progress-bar-color: var(--color-danger-item-base);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,7 +4,7 @@
|
||||
size="medium"
|
||||
accent="brand"
|
||||
variant="primary"
|
||||
:left-icon="faArrowUpRightFromSquare"
|
||||
left-icon="fa:arrow-up-right-from-square"
|
||||
class="xoa-button"
|
||||
@click="openXoa()"
|
||||
>
|
||||
@@ -15,11 +15,11 @@
|
||||
size="medium"
|
||||
accent="brand"
|
||||
variant="primary"
|
||||
:left-icon="faDownload"
|
||||
left-icon="fa:download"
|
||||
class="xoa-button"
|
||||
@click="openXoaDeploy()"
|
||||
>
|
||||
{{ t('deploy-xoa') }}
|
||||
{{ t('action:deploy-xoa') }}
|
||||
</UiButton>
|
||||
</template>
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
import type { PRIMARY_ADDRESS_TYPE } from '@/libs/xen-api/xen-api.enums'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import { faDownload, faArrowUpRightFromSquare } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
@@ -8,24 +8,24 @@
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<MenuItem :icon="faGear" @click="openSettings">{{ t('settings') }}</MenuItem>
|
||||
<MenuItem :icon="faBook" @click="openUrl('https://docs.xcp-ng.org?utm_campaign=xolite&utm_term=xcpdoc')">
|
||||
<MenuItem icon="fa:gear" @click="openSettings">{{ t('settings') }}</MenuItem>
|
||||
<MenuItem icon="fa:book" @click="openUrl('https://docs.xcp-ng.org?utm_campaign=xolite&utm_term=xcpdoc')">
|
||||
{{ t('documentation-name', { name: 'XCP-ng' }) }}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
:icon="faHeadset"
|
||||
icon="fa:headset"
|
||||
@click="openUrl('https://vates.tech/pricing-and-support?utm_campaign=xolite&utm_term=pricing')"
|
||||
>
|
||||
{{ t('professional-support') }}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
:icon="faComments"
|
||||
icon="fa:comments"
|
||||
@click="openUrl('https://xcp-ng.org/forum/topic/4731/xen-orchestra-lite?utm_campaign=xolite&utm_term=forum')"
|
||||
>
|
||||
{{ t('access-forum') }}
|
||||
</MenuItem>
|
||||
<MenuItem :icon="faArrowRightFromBracket" class="menu-item-logout" @click="logout">
|
||||
{{ t('log-out') }}
|
||||
<MenuItem icon="fa:arrow-right-from-bracket" class="menu-item-logout" @click="logout">
|
||||
{{ t('action:log-out') }}
|
||||
</MenuItem>
|
||||
</MenuList>
|
||||
</template>
|
||||
@@ -36,7 +36,6 @@ import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import UiAccountMenuButton from '@core/components/ui/account-menu-button/UiAccountMenuButton.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { faArrowRightFromBracket, faBook, faComments, faGear, faHeadset } from '@fortawesome/free-solid-svg-icons'
|
||||
import { nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<MenuList placement="bottom">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<TabItem :active="isOpen" :disabled="presets === undefined" class="preset-tab" @click="open">
|
||||
<UiIcon :icon="faSliders" />
|
||||
<VtsIcon name="fa:sliders" size="medium" />
|
||||
Presets
|
||||
</TabItem>
|
||||
</template>
|
||||
@@ -79,7 +79,6 @@ import StoryEventParams from '@/components/component-story/StoryEventParams.vue'
|
||||
import StoryPropParams from '@/components/component-story/StoryPropParams.vue'
|
||||
import StorySettingParams from '@/components/component-story/StorySettingParams.vue'
|
||||
import StorySlotParams from '@/components/component-story/StorySlotParams.vue'
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import UiCard from '@/components/ui/UiCard.vue'
|
||||
import UiCardTitle from '@/components/ui/UiCardTitle.vue'
|
||||
import {
|
||||
@@ -91,13 +90,13 @@ import {
|
||||
ModelParam,
|
||||
type Param,
|
||||
} from '@/libs/story/story-param'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import TabItem from '@core/components/tab/TabItem.vue'
|
||||
import TabList from '@core/components/tab/TabList.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import { faSliders } from '@fortawesome/free-solid-svg-icons'
|
||||
import 'highlight.js/styles/github-dark.css'
|
||||
import { uniqueId, upperFirst } from 'lodash-es'
|
||||
import { computed, onBeforeMount, reactive, ref, watch, watchEffect } from 'vue'
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
class="directory typo-body-bold"
|
||||
@click="emit('toggleDirectory', node.directory)"
|
||||
>
|
||||
<UiIcon :icon="isOpen(node.directory) ? faFolderOpen : faFolderClosed" />
|
||||
<VtsIcon :name="isOpen(node.directory) ? 'fa:folder-open' : 'fa:folder-closed'" size="medium" />
|
||||
{{ formatName(key) }}
|
||||
</span>
|
||||
<RouterLink v-else :to="node.path" class="link typo-body-regular">
|
||||
<UiIcon :icon="faFile" />
|
||||
<VtsIcon name="fa:file" size="medium" />
|
||||
{{ formatName(key) }}
|
||||
</RouterLink>
|
||||
|
||||
@@ -26,8 +26,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { StoryTree } from '@/components/component-story/StoryMenu.vue'
|
||||
import UiIcon from '@/components/ui/icon/UiIcon.vue'
|
||||
import { faFile, faFolderClosed, faFolderOpen } from '@fortawesome/free-regular-svg-icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
tree: StoryTree
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user