Compare commits
499 Commits
20230104
...
renovate/t
Author | SHA1 | Date | |
---|---|---|---|
1dc13ab438 | |||
b633694f74 | |||
ab16bd7bcf | |||
1080ab5cb2 | |||
a2845ddafe | |||
c968b64b51 | |||
12833dc6da | |||
8c4f2a9f2d | |||
9a6b6cfb2d | |||
b28ca5f27d | |||
92f187bf91 | |||
9f1f4b44ca | |||
b00d46105b | |||
7d6ccd4ce6 | |||
b5371421e1 | |||
07d305c54e | |||
78c525f47a | |||
978a881372 | |||
ee733b04f3 | |||
0d8ef226c1 | |||
feca07558e | |||
0de15af10e | |||
d4bc92f562 | |||
a1439689dd | |||
63126c75fa | |||
940302a825 | |||
9c374f849b | |||
2fa4d0e11b | |||
d7796e1459 | |||
759361d9f6 | |||
b2529c250a | |||
8a7712ec42 | |||
9609cfb33a | |||
1fe7c60f36 | |||
f1339f0711 | |||
b3f56cea81 | |||
9bd702d60f | |||
c8b42626a9 | |||
4ef15507d9 | |||
8a4b3a4db6 | |||
8bce9ca9b7 | |||
5574037b73 | |||
d1ca9aee39 | |||
f850ca5cb7 | |||
4ee01cad4b | |||
5518b45219 | |||
0279907ca9 | |||
5fe481ffed | |||
c7cc15d8d0 | |||
22416badcf | |||
ef0d77f1d6 | |||
1d4af8c74e | |||
ec9492c933 | |||
fa03ae885f | |||
ea98aaf856 | |||
794d16bdaa | |||
a3ac56f849 | |||
6130f37336 | |||
6b6fef5ccc | |||
83df7e1b20 | |||
a18310e04a | |||
dd7f9176fa | |||
d5fbc24c96 | |||
d765f9c2c3 | |||
21fd5de139 | |||
42f22c110c | |||
9822c5a72a | |||
452a395525 | |||
80d81c34bb | |||
b9353326f5 | |||
3ffc64f129 | |||
e869517bb1 | |||
90f4bf35e9 | |||
80d6fe0298 | |||
e017fe96d5 | |||
e7ac0198ab | |||
927a51cda7 | |||
615dc1ed83 | |||
20de618568 | |||
7451f1b7b4 | |||
5814b0ab6a | |||
5a5450070a | |||
19ec9992be | |||
b55880b43c | |||
6a7af7e6c4 | |||
a8171375a8 | |||
de33c7d521 | |||
ff372800bd | |||
aac05b7faf | |||
61e5a42ef7 | |||
19f2f6d730 | |||
dce17062a3 | |||
dcb0743cbe | |||
644fd6f1bb | |||
94ee8f8c78 | |||
53a8963fc4 | |||
56ab7065ac | |||
1e8394b3c4 | |||
01f26c1a79 | |||
8c27010396 | |||
35e7f4b59c | |||
d08516a72d | |||
479cc1fa0f | |||
3c636406af | |||
578f1432a0 | |||
f403c85f0a | |||
db25c7e426 | |||
98b67534cb | |||
09d3cf08f3 | |||
9b3d32811f | |||
26d391ea96 | |||
c044996014 | |||
34b04968b2 | |||
c44a3f2673 | |||
e46adcd1da | |||
d1506f26ab | |||
23194d13d2 | |||
131dec892d | |||
c2e6105aff | |||
f5202f596d | |||
3bf8859ff9 | |||
9a905e83f7 | |||
4b9df95721 | |||
e14f51ef7e | |||
5d49ce17a6 | |||
e5753d2b26 | |||
e9e3103938 | |||
44188975ca | |||
3f8d4e78d8 | |||
1c01a3b1ac | |||
a5c40255c7 | |||
6080bd83b5 | |||
8cb9d8bb32 | |||
3c613e40bf | |||
7fed9e2324 | |||
afe7aab751 | |||
accd4776cb | |||
6aabab866c | |||
4981a41a0a | |||
9daced06e4 | |||
8299065eb2 | |||
67549d54a3 | |||
c0690d888e | |||
ed9fd097e9 | |||
3c8de8279b | |||
6d8ce34e4a | |||
7c7df3bdde | |||
d9767d1011 | |||
136dfbbea0 | |||
7c8a1e06af | |||
296e7da865 | |||
0f84db322a | |||
70ca59d96f | |||
0669493d9b | |||
ef38125277 | |||
4107e7f77c | |||
f3c6b85827 | |||
cf31ab6ecd | |||
76a4506a62 | |||
c16f805df6 | |||
7ad8b42609 | |||
b139dfdfee | |||
72c559bf10 | |||
9b6a813c6f | |||
0830d81b3d | |||
3ed64003d3 | |||
6f1e707c2f | |||
300efe5367 | |||
375ce6ca7e | |||
8eff09a607 | |||
0885def533 | |||
48b1bc3185 | |||
99533fabf4 | |||
88a1c7a96a | |||
38ac6e575b | |||
51010fdea3 | |||
9b6704c39b | |||
8de0718650 | |||
10b1355c2c | |||
ec56af6a8e | |||
0549eb04d7 | |||
dd49c692b1 | |||
024360ac65 | |||
c2f04e41f3 | |||
b8d2c6ef5a | |||
a7b4a132cd | |||
94c9057a12 | |||
e7bc32d38f | |||
a8d0520ec5 | |||
63d13f4c27 | |||
0c8d37033a | |||
fd604e2869 | |||
990057be0d | |||
d65ebdcb0f | |||
cd7252b864 | |||
284f9d3a94 | |||
98f26c2bf7 | |||
d7db6a56d3 | |||
8389c026fa | |||
6cb5b37c23 | |||
058c2a4abb | |||
839a7d271b | |||
d53c5d45cf | |||
be4fa6f0d7 | |||
deced2492f | |||
0eb6567eb8 | |||
2c40d50435 | |||
5c5c54bbd7 | |||
772e14cc3d | |||
a2802647f2 | |||
79b2db0987 | |||
9cbbcc3bea | |||
f4571af3c5 | |||
5808589cf8 | |||
48e4d9a84d | |||
5ee1abde46 | |||
aca1c69f32 | |||
19f71e7d68 | |||
7583b547c2 | |||
f67201eaa9 | |||
ba7129b67f | |||
0642e2910e | |||
e5968f2444 | |||
1bbdbcbbaf | |||
5a85e9a91f | |||
20342a5cc9 | |||
4259327fbf | |||
9cdd0920a4 | |||
feb52889c1 | |||
70ef1a3717 | |||
b13712a430 | |||
8e350d4c60 | |||
824d9ba4ff | |||
5da98d3d12 | |||
a77faafdf7 | |||
61f4dab638 | |||
66fd3954c7 | |||
772e2270c4 | |||
2955dfa5c0 | |||
48e9c1d42f | |||
044b7d0de4 | |||
a969248744 | |||
7d046e607d | |||
ee77bd11c9 | |||
821021e66f | |||
68bd5a6c67 | |||
e49e69de88 | |||
a3f9ad17c0 | |||
b943691d18 | |||
bc051ee678 | |||
c7a2d1af23 | |||
93fbb31273 | |||
b4eb6f7ea4 | |||
00ff6f0b50 | |||
324042f956 | |||
e466d03ec5 | |||
89ba09f872 | |||
a322c46ca4 | |||
0915a3e2d9 | |||
07eceaf72f | |||
0e1396e177 | |||
e59f21984f | |||
8c508acd32 | |||
26e7af7675 | |||
2fadf53dea | |||
2b58ce4d5e | |||
9755bacc55 | |||
8b16ce0c5d | |||
20e6d7931e | |||
c908d00c62 | |||
55b49699eb | |||
91fe291341 | |||
eec6bbb598 | |||
d2243fa1c2 | |||
6e7dd7c1c4 | |||
e40e15287b | |||
800969b9cc | |||
5917068add | |||
9b14d62830 | |||
25503a688b | |||
868adc6cee | |||
528e30f3dc | |||
cc42d20e67 | |||
d189470539 | |||
6fdd9f91fa | |||
69c2d12fcd | |||
174e4a2c79 | |||
847ab20a63 | |||
09c32a5555 | |||
220c943642 | |||
e5d709c34f | |||
1e359a3b8e | |||
dbff6358db | |||
d5c05a0cdd | |||
1d24d2a84c | |||
d35dac2de8 | |||
01141f77e2 | |||
56f765a15a | |||
639b7f4b38 | |||
babda3acd1 | |||
197b72cad0 | |||
1910c7081b | |||
eda0fc80b0 | |||
f6e5356109 | |||
11da25b4c0 | |||
2599032581 | |||
ed58d60e84 | |||
a126e76eef | |||
c472dfe807 | |||
c883f13bf8 | |||
b320f0b326 | |||
9812120ed6 | |||
9ebd3b0315 | |||
24afa12be2 | |||
310689312c | |||
e7f4bc44e7 | |||
165937f88b | |||
a5d81de62b | |||
ba2b3494cf | |||
1944415371 | |||
4130fdda1c | |||
e4ef4c43bd | |||
afdf639d9b | |||
f2d6b9a5dd | |||
e3b61baf11 | |||
20732860cf | |||
7f14ab8a54 | |||
87d4c5b0fd | |||
0f58f82e52 | |||
16b73a2030 | |||
a32954785d | |||
2789fc299f | |||
0257ecba0b | |||
17fc64b1fe | |||
fbc818b5f3 | |||
a4292795d1 | |||
529e16c0c7 | |||
e1adc1456f | |||
f1f4a88ae3 | |||
8fdbb0f442 | |||
9efb1b29df | |||
2c07f5f121 | |||
953f6fdcf2 | |||
d66e384137 | |||
80bf70502f | |||
7f6cf26617 | |||
c9cf39bb76 | |||
93afb646ca | |||
4b358acbde | |||
b97dbc8149 | |||
e1292ae922 | |||
3e812b5530 | |||
b1e268bf63 | |||
887c4608b4 | |||
49e33cfd57 | |||
842733caa3 | |||
b6b56fdba8 | |||
8163d5e52f | |||
7aca0aee13 | |||
39fc34ef26 | |||
be06339bd7 | |||
00c1047734 | |||
a6c54ada50 | |||
8803c6755b | |||
cdab9df5c1 | |||
75b8c1d9e9 | |||
557fb7d97b | |||
bb85e58008 | |||
b8c1375f4f | |||
a96f6f33df | |||
a55061a2cd | |||
e6d3dd926c | |||
95dc089943 | |||
dafef923f0 | |||
5095a701eb | |||
a157484105 | |||
0e4bf4414c | |||
0a2a9d66e1 | |||
c4ff5d0621 | |||
ff1391694d | |||
368ae4e89d | |||
a539c092f5 | |||
dbf44e6204 | |||
448b029c17 | |||
f06082ce82 | |||
272763bdc3 | |||
1dd2dfc684 | |||
b5cb76cd7d | |||
4f7161ae9e | |||
f3d184e06d | |||
12404cc9a0 | |||
0eabdec559 | |||
8646837035 | |||
a164c6adb5 | |||
7de2c01418 | |||
7f11076f45 | |||
3f32aab8bd | |||
275e706ee5 | |||
7608a7cb18 | |||
e6293e3015 | |||
a44bc0a4fc | |||
a2221b0903 | |||
6ab4111182 | |||
8fb044b61d | |||
06ec35e1e7 | |||
e94b08827c | |||
5d1ab3be67 | |||
383b29ce21 | |||
85c9e0f4c6 | |||
7e3c105d78 | |||
6a3f1f40f9 | |||
b33c660c3e | |||
cd04e04d34 | |||
7dfbed0186 | |||
3dbefc8d84 | |||
077b385c0f | |||
3f203966d4 | |||
0ab8b23de4 | |||
a18787efcb | |||
68465270bf | |||
b88eb08ec2 | |||
8995b5e874 | |||
9fe4c67aa0 | |||
d6e2a10e59 | |||
03c7dbc357 | |||
27f33038a9 | |||
57b0957d3e | |||
2174ececd1 | |||
a61b38b4d3 | |||
ea84ebdda7 | |||
a972ea51aa | |||
f89a4f4481 | |||
0e07ca6bd3 | |||
aaba9f2f80 | |||
0ba70330db | |||
bb55ec4cfe | |||
90f8b46c84 | |||
51b34131d2 | |||
06374dc5ea | |||
151c1fc157 | |||
696b09f508 | |||
270fe60c1d | |||
50a224c9f6 | |||
2efe5877a4 | |||
c1de6d9621 | |||
2ae2717a5b | |||
0a25dc5730 | |||
1d6d6e6796 | |||
4e8b79deca | |||
0ddc4362a0 | |||
9d423e3443 | |||
1c3d3d57a4 | |||
edbfe53d1a | |||
81c1044bae | |||
3777d73c50 | |||
9365e9afdf | |||
9d738285ab | |||
c7de64cc02 | |||
149e3f4d72 | |||
f1ba3bc5ab | |||
cea123f5b0 | |||
927414dbaf | |||
2ac16fd1cb | |||
59c64e4633 | |||
74924cff88 | |||
f0328a8912 | |||
afc1b5cca6 | |||
b0ca64b2ff | |||
d8e5aa17f3 | |||
9002b0c4b1 | |||
33eaaf2e6b | |||
bdb15e16af | |||
0ec491bf3e | |||
389d03e699 | |||
e2210d247a | |||
586a60ab96 | |||
104b369fdd | |||
c96b8cbad1 | |||
f16176e927 | |||
0c5a8d56c9 | |||
7428512222 | |||
759a9b2dbf | |||
1ed23317cb | |||
9b55f1f29c | |||
5d26426074 | |||
39ff53f2ba | |||
96d264d15f | |||
6c23951d74 | |||
6ea8a927a3 | |||
4d0b4929c5 | |||
d6c8964380 | |||
ed25eed31e | |||
6fdcc8c07c | |||
f82925dbcb | |||
71e22bc328 | |||
e86b29c03a | |||
672e866897 | |||
80ecb3c5d2 | |||
134e27feb6 |
77
.drone.yml
Normal file
77
.drone.yml
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
---
|
||||||
|
kind: pipeline
|
||||||
|
type: docker
|
||||||
|
name: default
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: web_build
|
||||||
|
image: node:23
|
||||||
|
volumes:
|
||||||
|
- name: web_app
|
||||||
|
path: /tmp/web_build
|
||||||
|
commands:
|
||||||
|
- cd virtweb_frontend
|
||||||
|
- npm install
|
||||||
|
- npm run lint
|
||||||
|
- npm run build
|
||||||
|
- mv dist /tmp/web_build
|
||||||
|
|
||||||
|
- name: backend_check
|
||||||
|
image: rust
|
||||||
|
volumes:
|
||||||
|
- name: rust_registry
|
||||||
|
path: /usr/local/cargo/registry
|
||||||
|
commands:
|
||||||
|
- apt update && apt install -y libvirt-dev
|
||||||
|
- rustup component add clippy
|
||||||
|
- cd virtweb_backend
|
||||||
|
- cargo clippy -- -D warnings
|
||||||
|
- cargo clippy --examples -- -D warnings
|
||||||
|
- cargo test
|
||||||
|
|
||||||
|
- name: backend_compile
|
||||||
|
image: rust
|
||||||
|
volumes:
|
||||||
|
- name: rust_registry
|
||||||
|
path: /usr/local/cargo/registry
|
||||||
|
- name: web_app
|
||||||
|
path: /tmp/web_build
|
||||||
|
- name: release
|
||||||
|
path: /tmp/release
|
||||||
|
depends_on:
|
||||||
|
- backend_check
|
||||||
|
- web_build
|
||||||
|
commands:
|
||||||
|
- apt update && apt install -y libvirt-dev
|
||||||
|
- cd virtweb_backend
|
||||||
|
- mv /tmp/web_build/dist static
|
||||||
|
- cargo build --release
|
||||||
|
- cargo build --release --example api_curl
|
||||||
|
- ls -lah target/release/virtweb_backend target/release/examples/api_curl
|
||||||
|
- cp target/release/virtweb_backend target/release/examples/api_curl /tmp/release
|
||||||
|
|
||||||
|
- name: gitea_release
|
||||||
|
image: plugins/gitea-release
|
||||||
|
depends_on:
|
||||||
|
- backend_compile
|
||||||
|
when:
|
||||||
|
event:
|
||||||
|
- tag
|
||||||
|
volumes:
|
||||||
|
- name: release
|
||||||
|
path: /tmp/release
|
||||||
|
environment:
|
||||||
|
PLUGIN_API_KEY:
|
||||||
|
from_secret: API_KEY
|
||||||
|
settings:
|
||||||
|
base_url: https://gitea.communiquons.org
|
||||||
|
files: /tmp/release/*
|
||||||
|
checksum: sha512
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
- name: rust_registry
|
||||||
|
temp: {}
|
||||||
|
- name: web_app
|
||||||
|
temp: {}
|
||||||
|
- name: release
|
||||||
|
temp: {}
|
674
LICENSE
Normal file
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
19
README.md
19
README.md
@ -1,8 +1,23 @@
|
|||||||
# VirtWEB
|
# VirtWEB
|
||||||
WIP project
|
Open Source Web interface for LibVirt. Simplify the management of VM.
|
||||||
|
|
||||||
## Setup for dev
|
## Setup for dev
|
||||||
Please refer to this guide: [virtweb_docs/SETUP_DEV.md](virtweb_docs/SETUP_DEV.md)
|
Please refer to this guide: [virtweb_docs/SETUP_DEV.md](virtweb_docs/SETUP_DEV.md)
|
||||||
|
|
||||||
## Production requirements
|
## Production requirements
|
||||||
Please refer to this guide: [virtweb_docs/SETUP_PROD.md](virtweb_docs/SETUP_PROD.md)
|
Please refer to this guide: [virtweb_docs/SETUP_PROD.md](virtweb_docs/SETUP_PROD.md)
|
||||||
|
|
||||||
|
## Features
|
||||||
|
* Only Qemu / KVM is supported!
|
||||||
|
* Basic auth / OpenID auth
|
||||||
|
* Create, update & delete VM
|
||||||
|
* noVNC control of VMs
|
||||||
|
* Start, stop, suspend, resume, reset & kill VMs
|
||||||
|
* Create, update & delete networks
|
||||||
|
* Start & stop networks
|
||||||
|
* Create, update & delete network filters
|
||||||
|
* Upload ISO for easy VM installation
|
||||||
|
* API tokens for system interconnection
|
||||||
|
|
||||||
|
## Screenshot
|
||||||
|

|
||||||
|
3
renovate.json
Normal file
3
renovate.json
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"extends": ["local>renovate/presets"]
|
||||||
|
}
|
3076
virtweb_backend/Cargo.lock
generated
3076
virtweb_backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,46 +1,49 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "virtweb_backend"
|
name = "virtweb_backend"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
log = "0.4.19"
|
log = "0.4.27"
|
||||||
env_logger = "0.10.1"
|
env_logger = "0.11.8"
|
||||||
clap = { version = "4.4.11", features = ["derive", "env"] }
|
clap = { version = "4.5.40", features = ["derive", "env"] }
|
||||||
light-openid = { version = "1.0.1", features = ["crypto-wrapper"] }
|
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.5.0"
|
||||||
actix = "0.13.1"
|
actix = "0.13.5"
|
||||||
actix-web = "4"
|
actix-web = "4.11.0"
|
||||||
actix-remote-ip = "0.1.0"
|
actix-remote-ip = "0.1.0"
|
||||||
actix-session = { version = "0.8.0", features = ["cookie-session"] }
|
actix-session = { version = "0.10.1", features = ["cookie-session"] }
|
||||||
actix-identity = "0.6.0"
|
actix-identity = "0.8.0"
|
||||||
actix-cors = "0.6.5"
|
actix-cors = "0.7.1"
|
||||||
actix-files = "0.6.2"
|
actix-files = "0.6.6"
|
||||||
actix-web-actors = "4.2.0"
|
actix-ws = "0.3.0"
|
||||||
actix-http = "3.4.0"
|
actix-http = "3.11.0"
|
||||||
serde = { version = "1.0.193", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = "1.0.108"
|
serde_json = "1.0.140"
|
||||||
quick-xml = { version = "0.31.0", features = ["serialize", "overlapped-lists"] }
|
serde_yml = "0.0.12"
|
||||||
futures-util = "0.3.28"
|
quick-xml = { version = "0.37.5", features = ["serialize", "overlapped-lists"] }
|
||||||
anyhow = "1.0.75"
|
futures-util = "0.3.31"
|
||||||
actix-multipart = "0.6.1"
|
anyhow = "1.0.98"
|
||||||
tempfile = "3.8.1"
|
actix-multipart = "0.7.2"
|
||||||
reqwest = { version = "0.11.23", features = ["stream"] }
|
tempfile = "3.20.0"
|
||||||
url = "2.5.0"
|
reqwest = { version = "0.12.20", features = ["stream"] }
|
||||||
virt = "0.3.1"
|
url = "2.5.4"
|
||||||
sysinfo = { version = "0.29.11", features = ["serde"] }
|
virt = "0.4.2"
|
||||||
uuid = { version = "1.6.1", features = ["v4", "serde"] }
|
sysinfo = { version = "0.35.1", features = ["serde"] }
|
||||||
lazy-regex = "3.1.0"
|
uuid = { version = "1.16.0", features = ["v4", "serde"] }
|
||||||
thiserror = "1.0.51"
|
lazy-regex = "3.4.1"
|
||||||
image = "0.24.7"
|
thiserror = "2.0.12"
|
||||||
rand = "0.8.5"
|
image = "0.25.6"
|
||||||
bytes = "1.5.0"
|
rand = "0.9.1"
|
||||||
tokio = "1.35.0"
|
tokio = { version = "1.45.1", features = ["rt", "time", "macros"] }
|
||||||
futures = "0.3.29"
|
futures = "0.3.31"
|
||||||
ipnetwork = "0.20.0"
|
ipnetwork = { version = "0.21.1", features = ["serde"] }
|
||||||
num = "0.4.1"
|
num = "0.4.3"
|
||||||
rust-embed = { version = "8.1.0" }
|
rust-embed = { version = "8.7.2", features = ["mime-guess"] }
|
||||||
mime_guess = "2.0.4"
|
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
|
nix = { version = "0.30.1", features = ["net"] }
|
||||||
|
basic-jwt = "0.3.0"
|
||||||
|
zip = "4.1.0"
|
||||||
|
chrono = "0.4.41"
|
86
virtweb_backend/assets/img/debian.svg
Normal file
86
virtweb_backend/assets/img/debian.svg
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Generator: Adobe Illustrator 10.0, SVG Export Plug-In . SVG Version: 3.0.0 Build 77) -->
|
||||||
|
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd" [
|
||||||
|
<!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">
|
||||||
|
<!ENTITY ns_extend "http://ns.adobe.com/Extensibility/1.0/">
|
||||||
|
<!ENTITY ns_ai "http://ns.adobe.com/AdobeIllustrator/10.0/">
|
||||||
|
<!ENTITY ns_graphs "http://ns.adobe.com/Graphs/1.0/">
|
||||||
|
<!ENTITY ns_vars "http://ns.adobe.com/Variables/1.0/">
|
||||||
|
<!ENTITY ns_imrep "http://ns.adobe.com/ImageReplacement/1.0/">
|
||||||
|
<!ENTITY ns_sfw "http://ns.adobe.com/SaveForWeb/1.0/">
|
||||||
|
<!ENTITY ns_custom "http://ns.adobe.com/GenericCustomNamespace/1.0/">
|
||||||
|
<!ENTITY ns_adobe_xpath "http://ns.adobe.com/XPath/1.0/">
|
||||||
|
<!ENTITY ns_svg "http://www.w3.org/2000/svg">
|
||||||
|
<!ENTITY ns_xlink "http://www.w3.org/1999/xlink">
|
||||||
|
]>
|
||||||
|
<svg
|
||||||
|
xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;" i:viewOrigin="262 450" i:rulerOrigin="0 0" i:pageBounds="0 792 612 0"
|
||||||
|
xmlns="&ns_svg;" xmlns:xlink="&ns_xlink;" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
|
||||||
|
width="87.041" height="108.445" viewBox="0 0 87.041 108.445" overflow="visible" enable-background="new 0 0 87.041 108.445"
|
||||||
|
xml:space="preserve">
|
||||||
|
<metadata>
|
||||||
|
<variableSets xmlns="&ns_vars;">
|
||||||
|
<variableSet varSetName="binding1" locked="none">
|
||||||
|
<variables></variables>
|
||||||
|
<v:sampleDataSets xmlns="&ns_custom;" xmlns:v="&ns_vars;"></v:sampleDataSets>
|
||||||
|
</variableSet>
|
||||||
|
</variableSets>
|
||||||
|
<sfw xmlns="&ns_sfw;">
|
||||||
|
<slices></slices>
|
||||||
|
<sliceSourceBounds y="341.555" x="262" width="87.041" height="108.445" bottomLeftOrigin="true"></sliceSourceBounds>
|
||||||
|
</sfw>
|
||||||
|
</metadata>
|
||||||
|
<g id="Layer_1" i:layer="yes" i:dimmedPercent="50" i:rgbTrio="#4F008000FFFF">
|
||||||
|
<g>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M51.986,57.297c-1.797,0.025,0.34,0.926,2.686,1.287
|
||||||
|
c0.648-0.506,1.236-1.018,1.76-1.516C54.971,57.426,53.484,57.434,51.986,57.297"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M61.631,54.893c1.07-1.477,1.85-3.094,2.125-4.766c-0.24,1.192-0.887,2.221-1.496,3.307
|
||||||
|
c-3.359,2.115-0.316-1.256-0.002-2.537C58.646,55.443,61.762,53.623,61.631,54.893"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M65.191,45.629c0.217-3.236-0.637-2.213-0.924-0.978
|
||||||
|
C64.602,44.825,64.867,46.932,65.191,45.629"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M45.172,1.399c0.959,0.172,2.072,0.304,1.916,0.533
|
||||||
|
C48.137,1.702,48.375,1.49,45.172,1.399"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M47.088,1.932l-0.678,0.14l0.631-0.056L47.088,1.932"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M76.992,46.856c0.107,2.906-0.85,4.316-1.713,6.812l-1.553,0.776
|
||||||
|
c-1.271,2.468,0.123,1.567-0.787,3.53c-1.984,1.764-6.021,5.52-7.313,5.863c-0.943-0.021,0.639-1.113,0.846-1.541
|
||||||
|
c-2.656,1.824-2.131,2.738-6.193,3.846l-0.119-0.264c-10.018,4.713-23.934-4.627-23.751-17.371
|
||||||
|
c-0.107,0.809-0.304,0.607-0.526,0.934c-0.517-6.557,3.028-13.143,9.007-15.832c5.848-2.895,12.704-1.707,16.893,2.197
|
||||||
|
c-2.301-3.014-6.881-6.209-12.309-5.91c-5.317,0.084-10.291,3.463-11.951,7.131c-2.724,1.715-3.04,6.611-4.227,7.507
|
||||||
|
C31.699,56.271,36.3,61.342,44.083,67.307c1.225,0.826,0.345,0.951,0.511,1.58c-2.586-1.211-4.954-3.039-6.901-5.277
|
||||||
|
c1.033,1.512,2.148,2.982,3.589,4.137c-2.438-0.826-5.695-5.908-6.646-6.115c4.203,7.525,17.052,13.197,23.78,10.383
|
||||||
|
c-3.113,0.115-7.068,0.064-10.566-1.229c-1.469-0.756-3.467-2.322-3.11-2.615c9.182,3.43,18.667,2.598,26.612-3.771
|
||||||
|
c2.021-1.574,4.229-4.252,4.867-4.289c-0.961,1.445,0.164,0.695-0.574,1.971c2.014-3.248-0.875-1.322,2.082-5.609l1.092,1.504
|
||||||
|
c-0.406-2.696,3.348-5.97,2.967-10.234c0.861-1.304,0.961,1.403,0.047,4.403c1.268-3.328,0.334-3.863,0.66-6.609
|
||||||
|
c0.352,0.923,0.814,1.904,1.051,2.878c-0.826-3.216,0.848-5.416,1.262-7.285c-0.408-0.181-1.275,1.422-1.473-2.377
|
||||||
|
c0.029-1.65,0.459-0.865,0.625-1.271c-0.324-0.186-1.174-1.451-1.691-3.877c0.375-0.57,1.002,1.478,1.512,1.562
|
||||||
|
c-0.328-1.929-0.893-3.4-0.916-4.88c-1.49-3.114-0.527,0.415-1.736-1.337c-1.586-4.947,1.316-1.148,1.512-3.396
|
||||||
|
c2.404,3.483,3.775,8.881,4.404,11.117c-0.48-2.726-1.256-5.367-2.203-7.922c0.73,0.307-1.176-5.609,0.949-1.691
|
||||||
|
c-2.27-8.352-9.715-16.156-16.564-19.818c0.838,0.767,1.896,1.73,1.516,1.881c-3.406-2.028-2.807-2.186-3.295-3.043
|
||||||
|
c-2.775-1.129-2.957,0.091-4.795,0.002c-5.23-2.774-6.238-2.479-11.051-4.217l0.219,1.023c-3.465-1.154-4.037,0.438-7.782,0.004
|
||||||
|
c-0.228-0.178,1.2-0.644,2.375-0.815c-3.35,0.442-3.193-0.66-6.471,0.122c0.808-0.567,1.662-0.942,2.524-1.424
|
||||||
|
c-2.732,0.166-6.522,1.59-5.352,0.295c-4.456,1.988-12.37,4.779-16.811,8.943l-0.14-0.933c-2.035,2.443-8.874,7.296-9.419,10.46
|
||||||
|
l-0.544,0.127c-1.059,1.793-1.744,3.825-2.584,5.67c-1.385,2.36-2.03,0.908-1.833,1.278c-2.724,5.523-4.077,10.164-5.246,13.97
|
||||||
|
c0.833,1.245,0.02,7.495,0.335,12.497c-1.368,24.704,17.338,48.69,37.785,54.228c2.997,1.072,7.454,1.031,11.245,1.141
|
||||||
|
c-4.473-1.279-5.051-0.678-9.408-2.197c-3.143-1.48-3.832-3.17-6.058-5.102l0.881,1.557c-4.366-1.545-2.539-1.912-6.091-3.037
|
||||||
|
l0.941-1.229c-1.415-0.107-3.748-2.385-4.386-3.646l-1.548,0.061c-1.86-2.295-2.851-3.949-2.779-5.23l-0.5,0.891
|
||||||
|
c-0.567-0.973-6.843-8.607-3.587-6.83c-0.605-0.553-1.409-0.9-2.281-2.484l0.663-0.758c-1.567-2.016-2.884-4.6-2.784-5.461
|
||||||
|
c0.836,1.129,1.416,1.34,1.99,1.533c-3.957-9.818-4.179-0.541-7.176-9.994l0.634-0.051c-0.486-0.732-0.781-1.527-1.172-2.307
|
||||||
|
l0.276-2.75C4.667,58.121,6.719,47.409,7.13,41.534c0.285-2.389,2.378-4.932,3.97-8.92l-0.97-0.167
|
||||||
|
c1.854-3.234,10.586-12.988,14.63-12.486c1.959-2.461-0.389-0.009-0.772-0.629c4.303-4.453,5.656-3.146,8.56-3.947
|
||||||
|
c3.132-1.859-2.688,0.725-1.203-0.709c5.414-1.383,3.837-3.144,10.9-3.846c0.745,0.424-1.729,0.655-2.35,1.205
|
||||||
|
c4.511-2.207,14.275-1.705,20.617,1.225c7.359,3.439,15.627,13.605,15.953,23.17l0.371,0.1
|
||||||
|
c-0.188,3.802,0.582,8.199-0.752,12.238L76.992,46.856"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M32.372,59.764l-0.252,1.26c1.181,1.604,2.118,3.342,3.626,4.596
|
||||||
|
C34.661,63.502,33.855,62.627,32.372,59.764"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M35.164,59.654c-0.625-0.691-0.995-1.523-1.409-2.352
|
||||||
|
c0.396,1.457,1.207,2.709,1.962,3.982L35.164,59.654"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M84.568,48.916l-0.264,0.662c-0.484,3.438-1.529,6.84-3.131,9.994
|
||||||
|
C82.943,56.244,84.088,52.604,84.568,48.916"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M45.527,0.537C46.742,0.092,48.514,0.293,49.803,0c-1.68,0.141-3.352,0.225-5.003,0.438
|
||||||
|
L45.527,0.537"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M2.872,23.219c0.28,2.592-1.95,3.598,0.494,1.889
|
||||||
|
C4.676,22.157,2.854,24.293,2.872,23.219"/>
|
||||||
|
<path i:knockout="Off" fill="#A80030" d="M0,35.215c0.563-1.728,0.665-2.766,0.88-3.766C-0.676,33.438,0.164,33.862,0,35.215"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
After Width: | Height: | Size: 6.7 KiB |
BIN
virtweb_backend/assets/img/kvm.png
Normal file
BIN
virtweb_backend/assets/img/kvm.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 194 KiB |
8
virtweb_backend/assets/img/ubuntu.svg
Normal file
8
virtweb_backend/assets/img/ubuntu.svg
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
|
||||||
|
<circle fill="#f47421" cy="50" cx="50" r="45"/>
|
||||||
|
<circle fill="none" stroke="#ffffff" stroke-width="8.55" cx="50" cy="50" r="21.825"/>
|
||||||
|
<g id="friend"><circle fill="#f47421" cx="19.4" cy="50" r="8.4376"/>
|
||||||
|
<path stroke="#f47421" stroke-width="3.2378" d="M67,50H77"/>
|
||||||
|
<circle fill="#ffffff" cx="19.4" cy="50" r="6.00745"/></g>
|
||||||
|
<use xlink:href="#friend" transform="rotate(120,50,50)"/>
|
||||||
|
<use xlink:href="#friend" transform="rotate(240,50,50)"/></svg>
|
After Width: | Height: | Size: 550 B |
1
virtweb_backend/assets/img/windows.svg
Normal file
1
virtweb_backend/assets/img/windows.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="88" width="88" xmlns:v="https://vecta.io/nano"><path d="M0 12.402l35.687-4.86.016 34.423-35.67.203zm35.67 33.529l.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349l-.011 41.34-47.318-6.678-.066-34.739z" fill="#00adef"/></svg>
|
After Width: | Height: | Size: 311 B |
47
virtweb_backend/assets/iso_catalog.json
Normal file
47
virtweb_backend/assets/iso_catalog.json
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "Ubuntu releases",
|
||||||
|
"url": "https://releases.ubuntu.com",
|
||||||
|
"image": "/assets/img/ubuntu.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Old ubuntu releases",
|
||||||
|
"url": "https://old-releases.ubuntu.com/releases/",
|
||||||
|
"image": "/assets/img/ubuntu.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Current Debian releases (amd64)",
|
||||||
|
"url": "https://cdimage.debian.org/mirror/cdimage/release/current/amd64/iso-dvd/",
|
||||||
|
"image": "/assets/img/debian.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Old Debian releases",
|
||||||
|
"url": "https://cdimage.debian.org/mirror/cdimage/archive/",
|
||||||
|
"image": "/assets/img/debian.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Latest stable Virtio driver",
|
||||||
|
"url": "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso",
|
||||||
|
"image": "/assets/img/kvm.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Windows server 2025",
|
||||||
|
"url": "https://www.microsoft.com/en-us/evalcenter/download-windows-server-2025",
|
||||||
|
"image": "/assets/img/windows.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Windows server 2022",
|
||||||
|
"url": "https://www.microsoft.com/en-us/evalcenter/download-windows-server-2022",
|
||||||
|
"image": "/assets/img/windows.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Windows 11",
|
||||||
|
"url": "https://www.microsoft.com/en-us/software-download/windows11",
|
||||||
|
"image": "/assets/img/windows.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Windows 11 Iot Enterprise LTSC 2024",
|
||||||
|
"url": "https://www.microsoft.com/en-us/evalcenter/download-windows-11-iot-enterprise-ltsc-eval",
|
||||||
|
"image": "/assets/img/windows.svg"
|
||||||
|
}
|
||||||
|
]
|
@ -1,9 +1,8 @@
|
|||||||
services:
|
services:
|
||||||
oidc:
|
oidc:
|
||||||
image: qlik/simple-oidc-provider
|
image: dexidp/dex
|
||||||
environment:
|
|
||||||
- REDIRECTS=http://localhost:3000/oidc_cb
|
|
||||||
- PORT=9001
|
|
||||||
ports:
|
ports:
|
||||||
- 9001:9001
|
- 9001:9001
|
||||||
|
volumes:
|
||||||
|
- ./docker/dex:/conf:ro
|
||||||
|
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
27
virtweb_backend/docker/dex/dex.config.yaml
Normal file
27
virtweb_backend/docker/dex/dex.config.yaml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
issuer: http://127.0.0.1:9001/dex
|
||||||
|
|
||||||
|
storage:
|
||||||
|
type: memory
|
||||||
|
|
||||||
|
web:
|
||||||
|
http: 0.0.0.0:9001
|
||||||
|
|
||||||
|
oauth2:
|
||||||
|
# Automate some clicking
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
skipApprovalScreen: false
|
||||||
|
|
||||||
|
connectors:
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
- type: mockCallback
|
||||||
|
id: mock
|
||||||
|
name: Example
|
||||||
|
|
||||||
|
# Basic OP test suite requires two clients.
|
||||||
|
staticClients:
|
||||||
|
- id: foo
|
||||||
|
secret: bar
|
||||||
|
redirectURIs:
|
||||||
|
- http://localhost:3000/oidc_cb
|
||||||
|
- http://localhost:5173/oidc_cb
|
||||||
|
name: Project
|
67
virtweb_backend/examples/api_curl.rs
Normal file
67
virtweb_backend/examples/api_curl.rs
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
use basic_jwt::JWTPrivateKey;
|
||||||
|
use clap::Parser;
|
||||||
|
use std::os::unix::prelude::CommandExt;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use virtweb_backend::api_tokens::TokenVerb;
|
||||||
|
use virtweb_backend::extractors::api_auth_extractor::TokenClaims;
|
||||||
|
use virtweb_backend::utils::time_utils::time;
|
||||||
|
|
||||||
|
/// cURL wrapper to query Virtweb backend API
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(version, about, long_about = None)]
|
||||||
|
struct Args {
|
||||||
|
/// URL of VirtWeb
|
||||||
|
#[arg(short('u'), long, env, default_value = "http://localhost:8000")]
|
||||||
|
virtweb_url: String,
|
||||||
|
|
||||||
|
/// Token ID
|
||||||
|
#[arg(short('i'), long, env)]
|
||||||
|
token_id: String,
|
||||||
|
|
||||||
|
/// Token private key
|
||||||
|
#[arg(short('t'), long, env)]
|
||||||
|
token_key: String,
|
||||||
|
|
||||||
|
/// Request verb
|
||||||
|
#[arg(short('X'), long, default_value = "GET")]
|
||||||
|
verb: String,
|
||||||
|
|
||||||
|
/// Request URI
|
||||||
|
uri: String,
|
||||||
|
|
||||||
|
/// Command line arguments to pass to cURL
|
||||||
|
#[clap(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||||
|
run: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let full_url = format!("{}{}", args.virtweb_url, args.uri);
|
||||||
|
log::debug!("Full URL: {full_url}");
|
||||||
|
|
||||||
|
let key = JWTPrivateKey::ES384 {
|
||||||
|
r#priv: args.token_key,
|
||||||
|
};
|
||||||
|
let claims = TokenClaims {
|
||||||
|
sub: args.token_id.to_string(),
|
||||||
|
iat: time() as usize,
|
||||||
|
exp: time() as usize + 50,
|
||||||
|
verb: TokenVerb::from_str(&args.verb).expect("Invalid request verb!"),
|
||||||
|
path: args.uri,
|
||||||
|
nonce: uuid::Uuid::new_v4().to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let jwt = key.sign_jwt(&claims).expect("Failed to sign JWT!");
|
||||||
|
|
||||||
|
let err = Command::new("curl")
|
||||||
|
.args(["-X", &args.verb])
|
||||||
|
.args(["-H", &format!("x-token-id: {}", args.token_id)])
|
||||||
|
.args(["-H", &format!("x-token-content: {jwt}")])
|
||||||
|
.args(args.run)
|
||||||
|
.arg(full_url)
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
panic!("Failed to run cURL! {err}")
|
||||||
|
}
|
@ -7,8 +7,9 @@ use crate::libvirt_rest_structures::hypervisor::*;
|
|||||||
use crate::libvirt_rest_structures::net::*;
|
use crate::libvirt_rest_structures::net::*;
|
||||||
use crate::libvirt_rest_structures::nw_filter::{NetworkFilter, NetworkFilterName};
|
use crate::libvirt_rest_structures::nw_filter::{NetworkFilter, NetworkFilterName};
|
||||||
use crate::libvirt_rest_structures::vm::*;
|
use crate::libvirt_rest_structures::vm::*;
|
||||||
|
use crate::nat::nat_lib;
|
||||||
use actix::{Actor, Context, Handler, Message};
|
use actix::{Actor, Context, Handler, Message};
|
||||||
use image::ImageOutputFormat;
|
use image::ImageFormat;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
use virt::connect::Connect;
|
use virt::connect::Connect;
|
||||||
use virt::domain::Domain;
|
use virt::domain::Domain;
|
||||||
@ -30,7 +31,7 @@ impl LibVirtActor {
|
|||||||
"Will connect to hypvervisor at address '{}'",
|
"Will connect to hypvervisor at address '{}'",
|
||||||
hypervisor_uri
|
hypervisor_uri
|
||||||
);
|
);
|
||||||
let conn = Connect::open(hypervisor_uri)?;
|
let conn = Connect::open(Some(hypervisor_uri))?;
|
||||||
|
|
||||||
Ok(Self { m: conn })
|
Ok(Self { m: conn })
|
||||||
}
|
}
|
||||||
@ -181,6 +182,13 @@ impl Handler<DeleteDomainReq> for LibVirtActor {
|
|||||||
false => sys::VIR_DOMAIN_UNDEFINE_NVRAM,
|
false => sys::VIR_DOMAIN_UNDEFINE_NVRAM,
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// Delete associated cloud init disk
|
||||||
|
let cloud_init_disk = AppConfig::get().cloud_init_disk_path_for_vm(&domain_name);
|
||||||
|
if cloud_init_disk.exists() {
|
||||||
|
std::fs::remove_file(cloud_init_disk)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If requested, delete block storage associated with the VM
|
||||||
if !msg.keep_files {
|
if !msg.keep_files {
|
||||||
log::info!("Delete storage associated with the domain");
|
log::info!("Delete storage associated with the domain");
|
||||||
let path = AppConfig::get().vm_storage_path(msg.id);
|
let path = AppConfig::get().vm_storage_path(msg.id);
|
||||||
@ -336,7 +344,7 @@ impl Handler<ScreenshotDomainReq> for LibVirtActor {
|
|||||||
|
|
||||||
let image = image::load_from_memory(&screen_out)?;
|
let image = image::load_from_memory(&screen_out)?;
|
||||||
let mut png_out = Cursor::new(Vec::new());
|
let mut png_out = Cursor::new(Vec::new());
|
||||||
image.write_to(&mut png_out, ImageOutputFormat::Png)?;
|
image.write_to(&mut png_out, ImageFormat::Png)?;
|
||||||
|
|
||||||
Ok(png_out.into_inner())
|
Ok(png_out.into_inner())
|
||||||
}
|
}
|
||||||
@ -395,6 +403,9 @@ impl Handler<DefineNetwork> for LibVirtActor {
|
|||||||
let network = Network::define_xml(&self.m, &network_xml)?;
|
let network = Network::define_xml(&self.m, &network_xml)?;
|
||||||
let uuid = XMLUuid::parse_from_str(&network.get_uuid_string()?)?;
|
let uuid = XMLUuid::parse_from_str(&network.get_uuid_string()?)?;
|
||||||
|
|
||||||
|
// Save NAT definition
|
||||||
|
nat_lib::save_nat_def(&msg.0)?;
|
||||||
|
|
||||||
// Save a copy of the source definition
|
// Save a copy of the source definition
|
||||||
msg.0.uuid = Some(uuid);
|
msg.0.uuid = Some(uuid);
|
||||||
let json = serde_json::to_string(&msg.0)?;
|
let json = serde_json::to_string(&msg.0)?;
|
||||||
@ -464,9 +475,12 @@ impl Handler<DeleteNetwork> for LibVirtActor {
|
|||||||
fn handle(&mut self, msg: DeleteNetwork, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: DeleteNetwork, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
log::debug!("Delete network: {}\n", msg.0.as_string());
|
log::debug!("Delete network: {}\n", msg.0.as_string());
|
||||||
let network = Network::lookup_by_uuid_string(&self.m, &msg.0.as_string())?;
|
let network = Network::lookup_by_uuid_string(&self.m, &msg.0.as_string())?;
|
||||||
let network_name = network.get_name()?;
|
let network_name = NetworkName(network.get_name()?);
|
||||||
network.undefine()?;
|
network.undefine()?;
|
||||||
|
|
||||||
|
// Remove NAT definition, if any
|
||||||
|
nat_lib::remove_nat_def(&network_name)?;
|
||||||
|
|
||||||
// Remove backup definition
|
// Remove backup definition
|
||||||
let backup_definition = AppConfig::get().net_definition_path(&network_name);
|
let backup_definition = AppConfig::get().net_definition_path(&network_name);
|
||||||
if backup_definition.exists() {
|
if backup_definition.exists() {
|
||||||
|
@ -1,3 +1,3 @@
|
|||||||
pub mod libvirt_actor;
|
pub mod libvirt_actor;
|
||||||
pub mod vnc_actor;
|
pub mod vnc_handler;
|
||||||
pub mod vnc_tokens_actor;
|
pub mod vnc_tokens_actor;
|
||||||
|
@ -1,209 +0,0 @@
|
|||||||
use actix::{Actor, ActorContext, AsyncContext, Handler, StreamHandler};
|
|
||||||
use actix_http::ws::Item;
|
|
||||||
use actix_web_actors::ws;
|
|
||||||
use actix_web_actors::ws::Message;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use image::EncodableLayout;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
||||||
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
|
|
||||||
use tokio::net::UnixStream;
|
|
||||||
|
|
||||||
/// How often heartbeat pings are sent
|
|
||||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|
||||||
|
|
||||||
/// How long before lack of client response causes a timeout
|
|
||||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
|
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
enum VNCError {
|
|
||||||
#[error("Socket file does not exists!")]
|
|
||||||
SocketDoesNotExists,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct VNCActor {
|
|
||||||
/// Qemu -> WS
|
|
||||||
read_half: Option<OwnedReadHalf>,
|
|
||||||
|
|
||||||
/// WS -> Qemu
|
|
||||||
write_half: OwnedWriteHalf,
|
|
||||||
|
|
||||||
// Client must respond to ping at a specific interval, otherwise we drop connection
|
|
||||||
hb: Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VNCActor {
|
|
||||||
pub async fn new(socket_path: &str) -> anyhow::Result<Self> {
|
|
||||||
let socket_path = Path::new(socket_path);
|
|
||||||
|
|
||||||
if !socket_path.exists() {
|
|
||||||
return Err(VNCError::SocketDoesNotExists.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let socket = UnixStream::connect(socket_path).await?;
|
|
||||||
let (read_half, write_half) = socket.into_split();
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
read_half: Some(read_half),
|
|
||||||
write_half,
|
|
||||||
hb: Instant::now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// helper method that sends ping to client every second.
|
|
||||||
///
|
|
||||||
/// also this method checks heartbeats from client
|
|
||||||
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
|
|
||||||
// check client heartbeats
|
|
||||||
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
|
|
||||||
// heartbeat timed out
|
|
||||||
log::warn!("WebSocket Client heartbeat failed, disconnecting!");
|
|
||||||
ctx.stop();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.ping(b"");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_to_socket(&mut self, bytes: Bytes, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
log::trace!("Received {} bytes for VNC socket", bytes.len());
|
|
||||||
|
|
||||||
if let Err(e) = futures::executor::block_on(self.write_half.write(bytes.as_bytes())) {
|
|
||||||
log::error!("Failed to relay bytes to VNC socket {e}");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_qemu_to_ws_end(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
let mut read_half = self.read_half.take().unwrap();
|
|
||||||
let addr = ctx.address();
|
|
||||||
let future = async move {
|
|
||||||
let mut buff: [u8; 5000] = [0; 5000];
|
|
||||||
loop {
|
|
||||||
match read_half.read(&mut buff).await {
|
|
||||||
Ok(mut l) => {
|
|
||||||
if l == 0 {
|
|
||||||
log::warn!("Got empty read!");
|
|
||||||
|
|
||||||
// Ugly hack made to wait for next byte
|
|
||||||
let mut one_byte_buff: [u8; 1] = [0; 1];
|
|
||||||
match read_half.read_exact(&mut one_byte_buff).await {
|
|
||||||
Ok(b) => {
|
|
||||||
if b == 0 {
|
|
||||||
log::error!("Did not get a byte !");
|
|
||||||
let _ = addr.send(CloseWebSocketReq).await;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
buff[0] = one_byte_buff[0];
|
|
||||||
l = 1;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to read 1 BYTE from remote socket. Stopping now... {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let to_send = SendBytesReq(Vec::from(&buff[0..l]));
|
|
||||||
if let Err(e) = addr.send(to_send).await {
|
|
||||||
log::error!("Failed to send to websocket. Stopping now... {:?}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to read from remote socket. Stopping now... {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
log::info!("Exited read loop");
|
|
||||||
};
|
|
||||||
|
|
||||||
tokio::spawn(future);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Actor for VNCActor {
|
|
||||||
type Context = ws::WebsocketContext<Self>;
|
|
||||||
|
|
||||||
fn started(&mut self, ctx: &mut Self::Context) {
|
|
||||||
self.hb(ctx);
|
|
||||||
self.start_qemu_to_ws_end(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StreamHandler<Result<Message, ws::ProtocolError>> for VNCActor {
|
|
||||||
fn handle(&mut self, msg: Result<Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
|
||||||
match msg {
|
|
||||||
Ok(Message::Ping(msg)) => ctx.pong(&msg),
|
|
||||||
|
|
||||||
Ok(Message::Text(_text)) => {
|
|
||||||
log::error!("Received unexpected text on VNC WebSocket!");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Binary(bin)) => {
|
|
||||||
log::info!("Forward {} bytes to VNC server", bin.len());
|
|
||||||
self.send_to_socket(bin, ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Continuation(msg)) => match msg {
|
|
||||||
Item::FirstText(_) => {
|
|
||||||
log::error!("Received unexpected split text!");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
Item::FirstBinary(bin) | Item::Continue(bin) | Item::Last(bin) => {
|
|
||||||
self.send_to_socket(bin, ctx);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
Ok(Message::Pong(_)) => {
|
|
||||||
log::trace!("Received PONG message");
|
|
||||||
self.hb = Instant::now();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Close(r)) => {
|
|
||||||
log::info!("WebSocket closed. Reason={r:?}");
|
|
||||||
ctx.close(r);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Nop) => {
|
|
||||||
log::debug!("Received Nop message")
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("WebSocket protocol error! {e}");
|
|
||||||
ctx.close(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
|
||||||
#[rtype(result = "()")]
|
|
||||||
pub struct SendBytesReq(Vec<u8>);
|
|
||||||
|
|
||||||
impl Handler<SendBytesReq> for VNCActor {
|
|
||||||
type Result = ();
|
|
||||||
|
|
||||||
fn handle(&mut self, msg: SendBytesReq, ctx: &mut Self::Context) -> Self::Result {
|
|
||||||
log::trace!("Send {} bytes to WS", msg.0.len());
|
|
||||||
ctx.binary(msg.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
|
||||||
#[rtype(result = "()")]
|
|
||||||
pub struct CloseWebSocketReq;
|
|
||||||
|
|
||||||
impl Handler<CloseWebSocketReq> for VNCActor {
|
|
||||||
type Result = ();
|
|
||||||
|
|
||||||
fn handle(&mut self, _msg: CloseWebSocketReq, ctx: &mut Self::Context) -> Self::Result {
|
|
||||||
log::trace!("Close websocket, because VNC socket has terminated");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
}
|
|
129
virtweb_backend/src/actors/vnc_handler.rs
Normal file
129
virtweb_backend/src/actors/vnc_handler.rs
Normal file
@ -0,0 +1,129 @@
|
|||||||
|
use actix_http::ws::Message;
|
||||||
|
use futures_util::StreamExt as _;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::UnixStream;
|
||||||
|
use tokio::select;
|
||||||
|
use tokio::time::interval;
|
||||||
|
|
||||||
|
/// How often heartbeat pings are sent
|
||||||
|
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// How long before lack of client response causes a timeout
|
||||||
|
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||||
|
|
||||||
|
/// Broadcast text & binary messages received from a client, respond to ping messages, and monitor
|
||||||
|
/// connection health to detect network issues and free up resources.
|
||||||
|
pub async fn handle(
|
||||||
|
mut session: actix_ws::Session,
|
||||||
|
mut msg_stream: actix_ws::MessageStream,
|
||||||
|
mut socket: UnixStream,
|
||||||
|
) {
|
||||||
|
log::info!("Connected to websocket");
|
||||||
|
|
||||||
|
let mut last_heartbeat = Instant::now();
|
||||||
|
let mut interval = interval(HEARTBEAT_INTERVAL);
|
||||||
|
|
||||||
|
let mut buf_socket = [0u8; 1024];
|
||||||
|
|
||||||
|
let reason = loop {
|
||||||
|
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
|
||||||
|
// to send a message, or the heartbeat interval timer to tick, yielding the value of
|
||||||
|
// whichever one is ready first
|
||||||
|
select! {
|
||||||
|
|
||||||
|
// heartbeat interval ticked
|
||||||
|
_tick = interval.tick() => {
|
||||||
|
// if no heartbeat ping/pong received recently, close the connection
|
||||||
|
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
|
||||||
|
log::info!(
|
||||||
|
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
|
||||||
|
);
|
||||||
|
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// send heartbeat ping
|
||||||
|
let _ = session.ping(b"").await;
|
||||||
|
}
|
||||||
|
|
||||||
|
msg = msg_stream.next() => {
|
||||||
|
let msg = match msg {
|
||||||
|
// received message from WebSocket client
|
||||||
|
Some(Ok(msg)) => msg,
|
||||||
|
|
||||||
|
// client WebSocket stream error
|
||||||
|
Some(Err(err)) => {
|
||||||
|
log::error!("{err}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// client WebSocket stream ended
|
||||||
|
None => break None
|
||||||
|
};
|
||||||
|
|
||||||
|
log::debug!("msg: {msg:?}");
|
||||||
|
|
||||||
|
match msg {
|
||||||
|
Message::Text(_) => {
|
||||||
|
log::error!("Received unexpected text on VNC WebSocket!");
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Binary(bin) => {
|
||||||
|
log::info!("Forward {} bytes to VNC server", bin.len());
|
||||||
|
if let Err(e) = socket.write(&bin).await {
|
||||||
|
log::error!("Failed to relay bytes to VNC socket {e}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Close(reason) => {
|
||||||
|
break reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Ping(bytes) => {
|
||||||
|
last_heartbeat = Instant::now();
|
||||||
|
let _ = session.pong(&bytes).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Pong(_) => {
|
||||||
|
last_heartbeat = Instant::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Continuation(_) => {
|
||||||
|
log::warn!("no support for continuation frames");
|
||||||
|
}
|
||||||
|
|
||||||
|
// no-op; ignore
|
||||||
|
Message::Nop => {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forward socket packet to WS client
|
||||||
|
count = socket.read(&mut buf_socket) => {
|
||||||
|
let count = match count {
|
||||||
|
Ok(count) => count,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[VNC] Failed to read from upstream! {e}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if count == 0 {
|
||||||
|
log::warn!("[VNC] infinite loop (upstream), closing connection");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e)=session.binary(buf_socket[0..count].to_vec()).await{
|
||||||
|
log::error!("[VNC] Failed to forward messages to upstream, will close connection! {e}");
|
||||||
|
break None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// attempt to close connection gracefully
|
||||||
|
let _ = session.close(reason).await;
|
||||||
|
|
||||||
|
log::info!("Disconnected from websocket");
|
||||||
|
}
|
299
virtweb_backend/src/api_tokens.rs
Normal file
299
virtweb_backend/src/api_tokens.rs
Normal file
@ -0,0 +1,299 @@
|
|||||||
|
//! # API tokens management
|
||||||
|
|
||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
use actix_http::Method;
|
||||||
|
use basic_jwt::{JWTPrivateKey, JWTPublicKey};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
|
||||||
|
pub struct TokenID(pub uuid::Uuid);
|
||||||
|
|
||||||
|
impl TokenID {
|
||||||
|
/// Parse a string as a token id
|
||||||
|
pub fn parse(t: &str) -> anyhow::Result<Self> {
|
||||||
|
Ok(Self(uuid::Uuid::parse_str(t)?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
||||||
|
pub struct TokenRight {
|
||||||
|
verb: TokenVerb,
|
||||||
|
path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct TokenRights(Vec<TokenRight>);
|
||||||
|
|
||||||
|
impl TokenRights {
|
||||||
|
pub fn check_error(&self) -> Option<&'static str> {
|
||||||
|
for r in &self.0 {
|
||||||
|
if !r.path.starts_with("/api/") {
|
||||||
|
return Some("All API rights shall start with /api/");
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.path.len() > constants::API_TOKEN_RIGHT_PATH_MAX_LENGTH {
|
||||||
|
return Some("An API path shall not exceed maximum URL size!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, verb: TokenVerb, path: &str) -> bool {
|
||||||
|
let req_path_split = path.split('/').collect::<Vec<_>>();
|
||||||
|
|
||||||
|
'root: for r in &self.0 {
|
||||||
|
if r.verb != verb {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut last_idx = 0;
|
||||||
|
for (idx, part) in r.path.split('/').enumerate() {
|
||||||
|
if idx >= req_path_split.len() {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
if part != "*" && part != req_path_split[idx] {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
last_idx = idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check we visited the whole path
|
||||||
|
if last_idx + 1 == req_path_split.len() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct Token {
|
||||||
|
pub id: TokenID,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
created: u64,
|
||||||
|
updated: u64,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pub_key: Option<JWTPublicKey>,
|
||||||
|
pub rights: TokenRights,
|
||||||
|
pub last_used: u64,
|
||||||
|
pub ip_restriction: Option<ipnetwork::IpNetwork>,
|
||||||
|
pub max_inactivity: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Token {
|
||||||
|
/// Turn the token into a JSON string
|
||||||
|
fn save(&self) -> anyhow::Result<()> {
|
||||||
|
let json = serde_json::to_string(self)?;
|
||||||
|
|
||||||
|
std::fs::write(AppConfig::get().api_token_definition_path(self.id), json)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load token information from a file
|
||||||
|
fn load_from_file(path: &Path) -> anyhow::Result<Self> {
|
||||||
|
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether a token is expired or not
|
||||||
|
pub fn is_expired(&self) -> bool {
|
||||||
|
if let Some(max_inactivity) = self.max_inactivity {
|
||||||
|
if max_inactivity + self.last_used < time() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether last_used shall be updated or not
|
||||||
|
pub fn should_update_last_activity(&self) -> bool {
|
||||||
|
self.last_used + 3600 < time()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
|
||||||
|
pub enum TokenVerb {
|
||||||
|
GET,
|
||||||
|
POST,
|
||||||
|
PUT,
|
||||||
|
PATCH,
|
||||||
|
DELETE,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenVerb {
|
||||||
|
pub fn as_method(&self) -> Method {
|
||||||
|
match self {
|
||||||
|
TokenVerb::GET => Method::GET,
|
||||||
|
TokenVerb::POST => Method::POST,
|
||||||
|
TokenVerb::PUT => Method::PUT,
|
||||||
|
TokenVerb::PATCH => Method::PATCH,
|
||||||
|
TokenVerb::DELETE => Method::DELETE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for TokenVerb {
|
||||||
|
type Err = ();
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"GET" => Ok(TokenVerb::GET),
|
||||||
|
"POST" => Ok(TokenVerb::POST),
|
||||||
|
"PUT" => Ok(TokenVerb::PUT),
|
||||||
|
"PATCH" => Ok(TokenVerb::PATCH),
|
||||||
|
"DELETE" => Ok(TokenVerb::DELETE),
|
||||||
|
_ => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structure used to create a token
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct NewToken {
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub rights: TokenRights,
|
||||||
|
pub ip_restriction: Option<ipnetwork::IpNetwork>,
|
||||||
|
pub max_inactivity: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NewToken {
|
||||||
|
/// Check for error in token
|
||||||
|
pub fn check_error(&self) -> Option<&'static str> {
|
||||||
|
if self.name.len() < constants::API_TOKEN_NAME_MIN_LENGTH {
|
||||||
|
return Some("Name is too short!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.name.len() > constants::API_TOKEN_NAME_MAX_LENGTH {
|
||||||
|
return Some("Name is too long!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.description.len() < constants::API_TOKEN_DESCRIPTION_MIN_LENGTH {
|
||||||
|
return Some("Description is too short!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.description.len() > constants::API_TOKEN_DESCRIPTION_MAX_LENGTH {
|
||||||
|
return Some("Description is too long!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(err) = self.rights.check_error() {
|
||||||
|
return Some(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(t) = self.max_inactivity {
|
||||||
|
if t < 3600 {
|
||||||
|
return Some("API tokens shall be valid for at least 1 hour!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new Token
|
||||||
|
pub async fn create(t: &NewToken) -> anyhow::Result<(Token, JWTPrivateKey)> {
|
||||||
|
let priv_key = JWTPrivateKey::generate_ec384_signing_key()?;
|
||||||
|
let pub_key = priv_key.to_public_key()?;
|
||||||
|
|
||||||
|
let token = Token {
|
||||||
|
name: t.name.to_string(),
|
||||||
|
description: t.description.to_string(),
|
||||||
|
id: TokenID(uuid::Uuid::new_v4()),
|
||||||
|
created: time(),
|
||||||
|
updated: time(),
|
||||||
|
pub_key: Some(pub_key),
|
||||||
|
rights: t.rights.clone(),
|
||||||
|
last_used: time(),
|
||||||
|
ip_restriction: t.ip_restriction,
|
||||||
|
max_inactivity: t.max_inactivity,
|
||||||
|
};
|
||||||
|
|
||||||
|
token.save()?;
|
||||||
|
|
||||||
|
Ok((token, priv_key))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the entire list of api tokens
|
||||||
|
pub async fn full_list() -> anyhow::Result<Vec<Token>> {
|
||||||
|
let mut list = Vec::new();
|
||||||
|
for f in std::fs::read_dir(AppConfig::get().api_tokens_path())? {
|
||||||
|
list.push(Token::load_from_file(&f?.path())?);
|
||||||
|
}
|
||||||
|
Ok(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the information about a single token
|
||||||
|
pub async fn get_single(id: TokenID) -> anyhow::Result<Token> {
|
||||||
|
Token::load_from_file(&AppConfig::get().api_token_definition_path(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update API tokens rights
|
||||||
|
pub async fn update_rights(id: TokenID, rights: TokenRights) -> anyhow::Result<()> {
|
||||||
|
let mut token = get_single(id).await?;
|
||||||
|
token.rights = rights;
|
||||||
|
token.updated = time();
|
||||||
|
token.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set last_used value of token
|
||||||
|
pub async fn refresh_last_used(id: TokenID) -> anyhow::Result<()> {
|
||||||
|
let mut token = get_single(id).await?;
|
||||||
|
token.last_used = time();
|
||||||
|
token.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete an API token
|
||||||
|
pub async fn delete(id: TokenID) -> anyhow::Result<()> {
|
||||||
|
let path = AppConfig::get().api_token_definition_path(id);
|
||||||
|
if path.exists() {
|
||||||
|
std::fs::remove_file(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::api_tokens::{TokenRight, TokenRights, TokenVerb};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_rights_patch() {
|
||||||
|
let rights = TokenRights(vec![
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/*".to_string(),
|
||||||
|
verb: TokenVerb::GET,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/a".to_string(),
|
||||||
|
verb: TokenVerb::PUT,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/a/other".to_string(),
|
||||||
|
verb: TokenVerb::DELETE,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/net/create".to_string(),
|
||||||
|
verb: TokenVerb::POST,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert!(rights.contains(TokenVerb::GET, "/api/vm/ab"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/vm"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/vm/ab/c"));
|
||||||
|
assert!(rights.contains(TokenVerb::PUT, "/api/vm/a"));
|
||||||
|
assert!(!rights.contains(TokenVerb::PUT, "/api/vm/other"));
|
||||||
|
assert!(rights.contains(TokenVerb::POST, "/api/net/create"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/net/create"));
|
||||||
|
assert!(!rights.contains(TokenVerb::POST, "/api/net/b"));
|
||||||
|
assert!(!rights.contains(TokenVerb::POST, "/api/net/create/b"));
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,7 @@
|
|||||||
|
use crate::api_tokens::TokenID;
|
||||||
|
use crate::constants;
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_rest_structures::net::NetworkName;
|
||||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilterName;
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilterName;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use std::net::IpAddr;
|
use std::net::IpAddr;
|
||||||
@ -65,7 +68,7 @@ pub struct AppConfig {
|
|||||||
#[arg(
|
#[arg(
|
||||||
long,
|
long,
|
||||||
env,
|
env,
|
||||||
default_value = "http://localhost:9001/.well-known/openid-configuration"
|
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
|
||||||
)]
|
)]
|
||||||
pub oidc_configuration_url: String,
|
pub oidc_configuration_url: String,
|
||||||
|
|
||||||
@ -100,10 +103,15 @@ pub struct AppConfig {
|
|||||||
#[arg(short = 'H', long, env)]
|
#[arg(short = 'H', long, env)]
|
||||||
pub hypervisor_uri: Option<String>,
|
pub hypervisor_uri: Option<String>,
|
||||||
|
|
||||||
/// Trusted network. If set, a client from a different will not be able to perform request other
|
/// Trusted network. If set, a client (user) from a different network will not be able to perform
|
||||||
/// than those with GET verb (aside for login)
|
/// request other than those with GET verb (aside for login)
|
||||||
#[arg(short = 'T', long, env)]
|
#[arg(short = 'T', long, env)]
|
||||||
pub trusted_network: Vec<String>,
|
pub trusted_network: Vec<String>,
|
||||||
|
|
||||||
|
/// Comma-separated list of allowed networks. If set, a client (user or API token) from a
|
||||||
|
/// different network will not be able to access VirtWeb
|
||||||
|
#[arg(short = 'A', long, env)]
|
||||||
|
pub allowed_networks: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@ -187,6 +195,25 @@ impl AppConfig {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if an IP belongs to an allowed network or not
|
||||||
|
pub fn is_allowed_ip(&self, ip: IpAddr) -> bool {
|
||||||
|
if self.allowed_networks.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for i in &self.allowed_networks {
|
||||||
|
for sub_i in i.split(',') {
|
||||||
|
let net =
|
||||||
|
ipnetwork::IpNetwork::from_str(sub_i).expect("Allowed network is invalid!");
|
||||||
|
if net.contains(ip) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
/// Get OpenID providers configuration
|
/// Get OpenID providers configuration
|
||||||
pub fn openid_provider(&self) -> Option<OIDCProvider<'_>> {
|
pub fn openid_provider(&self) -> Option<OIDCProvider<'_>> {
|
||||||
if self.disable_oidc {
|
if self.disable_oidc {
|
||||||
@ -218,11 +245,34 @@ impl AppConfig {
|
|||||||
storage_path.canonicalize().unwrap()
|
storage_path.canonicalize().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get iso storage directory
|
/// Get iso files storage directory
|
||||||
pub fn iso_storage_path(&self) -> PathBuf {
|
pub fn iso_storage_path(&self) -> PathBuf {
|
||||||
self.storage_path().join("iso")
|
self.storage_path().join("iso")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the path where generated cloud init disk image are stored
|
||||||
|
pub fn cloud_init_disk_storage_path(&self) -> PathBuf {
|
||||||
|
self.storage_path().join("cloud_init_disks")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the path where the disk image of a VM is stored
|
||||||
|
pub fn cloud_init_disk_path_for_vm(&self, name: &str) -> PathBuf {
|
||||||
|
self.cloud_init_disk_storage_path().join(format!(
|
||||||
|
"{}-{name}.iso",
|
||||||
|
constants::CLOUD_INIT_IMAGE_PREFIX_NAME
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get disk images storage directory
|
||||||
|
pub fn disk_images_storage_path(&self) -> PathBuf {
|
||||||
|
self.storage_path().join("disk_images")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the path of a disk image file
|
||||||
|
pub fn disk_images_file_path(&self, name: &str) -> PathBuf {
|
||||||
|
self.disk_images_storage_path().join(name)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get VM vnc sockets directory
|
/// Get VM vnc sockets directory
|
||||||
pub fn vnc_sockets_path(&self) -> PathBuf {
|
pub fn vnc_sockets_path(&self) -> PathBuf {
|
||||||
self.storage_path().join("vnc")
|
self.storage_path().join("vnc")
|
||||||
@ -233,15 +283,17 @@ impl AppConfig {
|
|||||||
self.vnc_sockets_path().join(format!("vnc-{}", name))
|
self.vnc_sockets_path().join(format!("vnc-{}", name))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get VM vnc sockets directory
|
/// Get VM root disks storage directory
|
||||||
pub fn disks_storage_path(&self) -> PathBuf {
|
pub fn root_vm_disks_storage_path(&self) -> PathBuf {
|
||||||
self.storage_path().join("disks")
|
self.storage_path().join("disks")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get specific VM disk storage directory
|
||||||
pub fn vm_storage_path(&self, id: XMLUuid) -> PathBuf {
|
pub fn vm_storage_path(&self, id: XMLUuid) -> PathBuf {
|
||||||
self.disks_storage_path().join(id.as_string())
|
self.root_vm_disks_storage_path().join(id.as_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the path were VM definitions are backed up
|
||||||
pub fn definitions_path(&self) -> PathBuf {
|
pub fn definitions_path(&self) -> PathBuf {
|
||||||
self.storage_path().join("definitions")
|
self.storage_path().join("definitions")
|
||||||
}
|
}
|
||||||
@ -250,14 +302,30 @@ impl AppConfig {
|
|||||||
self.definitions_path().join(format!("vm-{name}.json"))
|
self.definitions_path().join(format!("vm-{name}.json"))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn net_definition_path(&self, name: &str) -> PathBuf {
|
pub fn net_definition_path(&self, name: &NetworkName) -> PathBuf {
|
||||||
self.definitions_path().join(format!("net-{name}.json"))
|
self.definitions_path().join(format!("net-{}.json", name.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn nat_path(&self) -> PathBuf {
|
||||||
|
self.storage_path().join(constants::STORAGE_NAT_DIR)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn net_nat_path(&self, name: &NetworkName) -> PathBuf {
|
||||||
|
self.nat_path().join(name.nat_file_name())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn net_filter_definition_path(&self, name: &NetworkFilterName) -> PathBuf {
|
pub fn net_filter_definition_path(&self, name: &NetworkFilterName) -> PathBuf {
|
||||||
self.definitions_path()
|
self.definitions_path()
|
||||||
.join(format!("nwfilter-{}.json", name.0))
|
.join(format!("nwfilter-{}.json", name.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn api_tokens_path(&self) -> PathBuf {
|
||||||
|
self.storage_path().join(constants::STORAGE_TOKENS_DIR)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn api_token_definition_path(&self, id: TokenID) -> PathBuf {
|
||||||
|
self.api_tokens_path().join(format!("{}.json", id.0))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
use crate::utils::file_size_utils::FileSize;
|
||||||
|
|
||||||
/// Name of the cookie that contains session information
|
/// Name of the cookie that contains session information
|
||||||
pub const SESSION_COOKIE_NAME: &str = "X-auth-token";
|
pub const SESSION_COOKIE_NAME: &str = "X-auth-token";
|
||||||
|
|
||||||
@ -17,20 +19,32 @@ pub const ROUTES_WITHOUT_AUTH: [&str; 5] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
/// Allowed ISO mimetypes
|
/// Allowed ISO mimetypes
|
||||||
pub const ALLOWED_ISO_MIME_TYPES: [&str; 3] = [
|
pub const ALLOWED_ISO_MIME_TYPES: [&str; 4] = [
|
||||||
"application/x-cd-image",
|
"application/x-cd-image",
|
||||||
"application/x-iso9660-image",
|
"application/x-iso9660-image",
|
||||||
"application/octet-stream",
|
"application/octet-stream",
|
||||||
|
"application/vnd.efi.iso",
|
||||||
];
|
];
|
||||||
|
|
||||||
/// ISO max size
|
/// ISO max size
|
||||||
pub const ISO_MAX_SIZE: usize = 10 * 1000 * 1000 * 1000;
|
pub const ISO_MAX_SIZE: FileSize = FileSize::from_gb(10);
|
||||||
|
|
||||||
/// Min VM memory size (MB)
|
/// Allowed uploaded disk images formats
|
||||||
pub const MIN_VM_MEMORY: usize = 100;
|
pub const ALLOWED_DISK_IMAGES_MIME_TYPES: [&str; 4] = [
|
||||||
|
"application/x-qemu-disk",
|
||||||
|
"application/x-raw-disk-image",
|
||||||
|
"application/gzip",
|
||||||
|
"application/octet-stream",
|
||||||
|
];
|
||||||
|
|
||||||
/// Max VM memory size (MB)
|
/// Disk image max size
|
||||||
pub const MAX_VM_MEMORY: usize = 64000;
|
pub const DISK_IMAGE_MAX_SIZE: FileSize = FileSize::from_gb(10 * 1000);
|
||||||
|
|
||||||
|
/// Min VM memory size
|
||||||
|
pub const MIN_VM_MEMORY: FileSize = FileSize::from_mb(100);
|
||||||
|
|
||||||
|
/// Max VM memory size
|
||||||
|
pub const MAX_VM_MEMORY: FileSize = FileSize::from_gb(64);
|
||||||
|
|
||||||
/// Disk name min length
|
/// Disk name min length
|
||||||
pub const DISK_NAME_MIN_LEN: usize = 2;
|
pub const DISK_NAME_MIN_LEN: usize = 2;
|
||||||
@ -38,11 +52,17 @@ pub const DISK_NAME_MIN_LEN: usize = 2;
|
|||||||
/// Disk name max length
|
/// Disk name max length
|
||||||
pub const DISK_NAME_MAX_LEN: usize = 10;
|
pub const DISK_NAME_MAX_LEN: usize = 10;
|
||||||
|
|
||||||
/// Disk size min (MB)
|
/// Disk size min (B)
|
||||||
pub const DISK_SIZE_MIN: usize = 100;
|
pub const DISK_SIZE_MIN: FileSize = FileSize::from_mb(50);
|
||||||
|
|
||||||
/// Disk size max (MB)
|
/// Disk size max (B)
|
||||||
pub const DISK_SIZE_MAX: usize = 1000 * 1000 * 2;
|
pub const DISK_SIZE_MAX: FileSize = FileSize::from_gb(20000);
|
||||||
|
|
||||||
|
/// Cloud init generated disk image prefix
|
||||||
|
pub const CLOUD_INIT_IMAGE_PREFIX_NAME: &str = "virtweb-cloudinit-autogen-image";
|
||||||
|
|
||||||
|
/// Net nat entry comment max size
|
||||||
|
pub const NET_NAT_COMMENT_MAX_SIZE: usize = 250;
|
||||||
|
|
||||||
/// Network mac address default prefix
|
/// Network mac address default prefix
|
||||||
pub const NET_MAC_ADDR_PREFIX: &str = "52:54:00";
|
pub const NET_MAC_ADDR_PREFIX: &str = "52:54:00";
|
||||||
@ -77,3 +97,54 @@ pub const BUILTIN_NETWORK_FILTER_RULES: [&str; 24] = [
|
|||||||
|
|
||||||
/// List of valid network chains
|
/// List of valid network chains
|
||||||
pub const NETWORK_CHAINS: [&str; 8] = ["root", "mac", "stp", "vlan", "arp", "rarp", "ipv4", "ipv6"];
|
pub const NETWORK_CHAINS: [&str; 8] = ["root", "mac", "stp", "vlan", "arp", "rarp", "ipv4", "ipv6"];
|
||||||
|
|
||||||
|
/// Directory where nat rules are stored, inside storage directory
|
||||||
|
pub const STORAGE_NAT_DIR: &str = "nat";
|
||||||
|
|
||||||
|
/// Environment variable that is set to run VirtWeb in NAT configuration mode
|
||||||
|
pub const NAT_MODE_ENV_VAR_NAME: &str = "NAT_MODE";
|
||||||
|
|
||||||
|
/// Nat hook file path
|
||||||
|
pub const NAT_HOOK_PATH: &str = "/etc/libvirt/hooks/network";
|
||||||
|
|
||||||
|
/// Directory where API tokens are stored, inside storage directory
|
||||||
|
pub const STORAGE_TOKENS_DIR: &str = "tokens";
|
||||||
|
|
||||||
|
/// API token name min length
|
||||||
|
pub const API_TOKEN_NAME_MIN_LENGTH: usize = 3;
|
||||||
|
|
||||||
|
/// API token name max length
|
||||||
|
pub const API_TOKEN_NAME_MAX_LENGTH: usize = 30;
|
||||||
|
|
||||||
|
/// API token description min length
|
||||||
|
pub const API_TOKEN_DESCRIPTION_MIN_LENGTH: usize = 5;
|
||||||
|
|
||||||
|
/// API token description max length
|
||||||
|
pub const API_TOKEN_DESCRIPTION_MAX_LENGTH: usize = 30;
|
||||||
|
|
||||||
|
/// API token right path max length
|
||||||
|
pub const API_TOKEN_RIGHT_PATH_MAX_LENGTH: usize = 255;
|
||||||
|
|
||||||
|
/// Qemu image program path
|
||||||
|
pub const PROGRAM_QEMU_IMAGE: &str = "/usr/bin/qemu-img";
|
||||||
|
|
||||||
|
/// IP program path
|
||||||
|
pub const PROGRAM_IP: &str = "/usr/sbin/ip";
|
||||||
|
|
||||||
|
/// Copy program path
|
||||||
|
pub const PROGRAM_COPY: &str = "/bin/cp";
|
||||||
|
|
||||||
|
/// Gzip program path
|
||||||
|
pub const PROGRAM_GZIP: &str = "/usr/bin/gzip";
|
||||||
|
|
||||||
|
/// XZ program path
|
||||||
|
pub const PROGRAM_XZ: &str = "/usr/bin/xz";
|
||||||
|
|
||||||
|
/// Bash program
|
||||||
|
pub const PROGRAM_BASH: &str = "/usr/bin/bash";
|
||||||
|
|
||||||
|
/// DD program
|
||||||
|
pub const PROGRAM_DD: &str = "/usr/bin/dd";
|
||||||
|
|
||||||
|
/// cloud-localds program
|
||||||
|
pub const PROGRAM_CLOUD_LOCALDS: &str = "/usr/bin/cloud-localds";
|
||||||
|
100
virtweb_backend/src/controllers/api_tokens_controller.rs
Normal file
100
virtweb_backend/src/controllers/api_tokens_controller.rs
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
//! # API tokens management
|
||||||
|
|
||||||
|
use crate::api_tokens;
|
||||||
|
use crate::api_tokens::{NewToken, TokenID, TokenRights};
|
||||||
|
use crate::controllers::HttpResult;
|
||||||
|
use crate::controllers::api_tokens_controller::rest_token::RestToken;
|
||||||
|
use actix_web::{HttpResponse, web};
|
||||||
|
use basic_jwt::JWTPrivateKey;
|
||||||
|
|
||||||
|
/// Create a special module for REST token to enforce usage of constructor function
|
||||||
|
mod rest_token {
|
||||||
|
use crate::api_tokens::Token;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub struct RestToken {
|
||||||
|
#[serde(flatten)]
|
||||||
|
token: Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RestToken {
|
||||||
|
pub fn new(mut token: Token) -> Self {
|
||||||
|
token.pub_key = None;
|
||||||
|
Self { token }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct CreateTokenResult {
|
||||||
|
token: RestToken,
|
||||||
|
priv_key: JWTPrivateKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new API token
|
||||||
|
pub async fn create(new_token: web::Json<NewToken>) -> HttpResult {
|
||||||
|
if let Some(err) = new_token.check_error() {
|
||||||
|
log::error!("Failed to validate new API token information! {err}");
|
||||||
|
return Ok(HttpResponse::BadRequest().json(format!(
|
||||||
|
"Failed to validate new API token information! {err}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (token, priv_key) = api_tokens::create(&new_token).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(CreateTokenResult {
|
||||||
|
token: RestToken::new(token),
|
||||||
|
priv_key,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of API tokens
|
||||||
|
pub async fn list() -> HttpResult {
|
||||||
|
let list = api_tokens::full_list()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(RestToken::new)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(list))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct TokenIDInPath {
|
||||||
|
uid: TokenID,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the information about a single token
|
||||||
|
pub async fn get_single(path: web::Path<TokenIDInPath>) -> HttpResult {
|
||||||
|
let token = api_tokens::get_single(path.uid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(RestToken::new(token)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct UpdateTokenBody {
|
||||||
|
rights: TokenRights,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a token
|
||||||
|
pub async fn update(
|
||||||
|
path: web::Path<TokenIDInPath>,
|
||||||
|
body: web::Json<UpdateTokenBody>,
|
||||||
|
) -> HttpResult {
|
||||||
|
if let Some(err) = body.rights.check_error() {
|
||||||
|
log::error!("Failed to validate updated API token information! {err}");
|
||||||
|
return Ok(HttpResponse::BadRequest()
|
||||||
|
.json(format!("Failed to validate API token information! {err}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
api_tokens::update_rights(path.uid, body.0.rights).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete a token
|
||||||
|
pub async fn delete(path: web::Path<TokenIDInPath>) -> HttpResult {
|
||||||
|
api_tokens::delete(path.uid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
@ -1,6 +1,6 @@
|
|||||||
use actix_remote_ip::RemoteIP;
|
use actix_remote_ip::RemoteIP;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{web, HttpResponse, Responder};
|
use actix_web::{HttpResponse, Responder, web};
|
||||||
use light_openid::basic_state_manager::BasicStateManager;
|
use light_openid::basic_state_manager::BasicStateManager;
|
||||||
|
|
||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
|
255
virtweb_backend/src/controllers/disk_images_controller.rs
Normal file
255
virtweb_backend/src/controllers/disk_images_controller.rs
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
|
use crate::utils::file_disks_utils::{DiskFileFormat, DiskFileInfo};
|
||||||
|
use crate::utils::files_utils;
|
||||||
|
use actix_files::NamedFile;
|
||||||
|
use actix_multipart::form::MultipartForm;
|
||||||
|
use actix_multipart::form::tempfile::TempFile;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
|
|
||||||
|
#[derive(Debug, MultipartForm)]
|
||||||
|
pub struct UploadDiskImageForm {
|
||||||
|
#[multipart(rename = "file")]
|
||||||
|
files: Vec<TempFile>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upload disk image file
|
||||||
|
pub async fn upload(MultipartForm(mut form): MultipartForm<UploadDiskImageForm>) -> HttpResult {
|
||||||
|
if form.files.is_empty() {
|
||||||
|
log::error!("Missing uploaded disk file!");
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Missing file!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let file = form.files.remove(0);
|
||||||
|
|
||||||
|
// Check uploaded file size
|
||||||
|
if file.size > constants::DISK_IMAGE_MAX_SIZE.as_bytes() {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Disk image max size exceeded!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check file mime type
|
||||||
|
if let Some(mime_type) = file.content_type {
|
||||||
|
if !constants::ALLOWED_DISK_IMAGES_MIME_TYPES.contains(&mime_type.as_ref()) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json(format!(
|
||||||
|
"Unsupported file type for disk upload: {}",
|
||||||
|
mime_type
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract and check file name
|
||||||
|
let Some(file_name) = file.file_name else {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Missing file name of uploaded file!"));
|
||||||
|
};
|
||||||
|
if !files_utils::check_file_name(&file_name) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid uploaded file name!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a file with the same name already exists
|
||||||
|
let dest_path = AppConfig::get().disk_images_file_path(&file_name);
|
||||||
|
if dest_path.is_file() {
|
||||||
|
return Ok(HttpResponse::Conflict().json("A file with the same name already exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy the file to the destination
|
||||||
|
file.file.persist(&dest_path)?;
|
||||||
|
|
||||||
|
// Check if file information can be loaded
|
||||||
|
if let Err(e) = DiskFileInfo::load_file(&dest_path) {
|
||||||
|
log::error!("Failed to get information about uploaded disk file! {e}");
|
||||||
|
std::fs::remove_file(&dest_path)?;
|
||||||
|
return Ok(HttpResponse::InternalServerError()
|
||||||
|
.json(format!("Unable to process uploaded file! {e}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json("Successfully uploaded disk image!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get disk images list
|
||||||
|
pub async fn get_list() -> HttpResult {
|
||||||
|
let mut list = vec![];
|
||||||
|
for entry in AppConfig::get().disk_images_storage_path().read_dir()? {
|
||||||
|
let entry = entry?;
|
||||||
|
list.push(DiskFileInfo::load_file(&entry.path())?);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(list))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct DiskFilePath {
|
||||||
|
filename: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Download disk image
|
||||||
|
pub async fn download(p: web::Path<DiskFilePath>, req: HttpRequest) -> HttpResult {
|
||||||
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let file_path = AppConfig::get().disk_images_file_path(&p.filename);
|
||||||
|
|
||||||
|
if !file_path.exists() {
|
||||||
|
return Ok(HttpResponse::NotFound().json("Disk image does not exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(NamedFile::open(file_path)?.into_response(&req))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct ConvertDiskImageRequest {
|
||||||
|
dest_file_name: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
format: DiskFileFormat,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert disk image into a new format
|
||||||
|
pub async fn convert(
|
||||||
|
p: web::Path<DiskFilePath>,
|
||||||
|
req: web::Json<ConvertDiskImageRequest>,
|
||||||
|
) -> HttpResult {
|
||||||
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid src file name!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let src_file_path = AppConfig::get().disk_images_file_path(&p.filename);
|
||||||
|
|
||||||
|
let src = DiskFileInfo::load_file(&src_file_path)?;
|
||||||
|
|
||||||
|
handle_convert_request(src, &req).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct BackupVMDiskPath {
|
||||||
|
uid: XMLUuid,
|
||||||
|
diskid: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Perform disk backup
|
||||||
|
pub async fn backup_disk(
|
||||||
|
client: LibVirtReq,
|
||||||
|
path: web::Path<BackupVMDiskPath>,
|
||||||
|
req: web::Json<ConvertDiskImageRequest>,
|
||||||
|
) -> HttpResult {
|
||||||
|
// Get the VM information
|
||||||
|
let info = match client.get_single_domain(path.uid).await {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get domain info! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError().json(e.to_string()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let vm = VMInfo::from_domain(info)?;
|
||||||
|
|
||||||
|
// Load disk information
|
||||||
|
let Some(disk) = vm
|
||||||
|
.file_disks
|
||||||
|
.into_iter()
|
||||||
|
.find(|disk| disk.name == path.diskid)
|
||||||
|
else {
|
||||||
|
return Ok(HttpResponse::NotFound()
|
||||||
|
.json(format!("Disk {} not found for vm {}", path.diskid, vm.name)));
|
||||||
|
};
|
||||||
|
|
||||||
|
let src_path = disk.disk_path(vm.uuid.expect("Missing VM uuid!"));
|
||||||
|
let src_disk = DiskFileInfo::load_file(&src_path)?;
|
||||||
|
|
||||||
|
// Perform conversion
|
||||||
|
handle_convert_request(src_disk, &req).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generic controller code that performs image conversion to create a disk image file
|
||||||
|
pub async fn handle_convert_request(
|
||||||
|
src: DiskFileInfo,
|
||||||
|
req: &ConvertDiskImageRequest,
|
||||||
|
) -> HttpResult {
|
||||||
|
// Check destination file
|
||||||
|
if !files_utils::check_file_name(&req.dest_file_name) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid destination file name!"));
|
||||||
|
}
|
||||||
|
if !req
|
||||||
|
.format
|
||||||
|
.ext()
|
||||||
|
.iter()
|
||||||
|
.any(|e| req.dest_file_name.ends_with(e))
|
||||||
|
{
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid destination file extension!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let dst_file_path = AppConfig::get().disk_images_file_path(&req.dest_file_name);
|
||||||
|
|
||||||
|
if dst_file_path.exists() {
|
||||||
|
return Ok(HttpResponse::Conflict().json("Specified destination file already exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform conversion
|
||||||
|
if let Err(e) = src.convert(&dst_file_path, req.format) {
|
||||||
|
log::error!("Disk file conversion error: {e}");
|
||||||
|
return Ok(
|
||||||
|
HttpResponse::InternalServerError().json(format!("Disk file conversion error: {e}"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().json("Successfully converted disk file"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct RenameDiskImageRequest {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename disk image
|
||||||
|
pub async fn rename(
|
||||||
|
p: web::Path<DiskFilePath>,
|
||||||
|
req: web::Json<RenameDiskImageRequest>,
|
||||||
|
) -> HttpResult {
|
||||||
|
// Check source
|
||||||
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid src file name!"));
|
||||||
|
}
|
||||||
|
let src_path = AppConfig::get().disk_images_file_path(&p.filename);
|
||||||
|
if !src_path.exists() {
|
||||||
|
return Ok(HttpResponse::NotFound().json("Disk image does not exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check destination
|
||||||
|
if !files_utils::check_file_name(&req.name) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid dst file name!"));
|
||||||
|
}
|
||||||
|
let dst_path = AppConfig::get().disk_images_file_path(&req.name);
|
||||||
|
if dst_path.exists() {
|
||||||
|
return Ok(HttpResponse::Conflict().json("Destination name already exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check extension
|
||||||
|
let disk = DiskFileInfo::load_file(&src_path)?;
|
||||||
|
if !disk.format.ext().iter().any(|e| req.name.ends_with(e)) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid destination file extension!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform rename
|
||||||
|
std::fs::rename(&src_path, &dst_path)?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete a disk image
|
||||||
|
pub async fn delete(p: web::Path<DiskFilePath>) -> HttpResult {
|
||||||
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let file_path = AppConfig::get().disk_images_file_path(&p.filename);
|
||||||
|
|
||||||
|
if !file_path.exists() {
|
||||||
|
return Ok(HttpResponse::NotFound().json("Disk image does not exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::fs::remove_file(file_path)?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
148
virtweb_backend/src/controllers/groups_controller.rs
Normal file
148
virtweb_backend/src/controllers/groups_controller.rs
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
|
use crate::extractors::group_vm_id_extractor::GroupVmIdExtractor;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
|
use actix_web::HttpResponse;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Get the list of groups
|
||||||
|
pub async fn list(client: LibVirtReq) -> HttpResult {
|
||||||
|
let groups = match client.get_full_groups_list().await {
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get the list of groups! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError()
|
||||||
|
.json(format!("Failed to get the list of groups! {e}")));
|
||||||
|
}
|
||||||
|
Ok(l) => l,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(groups))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get information about the VMs of a group
|
||||||
|
pub async fn vm_info(vms_xml: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut vms = Vec::new();
|
||||||
|
for vm in vms_xml.0 {
|
||||||
|
vms.push(VMInfo::from_domain(vm)?)
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(vms))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, serde::Serialize)]
|
||||||
|
pub struct TreatmentResult {
|
||||||
|
ok: usize,
|
||||||
|
failed: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the VMs of a group
|
||||||
|
pub async fn vm_start(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.start_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shutdown the VMs of a group
|
||||||
|
pub async fn vm_shutdown(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.shutdown_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Suspend the VMs of a group
|
||||||
|
pub async fn vm_suspend(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.suspend_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resume the VMs of a group
|
||||||
|
pub async fn vm_resume(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.resume_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kill the VMs of a group
|
||||||
|
pub async fn vm_kill(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.kill_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reset the VMs of a group
|
||||||
|
pub async fn vm_reset(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.reset_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the screenshot of the VMs of a group
|
||||||
|
pub async fn vm_screenshot(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
if vms.0.is_empty() {
|
||||||
|
return Ok(HttpResponse::NoContent().finish());
|
||||||
|
}
|
||||||
|
|
||||||
|
let image = if vms.0.len() == 1 {
|
||||||
|
client.screenshot_domain(vms.0[0].uuid.unwrap()).await?
|
||||||
|
} else {
|
||||||
|
return Ok(
|
||||||
|
HttpResponse::UnprocessableEntity().json("Cannot return multiple VM screenshots!!")
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().content_type("image/png").body(image))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the state of the VMs
|
||||||
|
pub async fn vm_state(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut states = HashMap::new();
|
||||||
|
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
states.insert(uuid, client.get_domain_state(uuid).await?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(states))
|
||||||
|
}
|
@ -3,9 +3,9 @@ use crate::constants;
|
|||||||
use crate::controllers::HttpResult;
|
use crate::controllers::HttpResult;
|
||||||
use crate::utils::files_utils;
|
use crate::utils::files_utils;
|
||||||
use actix_files::NamedFile;
|
use actix_files::NamedFile;
|
||||||
use actix_multipart::form::tempfile::TempFile;
|
|
||||||
use actix_multipart::form::MultipartForm;
|
use actix_multipart::form::MultipartForm;
|
||||||
use actix_web::{web, HttpRequest, HttpResponse};
|
use actix_multipart::form::tempfile::TempFile;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
@ -26,7 +26,7 @@ pub async fn upload_file(MultipartForm(mut form): MultipartForm<UploadIsoForm>)
|
|||||||
|
|
||||||
let file = form.files.remove(0);
|
let file = form.files.remove(0);
|
||||||
|
|
||||||
if file.size > constants::ISO_MAX_SIZE {
|
if file.size > constants::ISO_MAX_SIZE.as_bytes() {
|
||||||
log::error!("Uploaded ISO file is too large!");
|
log::error!("Uploaded ISO file is too large!");
|
||||||
return Ok(HttpResponse::BadRequest().json("File is too large!"));
|
return Ok(HttpResponse::BadRequest().json("File is too large!"));
|
||||||
}
|
}
|
||||||
@ -88,7 +88,7 @@ pub async fn upload_from_url(req: web::Json<DownloadFromURLReq>) -> HttpResult {
|
|||||||
let response = reqwest::get(&req.url).await?;
|
let response = reqwest::get(&req.url).await?;
|
||||||
|
|
||||||
if let Some(len) = response.content_length() {
|
if let Some(len) = response.content_length() {
|
||||||
if len > constants::ISO_MAX_SIZE as u64 {
|
if len > constants::ISO_MAX_SIZE.as_bytes() as u64 {
|
||||||
return Ok(HttpResponse::BadRequest().json("File is too large!"));
|
return Ok(HttpResponse::BadRequest().json("File is too large!"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,12 +132,12 @@ pub async fn get_list() -> HttpResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
pub struct DownloadFilePath {
|
pub struct IsoFilePath {
|
||||||
filename: String,
|
filename: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Download ISO file
|
/// Download ISO file
|
||||||
pub async fn download_file(p: web::Path<DownloadFilePath>, req: HttpRequest) -> HttpResult {
|
pub async fn download_file(p: web::Path<IsoFilePath>, req: HttpRequest) -> HttpResult {
|
||||||
if !files_utils::check_file_name(&p.filename) {
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
||||||
}
|
}
|
||||||
@ -152,7 +152,7 @@ pub async fn download_file(p: web::Path<DownloadFilePath>, req: HttpRequest) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Delete ISO file
|
/// Delete ISO file
|
||||||
pub async fn delete_file(p: web::Path<DownloadFilePath>) -> HttpResult {
|
pub async fn delete_file(p: web::Path<IsoFilePath>) -> HttpResult {
|
||||||
if !files_utils::check_file_name(&p.filename) {
|
if !files_utils::check_file_name(&p.filename) {
|
||||||
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,15 @@
|
|||||||
use crate::libvirt_client::LibVirtClient;
|
use crate::libvirt_client::LibVirtClient;
|
||||||
use actix_http::StatusCode;
|
use actix_http::StatusCode;
|
||||||
use actix_web::body::BoxBody;
|
use actix_web::body::BoxBody;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
use std::io::ErrorKind;
|
use zip::result::ZipError;
|
||||||
|
|
||||||
|
pub mod api_tokens_controller;
|
||||||
pub mod auth_controller;
|
pub mod auth_controller;
|
||||||
|
pub mod disk_images_controller;
|
||||||
|
pub mod groups_controller;
|
||||||
pub mod iso_controller;
|
pub mod iso_controller;
|
||||||
pub mod network_controller;
|
pub mod network_controller;
|
||||||
pub mod nwfilter_controller;
|
pub mod nwfilter_controller;
|
||||||
@ -60,7 +63,7 @@ impl From<serde_json::Error> for HttpErr {
|
|||||||
|
|
||||||
impl From<Box<dyn Error>> for HttpErr {
|
impl From<Box<dyn Error>> for HttpErr {
|
||||||
fn from(value: Box<dyn Error>) -> Self {
|
fn from(value: Box<dyn Error>) -> Self {
|
||||||
HttpErr::Err(std::io::Error::new(ErrorKind::Other, value.to_string()).into())
|
HttpErr::Err(std::io::Error::other(value.to_string()).into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,7 +99,13 @@ impl From<reqwest::header::ToStrError> for HttpErr {
|
|||||||
|
|
||||||
impl From<actix_web::Error> for HttpErr {
|
impl From<actix_web::Error> for HttpErr {
|
||||||
fn from(value: actix_web::Error) -> Self {
|
fn from(value: actix_web::Error) -> Self {
|
||||||
HttpErr::Err(std::io::Error::new(ErrorKind::Other, value.to_string()).into())
|
HttpErr::Err(std::io::Error::other(value.to_string()).into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ZipError> for HttpErr {
|
||||||
|
fn from(value: ZipError) -> Self {
|
||||||
|
HttpErr::Err(std::io::Error::other(value.to_string()).into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_rest_structures::net::NetworkInfo;
|
use crate::libvirt_rest_structures::net::NetworkInfo;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NetworkID {
|
pub struct NetworkID {
|
||||||
|
@ -2,7 +2,7 @@ use crate::constants;
|
|||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NetworkFilterID {
|
pub struct NetworkFilterID {
|
||||||
|
@ -1,12 +1,24 @@
|
|||||||
use crate::actors::vnc_tokens_actor::VNC_TOKEN_LIFETIME;
|
use crate::actors::vnc_tokens_actor::VNC_TOKEN_LIFETIME;
|
||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use crate::constants;
|
|
||||||
use crate::constants::{DISK_NAME_MAX_LEN, DISK_NAME_MIN_LEN, DISK_SIZE_MAX, DISK_SIZE_MIN};
|
use crate::constants::{DISK_NAME_MAX_LEN, DISK_NAME_MIN_LEN, DISK_SIZE_MAX, DISK_SIZE_MIN};
|
||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::extractors::local_auth_extractor::LocalAuthEnabled;
|
use crate::extractors::local_auth_extractor::LocalAuthEnabled;
|
||||||
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
||||||
use actix_web::{HttpResponse, Responder};
|
use crate::libvirt_rest_structures::net::NetworkInfo;
|
||||||
use sysinfo::{NetworksExt, System, SystemExt};
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
|
use crate::nat::nat_hook;
|
||||||
|
use crate::utils::net_utils;
|
||||||
|
use crate::utils::time_utils::{format_date, time};
|
||||||
|
use crate::{api_tokens, constants};
|
||||||
|
use actix_files::NamedFile;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, Responder};
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::Write;
|
||||||
|
use sysinfo::{Components, Disks, Networks, System};
|
||||||
|
use zip::ZipWriter;
|
||||||
|
use zip::write::SimpleFileOptions;
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
struct StaticConfig {
|
struct StaticConfig {
|
||||||
@ -14,6 +26,7 @@ struct StaticConfig {
|
|||||||
local_auth_enabled: bool,
|
local_auth_enabled: bool,
|
||||||
oidc_auth_enabled: bool,
|
oidc_auth_enabled: bool,
|
||||||
iso_mimetypes: &'static [&'static str],
|
iso_mimetypes: &'static [&'static str],
|
||||||
|
disk_images_mimetypes: &'static [&'static str],
|
||||||
net_mac_prefix: &'static str,
|
net_mac_prefix: &'static str,
|
||||||
builtin_nwfilter_rules: &'static [&'static str],
|
builtin_nwfilter_rules: &'static [&'static str],
|
||||||
nwfilter_chains: &'static [&'static str],
|
nwfilter_chains: &'static [&'static str],
|
||||||
@ -35,19 +48,26 @@ struct SLenConstraints {
|
|||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
struct ServerConstraints {
|
struct ServerConstraints {
|
||||||
iso_max_size: usize,
|
iso_max_size: usize,
|
||||||
|
disk_image_max_size: usize,
|
||||||
vnc_token_duration: u64,
|
vnc_token_duration: u64,
|
||||||
vm_name_size: LenConstraints,
|
vm_name_size: LenConstraints,
|
||||||
vm_title_size: LenConstraints,
|
vm_title_size: LenConstraints,
|
||||||
|
group_id_size: LenConstraints,
|
||||||
memory_size: LenConstraints,
|
memory_size: LenConstraints,
|
||||||
disk_name_size: LenConstraints,
|
disk_name_size: LenConstraints,
|
||||||
disk_size: LenConstraints,
|
disk_size: LenConstraints,
|
||||||
|
disk_image_name_size: LenConstraints,
|
||||||
net_name_size: LenConstraints,
|
net_name_size: LenConstraints,
|
||||||
net_title_size: LenConstraints,
|
net_title_size: LenConstraints,
|
||||||
|
net_nat_comment_size: LenConstraints,
|
||||||
dhcp_reservation_host_name: LenConstraints,
|
dhcp_reservation_host_name: LenConstraints,
|
||||||
nwfilter_name_size: LenConstraints,
|
nwfilter_name_size: LenConstraints,
|
||||||
nwfilter_comment_size: LenConstraints,
|
nwfilter_comment_size: LenConstraints,
|
||||||
nwfilter_priority: SLenConstraints,
|
nwfilter_priority: SLenConstraints,
|
||||||
nwfilter_selectors_count: LenConstraints,
|
nwfilter_selectors_count: LenConstraints,
|
||||||
|
api_token_name_size: LenConstraints,
|
||||||
|
api_token_description_size: LenConstraints,
|
||||||
|
api_token_right_path_size: LenConstraints,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
||||||
@ -56,31 +76,40 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
|||||||
local_auth_enabled: *local_auth,
|
local_auth_enabled: *local_auth,
|
||||||
oidc_auth_enabled: !AppConfig::get().disable_oidc,
|
oidc_auth_enabled: !AppConfig::get().disable_oidc,
|
||||||
iso_mimetypes: &constants::ALLOWED_ISO_MIME_TYPES,
|
iso_mimetypes: &constants::ALLOWED_ISO_MIME_TYPES,
|
||||||
|
disk_images_mimetypes: &constants::ALLOWED_DISK_IMAGES_MIME_TYPES,
|
||||||
net_mac_prefix: constants::NET_MAC_ADDR_PREFIX,
|
net_mac_prefix: constants::NET_MAC_ADDR_PREFIX,
|
||||||
builtin_nwfilter_rules: &constants::BUILTIN_NETWORK_FILTER_RULES,
|
builtin_nwfilter_rules: &constants::BUILTIN_NETWORK_FILTER_RULES,
|
||||||
nwfilter_chains: &constants::NETWORK_CHAINS,
|
nwfilter_chains: &constants::NETWORK_CHAINS,
|
||||||
constraints: ServerConstraints {
|
constraints: ServerConstraints {
|
||||||
iso_max_size: constants::ISO_MAX_SIZE,
|
iso_max_size: constants::ISO_MAX_SIZE.as_bytes(),
|
||||||
|
disk_image_max_size: constants::DISK_IMAGE_MAX_SIZE.as_bytes(),
|
||||||
|
|
||||||
vnc_token_duration: VNC_TOKEN_LIFETIME,
|
vnc_token_duration: VNC_TOKEN_LIFETIME,
|
||||||
|
|
||||||
vm_name_size: LenConstraints { min: 2, max: 50 },
|
vm_name_size: LenConstraints { min: 2, max: 50 },
|
||||||
vm_title_size: LenConstraints { min: 0, max: 50 },
|
vm_title_size: LenConstraints { min: 0, max: 50 },
|
||||||
|
group_id_size: LenConstraints { min: 3, max: 50 },
|
||||||
memory_size: LenConstraints {
|
memory_size: LenConstraints {
|
||||||
min: constants::MIN_VM_MEMORY,
|
min: constants::MIN_VM_MEMORY.as_bytes(),
|
||||||
max: constants::MAX_VM_MEMORY,
|
max: constants::MAX_VM_MEMORY.as_bytes(),
|
||||||
},
|
},
|
||||||
disk_name_size: LenConstraints {
|
disk_name_size: LenConstraints {
|
||||||
min: DISK_NAME_MIN_LEN,
|
min: DISK_NAME_MIN_LEN,
|
||||||
max: DISK_NAME_MAX_LEN,
|
max: DISK_NAME_MAX_LEN,
|
||||||
},
|
},
|
||||||
disk_size: LenConstraints {
|
disk_size: LenConstraints {
|
||||||
min: DISK_SIZE_MIN,
|
min: DISK_SIZE_MIN.as_bytes(),
|
||||||
max: DISK_SIZE_MAX,
|
max: DISK_SIZE_MAX.as_bytes(),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
disk_image_name_size: LenConstraints { min: 5, max: 220 },
|
||||||
|
|
||||||
net_name_size: LenConstraints { min: 2, max: 50 },
|
net_name_size: LenConstraints { min: 2, max: 50 },
|
||||||
net_title_size: LenConstraints { min: 0, max: 50 },
|
net_title_size: LenConstraints { min: 0, max: 50 },
|
||||||
|
net_nat_comment_size: LenConstraints {
|
||||||
|
min: 0,
|
||||||
|
max: constants::NET_NAT_COMMENT_MAX_SIZE,
|
||||||
|
},
|
||||||
|
|
||||||
dhcp_reservation_host_name: LenConstraints { min: 2, max: 250 },
|
dhcp_reservation_host_name: LenConstraints { min: 2, max: 250 },
|
||||||
|
|
||||||
@ -91,6 +120,21 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
|||||||
max: 1000,
|
max: 1000,
|
||||||
},
|
},
|
||||||
nwfilter_selectors_count: LenConstraints { min: 0, max: 1 },
|
nwfilter_selectors_count: LenConstraints { min: 0, max: 1 },
|
||||||
|
|
||||||
|
api_token_name_size: LenConstraints {
|
||||||
|
min: constants::API_TOKEN_NAME_MIN_LENGTH,
|
||||||
|
max: constants::API_TOKEN_NAME_MAX_LENGTH,
|
||||||
|
},
|
||||||
|
|
||||||
|
api_token_description_size: LenConstraints {
|
||||||
|
min: constants::API_TOKEN_DESCRIPTION_MIN_LENGTH,
|
||||||
|
max: constants::API_TOKEN_DESCRIPTION_MAX_LENGTH,
|
||||||
|
},
|
||||||
|
|
||||||
|
api_token_right_path_size: LenConstraints {
|
||||||
|
min: 0,
|
||||||
|
max: constants::API_TOKEN_RIGHT_PATH_MAX_LENGTH,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -99,24 +143,51 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
|||||||
struct ServerInfo {
|
struct ServerInfo {
|
||||||
hypervisor: HypervisorInfo,
|
hypervisor: HypervisorInfo,
|
||||||
system: System,
|
system: System,
|
||||||
|
components: Components,
|
||||||
|
disks: Disks,
|
||||||
|
networks: Networks,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn server_info(client: LibVirtReq) -> HttpResult {
|
pub async fn server_info(client: LibVirtReq) -> HttpResult {
|
||||||
let mut system = System::new();
|
let mut system = System::new();
|
||||||
system.refresh_disks_list();
|
|
||||||
system.refresh_components_list();
|
|
||||||
system.refresh_networks_list();
|
|
||||||
system.refresh_all();
|
system.refresh_all();
|
||||||
|
|
||||||
|
let mut components = Components::new();
|
||||||
|
components.refresh(true);
|
||||||
|
|
||||||
|
let mut disks = Disks::new();
|
||||||
|
disks.refresh(true);
|
||||||
|
|
||||||
|
let mut networks = Networks::new();
|
||||||
|
networks.refresh(true);
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(ServerInfo {
|
Ok(HttpResponse::Ok().json(ServerInfo {
|
||||||
hypervisor: client.get_info().await?,
|
hypervisor: client.get_info().await?,
|
||||||
system,
|
system,
|
||||||
|
components,
|
||||||
|
disks,
|
||||||
|
networks,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct NetworkHookStatus {
|
||||||
|
installed: bool,
|
||||||
|
content: String,
|
||||||
|
path: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn network_hook_status() -> HttpResult {
|
||||||
|
Ok(HttpResponse::Ok().json(NetworkHookStatus {
|
||||||
|
installed: nat_hook::is_installed()?,
|
||||||
|
content: nat_hook::hook_content()?,
|
||||||
|
path: constants::NAT_HOOK_PATH,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn number_vcpus() -> HttpResult {
|
pub async fn number_vcpus() -> HttpResult {
|
||||||
let mut system = System::new();
|
let mut system = System::new();
|
||||||
system.refresh_cpu();
|
system.refresh_cpu_all();
|
||||||
let number_cpus = system.cpus().len();
|
let number_cpus = system.cpus().len();
|
||||||
assert_ne!(number_cpus, 0, "Got invlid number of CPU!");
|
assert_ne!(number_cpus, 0, "Got invlid number of CPU!");
|
||||||
|
|
||||||
@ -132,14 +203,91 @@ pub async fn number_vcpus() -> HttpResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn networks_list() -> HttpResult {
|
pub async fn networks_list() -> HttpResult {
|
||||||
let mut system = System::new();
|
Ok(HttpResponse::Ok().json(net_utils::net_list()))
|
||||||
system.refresh_networks_list();
|
}
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(
|
pub async fn bridges_list() -> HttpResult {
|
||||||
system
|
Ok(HttpResponse::Ok().json(net_utils::bridges_list()?))
|
||||||
.networks()
|
}
|
||||||
.iter()
|
|
||||||
.map(|n| n.0.to_string())
|
/// Add JSON file to ZIP
|
||||||
.collect::<Vec<_>>(),
|
fn zip_json<E: Serialize, F>(
|
||||||
))
|
zip: &mut ZipWriter<File>,
|
||||||
|
dir: &str,
|
||||||
|
content: &Vec<E>,
|
||||||
|
file_name: F,
|
||||||
|
) -> anyhow::Result<()>
|
||||||
|
where
|
||||||
|
F: Fn(&E) -> String,
|
||||||
|
{
|
||||||
|
for entry in content {
|
||||||
|
let file_encoded = serde_json::to_string(&entry)?;
|
||||||
|
|
||||||
|
let options = SimpleFileOptions::default()
|
||||||
|
.compression_method(zip::CompressionMethod::Deflated)
|
||||||
|
.unix_permissions(0o750);
|
||||||
|
|
||||||
|
zip.start_file(format!("{dir}/{}.json", file_name(entry)), options)?;
|
||||||
|
zip.write_all(file_encoded.as_bytes())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Export all configuration elements at once
|
||||||
|
pub async fn export_all_configs(req: HttpRequest, client: LibVirtReq) -> HttpResult {
|
||||||
|
// Perform extractions
|
||||||
|
let vms = client
|
||||||
|
.get_full_domains_list()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(VMInfo::from_domain)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let networks = client
|
||||||
|
.get_full_networks_list()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(NetworkInfo::from_xml)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let nw_filters = client
|
||||||
|
.get_full_network_filters_list()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(NetworkFilter::lib2rest)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let tokens = api_tokens::full_list().await?;
|
||||||
|
|
||||||
|
// Create ZIP file
|
||||||
|
let dest_dir = tempfile::tempdir_in(&AppConfig::get().temp_dir)?;
|
||||||
|
let zip_path = dest_dir.path().join("export.zip");
|
||||||
|
|
||||||
|
let file = File::create(&zip_path)?;
|
||||||
|
let mut zip = ZipWriter::new(file);
|
||||||
|
|
||||||
|
// Encode entities to JSON
|
||||||
|
zip_json(&mut zip, "vms", &vms, |v| v.name.to_string())?;
|
||||||
|
zip_json(&mut zip, "networks", &networks, |v| v.name.0.to_string())?;
|
||||||
|
zip_json(
|
||||||
|
&mut zip,
|
||||||
|
"nw_filters",
|
||||||
|
&nw_filters,
|
||||||
|
|v| match constants::BUILTIN_NETWORK_FILTER_RULES.contains(&v.name.0.as_str()) {
|
||||||
|
true => format!("builtin/{}", v.name.0),
|
||||||
|
false => v.name.0.to_string(),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
zip_json(&mut zip, "tokens", &tokens, |v| v.id.0.to_string())?;
|
||||||
|
|
||||||
|
// Finalize ZIP and return response
|
||||||
|
zip.finish()?;
|
||||||
|
let file = File::open(zip_path)?;
|
||||||
|
|
||||||
|
let file = NamedFile::from_file(
|
||||||
|
file,
|
||||||
|
format!(
|
||||||
|
"export_{}.zip",
|
||||||
|
format_date(time() as i64).unwrap().replace('/', "-")
|
||||||
|
),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(file.into_response(&req))
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,27 @@ pub use serve_static_debug::{root_index, serve_static_content};
|
|||||||
#[cfg(not(debug_assertions))]
|
#[cfg(not(debug_assertions))]
|
||||||
pub use serve_static_release::{root_index, serve_static_content};
|
pub use serve_static_release::{root_index, serve_static_content};
|
||||||
|
|
||||||
|
/// Static API assets hosting
|
||||||
|
pub mod serve_assets {
|
||||||
|
use actix_web::{HttpResponse, web};
|
||||||
|
use rust_embed::RustEmbed;
|
||||||
|
|
||||||
|
#[derive(RustEmbed)]
|
||||||
|
#[folder = "assets/"]
|
||||||
|
struct Asset;
|
||||||
|
|
||||||
|
/// Serve API assets
|
||||||
|
pub async fn serve_api_assets(file: web::Path<String>) -> HttpResponse {
|
||||||
|
match Asset::get(&file) {
|
||||||
|
None => HttpResponse::NotFound().body("File not found"),
|
||||||
|
Some(asset) => HttpResponse::Ok()
|
||||||
|
.content_type(asset.metadata.mimetype())
|
||||||
|
.body(asset.data),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Web asset hosting placeholder in debug mode
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
mod serve_static_debug {
|
mod serve_static_debug {
|
||||||
use actix_web::{HttpResponse, Responder};
|
use actix_web::{HttpResponse, Responder};
|
||||||
@ -16,19 +37,20 @@ mod serve_static_debug {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Web asset hosting in release mode
|
||||||
#[cfg(not(debug_assertions))]
|
#[cfg(not(debug_assertions))]
|
||||||
mod serve_static_release {
|
mod serve_static_release {
|
||||||
use actix_web::{web, HttpResponse, Responder};
|
use actix_web::{HttpResponse, Responder, web};
|
||||||
use rust_embed::RustEmbed;
|
use rust_embed::RustEmbed;
|
||||||
|
|
||||||
#[derive(RustEmbed)]
|
#[derive(RustEmbed)]
|
||||||
#[folder = "static/"]
|
#[folder = "static/"]
|
||||||
struct Asset;
|
struct WebAsset;
|
||||||
|
|
||||||
fn handle_embedded_file(path: &str, can_fallback: bool) -> HttpResponse {
|
fn handle_embedded_file(path: &str, can_fallback: bool) -> HttpResponse {
|
||||||
match (Asset::get(path), can_fallback) {
|
match (WebAsset::get(path), can_fallback) {
|
||||||
(Some(content), _) => HttpResponse::Ok()
|
(Some(content), _) => HttpResponse::Ok()
|
||||||
.content_type(mime_guess::from_path(path).first_or_octet_stream().as_ref())
|
.content_type(content.metadata.mimetype())
|
||||||
.body(content.data.into_owned()),
|
.body(content.data.into_owned()),
|
||||||
(None, false) => HttpResponse::NotFound().body("404 Not Found"),
|
(None, false) => HttpResponse::NotFound().body("404 Not Found"),
|
||||||
(None, true) => handle_embedded_file("index.html", false),
|
(None, true) => handle_embedded_file("index.html", false),
|
||||||
|
@ -1,11 +1,12 @@
|
|||||||
use crate::actors::vnc_actor::VNCActor;
|
use crate::actors::vnc_handler;
|
||||||
use crate::actors::vnc_tokens_actor::VNCTokensManager;
|
use crate::actors::vnc_tokens_actor::VNCTokensManager;
|
||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::domain::DomainState;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::DomainState;
|
||||||
use crate::libvirt_rest_structures::vm::VMInfo;
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
use actix_web::{web, HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse, rt, web};
|
||||||
use actix_web_actors::ws;
|
use std::path::Path;
|
||||||
|
use tokio::net::UnixStream;
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
struct VMInfoAndState {
|
struct VMInfoAndState {
|
||||||
@ -21,7 +22,7 @@ struct VMUuid {
|
|||||||
|
|
||||||
/// Create a new VM
|
/// Create a new VM
|
||||||
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
|
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
|
||||||
let domain = match req.0.as_tomain() {
|
let domain = match req.0.as_domain() {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to extract domain info! {e}");
|
log::error!("Failed to extract domain info! {e}");
|
||||||
@ -83,6 +84,8 @@ pub async fn get_single(client: LibVirtReq, id: web::Path<SingleVMUUidReq>) -> H
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
log::debug!("INFO={info:#?}");
|
||||||
|
|
||||||
let state = client.get_domain_state(id.uid).await?;
|
let state = client.get_domain_state(id.uid).await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(VMInfoAndState {
|
Ok(HttpResponse::Ok().json(VMInfoAndState {
|
||||||
@ -106,13 +109,35 @@ pub async fn get_single_src_def(client: LibVirtReq, id: web::Path<SingleVMUUidRe
|
|||||||
.body(info))
|
.body(info))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the generated cloud init configuration disk of a vm
|
||||||
|
pub async fn get_cloud_init_disk(client: LibVirtReq, id: web::Path<SingleVMUUidReq>) -> HttpResult {
|
||||||
|
let info = match client.get_single_domain(id.uid).await {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get domain information! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError().json(e.to_string()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let vm = VMInfo::from_domain(info)?;
|
||||||
|
let disk = vm.cloud_init.generate_nocloud_disk()?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok()
|
||||||
|
.content_type("application/x-iso9660-image")
|
||||||
|
.insert_header((
|
||||||
|
"Content-Disposition",
|
||||||
|
format!("attachment; filename=\"cloud_init_{}.iso\"", vm.name),
|
||||||
|
))
|
||||||
|
.body(disk))
|
||||||
|
}
|
||||||
|
|
||||||
/// Update a VM information
|
/// Update a VM information
|
||||||
pub async fn update(
|
pub async fn update(
|
||||||
client: LibVirtReq,
|
client: LibVirtReq,
|
||||||
id: web::Path<SingleVMUUidReq>,
|
id: web::Path<SingleVMUUidReq>,
|
||||||
req: web::Json<VMInfo>,
|
req: web::Json<VMInfo>,
|
||||||
) -> HttpResult {
|
) -> HttpResult {
|
||||||
let mut domain = match req.0.as_tomain() {
|
let mut domain = match req.0.as_domain() {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to extract domain info! {e}");
|
log::error!("Failed to extract domain info! {e}");
|
||||||
@ -322,5 +347,19 @@ pub async fn vnc(
|
|||||||
};
|
};
|
||||||
|
|
||||||
log::info!("Start VNC connection on socket {socket_path}");
|
log::info!("Start VNC connection on socket {socket_path}");
|
||||||
Ok(ws::start(VNCActor::new(&socket_path).await?, &req, stream)?)
|
|
||||||
|
let socket_path = Path::new(&socket_path);
|
||||||
|
if !socket_path.exists() {
|
||||||
|
log::error!("VNC socket path {socket_path:?} does not exist!");
|
||||||
|
return Ok(HttpResponse::ServiceUnavailable().json("VNC socket path does not exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let socket = UnixStream::connect(socket_path).await?;
|
||||||
|
|
||||||
|
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
|
||||||
|
|
||||||
|
// spawn websocket handler (and don't await it) so that the response is returned immediately
|
||||||
|
rt::spawn(vnc_handler::handle(session, msg_stream, socket));
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
151
virtweb_backend/src/extractors/api_auth_extractor.rs
Normal file
151
virtweb_backend/src/extractors/api_auth_extractor.rs
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
use crate::api_tokens::{Token, TokenID, TokenVerb};
|
||||||
|
|
||||||
|
use crate::api_tokens;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
use actix_remote_ip::RemoteIP;
|
||||||
|
use actix_web::dev::Payload;
|
||||||
|
use actix_web::error::{ErrorBadRequest, ErrorUnauthorized};
|
||||||
|
use actix_web::{Error, FromRequest, HttpRequest};
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug)]
|
||||||
|
pub struct TokenClaims {
|
||||||
|
pub sub: String,
|
||||||
|
pub iat: usize,
|
||||||
|
pub exp: usize,
|
||||||
|
pub verb: TokenVerb,
|
||||||
|
pub path: String,
|
||||||
|
pub nonce: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ApiAuthExtractor {
|
||||||
|
pub token: Token,
|
||||||
|
pub claims: TokenClaims,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for ApiAuthExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
|
let req = req.clone();
|
||||||
|
|
||||||
|
let remote_ip = match RemoteIP::from_request(&req, payload).into_inner() {
|
||||||
|
Ok(ip) => ip,
|
||||||
|
Err(e) => return Box::pin(async { Err(e) }),
|
||||||
|
};
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let (token_id, token_jwt) = match (
|
||||||
|
req.headers().get("x-token-id"),
|
||||||
|
req.headers().get("x-token-content"),
|
||||||
|
) {
|
||||||
|
(Some(id), Some(jwt)) => (
|
||||||
|
id.to_str().unwrap_or("").to_string(),
|
||||||
|
jwt.to_str().unwrap_or("").to_string(),
|
||||||
|
),
|
||||||
|
(_, _) => {
|
||||||
|
return Err(ErrorBadRequest("API auth headers were not all specified!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let token_id = match TokenID::parse(&token_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to parse token id! {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token ID!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let token = match api_tokens::get_single(token_id).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to retrieve token: {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if token.is_expired() {
|
||||||
|
log::error!("Token has expired (not been used for too long)!");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let claims = match token
|
||||||
|
.pub_key
|
||||||
|
.as_ref()
|
||||||
|
.expect("All tokens shall have public key!")
|
||||||
|
.validate_jwt::<TokenClaims>(&token_jwt)
|
||||||
|
{
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to validate JWT: {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if claims.sub != token.id.0.to_string() {
|
||||||
|
log::error!("JWT sub mismatch (should equal to token id)!");
|
||||||
|
return Err(ErrorBadRequest(
|
||||||
|
"JWT sub mismatch (should equal to token id)!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if time() + 60 * 15 < claims.iat as u64 {
|
||||||
|
log::error!("iat is in the future!");
|
||||||
|
return Err(ErrorBadRequest("iat is in the future!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.exp < claims.iat {
|
||||||
|
log::error!("exp shall not be smaller than iat!");
|
||||||
|
return Err(ErrorBadRequest("exp shall not be smaller than iat!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.exp - claims.iat > 1800 {
|
||||||
|
log::error!("JWT shall not be valid more than 30 minutes!");
|
||||||
|
return Err(ErrorBadRequest(
|
||||||
|
"JWT shall not be valid more than 30 minutes!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.path != req.path() {
|
||||||
|
log::error!("JWT path mismatch!");
|
||||||
|
return Err(ErrorBadRequest("JWT path mismatch!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.verb.as_method() != req.method() {
|
||||||
|
log::error!("JWT method mismatch!");
|
||||||
|
return Err(ErrorBadRequest("JWT method mismatch!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !token.rights.contains(claims.verb, req.path()) {
|
||||||
|
log::error!(
|
||||||
|
"Attempt to use a token for an unauthorized route! (token_id={})",
|
||||||
|
token.id.0
|
||||||
|
);
|
||||||
|
return Err(ErrorUnauthorized(
|
||||||
|
"Token cannot be used to query this route!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ip) = token.ip_restriction {
|
||||||
|
if !ip.contains(remote_ip.0) {
|
||||||
|
log::error!(
|
||||||
|
"Attempt to use a token for an unauthorized IP! {remote_ip:?} token_id={}",
|
||||||
|
token.id.0
|
||||||
|
);
|
||||||
|
return Err(ErrorUnauthorized("Token cannot be used from this IP!"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if token.should_update_last_activity() {
|
||||||
|
if let Err(e) = api_tokens::refresh_last_used(token.id).await {
|
||||||
|
log::error!("Could not update token last activity! {e}");
|
||||||
|
return Err(ErrorBadRequest("Couldn't refresh token last activity!"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ApiAuthExtractor { token, claims })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
use actix_identity::Identity;
|
use actix_identity::Identity;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
|
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
|
||||||
use futures_util::future::{ready, Ready};
|
use futures_util::future::{Ready, ready};
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
pub struct AuthExtractor {
|
pub struct AuthExtractor {
|
||||||
|
66
virtweb_backend/src/extractors/group_vm_id_extractor.rs
Normal file
66
virtweb_backend/src/extractors/group_vm_id_extractor.rs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
use crate::controllers::LibVirtReq;
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::DomainXML;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMGroupId;
|
||||||
|
use actix_http::Payload;
|
||||||
|
use actix_web::error::ErrorBadRequest;
|
||||||
|
use actix_web::web::Query;
|
||||||
|
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
pub struct GroupVmIdExtractor(pub Vec<DomainXML>);
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct GroupIDInPath {
|
||||||
|
gid: VMGroupId,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct FilterVM {
|
||||||
|
vm_id: Option<XMLUuid>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for GroupVmIdExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
|
||||||
|
let req = req.clone();
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let Ok(group_id) =
|
||||||
|
web::Path::<GroupIDInPath>::from_request(&req, &mut Payload::None).await
|
||||||
|
else {
|
||||||
|
return Err(ErrorBadRequest("Group ID not specified in path!"));
|
||||||
|
};
|
||||||
|
let group_id = group_id.into_inner().gid;
|
||||||
|
|
||||||
|
let filter_vm = match Query::<FilterVM>::from_request(&req, &mut Payload::None).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to extract VM id from request! {e}");
|
||||||
|
return Err(ErrorBadRequest("Failed to extract VM id from request!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(client) = LibVirtReq::from_request(&req, &mut Payload::None).await else {
|
||||||
|
return Err(ErrorBadRequest("Failed to extract client handle!"));
|
||||||
|
};
|
||||||
|
|
||||||
|
let vms = match client.get_full_group_vm_list(&group_id).await {
|
||||||
|
Ok(vms) => vms,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get the VMs of the group {group_id:?}: {e}");
|
||||||
|
return Err(ErrorBadRequest("Failed to get the VMs of the group!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter (if requested by the user)
|
||||||
|
Ok(GroupVmIdExtractor(match filter_vm.vm_id {
|
||||||
|
None => vms,
|
||||||
|
Some(id) => vms.into_iter().filter(|vms| vms.uuid == Some(id)).collect(),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{Error, FromRequest, HttpRequest};
|
use actix_web::{Error, FromRequest, HttpRequest};
|
||||||
use futures_util::future::{ready, Ready};
|
use futures_util::future::{Ready, ready};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
|
@ -1,2 +1,4 @@
|
|||||||
|
pub mod api_auth_extractor;
|
||||||
pub mod auth_extractor;
|
pub mod auth_extractor;
|
||||||
|
pub mod group_vm_id_extractor;
|
||||||
pub mod local_auth_extractor;
|
pub mod local_auth_extractor;
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
pub mod actors;
|
pub mod actors;
|
||||||
|
pub mod api_tokens;
|
||||||
pub mod app_config;
|
pub mod app_config;
|
||||||
pub mod constants;
|
pub mod constants;
|
||||||
pub mod controllers;
|
pub mod controllers;
|
||||||
@ -7,4 +8,5 @@ pub mod libvirt_client;
|
|||||||
pub mod libvirt_lib_structures;
|
pub mod libvirt_lib_structures;
|
||||||
pub mod libvirt_rest_structures;
|
pub mod libvirt_rest_structures;
|
||||||
pub mod middlewares;
|
pub mod middlewares;
|
||||||
|
pub mod nat;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
@ -1,14 +1,15 @@
|
|||||||
use crate::actors::libvirt_actor;
|
use crate::actors::libvirt_actor;
|
||||||
use crate::actors::libvirt_actor::LibVirtActor;
|
use crate::actors::libvirt_actor::LibVirtActor;
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
|
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
|
||||||
use crate::libvirt_lib_structures::network::NetworkXML;
|
use crate::libvirt_lib_structures::network::NetworkXML;
|
||||||
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
|
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
|
||||||
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
||||||
use crate::libvirt_rest_structures::net::NetworkInfo;
|
use crate::libvirt_rest_structures::net::NetworkInfo;
|
||||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
||||||
use crate::libvirt_rest_structures::vm::VMInfo;
|
use crate::libvirt_rest_structures::vm::{VMGroupId, VMInfo};
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct LibVirtClient(pub Addr<LibVirtActor>);
|
pub struct LibVirtClient(pub Addr<LibVirtActor>);
|
||||||
@ -107,6 +108,35 @@ impl LibVirtClient {
|
|||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the full list of groups
|
||||||
|
pub async fn get_full_groups_list(&self) -> anyhow::Result<Vec<VMGroupId>> {
|
||||||
|
let domains = self.get_full_domains_list().await?;
|
||||||
|
let mut out = HashSet::new();
|
||||||
|
for d in domains {
|
||||||
|
if let Some(g) = VMInfo::from_domain(d)?.group {
|
||||||
|
out.insert(g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out: Vec<_> = out.into_iter().collect();
|
||||||
|
out.sort();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the full list of VMs of a given group
|
||||||
|
pub async fn get_full_group_vm_list(
|
||||||
|
&self,
|
||||||
|
group: &VMGroupId,
|
||||||
|
) -> anyhow::Result<Vec<DomainXML>> {
|
||||||
|
let vms = self.get_full_domains_list().await?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for vm in vms {
|
||||||
|
if VMInfo::from_domain(vm.clone())?.group == Some(group.clone()) {
|
||||||
|
out.push(vm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
/// Update a network configuration
|
/// Update a network configuration
|
||||||
pub async fn update_network(
|
pub async fn update_network(
|
||||||
&self,
|
&self,
|
||||||
|
@ -1,17 +1,42 @@
|
|||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::utils::cloud_init_utils::CloudInitConfig;
|
||||||
|
|
||||||
|
/// VirtWeb specific metadata
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
|
||||||
|
#[serde(rename = "virtweb", default)]
|
||||||
|
pub struct DomainMetadataVirtWebXML {
|
||||||
|
#[serde(rename = "@xmlns:virtweb", default)]
|
||||||
|
pub ns: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub group: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cloud_init: Option<CloudInitConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Domain metadata
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
|
||||||
|
#[serde(rename = "metadata")]
|
||||||
|
pub struct DomainMetadataXML {
|
||||||
|
#[serde(rename = "virtweb:metadata", default)]
|
||||||
|
pub virtweb: DomainMetadataVirtWebXML,
|
||||||
|
}
|
||||||
|
|
||||||
/// OS information
|
/// OS information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "os")]
|
#[serde(rename = "os")]
|
||||||
pub struct OSXML {
|
pub struct OSXML {
|
||||||
#[serde(rename = "@firmware", default)]
|
#[serde(rename = "@firmware", default, skip_serializing_if = "Option::is_none")]
|
||||||
pub firmware: String,
|
pub firmware: Option<String>,
|
||||||
pub r#type: OSTypeXML,
|
pub r#type: OSTypeXML,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub loader: Option<OSLoaderXML>,
|
pub loader: Option<OSLoaderXML>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub bootmenu: Option<OSBootMenuXML>,
|
||||||
|
pub smbios: Option<OSSMBiosXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// OS Type information
|
/// OS Type information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "os")]
|
#[serde(rename = "os")]
|
||||||
pub struct OSTypeXML {
|
pub struct OSTypeXML {
|
||||||
#[serde(rename = "@arch")]
|
#[serde(rename = "@arch")]
|
||||||
@ -23,47 +48,67 @@ pub struct OSTypeXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// OS Loader information
|
/// OS Loader information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "loader")]
|
#[serde(rename = "loader")]
|
||||||
pub struct OSLoaderXML {
|
pub struct OSLoaderXML {
|
||||||
#[serde(rename = "@secure")]
|
#[serde(rename = "@secure")]
|
||||||
pub secure: String,
|
pub secure: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Legacy boot menu information
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename = "bootmenu")]
|
||||||
|
pub struct OSBootMenuXML {
|
||||||
|
#[serde(rename = "@enable")]
|
||||||
|
pub enable: String,
|
||||||
|
#[serde(rename = "@timeout")]
|
||||||
|
pub timeout: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SMBIOS System information
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename = "smbios")]
|
||||||
|
pub struct OSSMBiosXML {
|
||||||
|
#[serde(rename = "@mode")]
|
||||||
|
pub mode: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// Hypervisor features
|
/// Hypervisor features
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Default)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
|
||||||
#[serde(rename = "features")]
|
#[serde(rename = "features")]
|
||||||
pub struct FeaturesXML {
|
pub struct FeaturesXML {
|
||||||
pub acpi: ACPIXML,
|
pub acpi: ACPIXML,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// ACPI feature
|
/// ACPI feature
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Default)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
|
||||||
#[serde(rename = "acpi")]
|
#[serde(rename = "acpi")]
|
||||||
pub struct ACPIXML {}
|
pub struct ACPIXML {}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "mac")]
|
#[serde(rename = "mac")]
|
||||||
pub struct NetMacAddress {
|
pub struct NetMacAddress {
|
||||||
#[serde(rename = "@address")]
|
#[serde(rename = "@address")]
|
||||||
pub address: String,
|
pub address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "source")]
|
#[serde(rename = "source")]
|
||||||
pub struct NetIntSourceXML {
|
pub struct NetIntSourceXML {
|
||||||
#[serde(rename = "@network")]
|
#[serde(rename = "@network")]
|
||||||
pub network: String,
|
pub network: Option<String>,
|
||||||
|
#[serde(rename = "@bridge")]
|
||||||
|
pub bridge: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "model")]
|
#[serde(rename = "model")]
|
||||||
pub struct NetIntModelXML {
|
pub struct NetIntModelXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
pub r#type: String,
|
pub r#type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "filterref")]
|
#[serde(rename = "filterref")]
|
||||||
pub struct NetIntFilterParameterXML {
|
pub struct NetIntFilterParameterXML {
|
||||||
#[serde(rename = "@name")]
|
#[serde(rename = "@name")]
|
||||||
@ -72,7 +117,7 @@ pub struct NetIntFilterParameterXML {
|
|||||||
pub value: String,
|
pub value: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "filterref")]
|
#[serde(rename = "filterref")]
|
||||||
pub struct NetIntfilterRefXML {
|
pub struct NetIntfilterRefXML {
|
||||||
#[serde(rename = "@filter")]
|
#[serde(rename = "@filter")]
|
||||||
@ -81,7 +126,7 @@ pub struct NetIntfilterRefXML {
|
|||||||
pub parameters: Vec<NetIntFilterParameterXML>,
|
pub parameters: Vec<NetIntFilterParameterXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "interface")]
|
#[serde(rename = "interface")]
|
||||||
pub struct DomainNetInterfaceXML {
|
pub struct DomainNetInterfaceXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -95,14 +140,14 @@ pub struct DomainNetInterfaceXML {
|
|||||||
pub filterref: Option<NetIntfilterRefXML>,
|
pub filterref: Option<NetIntfilterRefXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "input")]
|
#[serde(rename = "input")]
|
||||||
pub struct DomainInputXML {
|
pub struct DomainInputXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
pub r#type: String,
|
pub r#type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "backend")]
|
#[serde(rename = "backend")]
|
||||||
pub struct TPMBackendXML {
|
pub struct TPMBackendXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -112,7 +157,7 @@ pub struct TPMBackendXML {
|
|||||||
pub r#version: String,
|
pub r#version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "tpm")]
|
#[serde(rename = "tpm")]
|
||||||
pub struct TPMDeviceXML {
|
pub struct TPMDeviceXML {
|
||||||
#[serde(rename = "@model")]
|
#[serde(rename = "@model")]
|
||||||
@ -121,7 +166,7 @@ pub struct TPMDeviceXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Devices information
|
/// Devices information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "devices")]
|
#[serde(rename = "devices")]
|
||||||
pub struct DevicesXML {
|
pub struct DevicesXML {
|
||||||
/// Graphics (used for VNC)
|
/// Graphics (used for VNC)
|
||||||
@ -150,7 +195,7 @@ pub struct DevicesXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Graphics information
|
/// Graphics information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "graphics")]
|
#[serde(rename = "graphics")]
|
||||||
pub struct GraphicsXML {
|
pub struct GraphicsXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -160,14 +205,14 @@ pub struct GraphicsXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Video device information
|
/// Video device information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "video")]
|
#[serde(rename = "video")]
|
||||||
pub struct VideoXML {
|
pub struct VideoXML {
|
||||||
pub model: VideoModelXML,
|
pub model: VideoModelXML,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Video model device information
|
/// Video model device information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "model")]
|
#[serde(rename = "model")]
|
||||||
pub struct VideoModelXML {
|
pub struct VideoModelXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -175,7 +220,7 @@ pub struct VideoModelXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Disk information
|
/// Disk information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "disk")]
|
#[serde(rename = "disk")]
|
||||||
pub struct DiskXML {
|
pub struct DiskXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -193,7 +238,7 @@ pub struct DiskXML {
|
|||||||
pub address: Option<DiskAddressXML>,
|
pub address: Option<DiskAddressXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "driver")]
|
#[serde(rename = "driver")]
|
||||||
pub struct DiskDriverXML {
|
pub struct DiskDriverXML {
|
||||||
#[serde(rename = "@name")]
|
#[serde(rename = "@name")]
|
||||||
@ -204,14 +249,14 @@ pub struct DiskDriverXML {
|
|||||||
pub r#cache: String,
|
pub r#cache: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "source")]
|
#[serde(rename = "source")]
|
||||||
pub struct DiskSourceXML {
|
pub struct DiskSourceXML {
|
||||||
#[serde(rename = "@file")]
|
#[serde(rename = "@file")]
|
||||||
pub file: String,
|
pub file: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "target")]
|
#[serde(rename = "target")]
|
||||||
pub struct DiskTargetXML {
|
pub struct DiskTargetXML {
|
||||||
#[serde(rename = "@dev")]
|
#[serde(rename = "@dev")]
|
||||||
@ -220,18 +265,18 @@ pub struct DiskTargetXML {
|
|||||||
pub bus: String,
|
pub bus: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "readonly")]
|
#[serde(rename = "readonly")]
|
||||||
pub struct DiskReadOnlyXML {}
|
pub struct DiskReadOnlyXML {}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "boot")]
|
#[serde(rename = "boot")]
|
||||||
pub struct DiskBootXML {
|
pub struct DiskBootXML {
|
||||||
#[serde(rename = "@order")]
|
#[serde(rename = "@order")]
|
||||||
pub order: String,
|
pub order: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "address")]
|
#[serde(rename = "address")]
|
||||||
pub struct DiskAddressXML {
|
pub struct DiskAddressXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@ -251,7 +296,7 @@ pub struct DiskAddressXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Domain RAM information
|
/// Domain RAM information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "memory")]
|
#[serde(rename = "memory")]
|
||||||
pub struct DomainMemoryXML {
|
pub struct DomainMemoryXML {
|
||||||
#[serde(rename = "@unit")]
|
#[serde(rename = "@unit")]
|
||||||
@ -261,7 +306,7 @@ pub struct DomainMemoryXML {
|
|||||||
pub memory: usize,
|
pub memory: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "topology")]
|
#[serde(rename = "topology")]
|
||||||
pub struct DomainCPUTopology {
|
pub struct DomainCPUTopology {
|
||||||
#[serde(rename = "@sockets")]
|
#[serde(rename = "@sockets")]
|
||||||
@ -272,14 +317,14 @@ pub struct DomainCPUTopology {
|
|||||||
pub threads: usize,
|
pub threads: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "cpu")]
|
#[serde(rename = "cpu")]
|
||||||
pub struct DomainVCPUXML {
|
pub struct DomainVCPUXML {
|
||||||
#[serde(rename = "$value")]
|
#[serde(rename = "$value")]
|
||||||
pub body: usize,
|
pub body: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "cpu")]
|
#[serde(rename = "cpu")]
|
||||||
pub struct DomainCPUXML {
|
pub struct DomainCPUXML {
|
||||||
#[serde(rename = "@mode")]
|
#[serde(rename = "@mode")]
|
||||||
@ -287,8 +332,31 @@ pub struct DomainCPUXML {
|
|||||||
pub topology: Option<DomainCPUTopology>,
|
pub topology: Option<DomainCPUTopology>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename = "entry")]
|
||||||
|
pub struct OEMStringEntryXML {
|
||||||
|
#[serde(rename = "$text", default)]
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename = "oemStrings")]
|
||||||
|
pub struct OEMStringsXML {
|
||||||
|
#[serde(rename = "entry")]
|
||||||
|
pub entries: Vec<OEMStringEntryXML>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename = "sysinfo")]
|
||||||
|
pub struct SysInfoXML {
|
||||||
|
#[serde(rename = "@type")]
|
||||||
|
pub r#type: String,
|
||||||
|
#[serde(rename = "oemStrings")]
|
||||||
|
pub oem_strings: Option<OEMStringsXML>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Domain information, see https://libvirt.org/formatdomain.html
|
/// Domain information, see https://libvirt.org/formatdomain.html
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "domain")]
|
#[serde(rename = "domain")]
|
||||||
pub struct DomainXML {
|
pub struct DomainXML {
|
||||||
/// Domain type (kvm)
|
/// Domain type (kvm)
|
||||||
@ -300,6 +368,9 @@ pub struct DomainXML {
|
|||||||
pub genid: Option<uuid::Uuid>,
|
pub genid: Option<uuid::Uuid>,
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub metadata: Option<DomainMetadataXML>,
|
||||||
|
|
||||||
pub os: OSXML,
|
pub os: OSXML,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub features: FeaturesXML,
|
pub features: FeaturesXML,
|
||||||
@ -314,15 +385,41 @@ pub struct DomainXML {
|
|||||||
/// CPU information
|
/// CPU information
|
||||||
pub cpu: DomainCPUXML,
|
pub cpu: DomainCPUXML,
|
||||||
|
|
||||||
|
/// SMBios strings
|
||||||
|
pub sysinfo: Option<SysInfoXML>,
|
||||||
|
|
||||||
|
/// Behavior when guest state change
|
||||||
pub on_poweroff: String,
|
pub on_poweroff: String,
|
||||||
pub on_reboot: String,
|
pub on_reboot: String,
|
||||||
pub on_crash: String,
|
pub on_crash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const METADATA_START_MARKER: &str =
|
||||||
|
"<virtweb:metadata xmlns:virtweb=\"https://virtweb.communiquons.org\">";
|
||||||
|
const METADATA_END_MARKER: &str = "</virtweb:metadata>";
|
||||||
|
|
||||||
impl DomainXML {
|
impl DomainXML {
|
||||||
/// Decode Domain structure from XML definition
|
/// Decode Domain structure from XML definition
|
||||||
pub fn parse_xml(xml: &str) -> anyhow::Result<Self> {
|
pub fn parse_xml(xml: &str) -> anyhow::Result<Self> {
|
||||||
Ok(quick_xml::de::from_str(xml)?)
|
let mut res: Self = quick_xml::de::from_str(xml)?;
|
||||||
|
|
||||||
|
// Handle custom metadata parsing issue
|
||||||
|
//
|
||||||
|
// https://github.com/tafia/quick-xml/pull/797
|
||||||
|
if xml.contains(METADATA_START_MARKER) && xml.contains(METADATA_END_MARKER) {
|
||||||
|
let s = xml
|
||||||
|
.split_once(METADATA_START_MARKER)
|
||||||
|
.unwrap()
|
||||||
|
.1
|
||||||
|
.split_once(METADATA_END_MARKER)
|
||||||
|
.unwrap()
|
||||||
|
.0;
|
||||||
|
let s = format!("<virtweb>{s}</virtweb>");
|
||||||
|
let metadata: DomainMetadataVirtWebXML = quick_xml::de::from_str(&s)?;
|
||||||
|
res.metadata = Some(DomainMetadataXML { virtweb: metadata });
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Turn this domain into its XML definition
|
/// Turn this domain into its XML definition
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||||
pub struct XMLUuid(pub uuid::Uuid);
|
pub struct XMLUuid(pub uuid::Uuid);
|
||||||
|
|
||||||
impl XMLUuid {
|
impl XMLUuid {
|
||||||
|
@ -43,14 +43,6 @@ pub struct NetworkDomainXML {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn invalid_prefix() -> u32 {
|
|
||||||
u32::MAX
|
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_ip() -> IpAddr {
|
|
||||||
IpAddr::V4(Ipv4Addr::BROADCAST)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Network ip information
|
/// Network ip information
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Debug)]
|
||||||
#[serde(rename = "ip")]
|
#[serde(rename = "ip")]
|
||||||
@ -60,12 +52,13 @@ pub struct NetworkIPXML {
|
|||||||
#[serde(rename = "@address")]
|
#[serde(rename = "@address")]
|
||||||
pub address: IpAddr,
|
pub address: IpAddr,
|
||||||
/// Network Prefix
|
/// Network Prefix
|
||||||
#[serde(rename = "@prefix", default = "invalid_prefix")]
|
#[serde(rename = "@prefix")]
|
||||||
pub prefix: u32,
|
pub prefix: Option<u8>,
|
||||||
/// Network Netmask. This field is never serialized, but because we can't know if LibVirt will
|
/// Network Netmask. This field is never serialized, but because we can't know if LibVirt will
|
||||||
/// provide us netmask or prefix, we need to handle both of these fields
|
/// provide us netmask or prefix, we need to handle both of these fields
|
||||||
#[serde(rename = "@netmask", default = "invalid_ip", skip_serializing)]
|
#[serde(rename = "@netmask", skip_serializing)]
|
||||||
pub netmask: IpAddr,
|
pub netmask: Option<IpAddr>,
|
||||||
|
|
||||||
pub dhcp: Option<NetworkDHCPXML>,
|
pub dhcp: Option<NetworkDHCPXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,4 +13,6 @@ enum LibVirtStructError {
|
|||||||
ParseFilteringChain(String),
|
ParseFilteringChain(String),
|
||||||
#[error("NetworkFilterExtractionError: {0}")]
|
#[error("NetworkFilterExtractionError: {0}")]
|
||||||
NetworkFilterExtraction(String),
|
NetworkFilterExtraction(String),
|
||||||
|
#[error("CloudInitConfigurationError: {0}")]
|
||||||
|
CloudInitConfiguration(String),
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
use crate::libvirt_lib_structures::network::*;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::network::*;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
||||||
|
use crate::nat::nat_definition::Nat;
|
||||||
|
use crate::nat::nat_lib;
|
||||||
|
use crate::utils::net_utils;
|
||||||
use crate::utils::net_utils::{extract_ipv4, extract_ipv6};
|
use crate::utils::net_utils::{extract_ipv4, extract_ipv6};
|
||||||
use ipnetwork::{Ipv4Network, Ipv6Network};
|
use ipnetwork::{Ipv4Network, Ipv6Network};
|
||||||
use lazy_regex::regex;
|
use lazy_regex::regex;
|
||||||
@ -21,57 +24,75 @@ pub struct DHCPv4HostReservation {
|
|||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct IPv4DHCPConfig {
|
pub struct IPv4DHCPConfig {
|
||||||
start: Ipv4Addr,
|
pub start: Ipv4Addr,
|
||||||
end: Ipv4Addr,
|
pub end: Ipv4Addr,
|
||||||
hosts: Vec<DHCPv4HostReservation>,
|
pub hosts: Vec<DHCPv4HostReservation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct IPV4Config {
|
pub struct IPV4Config {
|
||||||
bridge_address: Ipv4Addr,
|
pub bridge_address: Ipv4Addr,
|
||||||
prefix: u32,
|
pub prefix: u8,
|
||||||
dhcp: Option<IPv4DHCPConfig>,
|
pub dhcp: Option<IPv4DHCPConfig>,
|
||||||
|
pub nat: Option<Vec<Nat<Ipv4Addr>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct DHCPv6HostReservation {
|
pub struct DHCPv6HostReservation {
|
||||||
name: String,
|
pub name: String,
|
||||||
ip: Ipv6Addr,
|
pub ip: Ipv6Addr,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct IPv6DHCPConfig {
|
pub struct IPv6DHCPConfig {
|
||||||
start: Ipv6Addr,
|
pub start: Ipv6Addr,
|
||||||
end: Ipv6Addr,
|
pub end: Ipv6Addr,
|
||||||
hosts: Vec<DHCPv6HostReservation>,
|
pub hosts: Vec<DHCPv6HostReservation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct IPV6Config {
|
pub struct IPV6Config {
|
||||||
bridge_address: Ipv6Addr,
|
pub bridge_address: Ipv6Addr,
|
||||||
prefix: u32,
|
pub prefix: u8,
|
||||||
dhcp: Option<IPv6DHCPConfig>,
|
pub dhcp: Option<IPv6DHCPConfig>,
|
||||||
|
pub nat: Option<Vec<Nat<Ipv6Addr>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct NetworkName(pub String);
|
||||||
|
|
||||||
|
impl NetworkName {
|
||||||
|
/// Get the name of the file that will store the NAT configuration of this network
|
||||||
|
pub fn nat_file_name(&self) -> String {
|
||||||
|
format!("nat-{}.json", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NetworkName {
|
||||||
|
pub fn is_valid(&self) -> bool {
|
||||||
|
regex!("^[a-zA-Z0-9]+$").is_match(&self.0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Network configuration
|
/// Network configuration
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
|
||||||
pub struct NetworkInfo {
|
pub struct NetworkInfo {
|
||||||
pub name: String,
|
pub name: NetworkName,
|
||||||
pub uuid: Option<XMLUuid>,
|
pub uuid: Option<XMLUuid>,
|
||||||
title: Option<String>,
|
pub title: Option<String>,
|
||||||
description: Option<String>,
|
pub description: Option<String>,
|
||||||
forward_mode: NetworkForwardMode,
|
pub forward_mode: NetworkForwardMode,
|
||||||
device: Option<String>,
|
pub device: Option<String>,
|
||||||
bridge_name: Option<String>,
|
pub bridge_name: Option<String>,
|
||||||
dns_server: Option<Ipv4Addr>,
|
pub dns_server: Option<Ipv4Addr>,
|
||||||
domain: Option<String>,
|
pub domain: Option<String>,
|
||||||
ip_v4: Option<IPV4Config>,
|
pub ip_v4: Option<IPV4Config>,
|
||||||
ip_v6: Option<IPV6Config>,
|
pub ip_v6: Option<IPV6Config>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NetworkInfo {
|
impl NetworkInfo {
|
||||||
pub fn as_virt_network(&self) -> anyhow::Result<NetworkXML> {
|
pub fn as_virt_network(&self) -> anyhow::Result<NetworkXML> {
|
||||||
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
if !self.name.is_valid() {
|
||||||
return Err(StructureExtraction("network name is invalid!").into());
|
return Err(StructureExtraction("network name is invalid!").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,18 +123,26 @@ impl NetworkInfo {
|
|||||||
let mut ips = Vec::with_capacity(2);
|
let mut ips = Vec::with_capacity(2);
|
||||||
|
|
||||||
if let Some(ipv4) = &self.ip_v4 {
|
if let Some(ipv4) = &self.ip_v4 {
|
||||||
if ipv4.prefix > 32 {
|
if !net_utils::is_ipv4_mask_valid(ipv4.prefix) {
|
||||||
return Err(StructureExtraction("IPv4 prefix is invalid!").into());
|
return Err(StructureExtraction("IPv4 prefix is invalid!").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(nat) = &ipv4.nat {
|
||||||
|
for n in nat {
|
||||||
|
n.check()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
ips.push(NetworkIPXML {
|
ips.push(NetworkIPXML {
|
||||||
family: "ipv4".to_string(),
|
family: "ipv4".to_string(),
|
||||||
address: IpAddr::V4(ipv4.bridge_address),
|
address: IpAddr::V4(ipv4.bridge_address),
|
||||||
prefix: ipv4.prefix,
|
prefix: Some(ipv4.prefix),
|
||||||
netmask: Ipv4Network::new(ipv4.bridge_address, ipv4.prefix as u8)
|
netmask: Some(
|
||||||
.unwrap()
|
Ipv4Network::new(ipv4.bridge_address, ipv4.prefix)
|
||||||
.mask()
|
.unwrap()
|
||||||
.into(),
|
.mask()
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
dhcp: ipv4.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
dhcp: ipv4.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
||||||
range: NetworkDHCPRangeXML {
|
range: NetworkDHCPRangeXML {
|
||||||
start: IpAddr::V4(dhcp.start),
|
start: IpAddr::V4(dhcp.start),
|
||||||
@ -133,14 +162,26 @@ impl NetworkInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ipv6) = &self.ip_v6 {
|
if let Some(ipv6) = &self.ip_v6 {
|
||||||
|
if !net_utils::is_ipv6_mask_valid(ipv6.prefix) {
|
||||||
|
return Err(StructureExtraction("IPv6 prefix is invalid!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(nat) = &ipv6.nat {
|
||||||
|
for n in nat {
|
||||||
|
n.check()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
ips.push(NetworkIPXML {
|
ips.push(NetworkIPXML {
|
||||||
family: "ipv6".to_string(),
|
family: "ipv6".to_string(),
|
||||||
address: IpAddr::V6(ipv6.bridge_address),
|
address: IpAddr::V6(ipv6.bridge_address),
|
||||||
prefix: ipv6.prefix,
|
prefix: Some(ipv6.prefix),
|
||||||
netmask: Ipv6Network::new(ipv6.bridge_address, ipv6.prefix as u8)
|
netmask: Some(
|
||||||
.unwrap()
|
Ipv6Network::new(ipv6.bridge_address, ipv6.prefix)
|
||||||
.mask()
|
.unwrap()
|
||||||
.into(),
|
.mask()
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
dhcp: ipv6.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
dhcp: ipv6.dhcp.as_ref().map(|dhcp| NetworkDHCPXML {
|
||||||
range: NetworkDHCPRangeXML {
|
range: NetworkDHCPRangeXML {
|
||||||
start: IpAddr::V6(dhcp.start),
|
start: IpAddr::V6(dhcp.start),
|
||||||
@ -160,7 +201,7 @@ impl NetworkInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(NetworkXML {
|
Ok(NetworkXML {
|
||||||
name: self.name.to_string(),
|
name: self.name.0.to_string(),
|
||||||
uuid: self.uuid,
|
uuid: self.uuid,
|
||||||
title: self.title.clone(),
|
title: self.title.clone(),
|
||||||
description: self.description.clone(),
|
description: self.description.clone(),
|
||||||
@ -183,8 +224,12 @@ impl NetworkInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_xml(xml: NetworkXML) -> anyhow::Result<Self> {
|
pub fn from_xml(xml: NetworkXML) -> anyhow::Result<Self> {
|
||||||
|
let name = NetworkName(xml.name);
|
||||||
|
|
||||||
|
let nat = nat_lib::load_nat_def(&name)?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
name: xml.name,
|
name,
|
||||||
uuid: xml.uuid,
|
uuid: xml.uuid,
|
||||||
title: xml.title,
|
title: xml.title,
|
||||||
description: xml.description,
|
description: xml.description,
|
||||||
@ -209,10 +254,9 @@ impl NetworkInfo {
|
|||||||
.map(|i| IPV4Config {
|
.map(|i| IPV4Config {
|
||||||
bridge_address: extract_ipv4(i.address),
|
bridge_address: extract_ipv4(i.address),
|
||||||
prefix: match i.prefix {
|
prefix: match i.prefix {
|
||||||
u32::MAX => ipnetwork::ipv4_mask_to_prefix(extract_ipv4(i.netmask))
|
None => ipnetwork::ipv4_mask_to_prefix(extract_ipv4(i.netmask.unwrap()))
|
||||||
.expect("Failed to convert IPv4 netmask to network")
|
.expect("Failed to convert IPv4 netmask to network"),
|
||||||
as u32,
|
Some(p) => p,
|
||||||
p => p,
|
|
||||||
},
|
},
|
||||||
dhcp: i.dhcp.as_ref().map(|d| IPv4DHCPConfig {
|
dhcp: i.dhcp.as_ref().map(|d| IPv4DHCPConfig {
|
||||||
start: extract_ipv4(d.range.start),
|
start: extract_ipv4(d.range.start),
|
||||||
@ -227,6 +271,7 @@ impl NetworkInfo {
|
|||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
}),
|
}),
|
||||||
|
nat: nat.ipv4,
|
||||||
}),
|
}),
|
||||||
ip_v6: xml
|
ip_v6: xml
|
||||||
.ips
|
.ips
|
||||||
@ -235,10 +280,9 @@ impl NetworkInfo {
|
|||||||
.map(|i| IPV6Config {
|
.map(|i| IPV6Config {
|
||||||
bridge_address: extract_ipv6(i.address),
|
bridge_address: extract_ipv6(i.address),
|
||||||
prefix: match i.prefix {
|
prefix: match i.prefix {
|
||||||
u32::MAX => ipnetwork::ipv6_mask_to_prefix(extract_ipv6(i.netmask))
|
None => ipnetwork::ipv6_mask_to_prefix(extract_ipv6(i.netmask.unwrap()))
|
||||||
.expect("Failed to convert IPv6 netmask to network")
|
.expect("Failed to convert IPv6 netmask to network"),
|
||||||
as u32,
|
Some(p) => p,
|
||||||
p => p,
|
|
||||||
},
|
},
|
||||||
dhcp: i.dhcp.as_ref().map(|d| IPv6DHCPConfig {
|
dhcp: i.dhcp.as_ref().map(|d| IPv6DHCPConfig {
|
||||||
start: extract_ipv6(d.range.start),
|
start: extract_ipv6(d.range.start),
|
||||||
@ -252,7 +296,25 @@ impl NetworkInfo {
|
|||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
}),
|
}),
|
||||||
|
nat: nat.ipv6,
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if at least one NAT definition was specified on this interface
|
||||||
|
pub fn has_nat_def(&self) -> bool {
|
||||||
|
if let Some(ipv4) = &self.ip_v4 {
|
||||||
|
if ipv4.nat.is_some() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ipv6) = &self.ip_v6 {
|
||||||
|
if ipv6.nat.is_some() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_lib_structures::nwfilter::{
|
use crate::libvirt_lib_structures::nwfilter::{
|
||||||
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
|
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
|
||||||
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
|
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
|
||||||
NetworkFilterRuleXML, NetworkFilterXML,
|
NetworkFilterRuleXML, NetworkFilterXML,
|
||||||
};
|
};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError;
|
use crate::libvirt_rest_structures::LibVirtStructError;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::{
|
use crate::libvirt_rest_structures::LibVirtStructError::{
|
||||||
NetworkFilterExtraction, StructureExtraction,
|
NetworkFilterExtraction, StructureExtraction,
|
||||||
|
@ -1,17 +1,26 @@
|
|||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use crate::constants;
|
use crate::constants;
|
||||||
use crate::libvirt_lib_structures::domain::*;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::*;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError;
|
use crate::libvirt_rest_structures::LibVirtStructError;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
use crate::libvirt_rest_structures::LibVirtStructError::{
|
||||||
use crate::utils::disks_utils::Disk;
|
CloudInitConfiguration, StructureExtraction,
|
||||||
|
};
|
||||||
|
use crate::utils::cloud_init_utils::CloudInitConfig;
|
||||||
|
use crate::utils::file_size_utils::FileSize;
|
||||||
use crate::utils::files_utils;
|
use crate::utils::files_utils;
|
||||||
use crate::utils::files_utils::convert_size_unit_to_mb;
|
use crate::utils::vm_file_disks_utils::{VMDiskBus, VMDiskFormat, VMFileDisk};
|
||||||
use lazy_regex::regex;
|
use lazy_regex::regex;
|
||||||
use num::Integer;
|
use num::Integer;
|
||||||
|
|
||||||
|
#[derive(
|
||||||
|
Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, Ord, PartialOrd,
|
||||||
|
)]
|
||||||
|
pub struct VMGroupId(pub String);
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub enum BootType {
|
pub enum BootType {
|
||||||
|
Legacy,
|
||||||
UEFI,
|
UEFI,
|
||||||
UEFISecureBoot,
|
UEFISecureBoot,
|
||||||
}
|
}
|
||||||
@ -24,6 +33,12 @@ pub enum VMArchitecture {
|
|||||||
X86_64,
|
X86_64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum NetworkInterfaceModelType {
|
||||||
|
Virtio,
|
||||||
|
E1000,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NWFilterParam {
|
pub struct NWFilterParam {
|
||||||
name: String,
|
name: String,
|
||||||
@ -41,6 +56,7 @@ pub struct Network {
|
|||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
r#type: NetworkType,
|
r#type: NetworkType,
|
||||||
mac: String,
|
mac: String,
|
||||||
|
model: NetworkInterfaceModelType,
|
||||||
nwfilterref: Option<NWFilterRef>,
|
nwfilterref: Option<NWFilterRef>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,7 +64,8 @@ pub struct Network {
|
|||||||
#[serde(tag = "type")]
|
#[serde(tag = "type")]
|
||||||
pub enum NetworkType {
|
pub enum NetworkType {
|
||||||
UserspaceSLIRPStack,
|
UserspaceSLIRPStack,
|
||||||
DefinedNetwork { network: String }, // TODO : complete network types
|
DefinedNetwork { network: String },
|
||||||
|
Bridge { bridge: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
@ -59,27 +76,35 @@ pub struct VMInfo {
|
|||||||
pub genid: Option<XMLUuid>,
|
pub genid: Option<XMLUuid>,
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
|
/// Group associated with the VM (VirtWeb specific field)
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub group: Option<VMGroupId>,
|
||||||
pub boot_type: BootType,
|
pub boot_type: BootType,
|
||||||
pub architecture: VMArchitecture,
|
pub architecture: VMArchitecture,
|
||||||
/// VM allocated memory, in megabytes
|
/// VM allocated RAM memory
|
||||||
pub memory: usize,
|
pub memory: FileSize,
|
||||||
/// Number of vCPU for the VM
|
/// Number of vCPU for the VM
|
||||||
pub number_vcpu: usize,
|
pub number_vcpu: usize,
|
||||||
/// Enable VNC access through admin console
|
/// Enable VNC access through admin console
|
||||||
pub vnc_access: bool,
|
pub vnc_access: bool,
|
||||||
/// Attach ISO file(s)
|
/// Attach ISO file(s)
|
||||||
pub iso_files: Vec<String>,
|
pub iso_files: Vec<String>,
|
||||||
/// Storage - https://access.redhat.com/documentation/fr-fr/red_hat_enterprise_linux/6/html/virtualization_administration_guide/sect-virtualization-virtualized_block_devices-adding_storage_devices_to_guests#sect-Virtualization-Adding_storage_devices_to_guests-Adding_file_based_storage_to_a_guest
|
/// File Storage - https://access.redhat.com/documentation/fr-fr/red_hat_enterprise_linux/6/html/virtualization_administration_guide/sect-virtualization-virtualized_block_devices-adding_storage_devices_to_guests#sect-Virtualization-Adding_storage_devices_to_guests-Adding_file_based_storage_to_a_guest
|
||||||
pub disks: Vec<Disk>,
|
pub file_disks: Vec<VMFileDisk>,
|
||||||
/// Network cards
|
/// Network cards
|
||||||
pub networks: Vec<Network>,
|
pub networks: Vec<Network>,
|
||||||
/// Add a TPM v2.0 module
|
/// Add a TPM v2.0 module
|
||||||
pub tpm_module: bool,
|
pub tpm_module: bool,
|
||||||
|
/// Strings injected as OEM Strings in SMBios configuration
|
||||||
|
pub oem_strings: Vec<String>,
|
||||||
|
/// Cloud init configuration
|
||||||
|
#[serde(default)]
|
||||||
|
pub cloud_init: CloudInitConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VMInfo {
|
impl VMInfo {
|
||||||
/// Turn this VM into a domain
|
/// Turn this VM into a domain
|
||||||
pub fn as_tomain(&self) -> anyhow::Result<DomainXML> {
|
pub fn as_domain(&self) -> anyhow::Result<DomainXML> {
|
||||||
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
||||||
return Err(StructureExtraction("VM name is invalid!").into());
|
return Err(StructureExtraction("VM name is invalid!").into());
|
||||||
}
|
}
|
||||||
@ -105,6 +130,12 @@ impl VMInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(group) = &self.group {
|
||||||
|
if !regex!("^[a-zA-Z0-9]+$").is_match(&group.0) {
|
||||||
|
return Err(StructureExtraction("VM group name is invalid!").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.memory < constants::MIN_VM_MEMORY || self.memory > constants::MAX_VM_MEMORY {
|
if self.memory < constants::MIN_VM_MEMORY || self.memory > constants::MAX_VM_MEMORY {
|
||||||
return Err(StructureExtraction("VM memory is invalid!").into());
|
return Err(StructureExtraction("VM memory is invalid!").into());
|
||||||
}
|
}
|
||||||
@ -113,8 +144,26 @@ impl VMInfo {
|
|||||||
return Err(StructureExtraction("Invalid number of vCPU specified!").into());
|
return Err(StructureExtraction("Invalid number of vCPU specified!").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut disks = vec![];
|
if let Some(e) = self.cloud_init.check_error() {
|
||||||
|
return Err(CloudInitConfiguration(e).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut iso_absolute_files = vec![];
|
||||||
|
|
||||||
|
// Process cloud init image
|
||||||
|
if self.cloud_init.attach_config {
|
||||||
|
let cloud_init_disk_path = AppConfig::get().cloud_init_disk_path_for_vm(&self.name);
|
||||||
|
|
||||||
|
// Apply latest cloud init configuration
|
||||||
|
std::fs::write(
|
||||||
|
&cloud_init_disk_path,
|
||||||
|
self.cloud_init.generate_nocloud_disk()?,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
iso_absolute_files.push(cloud_init_disk_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process uploaded ISO files
|
||||||
for iso_file in &self.iso_files {
|
for iso_file in &self.iso_files {
|
||||||
if !files_utils::check_file_name(iso_file) {
|
if !files_utils::check_file_name(iso_file) {
|
||||||
return Err(StructureExtraction("ISO filename is invalid!").into());
|
return Err(StructureExtraction("ISO filename is invalid!").into());
|
||||||
@ -126,6 +175,13 @@ impl VMInfo {
|
|||||||
return Err(StructureExtraction("Specified ISO file does not exists!").into());
|
return Err(StructureExtraction("Specified ISO file does not exists!").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
iso_absolute_files.push(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut disks = vec![];
|
||||||
|
|
||||||
|
// Add ISO disk files
|
||||||
|
for iso_path in iso_absolute_files {
|
||||||
disks.push(DiskXML {
|
disks.push(DiskXML {
|
||||||
r#type: "file".to_string(),
|
r#type: "file".to_string(),
|
||||||
device: "cdrom".to_string(),
|
device: "cdrom".to_string(),
|
||||||
@ -135,7 +191,7 @@ impl VMInfo {
|
|||||||
cache: "none".to_string(),
|
cache: "none".to_string(),
|
||||||
},
|
},
|
||||||
source: DiskSourceXML {
|
source: DiskSourceXML {
|
||||||
file: path.to_string_lossy().to_string(),
|
file: iso_path.to_string_lossy().to_string(),
|
||||||
},
|
},
|
||||||
target: DiskTargetXML {
|
target: DiskTargetXML {
|
||||||
dev: format!(
|
dev: format!(
|
||||||
@ -152,6 +208,7 @@ impl VMInfo {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Configure VNC access, if requested
|
||||||
let (vnc_graphics, vnc_video) = match self.vnc_access {
|
let (vnc_graphics, vnc_video) = match self.vnc_access {
|
||||||
true => (
|
true => (
|
||||||
Some(GraphicsXML {
|
Some(GraphicsXML {
|
||||||
@ -178,7 +235,11 @@ impl VMInfo {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let model = Some(NetIntModelXML {
|
let model = Some(NetIntModelXML {
|
||||||
r#type: "virtio".to_string(),
|
r#type: match n.model {
|
||||||
|
NetworkInterfaceModelType::Virtio => "virtio",
|
||||||
|
NetworkInterfaceModelType::E1000 => "e1000",
|
||||||
|
}
|
||||||
|
.to_string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let filterref = if let Some(n) = &n.nwfilterref {
|
let filterref = if let Some(n) = &n.nwfilterref {
|
||||||
@ -223,7 +284,18 @@ impl VMInfo {
|
|||||||
mac,
|
mac,
|
||||||
r#type: "network".to_string(),
|
r#type: "network".to_string(),
|
||||||
source: Some(NetIntSourceXML {
|
source: Some(NetIntSourceXML {
|
||||||
network: network.to_string(),
|
network: Some(network.to_string()),
|
||||||
|
bridge: None,
|
||||||
|
}),
|
||||||
|
model,
|
||||||
|
filterref,
|
||||||
|
},
|
||||||
|
NetworkType::Bridge { bridge } => DomainNetInterfaceXML {
|
||||||
|
r#type: "bridge".to_string(),
|
||||||
|
mac,
|
||||||
|
source: Some(NetIntSourceXML {
|
||||||
|
network: None,
|
||||||
|
bridge: Some(bridge.to_string()),
|
||||||
}),
|
}),
|
||||||
model,
|
model,
|
||||||
filterref,
|
filterref,
|
||||||
@ -232,15 +304,21 @@ impl VMInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check disks name for duplicates
|
// Check disks name for duplicates
|
||||||
for disk in &self.disks {
|
for disk in &self.file_disks {
|
||||||
if self.disks.iter().filter(|d| d.name == disk.name).count() > 1 {
|
if self
|
||||||
|
.file_disks
|
||||||
|
.iter()
|
||||||
|
.filter(|d| d.name == disk.name)
|
||||||
|
.count()
|
||||||
|
> 1
|
||||||
|
{
|
||||||
return Err(StructureExtraction("Two different disks have the same name!").into());
|
return Err(StructureExtraction("Two different disks have the same name!").into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply disks configuration. Starting from now, the function should ideally never fail due to
|
// Apply disks configuration. Starting from now, the function should ideally never fail due to
|
||||||
// bad user input
|
// bad user input
|
||||||
for disk in &self.disks {
|
for disk in &self.file_disks {
|
||||||
disk.check_config()?;
|
disk.check_config()?;
|
||||||
disk.apply_config(uuid)?;
|
disk.apply_config(uuid)?;
|
||||||
|
|
||||||
@ -253,7 +331,10 @@ impl VMInfo {
|
|||||||
device: "disk".to_string(),
|
device: "disk".to_string(),
|
||||||
driver: DiskDriverXML {
|
driver: DiskDriverXML {
|
||||||
name: "qemu".to_string(),
|
name: "qemu".to_string(),
|
||||||
r#type: "raw".to_string(),
|
r#type: match disk.format {
|
||||||
|
VMDiskFormat::Raw { .. } => "raw".to_string(),
|
||||||
|
VMDiskFormat::QCow2 => "qcow2".to_string(),
|
||||||
|
},
|
||||||
cache: "none".to_string(),
|
cache: "none".to_string(),
|
||||||
},
|
},
|
||||||
source: DiskSourceXML {
|
source: DiskSourceXML {
|
||||||
@ -264,7 +345,11 @@ impl VMInfo {
|
|||||||
"vd{}",
|
"vd{}",
|
||||||
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"][disks.len()]
|
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"][disks.len()]
|
||||||
),
|
),
|
||||||
bus: "virtio".to_string(),
|
bus: match disk.bus {
|
||||||
|
VMDiskBus::Virtio => "virtio",
|
||||||
|
VMDiskBus::SATA => "sata",
|
||||||
|
}
|
||||||
|
.to_string(),
|
||||||
},
|
},
|
||||||
readonly: None,
|
readonly: None,
|
||||||
boot: DiskBootXML {
|
boot: DiskBootXML {
|
||||||
@ -282,6 +367,13 @@ impl VMInfo {
|
|||||||
title: self.title.clone(),
|
title: self.title.clone(),
|
||||||
description: self.description.clone(),
|
description: self.description.clone(),
|
||||||
|
|
||||||
|
metadata: Some(DomainMetadataXML {
|
||||||
|
virtweb: DomainMetadataVirtWebXML {
|
||||||
|
ns: "https://virtweb.communiquons.org".to_string(),
|
||||||
|
group: self.group.clone().map(|g| g.0),
|
||||||
|
cloud_init: Some(self.cloud_init.clone()),
|
||||||
|
},
|
||||||
|
}),
|
||||||
os: OSXML {
|
os: OSXML {
|
||||||
r#type: OSTypeXML {
|
r#type: OSTypeXML {
|
||||||
arch: match self.architecture {
|
arch: match self.architecture {
|
||||||
@ -292,12 +384,28 @@ impl VMInfo {
|
|||||||
machine: "q35".to_string(),
|
machine: "q35".to_string(),
|
||||||
body: "hvm".to_string(),
|
body: "hvm".to_string(),
|
||||||
},
|
},
|
||||||
firmware: "efi".to_string(),
|
firmware: match self.boot_type {
|
||||||
loader: Some(OSLoaderXML {
|
BootType::Legacy => None,
|
||||||
secure: match self.boot_type {
|
_ => Some("efi".to_string()),
|
||||||
BootType::UEFI => "no".to_string(),
|
},
|
||||||
BootType::UEFISecureBoot => "yes".to_string(),
|
loader: match self.boot_type {
|
||||||
},
|
BootType::Legacy => None,
|
||||||
|
_ => Some(OSLoaderXML {
|
||||||
|
secure: match self.boot_type {
|
||||||
|
BootType::UEFISecureBoot => "yes".to_string(),
|
||||||
|
_ => "no".to_string(),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
bootmenu: match self.boot_type {
|
||||||
|
BootType::Legacy => Some(OSBootMenuXML {
|
||||||
|
enable: "yes".to_string(),
|
||||||
|
timeout: 3000,
|
||||||
|
}),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
smbios: Some(OSSMBiosXML {
|
||||||
|
mode: "sysinfo".to_string(),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -333,7 +441,7 @@ impl VMInfo {
|
|||||||
|
|
||||||
memory: DomainMemoryXML {
|
memory: DomainMemoryXML {
|
||||||
unit: "MB".to_string(),
|
unit: "MB".to_string(),
|
||||||
memory: self.memory,
|
memory: self.memory.as_mb(),
|
||||||
},
|
},
|
||||||
|
|
||||||
vcpu: DomainVCPUXML {
|
vcpu: DomainVCPUXML {
|
||||||
@ -355,6 +463,17 @@ impl VMInfo {
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
sysinfo: Some(SysInfoXML {
|
||||||
|
r#type: "smbios".to_string(),
|
||||||
|
oem_strings: Some(OEMStringsXML {
|
||||||
|
entries: self
|
||||||
|
.oem_strings
|
||||||
|
.iter()
|
||||||
|
.map(|s| OEMStringEntryXML { content: s.clone() })
|
||||||
|
.collect(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
|
||||||
on_poweroff: "destroy".to_string(),
|
on_poweroff: "destroy".to_string(),
|
||||||
on_reboot: "restart".to_string(),
|
on_reboot: "restart".to_string(),
|
||||||
on_crash: "destroy".to_string(),
|
on_crash: "destroy".to_string(),
|
||||||
@ -369,9 +488,17 @@ impl VMInfo {
|
|||||||
genid: domain.genid.map(XMLUuid),
|
genid: domain.genid.map(XMLUuid),
|
||||||
title: domain.title,
|
title: domain.title,
|
||||||
description: domain.description,
|
description: domain.description,
|
||||||
boot_type: match domain.os.loader {
|
group: domain
|
||||||
None => BootType::UEFI,
|
.metadata
|
||||||
Some(l) => match l.secure.as_str() {
|
.clone()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.virtweb
|
||||||
|
.group
|
||||||
|
.map(VMGroupId),
|
||||||
|
boot_type: match (domain.os.loader, domain.os.bootmenu) {
|
||||||
|
(_, Some(_)) => BootType::Legacy,
|
||||||
|
(None, _) => BootType::UEFI,
|
||||||
|
(Some(l), _) => match l.secure.as_str() {
|
||||||
"yes" => BootType::UEFISecureBoot,
|
"yes" => BootType::UEFISecureBoot,
|
||||||
_ => BootType::UEFI,
|
_ => BootType::UEFI,
|
||||||
},
|
},
|
||||||
@ -387,7 +514,7 @@ impl VMInfo {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
number_vcpu: domain.vcpu.body,
|
number_vcpu: domain.vcpu.body,
|
||||||
memory: convert_size_unit_to_mb(&domain.memory.unit, domain.memory.memory)?,
|
memory: FileSize::from_size_unit(&domain.memory.unit, domain.memory.memory)?,
|
||||||
vnc_access: domain.devices.graphics.is_some(),
|
vnc_access: domain.devices.graphics.is_some(),
|
||||||
iso_files: domain
|
iso_files: domain
|
||||||
.devices
|
.devices
|
||||||
@ -395,14 +522,18 @@ impl VMInfo {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|d| d.device == "cdrom")
|
.filter(|d| d.device == "cdrom")
|
||||||
.map(|d| d.source.file.rsplit_once('/').unwrap().1.to_string())
|
.map(|d| d.source.file.rsplit_once('/').unwrap().1.to_string())
|
||||||
|
.filter(|d| !d.starts_with(constants::CLOUD_INIT_IMAGE_PREFIX_NAME))
|
||||||
.collect(),
|
.collect(),
|
||||||
|
|
||||||
disks: domain
|
file_disks: domain
|
||||||
.devices
|
.devices
|
||||||
.disks
|
.disks
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|d| d.device == "disk")
|
.filter(|d| d.device == "disk")
|
||||||
.map(|d| Disk::load_from_file(&d.source.file).unwrap())
|
.map(|d| {
|
||||||
|
VMFileDisk::load_from_file(&d.source.file, &d.target.bus)
|
||||||
|
.expect("Failed to load file disk information!")
|
||||||
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
|
|
||||||
networks: domain
|
networks: domain
|
||||||
@ -415,7 +546,34 @@ impl VMInfo {
|
|||||||
r#type: match d.r#type.as_str() {
|
r#type: match d.r#type.as_str() {
|
||||||
"user" => NetworkType::UserspaceSLIRPStack,
|
"user" => NetworkType::UserspaceSLIRPStack,
|
||||||
"network" => NetworkType::DefinedNetwork {
|
"network" => NetworkType::DefinedNetwork {
|
||||||
network: d.source.as_ref().unwrap().network.to_string(),
|
network: d
|
||||||
|
.source
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.network
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
LibVirtStructError::DomainExtraction(
|
||||||
|
"Missing source network for defined network!"
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
})?
|
||||||
|
.to_string(),
|
||||||
|
},
|
||||||
|
"bridge" => NetworkType::Bridge {
|
||||||
|
bridge: d
|
||||||
|
.source
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.bridge
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
LibVirtStructError::DomainExtraction(
|
||||||
|
"Missing bridge name for bridge connection!"
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
})?
|
||||||
|
.to_string(),
|
||||||
},
|
},
|
||||||
a => {
|
a => {
|
||||||
return Err(LibVirtStructError::DomainExtraction(format!(
|
return Err(LibVirtStructError::DomainExtraction(format!(
|
||||||
@ -423,6 +581,18 @@ impl VMInfo {
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
model: match d.model.as_ref() {
|
||||||
|
None => NetworkInterfaceModelType::Virtio,
|
||||||
|
Some(model) => match model.r#type.as_str() {
|
||||||
|
"virtio" => NetworkInterfaceModelType::Virtio,
|
||||||
|
"e1000" => NetworkInterfaceModelType::E1000,
|
||||||
|
model => {
|
||||||
|
return Err(LibVirtStructError::DomainExtraction(format!(
|
||||||
|
"Unknown network interface model type: {model}! "
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
nwfilterref: d.filterref.as_ref().map(|f| NWFilterRef {
|
nwfilterref: d.filterref.as_ref().map(|f| NWFilterRef {
|
||||||
name: f.filter.to_string(),
|
name: f.filter.to_string(),
|
||||||
parameters: f
|
parameters: f
|
||||||
@ -439,6 +609,19 @@ impl VMInfo {
|
|||||||
.collect::<Result<Vec<_>, _>>()?,
|
.collect::<Result<Vec<_>, _>>()?,
|
||||||
|
|
||||||
tpm_module: domain.devices.tpm.is_some(),
|
tpm_module: domain.devices.tpm.is_some(),
|
||||||
|
|
||||||
|
oem_strings: domain
|
||||||
|
.sysinfo
|
||||||
|
.and_then(|s| s.oem_strings)
|
||||||
|
.map(|s| s.entries.iter().map(|o| o.content.to_string()).collect())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
cloud_init: domain
|
||||||
|
.metadata
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.virtweb
|
||||||
|
.cloud_init
|
||||||
|
.unwrap_or_default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,19 @@
|
|||||||
use actix::Actor;
|
use actix::Actor;
|
||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_identity::config::LogoutBehaviour;
|
|
||||||
use actix_identity::IdentityMiddleware;
|
use actix_identity::IdentityMiddleware;
|
||||||
use actix_multipart::form::tempfile::TempFileConfig;
|
use actix_identity::config::LogoutBehaviour;
|
||||||
use actix_multipart::form::MultipartFormConfig;
|
use actix_multipart::form::MultipartFormConfig;
|
||||||
|
use actix_multipart::form::tempfile::TempFileConfig;
|
||||||
use actix_remote_ip::RemoteIPConfig;
|
use actix_remote_ip::RemoteIPConfig;
|
||||||
use actix_session::storage::CookieSessionStore;
|
|
||||||
use actix_session::SessionMiddleware;
|
use actix_session::SessionMiddleware;
|
||||||
|
use actix_session::storage::CookieSessionStore;
|
||||||
use actix_web::cookie::{Key, SameSite};
|
use actix_web::cookie::{Key, SameSite};
|
||||||
use actix_web::http::header;
|
use actix_web::http::header;
|
||||||
use actix_web::middleware::Logger;
|
use actix_web::middleware::Logger;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{web, App, HttpServer};
|
use actix_web::{App, HttpServer, web};
|
||||||
use light_openid::basic_state_manager::BasicStateManager;
|
use light_openid::basic_state_manager::BasicStateManager;
|
||||||
|
use std::cmp::max;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use virtweb_backend::actors::libvirt_actor::LibVirtActor;
|
use virtweb_backend::actors::libvirt_actor::LibVirtActor;
|
||||||
use virtweb_backend::actors::vnc_tokens_actor::VNCTokensManager;
|
use virtweb_backend::actors::vnc_tokens_actor::VNCTokensManager;
|
||||||
@ -22,26 +23,54 @@ use virtweb_backend::constants::{
|
|||||||
MAX_INACTIVITY_DURATION, MAX_SESSION_DURATION, SESSION_COOKIE_NAME,
|
MAX_INACTIVITY_DURATION, MAX_SESSION_DURATION, SESSION_COOKIE_NAME,
|
||||||
};
|
};
|
||||||
use virtweb_backend::controllers::{
|
use virtweb_backend::controllers::{
|
||||||
auth_controller, iso_controller, network_controller, nwfilter_controller, server_controller,
|
api_tokens_controller, auth_controller, disk_images_controller, groups_controller,
|
||||||
static_controller, vm_controller,
|
iso_controller, network_controller, nwfilter_controller, server_controller, static_controller,
|
||||||
|
vm_controller,
|
||||||
};
|
};
|
||||||
use virtweb_backend::libvirt_client::LibVirtClient;
|
use virtweb_backend::libvirt_client::LibVirtClient;
|
||||||
use virtweb_backend::middlewares::auth_middleware::AuthChecker;
|
use virtweb_backend::middlewares::auth_middleware::AuthChecker;
|
||||||
use virtweb_backend::utils::files_utils;
|
use virtweb_backend::nat::nat_conf_mode;
|
||||||
|
use virtweb_backend::utils::{exec_utils, files_utils};
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
|
|
||||||
|
// Run in NAT configuration mode, if requested
|
||||||
|
if std::env::var(constants::NAT_MODE_ENV_VAR_NAME).is_ok() {
|
||||||
|
nat_conf_mode::sub_main().await.unwrap();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
// Load additional config from file, if requested
|
// Load additional config from file, if requested
|
||||||
AppConfig::parse_env_file().unwrap();
|
AppConfig::parse_env_file().unwrap();
|
||||||
|
|
||||||
|
log::debug!("Checking for required programs");
|
||||||
|
exec_utils::check_program(
|
||||||
|
constants::PROGRAM_QEMU_IMAGE,
|
||||||
|
"QEMU disk image utility is required to manipulate QCow2 files!",
|
||||||
|
);
|
||||||
|
exec_utils::check_program(
|
||||||
|
constants::PROGRAM_IP,
|
||||||
|
"ip is required to access bridges information!",
|
||||||
|
);
|
||||||
|
exec_utils::check_program(
|
||||||
|
constants::PROGRAM_CLOUD_LOCALDS,
|
||||||
|
"cloud-localds from package cloud-image-utils is required to build cloud-init images!",
|
||||||
|
);
|
||||||
|
|
||||||
log::debug!("Create required directory, if missing");
|
log::debug!("Create required directory, if missing");
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().iso_storage_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().iso_storage_path()).unwrap();
|
||||||
|
files_utils::create_directory_if_missing(AppConfig::get().cloud_init_disk_storage_path())
|
||||||
|
.unwrap();
|
||||||
|
files_utils::create_directory_if_missing(AppConfig::get().disk_images_storage_path()).unwrap();
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().vnc_sockets_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().vnc_sockets_path()).unwrap();
|
||||||
files_utils::set_file_permission(AppConfig::get().vnc_sockets_path(), 0o777).unwrap();
|
files_utils::set_file_permission(AppConfig::get().vnc_sockets_path(), 0o777).unwrap();
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().disks_storage_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().root_vm_disks_storage_path())
|
||||||
|
.unwrap();
|
||||||
|
files_utils::create_directory_if_missing(AppConfig::get().nat_path()).unwrap();
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().definitions_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().definitions_path()).unwrap();
|
||||||
|
files_utils::create_directory_if_missing(AppConfig::get().api_tokens_path()).unwrap();
|
||||||
|
|
||||||
let conn = Data::new(LibVirtClient(
|
let conn = Data::new(LibVirtClient(
|
||||||
LibVirtActor::connect()
|
LibVirtActor::connect()
|
||||||
@ -76,7 +105,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
let mut cors = Cors::default()
|
let mut cors = Cors::default()
|
||||||
.allowed_origin(&AppConfig::get().website_origin)
|
.allowed_origin(&AppConfig::get().website_origin)
|
||||||
.allowed_methods(vec!["GET", "POST", "DELETE", "PUT"])
|
.allowed_methods(vec!["GET", "POST", "DELETE", "PUT", "PATCH"])
|
||||||
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||||
.allowed_header(header::CONTENT_TYPE)
|
.allowed_header(header::CONTENT_TYPE)
|
||||||
.supports_credentials()
|
.supports_credentials()
|
||||||
@ -99,7 +128,9 @@ async fn main() -> std::io::Result<()> {
|
|||||||
}))
|
}))
|
||||||
.app_data(conn.clone())
|
.app_data(conn.clone())
|
||||||
// Uploaded files
|
// Uploaded files
|
||||||
.app_data(MultipartFormConfig::default().total_limit(constants::ISO_MAX_SIZE))
|
.app_data(MultipartFormConfig::default().total_limit(
|
||||||
|
max(constants::DISK_IMAGE_MAX_SIZE, constants::ISO_MAX_SIZE).as_bytes(),
|
||||||
|
))
|
||||||
.app_data(TempFileConfig::default().directory(&AppConfig::get().temp_dir))
|
.app_data(TempFileConfig::default().directory(&AppConfig::get().temp_dir))
|
||||||
// Server controller
|
// Server controller
|
||||||
.route(
|
.route(
|
||||||
@ -110,6 +141,10 @@ async fn main() -> std::io::Result<()> {
|
|||||||
"/api/server/info",
|
"/api/server/info",
|
||||||
web::get().to(server_controller::server_info),
|
web::get().to(server_controller::server_info),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/server/network_hook_status",
|
||||||
|
web::get().to(server_controller::network_hook_status),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/server/number_vcpus",
|
"/api/server/number_vcpus",
|
||||||
web::get().to(server_controller::number_vcpus),
|
web::get().to(server_controller::number_vcpus),
|
||||||
@ -118,6 +153,14 @@ async fn main() -> std::io::Result<()> {
|
|||||||
"/api/server/networks",
|
"/api/server/networks",
|
||||||
web::get().to(server_controller::networks_list),
|
web::get().to(server_controller::networks_list),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/server/bridges",
|
||||||
|
web::get().to(server_controller::bridges_list),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/server/export_configs",
|
||||||
|
web::get().to(server_controller::export_all_configs),
|
||||||
|
)
|
||||||
// Auth controller
|
// Auth controller
|
||||||
.route(
|
.route(
|
||||||
"/api/auth/local",
|
"/api/auth/local",
|
||||||
@ -165,6 +208,10 @@ async fn main() -> std::io::Result<()> {
|
|||||||
"/api/vm/{uid}/src",
|
"/api/vm/{uid}/src",
|
||||||
web::get().to(vm_controller::get_single_src_def),
|
web::get().to(vm_controller::get_single_src_def),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/vm/{uid}/cloud_init_disk",
|
||||||
|
web::get().to(vm_controller::get_cloud_init_disk),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/vm/{uid}/autostart",
|
"/api/vm/{uid}/autostart",
|
||||||
web::get().to(vm_controller::get_autostart),
|
web::get().to(vm_controller::get_autostart),
|
||||||
@ -197,6 +244,44 @@ async fn main() -> std::io::Result<()> {
|
|||||||
web::get().to(vm_controller::vnc_token),
|
web::get().to(vm_controller::vnc_token),
|
||||||
)
|
)
|
||||||
.route("/api/vnc", web::get().to(vm_controller::vnc))
|
.route("/api/vnc", web::get().to(vm_controller::vnc))
|
||||||
|
// Groups controller
|
||||||
|
.route("/api/group/list", web::get().to(groups_controller::list))
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/info",
|
||||||
|
web::get().to(groups_controller::vm_info),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/start",
|
||||||
|
web::get().to(groups_controller::vm_start),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/shutdown",
|
||||||
|
web::get().to(groups_controller::vm_shutdown),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/suspend",
|
||||||
|
web::get().to(groups_controller::vm_suspend),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/resume",
|
||||||
|
web::get().to(groups_controller::vm_resume),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/kill",
|
||||||
|
web::get().to(groups_controller::vm_kill),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/reset",
|
||||||
|
web::get().to(groups_controller::vm_reset),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/screenshot",
|
||||||
|
web::get().to(groups_controller::vm_screenshot),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/state",
|
||||||
|
web::get().to(groups_controller::vm_state),
|
||||||
|
)
|
||||||
// Network controller
|
// Network controller
|
||||||
.route(
|
.route(
|
||||||
"/api/network/create",
|
"/api/network/create",
|
||||||
@ -264,7 +349,62 @@ async fn main() -> std::io::Result<()> {
|
|||||||
"/api/nwfilter/{uid}",
|
"/api/nwfilter/{uid}",
|
||||||
web::delete().to(nwfilter_controller::delete),
|
web::delete().to(nwfilter_controller::delete),
|
||||||
)
|
)
|
||||||
|
// Disk images library
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/upload",
|
||||||
|
web::post().to(disk_images_controller::upload),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/list",
|
||||||
|
web::get().to(disk_images_controller::get_list),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/{filename}",
|
||||||
|
web::get().to(disk_images_controller::download),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/{filename}/convert",
|
||||||
|
web::post().to(disk_images_controller::convert),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/{filename}/rename",
|
||||||
|
web::post().to(disk_images_controller::rename),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/disk_images/{filename}",
|
||||||
|
web::delete().to(disk_images_controller::delete),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/vm/{uid}/disk/{diskid}/backup",
|
||||||
|
web::post().to(disk_images_controller::backup_disk),
|
||||||
|
)
|
||||||
|
// API tokens controller
|
||||||
|
.route(
|
||||||
|
"/api/token/create",
|
||||||
|
web::post().to(api_tokens_controller::create),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/list",
|
||||||
|
web::get().to(api_tokens_controller::list),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::get().to(api_tokens_controller::get_single),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::patch().to(api_tokens_controller::update),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::delete().to(api_tokens_controller::delete),
|
||||||
|
)
|
||||||
// Static assets
|
// Static assets
|
||||||
|
.route(
|
||||||
|
"/api/assets/{tail:.*}",
|
||||||
|
web::get().to(static_controller::serve_assets::serve_api_assets),
|
||||||
|
)
|
||||||
|
// Static web frontend
|
||||||
.route("/", web::get().to(static_controller::root_index))
|
.route("/", web::get().to(static_controller::root_index))
|
||||||
.route(
|
.route(
|
||||||
"/{tail:.*}",
|
"/{tail:.*}",
|
||||||
|
@ -1,14 +1,15 @@
|
|||||||
use std::future::{ready, Ready};
|
use std::future::{Ready, ready};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use crate::constants;
|
use crate::constants;
|
||||||
|
use crate::extractors::api_auth_extractor::ApiAuthExtractor;
|
||||||
use crate::extractors::auth_extractor::AuthExtractor;
|
use crate::extractors::auth_extractor::AuthExtractor;
|
||||||
use actix_web::body::EitherBody;
|
use actix_web::body::EitherBody;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
|
|
||||||
Error, FromRequest, HttpResponse,
|
Error, FromRequest, HttpResponse,
|
||||||
|
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
|
||||||
};
|
};
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
|
|
||||||
@ -66,10 +67,43 @@ where
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
if !AppConfig::get().is_allowed_ip(remote_ip.0) {
|
||||||
|
log::error!(
|
||||||
|
"An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}",
|
||||||
|
remote_ip
|
||||||
|
);
|
||||||
|
return Ok(req
|
||||||
|
.into_response(
|
||||||
|
HttpResponse::MethodNotAllowed()
|
||||||
|
.json("I am sorry, but your IP is not allowed to access this service!"),
|
||||||
|
)
|
||||||
|
.map_into_right_body());
|
||||||
|
}
|
||||||
|
|
||||||
let auth_disabled = AppConfig::get().unsecure_disable_auth;
|
let auth_disabled = AppConfig::get().unsecure_disable_auth;
|
||||||
|
|
||||||
// Check authentication, if required
|
// Check API authentication
|
||||||
if !auth_disabled
|
if req.headers().get("x-token-id").is_some() {
|
||||||
|
let auth =
|
||||||
|
match ApiAuthExtractor::from_request(req.request(), &mut Payload::None).await {
|
||||||
|
Ok(auth) => auth,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(
|
||||||
|
"Failed to extract API authentication information from request! {e}"
|
||||||
|
);
|
||||||
|
return Ok(req
|
||||||
|
.into_response(HttpResponse::PreconditionFailed().finish())
|
||||||
|
.map_into_right_body());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"Using API token '{}' to perform the request",
|
||||||
|
auth.token.name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Check user authentication, if required
|
||||||
|
else if !auth_disabled
|
||||||
&& !constants::ROUTES_WITHOUT_AUTH.contains(&req.path())
|
&& !constants::ROUTES_WITHOUT_AUTH.contains(&req.path())
|
||||||
&& req.path().starts_with("/api/")
|
&& req.path().starts_with("/api/")
|
||||||
{
|
{
|
||||||
|
4
virtweb_backend/src/nat/mod.rs
Normal file
4
virtweb_backend/src/nat/mod.rs
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
pub mod nat_conf_mode;
|
||||||
|
pub mod nat_definition;
|
||||||
|
pub mod nat_hook;
|
||||||
|
pub mod nat_lib;
|
236
virtweb_backend/src/nat/nat_conf_mode.rs
Normal file
236
virtweb_backend/src/nat/nat_conf_mode.rs
Normal file
@ -0,0 +1,236 @@
|
|||||||
|
use crate::constants;
|
||||||
|
use crate::libvirt_rest_structures::net::NetworkName;
|
||||||
|
use crate::nat::nat_definition::{Nat, NatSourceIP, NetNat};
|
||||||
|
use crate::utils::net_utils;
|
||||||
|
use clap::Parser;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, ExitStatus};
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum NatConfModeError {
|
||||||
|
#[error("UpdateFirewall failed!")]
|
||||||
|
UpdateFirewall,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// VirtWeb NAT configuration mode. This executable should never be executed manually
|
||||||
|
#[derive(Parser, Debug, Clone)]
|
||||||
|
#[clap(author, version, about, long_about = None)]
|
||||||
|
struct NatArgs {
|
||||||
|
/// Storage directory
|
||||||
|
#[clap(short, long)]
|
||||||
|
storage: String,
|
||||||
|
|
||||||
|
/// Network name
|
||||||
|
#[clap(short, long)]
|
||||||
|
network_name: String,
|
||||||
|
|
||||||
|
/// Operation
|
||||||
|
#[clap(short, long)]
|
||||||
|
operation: String,
|
||||||
|
|
||||||
|
/// Sub operation
|
||||||
|
#[clap(long)]
|
||||||
|
sub_operation: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NatArgs {
|
||||||
|
pub fn network_file(&self) -> PathBuf {
|
||||||
|
let network_name = NetworkName(self.network_name.to_string());
|
||||||
|
Path::new(&self.storage)
|
||||||
|
.join(constants::STORAGE_NAT_DIR)
|
||||||
|
.join(network_name.nat_file_name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// NAT sub main function
|
||||||
|
pub async fn sub_main() -> anyhow::Result<()> {
|
||||||
|
let args = NatArgs::parse();
|
||||||
|
|
||||||
|
if !args.network_file().exists() {
|
||||||
|
log::warn!(
|
||||||
|
"Cannot do anything for the network, because the NAT configuration file does not exixsts!"
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let conf_json = std::fs::read_to_string(args.network_file())?;
|
||||||
|
let conf: NetNat = serde_json::from_str(&conf_json)?;
|
||||||
|
|
||||||
|
let nic_ips = net_utils::net_list_and_ips()?;
|
||||||
|
|
||||||
|
match (args.operation.as_str(), args.sub_operation.as_str()) {
|
||||||
|
("started", "begin") => {
|
||||||
|
log::info!("Enable port forwarding for network");
|
||||||
|
trigger_nat_forwarding(true, &conf, &nic_ips).await?
|
||||||
|
}
|
||||||
|
("stopped", "end") => {
|
||||||
|
log::info!("Disable port forwarding for network");
|
||||||
|
trigger_nat_forwarding(false, &conf, &nic_ips).await?
|
||||||
|
}
|
||||||
|
_ => log::debug!(
|
||||||
|
"Operation {} - {} not supported",
|
||||||
|
args.operation,
|
||||||
|
args.sub_operation
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trigger_nat_forwarding(
|
||||||
|
enable: bool,
|
||||||
|
conf: &NetNat,
|
||||||
|
nic_ips: &HashMap<String, Vec<IpAddr>>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
if let Some(ipv4) = &conf.ipv4 {
|
||||||
|
trigger_nat_forwarding_nat_ipv(
|
||||||
|
enable,
|
||||||
|
&conf.interface,
|
||||||
|
&ipv4.iter().map(|i| i.generalize()).collect::<Vec<_>>(),
|
||||||
|
nic_ips,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ipv6) = &conf.ipv6 {
|
||||||
|
trigger_nat_forwarding_nat_ipv(
|
||||||
|
enable,
|
||||||
|
&conf.interface,
|
||||||
|
&ipv6.iter().map(|i| i.generalize()).collect::<Vec<_>>(),
|
||||||
|
nic_ips,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trigger_nat_forwarding_nat_ipv(
|
||||||
|
enable: bool,
|
||||||
|
net_interface: &str,
|
||||||
|
rules: &[Nat<IpAddr>],
|
||||||
|
nic_ips: &HashMap<String, Vec<IpAddr>>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
for r in rules {
|
||||||
|
let host_ips = match &r.host_ip {
|
||||||
|
NatSourceIP::Interface { name } => nic_ips.get(name).cloned().unwrap_or_default(),
|
||||||
|
NatSourceIP::Ip { ip } => vec![*ip],
|
||||||
|
};
|
||||||
|
|
||||||
|
for host_ip in host_ips {
|
||||||
|
let mut guest_port = r.guest_port;
|
||||||
|
for host_port in r.host_port.as_seq() {
|
||||||
|
if r.protocol.has_tcp() {
|
||||||
|
toggle_port_forwarding(
|
||||||
|
enable,
|
||||||
|
false,
|
||||||
|
host_ip,
|
||||||
|
host_port,
|
||||||
|
net_interface,
|
||||||
|
r.guest_ip,
|
||||||
|
guest_port,
|
||||||
|
)?
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.protocol.has_udp() {
|
||||||
|
toggle_port_forwarding(
|
||||||
|
enable,
|
||||||
|
true,
|
||||||
|
host_ip,
|
||||||
|
host_port,
|
||||||
|
net_interface,
|
||||||
|
r.guest_ip,
|
||||||
|
guest_port,
|
||||||
|
)?
|
||||||
|
}
|
||||||
|
|
||||||
|
guest_port += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_cmd(s: ExitStatus) -> anyhow::Result<()> {
|
||||||
|
if !s.success() {
|
||||||
|
log::error!("Failed to update firewall rules!");
|
||||||
|
return Err(NatConfModeError::UpdateFirewall.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn toggle_port_forwarding(
|
||||||
|
enable: bool,
|
||||||
|
is_udp: bool,
|
||||||
|
host_ip: IpAddr,
|
||||||
|
host_port: u16,
|
||||||
|
net_interface: &str,
|
||||||
|
guest_ip: IpAddr,
|
||||||
|
guest_port: u16,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
if host_ip.is_ipv4() != guest_ip.is_ipv4() {
|
||||||
|
log::trace!("Skipping invalid combination {host_ip} -> {guest_ip}");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let program = match host_ip.is_ipv4() {
|
||||||
|
true => "/sbin/iptables",
|
||||||
|
false => "/sbin/ip6tables",
|
||||||
|
};
|
||||||
|
|
||||||
|
let protocol = match is_udp {
|
||||||
|
true => "udp",
|
||||||
|
false => "tcp",
|
||||||
|
};
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Rule 1
|
||||||
|
let cmd = Command::new(program)
|
||||||
|
.arg(match enable {
|
||||||
|
true => "-I",
|
||||||
|
false => "-D",
|
||||||
|
})
|
||||||
|
.arg("FORWARD")
|
||||||
|
.arg("-o")
|
||||||
|
.arg(net_interface)
|
||||||
|
.arg("-p")
|
||||||
|
.arg(protocol)
|
||||||
|
.arg("-d")
|
||||||
|
.arg(guest_ip.to_string())
|
||||||
|
.arg("--dport")
|
||||||
|
.arg(guest_port.to_string())
|
||||||
|
.arg("-j")
|
||||||
|
.arg("ACCEPT")
|
||||||
|
.status()?;
|
||||||
|
check_cmd(cmd)?;
|
||||||
|
|
||||||
|
// Rule 2
|
||||||
|
let cmd = Command::new(program)
|
||||||
|
.arg("-t")
|
||||||
|
.arg("nat")
|
||||||
|
.arg(match enable {
|
||||||
|
true => "-I",
|
||||||
|
false => "-D",
|
||||||
|
})
|
||||||
|
.arg("PREROUTING")
|
||||||
|
.arg("-p")
|
||||||
|
.arg(protocol)
|
||||||
|
.arg("-d")
|
||||||
|
.arg(host_ip.to_string())
|
||||||
|
.arg("--dport")
|
||||||
|
.arg(host_port.to_string())
|
||||||
|
.arg("-j")
|
||||||
|
.arg("DNAT")
|
||||||
|
.arg("--to")
|
||||||
|
.arg(format!("{guest_ip}:{guest_port}"))
|
||||||
|
.status()?;
|
||||||
|
check_cmd(cmd)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
142
virtweb_backend/src/nat/nat_definition.rs
Normal file
142
virtweb_backend/src/nat/nat_definition.rs
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
use crate::constants;
|
||||||
|
use crate::utils::net_utils;
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum NatDefError {
|
||||||
|
#[error("Invalid nat definition: {0}")]
|
||||||
|
InvalidNatDef(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "lowercase")]
|
||||||
|
pub enum NatSourceIP<IPv> {
|
||||||
|
Interface { name: String },
|
||||||
|
Ip { ip: IPv },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum NatProtocol {
|
||||||
|
TCP,
|
||||||
|
UDP,
|
||||||
|
Both,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NatProtocol {
|
||||||
|
pub fn has_tcp(&self) -> bool {
|
||||||
|
!matches!(&self, NatProtocol::UDP)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_udp(&self) -> bool {
|
||||||
|
!matches!(&self, NatProtocol::TCP)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "lowercase")]
|
||||||
|
pub enum NatHostPort {
|
||||||
|
Single { port: u16 },
|
||||||
|
Range { start: u16, end: u16 },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NatHostPort {
|
||||||
|
pub fn as_seq(&self) -> Vec<u16> {
|
||||||
|
match self {
|
||||||
|
NatHostPort::Single { port } => vec![*port],
|
||||||
|
NatHostPort::Range { start, end } => (*start..(*end + 1)).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct Nat<IPv> {
|
||||||
|
pub protocol: NatProtocol,
|
||||||
|
pub host_ip: NatSourceIP<IPv>,
|
||||||
|
pub host_port: NatHostPort,
|
||||||
|
pub guest_ip: IPv,
|
||||||
|
pub guest_port: u16,
|
||||||
|
pub comment: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<IPv> Nat<IPv> {
|
||||||
|
pub fn check(&self) -> anyhow::Result<()> {
|
||||||
|
if let NatSourceIP::Interface { name } = &self.host_ip {
|
||||||
|
if !net_utils::is_net_interface_name_valid(name) {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Invalid nat interface name!").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let NatHostPort::Range { start, end } = &self.host_port {
|
||||||
|
if *start == 0 {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Invalid start range!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if start > end {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Invalid port range!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if u16::MAX - (end - start) < self.guest_port {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Guest port is too high!").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.guest_port == 0 {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Invalid guest port!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(comment) = &self.comment {
|
||||||
|
if comment.len() > constants::NET_NAT_COMMENT_MAX_SIZE {
|
||||||
|
return Err(NatDefError::InvalidNatDef("Comment is too large!").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Nat<Ipv4Addr> {
|
||||||
|
pub fn generalize(&self) -> Nat<IpAddr> {
|
||||||
|
Nat {
|
||||||
|
protocol: self.protocol,
|
||||||
|
host_ip: match &self.host_ip {
|
||||||
|
NatSourceIP::Ip { ip } => NatSourceIP::Ip {
|
||||||
|
ip: IpAddr::V4(*ip),
|
||||||
|
},
|
||||||
|
NatSourceIP::Interface { name } => NatSourceIP::Interface {
|
||||||
|
name: name.to_string(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
host_port: self.host_port.clone(),
|
||||||
|
guest_ip: IpAddr::V4(self.guest_ip),
|
||||||
|
guest_port: self.guest_port,
|
||||||
|
comment: self.comment.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Nat<Ipv6Addr> {
|
||||||
|
pub fn generalize(&self) -> Nat<IpAddr> {
|
||||||
|
Nat {
|
||||||
|
protocol: self.protocol,
|
||||||
|
host_ip: match &self.host_ip {
|
||||||
|
NatSourceIP::Ip { ip } => NatSourceIP::Ip {
|
||||||
|
ip: IpAddr::V6(*ip),
|
||||||
|
},
|
||||||
|
NatSourceIP::Interface { name } => NatSourceIP::Interface {
|
||||||
|
name: name.to_string(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
host_port: self.host_port.clone(),
|
||||||
|
guest_ip: IpAddr::V6(self.guest_ip),
|
||||||
|
guest_port: self.guest_port,
|
||||||
|
comment: self.comment.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
|
||||||
|
pub struct NetNat {
|
||||||
|
pub interface: String,
|
||||||
|
pub ipv4: Option<Vec<Nat<Ipv4Addr>>>,
|
||||||
|
pub ipv6: Option<Vec<Nat<Ipv6Addr>>>,
|
||||||
|
}
|
29
virtweb_backend/src/nat/nat_hook.rs
Normal file
29
virtweb_backend/src/nat/nat_hook.rs
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// Check out whether NAT hook has been installed or not
|
||||||
|
pub fn is_installed() -> anyhow::Result<bool> {
|
||||||
|
let hook_file = Path::new(constants::NAT_HOOK_PATH);
|
||||||
|
|
||||||
|
if !hook_file.exists() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
let exe = std::env::current_exe()?;
|
||||||
|
let hook_content = std::fs::read_to_string(hook_file)?;
|
||||||
|
|
||||||
|
Ok(hook_content.contains(exe.to_string_lossy().as_ref()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get nat hook expected content
|
||||||
|
pub fn hook_content() -> anyhow::Result<String> {
|
||||||
|
let exe = std::env::current_exe()?;
|
||||||
|
|
||||||
|
Ok(format!(
|
||||||
|
"#!/bin/bash\n\
|
||||||
|
NAT_MODE=1 {} --storage {} --network-name \"$1\" --operation \"$2\" --sub-operation \"$3\"",
|
||||||
|
exe.to_string_lossy(),
|
||||||
|
AppConfig::get().storage
|
||||||
|
))
|
||||||
|
}
|
61
virtweb_backend/src/nat/nat_lib.rs
Normal file
61
virtweb_backend/src/nat/nat_lib.rs
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::libvirt_rest_structures::net::{NetworkInfo, NetworkName};
|
||||||
|
use crate::nat::nat_definition::NetNat;
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum NatLibError {
|
||||||
|
#[error("Could not save nat definition, because network bridge name was not specified!")]
|
||||||
|
MissingNetworkBridgeName,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save nat definition
|
||||||
|
pub fn save_nat_def(net: &NetworkInfo) -> anyhow::Result<()> {
|
||||||
|
let nat = match net.has_nat_def() {
|
||||||
|
true => NetNat {
|
||||||
|
interface: net
|
||||||
|
.bridge_name
|
||||||
|
.as_ref()
|
||||||
|
.ok_or(NatLibError::MissingNetworkBridgeName)?
|
||||||
|
.to_string(),
|
||||||
|
ipv4: net
|
||||||
|
.ip_v4
|
||||||
|
.as_ref()
|
||||||
|
.map(|i| i.nat.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
ipv6: net
|
||||||
|
.ip_v6
|
||||||
|
.as_ref()
|
||||||
|
.map(|i| i.nat.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
},
|
||||||
|
false => NetNat::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let json = serde_json::to_string(&nat)?;
|
||||||
|
|
||||||
|
std::fs::write(AppConfig::get().net_nat_path(&net.name), json)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove nat definition, if existing
|
||||||
|
pub fn remove_nat_def(name: &NetworkName) -> anyhow::Result<()> {
|
||||||
|
let nat_file = AppConfig::get().net_nat_path(name);
|
||||||
|
if nat_file.exists() {
|
||||||
|
std::fs::remove_file(nat_file)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load nat definition, if available
|
||||||
|
pub fn load_nat_def(name: &NetworkName) -> anyhow::Result<NetNat> {
|
||||||
|
let nat_file = AppConfig::get().net_nat_path(name);
|
||||||
|
if !nat_file.exists() {
|
||||||
|
return Ok(NetNat::default());
|
||||||
|
}
|
||||||
|
|
||||||
|
let file = std::fs::read_to_string(nat_file)?;
|
||||||
|
|
||||||
|
Ok(serde_json::from_str(&file)?)
|
||||||
|
}
|
117
virtweb_backend/src/utils/cloud_init_utils.rs
Normal file
117
virtweb_backend/src/utils/cloud_init_utils.rs
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
/// Cloud init DS Mode
|
||||||
|
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum CloudInitDSMode {
|
||||||
|
/// Networking is required
|
||||||
|
Net,
|
||||||
|
/// Does not require networking to be up before user-data actions are run
|
||||||
|
Local,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// VM Cloud Init configuration
|
||||||
|
///
|
||||||
|
/// RedHat documentation: https://docs.redhat.com/fr/documentation/red_hat_enterprise_linux/9/html/configuring_and_managing_cloud-init_for_rhel_9/configuring-cloud-init_cloud-content
|
||||||
|
/// cloud-localds source code: https://github.com/canonical/cloud-utils/blob/main/bin/cloud-localds
|
||||||
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Default)]
|
||||||
|
pub struct CloudInitConfig {
|
||||||
|
pub attach_config: bool,
|
||||||
|
/// Main user data
|
||||||
|
pub user_data: String,
|
||||||
|
/// Instance ID, set in metadata file
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub instance_id: Option<String>,
|
||||||
|
/// Local hostname, set in metadata file
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub local_hostname: Option<String>,
|
||||||
|
/// Data source mode
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub dsmode: Option<CloudInitDSMode>,
|
||||||
|
/// Network configuration
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub network_configuration: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CloudInitConfig {
|
||||||
|
/// Check cloud init configuration
|
||||||
|
pub fn check_error(&self) -> Option<String> {
|
||||||
|
if !self.user_data.is_empty() {
|
||||||
|
// Check YAML content
|
||||||
|
if let Err(e) = serde_yml::from_str::<serde_json::Value>(&self.user_data) {
|
||||||
|
return Some(format!(
|
||||||
|
"user data is an invalid YAML file! Deserialization error: {e}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check first line
|
||||||
|
if !self.user_data.starts_with("#cloud-config\n") {
|
||||||
|
return Some(
|
||||||
|
"user data file MUST start with '#cloud-config' as first line!".to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate disk image for nocloud usage
|
||||||
|
pub fn generate_nocloud_disk(&self) -> anyhow::Result<Vec<u8>> {
|
||||||
|
let temp_path = tempfile::tempdir_in(&AppConfig::get().temp_dir)?;
|
||||||
|
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_CLOUD_LOCALDS);
|
||||||
|
|
||||||
|
// ISO destination path
|
||||||
|
let temp_iso = temp_path.path().join("disk.iso");
|
||||||
|
cmd.arg(&temp_iso);
|
||||||
|
|
||||||
|
// Process network configuration
|
||||||
|
if let Some(net_conf) = &self.network_configuration {
|
||||||
|
let net_conf_path = temp_path.path().join("network");
|
||||||
|
std::fs::write(&net_conf_path, net_conf)?;
|
||||||
|
cmd.arg("--network-config").arg(&net_conf_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process user data
|
||||||
|
let user_data_path = temp_path.path().join("user-data");
|
||||||
|
std::fs::write(&user_data_path, &self.user_data)?;
|
||||||
|
cmd.arg(user_data_path);
|
||||||
|
|
||||||
|
// Process metadata
|
||||||
|
let mut metadatas = vec![];
|
||||||
|
if let Some(inst_id) = &self.instance_id {
|
||||||
|
metadatas.push(format!("instance-id: {}", inst_id));
|
||||||
|
}
|
||||||
|
if let Some(local_hostname) = &self.local_hostname {
|
||||||
|
metadatas.push(format!("local-hostname: {}", local_hostname));
|
||||||
|
}
|
||||||
|
if let Some(dsmode) = &self.dsmode {
|
||||||
|
metadatas.push(format!(
|
||||||
|
"dsmode: {}",
|
||||||
|
match dsmode {
|
||||||
|
CloudInitDSMode::Net => "net",
|
||||||
|
CloudInitDSMode::Local => "local",
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let meta_data_path = temp_path.path().join("meta-data");
|
||||||
|
std::fs::write(&meta_data_path, metadatas.join("\n"))?;
|
||||||
|
cmd.arg(meta_data_path);
|
||||||
|
|
||||||
|
// Execute command
|
||||||
|
let output = cmd.output()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"{} exited with status {}!\nStdout: {}\nStderr: {}",
|
||||||
|
constants::PROGRAM_CLOUD_LOCALDS,
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read generated ISO file
|
||||||
|
Ok(std::fs::read(temp_iso)?)
|
||||||
|
}
|
||||||
|
}
|
@ -1,133 +0,0 @@
|
|||||||
use crate::app_config::AppConfig;
|
|
||||||
use crate::constants;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
|
||||||
use crate::utils::files_utils;
|
|
||||||
use lazy_regex::regex;
|
|
||||||
use std::os::linux::fs::MetadataExt;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::process::Command;
|
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
enum DisksError {
|
|
||||||
#[error("DiskParseError: {0}")]
|
|
||||||
Parse(&'static str),
|
|
||||||
#[error("DiskConfigError: {0}")]
|
|
||||||
Config(&'static str),
|
|
||||||
#[error("DiskCreateError")]
|
|
||||||
Create,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Type of disk allocation
|
|
||||||
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
|
||||||
pub enum DiskAllocType {
|
|
||||||
Fixed,
|
|
||||||
Sparse,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
|
||||||
pub struct Disk {
|
|
||||||
/// Disk size, in megabytes
|
|
||||||
pub size: usize,
|
|
||||||
/// Disk name
|
|
||||||
pub name: String,
|
|
||||||
pub alloc_type: DiskAllocType,
|
|
||||||
/// Set this variable to true to delete the disk
|
|
||||||
pub delete: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Disk {
|
|
||||||
pub fn load_from_file(path: &str) -> anyhow::Result<Self> {
|
|
||||||
let file = Path::new(path);
|
|
||||||
|
|
||||||
if !file.is_file() {
|
|
||||||
return Err(DisksError::Parse("Path is not a file!").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let metadata = file.metadata()?;
|
|
||||||
|
|
||||||
// Approximate estimation
|
|
||||||
let is_sparse = metadata.len() / 512 >= metadata.st_blocks();
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
size: metadata.len() as usize / (1000 * 1000),
|
|
||||||
name: path.rsplit_once('/').unwrap().1.to_string(),
|
|
||||||
alloc_type: match is_sparse {
|
|
||||||
true => DiskAllocType::Sparse,
|
|
||||||
false => DiskAllocType::Fixed,
|
|
||||||
},
|
|
||||||
delete: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn check_config(&self) -> anyhow::Result<()> {
|
|
||||||
if constants::DISK_NAME_MIN_LEN > self.name.len()
|
|
||||||
|| constants::DISK_NAME_MAX_LEN < self.name.len()
|
|
||||||
{
|
|
||||||
return Err(DisksError::Config("Disk name length is invalid").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
|
||||||
return Err(DisksError::Config("Disk name contains invalid characters!").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.size < constants::DISK_SIZE_MIN || self.size > constants::DISK_SIZE_MAX {
|
|
||||||
return Err(DisksError::Config("Disk size is invalid!").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get disk path
|
|
||||||
pub fn disk_path(&self, id: XMLUuid) -> PathBuf {
|
|
||||||
let domain_dir = AppConfig::get().vm_storage_path(id);
|
|
||||||
domain_dir.join(&self.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply disk configuration
|
|
||||||
pub fn apply_config(&self, id: XMLUuid) -> anyhow::Result<()> {
|
|
||||||
self.check_config()?;
|
|
||||||
|
|
||||||
let file = self.disk_path(id);
|
|
||||||
files_utils::create_directory_if_missing(file.parent().unwrap())?;
|
|
||||||
|
|
||||||
// Delete file if requested
|
|
||||||
if self.delete {
|
|
||||||
if !file.exists() {
|
|
||||||
log::debug!("File {file:?} does not exists, so it was not deleted");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
log::info!("Deleting {file:?}");
|
|
||||||
std::fs::remove_file(file)?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if file.exists() {
|
|
||||||
log::debug!("File {file:?} does not exists, so it was not touched");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut cmd = Command::new("/usr/bin/dd");
|
|
||||||
cmd.arg("if=/dev/zero")
|
|
||||||
.arg(format!("of={}", file.to_string_lossy()))
|
|
||||||
.arg("bs=1M");
|
|
||||||
|
|
||||||
match self.alloc_type {
|
|
||||||
DiskAllocType::Fixed => cmd.arg(format!("count={}", self.size)),
|
|
||||||
DiskAllocType::Sparse => cmd.arg(format!("seek={}", self.size)).arg("count=0"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let res = cmd.output()?;
|
|
||||||
|
|
||||||
if !res.status.success() {
|
|
||||||
log::error!(
|
|
||||||
"Failed to create disk! stderr={} stdout={}",
|
|
||||||
String::from_utf8_lossy(&res.stderr),
|
|
||||||
String::from_utf8_lossy(&res.stdout)
|
|
||||||
);
|
|
||||||
return Err(DisksError::Create.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
10
virtweb_backend/src/utils/exec_utils.rs
Normal file
10
virtweb_backend/src/utils/exec_utils.rs
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// Check the existence of a required program
|
||||||
|
pub fn check_program(name: &str, description: &str) {
|
||||||
|
let path = Path::new(name);
|
||||||
|
|
||||||
|
if !path.exists() {
|
||||||
|
panic!("{name} does not exist! {description}");
|
||||||
|
}
|
||||||
|
}
|
468
virtweb_backend/src/utils/file_disks_utils.rs
Normal file
468
virtweb_backend/src/utils/file_disks_utils.rs
Normal file
@ -0,0 +1,468 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::utils::file_size_utils::FileSize;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::os::linux::fs::MetadataExt;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
use std::time::UNIX_EPOCH;
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum DisksError {
|
||||||
|
#[error("DiskParseError: {0}")]
|
||||||
|
Parse(&'static str),
|
||||||
|
#[error("DiskCreateError")]
|
||||||
|
Create,
|
||||||
|
#[error("DiskConvertError: {0}")]
|
||||||
|
Convert(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, serde::Serialize, serde::Deserialize, Copy, Clone, PartialEq, Eq)]
|
||||||
|
#[serde(tag = "format")]
|
||||||
|
pub enum DiskFileFormat {
|
||||||
|
Raw {
|
||||||
|
#[serde(default)]
|
||||||
|
is_sparse: bool,
|
||||||
|
},
|
||||||
|
QCow2 {
|
||||||
|
#[serde(default)]
|
||||||
|
virtual_size: FileSize,
|
||||||
|
},
|
||||||
|
GzCompressedRaw,
|
||||||
|
GzCompressedQCow2,
|
||||||
|
XzCompressedRaw,
|
||||||
|
XzCompressedQCow2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DiskFileFormat {
|
||||||
|
pub fn ext(&self) -> &'static [&'static str] {
|
||||||
|
match self {
|
||||||
|
DiskFileFormat::Raw { .. } => &["raw", ""],
|
||||||
|
DiskFileFormat::QCow2 { .. } => &["qcow2"],
|
||||||
|
DiskFileFormat::GzCompressedRaw => &["raw.gz"],
|
||||||
|
DiskFileFormat::GzCompressedQCow2 => &["qcow2.gz"],
|
||||||
|
DiskFileFormat::XzCompressedRaw => &["raw.xz"],
|
||||||
|
DiskFileFormat::XzCompressedQCow2 => &["qcow2.xz"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disk file information
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub struct DiskFileInfo {
|
||||||
|
pub file_path: PathBuf,
|
||||||
|
pub file_size: FileSize,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub format: DiskFileFormat,
|
||||||
|
pub file_name: String,
|
||||||
|
pub name: String,
|
||||||
|
pub created: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DiskFileInfo {
|
||||||
|
/// Get disk image file information
|
||||||
|
pub fn load_file(file: &Path) -> anyhow::Result<Self> {
|
||||||
|
if !file.is_file() {
|
||||||
|
return Err(DisksError::Parse("Path is not a file!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get file metadata
|
||||||
|
let metadata = file.metadata()?;
|
||||||
|
let mut name = file
|
||||||
|
.file_stem()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.unwrap_or("disk")
|
||||||
|
.to_string();
|
||||||
|
let ext = file.extension().and_then(|s| s.to_str()).unwrap_or("raw");
|
||||||
|
|
||||||
|
// Determine file format
|
||||||
|
let format = match ext {
|
||||||
|
"qcow2" => DiskFileFormat::QCow2 {
|
||||||
|
virtual_size: qcow_virt_size(file)?,
|
||||||
|
},
|
||||||
|
"raw" => DiskFileFormat::Raw {
|
||||||
|
is_sparse: metadata.len() / 512 >= metadata.st_blocks(),
|
||||||
|
},
|
||||||
|
"gz" if name.ends_with(".qcow2") => {
|
||||||
|
name = name.strip_suffix(".qcow2").unwrap_or(&name).to_string();
|
||||||
|
DiskFileFormat::GzCompressedQCow2
|
||||||
|
}
|
||||||
|
"gz" => DiskFileFormat::GzCompressedRaw,
|
||||||
|
"xz" if name.ends_with(".qcow2") => {
|
||||||
|
name = name.strip_suffix(".qcow2").unwrap_or(&name).to_string();
|
||||||
|
DiskFileFormat::XzCompressedQCow2
|
||||||
|
}
|
||||||
|
"xz" => DiskFileFormat::XzCompressedRaw,
|
||||||
|
_ => anyhow::bail!("Unsupported disk extension: {ext}!"),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
file_path: file.to_path_buf(),
|
||||||
|
name,
|
||||||
|
file_size: FileSize::from_bytes(metadata.len() as usize),
|
||||||
|
format,
|
||||||
|
file_name: file
|
||||||
|
.file_name()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string(),
|
||||||
|
created: metadata
|
||||||
|
.created()?
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new empty disk
|
||||||
|
pub fn create(file: &Path, format: DiskFileFormat, size: FileSize) -> anyhow::Result<()> {
|
||||||
|
// Prepare command to create file
|
||||||
|
let res = match format {
|
||||||
|
DiskFileFormat::Raw { is_sparse } => {
|
||||||
|
let mut cmd = Command::new("/usr/bin/dd");
|
||||||
|
cmd.arg("if=/dev/zero")
|
||||||
|
.arg(format!("of={}", file.to_string_lossy()))
|
||||||
|
.arg("bs=1M");
|
||||||
|
|
||||||
|
match is_sparse {
|
||||||
|
false => cmd.arg(format!("count={}", size.as_mb())),
|
||||||
|
true => cmd.arg(format!("seek={}", size.as_mb())).arg("count=0"),
|
||||||
|
};
|
||||||
|
|
||||||
|
cmd.output()?
|
||||||
|
}
|
||||||
|
|
||||||
|
DiskFileFormat::QCow2 { virtual_size } => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.arg("create")
|
||||||
|
.arg("-f")
|
||||||
|
.arg("qcow2")
|
||||||
|
.arg(file)
|
||||||
|
.arg(format!("{}M", virtual_size.as_mb()));
|
||||||
|
|
||||||
|
cmd.output()?
|
||||||
|
}
|
||||||
|
_ => anyhow::bail!("Cannot create disk file image of this format: {format:?}!"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Execute Linux command
|
||||||
|
if !res.status.success() {
|
||||||
|
log::error!(
|
||||||
|
"Failed to create disk! stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&res.stderr),
|
||||||
|
String::from_utf8_lossy(&res.stdout)
|
||||||
|
);
|
||||||
|
return Err(DisksError::Create.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy / convert file disk image into a new destination with optionally a new file format
|
||||||
|
pub fn convert(&self, dest_file: &Path, dest_format: DiskFileFormat) -> anyhow::Result<()> {
|
||||||
|
// Create a temporary directory to perform the operation
|
||||||
|
let temp_dir = tempfile::tempdir_in(&AppConfig::get().temp_dir)?;
|
||||||
|
let temp_file = temp_dir
|
||||||
|
.path()
|
||||||
|
.join(format!("temp_file.{}", dest_format.ext()[0]));
|
||||||
|
|
||||||
|
// Prepare the conversion
|
||||||
|
let mut cmd = match (self.format, dest_format) {
|
||||||
|
// Decompress QCow2 (GZIP)
|
||||||
|
(DiskFileFormat::GzCompressedQCow2, DiskFileFormat::QCow2 { .. }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_GZIP);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--decompress")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress QCow2 (XZ)
|
||||||
|
(DiskFileFormat::XzCompressedQCow2, DiskFileFormat::QCow2 { .. }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_XZ);
|
||||||
|
cmd.arg("--stdout")
|
||||||
|
.arg("--keep")
|
||||||
|
.arg("--decompress")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress QCow2 (Gzip)
|
||||||
|
(DiskFileFormat::QCow2 { .. }, DiskFileFormat::GzCompressedQCow2) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_GZIP);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress QCow2 (Xz)
|
||||||
|
(DiskFileFormat::QCow2 { .. }, DiskFileFormat::XzCompressedQCow2) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_XZ);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert QCow2 to Raw file
|
||||||
|
(DiskFileFormat::QCow2 { .. }, DiskFileFormat::Raw { is_sparse }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.arg("convert")
|
||||||
|
.arg("-f")
|
||||||
|
.arg("qcow2")
|
||||||
|
.arg("-O")
|
||||||
|
.arg("raw")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(&temp_file);
|
||||||
|
|
||||||
|
if !is_sparse {
|
||||||
|
cmd.args(["-S", "0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clone a QCow file, using qemu-image instead of cp might improve "sparsification" of
|
||||||
|
// file
|
||||||
|
(DiskFileFormat::QCow2 { .. }, DiskFileFormat::QCow2 { .. }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.arg("convert")
|
||||||
|
.arg("-f")
|
||||||
|
.arg("qcow2")
|
||||||
|
.arg("-O")
|
||||||
|
.arg("qcow2")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(&temp_file);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert Raw to QCow2 file
|
||||||
|
(DiskFileFormat::Raw { .. }, DiskFileFormat::QCow2 { .. }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.arg("convert")
|
||||||
|
.arg("-f")
|
||||||
|
.arg("raw")
|
||||||
|
.arg("-O")
|
||||||
|
.arg("qcow2")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(&temp_file);
|
||||||
|
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render raw file non sparse
|
||||||
|
(DiskFileFormat::Raw { is_sparse: true }, DiskFileFormat::Raw { is_sparse: false }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_COPY);
|
||||||
|
cmd.arg("--sparse=never")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(&temp_file);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render raw file sparse
|
||||||
|
(DiskFileFormat::Raw { is_sparse: false }, DiskFileFormat::Raw { is_sparse: true }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_DD);
|
||||||
|
cmd.arg("conv=sparse")
|
||||||
|
.arg(format!("if={}", self.file_path.display()))
|
||||||
|
.arg(format!("of={}", temp_file.display()));
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress Raw (Gz)
|
||||||
|
(DiskFileFormat::Raw { .. }, DiskFileFormat::GzCompressedRaw) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_GZIP);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress Raw (Xz)
|
||||||
|
(DiskFileFormat::Raw { .. }, DiskFileFormat::XzCompressedRaw) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_XZ);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress Raw (Gz) to not sparse file
|
||||||
|
(DiskFileFormat::GzCompressedRaw, DiskFileFormat::Raw { is_sparse: false }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_GZIP);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--decompress")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
// Decompress Raw (Xz) to not sparse file
|
||||||
|
(DiskFileFormat::XzCompressedRaw, DiskFileFormat::Raw { is_sparse: false }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_XZ);
|
||||||
|
cmd.arg("--keep")
|
||||||
|
.arg("--decompress")
|
||||||
|
.arg("--to-stdout")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.stdout(File::create(&temp_file)?);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress Raw (Gz) to sparse file
|
||||||
|
// https://benou.fr/www/ben/decompressing-sparse-files.html
|
||||||
|
(DiskFileFormat::GzCompressedRaw, DiskFileFormat::Raw { is_sparse: true }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_BASH);
|
||||||
|
cmd.arg("-c").arg(format!(
|
||||||
|
"{} --decompress --to-stdout {} | {} conv=sparse of={}",
|
||||||
|
constants::PROGRAM_GZIP,
|
||||||
|
self.file_path.display(),
|
||||||
|
constants::PROGRAM_DD,
|
||||||
|
temp_file.display()
|
||||||
|
));
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress Raw (XZ) to sparse file
|
||||||
|
// https://benou.fr/www/ben/decompressing-sparse-files.html
|
||||||
|
(DiskFileFormat::XzCompressedRaw, DiskFileFormat::Raw { is_sparse: true }) => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_BASH);
|
||||||
|
cmd.arg("-c").arg(format!(
|
||||||
|
"{} --decompress --to-stdout {} | {} conv=sparse of={}",
|
||||||
|
constants::PROGRAM_XZ,
|
||||||
|
self.file_path.display(),
|
||||||
|
constants::PROGRAM_DD,
|
||||||
|
temp_file.display()
|
||||||
|
));
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dumb copy of file
|
||||||
|
(a, b) if a == b => {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_COPY);
|
||||||
|
cmd.arg("--sparse=auto")
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(&temp_file);
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// By default, conversion is unsupported
|
||||||
|
(src, dest) => {
|
||||||
|
return Err(DisksError::Convert(format!(
|
||||||
|
"Conversion from {src:?} to {dest:?} is not supported!"
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Execute the conversion
|
||||||
|
let command_s = format!(
|
||||||
|
"{} {}",
|
||||||
|
cmd.get_program().display(),
|
||||||
|
cmd.get_args()
|
||||||
|
.map(|a| format!("'{}'", a.display()))
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(" ")
|
||||||
|
);
|
||||||
|
let cmd_output = cmd.output()?;
|
||||||
|
if !cmd_output.status.success() {
|
||||||
|
return Err(DisksError::Convert(format!(
|
||||||
|
"Command failed:\n{command_s}\nStatus: {}\nstdout: {}\nstderr: {}",
|
||||||
|
cmd_output.status,
|
||||||
|
String::from_utf8_lossy(&cmd_output.stdout),
|
||||||
|
String::from_utf8_lossy(&cmd_output.stderr)
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the file was created
|
||||||
|
if !temp_file.is_file() {
|
||||||
|
return Err(DisksError::Convert(
|
||||||
|
"Temporary was not created after execution of command!".to_string(),
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move the file to its final location
|
||||||
|
std::fs::rename(temp_file, dest_file)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get disk virtual size, if available
|
||||||
|
pub fn virtual_size(&self) -> Option<FileSize> {
|
||||||
|
match self.format {
|
||||||
|
DiskFileFormat::Raw { .. } => Some(self.file_size),
|
||||||
|
DiskFileFormat::QCow2 { virtual_size } => Some(virtual_size),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resize disk
|
||||||
|
pub fn resize(&self, new_size: FileSize) -> anyhow::Result<()> {
|
||||||
|
if new_size <= self.virtual_size().unwrap_or(new_size) {
|
||||||
|
anyhow::bail!("Shrinking disk image file is not supported!");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.arg("resize")
|
||||||
|
.arg("-f")
|
||||||
|
.arg(match self.format {
|
||||||
|
DiskFileFormat::QCow2 { .. } => "qcow2",
|
||||||
|
DiskFileFormat::Raw { .. } => "raw",
|
||||||
|
f => anyhow::bail!("Unsupported disk format for resize: {f:?}"),
|
||||||
|
})
|
||||||
|
.arg(&self.file_path)
|
||||||
|
.arg(new_size.as_bytes().to_string());
|
||||||
|
|
||||||
|
let output = cmd.output()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"{} info failed, status: {}, stderr: {}",
|
||||||
|
constants::PROGRAM_QEMU_IMAGE,
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct QCowInfoOutput {
|
||||||
|
#[serde(rename = "virtual-size")]
|
||||||
|
virtual_size: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get QCow2 virtual size
|
||||||
|
fn qcow_virt_size(path: &Path) -> anyhow::Result<FileSize> {
|
||||||
|
// Run qemu-img
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_QEMU_IMAGE);
|
||||||
|
cmd.args([
|
||||||
|
"info",
|
||||||
|
path.to_str().unwrap_or(""),
|
||||||
|
"--output",
|
||||||
|
"json",
|
||||||
|
"--force-share",
|
||||||
|
]);
|
||||||
|
let output = cmd.output()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"{} info failed, status: {}, stderr: {}",
|
||||||
|
constants::PROGRAM_QEMU_IMAGE,
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let res_json = String::from_utf8(output.stdout)?;
|
||||||
|
|
||||||
|
// Decode JSON
|
||||||
|
let decoded: QCowInfoOutput = serde_json::from_str(&res_json)?;
|
||||||
|
Ok(FileSize::from_bytes(decoded.virtual_size))
|
||||||
|
}
|
91
virtweb_backend/src/utils/file_size_utils.rs
Normal file
91
virtweb_backend/src/utils/file_size_utils.rs
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
use std::ops::Mul;
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum FilesSizeUtilsError {
|
||||||
|
#[error("UnitConvertError: {0}")]
|
||||||
|
UnitConvert(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Holds a data size, convertible in any form
|
||||||
|
#[derive(
|
||||||
|
serde::Serialize,
|
||||||
|
serde::Deserialize,
|
||||||
|
Copy,
|
||||||
|
Clone,
|
||||||
|
Debug,
|
||||||
|
Eq,
|
||||||
|
PartialEq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
Default,
|
||||||
|
)]
|
||||||
|
pub struct FileSize(usize);
|
||||||
|
|
||||||
|
impl FileSize {
|
||||||
|
pub const fn from_bytes(size: usize) -> Self {
|
||||||
|
Self(size)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn from_mb(mb: usize) -> Self {
|
||||||
|
Self(mb * 1000 * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn from_gb(gb: usize) -> Self {
|
||||||
|
Self(gb * 1000 * 1000 * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert size unit to MB
|
||||||
|
pub fn from_size_unit(unit: &str, value: usize) -> anyhow::Result<Self> {
|
||||||
|
let fact = match unit {
|
||||||
|
"bytes" | "b" => 1f64,
|
||||||
|
"KB" => 1000f64,
|
||||||
|
"MB" => 1000f64 * 1000f64,
|
||||||
|
"GB" => 1000f64 * 1000f64 * 1000f64,
|
||||||
|
"TB" => 1000f64 * 1000f64 * 1000f64 * 1000f64,
|
||||||
|
|
||||||
|
"k" | "KiB" => 1024f64,
|
||||||
|
"M" | "MiB" => 1024f64 * 1024f64,
|
||||||
|
"G" | "GiB" => 1024f64 * 1024f64 * 1024f64,
|
||||||
|
"T" | "TiB" => 1024f64 * 1024f64 * 1024f64 * 1024f64,
|
||||||
|
|
||||||
|
_ => {
|
||||||
|
return Err(
|
||||||
|
FilesSizeUtilsError::UnitConvert(format!("Unknown size unit: {unit}")).into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self((value as f64).mul(fact).ceil() as usize))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get file size as bytes
|
||||||
|
pub fn as_bytes(&self) -> usize {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get file size as megabytes
|
||||||
|
pub fn as_mb(&self) -> usize {
|
||||||
|
self.0 / (1000 * 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::utils::file_size_utils::FileSize;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn convert_units_mb() {
|
||||||
|
assert_eq!(FileSize::from_size_unit("MB", 1).unwrap().as_mb(), 1);
|
||||||
|
assert_eq!(FileSize::from_size_unit("MB", 1000).unwrap().as_mb(), 1000);
|
||||||
|
assert_eq!(
|
||||||
|
FileSize::from_size_unit("GB", 1000).unwrap().as_mb(),
|
||||||
|
1000 * 1000
|
||||||
|
);
|
||||||
|
assert_eq!(FileSize::from_size_unit("GB", 1).unwrap().as_mb(), 1000);
|
||||||
|
assert_eq!(FileSize::from_size_unit("GiB", 3).unwrap().as_mb(), 3221);
|
||||||
|
assert_eq!(
|
||||||
|
FileSize::from_size_unit("KiB", 488281).unwrap().as_mb(),
|
||||||
|
499
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
@ -1,13 +1,6 @@
|
|||||||
use std::ops::{Div, Mul};
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
enum FilesUtilsError {
|
|
||||||
#[error("UnitConvertError: {0}")]
|
|
||||||
UnitConvert(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
const INVALID_CHARS: [&str; 19] = [
|
const INVALID_CHARS: [&str; 19] = [
|
||||||
"@", "\\", "/", ":", ",", "<", ">", "%", "'", "\"", "?", "{", "}", "$", "*", "|", ";", "=",
|
"@", "\\", "/", ":", ",", "<", ">", "%", "'", "\"", "?", "{", "}", "$", "*", "|", ";", "=",
|
||||||
"\t",
|
"\t",
|
||||||
@ -35,31 +28,9 @@ pub fn set_file_permission<P: AsRef<Path>>(path: P, mode: u32) -> anyhow::Result
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert size unit to MB
|
|
||||||
pub fn convert_size_unit_to_mb(unit: &str, value: usize) -> anyhow::Result<usize> {
|
|
||||||
let fact = match unit {
|
|
||||||
"bytes" | "b" => 1f64,
|
|
||||||
"KB" => 1000f64,
|
|
||||||
"MB" => 1000f64 * 1000f64,
|
|
||||||
"GB" => 1000f64 * 1000f64 * 1000f64,
|
|
||||||
"TB" => 1000f64 * 1000f64 * 1000f64 * 1000f64,
|
|
||||||
|
|
||||||
"k" | "KiB" => 1024f64,
|
|
||||||
"M" | "MiB" => 1024f64 * 1024f64,
|
|
||||||
"G" | "GiB" => 1024f64 * 1024f64 * 1024f64,
|
|
||||||
"T" | "TiB" => 1024f64 * 1024f64 * 1024f64 * 1024f64,
|
|
||||||
|
|
||||||
_ => {
|
|
||||||
return Err(FilesUtilsError::UnitConvert(format!("Unknown size unit: {unit}")).into());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok((value as f64).mul(fact.div((1000 * 1000) as f64)).ceil() as usize)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use crate::utils::files_utils::{check_file_name, convert_size_unit_to_mb};
|
use crate::utils::files_utils::check_file_name;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn empty_file_name() {
|
fn empty_file_name() {
|
||||||
@ -85,14 +56,4 @@ mod test {
|
|||||||
fn valid_file_name() {
|
fn valid_file_name() {
|
||||||
assert!(check_file_name("test.iso"));
|
assert!(check_file_name("test.iso"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn convert_units_mb() {
|
|
||||||
assert_eq!(convert_size_unit_to_mb("MB", 1).unwrap(), 1);
|
|
||||||
assert_eq!(convert_size_unit_to_mb("MB", 1000).unwrap(), 1000);
|
|
||||||
assert_eq!(convert_size_unit_to_mb("GB", 1000).unwrap(), 1000 * 1000);
|
|
||||||
assert_eq!(convert_size_unit_to_mb("GB", 1).unwrap(), 1000);
|
|
||||||
assert_eq!(convert_size_unit_to_mb("GiB", 3).unwrap(), 3222);
|
|
||||||
assert_eq!(convert_size_unit_to_mb("KiB", 488281).unwrap(), 500);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
pub mod disks_utils;
|
pub mod cloud_init_utils;
|
||||||
|
pub mod exec_utils;
|
||||||
|
pub mod file_disks_utils;
|
||||||
|
pub mod file_size_utils;
|
||||||
pub mod files_utils;
|
pub mod files_utils;
|
||||||
pub mod net_utils;
|
pub mod net_utils;
|
||||||
pub mod rand_utils;
|
pub mod rand_utils;
|
||||||
pub mod time_utils;
|
pub mod time_utils;
|
||||||
pub mod url_utils;
|
pub mod url_utils;
|
||||||
|
pub mod vm_file_disks_utils;
|
||||||
|
@ -1,5 +1,10 @@
|
|||||||
|
use crate::constants;
|
||||||
|
use nix::sys::socket::{AddressFamily, SockaddrLike};
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
use std::process::Command;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
use sysinfo::Networks;
|
||||||
|
|
||||||
pub fn extract_ipv4(ip: IpAddr) -> Ipv4Addr {
|
pub fn extract_ipv4(ip: IpAddr) -> Ipv4Addr {
|
||||||
match ip {
|
match ip {
|
||||||
@ -32,7 +37,7 @@ pub fn is_ipv4_mask_valid(mask: u8) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_ipv6_mask_valid(mask: u8) -> bool {
|
pub fn is_ipv6_mask_valid(mask: u8) -> bool {
|
||||||
mask <= 64
|
mask <= 128
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_mask_valid(ipv: usize, mask: u8) -> bool {
|
pub fn is_mask_valid(ipv: usize, mask: u8) -> bool {
|
||||||
@ -47,10 +52,122 @@ pub fn is_mac_address_valid<D: AsRef<str>>(mac: D) -> bool {
|
|||||||
lazy_regex::regex!("^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$").is_match(mac.as_ref())
|
lazy_regex::regex!("^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$").is_match(mac.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_net_interface_name_valid<D: AsRef<str>>(int: D) -> bool {
|
||||||
|
lazy_regex::regex!("^[a-zA-Z0-9]+$").is_match(int.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of available network interfaces
|
||||||
|
pub fn net_list() -> Vec<String> {
|
||||||
|
let mut networks = Networks::new();
|
||||||
|
networks.refresh(true);
|
||||||
|
|
||||||
|
networks
|
||||||
|
.list()
|
||||||
|
.iter()
|
||||||
|
.map(|n| n.0.to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of available network interfaces associated with their IP address
|
||||||
|
pub fn net_list_and_ips() -> anyhow::Result<HashMap<String, Vec<IpAddr>>> {
|
||||||
|
let addrs = nix::ifaddrs::getifaddrs()?;
|
||||||
|
|
||||||
|
let mut res = HashMap::new();
|
||||||
|
|
||||||
|
for ifaddr in addrs {
|
||||||
|
let address = match ifaddr.address {
|
||||||
|
Some(address) => address,
|
||||||
|
None => {
|
||||||
|
log::debug!(
|
||||||
|
"Interface {} has an unsupported address family",
|
||||||
|
ifaddr.interface_name
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let addr_str = match address.family() {
|
||||||
|
Some(AddressFamily::Inet) => {
|
||||||
|
let address = address.to_string();
|
||||||
|
address
|
||||||
|
.split_once(':')
|
||||||
|
.map(|a| a.0)
|
||||||
|
.unwrap_or(&address)
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
Some(AddressFamily::Inet6) => {
|
||||||
|
let address = address.to_string();
|
||||||
|
let address = address
|
||||||
|
.split_once(']')
|
||||||
|
.map(|a| a.0)
|
||||||
|
.unwrap_or(&address)
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let address = address
|
||||||
|
.split_once('%')
|
||||||
|
.map(|a| a.0)
|
||||||
|
.unwrap_or(&address)
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
address.strip_prefix('[').unwrap_or(&address).to_string()
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log::debug!(
|
||||||
|
"Interface {} has an unsupported address family {:?}",
|
||||||
|
ifaddr.interface_name,
|
||||||
|
address.family()
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"Process ip {addr_str} for interface {}",
|
||||||
|
ifaddr.interface_name
|
||||||
|
);
|
||||||
|
|
||||||
|
let ip = IpAddr::from_str(&addr_str)?;
|
||||||
|
|
||||||
|
if !res.contains_key(&ifaddr.interface_name) {
|
||||||
|
res.insert(ifaddr.interface_name.to_string(), Vec::with_capacity(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
res.get_mut(&ifaddr.interface_name).unwrap().push(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct IPBridgeInfo {
|
||||||
|
ifname: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of bridge interfaces
|
||||||
|
pub fn bridges_list() -> anyhow::Result<Vec<String>> {
|
||||||
|
let mut cmd = Command::new(constants::PROGRAM_IP);
|
||||||
|
cmd.args(["-json", "link", "show", "type", "bridge"]);
|
||||||
|
let output = cmd.output()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"{} failed, status: {}, stderr: {}",
|
||||||
|
constants::PROGRAM_IP,
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse JSON result
|
||||||
|
let res: Vec<IPBridgeInfo> = serde_json::from_str(&String::from_utf8_lossy(&output.stdout))?;
|
||||||
|
|
||||||
|
Ok(res.iter().map(|ip| ip.ifname.clone()).collect())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::utils::net_utils::{
|
use crate::utils::net_utils::{
|
||||||
is_ipv4_address_valid, is_ipv6_address_valid, is_mac_address_valid, is_mask_valid,
|
is_ipv4_address_valid, is_ipv6_address_valid, is_mac_address_valid, is_mask_valid,
|
||||||
|
is_net_interface_name_valid,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -79,6 +196,7 @@ mod tests {
|
|||||||
assert!(is_ipv6_address_valid("fe80::"));
|
assert!(is_ipv6_address_valid("fe80::"));
|
||||||
assert!(is_ipv6_address_valid("fe80:dd::"));
|
assert!(is_ipv6_address_valid("fe80:dd::"));
|
||||||
assert!(is_ipv6_address_valid("00:00:00:00:00::"));
|
assert!(is_ipv6_address_valid("00:00:00:00:00::"));
|
||||||
|
assert!(is_ipv6_address_valid("0:0:0:0:0:0:0:0"));
|
||||||
|
|
||||||
assert!(!is_ipv6_address_valid("tata"));
|
assert!(!is_ipv6_address_valid("tata"));
|
||||||
assert!(!is_ipv6_address_valid("2.56.58.156"));
|
assert!(!is_ipv6_address_valid("2.56.58.156"));
|
||||||
@ -93,6 +211,17 @@ mod tests {
|
|||||||
assert!(is_mask_valid(6, 34));
|
assert!(is_mask_valid(6, 34));
|
||||||
|
|
||||||
assert!(!is_mask_valid(4, 34));
|
assert!(!is_mask_valid(4, 34));
|
||||||
assert!(!is_mask_valid(6, 69));
|
assert!(is_mask_valid(6, 69));
|
||||||
|
assert!(is_mask_valid(6, 128));
|
||||||
|
assert!(!is_mask_valid(6, 129));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_net_interface_name_valid() {
|
||||||
|
assert!(is_net_interface_name_valid("eth0"));
|
||||||
|
assert!(is_net_interface_name_valid("enp0s25"));
|
||||||
|
|
||||||
|
assert!(!is_net_interface_name_valid("enp0s25 "));
|
||||||
|
assert!(!is_net_interface_name_valid("@enp0s25 "));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,6 @@
|
|||||||
use rand::distributions::Alphanumeric;
|
use rand::distr::{Alphanumeric, SampleString};
|
||||||
use rand::Rng;
|
|
||||||
|
|
||||||
/// Generate a random string
|
/// Generate a random string
|
||||||
pub fn rand_str(len: usize) -> String {
|
pub fn rand_str(len: usize) -> String {
|
||||||
let s: String = rand::thread_rng()
|
Alphanumeric.sample_string(&mut rand::rng(), len)
|
||||||
.sample_iter(&Alphanumeric)
|
|
||||||
.take(len)
|
|
||||||
.map(char::from)
|
|
||||||
.collect();
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
use chrono::Datelike;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
/// Get the current time since epoch
|
/// Get the current time since epoch
|
||||||
@ -13,3 +14,15 @@ pub fn time() -> u64 {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.as_secs()
|
.as_secs()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Format given UNIX time in a simple format
|
||||||
|
pub fn format_date(time: i64) -> anyhow::Result<String> {
|
||||||
|
let date = chrono::DateTime::from_timestamp(time, 0).ok_or(anyhow::anyhow!("invalid date"))?;
|
||||||
|
|
||||||
|
Ok(format!(
|
||||||
|
"{:0>2}/{:0>2}/{}",
|
||||||
|
date.day(),
|
||||||
|
date.month(),
|
||||||
|
date.year()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
190
virtweb_backend/src/utils/vm_file_disks_utils.rs
Normal file
190
virtweb_backend/src/utils/vm_file_disks_utils.rs
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::utils::file_disks_utils::{DiskFileFormat, DiskFileInfo};
|
||||||
|
use crate::utils::file_size_utils::FileSize;
|
||||||
|
use crate::utils::files_utils;
|
||||||
|
use lazy_regex::regex;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum VMDisksError {
|
||||||
|
#[error("DiskConfigError: {0}")]
|
||||||
|
Config(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum VMDiskBus {
|
||||||
|
Virtio,
|
||||||
|
SATA,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disk allocation type
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(tag = "format")]
|
||||||
|
pub enum VMDiskFormat {
|
||||||
|
Raw {
|
||||||
|
/// Is raw file a sparse file?
|
||||||
|
is_sparse: bool,
|
||||||
|
},
|
||||||
|
QCow2,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct VMFileDisk {
|
||||||
|
/// Disk name
|
||||||
|
pub name: String,
|
||||||
|
/// Disk size, in bytes
|
||||||
|
pub size: FileSize,
|
||||||
|
/// Disk bus
|
||||||
|
pub bus: VMDiskBus,
|
||||||
|
/// Disk format
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub format: VMDiskFormat,
|
||||||
|
/// When creating a new disk, specify the disk image template to use
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub from_image: Option<String>,
|
||||||
|
/// Set this variable to true to resize disk image
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub resize: Option<bool>,
|
||||||
|
/// Set this variable to true to delete the disk
|
||||||
|
pub delete: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VMFileDisk {
|
||||||
|
pub fn load_from_file(path: &str, bus: &str) -> anyhow::Result<Self> {
|
||||||
|
let file = Path::new(path);
|
||||||
|
|
||||||
|
let info = DiskFileInfo::load_file(file)?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
name: info.name,
|
||||||
|
|
||||||
|
// Get only the virtual size of the file
|
||||||
|
size: match info.format {
|
||||||
|
DiskFileFormat::Raw { .. } => info.file_size,
|
||||||
|
DiskFileFormat::QCow2 { virtual_size } => virtual_size,
|
||||||
|
_ => anyhow::bail!("Unsupported image format: {:?}", info.format),
|
||||||
|
},
|
||||||
|
|
||||||
|
format: match info.format {
|
||||||
|
DiskFileFormat::Raw { is_sparse } => VMDiskFormat::Raw { is_sparse },
|
||||||
|
DiskFileFormat::QCow2 { .. } => VMDiskFormat::QCow2,
|
||||||
|
_ => anyhow::bail!("Unsupported image format: {:?}", info.format),
|
||||||
|
},
|
||||||
|
|
||||||
|
bus: match bus {
|
||||||
|
"virtio" => VMDiskBus::Virtio,
|
||||||
|
"sata" => VMDiskBus::SATA,
|
||||||
|
_ => anyhow::bail!("Unsupported disk bus type: {bus}"),
|
||||||
|
},
|
||||||
|
|
||||||
|
delete: false,
|
||||||
|
from_image: None,
|
||||||
|
resize: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_config(&self) -> anyhow::Result<()> {
|
||||||
|
if constants::DISK_NAME_MIN_LEN > self.name.len()
|
||||||
|
|| constants::DISK_NAME_MAX_LEN < self.name.len()
|
||||||
|
{
|
||||||
|
return Err(VMDisksError::Config("Disk name length is invalid").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
||||||
|
return Err(VMDisksError::Config("Disk name contains invalid characters!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check disk size
|
||||||
|
if !(constants::DISK_SIZE_MIN..=constants::DISK_SIZE_MAX).contains(&self.size) {
|
||||||
|
return Err(VMDisksError::Config("Disk size is invalid!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check specified disk image template
|
||||||
|
if let Some(disk_image) = &self.from_image {
|
||||||
|
if !files_utils::check_file_name(disk_image) {
|
||||||
|
return Err(VMDisksError::Config("Disk image template name is not valid!").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !AppConfig::get().disk_images_file_path(disk_image).is_file() {
|
||||||
|
return Err(
|
||||||
|
VMDisksError::Config("Specified disk image file does not exist!").into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get disk path on file system
|
||||||
|
pub fn disk_path(&self, id: XMLUuid) -> PathBuf {
|
||||||
|
let domain_dir = AppConfig::get().vm_storage_path(id);
|
||||||
|
let file_name = match self.format {
|
||||||
|
VMDiskFormat::Raw { .. } => self.name.to_string(),
|
||||||
|
VMDiskFormat::QCow2 => format!("{}.qcow2", self.name),
|
||||||
|
};
|
||||||
|
domain_dir.join(&file_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply disk configuration
|
||||||
|
pub fn apply_config(&self, id: XMLUuid) -> anyhow::Result<()> {
|
||||||
|
self.check_config()?;
|
||||||
|
|
||||||
|
let file = self.disk_path(id);
|
||||||
|
files_utils::create_directory_if_missing(file.parent().unwrap())?;
|
||||||
|
|
||||||
|
// Delete file if requested
|
||||||
|
if self.delete {
|
||||||
|
if !file.exists() {
|
||||||
|
log::debug!("File {file:?} does not exists, so it was not deleted");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!("Deleting {file:?}");
|
||||||
|
std::fs::remove_file(file)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if file.exists() {
|
||||||
|
log::debug!("File {file:?} does not exists, so it was not touched");
|
||||||
|
}
|
||||||
|
// Create disk if required
|
||||||
|
else {
|
||||||
|
// Determine file format
|
||||||
|
let format = match self.format {
|
||||||
|
VMDiskFormat::Raw { is_sparse } => DiskFileFormat::Raw { is_sparse },
|
||||||
|
VMDiskFormat::QCow2 => DiskFileFormat::QCow2 {
|
||||||
|
virtual_size: self.size,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create / Restore disk file
|
||||||
|
match &self.from_image {
|
||||||
|
// Create disk file
|
||||||
|
None => {
|
||||||
|
DiskFileInfo::create(&file, format, self.size)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore disk image template
|
||||||
|
Some(disk_img) => {
|
||||||
|
let src_file =
|
||||||
|
DiskFileInfo::load_file(&AppConfig::get().disk_images_file_path(disk_img))?;
|
||||||
|
src_file.convert(&file, format)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resize disk file if requested
|
||||||
|
if self.resize == Some(true) {
|
||||||
|
let disk = DiskFileInfo::load_file(&file)?;
|
||||||
|
|
||||||
|
// Can only increase disk size
|
||||||
|
if let Err(e) = disk.resize(self.size) {
|
||||||
|
log::error!("Failed to resize disk file {}: {e:?}", self.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
47
virtweb_docs/BRIDGE.md
Normal file
47
virtweb_docs/BRIDGE.md
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
# Bridges
|
||||||
|
|
||||||
|
Bridges can be used to connect virtual machines to networks.
|
||||||
|
|
||||||
|
## Setup Bridge on Ubuntu
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install bridge-utils
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Adapt your netplan configuration to set the following:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
network:
|
||||||
|
version: 2
|
||||||
|
renderer: networkd
|
||||||
|
ethernets:
|
||||||
|
enp2s0:
|
||||||
|
dhcp4: no
|
||||||
|
bridges:
|
||||||
|
br0: # Bridge name
|
||||||
|
dhcp4: yes
|
||||||
|
interfaces:
|
||||||
|
- enp2s0 # Set to your interface
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
3. Apply netplan configuration:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo netplan apply
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
4. Get the state and the list of bridges in the system:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo brctl show
|
||||||
|
|
||||||
|
# Or
|
||||||
|
ip link show type bridge
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
[How to Configure Network Bridge in Ubuntu](https://www.tecmint.com/create-network-bridge-in-ubuntu/)
|
11
virtweb_docs/REFERENCE.md
Normal file
11
virtweb_docs/REFERENCE.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
## References
|
||||||
|
|
||||||
|
### LibVirt XML documentation
|
||||||
|
* Online: https://libvirt.org/format.html
|
||||||
|
|
||||||
|
* Offline with Ubuntu:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install libvirt-doc
|
||||||
|
firefox /usr/share/doc/libvirt-doc/html/index.html
|
||||||
|
```
|
@ -5,13 +5,13 @@
|
|||||||
sudo apt install libvirt-dev
|
sudo apt install libvirt-dev
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Libvirt must also be installed:
|
2. Libvirt and cloud image utilities must also be installed:
|
||||||
```bash
|
```bash
|
||||||
sudo apt install qemu-kvm libvirt-daemon-system
|
sudo apt install qemu-kvm libvirt-daemon-system cloud-image-utils
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Allow the current user to manage VMs:
|
3. Allow the current user to manage VMs:
|
||||||
```
|
```bash
|
||||||
sudo adduser $USER libvirt
|
sudo adduser $USER libvirt
|
||||||
sudo adduser $USER kvm
|
sudo adduser $USER kvm
|
||||||
```
|
```
|
||||||
@ -20,4 +20,27 @@ sudo adduser $USER kvm
|
|||||||
|
|
||||||
4. Install required developpment tools:
|
4. Install required developpment tools:
|
||||||
* Rust: https://www.rust-lang.org/learn/get-started
|
* Rust: https://www.rust-lang.org/learn/get-started
|
||||||
* NodeJS: https://nodejs.org/en/download/current
|
* NodeJS: https://nodejs.org/en/download/current
|
||||||
|
|
||||||
|
|
||||||
|
5. Run sample OpenID service
|
||||||
|
```bash
|
||||||
|
cd virtweb_backend
|
||||||
|
docker compose up
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Run the backend:
|
||||||
|
```bash
|
||||||
|
sudo mkdir /var/virtweb
|
||||||
|
sudo chown $USER:$USER /var/virtweb
|
||||||
|
cd virtweb_backend
|
||||||
|
cargo fmt && cargo clippy && cargo run -- -s /var/virtweb --hypervisor-uri "qemu:///system" --website-origin "http://localhost:5173"
|
||||||
|
```
|
||||||
|
|
||||||
|
7. Run the frontend
|
||||||
|
```bash
|
||||||
|
cd virtweb_frontend
|
||||||
|
npm run start
|
||||||
|
```
|
||||||
|
|
||||||
|
Have fun with your development!
|
@ -9,13 +9,13 @@ make
|
|||||||
|
|
||||||
The release file will be available in `virtweb_backend/target/release/virtweb_backend`.
|
The release file will be available in `virtweb_backend/target/release/virtweb_backend`.
|
||||||
|
|
||||||
This is the only artifcat that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
|
This is the only artifact that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
|
||||||
|
|
||||||
## Install requirements
|
## Install requirements
|
||||||
In order to work properly, VirtWeb relies on `libvirt`, `qemu` and `kvm`:
|
In order to work properly, VirtWeb relies on `libvirt`, `qemu`, `kvm` and `cloud-localds`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install qemu-kvm libvirt-daemon-system libvirt0 libvirt-clients libvirt-daemon bridge-utils
|
sudo apt install qemu-kvm libvirt-daemon-system libvirt0 libvirt-clients libvirt-daemon bridge-utils cloud-image-utils
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dedicated user
|
## Dedicated user
|
||||||
@ -61,7 +61,7 @@ STORAGE=/home/virtweb/storage
|
|||||||
HYPERVISOR_URI=qemu:///system
|
HYPERVISOR_URI=qemu:///system
|
||||||
```
|
```
|
||||||
|
|
||||||
> Note: `HYPERVISOR_URI=qemu:///system` is used to sepcify that we want to use the main hypervisor.
|
> Note: `HYPERVISOR_URI=qemu:///system` is used to specify that we want to use the main hypervisor.
|
||||||
|
|
||||||
## Register Virtweb service
|
## Register Virtweb service
|
||||||
Before registering service, check that the configuration works correctly:
|
Before registering service, check that the configuration works correctly:
|
||||||
@ -102,7 +102,8 @@ sudo systemctl start virtweb
|
|||||||
|
|
||||||
You should now be able to create VMs!
|
You should now be able to create VMs!
|
||||||
|
|
||||||
### Manual port forwarding without a LibVirt HOOK
|
|
||||||
|
## Configure port forwarding
|
||||||
* Allow ip forwarding in the kernel: edit `/etc/sysctl.conf` and uncomment the following line:
|
* Allow ip forwarding in the kernel: edit `/etc/sysctl.conf` and uncomment the following line:
|
||||||
|
|
||||||
```
|
```
|
||||||
@ -115,85 +116,34 @@ net.ipv4.ip_forward=1
|
|||||||
sudo sysctl -p /etc/sysctl.conf
|
sudo sysctl -p /etc/sysctl.conf
|
||||||
```
|
```
|
||||||
|
|
||||||
* Create the following IPTables rules:
|
* Configure apparmore service. Create or update a file named `/etc/apparmor.d/local/usr.sbin.libvirtd` with the following content:
|
||||||
|
|
||||||
```
|
```
|
||||||
UP_DEV=$(ip a | grep "192.168.1." -B 2 | head -n 1 | cut -d ':' -f 2 |
|
/usr/local/bin/virtweb_backend ux,
|
||||||
tr -d ' ')
|
|
||||||
LOCAL_DEV=$(ip a | grep "192.168.25." -B 2 | head -n 1 | cut -d ':' -f 2 | tr -d ' ')
|
|
||||||
echo "$UP_DEV -> $LOCAL_DEV"
|
|
||||||
|
|
||||||
GUEST_IP=192.168.25.189
|
|
||||||
HOST_PORT=8085
|
|
||||||
GUEST_PORT=8085
|
|
||||||
|
|
||||||
# connections from outside
|
|
||||||
sudo iptables -I FORWARD -o $LOCAL_DEV -d $GUEST_IP -j ACCEPT
|
|
||||||
sudo iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
|
||||||
```
|
```
|
||||||
|
|
||||||
* Theses rules can be persisted using `iptables-save` then, or using a libvirt hook.
|
* Update Apparmor configuration:
|
||||||
|
|
||||||
|
```bash
|
||||||
### Manual port forwarding with a LibVirt HOOK
|
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.libvirtd
|
||||||
* Allow ip forwarding in the kernel: edit `/etc/sysctl.conf` and uncomment the following line:
|
|
||||||
|
|
||||||
```
|
|
||||||
net.ipv4.ip_forward=1
|
|
||||||
```
|
```
|
||||||
|
|
||||||
* To reload `sysctl` without reboot:
|
* Create VirtWeb hook. Set the following content inside `/etc/libvirt/hooks/network`:
|
||||||
|
|
||||||
```
|
|
||||||
sudo sysctl -p /etc/sysctl.conf
|
|
||||||
```
|
|
||||||
|
|
||||||
* Get the following information, using the web ui or `virsh`:
|
|
||||||
* The name of the target guest
|
|
||||||
* The IP and port of the guest who will receive the connection
|
|
||||||
* The port of the host that will be forwarded to the guest
|
|
||||||
|
|
||||||
* Stop the guest if its running, either using `virsh` or from the web ui
|
|
||||||
|
|
||||||
* Create or append the following content to the file `/etc/libvirt/hooks/qemu`:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
NAT_MODE=1 /usr/local/bin/virtweb_backend --storage /home/virtweb/storage --network-name "$1" --operation "$2" --sub-operation "$3"
|
||||||
# IMPORTANT: Change the "VM NAME" string to match your actual VM Name.
|
|
||||||
# In order to create rules to other VMs, just duplicate the below block and configure
|
|
||||||
# it accordingly.
|
|
||||||
if [ "${1}" = "VM NAME" ]; then
|
|
||||||
|
|
||||||
# Update the following variables to fit your setup
|
|
||||||
GUEST_IP=
|
|
||||||
GUEST_PORT=
|
|
||||||
HOST_PORT=
|
|
||||||
|
|
||||||
if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
|
|
||||||
/sbin/iptables -D FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT
|
|
||||||
/sbin/iptables -t nat -D PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
|
||||||
fi
|
|
||||||
if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
|
|
||||||
/sbin/iptables -I FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT
|
|
||||||
/sbin/iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
```
|
```
|
||||||
|
|
||||||
* Make the hook executable:
|
* Make the script executable:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo chmod +x /etc/libvirt/hooks/qemu
|
sudo chmod +x /etc/libvirt/hooks/network
|
||||||
```
|
```
|
||||||
|
|
||||||
* Restart the `libvirtd` service:
|
* Restart `libvirtd` and `VirtWeb`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl restart libvirtd.service
|
sudo systemctl restart libvirtd
|
||||||
```
|
sudo systemctl restart virtweb
|
||||||
|
```
|
||||||
* Start the guest
|
|
||||||
|
|
||||||
|
|
||||||
> Note: this guide is based on https://wiki.libvirt.org/Networking.html
|
|
2
virtweb_frontend/.gitignore
vendored
2
virtweb_frontend/.gitignore
vendored
@ -1,5 +1,7 @@
|
|||||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
dist/
|
||||||
|
|
||||||
# dependencies
|
# dependencies
|
||||||
/node_modules
|
/node_modules
|
||||||
/.pnp
|
/.pnp
|
||||||
|
@ -1,46 +1,12 @@
|
|||||||
# Getting Started with Create React App
|
# Virtweb frontend
|
||||||
|
Built with Vite + React + TypeScript
|
||||||
|
|
||||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
## Get dependencies
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
## Available Scripts
|
# Run for developpment
|
||||||
|
```bash
|
||||||
In the project directory, you can run:
|
npm run dev
|
||||||
|
```
|
||||||
### `npm start`
|
|
||||||
|
|
||||||
Runs the app in the development mode.\
|
|
||||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
|
||||||
|
|
||||||
The page will reload if you make edits.\
|
|
||||||
You will also see any lint errors in the console.
|
|
||||||
|
|
||||||
### `npm test`
|
|
||||||
|
|
||||||
Launches the test runner in the interactive watch mode.\
|
|
||||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
|
||||||
|
|
||||||
### `npm run build`
|
|
||||||
|
|
||||||
Builds the app for production to the `build` folder.\
|
|
||||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
|
||||||
|
|
||||||
The build is minified and the filenames include the hashes.\
|
|
||||||
Your app is ready to be deployed!
|
|
||||||
|
|
||||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
|
||||||
|
|
||||||
### `npm run eject`
|
|
||||||
|
|
||||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
|
||||||
|
|
||||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
|
||||||
|
|
||||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
|
||||||
|
|
||||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
|
||||||
|
|
||||||
## Learn More
|
|
||||||
|
|
||||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
|
||||||
|
|
||||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
|
54
virtweb_frontend/eslint.config.js
Normal file
54
virtweb_frontend/eslint.config.js
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import js from "@eslint/js";
|
||||||
|
import reactDom from "eslint-plugin-react-dom";
|
||||||
|
import reactHooks from "eslint-plugin-react-hooks";
|
||||||
|
import reactRefresh from "eslint-plugin-react-refresh";
|
||||||
|
import reactX from "eslint-plugin-react-x";
|
||||||
|
import globals from "globals";
|
||||||
|
import tseslint from "typescript-eslint";
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{ ignores: ["dist"] },
|
||||||
|
{
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
...tseslint.configs.strictTypeChecked,
|
||||||
|
...tseslint.configs.stylisticTypeChecked,
|
||||||
|
],
|
||||||
|
files: ["**/*.{ts,tsx}"],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
parserOptions: {
|
||||||
|
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
"react-hooks": reactHooks,
|
||||||
|
"react-refresh": reactRefresh,
|
||||||
|
"react-x": reactX,
|
||||||
|
"react-dom": reactDom,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
"react-refresh/only-export-components": [
|
||||||
|
"warn",
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
...reactX.configs["recommended-typescript"].rules,
|
||||||
|
...reactDom.configs.recommended.rules,
|
||||||
|
"@typescript-eslint/no-non-null-assertion": "off",
|
||||||
|
"@typescript-eslint/no-misused-promises": "off",
|
||||||
|
"@typescript-eslint/no-floating-promises": "off",
|
||||||
|
"@typescript-eslint/restrict-template-expressions": "off",
|
||||||
|
"@typescript-eslint/no-extraneous-class": "off",
|
||||||
|
"@typescript-eslint/no-explicit-any": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-return": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-call": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-argument": "off",
|
||||||
|
"react-refresh/only-export-components": "off",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
19593
virtweb_frontend/package-lock.json
generated
19593
virtweb_frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -3,62 +3,54 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
|
||||||
"@emotion/react": "^11.11.1",
|
|
||||||
"@emotion/styled": "^11.11.0",
|
|
||||||
"@fontsource/roboto": "^5.0.8",
|
|
||||||
"@mdi/js": "^7.2.96",
|
|
||||||
"@mdi/react": "^1.6.1",
|
|
||||||
"@mui/icons-material": "^5.14.7",
|
|
||||||
"@mui/material": "^5.14.7",
|
|
||||||
"@mui/x-charts": "^6.0.0-alpha.9",
|
|
||||||
"@mui/x-data-grid": "^6.12.1",
|
|
||||||
"@testing-library/jest-dom": "^5.17.0",
|
|
||||||
"@testing-library/react": "^13.4.0",
|
|
||||||
"@testing-library/user-event": "^13.5.0",
|
|
||||||
"@types/humanize-duration": "^3.27.1",
|
|
||||||
"@types/jest": "^27.5.2",
|
|
||||||
"@types/react": "^18.2.21",
|
|
||||||
"@types/react-dom": "^18.2.7",
|
|
||||||
"@types/react-syntax-highlighter": "^15.5.11",
|
|
||||||
"@types/uuid": "^9.0.5",
|
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
|
||||||
"filesize": "^10.0.12",
|
|
||||||
"humanize-duration": "^3.29.0",
|
|
||||||
"mui-file-input": "^3.0.1",
|
|
||||||
"react": "^18.2.0",
|
|
||||||
"react-dom": "^18.2.0",
|
|
||||||
"react-router-dom": "^6.15.0",
|
|
||||||
"react-syntax-highlighter": "^15.5.0",
|
|
||||||
"react-vnc": "^1.0.0",
|
|
||||||
"typescript": "^4.9.5",
|
|
||||||
"uuid": "^9.0.1",
|
|
||||||
"vite": "^5.0.8",
|
|
||||||
"vite-tsconfig-paths": "^4.2.2",
|
|
||||||
"web-vitals": "^2.1.4",
|
|
||||||
"xml-formatter": "^3.6.0"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"dependencies": {
|
||||||
"extends": [
|
"@emotion/react": "^11.14.0",
|
||||||
"react-app",
|
"@emotion/styled": "^11.14.0",
|
||||||
"react-app/jest"
|
"@fontsource/roboto": "^5.2.6",
|
||||||
]
|
"@mdi/js": "^7.4.47",
|
||||||
|
"@mdi/react": "^1.6.1",
|
||||||
|
"@monaco-editor/react": "^4.7.0",
|
||||||
|
"@mui/icons-material": "^7.1.1",
|
||||||
|
"@mui/material": "^7.1.1",
|
||||||
|
"@mui/x-charts": "^8.3.1",
|
||||||
|
"@mui/x-data-grid": "^8.3.1",
|
||||||
|
"date-and-time": "^3.6.0",
|
||||||
|
"filesize": "^10.1.6",
|
||||||
|
"humanize-duration": "^3.32.2",
|
||||||
|
"monaco-editor": "^0.52.2",
|
||||||
|
"monaco-yaml": "^5.4.0",
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-dom": "^19.1.0",
|
||||||
|
"react-router-dom": "^7.6.2",
|
||||||
|
"react-syntax-highlighter": "^15.6.1",
|
||||||
|
"react-vnc": "^3.1.0",
|
||||||
|
"uuid": "^11.1.0",
|
||||||
|
"xml-formatter": "^3.6.6",
|
||||||
|
"yaml": "^2.8.0"
|
||||||
},
|
},
|
||||||
"browserslist": {
|
"devDependencies": {
|
||||||
"production": [
|
"@eslint/js": "^9.27.0",
|
||||||
">0.2%",
|
"@types/humanize-duration": "^3.27.4",
|
||||||
"not dead",
|
"@types/jest": "^29.5.14",
|
||||||
"not op_mini all"
|
"@types/react": "^19.1.8",
|
||||||
],
|
"@types/react-dom": "^19.1.6",
|
||||||
"development": [
|
"@types/react-syntax-highlighter": "^15.5.13",
|
||||||
"last 1 chrome version",
|
"@types/uuid": "^10.0.0",
|
||||||
"last 1 firefox version",
|
"@vitejs/plugin-react": "^4.4.1",
|
||||||
"last 1 safari version"
|
"eslint": "^9.27.0",
|
||||||
]
|
"eslint-plugin-react-dom": "^1.49.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
|
"eslint-plugin-react-x": "^1.49.0",
|
||||||
|
"globals": "^16.1.0",
|
||||||
|
"typescript": "^5.8.3",
|
||||||
|
"typescript-eslint": "^8.32.1",
|
||||||
|
"vite": "^6.3.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,29 +9,36 @@ import "./App.css";
|
|||||||
import { AuthApi } from "./api/AuthApi";
|
import { AuthApi } from "./api/AuthApi";
|
||||||
import { ServerApi } from "./api/ServerApi";
|
import { ServerApi } from "./api/ServerApi";
|
||||||
import {
|
import {
|
||||||
CreateNetworkRoute,
|
CreateApiTokenRoute,
|
||||||
EditNetworkRoute,
|
EditApiTokenRoute,
|
||||||
} from "./routes/EditNetworkRoute";
|
} from "./routes/EditAPITokenRoute";
|
||||||
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";
|
|
||||||
import { IsoFilesRoute } from "./routes/IsoFilesRoute";
|
|
||||||
import { NetworksListRoute } from "./routes/NetworksListRoute";
|
|
||||||
import { NotFoundRoute } from "./routes/NotFound";
|
|
||||||
import { SysInfoRoute } from "./routes/SysInfoRoute";
|
|
||||||
import { VMListRoute } from "./routes/VMListRoute";
|
|
||||||
import { VMRoute } from "./routes/VMRoute";
|
|
||||||
import { VNCRoute } from "./routes/VNCRoute";
|
|
||||||
import { LoginRoute } from "./routes/auth/LoginRoute";
|
|
||||||
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
|
|
||||||
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
|
|
||||||
import { BaseLoginPage } from "./widgets/BaseLoginPage";
|
|
||||||
import { ViewNetworkRoute } from "./routes/ViewNetworkRoute";
|
|
||||||
import { HomeRoute } from "./routes/HomeRoute";
|
|
||||||
import { NetworkFiltersListRoute } from "./routes/NetworkFiltersListRoute";
|
|
||||||
import { ViewNWFilterRoute } from "./routes/ViewNWFilterRoute";
|
|
||||||
import {
|
import {
|
||||||
CreateNWFilterRoute,
|
CreateNWFilterRoute,
|
||||||
EditNWFilterRoute,
|
EditNWFilterRoute,
|
||||||
} from "./routes/EditNWFilterRoute";
|
} from "./routes/EditNWFilterRoute";
|
||||||
|
import {
|
||||||
|
CreateNetworkRoute,
|
||||||
|
EditNetworkRoute,
|
||||||
|
} from "./routes/EditNetworkRoute";
|
||||||
|
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";
|
||||||
|
import { HomeRoute } from "./routes/HomeRoute";
|
||||||
|
import { IsoFilesRoute } from "./routes/IsoFilesRoute";
|
||||||
|
import { NetworkFiltersListRoute } from "./routes/NetworkFiltersListRoute";
|
||||||
|
import { NetworksListRoute } from "./routes/NetworksListRoute";
|
||||||
|
import { NotFoundRoute } from "./routes/NotFound";
|
||||||
|
import { SysInfoRoute } from "./routes/SysInfoRoute";
|
||||||
|
import { TokensListRoute } from "./routes/TokensListRoute";
|
||||||
|
import { VMListRoute } from "./routes/VMListRoute";
|
||||||
|
import { VMRoute } from "./routes/VMRoute";
|
||||||
|
import { VNCRoute } from "./routes/VNCRoute";
|
||||||
|
import { ViewApiTokenRoute } from "./routes/ViewApiTokenRoute";
|
||||||
|
import { ViewNWFilterRoute } from "./routes/ViewNWFilterRoute";
|
||||||
|
import { ViewNetworkRoute } from "./routes/ViewNetworkRoute";
|
||||||
|
import { LoginRoute } from "./routes/auth/LoginRoute";
|
||||||
|
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
|
||||||
|
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
|
||||||
|
import { BaseLoginPage } from "./widgets/BaseLoginPage";
|
||||||
|
import { DiskImagesRoute } from "./routes/DiskImagesRoute";
|
||||||
|
|
||||||
interface AuthContext {
|
interface AuthContext {
|
||||||
signedIn: boolean;
|
signedIn: boolean;
|
||||||
@ -45,7 +52,10 @@ export function App() {
|
|||||||
|
|
||||||
const context: AuthContext = {
|
const context: AuthContext = {
|
||||||
signedIn: signedIn,
|
signedIn: signedIn,
|
||||||
setSignedIn: (s) => setSignedIn(s),
|
setSignedIn: (s) => {
|
||||||
|
setSignedIn(s);
|
||||||
|
location.reload();
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const router = createBrowserRouter(
|
const router = createBrowserRouter(
|
||||||
@ -54,6 +64,8 @@ export function App() {
|
|||||||
<Route path="*" element={<BaseAuthenticatedPage />}>
|
<Route path="*" element={<BaseAuthenticatedPage />}>
|
||||||
<Route path="" element={<HomeRoute />} />
|
<Route path="" element={<HomeRoute />} />
|
||||||
|
|
||||||
|
<Route path="disk_images" element={<DiskImagesRoute />} />
|
||||||
|
|
||||||
<Route path="iso" element={<IsoFilesRoute />} />
|
<Route path="iso" element={<IsoFilesRoute />} />
|
||||||
|
|
||||||
<Route path="vms" element={<VMListRoute />} />
|
<Route path="vms" element={<VMListRoute />} />
|
||||||
@ -72,6 +84,11 @@ export function App() {
|
|||||||
<Route path="nwfilter/:uuid" element={<ViewNWFilterRoute />} />
|
<Route path="nwfilter/:uuid" element={<ViewNWFilterRoute />} />
|
||||||
<Route path="nwfilter/:uuid/edit" element={<EditNWFilterRoute />} />
|
<Route path="nwfilter/:uuid/edit" element={<EditNWFilterRoute />} />
|
||||||
|
|
||||||
|
<Route path="tokens" element={<TokensListRoute />} />
|
||||||
|
<Route path="token/new" element={<CreateApiTokenRoute />} />
|
||||||
|
<Route path="token/:id" element={<ViewApiTokenRoute />} />
|
||||||
|
<Route path="token/:id/edit" element={<EditApiTokenRoute />} />
|
||||||
|
|
||||||
<Route path="sysinfo" element={<SysInfoRoute />} />
|
<Route path="sysinfo" element={<SysInfoRoute />} />
|
||||||
<Route path="*" element={<NotFoundRoute />} />
|
<Route path="*" element={<NotFoundRoute />} />
|
||||||
</Route>
|
</Route>
|
||||||
@ -86,12 +103,12 @@ export function App() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContextK.Provider value={context}>
|
<AuthContextK value={context}>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
</AuthContextK.Provider>
|
</AuthContextK>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuth(): AuthContext {
|
export function useAuth(): AuthContext {
|
||||||
return React.useContext(AuthContextK)!;
|
return React.use(AuthContextK)!;
|
||||||
}
|
}
|
||||||
|
@ -26,7 +26,7 @@ export class APIClient {
|
|||||||
* Get backend URL
|
* Get backend URL
|
||||||
*/
|
*/
|
||||||
static backendURL(): string {
|
static backendURL(): string {
|
||||||
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
|
const URL = String(import.meta.env.VITE_APP_BACKEND ?? "");
|
||||||
if (URL.length === 0) throw new Error("Backend URL undefined!");
|
if (URL.length === 0) throw new Error("Backend URL undefined!");
|
||||||
return URL;
|
return URL;
|
||||||
}
|
}
|
||||||
@ -44,7 +44,7 @@ export class APIClient {
|
|||||||
*/
|
*/
|
||||||
static async exec(args: RequestParams): Promise<APIResponse> {
|
static async exec(args: RequestParams): Promise<APIResponse> {
|
||||||
let body: string | undefined | FormData = undefined;
|
let body: string | undefined | FormData = undefined;
|
||||||
let headers: any = {};
|
const headers: any = {};
|
||||||
|
|
||||||
// JSON request
|
// JSON request
|
||||||
if (args.jsonData) {
|
if (args.jsonData) {
|
||||||
@ -66,22 +66,25 @@ export class APIClient {
|
|||||||
if (args.upProgress) {
|
if (args.upProgress) {
|
||||||
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
|
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.upload.addEventListener("progress", (e) =>
|
xhr.upload.addEventListener("progress", (e) => {
|
||||||
args.upProgress!(e.loaded / e.total)
|
args.upProgress!(e.loaded / e.total);
|
||||||
);
|
});
|
||||||
xhr.addEventListener("load", () => resolve(xhr));
|
xhr.addEventListener("load", () => {
|
||||||
xhr.addEventListener("error", () =>
|
resolve(xhr);
|
||||||
reject(new Error("File upload failed"))
|
});
|
||||||
);
|
xhr.addEventListener("error", () => {
|
||||||
xhr.addEventListener("abort", () =>
|
reject(new Error("File upload failed"));
|
||||||
reject(new Error("File upload aborted"))
|
});
|
||||||
);
|
xhr.addEventListener("abort", () => {
|
||||||
xhr.addEventListener("timeout", () =>
|
reject(new Error("File upload aborted"));
|
||||||
reject(new Error("File upload timeout"))
|
});
|
||||||
);
|
xhr.addEventListener("timeout", () => {
|
||||||
|
reject(new Error("File upload timeout"));
|
||||||
|
});
|
||||||
xhr.open(args.method, url, true);
|
xhr.open(args.method, url, true);
|
||||||
xhr.withCredentials = true;
|
xhr.withCredentials = true;
|
||||||
for (const key in headers) {
|
for (const key in headers) {
|
||||||
|
// eslint-disable-next-line no-prototype-builtins
|
||||||
if (headers.hasOwnProperty(key))
|
if (headers.hasOwnProperty(key))
|
||||||
xhr.setRequestHeader(key, headers[key]);
|
xhr.setRequestHeader(key, headers[key]);
|
||||||
}
|
}
|
||||||
@ -100,6 +103,7 @@ export class APIClient {
|
|||||||
body: body,
|
body: body,
|
||||||
headers: headers,
|
headers: headers,
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
|
signal: AbortSignal.timeout(50 * 1000 * 1000),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Process response
|
// Process response
|
||||||
|
119
virtweb_frontend/src/api/DiskImageApi.ts
Normal file
119
virtweb_frontend/src/api/DiskImageApi.ts
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
import { VMFileDisk, VMInfo } from "./VMApi";
|
||||||
|
|
||||||
|
export type DiskImageFormat =
|
||||||
|
| { format: "Raw"; is_sparse: boolean }
|
||||||
|
| { format: "QCow2"; virtual_size?: number }
|
||||||
|
| { format: "GzCompressedQCow2" }
|
||||||
|
| { format: "GzCompressedRaw" }
|
||||||
|
| { format: "XzCompressedQCow2" }
|
||||||
|
| { format: "XzCompressedRaw" };
|
||||||
|
|
||||||
|
export type DiskImage = {
|
||||||
|
file_size: number;
|
||||||
|
file_name: string;
|
||||||
|
name: string;
|
||||||
|
created: number;
|
||||||
|
} & DiskImageFormat;
|
||||||
|
|
||||||
|
export class DiskImageApi {
|
||||||
|
/**
|
||||||
|
* Upload a new disk image file to the server
|
||||||
|
*/
|
||||||
|
static async Upload(
|
||||||
|
file: File,
|
||||||
|
progress: (progress: number) => void
|
||||||
|
): Promise<void> {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "POST",
|
||||||
|
uri: "/disk_images/upload",
|
||||||
|
formData: fd,
|
||||||
|
upProgress: progress,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of disk images
|
||||||
|
*/
|
||||||
|
static async GetList(): Promise<DiskImage[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/disk_images/list",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download disk image file
|
||||||
|
*/
|
||||||
|
static async Download(
|
||||||
|
file: DiskImage,
|
||||||
|
progress: (p: number) => void
|
||||||
|
): Promise<Blob> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: `/disk_images/${file.file_name}`,
|
||||||
|
downProgress(e) {
|
||||||
|
progress(Math.floor(100 * (e.progress / e.total)));
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert disk image file
|
||||||
|
*/
|
||||||
|
static async Convert(
|
||||||
|
file: DiskImage,
|
||||||
|
dest_file_name: string,
|
||||||
|
dest_format: DiskImageFormat
|
||||||
|
): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "POST",
|
||||||
|
uri: `/disk_images/${file.file_name}/convert`,
|
||||||
|
jsonData: { ...dest_format, dest_file_name },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Backup VM disk into image disks library
|
||||||
|
*/
|
||||||
|
static async BackupVMDisk(
|
||||||
|
vm: VMInfo,
|
||||||
|
disk: VMFileDisk,
|
||||||
|
dest_file_name: string,
|
||||||
|
format: DiskImageFormat
|
||||||
|
): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: `/vm/${vm.uuid}/disk/${disk.name}/backup`,
|
||||||
|
method: "POST",
|
||||||
|
jsonData: { ...format, dest_file_name },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename disk image file
|
||||||
|
*/
|
||||||
|
static async Rename(file: DiskImage, name: string): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "POST",
|
||||||
|
uri: `/disk_images/${file.file_name}/rename`,
|
||||||
|
jsonData: { name },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete disk image file
|
||||||
|
*/
|
||||||
|
static async Delete(file: DiskImage): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "DELETE",
|
||||||
|
uri: `/disk_images/${file.file_name}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
15
virtweb_frontend/src/api/GroupApi.ts
Normal file
15
virtweb_frontend/src/api/GroupApi.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export class GroupApi {
|
||||||
|
/**
|
||||||
|
* Get the entire list of networks
|
||||||
|
*/
|
||||||
|
static async GetList(): Promise<string[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/group/list",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
}
|
@ -5,6 +5,15 @@ export interface IsoFile {
|
|||||||
size: number;
|
size: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ISO catalog entries
|
||||||
|
*/
|
||||||
|
export interface ISOCatalogEntry {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
image: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class IsoFilesApi {
|
export class IsoFilesApi {
|
||||||
/**
|
/**
|
||||||
* Upload a new ISO file to the server
|
* Upload a new ISO file to the server
|
||||||
@ -74,4 +83,23 @@ export class IsoFilesApi {
|
|||||||
uri: `/iso/${file.filename}`,
|
uri: `/iso/${file.filename}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get iso catalog
|
||||||
|
*/
|
||||||
|
static async Catalog(): Promise<ISOCatalogEntry[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/assets/iso_catalog.json",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get catalog image URL
|
||||||
|
*/
|
||||||
|
static CatalogImageURL(entry: ISOCatalogEntry): string {
|
||||||
|
return APIClient.backendURL() + entry.image;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -140,7 +140,7 @@ export interface NWFilter {
|
|||||||
rules: NWFilterRule[];
|
rules: NWFilterRule[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NWFilterURL(n: NWFilter, edit: boolean = false): string {
|
export function NWFilterURL(n: NWFilter, edit = false): string {
|
||||||
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
|
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -221,7 +221,7 @@ export class NWFilterApi {
|
|||||||
static async Delete(n: NWFilter): Promise<void> {
|
static async Delete(n: NWFilter): Promise<void> {
|
||||||
await APIClient.exec({
|
await APIClient.exec({
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
uri: `/nwfilter/${n.uuid}`,
|
uri: `/nwfilter/${n.uuid!}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,10 +13,28 @@ export interface DHCPConfig {
|
|||||||
hosts: DHCPHost[];
|
hosts: DHCPHost[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NatSource =
|
||||||
|
| { type: "interface"; name: string }
|
||||||
|
| { type: "ip"; ip: string };
|
||||||
|
|
||||||
|
export type NatHostPort =
|
||||||
|
| { type: "single"; port: number }
|
||||||
|
| { type: "range"; start: number; end: number };
|
||||||
|
|
||||||
|
export interface NatEntry {
|
||||||
|
protocol: "TCP" | "UDP" | "Both";
|
||||||
|
host_ip: NatSource;
|
||||||
|
host_port: NatHostPort;
|
||||||
|
guest_ip: string;
|
||||||
|
guest_port: number;
|
||||||
|
comment?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface IpConfig {
|
export interface IpConfig {
|
||||||
bridge_address: string;
|
bridge_address: string;
|
||||||
prefix: number;
|
prefix: number;
|
||||||
dhcp?: DHCPConfig;
|
dhcp?: DHCPConfig;
|
||||||
|
nat?: NatEntry[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NetworkInfo {
|
export interface NetworkInfo {
|
||||||
@ -35,7 +53,7 @@ export interface NetworkInfo {
|
|||||||
|
|
||||||
export type NetworkStatus = "Started" | "Stopped";
|
export type NetworkStatus = "Started" | "Stopped";
|
||||||
|
|
||||||
export function NetworkURL(n: NetworkInfo, edit: boolean = false): string {
|
export function NetworkURL(n: NetworkInfo, edit = false): string {
|
||||||
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
|
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,6 +5,7 @@ export interface ServerConfig {
|
|||||||
local_auth_enabled: boolean;
|
local_auth_enabled: boolean;
|
||||||
oidc_auth_enabled: boolean;
|
oidc_auth_enabled: boolean;
|
||||||
iso_mimetypes: string[];
|
iso_mimetypes: string[];
|
||||||
|
disk_images_mimetypes: string[];
|
||||||
net_mac_prefix: string;
|
net_mac_prefix: string;
|
||||||
builtin_nwfilter_rules: string[];
|
builtin_nwfilter_rules: string[];
|
||||||
nwfilter_chains: string[];
|
nwfilter_chains: string[];
|
||||||
@ -13,19 +14,26 @@ export interface ServerConfig {
|
|||||||
|
|
||||||
export interface ServerConstraints {
|
export interface ServerConstraints {
|
||||||
iso_max_size: number;
|
iso_max_size: number;
|
||||||
|
disk_image_max_size: number;
|
||||||
vnc_token_duration: number;
|
vnc_token_duration: number;
|
||||||
vm_name_size: LenConstraint;
|
vm_name_size: LenConstraint;
|
||||||
vm_title_size: LenConstraint;
|
vm_title_size: LenConstraint;
|
||||||
|
group_id_size: LenConstraint;
|
||||||
memory_size: LenConstraint;
|
memory_size: LenConstraint;
|
||||||
disk_name_size: LenConstraint;
|
disk_name_size: LenConstraint;
|
||||||
disk_size: LenConstraint;
|
disk_size: LenConstraint;
|
||||||
|
disk_image_name_size: LenConstraint;
|
||||||
net_name_size: LenConstraint;
|
net_name_size: LenConstraint;
|
||||||
net_title_size: LenConstraint;
|
net_title_size: LenConstraint;
|
||||||
|
net_nat_comment_size: LenConstraint;
|
||||||
dhcp_reservation_host_name: LenConstraint;
|
dhcp_reservation_host_name: LenConstraint;
|
||||||
nwfilter_name_size: LenConstraint;
|
nwfilter_name_size: LenConstraint;
|
||||||
nwfilter_comment_size: LenConstraint;
|
nwfilter_comment_size: LenConstraint;
|
||||||
nwfilter_priority: LenConstraint;
|
nwfilter_priority: LenConstraint;
|
||||||
nwfilter_selectors_count: LenConstraint;
|
nwfilter_selectors_count: LenConstraint;
|
||||||
|
api_token_name_size: LenConstraint;
|
||||||
|
api_token_description_size: LenConstraint;
|
||||||
|
api_token_right_path_size: LenConstraint;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LenConstraint {
|
export interface LenConstraint {
|
||||||
@ -38,6 +46,9 @@ let config: ServerConfig | null = null;
|
|||||||
export interface ServerSystemInfo {
|
export interface ServerSystemInfo {
|
||||||
hypervisor: HypervisorInfo;
|
hypervisor: HypervisorInfo;
|
||||||
system: SystemInfo;
|
system: SystemInfo;
|
||||||
|
components: SysComponent;
|
||||||
|
disks: DiskInfo[];
|
||||||
|
networks: NetworkInfo[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface HypervisorInfo {
|
interface HypervisorInfo {
|
||||||
@ -66,7 +77,7 @@ interface SystemInfo {
|
|||||||
secs: number;
|
secs: number;
|
||||||
nanos: number;
|
nanos: number;
|
||||||
};
|
};
|
||||||
global_cpu_info: GlobalCPUInfo;
|
global_cpu_usage: number;
|
||||||
cpus: CpuCore[];
|
cpus: CpuCore[];
|
||||||
physical_core_count: number;
|
physical_core_count: number;
|
||||||
total_memory: number;
|
total_memory: number;
|
||||||
@ -76,10 +87,6 @@ interface SystemInfo {
|
|||||||
total_swap: number;
|
total_swap: number;
|
||||||
free_swap: number;
|
free_swap: number;
|
||||||
used_swap: number;
|
used_swap: number;
|
||||||
components: SysComponent;
|
|
||||||
users: [];
|
|
||||||
disks: DiskInfo[];
|
|
||||||
networks: NetworkInfo[];
|
|
||||||
uptime: number;
|
uptime: number;
|
||||||
boot_time: number;
|
boot_time: number;
|
||||||
load_average: SysLoadAverage;
|
load_average: SysLoadAverage;
|
||||||
@ -91,14 +98,6 @@ interface SystemInfo {
|
|||||||
host_name: string;
|
host_name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GlobalCPUInfo {
|
|
||||||
cpu_usage: number;
|
|
||||||
name: string;
|
|
||||||
vendor_id: string;
|
|
||||||
brand: string;
|
|
||||||
frequency: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CpuCore {
|
interface CpuCore {
|
||||||
cpu_usage: number;
|
cpu_usage: number;
|
||||||
name: string;
|
name: string;
|
||||||
@ -147,6 +146,12 @@ interface SysLoadAverage {
|
|||||||
fifteen: number;
|
fifteen: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface NetworkHookStatus {
|
||||||
|
installed: boolean;
|
||||||
|
content: string;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class ServerApi {
|
export class ServerApi {
|
||||||
/**
|
/**
|
||||||
* Get server configuration
|
* Get server configuration
|
||||||
@ -180,6 +185,18 @@ export class ServerApi {
|
|||||||
).data;
|
).data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get network hook status
|
||||||
|
*/
|
||||||
|
static async NetworkHookStatus(): Promise<NetworkHookStatus> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/server/network_hook_status",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get host supported vCPUs configurations
|
* Get host supported vCPUs configurations
|
||||||
*/
|
*/
|
||||||
@ -203,4 +220,28 @@ export class ServerApi {
|
|||||||
})
|
})
|
||||||
).data;
|
).data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get host networks bridges list
|
||||||
|
*/
|
||||||
|
static async GetNetworksBridgesList(): Promise<string[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/server/bridges",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export all server configs
|
||||||
|
*/
|
||||||
|
static async ExportServerConfigs(): Promise<Blob> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/server/export_configs",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
102
virtweb_frontend/src/api/TokensApi.ts
Normal file
102
virtweb_frontend/src/api/TokensApi.ts
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
import { time } from "../utils/DateUtils";
|
||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export type RightVerb = "POST" | "GET" | "PUT" | "DELETE" | "PATCH";
|
||||||
|
|
||||||
|
export interface TokenRight {
|
||||||
|
verb: RightVerb;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface APIToken {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
created: number;
|
||||||
|
updated: number;
|
||||||
|
rights: TokenRight[];
|
||||||
|
last_used: number;
|
||||||
|
ip_restriction?: string;
|
||||||
|
max_inactivity?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function APITokenURL(t: APIToken, edit = false): string {
|
||||||
|
return `/token/${t.id}${edit ? "/edit" : ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExpiredAPIToken(t: APIToken): boolean {
|
||||||
|
if (!t.max_inactivity) return false;
|
||||||
|
return t.last_used + t.max_inactivity < time();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface APITokenPrivateKey {
|
||||||
|
alg: string;
|
||||||
|
priv: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatedAPIToken {
|
||||||
|
token: APIToken;
|
||||||
|
priv_key: APITokenPrivateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TokensApi {
|
||||||
|
/**
|
||||||
|
* Create a new API token
|
||||||
|
*/
|
||||||
|
static async Create(n: APIToken): Promise<CreatedAPIToken> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "POST",
|
||||||
|
uri: "/token/create",
|
||||||
|
jsonData: n,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the full list of tokens
|
||||||
|
*/
|
||||||
|
static async GetList(): Promise<APIToken[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/token/list",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the information about a single token
|
||||||
|
*/
|
||||||
|
static async GetSingle(uuid: string): Promise<APIToken> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: `/token/${uuid}`,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update an existing API token information
|
||||||
|
*/
|
||||||
|
static async Update(n: APIToken): Promise<void> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "PATCH",
|
||||||
|
uri: `/token/${n.id}`,
|
||||||
|
jsonData: n,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete an API token
|
||||||
|
*/
|
||||||
|
static async Delete(n: APIToken): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "DELETE",
|
||||||
|
uri: `/token/${n.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -17,19 +17,38 @@ export type VMState =
|
|||||||
| "PowerManagementSuspended"
|
| "PowerManagementSuspended"
|
||||||
| "Other";
|
| "Other";
|
||||||
|
|
||||||
export type DiskAllocType = "Sparse" | "Fixed";
|
export type VMFileDisk = BaseFileVMDisk & (RawVMDisk | QCow2Disk);
|
||||||
|
|
||||||
export interface VMDisk {
|
export type DiskBusType = "Virtio" | "SATA";
|
||||||
|
|
||||||
|
export interface BaseFileVMDisk {
|
||||||
size: number;
|
size: number;
|
||||||
name: string;
|
name: string;
|
||||||
alloc_type: DiskAllocType;
|
bus: DiskBusType;
|
||||||
|
|
||||||
delete: boolean;
|
delete: boolean;
|
||||||
|
|
||||||
// application attribute
|
// For new disk only
|
||||||
|
from_image?: string;
|
||||||
|
|
||||||
|
// Resize disk image after clone
|
||||||
|
resize?: boolean;
|
||||||
|
|
||||||
|
// application attributes
|
||||||
new?: boolean;
|
new?: boolean;
|
||||||
|
originalSize?: number;
|
||||||
deleteType?: "keepfile" | "deletefile";
|
deleteType?: "keepfile" | "deletefile";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface RawVMDisk {
|
||||||
|
format: "Raw";
|
||||||
|
is_sparse: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface QCow2Disk {
|
||||||
|
format: "QCow2";
|
||||||
|
}
|
||||||
|
|
||||||
export interface VMNetInterfaceFilterParams {
|
export interface VMNetInterfaceFilterParams {
|
||||||
name: string;
|
name: string;
|
||||||
value: string;
|
value: string;
|
||||||
@ -40,11 +59,16 @@ export interface VMNetInterfaceFilter {
|
|||||||
parameters: VMNetInterfaceFilterParams[];
|
parameters: VMNetInterfaceFilterParams[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type VMNetInterface = (VMNetUserspaceSLIRPStack | VMNetDefinedNetwork) &
|
export type VMNetInterface = (
|
||||||
|
| VMNetUserspaceSLIRPStack
|
||||||
|
| VMNetDefinedNetwork
|
||||||
|
| VMNetBridge
|
||||||
|
) &
|
||||||
VMNetInterfaceBase;
|
VMNetInterfaceBase;
|
||||||
|
|
||||||
export interface VMNetInterfaceBase {
|
export interface VMNetInterfaceBase {
|
||||||
mac: string;
|
mac: string;
|
||||||
|
model: "Virtio" | "E1000";
|
||||||
nwfilterref?: VMNetInterfaceFilter;
|
nwfilterref?: VMNetInterfaceFilter;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,21 +81,40 @@ export interface VMNetDefinedNetwork {
|
|||||||
network: string;
|
network: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VMNetBridge {
|
||||||
|
type: "Bridge";
|
||||||
|
bridge: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VMCloudInit {
|
||||||
|
attach_config: boolean;
|
||||||
|
user_data: string;
|
||||||
|
instance_id?: string;
|
||||||
|
local_hostname?: string;
|
||||||
|
dsmode?: "Net" | "Local";
|
||||||
|
network_configuration?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VMBootType = "UEFI" | "UEFISecureBoot" | "Legacy";
|
||||||
|
|
||||||
interface VMInfoInterface {
|
interface VMInfoInterface {
|
||||||
name: string;
|
name: string;
|
||||||
uuid?: string;
|
uuid?: string;
|
||||||
genid?: string;
|
genid?: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
boot_type: "UEFI" | "UEFISecureBoot";
|
group?: string;
|
||||||
|
boot_type: VMBootType;
|
||||||
architecture: "i686" | "x86_64";
|
architecture: "i686" | "x86_64";
|
||||||
memory: number;
|
memory: number;
|
||||||
number_vcpu: number;
|
number_vcpu: number;
|
||||||
vnc_access: boolean;
|
vnc_access: boolean;
|
||||||
iso_files: string[];
|
iso_files: string[];
|
||||||
disks: VMDisk[];
|
file_disks: VMFileDisk[];
|
||||||
networks: VMNetInterface[];
|
networks: VMNetInterface[];
|
||||||
tpm_module: boolean;
|
tpm_module: boolean;
|
||||||
|
oem_strings: string[];
|
||||||
|
cloud_init: VMCloudInit;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class VMInfo implements VMInfoInterface {
|
export class VMInfo implements VMInfoInterface {
|
||||||
@ -80,15 +123,18 @@ export class VMInfo implements VMInfoInterface {
|
|||||||
genid?: string;
|
genid?: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
boot_type: "UEFI" | "UEFISecureBoot";
|
group?: string;
|
||||||
|
boot_type: VMBootType;
|
||||||
architecture: "i686" | "x86_64";
|
architecture: "i686" | "x86_64";
|
||||||
number_vcpu: number;
|
number_vcpu: number;
|
||||||
memory: number;
|
memory: number;
|
||||||
vnc_access: boolean;
|
vnc_access: boolean;
|
||||||
iso_files: string[];
|
iso_files: string[];
|
||||||
disks: VMDisk[];
|
file_disks: VMFileDisk[];
|
||||||
networks: VMNetInterface[];
|
networks: VMNetInterface[];
|
||||||
tpm_module: boolean;
|
tpm_module: boolean;
|
||||||
|
oem_strings: string[];
|
||||||
|
cloud_init: VMCloudInit;
|
||||||
|
|
||||||
constructor(int: VMInfoInterface) {
|
constructor(int: VMInfoInterface) {
|
||||||
this.name = int.name;
|
this.name = int.name;
|
||||||
@ -96,15 +142,18 @@ export class VMInfo implements VMInfoInterface {
|
|||||||
this.genid = int.genid;
|
this.genid = int.genid;
|
||||||
this.title = int.title;
|
this.title = int.title;
|
||||||
this.description = int.description;
|
this.description = int.description;
|
||||||
|
this.group = int.group;
|
||||||
this.boot_type = int.boot_type;
|
this.boot_type = int.boot_type;
|
||||||
this.architecture = int.architecture;
|
this.architecture = int.architecture;
|
||||||
this.number_vcpu = int.number_vcpu;
|
this.number_vcpu = int.number_vcpu;
|
||||||
this.memory = int.memory;
|
this.memory = int.memory;
|
||||||
this.vnc_access = int.vnc_access;
|
this.vnc_access = int.vnc_access;
|
||||||
this.iso_files = int.iso_files;
|
this.iso_files = int.iso_files;
|
||||||
this.disks = int.disks;
|
this.file_disks = int.file_disks;
|
||||||
this.networks = int.networks;
|
this.networks = int.networks;
|
||||||
this.tpm_module = int.tpm_module;
|
this.tpm_module = int.tpm_module;
|
||||||
|
this.oem_strings = int.oem_strings;
|
||||||
|
this.cloud_init = int.cloud_init;
|
||||||
}
|
}
|
||||||
|
|
||||||
static NewEmpty(): VMInfo {
|
static NewEmpty(): VMInfo {
|
||||||
@ -112,13 +161,15 @@ export class VMInfo implements VMInfoInterface {
|
|||||||
name: "",
|
name: "",
|
||||||
boot_type: "UEFI",
|
boot_type: "UEFI",
|
||||||
architecture: "x86_64",
|
architecture: "x86_64",
|
||||||
memory: 1024,
|
memory: 1000 * 1000 * 1000,
|
||||||
number_vcpu: 1,
|
number_vcpu: 1,
|
||||||
vnc_access: true,
|
vnc_access: true,
|
||||||
iso_files: [],
|
iso_files: [],
|
||||||
disks: [],
|
file_disks: [],
|
||||||
networks: [],
|
networks: [],
|
||||||
tpm_module: true,
|
tpm_module: true,
|
||||||
|
oem_strings: [],
|
||||||
|
cloud_init: { attach_config: false, user_data: "" },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -191,8 +242,8 @@ export class VMApi {
|
|||||||
*/
|
*/
|
||||||
static async UpdateSingle(vm: VMInfo): Promise<VMInfo> {
|
static async UpdateSingle(vm: VMInfo): Promise<VMInfo> {
|
||||||
// Process disks list, looking for removal
|
// Process disks list, looking for removal
|
||||||
vm.disks = vm.disks.filter((d) => d.deleteType !== "keepfile");
|
vm.file_disks = vm.file_disks.filter((d) => d.deleteType !== "keepfile");
|
||||||
vm.disks.forEach((d) => {
|
vm.file_disks.forEach((d) => {
|
||||||
if (d.deleteType === "deletefile") d.delete = true;
|
if (d.deleteType === "deletefile") d.delete = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
148
virtweb_frontend/src/dialogs/ConvertDiskImageDialog.tsx
Normal file
148
virtweb_frontend/src/dialogs/ConvertDiskImageDialog.tsx
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { DiskImage, DiskImageApi, DiskImageFormat } from "../api/DiskImageApi";
|
||||||
|
import { ServerApi } from "../api/ServerApi";
|
||||||
|
import { VMFileDisk, VMInfo } from "../api/VMApi";
|
||||||
|
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
||||||
|
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
||||||
|
import { FileDiskImageWidget } from "../widgets/FileDiskImageWidget";
|
||||||
|
import { CheckboxInput } from "../widgets/forms/CheckboxInput";
|
||||||
|
import { SelectInput } from "../widgets/forms/SelectInput";
|
||||||
|
import { TextInput } from "../widgets/forms/TextInput";
|
||||||
|
import { VMDiskFileWidget } from "../widgets/vms/VMDiskFileWidget";
|
||||||
|
|
||||||
|
export function ConvertDiskImageDialog(
|
||||||
|
p: {
|
||||||
|
onCancel: () => void;
|
||||||
|
onFinished: () => void;
|
||||||
|
} & (
|
||||||
|
| { backup?: false; image: DiskImage }
|
||||||
|
| { backup: true; disk: VMFileDisk; vm: VMInfo }
|
||||||
|
)
|
||||||
|
): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const loadingMessage = useLoadingMessage();
|
||||||
|
|
||||||
|
const [format, setFormat] = React.useState<DiskImageFormat>({
|
||||||
|
format: "QCow2",
|
||||||
|
});
|
||||||
|
|
||||||
|
const origFilename = p.backup ? p.disk.name : p.image.file_name;
|
||||||
|
|
||||||
|
const [filename, setFilename] = React.useState(origFilename + ".qcow2");
|
||||||
|
|
||||||
|
const handleFormatChange = (value?: string) => {
|
||||||
|
setFormat({ format: value ?? ("QCow2" as any) });
|
||||||
|
|
||||||
|
if (value === "QCow2") setFilename(`${origFilename}.qcow2`);
|
||||||
|
if (value === "GzCompressedQCow2") setFilename(`${origFilename}.qcow2.gz`);
|
||||||
|
if (value === "XzCompressedQCow2") setFilename(`${origFilename}.qcow2.xz`);
|
||||||
|
if (value === "Raw") {
|
||||||
|
setFilename(`${origFilename}.raw`);
|
||||||
|
// Check sparse checkbox by default
|
||||||
|
setFormat({ format: "Raw", is_sparse: true });
|
||||||
|
}
|
||||||
|
if (value === "GzCompressedRaw") setFilename(`${origFilename}.raw.gz`);
|
||||||
|
if (value === "XzCompressedRaw") setFilename(`${origFilename}.raw.xz`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
try {
|
||||||
|
loadingMessage.show(
|
||||||
|
p.backup ? "Performing backup..." : "Converting image..."
|
||||||
|
);
|
||||||
|
|
||||||
|
// Perform the conversion / backup operation
|
||||||
|
if (p.backup)
|
||||||
|
await DiskImageApi.BackupVMDisk(p.vm, p.disk, filename, format);
|
||||||
|
else await DiskImageApi.Convert(p.image, filename, format);
|
||||||
|
|
||||||
|
p.onFinished();
|
||||||
|
|
||||||
|
alert(p.backup ? "Backup successful!" : "Conversion successful!");
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to perform backup/conversion!", e);
|
||||||
|
alert(
|
||||||
|
p.backup
|
||||||
|
? `Failed to perform backup! ${e}`
|
||||||
|
: `Failed to convert image! ${e}`
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
loadingMessage.hide();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onClose={p.onCancel}>
|
||||||
|
<DialogTitle>
|
||||||
|
{p.backup ? `Backup disk ${p.disk.name}` : "Convert disk image"}
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText>
|
||||||
|
Select the destination format for this image:
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
{/* Show details of of the image */}
|
||||||
|
{p.backup ? (
|
||||||
|
<VMDiskFileWidget {...p} />
|
||||||
|
) : (
|
||||||
|
<FileDiskImageWidget {...p} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* New image format */}
|
||||||
|
<SelectInput
|
||||||
|
editable
|
||||||
|
label="Target format"
|
||||||
|
value={format.format}
|
||||||
|
onValueChange={handleFormatChange}
|
||||||
|
options={[
|
||||||
|
{ value: "QCow2" },
|
||||||
|
{ value: "Raw" },
|
||||||
|
{ value: "GzCompressedRaw" },
|
||||||
|
{ value: "XzCompressedRaw" },
|
||||||
|
{ value: "GzCompressedQCow2" },
|
||||||
|
{ value: "XzCompressedQCow2" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Check for sparse file */}
|
||||||
|
{format.format === "Raw" && (
|
||||||
|
<CheckboxInput
|
||||||
|
editable
|
||||||
|
label="Sparse file"
|
||||||
|
checked={format.is_sparse}
|
||||||
|
onValueChange={(c) => {
|
||||||
|
setFormat({ format: "Raw", is_sparse: c });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* New image name */}
|
||||||
|
<TextInput
|
||||||
|
editable
|
||||||
|
label="New image name"
|
||||||
|
value={filename}
|
||||||
|
onValueChange={(s) => {
|
||||||
|
setFilename(s ?? "");
|
||||||
|
}}
|
||||||
|
size={ServerApi.Config.constraints.disk_image_name_size}
|
||||||
|
helperText="The image name shall contain the proper file extension for the selected target format"
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={p.onCancel}>Cancel</Button>
|
||||||
|
<Button onClick={handleSubmit} autoFocus>
|
||||||
|
{p.backup ? "Perform backup" : "Convert image"}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
58
virtweb_frontend/src/dialogs/CreatedTokenDialog.tsx
Normal file
58
virtweb_frontend/src/dialogs/CreatedTokenDialog.tsx
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { APITokenURL, CreatedAPIToken } from "../api/TokensApi";
|
||||||
|
import { CopyToClipboard } from "../widgets/CopyToClipboard";
|
||||||
|
import { InlineCode } from "../widgets/InlineCode";
|
||||||
|
|
||||||
|
export function CreatedTokenDialog(p: {
|
||||||
|
createdToken: CreatedAPIToken;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
navigate(APITokenURL(p.createdToken.token));
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Dialog open>
|
||||||
|
<DialogTitle>Token successfully created</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<Typography>
|
||||||
|
Your token was successfully created. You need now to copy the private
|
||||||
|
key, as it will be technically impossible to recover it after closing
|
||||||
|
this dialog.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<InfoBlock label="Token ID" value={p.createdToken.token.id} />
|
||||||
|
<InfoBlock label="Key algorithm" value={p.createdToken.priv_key.alg} />
|
||||||
|
<InfoBlock label="Private key" value={p.createdToken.priv_key.priv} />
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={close} color="error">
|
||||||
|
I copied the key, close this dialog
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function InfoBlock(
|
||||||
|
p: React.PropsWithChildren<{ label: string; value: string }>
|
||||||
|
): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{ display: "flex", flexDirection: "column", margin: "20px 10px" }}
|
||||||
|
>
|
||||||
|
<Typography variant="overline">{p.label}</Typography>
|
||||||
|
<CopyToClipboard content={p.value}>
|
||||||
|
<InlineCode>{p.value}</InlineCode>
|
||||||
|
</CopyToClipboard>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
75
virtweb_frontend/src/dialogs/IsoCatalogDialog.tsx
Normal file
75
virtweb_frontend/src/dialogs/IsoCatalogDialog.tsx
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
ListItemAvatar,
|
||||||
|
ListItemButton,
|
||||||
|
ListItemText,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { ISOCatalogEntry, IsoFilesApi } from "../api/IsoFilesApi";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
|
||||||
|
export function IsoCatalogDialog(p: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const [catalog, setCatalog] = React.useState<ISOCatalogEntry[] | undefined>();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setCatalog(await IsoFilesApi.Catalog());
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={p.open} onClose={p.onClose}>
|
||||||
|
<DialogTitle>ISO catalog</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={1}
|
||||||
|
load={load}
|
||||||
|
errMsg="Failed to load catalog"
|
||||||
|
build={() => <IsoCatalogDialogInner catalog={catalog!} />}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button autoFocus onClick={p.onClose}>
|
||||||
|
Close
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IsoCatalogDialogInner(p: {
|
||||||
|
catalog: ISOCatalogEntry[];
|
||||||
|
}): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<List dense>
|
||||||
|
{p.catalog.map((entry) => (
|
||||||
|
<a
|
||||||
|
key={entry.name}
|
||||||
|
href={entry.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
style={{ color: "inherit", textDecoration: "none" }}
|
||||||
|
>
|
||||||
|
<ListItem>
|
||||||
|
<ListItemButton>
|
||||||
|
<ListItemAvatar>
|
||||||
|
<img
|
||||||
|
src={IsoFilesApi.CatalogImageURL(entry)}
|
||||||
|
style={{ width: "2em" }}
|
||||||
|
/>
|
||||||
|
</ListItemAvatar>
|
||||||
|
<ListItemText primary={entry.name} />
|
||||||
|
</ListItemButton>
|
||||||
|
</ListItem>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
);
|
||||||
|
}
|
@ -39,7 +39,7 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<AlertContextK.Provider value={hook}>{p.children}</AlertContextK.Provider>
|
<AlertContextK value={hook}>{p.children}</AlertContextK>
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open}
|
open={open}
|
||||||
@ -67,5 +67,5 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useAlert(): AlertContext {
|
export function useAlert(): AlertContext {
|
||||||
return React.useContext(AlertContextK)!;
|
return React.use(AlertContextK)!;
|
||||||
}
|
}
|
||||||
|
@ -59,13 +59,13 @@ export function ConfirmDialogProvider(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ConfirmContextK.Provider value={hook}>
|
<ConfirmContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</ConfirmContextK.Provider>
|
</ConfirmContextK>
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open}
|
open={open}
|
||||||
onClose={() => handleClose(false)}
|
onClose={() => { handleClose(false); }}
|
||||||
aria-labelledby="alert-dialog-title"
|
aria-labelledby="alert-dialog-title"
|
||||||
aria-describedby="alert-dialog-description"
|
aria-describedby="alert-dialog-description"
|
||||||
>
|
>
|
||||||
@ -76,10 +76,10 @@ export function ConfirmDialogProvider(
|
|||||||
</DialogContentText>
|
</DialogContentText>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={() => handleClose(false)} autoFocus>
|
<Button onClick={() => { handleClose(false); }} autoFocus>
|
||||||
{cancelButton ?? "Cancel"}
|
{cancelButton ?? "Cancel"}
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={() => handleClose(true)} color="error">
|
<Button onClick={() => { handleClose(true); }} color="error">
|
||||||
{confirmButton ?? "Confirm"}
|
{confirmButton ?? "Confirm"}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
@ -89,5 +89,5 @@ export function ConfirmDialogProvider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useConfirm(): ConfirmContext {
|
export function useConfirm(): ConfirmContext {
|
||||||
return React.useContext(ConfirmContextK)!;
|
return React.use(ConfirmContextK)!;
|
||||||
}
|
}
|
||||||
|
@ -6,10 +6,10 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import React, { PropsWithChildren } from "react";
|
import React, { PropsWithChildren } from "react";
|
||||||
|
|
||||||
type LoadingMessageContext = {
|
interface LoadingMessageContext {
|
||||||
show: (message: string) => void;
|
show: (message: string) => void;
|
||||||
hide: () => void;
|
hide: () => void;
|
||||||
};
|
}
|
||||||
|
|
||||||
const LoadingMessageContextK =
|
const LoadingMessageContextK =
|
||||||
React.createContext<LoadingMessageContext | null>(null);
|
React.createContext<LoadingMessageContext | null>(null);
|
||||||
@ -34,9 +34,9 @@ export function LoadingMessageProvider(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<LoadingMessageContextK.Provider value={hook}>
|
<LoadingMessageContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</LoadingMessageContextK.Provider>
|
</LoadingMessageContextK>
|
||||||
|
|
||||||
<Dialog open={open}>
|
<Dialog open={open}>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
@ -60,5 +60,5 @@ export function LoadingMessageProvider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useLoadingMessage(): LoadingMessageContext {
|
export function useLoadingMessage(): LoadingMessageContext {
|
||||||
return React.useContext(LoadingMessageContextK)!;
|
return React.use(LoadingMessageContextK)!;
|
||||||
}
|
}
|
||||||
|
@ -24,9 +24,9 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SnackbarContextK.Provider value={hook}>
|
<SnackbarContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</SnackbarContextK.Provider>
|
</SnackbarContextK>
|
||||||
|
|
||||||
<Snackbar
|
<Snackbar
|
||||||
open={open}
|
open={open}
|
||||||
@ -39,5 +39,5 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useSnackbar(): SnackbarContext {
|
export function useSnackbar(): SnackbarContext {
|
||||||
return React.useContext(SnackbarContextK)!;
|
return React.use(SnackbarContextK)!;
|
||||||
}
|
}
|
||||||
|
@ -3,17 +3,44 @@ import "@fontsource/roboto/400.css";
|
|||||||
import "@fontsource/roboto/500.css";
|
import "@fontsource/roboto/500.css";
|
||||||
import "@fontsource/roboto/700.css";
|
import "@fontsource/roboto/700.css";
|
||||||
|
|
||||||
|
import { ThemeProvider, createTheme } from "@mui/material";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom/client";
|
import ReactDOM from "react-dom/client";
|
||||||
import { App } from "./App";
|
import { App } from "./App";
|
||||||
import "./index.css";
|
|
||||||
import reportWebVitals from "./reportWebVitals";
|
|
||||||
import { LoadServerConfig } from "./widgets/LoadServerConfig";
|
|
||||||
import { ThemeProvider, createTheme } from "@mui/material";
|
|
||||||
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
|
|
||||||
import { AlertDialogProvider } from "./hooks/providers/AlertDialogProvider";
|
import { AlertDialogProvider } from "./hooks/providers/AlertDialogProvider";
|
||||||
import { SnackbarProvider } from "./hooks/providers/SnackbarProvider";
|
|
||||||
import { ConfirmDialogProvider } from "./hooks/providers/ConfirmDialogProvider";
|
import { ConfirmDialogProvider } from "./hooks/providers/ConfirmDialogProvider";
|
||||||
|
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
|
||||||
|
import { SnackbarProvider } from "./hooks/providers/SnackbarProvider";
|
||||||
|
import "./index.css";
|
||||||
|
import { LoadServerConfig } from "./widgets/LoadServerConfig";
|
||||||
|
|
||||||
|
import { loader } from "@monaco-editor/react";
|
||||||
|
import * as monaco from "monaco-editor";
|
||||||
|
import EditorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
|
||||||
|
import { configureMonacoYaml } from "monaco-yaml";
|
||||||
|
import YamlWorker from "monaco-yaml/yaml.worker?worker";
|
||||||
|
|
||||||
|
// This allows to use a self hosted instance of Monaco editor
|
||||||
|
loader.config({ monaco });
|
||||||
|
|
||||||
|
// Add YAML support to Monaco
|
||||||
|
configureMonacoYaml(monaco, {
|
||||||
|
enableSchemaRequest: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// YAML worker
|
||||||
|
window.MonacoEnvironment = {
|
||||||
|
getWorker(_moduleId, label) {
|
||||||
|
switch (label) {
|
||||||
|
case "editorWorkerService":
|
||||||
|
return new EditorWorker();
|
||||||
|
case "yaml":
|
||||||
|
return new YamlWorker();
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown label ${label}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const darkTheme = createTheme({
|
const darkTheme = createTheme({
|
||||||
palette: {
|
palette: {
|
||||||
@ -21,9 +48,7 @@ const darkTheme = createTheme({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const root = ReactDOM.createRoot(
|
const root = ReactDOM.createRoot(document.getElementById("root")!);
|
||||||
document.getElementById("root") as HTMLElement
|
|
||||||
);
|
|
||||||
root.render(
|
root.render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<ThemeProvider theme={darkTheme}>
|
<ThemeProvider theme={darkTheme}>
|
||||||
@ -41,8 +66,3 @@ root.render(
|
|||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</React.StrictMode>
|
</React.StrictMode>
|
||||||
);
|
);
|
||||||
|
|
||||||
// If you want to start measuring performance in your app, pass a function
|
|
||||||
// to log results (for example: reportWebVitals(console.log))
|
|
||||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
|
||||||
reportWebVitals();
|
|
||||||
|
@ -1,15 +0,0 @@
|
|||||||
import { ReportHandler } from 'web-vitals';
|
|
||||||
|
|
||||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
|
||||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
|
||||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
|
||||||
getCLS(onPerfEntry);
|
|
||||||
getFID(onPerfEntry);
|
|
||||||
getFCP(onPerfEntry);
|
|
||||||
getLCP(onPerfEntry);
|
|
||||||
getTTFB(onPerfEntry);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default reportWebVitals;
|
|
417
virtweb_frontend/src/routes/DiskImagesRoute.tsx
Normal file
417
virtweb_frontend/src/routes/DiskImagesRoute.tsx
Normal file
@ -0,0 +1,417 @@
|
|||||||
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
import DownloadIcon from "@mui/icons-material/Download";
|
||||||
|
import LoopIcon from "@mui/icons-material/Loop";
|
||||||
|
import MoreVertIcon from "@mui/icons-material/MoreVert";
|
||||||
|
import RefreshIcon from "@mui/icons-material/Refresh";
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
CircularProgress,
|
||||||
|
IconButton,
|
||||||
|
LinearProgress,
|
||||||
|
ListItemIcon,
|
||||||
|
ListItemText,
|
||||||
|
Menu,
|
||||||
|
MenuItem,
|
||||||
|
Tooltip,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { DataGrid, GridColDef } from "@mui/x-data-grid";
|
||||||
|
import { filesize } from "filesize";
|
||||||
|
import React from "react";
|
||||||
|
import { DiskImage, DiskImageApi } from "../api/DiskImageApi";
|
||||||
|
import { ServerApi } from "../api/ServerApi";
|
||||||
|
import { ConvertDiskImageDialog } from "../dialogs/ConvertDiskImageDialog";
|
||||||
|
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
||||||
|
import { useConfirm } from "../hooks/providers/ConfirmDialogProvider";
|
||||||
|
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
||||||
|
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||||
|
import { downloadBlob } from "../utils/FilesUtils";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { DateWidget } from "../widgets/DateWidget";
|
||||||
|
import { FileInput } from "../widgets/forms/FileInput";
|
||||||
|
import { VirtWebPaper } from "../widgets/VirtWebPaper";
|
||||||
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
|
||||||
|
export function DiskImagesRoute(): React.ReactElement {
|
||||||
|
const [list, setList] = React.useState<DiskImage[] | undefined>();
|
||||||
|
|
||||||
|
const loadKey = React.useRef(1);
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setList(await DiskImageApi.GetList());
|
||||||
|
};
|
||||||
|
|
||||||
|
const reload = () => {
|
||||||
|
loadKey.current += 1;
|
||||||
|
setList(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebRouteContainer
|
||||||
|
label="Disk images management"
|
||||||
|
actions={
|
||||||
|
<span>
|
||||||
|
<Tooltip title="Refresh Disk images list">
|
||||||
|
<IconButton onClick={reload}>
|
||||||
|
<RefreshIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={loadKey.current}
|
||||||
|
errMsg="Failed to load disk images list!"
|
||||||
|
load={load}
|
||||||
|
ready={list !== undefined}
|
||||||
|
build={() => (
|
||||||
|
<>
|
||||||
|
<UploadDiskImageCard onFileUploaded={reload} />
|
||||||
|
<DiskImageList list={list!} onReload={reload} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UploadDiskImageCard(p: {
|
||||||
|
onFileUploaded: () => void;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
|
||||||
|
const [value, setValue] = React.useState<File | null>(null);
|
||||||
|
const [uploadProgress, setUploadProgress] = React.useState<number | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleChange = (newValue: File | null) => {
|
||||||
|
if (
|
||||||
|
newValue &&
|
||||||
|
newValue.size > ServerApi.Config.constraints.disk_image_max_size
|
||||||
|
) {
|
||||||
|
alert(
|
||||||
|
`The file is too big (max size allowed: ${filesize(
|
||||||
|
ServerApi.Config.constraints.disk_image_max_size
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
newValue &&
|
||||||
|
newValue.type.length > 0 &&
|
||||||
|
!ServerApi.Config.disk_images_mimetypes.includes(newValue.type)
|
||||||
|
) {
|
||||||
|
alert(`Selected file mimetype is not allowed! (${newValue.type})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setValue(newValue);
|
||||||
|
};
|
||||||
|
|
||||||
|
const upload = async () => {
|
||||||
|
try {
|
||||||
|
setUploadProgress(0);
|
||||||
|
await DiskImageApi.Upload(value!, setUploadProgress);
|
||||||
|
|
||||||
|
setValue(null);
|
||||||
|
snackbar("The file was successfully uploaded!");
|
||||||
|
|
||||||
|
p.onFileUploaded();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
await alert(`Failed to perform file upload! ${e}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploadProgress(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (uploadProgress !== null) {
|
||||||
|
return (
|
||||||
|
<VirtWebPaper label="File upload" noHorizontalMargin>
|
||||||
|
<Typography variant="body1">
|
||||||
|
Upload in progress ({Math.floor(uploadProgress * 100)}%)...
|
||||||
|
</Typography>
|
||||||
|
<LinearProgress variant="determinate" value={uploadProgress * 100} />
|
||||||
|
</VirtWebPaper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebPaper label="Disk image upload" noHorizontalMargin>
|
||||||
|
<div style={{ display: "flex", alignItems: "center" }}>
|
||||||
|
<FileInput
|
||||||
|
value={value}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
slotProps={{
|
||||||
|
htmlInput: {
|
||||||
|
accept: ServerApi.Config.disk_images_mimetypes.join(","),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{value && <Button onClick={upload}>Upload</Button>}
|
||||||
|
</div>
|
||||||
|
</VirtWebPaper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DiskImageList(p: {
|
||||||
|
list: DiskImage[];
|
||||||
|
onReload: () => void;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const loadingMessage = useLoadingMessage();
|
||||||
|
|
||||||
|
const [dlProgress, setDlProgress] = React.useState<undefined | number>();
|
||||||
|
|
||||||
|
const [currConversion, setCurrConversion] = React.useState<
|
||||||
|
DiskImage | undefined
|
||||||
|
>();
|
||||||
|
|
||||||
|
// Download disk image file
|
||||||
|
const downloadDiskImage = async (entry: DiskImage) => {
|
||||||
|
setDlProgress(0);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const blob = await DiskImageApi.Download(entry, setDlProgress);
|
||||||
|
|
||||||
|
downloadBlob(blob, entry.file_name);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to download disk image file! ${e}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
setDlProgress(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Convert disk image file
|
||||||
|
const convertDiskImage = (entry: DiskImage) => {
|
||||||
|
setCurrConversion(entry);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Delete disk image
|
||||||
|
const deleteDiskImage = async (entry: DiskImage) => {
|
||||||
|
if (
|
||||||
|
!(await confirm(
|
||||||
|
`Do you really want to delete this disk image (${entry.file_name}) ?`
|
||||||
|
))
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
|
||||||
|
loadingMessage.show("Deleting disk image file...");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await DiskImageApi.Delete(entry);
|
||||||
|
snackbar("The disk image has been successfully deleted!");
|
||||||
|
p.onReload();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to delete disk image!\n${e}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
loadingMessage.hide();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (p.list.length === 0)
|
||||||
|
return (
|
||||||
|
<Typography variant="body1" style={{ textAlign: "center" }}>
|
||||||
|
No disk image uploaded for now.
|
||||||
|
</Typography>
|
||||||
|
);
|
||||||
|
|
||||||
|
const columns: GridColDef<(typeof p.list)[number]>[] = [
|
||||||
|
{ field: "file_name", headerName: "File name", flex: 3, editable: true },
|
||||||
|
{
|
||||||
|
field: "format",
|
||||||
|
headerName: "Format",
|
||||||
|
flex: 1,
|
||||||
|
renderCell(params) {
|
||||||
|
let content = params.row.format;
|
||||||
|
|
||||||
|
if (params.row.format === "Raw") {
|
||||||
|
content += params.row.is_sparse ? " (Sparse)" : " (Fixed)";
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "file_size",
|
||||||
|
headerName: "File size",
|
||||||
|
flex: 1,
|
||||||
|
renderCell(params) {
|
||||||
|
let res = filesize(params.row.file_size);
|
||||||
|
|
||||||
|
if (params.row.format === "QCow2") {
|
||||||
|
res += ` (${filesize(params.row.virtual_size!)})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "created",
|
||||||
|
headerName: "Created",
|
||||||
|
flex: 1,
|
||||||
|
renderCell(params) {
|
||||||
|
return <DateWidget time={params.row.created} />;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "actions",
|
||||||
|
type: "actions",
|
||||||
|
headerName: "",
|
||||||
|
width: 55,
|
||||||
|
cellClassName: "actions",
|
||||||
|
editable: false,
|
||||||
|
getActions: (params) => {
|
||||||
|
return [
|
||||||
|
<DiskImageActionMenu
|
||||||
|
key="menu"
|
||||||
|
diskImage={params.row}
|
||||||
|
onDownload={downloadDiskImage}
|
||||||
|
onConvert={convertDiskImage}
|
||||||
|
onDelete={deleteDiskImage}
|
||||||
|
/>,
|
||||||
|
];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Download notification */}
|
||||||
|
{dlProgress !== undefined && (
|
||||||
|
<Alert severity="info">
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="body1">
|
||||||
|
Downloading... {dlProgress}%
|
||||||
|
</Typography>
|
||||||
|
<CircularProgress
|
||||||
|
variant="determinate"
|
||||||
|
size={"1.5rem"}
|
||||||
|
style={{ marginLeft: "10px" }}
|
||||||
|
value={dlProgress}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Disk image conversion dialog */}
|
||||||
|
{currConversion && (
|
||||||
|
<ConvertDiskImageDialog
|
||||||
|
image={currConversion}
|
||||||
|
onCancel={() => {
|
||||||
|
setCurrConversion(undefined);
|
||||||
|
}}
|
||||||
|
onFinished={() => {
|
||||||
|
setCurrConversion(undefined);
|
||||||
|
p.onReload();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* The table itself */}
|
||||||
|
<DataGrid<DiskImage>
|
||||||
|
getRowId={(c) => c.file_name}
|
||||||
|
rows={p.list}
|
||||||
|
columns={columns}
|
||||||
|
processRowUpdate={async (n, o) => {
|
||||||
|
try {
|
||||||
|
await DiskImageApi.Rename(o, n.file_name);
|
||||||
|
return n;
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to rename disk image!", e);
|
||||||
|
alert(`Failed to rename disk image! ${e}`);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
p.onReload();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DiskImageActionMenu(p: {
|
||||||
|
diskImage: DiskImage;
|
||||||
|
onDownload: (d: DiskImage) => void;
|
||||||
|
onConvert: (d: DiskImage) => void;
|
||||||
|
onDelete: (d: DiskImage) => void;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||||
|
const open = Boolean(anchorEl);
|
||||||
|
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||||
|
setAnchorEl(event.currentTarget);
|
||||||
|
};
|
||||||
|
const handleClose = () => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Actions"
|
||||||
|
aria-haspopup="true"
|
||||||
|
onClick={handleClick}
|
||||||
|
>
|
||||||
|
<MoreVertIcon />
|
||||||
|
</IconButton>
|
||||||
|
<Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
|
||||||
|
{/* Download disk image */}
|
||||||
|
<MenuItem
|
||||||
|
onClick={() => {
|
||||||
|
handleClose();
|
||||||
|
p.onDownload(p.diskImage);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ListItemIcon>
|
||||||
|
<DownloadIcon />
|
||||||
|
</ListItemIcon>
|
||||||
|
<ListItemText secondary={"Download disk image"}>
|
||||||
|
Download
|
||||||
|
</ListItemText>
|
||||||
|
</MenuItem>
|
||||||
|
|
||||||
|
{/* Convert disk image */}
|
||||||
|
<MenuItem
|
||||||
|
onClick={() => {
|
||||||
|
handleClose();
|
||||||
|
p.onConvert(p.diskImage);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ListItemIcon>
|
||||||
|
<LoopIcon />
|
||||||
|
</ListItemIcon>
|
||||||
|
<ListItemText secondary={"Convert disk image"}>Convert</ListItemText>
|
||||||
|
</MenuItem>
|
||||||
|
|
||||||
|
{/* Delete disk image */}
|
||||||
|
<MenuItem
|
||||||
|
onClick={() => {
|
||||||
|
handleClose();
|
||||||
|
p.onDelete(p.diskImage);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ListItemIcon>
|
||||||
|
<DeleteIcon color="error" />
|
||||||
|
</ListItemIcon>
|
||||||
|
<ListItemText secondary={"Delete disk image"}>Delete</ListItemText>
|
||||||
|
</MenuItem>
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
161
virtweb_frontend/src/routes/EditAPITokenRoute.tsx
Normal file
161
virtweb_frontend/src/routes/EditAPITokenRoute.tsx
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
import { Button } from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
APIToken,
|
||||||
|
APITokenURL,
|
||||||
|
CreatedAPIToken,
|
||||||
|
TokensApi,
|
||||||
|
} from "../api/TokensApi";
|
||||||
|
import { CreatedTokenDialog } from "../dialogs/CreatedTokenDialog";
|
||||||
|
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
||||||
|
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
||||||
|
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||||
|
import { time } from "../utils/DateUtils";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
import {
|
||||||
|
APITokenDetails,
|
||||||
|
TokenWidgetStatus,
|
||||||
|
} from "../widgets/tokens/APITokenDetails";
|
||||||
|
|
||||||
|
export function CreateApiTokenRoute(): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [createdToken, setCreatedToken] = React.useState<
|
||||||
|
CreatedAPIToken | undefined
|
||||||
|
>();
|
||||||
|
|
||||||
|
const [token] = React.useState<APIToken>({
|
||||||
|
id: "",
|
||||||
|
name: "",
|
||||||
|
description: "",
|
||||||
|
created: time(),
|
||||||
|
updated: time(),
|
||||||
|
last_used: time(),
|
||||||
|
rights: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const createApiToken = async (n: APIToken) => {
|
||||||
|
try {
|
||||||
|
const res = await TokensApi.Create(n);
|
||||||
|
snackbar("The api token was successfully created!");
|
||||||
|
setCreatedToken(res);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to create API token!\n${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{createdToken && <CreatedTokenDialog createdToken={createdToken} />}
|
||||||
|
|
||||||
|
<EditApiTokenRouteInner
|
||||||
|
token={token}
|
||||||
|
creating={true}
|
||||||
|
onCancel={() => navigate("/tokens")}
|
||||||
|
onSave={createApiToken}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditApiTokenRoute(): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
|
||||||
|
const { id } = useParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [token, setToken] = React.useState<APIToken | undefined>();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setToken(await TokensApi.GetSingle(id!));
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateApiToken = async (n: APIToken) => {
|
||||||
|
try {
|
||||||
|
await TokensApi.Update(n);
|
||||||
|
snackbar("The token was successfully updated!");
|
||||||
|
navigate(APITokenURL(token!));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to update token!\n${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={id}
|
||||||
|
ready={token !== undefined}
|
||||||
|
errMsg="Failed to fetch API token informations!"
|
||||||
|
load={load}
|
||||||
|
build={() => (
|
||||||
|
<EditApiTokenRouteInner
|
||||||
|
token={token!}
|
||||||
|
creating={false}
|
||||||
|
onCancel={() => navigate(`/token/${id}`)}
|
||||||
|
onSave={updateApiToken}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditApiTokenRouteInner(p: {
|
||||||
|
token: APIToken;
|
||||||
|
creating: boolean;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSave: (token: APIToken) => Promise<void>;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const loadingMessage = useLoadingMessage();
|
||||||
|
|
||||||
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
|
const [, updateState] = React.useState<any>();
|
||||||
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
|
const valueChanged = () => {
|
||||||
|
setChanged(true);
|
||||||
|
forceUpdate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
loadingMessage.show("Saving API token configuration...");
|
||||||
|
await p.onSave(p.token);
|
||||||
|
loadingMessage.hide();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebRouteContainer
|
||||||
|
label={p.creating ? "Create an API Token" : "Edit API Token"}
|
||||||
|
actions={
|
||||||
|
<span>
|
||||||
|
{changed && (
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={save}
|
||||||
|
style={{ marginRight: "10px" }}
|
||||||
|
>
|
||||||
|
{p.creating ? "Create" : "Save"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button onClick={p.onCancel} variant="outlined">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<APITokenDetails
|
||||||
|
token={p.token}
|
||||||
|
status={
|
||||||
|
p.creating ? TokenWidgetStatus.Create : TokenWidgetStatus.Update
|
||||||
|
}
|
||||||
|
onChange={valueChanged}
|
||||||
|
/>
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
);
|
||||||
|
}
|
@ -99,7 +99,7 @@ function EditNetworkFilterRouteInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
@ -97,7 +97,7 @@ function EditNetworkRouteInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
@ -15,7 +15,7 @@ export function CreateVMRoute(): React.ReactElement {
|
|||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const [vm, setVM] = React.useState(VMInfo.NewEmpty);
|
const [vm, setVM] = React.useState(VMInfo.NewEmpty());
|
||||||
|
|
||||||
const create = async (v: VMInfo) => {
|
const create = async (v: VMInfo) => {
|
||||||
try {
|
try {
|
||||||
@ -103,7 +103,9 @@ function EditVMInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => {
|
||||||
|
updateState({});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
import DownloadIcon from "@mui/icons-material/Download";
|
||||||
|
import MenuBookIcon from "@mui/icons-material/MenuBook";
|
||||||
|
import RefreshIcon from "@mui/icons-material/Refresh";
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
@ -9,24 +12,25 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import DownloadIcon from "@mui/icons-material/Download";
|
|
||||||
import { DataGrid, GridColDef } from "@mui/x-data-grid";
|
import { DataGrid, GridColDef } from "@mui/x-data-grid";
|
||||||
import { filesize } from "filesize";
|
import { filesize } from "filesize";
|
||||||
import { MuiFileInput } from "mui-file-input";
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { IsoFile, IsoFilesApi } from "../api/IsoFilesApi";
|
import { IsoFile, IsoFilesApi } from "../api/IsoFilesApi";
|
||||||
import { ServerApi } from "../api/ServerApi";
|
import { ServerApi } from "../api/ServerApi";
|
||||||
|
import { IsoCatalogDialog } from "../dialogs/IsoCatalogDialog";
|
||||||
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
||||||
|
import { useConfirm } from "../hooks/providers/ConfirmDialogProvider";
|
||||||
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
||||||
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||||
|
import { downloadBlob } from "../utils/FilesUtils";
|
||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { FileInput } from "../widgets/forms/FileInput";
|
||||||
import { VirtWebPaper } from "../widgets/VirtWebPaper";
|
import { VirtWebPaper } from "../widgets/VirtWebPaper";
|
||||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
import { useConfirm } from "../hooks/providers/ConfirmDialogProvider";
|
|
||||||
import { downloadBlob } from "../utils/FilesUtils";
|
|
||||||
|
|
||||||
export function IsoFilesRoute(): React.ReactElement {
|
export function IsoFilesRoute(): React.ReactElement {
|
||||||
const [list, setList] = React.useState<IsoFile[] | undefined>();
|
const [list, setList] = React.useState<IsoFile[] | undefined>();
|
||||||
|
const [isoCatalog, setIsoCatalog] = React.useState(false);
|
||||||
|
|
||||||
const loadKey = React.useRef(1);
|
const loadKey = React.useRef(1);
|
||||||
|
|
||||||
@ -40,19 +44,41 @@ export function IsoFilesRoute(): React.ReactElement {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AsyncWidget
|
<>
|
||||||
loadKey={loadKey.current}
|
<AsyncWidget
|
||||||
errMsg="Failed to load ISO files list!"
|
loadKey={loadKey.current}
|
||||||
load={load}
|
errMsg="Failed to load ISO files list!"
|
||||||
ready={list !== undefined}
|
load={load}
|
||||||
build={() => (
|
ready={list !== undefined}
|
||||||
<VirtWebRouteContainer label="ISO files management">
|
build={() => (
|
||||||
<UploadIsoFileCard onFileUploaded={reload} />
|
<VirtWebRouteContainer
|
||||||
<UploadIsoFileFromUrlCard onFileUploaded={reload} />
|
label="ISO files management"
|
||||||
<IsoFilesList list={list!} onReload={reload} />
|
actions={
|
||||||
</VirtWebRouteContainer>
|
<span>
|
||||||
)}
|
<Tooltip title="Open the ISO catalog">
|
||||||
/>
|
<IconButton onClick={() => { setIsoCatalog(true); }}>
|
||||||
|
<MenuBookIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="Refresh ISO list">
|
||||||
|
<IconButton onClick={reload}>
|
||||||
|
<RefreshIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<UploadIsoFileCard onFileUploaded={reload} />
|
||||||
|
<UploadIsoFileFromUrlCard onFileUploaded={reload} />
|
||||||
|
<IsoFilesList list={list!} onReload={reload} />
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<IsoCatalogDialog
|
||||||
|
open={isoCatalog}
|
||||||
|
onClose={() => { setIsoCatalog(false); }}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,7 +122,7 @@ function UploadIsoFileCard(p: {
|
|||||||
p.onFileUploaded();
|
p.onFileUploaded();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
await alert("Failed to perform file upload! " + e);
|
await alert(`Failed to perform file upload! ${e}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
setUploadProgress(null);
|
setUploadProgress(null);
|
||||||
@ -104,7 +130,7 @@ function UploadIsoFileCard(p: {
|
|||||||
|
|
||||||
if (uploadProgress !== null) {
|
if (uploadProgress !== null) {
|
||||||
return (
|
return (
|
||||||
<VirtWebPaper label="File upload">
|
<VirtWebPaper label="File upload" noHorizontalMargin>
|
||||||
<Typography variant="body1">
|
<Typography variant="body1">
|
||||||
Upload in progress ({Math.floor(uploadProgress * 100)}%)...
|
Upload in progress ({Math.floor(uploadProgress * 100)}%)...
|
||||||
</Typography>
|
</Typography>
|
||||||
@ -114,13 +140,15 @@ function UploadIsoFileCard(p: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VirtWebPaper label="File upload">
|
<VirtWebPaper label="File upload" noHorizontalMargin>
|
||||||
<div style={{ display: "flex", alignItems: "center" }}>
|
<div style={{ display: "flex", alignItems: "center" }}>
|
||||||
<MuiFileInput
|
<FileInput
|
||||||
value={value}
|
value={value}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
inputProps={{ accept: ServerApi.Config.iso_mimetypes.join(",") }}
|
slotProps={{
|
||||||
|
htmlInput: { accept: ServerApi.Config.iso_mimetypes.join(",") },
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{value && <Button onClick={upload}>Upload file</Button>}
|
{value && <Button onClick={upload}>Upload file</Button>}
|
||||||
@ -147,6 +175,8 @@ function UploadIsoFileFromUrlCard(p: {
|
|||||||
loadingMessage.show("Downloading file from URL...");
|
loadingMessage.show("Downloading file from URL...");
|
||||||
await IsoFilesApi.UploadFromURL(url, actualFileName);
|
await IsoFilesApi.UploadFromURL(url, actualFileName);
|
||||||
|
|
||||||
|
p.onFileUploaded();
|
||||||
|
|
||||||
setURL("");
|
setURL("");
|
||||||
setFilename(null);
|
setFilename(null);
|
||||||
snackbar("Successfully downloaded file!");
|
snackbar("Successfully downloaded file!");
|
||||||
@ -158,20 +188,24 @@ function UploadIsoFileFromUrlCard(p: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VirtWebPaper label="File upload from URL">
|
<VirtWebPaper label="File upload from URL" noHorizontalMargin>
|
||||||
<div style={{ display: "flex", alignItems: "center" }}>
|
<div style={{ display: "flex", alignItems: "center" }}>
|
||||||
<TextField
|
<TextField
|
||||||
label="URL"
|
label="URL"
|
||||||
value={url}
|
value={url}
|
||||||
style={{ flex: 3 }}
|
style={{ flex: 3 }}
|
||||||
onChange={(e) => setURL(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setURL(e.target.value);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<span style={{ width: "10px" }}></span>
|
<span style={{ width: "10px" }}></span>
|
||||||
<TextField
|
<TextField
|
||||||
label="Filename"
|
label="Filename"
|
||||||
value={actualFileName}
|
value={actualFileName}
|
||||||
style={{ flex: 2 }}
|
style={{ flex: 2 }}
|
||||||
onChange={(e) => setFilename(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setFilename(e.target.value);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
{url !== "" && actualFileName !== "" && (
|
{url !== "" && actualFileName !== "" && (
|
||||||
<Button onClick={upload}>Upload file</Button>
|
<Button onClick={upload}>Upload file</Button>
|
||||||
@ -198,7 +232,7 @@ function IsoFilesList(p: {
|
|||||||
try {
|
try {
|
||||||
const blob = await IsoFilesApi.Download(entry, setDlProgress);
|
const blob = await IsoFilesApi.Download(entry, setDlProgress);
|
||||||
|
|
||||||
await downloadBlob(blob, entry.filename);
|
downloadBlob(blob, entry.filename);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
alert("Failed to download iso file!");
|
alert("Failed to download iso file!");
|
||||||
@ -236,7 +270,7 @@ function IsoFilesList(p: {
|
|||||||
</Typography>
|
</Typography>
|
||||||
);
|
);
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef<IsoFile>[] = [
|
||||||
{ field: "filename", headerName: "File name", flex: 3 },
|
{ field: "filename", headerName: "File name", flex: 3 },
|
||||||
{
|
{
|
||||||
field: "size",
|
field: "size",
|
||||||
@ -271,39 +305,31 @@ function IsoFilesList(p: {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<VirtWebPaper label="Files list">
|
{/* Download notification */}
|
||||||
{/* Download notification */}
|
{dlProgress !== undefined && (
|
||||||
{dlProgress !== undefined && (
|
<Alert severity="info">
|
||||||
<Alert severity="info">
|
<div
|
||||||
<div
|
style={{
|
||||||
style={{
|
display: "flex",
|
||||||
display: "flex",
|
flexDirection: "row",
|
||||||
flexDirection: "row",
|
alignItems: "center",
|
||||||
alignItems: "center",
|
overflow: "hidden",
|
||||||
overflow: "hidden",
|
}}
|
||||||
}}
|
>
|
||||||
>
|
<Typography variant="body1">
|
||||||
<Typography variant="body1">
|
Downloading... {dlProgress}%
|
||||||
Downloading... {dlProgress}%
|
</Typography>
|
||||||
</Typography>
|
<CircularProgress
|
||||||
<CircularProgress
|
variant="determinate"
|
||||||
variant="determinate"
|
size={"1.5rem"}
|
||||||
size={"1.5rem"}
|
style={{ marginLeft: "10px" }}
|
||||||
style={{ marginLeft: "10px" }}
|
value={dlProgress}
|
||||||
value={dlProgress}
|
/>
|
||||||
/>
|
</div>
|
||||||
</div>
|
</Alert>
|
||||||
</Alert>
|
)}
|
||||||
)}
|
{/* ISO files list table */}
|
||||||
|
<DataGrid getRowId={(c) => c.filename} rows={p.list} columns={columns} />
|
||||||
{/* Files list table */}
|
|
||||||
<DataGrid
|
|
||||||
getRowId={(c) => c.filename}
|
|
||||||
rows={p.list}
|
|
||||||
columns={columns}
|
|
||||||
autoHeight={true}
|
|
||||||
/>
|
|
||||||
</VirtWebPaper>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -66,7 +66,7 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
|
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
|
||||||
|
|
||||||
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
|
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
|
||||||
}, [visibleFilters]);
|
}, [visibleFilters, p.list]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VirtWebRouteContainer
|
<VirtWebRouteContainer
|
||||||
@ -78,7 +78,9 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
size="small"
|
size="small"
|
||||||
value={visibleFilters}
|
value={visibleFilters}
|
||||||
exclusive
|
exclusive
|
||||||
onChange={(_ev, v) => setVisibleFilters(v)}
|
onChange={(_ev, v) => {
|
||||||
|
setVisibleFilters(v);
|
||||||
|
}}
|
||||||
aria-label="visible filters"
|
aria-label="visible filters"
|
||||||
>
|
>
|
||||||
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
|
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
|
||||||
@ -130,8 +132,8 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<ul>
|
<ul>
|
||||||
{t.join_filters.map((f, n) => (
|
{t.join_filters.map((f) => (
|
||||||
<li key={n}>{f}</li>
|
<li key={f}>{f}</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
|
||||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
@ -13,12 +12,13 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
import { NetworkApi, NetworkInfo, NetworkURL } from "../api/NetworksApi";
|
import { NetworkApi, NetworkInfo, NetworkURL } from "../api/NetworksApi";
|
||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
import { RouterLink } from "../widgets/RouterLink";
|
import { RouterLink } from "../widgets/RouterLink";
|
||||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
import { NetworkHookStatusWidget } from "../widgets/net/NetworkHookStatusWidget";
|
||||||
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";
|
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
|
|
||||||
export function NetworksListRoute(): React.ReactElement {
|
export function NetworksListRoute(): React.ReactElement {
|
||||||
const [list, setList] = React.useState<NetworkInfo[] | undefined>();
|
const [list, setList] = React.useState<NetworkInfo[] | undefined>();
|
||||||
@ -54,6 +54,8 @@ function NetworksListRouteInner(p: {
|
|||||||
</RouterLink>
|
</RouterLink>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<NetworkHookStatusWidget hiddenIfInstalled />
|
||||||
|
|
||||||
<TableContainer component={Paper}>
|
<TableContainer component={Paper}>
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead>
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user