Compare commits
260 Commits
Author | SHA1 | Date | |
---|---|---|---|
96f35520a0 | |||
490560e0c6 | |||
52f53d8280 | |||
27b8a3f671 | |||
abf9b6da42 | |||
0c9209b04c | |||
edebd52374 | |||
61205f00fb | |||
a303e00289 | |||
af9f72e9d8 | |||
5176346b30 | |||
731eeef25b | |||
a65e3e4bc0 | |||
027eb2bbe6 | |||
6982a54701 | |||
035c40e638 | |||
79c535955d | |||
8b7f8d3f3d | |||
866c859a1e | |||
23e4e90540 | |||
a4fa3fc241 | |||
81d10c3b37 | |||
f1e2904150 | |||
23f9503a31 | |||
a0ef68b93c | |||
6b127e6ea0 | |||
5e17dbf2bb | |||
dfb04575ad | |||
6f2626ae19 | |||
37e60ddcde | |||
05cdc05347 | |||
6364115b4b | |||
2133cd9103 | |||
01f84fcce1 | |||
08b3823025 | |||
968a0ab261 | |||
21b552848a | |||
fd19256470 | |||
1ed022576c | |||
f6aa7b38bf | |||
fdfcb74d67 | |||
98afc7b152 | |||
0d08fceeb9 | |||
3c945d73c2 | |||
58fcbf5ab7 | |||
3a3f31c947 | |||
8fc63287df | |||
172473e4de | |||
76f549debb | |||
c9097ff801 | |||
fb01fd3af6 | |||
fa4bcbcad0 | |||
189cdb7427 | |||
874bd5454d | |||
b649887e9a | |||
8c62c15f56 | |||
51ac17b56e | |||
fc5a012068 | |||
5e293f1315 | |||
87367decf2 | |||
f792220dd4 | |||
97030c9407 | |||
5d1d0f5d6c | |||
294466ee61 | |||
c100fe9108 | |||
e754da3ac2 | |||
bc1e52bc38 | |||
6f0073bbb5 | |||
2decf85d6e | |||
1d8f849457 | |||
beb07279b6 | |||
8c6854c8fd | |||
57f472d9bb | |||
94ffca10a2 | |||
0a274ab0a0 | |||
c0026563b0 | |||
e411924c7c | |||
709c15abaa | |||
b404e4d930 | |||
f507580c3f | |||
291b786076 | |||
06c9059dac | |||
d7c6ad60dd | |||
0a0ba0785b | |||
6ed79592f2 | |||
4c75ee3471 | |||
6f997da8cd | |||
03e40aa4ee | |||
be1d6cbcc6 | |||
ffaca016ad | |||
71f82a98d7 | |||
deef6fbc0c | |||
4ac529141f | |||
a108a2e967 | |||
ff7a29104c | |||
240b2ffb9b | |||
a86e703661 | |||
1ecf4e6d20 | |||
9f9a661b1a | |||
1b1cab8321 | |||
f4f9a503de | |||
a4971d5f90 | |||
477ebe6b78 | |||
38efbfc148 | |||
10052ea644 | |||
b57619ea29 | |||
445b0043b2 | |||
8b62cbe752 | |||
81f99362d9 | |||
414c23facb | |||
c5608cf86c | |||
5d08c750ef | |||
f3fde36beb | |||
0c83e8891e | |||
133de2dd1f | |||
c8219747f0 | |||
0247f794e9 | |||
710f787c41 | |||
d8916a326c | |||
924d6d4072 | |||
984ac33d5c | |||
0a4dfd63c9 | |||
a6e746f652 | |||
30f73fa2e0 | |||
9f0ee346e9 | |||
48d6dede4a | |||
8432e4a655 | |||
b35eb0a175 | |||
c3a1b34ed3 | |||
bb26843cd6 | |||
ee0ab12dd0 | |||
d5f7755467 | |||
5c64e83b1e | |||
0f6f99b4ec | |||
f668862ae0 | |||
c960d2b501 | |||
f5d9f2534b | |||
9a3ddcea33 | |||
030464d3a9 | |||
3f30b32c2e | |||
5eafe6aabc | |||
2c9f274efa | |||
31112c79ac | |||
d89f91b538 | |||
a6310ec294 | |||
98d9323534 | |||
09f1f28800 | |||
e1da9ca4bb | |||
625c7bfc0b | |||
d9503950e3 | |||
376e927980 | |||
5204cbcf0f | |||
e373dcc564 | |||
137a6ebcad | |||
ed1329ecf7 | |||
2371c1e371 | |||
63c07d950c | |||
a3cdb19e33 | |||
4623cd6497 | |||
ab81bb13ad | |||
616650a198 | |||
78763d21b1 | |||
f2d6324958 | |||
6e880f19cc | |||
64623f329e | |||
407f3fb994 | |||
0eb0c4bd63 | |||
82422c115a | |||
ed2beb334d | |||
f3b4820d06 | |||
8f7cd96df4 | |||
4accbc5853 | |||
2791318ff1 | |||
47208b4147 | |||
b783591fb5 | |||
9dd6175808 | |||
5e8b97178e | |||
38260cddf5 | |||
80b0423d54 | |||
b690bb69eb | |||
8a40e22691 | |||
f5c6a2c956 | |||
6d5803399b | |||
3896f80cb3 | |||
60d2a6157a | |||
b83b12cf80 | |||
86847f487b | |||
1b03910dea | |||
435a6c5e0a | |||
1f4befe136 | |||
7f0f366675 | |||
362e69610c | |||
bad26df102 | |||
790627b4bf | |||
6de14a55ed | |||
8b24c6880a | |||
5174956548 | |||
d669a739b2 | |||
c7fa61619e | |||
009a04f8d0 | |||
0953044cfb | |||
d923671a7b | |||
db8a606707 | |||
b614b29bea | |||
65595e169f | |||
10db4717f1 | |||
1d9d2f0f7c | |||
ad53c1d6dd | |||
beeadb8a4b | |||
b997524912 | |||
cc4a9d250a | |||
6227b9bab0 | |||
f608e74c8b | |||
08379a21d1 | |||
8f1d972149 | |||
b59c308219 | |||
0224c3c273 | |||
f0609851fc | |||
dbd45a72c3 | |||
4c979d5450 | |||
35c80d696f | |||
6823fdc7f9 | |||
3323798b54 | |||
67fd09791f | |||
1b37ebf6f6 | |||
043406d662 | |||
61db0851d6 | |||
ad54df3178 | |||
71103afd69 | |||
6465d809cd | |||
ae8635c307 | |||
e0100d618e | |||
455e5f7110 | |||
c26c9390ff | |||
9e45e03aef | |||
e144810d73 | |||
3c2dd8ad05 | |||
91e3b38da4 | |||
9d79cec4d5 | |||
4935681cf4 | |||
669fa672d9 | |||
a797583535 | |||
54ed1b2a71 | |||
8e12e86f0b | |||
fe7bdc9d29 | |||
546b6a23df | |||
4fdf13f95f | |||
385681c9ab | |||
be99df2767 | |||
30200b5c4a | |||
f47c1d3a2f | |||
6e545d0058 | |||
84006f98b2 | |||
42ca9e918a | |||
ea93bea7bf | |||
0081903f7c | |||
c53797f627 | |||
e1d367df47 | |||
71f413cd27 | |||
48aa2b93b7 |
16
Cargo.toml
@ -1,7 +1,16 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "proxmox-backup"
|
name = "proxmox-backup"
|
||||||
version = "0.9.5"
|
version = "1.0.5"
|
||||||
authors = ["Dietmar Maurer <dietmar@proxmox.com>"]
|
authors = [
|
||||||
|
"Dietmar Maurer <dietmar@proxmox.com>",
|
||||||
|
"Dominik Csapak <d.csapak@proxmox.com>",
|
||||||
|
"Christian Ebner <c.ebner@proxmox.com>",
|
||||||
|
"Fabian Grünbichler <f.gruenbichler@proxmox.com>",
|
||||||
|
"Stefan Reiter <s.reiter@proxmox.com>",
|
||||||
|
"Thomas Lamprecht <t.lamprecht@proxmox.com>",
|
||||||
|
"Wolfgang Bumiller <w.bumiller@proxmox.com>",
|
||||||
|
"Proxmox Support Team <support@proxmox.com>",
|
||||||
|
]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
license = "AGPL-3"
|
license = "AGPL-3"
|
||||||
description = "Proxmox Backup"
|
description = "Proxmox Backup"
|
||||||
@ -37,8 +46,9 @@ pam = "0.7"
|
|||||||
pam-sys = "0.5"
|
pam-sys = "0.5"
|
||||||
percent-encoding = "2.1"
|
percent-encoding = "2.1"
|
||||||
pin-utils = "0.1.0"
|
pin-utils = "0.1.0"
|
||||||
|
pin-project = "0.4"
|
||||||
pathpatterns = "0.1.2"
|
pathpatterns = "0.1.2"
|
||||||
proxmox = { version = "0.7.0", features = [ "sortable-macro", "api-macro", "websocket" ] }
|
proxmox = { version = "0.7.2", features = [ "sortable-macro", "api-macro", "websocket" ] }
|
||||||
#proxmox = { git = "git://git.proxmox.com/git/proxmox", version = "0.1.2", features = [ "sortable-macro", "api-macro" ] }
|
#proxmox = { git = "git://git.proxmox.com/git/proxmox", version = "0.1.2", features = [ "sortable-macro", "api-macro" ] }
|
||||||
#proxmox = { path = "../proxmox/proxmox", features = [ "sortable-macro", "api-macro", "websocket" ] }
|
#proxmox = { path = "../proxmox/proxmox", features = [ "sortable-macro", "api-macro", "websocket" ] }
|
||||||
proxmox-fuse = "0.1.0"
|
proxmox-fuse = "0.1.0"
|
||||||
|
149
debian/changelog
vendored
@ -1,3 +1,152 @@
|
|||||||
|
rust-proxmox-backup (1.0.5-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* client: restore: print meta information exclusively to standard error
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Wed, 25 Nov 2020 15:29:58 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (1.0.4-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* fingerprint: add bytes() accessor
|
||||||
|
|
||||||
|
* ui: fix broken gettext use
|
||||||
|
|
||||||
|
* cli: move more commands into "snapshot" sub-command
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Wed, 25 Nov 2020 06:37:41 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (1.0.3-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* client: inform user when automatically using the default encryption key
|
||||||
|
|
||||||
|
* ui: UserView: render name as 'Firstname Lastname'
|
||||||
|
|
||||||
|
* proxmox-backup-manager: add versions command
|
||||||
|
|
||||||
|
* pxar: fix anchored exclusion at archive root
|
||||||
|
|
||||||
|
* pxar: include .pxarexclude files in the archive
|
||||||
|
|
||||||
|
* client: expose all-file-systems option
|
||||||
|
|
||||||
|
* api: make expensive parts of datastore status opt-in
|
||||||
|
|
||||||
|
* api: include datastore ID in invalid owner errors
|
||||||
|
|
||||||
|
* garbage collection: treat .bad files like regular chunks to ensure they
|
||||||
|
are removed if not referenced anymore
|
||||||
|
|
||||||
|
* client: fix issues with encoded UPID strings
|
||||||
|
|
||||||
|
* encryption: add fingerprint to key config
|
||||||
|
|
||||||
|
* client: add 'key show' command
|
||||||
|
|
||||||
|
* fix #3139: add key fingerprint to backup snapshot manifest and check it
|
||||||
|
when loading with a key
|
||||||
|
|
||||||
|
* ui: add snapshot/file fingerprint tooltip
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Tue, 24 Nov 2020 08:55:47 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (1.0.1-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* ui: datastore summary: drop 'removed bytes' display
|
||||||
|
|
||||||
|
* ui: datastore add: set default schedule
|
||||||
|
|
||||||
|
* prune sim: make backup schedule a form, bind update button to its validity
|
||||||
|
|
||||||
|
* daemon: add workaround for race in reloading and systemd 'ready' notification
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Wed, 11 Nov 2020 10:18:12 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (1.0.0-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* fix #3121: forbid removing used remotes
|
||||||
|
|
||||||
|
* docs: backup-client: encryption: discuss paperkey command
|
||||||
|
|
||||||
|
* pxar: log when skipping mount points
|
||||||
|
|
||||||
|
* ui: show also parent ACLs which affect a datastore in its panel
|
||||||
|
|
||||||
|
* api: node/apt: add versions call
|
||||||
|
|
||||||
|
* ui: make Datastore a selectable panel again. Show a datastore summary
|
||||||
|
list, and provide unfiltered access to all sync and verify jobs.
|
||||||
|
|
||||||
|
* ui: add help tool-button to various paneös
|
||||||
|
|
||||||
|
* ui: set various onlineHelp buttons
|
||||||
|
|
||||||
|
* zfs: mount new zpools created via API under /mnt/datastore/<id>
|
||||||
|
|
||||||
|
* ui: move disks/directory views to its own tab panel
|
||||||
|
|
||||||
|
* fix #3060: continue sync if we cannot aquire the group lock
|
||||||
|
|
||||||
|
* HttpsConnector: include destination on connect errors
|
||||||
|
|
||||||
|
* fix #3060:: improve get_owner error handling
|
||||||
|
|
||||||
|
* remote.cfg: rename userid to 'auth-id'
|
||||||
|
|
||||||
|
* verify: log/warn on invalid owner
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Tue, 10 Nov 2020 14:36:13 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (0.9.7-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* ui: add remote store selector
|
||||||
|
|
||||||
|
* tools/daemon: fix reload with open connections
|
||||||
|
|
||||||
|
* pxar/create: fix endless loop for shrinking files
|
||||||
|
|
||||||
|
* pxar/create: handle ErrorKind::Interrupted for file reads
|
||||||
|
|
||||||
|
* ui: add action-button for changing backup group owner
|
||||||
|
|
||||||
|
* docs: add interactive prune simulator
|
||||||
|
|
||||||
|
* verify: fix unprivileged verification jobs
|
||||||
|
|
||||||
|
* tasks: allow access to job tasks
|
||||||
|
|
||||||
|
* drop internal 'backup@pam' owner, sync jobs need to set a explicit owner
|
||||||
|
|
||||||
|
* api: datastore: allow to set "verify-new" option over API
|
||||||
|
|
||||||
|
* ui: datastore: add Options tab, allowing one to change per-datastore
|
||||||
|
notification and verify-new options
|
||||||
|
|
||||||
|
* docs: scroll navigation bar to current active section
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Mon, 09 Nov 2020 07:36:58 +0100
|
||||||
|
|
||||||
|
rust-proxmox-backup (0.9.6-1) unstable; urgency=medium
|
||||||
|
|
||||||
|
* fix #3106: improve queueing new incoming connections
|
||||||
|
|
||||||
|
* fix #2870: sync: ensure a updated ticket is used, if available
|
||||||
|
|
||||||
|
* proxy: log if there are too many open connections
|
||||||
|
|
||||||
|
* ui: SyncJobEdit: fix sending 'delete' values on SyncJob creation
|
||||||
|
|
||||||
|
* datastore config: allow to configure who receives job notify emails
|
||||||
|
|
||||||
|
* ui: fix task description for log rotate
|
||||||
|
|
||||||
|
* proxy: also rotate auth.log file
|
||||||
|
|
||||||
|
* ui: add shell panel under administration
|
||||||
|
|
||||||
|
* ui: sync jobs: only set default schedule when creating new jobs and some
|
||||||
|
other small fixes
|
||||||
|
|
||||||
|
-- Proxmox Support Team <support@proxmox.com> Wed, 04 Nov 2020 19:12:57 +0100
|
||||||
|
|
||||||
rust-proxmox-backup (0.9.5-1) unstable; urgency=medium
|
rust-proxmox-backup (0.9.5-1) unstable; urgency=medium
|
||||||
|
|
||||||
* ui: user menu: allow one to change the language while staying logged in
|
* ui: user menu: allow one to change the language while staying logged in
|
||||||
|
14
debian/control
vendored
@ -33,11 +33,12 @@ Build-Depends: debhelper (>= 11),
|
|||||||
librust-pam-sys-0.5+default-dev,
|
librust-pam-sys-0.5+default-dev,
|
||||||
librust-pathpatterns-0.1+default-dev (>= 0.1.2-~~),
|
librust-pathpatterns-0.1+default-dev (>= 0.1.2-~~),
|
||||||
librust-percent-encoding-2+default-dev (>= 2.1-~~),
|
librust-percent-encoding-2+default-dev (>= 2.1-~~),
|
||||||
|
librust-pin-project-0.4+default-dev,
|
||||||
librust-pin-utils-0.1+default-dev,
|
librust-pin-utils-0.1+default-dev,
|
||||||
librust-proxmox-0.7+api-macro-dev,
|
librust-proxmox-0.7+api-macro-dev (>= 0.7.2-~~),
|
||||||
librust-proxmox-0.7+default-dev,
|
librust-proxmox-0.7+default-dev (>= 0.7.2-~~),
|
||||||
librust-proxmox-0.7+sortable-macro-dev,
|
librust-proxmox-0.7+sortable-macro-dev (>= 0.7.2-~~),
|
||||||
librust-proxmox-0.7+websocket-dev,
|
librust-proxmox-0.7+websocket-dev (>= 0.7.2-~~),
|
||||||
librust-proxmox-fuse-0.1+default-dev,
|
librust-proxmox-fuse-0.1+default-dev,
|
||||||
librust-pxar-0.6+default-dev (>= 0.6.1-~~),
|
librust-pxar-0.6+default-dev (>= 0.6.1-~~),
|
||||||
librust-pxar-0.6+futures-io-dev (>= 0.6.1-~~),
|
librust-pxar-0.6+futures-io-dev (>= 0.6.1-~~),
|
||||||
@ -78,7 +79,7 @@ Build-Depends: debhelper (>= 11),
|
|||||||
uuid-dev,
|
uuid-dev,
|
||||||
debhelper (>= 12~),
|
debhelper (>= 12~),
|
||||||
bash-completion,
|
bash-completion,
|
||||||
pve-eslint,
|
pve-eslint (>= 7.12.1-1),
|
||||||
python3-docutils,
|
python3-docutils,
|
||||||
python3-pygments,
|
python3-pygments,
|
||||||
rsync,
|
rsync,
|
||||||
@ -104,7 +105,9 @@ Depends: fonts-font-awesome,
|
|||||||
libjs-extjs (>= 6.0.1),
|
libjs-extjs (>= 6.0.1),
|
||||||
libzstd1 (>= 1.3.8),
|
libzstd1 (>= 1.3.8),
|
||||||
lvm2,
|
lvm2,
|
||||||
|
openssh-server,
|
||||||
pbs-i18n,
|
pbs-i18n,
|
||||||
|
postfix | mail-transport-agent,
|
||||||
proxmox-backup-docs,
|
proxmox-backup-docs,
|
||||||
proxmox-mini-journalreader,
|
proxmox-mini-journalreader,
|
||||||
proxmox-widget-toolkit (>= 2.3-6),
|
proxmox-widget-toolkit (>= 2.3-6),
|
||||||
@ -113,6 +116,7 @@ Depends: fonts-font-awesome,
|
|||||||
${misc:Depends},
|
${misc:Depends},
|
||||||
${shlibs:Depends},
|
${shlibs:Depends},
|
||||||
Recommends: zfsutils-linux,
|
Recommends: zfsutils-linux,
|
||||||
|
ifupdown2,
|
||||||
Description: Proxmox Backup Server daemon with tools and GUI
|
Description: Proxmox Backup Server daemon with tools and GUI
|
||||||
This package contains the Proxmox Backup Server daemons and related
|
This package contains the Proxmox Backup Server daemons and related
|
||||||
tools. This includes a web-based graphical user interface.
|
tools. This includes a web-based graphical user interface.
|
||||||
|
3
debian/control.in
vendored
@ -4,7 +4,9 @@ Depends: fonts-font-awesome,
|
|||||||
libjs-extjs (>= 6.0.1),
|
libjs-extjs (>= 6.0.1),
|
||||||
libzstd1 (>= 1.3.8),
|
libzstd1 (>= 1.3.8),
|
||||||
lvm2,
|
lvm2,
|
||||||
|
openssh-server,
|
||||||
pbs-i18n,
|
pbs-i18n,
|
||||||
|
postfix | mail-transport-agent,
|
||||||
proxmox-backup-docs,
|
proxmox-backup-docs,
|
||||||
proxmox-mini-journalreader,
|
proxmox-mini-journalreader,
|
||||||
proxmox-widget-toolkit (>= 2.3-6),
|
proxmox-widget-toolkit (>= 2.3-6),
|
||||||
@ -13,6 +15,7 @@ Depends: fonts-font-awesome,
|
|||||||
${misc:Depends},
|
${misc:Depends},
|
||||||
${shlibs:Depends},
|
${shlibs:Depends},
|
||||||
Recommends: zfsutils-linux,
|
Recommends: zfsutils-linux,
|
||||||
|
ifupdown2,
|
||||||
Description: Proxmox Backup Server daemon with tools and GUI
|
Description: Proxmox Backup Server daemon with tools and GUI
|
||||||
This package contains the Proxmox Backup Server daemons and related
|
This package contains the Proxmox Backup Server daemons and related
|
||||||
tools. This includes a web-based graphical user interface.
|
tools. This includes a web-based graphical user interface.
|
||||||
|
2
debian/debcargo.toml
vendored
@ -14,7 +14,7 @@ section = "admin"
|
|||||||
build_depends = [
|
build_depends = [
|
||||||
"debhelper (>= 12~)",
|
"debhelper (>= 12~)",
|
||||||
"bash-completion",
|
"bash-completion",
|
||||||
"pve-eslint",
|
"pve-eslint (>= 7.12.1-1)",
|
||||||
"python3-docutils",
|
"python3-docutils",
|
||||||
"python3-pygments",
|
"python3-pygments",
|
||||||
"rsync",
|
"rsync",
|
||||||
|
2
debian/lintian-overrides
vendored
@ -1,2 +1,2 @@
|
|||||||
proxmox-backup-server: package-installs-apt-sources etc/apt/sources.list.d/pbstest-beta.list
|
proxmox-backup-server: package-installs-apt-sources etc/apt/sources.list.d/pbs-enterprise.list
|
||||||
proxmox-backup-server: systemd-service-file-refers-to-unusual-wantedby-target lib/systemd/system/proxmox-backup-banner.service getty.target
|
proxmox-backup-server: systemd-service-file-refers-to-unusual-wantedby-target lib/systemd/system/proxmox-backup-banner.service getty.target
|
||||||
|
12
debian/postinst
vendored
@ -25,6 +25,18 @@ case "$1" in
|
|||||||
sed -i '/^\s\+verify-schedule /d' /etc/proxmox-backup/datastore.cfg || true
|
sed -i '/^\s\+verify-schedule /d' /etc/proxmox-backup/datastore.cfg || true
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
if dpkg --compare-versions "$2" 'le' '0.9.5-1'; then
|
||||||
|
chown --quiet backup:backup /var/log/proxmox-backup/api/auth.log || true
|
||||||
|
fi
|
||||||
|
if dpkg --compare-versions "$2" 'le' '0.9.7-1'; then
|
||||||
|
if [ -e /etc/proxmox-backup/remote.cfg ]; then
|
||||||
|
echo "NOTE: Switching over remote.cfg to new field names.."
|
||||||
|
flock -w 30 /etc/proxmox-backup/.remote.lck \
|
||||||
|
sed -i \
|
||||||
|
-e 's/^\s\+userid /\tauth-id /g' \
|
||||||
|
/etc/proxmox-backup/remote.cfg || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
# FIXME: Remove in future version once we're sure no broken entries remain in anyone's files
|
# FIXME: Remove in future version once we're sure no broken entries remain in anyone's files
|
||||||
if grep -q -e ':termproxy::[^@]\+: ' /var/log/proxmox-backup/tasks/active; then
|
if grep -q -e ':termproxy::[^@]\+: ' /var/log/proxmox-backup/tasks/active; then
|
||||||
|
1
debian/proxmox-backup-docs.links
vendored
@ -1 +1,2 @@
|
|||||||
/usr/share/doc/proxmox-backup/proxmox-backup.pdf /usr/share/doc/proxmox-backup/html/proxmox-backup.pdf
|
/usr/share/doc/proxmox-backup/proxmox-backup.pdf /usr/share/doc/proxmox-backup/html/proxmox-backup.pdf
|
||||||
|
/usr/share/javascript/extjs /usr/share/doc/proxmox-backup/html/prune-simulator/extjs
|
||||||
|
2
debian/proxmox-backup-server.install
vendored
@ -3,7 +3,7 @@ etc/proxmox-backup.service /lib/systemd/system/
|
|||||||
etc/proxmox-backup-banner.service /lib/systemd/system/
|
etc/proxmox-backup-banner.service /lib/systemd/system/
|
||||||
etc/proxmox-backup-daily-update.service /lib/systemd/system/
|
etc/proxmox-backup-daily-update.service /lib/systemd/system/
|
||||||
etc/proxmox-backup-daily-update.timer /lib/systemd/system/
|
etc/proxmox-backup-daily-update.timer /lib/systemd/system/
|
||||||
etc/pbstest-beta.list /etc/apt/sources.list.d/
|
etc/pbs-enterprise.list /etc/apt/sources.list.d/
|
||||||
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-api
|
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-api
|
||||||
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-proxy
|
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-proxy
|
||||||
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-banner
|
usr/lib/x86_64-linux-gnu/proxmox-backup/proxmox-backup-banner
|
||||||
|
1
debian/proxmox-backup-server.maintscript
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
rm_conffile /etc/apt/sources.list.d/pbstest-beta.list 1.0.0~ proxmox-backup-server
|
@ -14,6 +14,11 @@ MANUAL_PAGES := \
|
|||||||
proxmox-backup-client.1 \
|
proxmox-backup-client.1 \
|
||||||
proxmox-backup-manager.1
|
proxmox-backup-manager.1
|
||||||
|
|
||||||
|
PRUNE_SIMULATOR_FILES := \
|
||||||
|
prune-simulator/index.html \
|
||||||
|
prune-simulator/documentation.html \
|
||||||
|
prune-simulator/clear-trigger.png \
|
||||||
|
prune-simulator/prune-simulator.js
|
||||||
|
|
||||||
# Sphinx documentation setup
|
# Sphinx documentation setup
|
||||||
SPHINXOPTS =
|
SPHINXOPTS =
|
||||||
@ -74,10 +79,11 @@ onlinehelpinfo:
|
|||||||
@echo "Build finished. OnlineHelpInfo.js is in $(BUILDDIR)/scanrefs."
|
@echo "Build finished. OnlineHelpInfo.js is in $(BUILDDIR)/scanrefs."
|
||||||
|
|
||||||
.PHONY: html
|
.PHONY: html
|
||||||
html: ${GENERATED_SYNOPSIS} images/proxmox-logo.svg custom.css conf.py
|
html: ${GENERATED_SYNOPSIS} images/proxmox-logo.svg custom.css conf.py ${PRUNE_SIMULATOR_FILES}
|
||||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||||
cp images/proxmox-logo.svg $(BUILDDIR)/html/_static/
|
install -m 0644 custom.js custom.css images/proxmox-logo.svg $(BUILDDIR)/html/_static/
|
||||||
cp custom.css $(BUILDDIR)/html/_static/
|
install -dm 0755 $(BUILDDIR)/html/prune-simulator
|
||||||
|
install -m 0644 ${PRUNE_SIMULATOR_FILES} $(BUILDDIR)/html/prune-simulator
|
||||||
@echo
|
@echo
|
||||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@ def scan_extjs_files(wwwdir="../www"): # a bit rough i know, but we can optimize
|
|||||||
js_files.append(os.path.join(root, filename))
|
js_files.append(os.path.join(root, filename))
|
||||||
for js_file in js_files:
|
for js_file in js_files:
|
||||||
fd = open(js_file).read()
|
fd = open(js_file).read()
|
||||||
allmatch = re.findall("onlineHelp:\s*[\'\"](.*?)[\'\"]", fd, re.M)
|
allmatch = re.findall("(?:onlineHelp:|get_help_tool\s*\()\s*[\'\"](.*?)[\'\"]", fd, re.M)
|
||||||
for match in allmatch:
|
for match in allmatch:
|
||||||
anchor = match
|
anchor = match
|
||||||
anchor = re.sub('_', '-', anchor) # normalize labels
|
anchor = re.sub('_', '-', anchor) # normalize labels
|
||||||
@ -73,7 +73,9 @@ class ReflabelMapper(Builder):
|
|||||||
'link': '/docs/index.html',
|
'link': '/docs/index.html',
|
||||||
'title': 'Proxmox Backup Server Documentation Index',
|
'title': 'Proxmox Backup Server Documentation Index',
|
||||||
}
|
}
|
||||||
self.env.used_anchors = scan_extjs_files()
|
# Disabled until we find a sensible way to scan proxmox-widget-toolkit
|
||||||
|
# as well
|
||||||
|
#self.env.used_anchors = scan_extjs_files()
|
||||||
|
|
||||||
if not os.path.isdir(self.outdir):
|
if not os.path.isdir(self.outdir):
|
||||||
os.mkdir(self.outdir)
|
os.mkdir(self.outdir)
|
||||||
@ -93,6 +95,9 @@ class ReflabelMapper(Builder):
|
|||||||
logger.info('traversing section {}'.format(title.astext()))
|
logger.info('traversing section {}'.format(title.astext()))
|
||||||
ref_name = getattr(title, 'rawsource', title.astext())
|
ref_name = getattr(title, 'rawsource', title.astext())
|
||||||
|
|
||||||
|
if (ref_name[:7] == ':term:`'):
|
||||||
|
ref_name = ref_name[7:-1]
|
||||||
|
|
||||||
self.env.online_help[labelid] = {'link': '', 'title': ''}
|
self.env.online_help[labelid] = {'link': '', 'title': ''}
|
||||||
self.env.online_help[labelid]['link'] = "/docs/" + os.path.basename(filename_html) + "#{}".format(labelid)
|
self.env.online_help[labelid]['link'] = "/docs/" + os.path.basename(filename_html) + "#{}".format(labelid)
|
||||||
self.env.online_help[labelid]['title'] = ref_name
|
self.env.online_help[labelid]['title'] = ref_name
|
||||||
@ -112,15 +117,18 @@ class ReflabelMapper(Builder):
|
|||||||
def validate_anchors(self):
|
def validate_anchors(self):
|
||||||
#pprint(self.env.online_help)
|
#pprint(self.env.online_help)
|
||||||
to_remove = []
|
to_remove = []
|
||||||
for anchor in self.env.used_anchors:
|
|
||||||
if anchor not in self.env.online_help:
|
# Disabled until we find a sensible way to scan proxmox-widget-toolkit
|
||||||
logger.info("[-] anchor {} is missing from onlinehelp!".format(anchor))
|
# as well
|
||||||
for anchor in self.env.online_help:
|
#for anchor in self.env.used_anchors:
|
||||||
if anchor not in self.env.used_anchors and anchor != 'pbs_documentation_index':
|
# if anchor not in self.env.online_help:
|
||||||
logger.info("[*] anchor {} not used! deleting...".format(anchor))
|
# logger.info("[-] anchor {} is missing from onlinehelp!".format(anchor))
|
||||||
to_remove.append(anchor)
|
#for anchor in self.env.online_help:
|
||||||
for anchor in to_remove:
|
# if anchor not in self.env.used_anchors and anchor != 'pbs_documentation_index':
|
||||||
self.env.online_help.pop(anchor, None)
|
# logger.info("[*] anchor {} not used! deleting...".format(anchor))
|
||||||
|
# to_remove.append(anchor)
|
||||||
|
#for anchor in to_remove:
|
||||||
|
# self.env.online_help.pop(anchor, None)
|
||||||
return
|
return
|
||||||
|
|
||||||
def finish(self):
|
def finish(self):
|
||||||
|
@ -365,9 +365,22 @@ To set up a master key:
|
|||||||
backed up. It can happen, for example, that you back up an entire system, using
|
backed up. It can happen, for example, that you back up an entire system, using
|
||||||
a key on that system. If the system then becomes inaccessible for any reason
|
a key on that system. If the system then becomes inaccessible for any reason
|
||||||
and needs to be restored, this will not be possible as the encryption key will be
|
and needs to be restored, this will not be possible as the encryption key will be
|
||||||
lost along with the broken system. In preparation for the worst case scenario,
|
lost along with the broken system.
|
||||||
you should consider keeping a paper copy of this key locked away in
|
|
||||||
a safe place.
|
It is recommended that you keep your master key safe, but easily accessible, in
|
||||||
|
order for quick disaster recovery. For this reason, the best place to store it
|
||||||
|
is in your password manager, where it is immediately recoverable. As a backup to
|
||||||
|
this, you should also save the key to a USB drive and store that in a secure
|
||||||
|
place. This way, it is detached from any system, but is still easy to recover
|
||||||
|
from, in case of emergency. Finally, in preparation for the worst case scenario,
|
||||||
|
you should also consider keeping a paper copy of your master key locked away in
|
||||||
|
a safe place. The ``paperkey`` subcommand can be used to create a QR encoded
|
||||||
|
version of your master key. The following command sends the output of the
|
||||||
|
``paperkey`` command to a text file, for easy printing.
|
||||||
|
|
||||||
|
.. code-block:: console
|
||||||
|
|
||||||
|
proxmox-backup-client key paperkey --output-format text > qrkey.txt
|
||||||
|
|
||||||
|
|
||||||
Restoring Data
|
Restoring Data
|
||||||
@ -379,11 +392,11 @@ periodic recovery tests to ensure that you can access the data in
|
|||||||
case of problems.
|
case of problems.
|
||||||
|
|
||||||
First, you need to find the snapshot which you want to restore. The snapshot
|
First, you need to find the snapshot which you want to restore. The snapshot
|
||||||
command provides a list of all the snapshots on the server:
|
list command provides a list of all the snapshots on the server:
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
# proxmox-backup-client snapshots
|
# proxmox-backup-client snapshot list
|
||||||
┌────────────────────────────────┬─────────────┬────────────────────────────────────┐
|
┌────────────────────────────────┬─────────────┬────────────────────────────────────┐
|
||||||
│ snapshot │ size │ files │
|
│ snapshot │ size │ files │
|
||||||
╞════════════════════════════════╪═════════════╪════════════════════════════════════╡
|
╞════════════════════════════════╪═════════════╪════════════════════════════════════╡
|
||||||
@ -535,6 +548,29 @@ To remove the ticket, issue a logout:
|
|||||||
# proxmox-backup-client logout
|
# proxmox-backup-client logout
|
||||||
|
|
||||||
|
|
||||||
|
.. _changing-backup-owner:
|
||||||
|
|
||||||
|
Changing the Owner of a Backup Group
|
||||||
|
------------------------------------
|
||||||
|
|
||||||
|
By default, the owner of a backup group is the user which was used to originally
|
||||||
|
create that backup group (or in the case of sync jobs, ``root@pam``). This
|
||||||
|
means that if a user ``mike@pbs`` created a backup, another user ``john@pbs``
|
||||||
|
can not be used to create backups in that same backup group. In case you want
|
||||||
|
to change the owner of a backup, you can do so with the below command, using a
|
||||||
|
user that has ``Datastore.Modify`` privileges on the datastore.
|
||||||
|
|
||||||
|
.. code-block:: console
|
||||||
|
|
||||||
|
# proxmox-backup-client change-owner vm/103 john@pbs
|
||||||
|
|
||||||
|
This can also be done from within the web interface, by navigating to the
|
||||||
|
`Content` section of the datastore that contains the backup group and
|
||||||
|
selecting the user icon under the `Actions` column. Common cases for this could
|
||||||
|
be to change the owner of a sync job from ``root@pam``, or to repurpose a
|
||||||
|
backup group.
|
||||||
|
|
||||||
|
|
||||||
.. _backup-pruning:
|
.. _backup-pruning:
|
||||||
|
|
||||||
Pruning and Removing Backups
|
Pruning and Removing Backups
|
||||||
@ -545,7 +581,7 @@ command:
|
|||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
# proxmox-backup-client forget <snapshot>
|
# proxmox-backup-client snapshot forget <snapshot>
|
||||||
|
|
||||||
|
|
||||||
.. caution:: This command removes all archives in this backup
|
.. caution:: This command removes all archives in this backup
|
||||||
|
@ -171,6 +171,7 @@ html_theme_options = {
|
|||||||
'extra_nav_links': {
|
'extra_nav_links': {
|
||||||
'Proxmox Homepage': 'https://proxmox.com',
|
'Proxmox Homepage': 'https://proxmox.com',
|
||||||
'PDF': 'proxmox-backup.pdf',
|
'PDF': 'proxmox-backup.pdf',
|
||||||
|
'Prune Simulator' : 'prune-simulator/index.html',
|
||||||
},
|
},
|
||||||
|
|
||||||
'sidebar_width': '320px',
|
'sidebar_width': '320px',
|
||||||
@ -228,6 +229,10 @@ html_favicon = 'images/favicon.ico'
|
|||||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||||
html_static_path = ['_static']
|
html_static_path = ['_static']
|
||||||
|
|
||||||
|
html_js_files = [
|
||||||
|
'custom.js',
|
||||||
|
]
|
||||||
|
|
||||||
# Add any extra paths that contain custom files (such as robots.txt or
|
# Add any extra paths that contain custom files (such as robots.txt or
|
||||||
# .htaccess) here, relative to this directory. These files are copied
|
# .htaccess) here, relative to this directory. These files are copied
|
||||||
# directly to the root of the documentation.
|
# directly to the root of the documentation.
|
||||||
|
7
docs/custom.js
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
window.addEventListener('DOMContentLoaded', (event) => {
|
||||||
|
let activeSection = document.querySelector("a.current");
|
||||||
|
if (activeSection) {
|
||||||
|
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
|
||||||
|
activeSection.scrollIntoView({ block: 'center' });
|
||||||
|
}
|
||||||
|
});
|
@ -27,7 +27,7 @@ How long will my Proxmox Backup Server version be supported?
|
|||||||
+-----------------------+--------------------+---------------+------------+--------------------+
|
+-----------------------+--------------------+---------------+------------+--------------------+
|
||||||
|Proxmox Backup Version | Debian Version | First Release | Debian EOL | Proxmox Backup EOL |
|
|Proxmox Backup Version | Debian Version | First Release | Debian EOL | Proxmox Backup EOL |
|
||||||
+=======================+====================+===============+============+====================+
|
+=======================+====================+===============+============+====================+
|
||||||
|Proxmox Backup 1.x | Debian 10 (Buster) | tba | tba | tba |
|
|Proxmox Backup 1.x | Debian 10 (Buster) | 2020-11 | tba | tba |
|
||||||
+-----------------------+--------------------+---------------+------------+--------------------+
|
+-----------------------+--------------------+---------------+------------+--------------------+
|
||||||
|
|
||||||
|
|
||||||
|
35
docs/gui.rst
@ -4,7 +4,7 @@ Graphical User Interface
|
|||||||
Proxmox Backup Server offers an integrated, web-based interface to manage the
|
Proxmox Backup Server offers an integrated, web-based interface to manage the
|
||||||
server. This means that you can carry out all administration tasks through your
|
server. This means that you can carry out all administration tasks through your
|
||||||
web browser, and that you don't have to worry about installing extra management
|
web browser, and that you don't have to worry about installing extra management
|
||||||
tools. The web interface also provides a built in console, so if you prefer the
|
tools. The web interface also provides a built-in console, so if you prefer the
|
||||||
command line or need some extra control, you have this option.
|
command line or need some extra control, you have this option.
|
||||||
|
|
||||||
The web interface can be accessed via https://youripaddress:8007. The default
|
The web interface can be accessed via https://youripaddress:8007. The default
|
||||||
@ -28,7 +28,6 @@ Login
|
|||||||
-----
|
-----
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-login-window.png
|
.. image:: images/screenshots/pbs-gui-login-window.png
|
||||||
:width: 250
|
|
||||||
:align: right
|
:align: right
|
||||||
:alt: PBS login window
|
:alt: PBS login window
|
||||||
|
|
||||||
@ -44,14 +43,13 @@ GUI Overview
|
|||||||
------------
|
------------
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-dashboard.png
|
.. image:: images/screenshots/pbs-gui-dashboard.png
|
||||||
:width: 250
|
|
||||||
:align: right
|
:align: right
|
||||||
:alt: PBS GUI Dashboard
|
:alt: PBS GUI Dashboard
|
||||||
|
|
||||||
The Proxmox Backup Server web interface consists of 3 main sections:
|
The Proxmox Backup Server web interface consists of 3 main sections:
|
||||||
|
|
||||||
* **Header**: At the top. This shows version information, and contains buttons to view
|
* **Header**: At the top. This shows version information, and contains buttons to view
|
||||||
documentation, monitor running tasks, and logout.
|
documentation, monitor running tasks, set the language and logout.
|
||||||
* **Sidebar**: On the left. This contains the configuration options for
|
* **Sidebar**: On the left. This contains the configuration options for
|
||||||
the server.
|
the server.
|
||||||
* **Configuration Panel**: In the center. This contains the control interface for the
|
* **Configuration Panel**: In the center. This contains the control interface for the
|
||||||
@ -79,18 +77,17 @@ Configuration
|
|||||||
The Configuration section contains some system configuration options, such as
|
The Configuration section contains some system configuration options, such as
|
||||||
time and network configuration. It also contains the following subsections:
|
time and network configuration. It also contains the following subsections:
|
||||||
|
|
||||||
* **User Management**: Add users and manage accounts
|
* **Access Control**: Add and manage users, API tokens, and the permissions
|
||||||
* **Permissions**: Manage permissions for various users
|
associated with these items
|
||||||
* **Remotes**: Add, edit and remove remotes (see :term:`Remote`)
|
* **Remotes**: Add, edit and remove remotes (see :term:`Remote`)
|
||||||
* **Sync Jobs**: Manage and run sync jobs to remotes
|
* **Subscription**: Upload a subscription key, view subscription status and
|
||||||
* **Subscription**: Upload a subscription key and view subscription status
|
access a text-based system report.
|
||||||
|
|
||||||
|
|
||||||
Administration
|
Administration
|
||||||
^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-administration-serverstatus.png
|
.. image:: images/screenshots/pbs-gui-administration-serverstatus.png
|
||||||
:width: 250
|
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Administration: Server Status overview
|
:alt: Administration: Server Status overview
|
||||||
|
|
||||||
@ -105,7 +102,6 @@ tasks and information. These are:
|
|||||||
* **Tasks**: Task history with multiple filter options
|
* **Tasks**: Task history with multiple filter options
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-disks.png
|
.. image:: images/screenshots/pbs-gui-disks.png
|
||||||
:width: 250
|
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Administration: Disks
|
:alt: Administration: Disks
|
||||||
|
|
||||||
@ -120,16 +116,21 @@ The administration menu item also contains a disk management subsection:
|
|||||||
Datastore
|
Datastore
|
||||||
^^^^^^^^^
|
^^^^^^^^^
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-datastore.png
|
.. image:: images/screenshots/pbs-gui-datastore-summary.png
|
||||||
:width: 250
|
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Datastore Configuration
|
:alt: Datastore Configuration
|
||||||
|
|
||||||
The Datastore section provides an interface for creating and managing
|
The Datastore section contains interfaces for creating and managing
|
||||||
datastores. It contains a subsection for each datastore on the system, in
|
datastores. It contains a button to create a new datastore on the server, as
|
||||||
which you can use the top panel to view:
|
well as a subsection for each datastore on the system, in which you can use the
|
||||||
|
top panel to view:
|
||||||
|
|
||||||
|
* **Summary**: Access a range of datastore usage statistics
|
||||||
* **Content**: Information on the datastore's backup groups and their respective
|
* **Content**: Information on the datastore's backup groups and their respective
|
||||||
contents
|
contents
|
||||||
* **Statistics**: Usage statistics for the datastore
|
* **Prune & GC**: Schedule :ref:`pruning <backup-pruning>` and :ref:`garbage
|
||||||
* **Permissions**: View and manage permissions for the datastore
|
collection <garbage-collection>` operations, and run garbage collection
|
||||||
|
manually
|
||||||
|
* **Sync Jobs**: Create, manage and run :ref:`syncjobs` from remote servers
|
||||||
|
* **Verify Jobs**: Create, manage and run :ref:`maintenance_verification` jobs on the
|
||||||
|
datastore
|
||||||
|
Before Width: | Height: | Size: 127 KiB After Width: | Height: | Size: 140 KiB |
BIN
docs/images/screenshots/pbs-gui-apitoken-overview.png
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
docs/images/screenshots/pbs-gui-apitoken-secret-value.png
Normal file
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 33 KiB |
BIN
docs/images/screenshots/pbs-gui-datastore-content.png
Normal file
After Width: | Height: | Size: 90 KiB |
BIN
docs/images/screenshots/pbs-gui-datastore-prunegc.png
Normal file
After Width: | Height: | Size: 66 KiB |
BIN
docs/images/screenshots/pbs-gui-datastore-summary.png
Normal file
After Width: | Height: | Size: 130 KiB |
BIN
docs/images/screenshots/pbs-gui-datastore-verifyjob-add.png
Normal file
After Width: | Height: | Size: 15 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 62 KiB |
@ -9,7 +9,7 @@ Debian_ from the provided package repository.
|
|||||||
|
|
||||||
.. include:: package-repositories.rst
|
.. include:: package-repositories.rst
|
||||||
|
|
||||||
Server installation
|
Server Installation
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
The backup server stores the actual backed up data and provides a web based GUI
|
The backup server stores the actual backed up data and provides a web based GUI
|
||||||
@ -37,22 +37,21 @@ Download the ISO from |DOWNLOADS|.
|
|||||||
It includes the following:
|
It includes the following:
|
||||||
|
|
||||||
* The `Proxmox Backup`_ server installer, which partitions the local
|
* The `Proxmox Backup`_ server installer, which partitions the local
|
||||||
disk(s) with ext4, ext3, xfs or ZFS, and installs the operating
|
disk(s) with ext4, xfs or ZFS, and installs the operating system
|
||||||
system
|
|
||||||
|
|
||||||
* Complete operating system (Debian Linux, 64-bit)
|
* Complete operating system (Debian Linux, 64-bit)
|
||||||
|
|
||||||
* Our Linux kernel with ZFS support
|
* Proxmox Linux kernel with ZFS support
|
||||||
|
|
||||||
* Complete tool-set to administer backups and all necessary resources
|
* Complete tool-set to administer backups and all necessary resources
|
||||||
|
|
||||||
* Web based GUI management interface
|
* Web based management interface
|
||||||
|
|
||||||
.. note:: During the installation process, the complete server
|
.. note:: During the installation process, the complete server
|
||||||
is used by default and all existing data is removed.
|
is used by default and all existing data is removed.
|
||||||
|
|
||||||
|
|
||||||
Install `Proxmox Backup`_ server on Debian
|
Install `Proxmox Backup`_ Server on Debian
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Proxmox ships as a set of Debian packages which can be installed on top of a
|
Proxmox ships as a set of Debian packages which can be installed on top of a
|
||||||
@ -84,11 +83,11 @@ support, and a set of common and useful packages.
|
|||||||
when LVM_ or ZFS_ is used. The network configuration is completely up to you
|
when LVM_ or ZFS_ is used. The network configuration is completely up to you
|
||||||
as well.
|
as well.
|
||||||
|
|
||||||
.. note:: You can access the web interface of the Proxmox Backup Server with
|
.. Note:: You can access the web interface of the Proxmox Backup Server with
|
||||||
your web browser, using HTTPS on port 8007. For example at
|
your web browser, using HTTPS on port 8007. For example at
|
||||||
``https://<ip-or-dns-name>:8007``
|
``https://<ip-or-dns-name>:8007``
|
||||||
|
|
||||||
Install Proxmox Backup server on `Proxmox VE`_
|
Install Proxmox Backup Server on `Proxmox VE`_
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
After configuring the
|
After configuring the
|
||||||
@ -104,14 +103,14 @@ After configuring the
|
|||||||
server to store backups. Should the hypervisor server fail, you can
|
server to store backups. Should the hypervisor server fail, you can
|
||||||
still access the backups.
|
still access the backups.
|
||||||
|
|
||||||
.. note::
|
.. Note:: You can access the web interface of the Proxmox Backup Server with
|
||||||
You can access the web interface of the Proxmox Backup Server with your web
|
your web browser, using HTTPS on port 8007. For example at
|
||||||
browser, using HTTPS on port 8007. For example at ``https://<ip-or-dns-name>:8007``
|
``https://<ip-or-dns-name>:8007``
|
||||||
|
|
||||||
Client installation
|
Client Installation
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
Install `Proxmox Backup`_ client on Debian
|
Install `Proxmox Backup`_ Client on Debian
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Proxmox ships as a set of Debian packages to be installed on
|
Proxmox ships as a set of Debian packages to be installed on
|
||||||
|
@ -127,8 +127,7 @@ language.
|
|||||||
|
|
||||||
-- `The Rust Programming Language <https://doc.rust-lang.org/book/ch00-00-introduction.html>`_
|
-- `The Rust Programming Language <https://doc.rust-lang.org/book/ch00-00-introduction.html>`_
|
||||||
|
|
||||||
.. todo:: further explain the software stack
|
.. _get_help:
|
||||||
|
|
||||||
|
|
||||||
Getting Help
|
Getting Help
|
||||||
------------
|
------------
|
||||||
|
@ -1,13 +1,184 @@
|
|||||||
Maintenance Tasks
|
Maintenance Tasks
|
||||||
=================
|
=================
|
||||||
|
|
||||||
|
.. _maintenance_pruning:
|
||||||
|
|
||||||
|
Pruning
|
||||||
|
-------
|
||||||
|
|
||||||
|
Prune lets you specify which backup snapshots you want to keep. The
|
||||||
|
following retention options are available:
|
||||||
|
|
||||||
|
``keep-last <N>``
|
||||||
|
Keep the last ``<N>`` backup snapshots.
|
||||||
|
|
||||||
|
``keep-hourly <N>``
|
||||||
|
Keep backups for the last ``<N>`` hours. If there is more than one
|
||||||
|
backup for a single hour, only the latest is kept.
|
||||||
|
|
||||||
|
``keep-daily <N>``
|
||||||
|
Keep backups for the last ``<N>`` days. If there is more than one
|
||||||
|
backup for a single day, only the latest is kept.
|
||||||
|
|
||||||
|
``keep-weekly <N>``
|
||||||
|
Keep backups for the last ``<N>`` weeks. If there is more than one
|
||||||
|
backup for a single week, only the latest is kept.
|
||||||
|
|
||||||
|
.. note:: Weeks start on Monday and end on Sunday. The software
|
||||||
|
uses the `ISO week date`_ system and handles weeks at
|
||||||
|
the end of the year correctly.
|
||||||
|
|
||||||
|
``keep-monthly <N>``
|
||||||
|
Keep backups for the last ``<N>`` months. If there is more than one
|
||||||
|
backup for a single month, only the latest is kept.
|
||||||
|
|
||||||
|
``keep-yearly <N>``
|
||||||
|
Keep backups for the last ``<N>`` years. If there is more than one
|
||||||
|
backup for a single year, only the latest is kept.
|
||||||
|
|
||||||
|
The retention options are processed in the order given above. Each option
|
||||||
|
only covers backups within its time period. The next option does not take care
|
||||||
|
of already covered backups. It will only consider older backups.
|
||||||
|
|
||||||
|
Unfinished and incomplete backups will be removed by the prune command unless
|
||||||
|
they are newer than the last successful backup. In this case, the last failed
|
||||||
|
backup is retained.
|
||||||
|
|
||||||
|
Prune Simulator
|
||||||
|
^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
You can use the built-in `prune simulator <prune-simulator/index.html>`_
|
||||||
|
to explore the effect of different retetion options with various backup
|
||||||
|
schedules.
|
||||||
|
|
||||||
|
Manual Pruning
|
||||||
|
^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
.. image:: images/screenshots/pbs-gui-datastore-content-prune-group.png
|
||||||
|
:target: _images/pbs-gui-datastore-content-prune-group.png
|
||||||
|
:align: right
|
||||||
|
:alt: Prune and garbage collection options
|
||||||
|
|
||||||
|
To access pruning functionality for a specific backup group, you can use the
|
||||||
|
prune command line option discussed in :ref:`backup-pruning`, or navigate to
|
||||||
|
the **Content** tab of the datastore and click the scissors icon in the
|
||||||
|
**Actions** column of the relevant backup group.
|
||||||
|
|
||||||
|
Prune Schedules
|
||||||
|
^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
To prune on a datastore level, scheduling options can be found under the
|
||||||
|
**Prune & GC** tab of the datastore. Here you can set retention settings and
|
||||||
|
edit the interval at which pruning takes place.
|
||||||
|
|
||||||
|
.. image:: images/screenshots/pbs-gui-datastore-prunegc.png
|
||||||
|
:target: _images/pbs-gui-datastore-prunegc.png
|
||||||
|
:align: right
|
||||||
|
:alt: Prune and garbage collection options
|
||||||
|
|
||||||
|
|
||||||
|
Retention Settings Example
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
The backup frequency and retention of old backups may depend on how often data
|
||||||
|
changes, and how important an older state may be, in a specific work load.
|
||||||
|
When backups act as a company's document archive, there may also be legal
|
||||||
|
requirements for how long backup snapshots must be kept.
|
||||||
|
|
||||||
|
For this example, we assume that you are doing daily backups, have a retention
|
||||||
|
period of 10 years, and the period between backups stored gradually grows.
|
||||||
|
|
||||||
|
- **keep-last:** ``3`` - even if only daily backups, an admin may want to create
|
||||||
|
an extra one just before or after a big upgrade. Setting keep-last ensures
|
||||||
|
this.
|
||||||
|
|
||||||
|
- **keep-hourly:** not set - for daily backups this is not relevant. You cover
|
||||||
|
extra manual backups already, with keep-last.
|
||||||
|
|
||||||
|
- **keep-daily:** ``13`` - together with keep-last, which covers at least one
|
||||||
|
day, this ensures that you have at least two weeks of backups.
|
||||||
|
|
||||||
|
- **keep-weekly:** ``8`` - ensures that you have at least two full months of
|
||||||
|
weekly backups.
|
||||||
|
|
||||||
|
- **keep-monthly:** ``11`` - together with the previous keep settings, this
|
||||||
|
ensures that you have at least a year of monthly backups.
|
||||||
|
|
||||||
|
- **keep-yearly:** ``9`` - this is for the long term archive. As you covered the
|
||||||
|
current year with the previous options, you would set this to nine for the
|
||||||
|
remaining ones, giving you a total of at least 10 years of coverage.
|
||||||
|
|
||||||
|
We recommend that you use a higher retention period than is minimally required
|
||||||
|
by your environment; you can always reduce it if you find it is unnecessarily
|
||||||
|
high, but you cannot recreate backup snapshots from the past.
|
||||||
|
|
||||||
|
|
||||||
|
.. _maintenance_gc:
|
||||||
|
|
||||||
Garbage Collection
|
Garbage Collection
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
You can monitor and run :ref:`garbage collection <garbage-collection>` on the
|
You can monitor and run :ref:`garbage collection <garbage-collection>` on the
|
||||||
Proxmox Backup Server using the ``garbage-collection`` subcommand of
|
Proxmox Backup Server using the ``garbage-collection`` subcommand of
|
||||||
``proxmox-backup-manager``. You can use the ``start`` subcommand to manually start garbage
|
``proxmox-backup-manager``. You can use the ``start`` subcommand to manually
|
||||||
collection on an entire datastore and the ``status`` subcommand to see
|
start garbage collection on an entire datastore and the ``status`` subcommand to
|
||||||
attributes relating to the :ref:`garbage collection <garbage-collection>`.
|
see attributes relating to the :ref:`garbage collection <garbage-collection>`.
|
||||||
|
|
||||||
.. todo:: Add section on verification
|
This functionality can also be accessed in the GUI, by navigating to **Prune &
|
||||||
|
GC** from the top panel. From here, you can edit the schedule at which garbage
|
||||||
|
collection runs and manually start the operation.
|
||||||
|
|
||||||
|
|
||||||
|
.. _maintenance_verification:
|
||||||
|
|
||||||
|
Verification
|
||||||
|
------------
|
||||||
|
|
||||||
|
.. image:: images/screenshots/pbs-gui-datastore-verifyjob-add.png
|
||||||
|
:target: _images/pbs-gui-datastore-verifyjob-add.png
|
||||||
|
:align: right
|
||||||
|
:alt: Adding a verify job
|
||||||
|
|
||||||
|
Proxmox Backup offers various verification options to ensure that backup data is
|
||||||
|
intact. Verification is generally carried out through the creation of verify
|
||||||
|
jobs. These are scheduled tasks that run verification at a given interval (see
|
||||||
|
:ref:`calendar-events`). With these, you can set whether already verified
|
||||||
|
snapshots are ignored, as well as set a time period, after which verified jobs
|
||||||
|
are checked again. The interface for creating verify jobs can be found under the
|
||||||
|
**Verify Jobs** tab of the datastore.
|
||||||
|
|
||||||
|
.. Note:: It is recommended that you reverify all backups at least monthly, even
|
||||||
|
if a previous verification was successful. This is becuase physical drives
|
||||||
|
are susceptible to damage over time, which can cause an old, working backup
|
||||||
|
to become corrupted in a process known as `bit rot/data degradation
|
||||||
|
<https://en.wikipedia.org/wiki/Data_degradation>`_. It is good practice to
|
||||||
|
have a regularly recurring (hourly/daily) verification job, which checks new
|
||||||
|
and expired backups, then another weekly/monthly job that will reverify
|
||||||
|
everything. This way, there will be no surprises when it comes to restoring
|
||||||
|
data.
|
||||||
|
|
||||||
|
Aside from using verify jobs, you can also run verification manually on entire
|
||||||
|
datastores, backup groups, or snapshots. To do this, navigate to the **Content**
|
||||||
|
tab of the datastore and either click *Verify All*, or select the *V.* icon from
|
||||||
|
the *Actions* column in the table.
|
||||||
|
|
||||||
|
.. _maintenance_notification:
|
||||||
|
|
||||||
|
Notifications
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Proxmox Backup Server can send you notification emails about automatically
|
||||||
|
scheduled verification, garbage-collection and synchronization tasks results.
|
||||||
|
|
||||||
|
By default, notifications are send to the email address configured for the
|
||||||
|
`root@pam` user. You can set that user for each datastore.
|
||||||
|
|
||||||
|
You can also change the level of notification received per task type, the
|
||||||
|
following options are available:
|
||||||
|
|
||||||
|
* Always: send a notification for any scheduled task, independent of the
|
||||||
|
outcome
|
||||||
|
|
||||||
|
* Errors: send a notification for any scheduled task resulting in an error
|
||||||
|
|
||||||
|
* Never: do not send any notification at all
|
||||||
|
@ -59,13 +59,13 @@ Sync Jobs
|
|||||||
:alt: Add a Sync Job
|
:alt: Add a Sync Job
|
||||||
|
|
||||||
Sync jobs are configured to pull the contents of a datastore on a **Remote** to
|
Sync jobs are configured to pull the contents of a datastore on a **Remote** to
|
||||||
a local datastore. You can manage sync jobs under **Configuration -> Sync Jobs**
|
a local datastore. You can manage sync jobs in the web interface, from the
|
||||||
in the web interface, or using the ``proxmox-backup-manager sync-job`` command.
|
**Sync Jobs** tab of the datastore which you'd like to set one up for, or using
|
||||||
The configuration information for sync jobs is stored at
|
the ``proxmox-backup-manager sync-job`` command. The configuration information
|
||||||
``/etc/proxmox-backup/sync.cfg``. To create a new sync job, click the add button
|
for sync jobs is stored at ``/etc/proxmox-backup/sync.cfg``. To create a new
|
||||||
in the GUI, or use the ``create`` subcommand. After creating a sync job, you can
|
sync job, click the add button in the GUI, or use the ``create`` subcommand.
|
||||||
either start it manually on the GUI or provide it with a schedule (see
|
After creating a sync job, you can either start it manually from the GUI or
|
||||||
:ref:`calendar-events`) to run regularly.
|
provide it with a schedule (see :ref:`calendar-events`) to run regularly.
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
@ -86,7 +86,7 @@ For setting up sync jobs, the configuring user needs the following permissions:
|
|||||||
|
|
||||||
If the ``remove-vanished`` option is set, ``Datastore.Prune`` is required on
|
If the ``remove-vanished`` option is set, ``Datastore.Prune`` is required on
|
||||||
the local datastore as well. If the ``owner`` option is not set (defaulting to
|
the local datastore as well. If the ``owner`` option is not set (defaulting to
|
||||||
``backup@pam``) or set to something other than the configuring user,
|
``root@pam``) or set to something other than the configuring user,
|
||||||
``Datastore.Modify`` is required as well.
|
``Datastore.Modify`` is required as well.
|
||||||
|
|
||||||
.. note:: A sync job can only sync backup groups that the configured remote's
|
.. note:: A sync job can only sync backup groups that the configured remote's
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
.. _sysadmin_network_configuration:
|
||||||
|
|
||||||
Network Management
|
Network Management
|
||||||
==================
|
==================
|
||||||
|
|
||||||
|
@ -26,11 +26,8 @@ update``.
|
|||||||
|
|
||||||
.. FIXME for 7.0: change security update suite to bullseye-security
|
.. FIXME for 7.0: change security update suite to bullseye-security
|
||||||
|
|
||||||
In addition, you need a package repository from Proxmox to get Proxmox Backup updates.
|
In addition, you need a package repository from Proxmox to get Proxmox Backup
|
||||||
|
updates.
|
||||||
During the Proxmox Backup beta phase, only one repository (pbstest) will be
|
|
||||||
available. Once released, an Enterprise repository for production use and a
|
|
||||||
no-subscription repository will be provided.
|
|
||||||
|
|
||||||
SecureApt
|
SecureApt
|
||||||
~~~~~~~~~
|
~~~~~~~~~
|
||||||
@ -72,68 +69,63 @@ Here, the output should be:
|
|||||||
|
|
||||||
f3f6c5a3a67baf38ad178e5ff1ee270c /etc/apt/trusted.gpg.d/proxmox-ve-release-6.x.gpg
|
f3f6c5a3a67baf38ad178e5ff1ee270c /etc/apt/trusted.gpg.d/proxmox-ve-release-6.x.gpg
|
||||||
|
|
||||||
.. comment
|
`Proxmox Backup`_ Enterprise Repository
|
||||||
`Proxmox Backup`_ Enterprise Repository
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
||||||
|
|
||||||
This will be the default, stable, and recommended repository. It is available for
|
This will be the default, stable, and recommended repository. It is available for
|
||||||
all `Proxmox Backup`_ subscription users. It contains the most stable packages,
|
all `Proxmox Backup`_ subscription users. It contains the most stable packages,
|
||||||
and is suitable for production use. The ``pbs-enterprise`` repository is
|
and is suitable for production use. The ``pbs-enterprise`` repository is
|
||||||
enabled by default:
|
enabled by default:
|
||||||
|
|
||||||
.. note:: During the Proxmox Backup beta phase only one repository (pbstest)
|
.. code-block:: sources.list
|
||||||
will be available.
|
:caption: File: ``/etc/apt/sources.list.d/pbs-enterprise.list``
|
||||||
|
|
||||||
.. code-block:: sources.list
|
deb https://enterprise.proxmox.com/debian/pbs buster pbs-enterprise
|
||||||
:caption: File: ``/etc/apt/sources.list.d/pbs-enterprise.list``
|
|
||||||
|
|
||||||
deb https://enterprise.proxmox.com/debian/pbs buster pbs-enterprise
|
|
||||||
|
|
||||||
|
|
||||||
To never miss important security fixes, the superuser (``root@pam`` user) is
|
To never miss important security fixes, the superuser (``root@pam`` user) is
|
||||||
notified via email about new packages as soon as they are available. The
|
notified via email about new packages as soon as they are available. The
|
||||||
change-log and details of each package can be viewed in the GUI (if available).
|
change-log and details of each package can be viewed in the GUI (if available).
|
||||||
|
|
||||||
Please note that you need a valid subscription key to access this
|
Please note that you need a valid subscription key to access this
|
||||||
repository. More information regarding subscription levels and pricing can be
|
repository. More information regarding subscription levels and pricing can be
|
||||||
found at https://www.proxmox.com/en/proxmox-backup/pricing.
|
found at https://www.proxmox.com/en/proxmox-backup-server/pricing
|
||||||
|
|
||||||
.. note:: You can disable this repository by commenting out the above
|
.. note:: You can disable this repository by commenting out the above line
|
||||||
line using a `#` (at the start of the line). This prevents error
|
using a `#` (at the start of the line). This prevents error messages if you do
|
||||||
messages if you do not have a subscription key. Please configure the
|
not have a subscription key. Please configure the ``pbs-no-subscription``
|
||||||
``pbs-no-subscription`` repository in that case.
|
repository in that case.
|
||||||
|
|
||||||
|
|
||||||
`Proxmox Backup`_ No-Subscription Repository
|
`Proxmox Backup`_ No-Subscription Repository
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
As the name suggests, you do not need a subscription key to access
|
As the name suggests, you do not need a subscription key to access
|
||||||
this repository. It can be used for testing and non-production
|
this repository. It can be used for testing and non-production
|
||||||
use. It is not recommended to use it on production servers, because these
|
use. It is not recommended to use it on production servers, because these
|
||||||
packages are not always heavily tested and validated.
|
packages are not always heavily tested and validated.
|
||||||
|
|
||||||
We recommend to configure this repository in ``/etc/apt/sources.list``.
|
We recommend to configure this repository in ``/etc/apt/sources.list``.
|
||||||
|
|
||||||
.. code-block:: sources.list
|
.. code-block:: sources.list
|
||||||
:caption: File: ``/etc/apt/sources.list``
|
:caption: File: ``/etc/apt/sources.list``
|
||||||
|
|
||||||
deb http://ftp.debian.org/debian buster main contrib
|
deb http://ftp.debian.org/debian buster main contrib
|
||||||
deb http://ftp.debian.org/debian buster-updates main contrib
|
deb http://ftp.debian.org/debian buster-updates main contrib
|
||||||
|
|
||||||
# PBS pbs-no-subscription repository provided by proxmox.com,
|
# PBS pbs-no-subscription repository provided by proxmox.com,
|
||||||
# NOT recommended for production use
|
# NOT recommended for production use
|
||||||
deb http://download.proxmox.com/debian/pbs buster pbs-no-subscription
|
deb http://download.proxmox.com/debian/pbs buster pbs-no-subscription
|
||||||
|
|
||||||
# security updates
|
# security updates
|
||||||
deb http://security.debian.org/debian-security buster/updates main contrib
|
deb http://security.debian.org/debian-security buster/updates main contrib
|
||||||
|
|
||||||
|
|
||||||
`Proxmox Backup`_ Beta Repository
|
`Proxmox Backup`_ Test Repository
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
During the public beta, there is a repository called ``pbstest``. This one
|
This repository contains the latest packages and is heavily used by developers
|
||||||
contains the latest packages and is heavily used by developers to test new
|
to test new features.
|
||||||
features.
|
|
||||||
|
|
||||||
.. .. warning:: the ``pbstest`` repository should (as the name implies)
|
.. .. warning:: the ``pbstest`` repository should (as the name implies)
|
||||||
only be used to test new features or bug fixes.
|
only be used to test new features or bug fixes.
|
||||||
@ -145,7 +137,3 @@ You can access this repository by adding the following line to
|
|||||||
:caption: sources.list entry for ``pbstest``
|
:caption: sources.list entry for ``pbstest``
|
||||||
|
|
||||||
deb http://download.proxmox.com/debian/pbs buster pbstest
|
deb http://download.proxmox.com/debian/pbs buster pbstest
|
||||||
|
|
||||||
If you installed Proxmox Backup Server from the official beta ISO, you should
|
|
||||||
have this repository already configured in
|
|
||||||
``/etc/apt/sources.list.d/pbstest-beta.list``
|
|
||||||
|
BIN
docs/prune-simulator/clear-trigger.png
Normal file
After Width: | Height: | Size: 11 KiB |
102
docs/prune-simulator/documentation.html
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<style>
|
||||||
|
/* similar to sphinx alabaster theme ones */
|
||||||
|
body {
|
||||||
|
max-width: 90ch;
|
||||||
|
margin-left: 2ch;
|
||||||
|
margin-right: 2ch;
|
||||||
|
line-height: 1.4em;
|
||||||
|
/* avoid the very high contrast of black on white, tone it down a bit */
|
||||||
|
color: #3E4349;
|
||||||
|
hyphens: auto;
|
||||||
|
text-align: left;
|
||||||
|
font-family: 'Open Sans', sans-serif;
|
||||||
|
font-size: 17px;
|
||||||
|
}
|
||||||
|
h1, h2, h3 {
|
||||||
|
font-family: Lato, sans-serif;
|
||||||
|
font-size: 150%;
|
||||||
|
line-height:1.2
|
||||||
|
}
|
||||||
|
tt, code {
|
||||||
|
background-color: #ecf0f3;
|
||||||
|
color: #222;
|
||||||
|
}
|
||||||
|
pre, tt, code {
|
||||||
|
font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
div.note {
|
||||||
|
background-color: #EEE;
|
||||||
|
border: 1px solid #CCC;
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 0px 20px;
|
||||||
|
}
|
||||||
|
p.note-title {
|
||||||
|
font-weight: bolder;
|
||||||
|
padding: 0;
|
||||||
|
margin: 10px 0 0 0;
|
||||||
|
}
|
||||||
|
div.note > p.last {
|
||||||
|
margin: 5px 0 10px 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<p>A simulator to experiment with different backup schedules and prune
|
||||||
|
options.</p>
|
||||||
|
|
||||||
|
<h3>Schedule</h3>
|
||||||
|
<p>Select weekdays with the combobox and input hour and minute
|
||||||
|
specification separated by a colon, i.e. <code>HOUR:MINUTE</code>. Each of
|
||||||
|
<code>HOUR</code> and <code>MINUTE</code> can be either a single value or
|
||||||
|
one of the following:</p>
|
||||||
|
<ul class="simple">
|
||||||
|
<li>a comma-separated list: e.g., <code>01,02,03</code></li>
|
||||||
|
<li>a range: e.g., <code>01..10</code></li>
|
||||||
|
<li>a repetition: e.g, <code>05/10</code> (means starting at <code>5</code> every <code>10</code>)</li>
|
||||||
|
<li>a combination of the above: e.g., <code>01,05..10,12/02</code></li>
|
||||||
|
<li>a <code>*</code> for every possible value</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3>Pruning</h3>
|
||||||
|
<p>Prune lets you systematically delete older backups, retaining backups for
|
||||||
|
the last given number of time intervals. The following retention options are
|
||||||
|
available:</p>
|
||||||
|
<dl class="docutils">
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-last</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> backup snapshots.</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-hourly</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep backups for the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> hours. If there is more than one
|
||||||
|
backup for a single hour, only the latest is kept.</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-daily</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep backups for the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> days. If there is more than one
|
||||||
|
backup for a single day, only the latest is kept.</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-weekly</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep backups for the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> weeks. If there is more than one
|
||||||
|
backup for a single week, only the latest is kept.
|
||||||
|
<div class="last admonition note">
|
||||||
|
<p class="note-title">Note:</p>
|
||||||
|
<p class="last">Weeks start on Monday and end on Sunday. The software
|
||||||
|
uses the <a class="reference external" href="https://en.wikipedia.org/wiki/ISO_week_date">ISO week date</a> system and handles weeks at
|
||||||
|
the end of the year correctly.</p>
|
||||||
|
</div>
|
||||||
|
</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-monthly</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep backups for the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> months. If there is more than one
|
||||||
|
backup for a single month, only the latest is kept.</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">keep-yearly</span> <span class="pre"><N></span></code></dt>
|
||||||
|
<dd>Keep backups for the last <code class="docutils literal notranslate"><span class="pre"><N></span></code> years. If there is more than one
|
||||||
|
backup for a single year, only the latest is kept.</dd>
|
||||||
|
</dl>
|
||||||
|
<p>The retention options are processed in the order given above. Each option
|
||||||
|
only covers backups within its time period. The next option does not take care
|
||||||
|
of already covered backups. It will only consider older backups.</p>
|
||||||
|
<p>For example, in a week covered by <code>keep-weekly</code>, one backup is
|
||||||
|
kept while all others are removed; <code>keep-monthly</code> then does not
|
||||||
|
consider backups from that week anymore, even if part of the week is part of
|
||||||
|
an earlier month.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
45
docs/prune-simulator/index.html
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||||
|
<title>PBS Prune Simulator</title>
|
||||||
|
|
||||||
|
<link rel="stylesheet" type="text/css" href="extjs/theme-crisp/resources/theme-crisp-all.css">
|
||||||
|
<style>
|
||||||
|
.cal {
|
||||||
|
margin: 5px;
|
||||||
|
}
|
||||||
|
.cal-day {
|
||||||
|
vertical-align: top;
|
||||||
|
width: 150px;
|
||||||
|
height: 75px; /* this is like min-height when used in tables */
|
||||||
|
border: #939393 1px solid;
|
||||||
|
color: #454545;
|
||||||
|
}
|
||||||
|
.cal-day-date {
|
||||||
|
border-bottom: #444 1px solid;
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
.strikethrough {
|
||||||
|
text-decoration: line-through;
|
||||||
|
}
|
||||||
|
.black {
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
.sun {
|
||||||
|
background-color: #ededed;
|
||||||
|
}
|
||||||
|
.first-of-month {
|
||||||
|
border-right: dashed black 4px;
|
||||||
|
}
|
||||||
|
.clear-trigger {
|
||||||
|
background-image: url(./clear-trigger.png);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script type="text/javascript" src="extjs/ext-all.js"></script>
|
||||||
|
<script type="text/javascript" src="prune-simulator.js"></script>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
790
docs/prune-simulator/prune-simulator.js
Normal file
@ -0,0 +1,790 @@
|
|||||||
|
// FIXME: HACK! Makes scrolling in number spinner work again. fixed in ExtJS >= 6.1
|
||||||
|
if (Ext.isFirefox) {
|
||||||
|
Ext.$eventNameMap.DOMMouseScroll = 'DOMMouseScroll';
|
||||||
|
}
|
||||||
|
|
||||||
|
Ext.onReady(function() {
|
||||||
|
const NOW = new Date();
|
||||||
|
const COLORS = {
|
||||||
|
'keep-last': 'orange',
|
||||||
|
'keep-hourly': 'purple',
|
||||||
|
'keep-daily': 'yellow',
|
||||||
|
'keep-weekly': 'green',
|
||||||
|
'keep-monthly': 'blue',
|
||||||
|
'keep-yearly': 'red',
|
||||||
|
'all zero': 'white',
|
||||||
|
};
|
||||||
|
const TEXT_COLORS = {
|
||||||
|
'keep-last': 'black',
|
||||||
|
'keep-hourly': 'white',
|
||||||
|
'keep-daily': 'black',
|
||||||
|
'keep-weekly': 'white',
|
||||||
|
'keep-monthly': 'white',
|
||||||
|
'keep-yearly': 'white',
|
||||||
|
'all zero': 'black',
|
||||||
|
};
|
||||||
|
|
||||||
|
Ext.define('PBS.prunesimulator.Documentation', {
|
||||||
|
extend: 'Ext.Panel',
|
||||||
|
alias: 'widget.prunesimulatorDocumentation',
|
||||||
|
|
||||||
|
html: '<iframe style="width:100%;height:100%;border:0px;" src="./documentation.html"/>',
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.prunesimulator.CalendarEvent', {
|
||||||
|
extend: 'Ext.form.field.ComboBox',
|
||||||
|
alias: 'widget.prunesimulatorCalendarEvent',
|
||||||
|
|
||||||
|
editable: true,
|
||||||
|
|
||||||
|
displayField: 'text',
|
||||||
|
valueField: 'value',
|
||||||
|
queryMode: 'local',
|
||||||
|
|
||||||
|
store: {
|
||||||
|
field: ['value', 'text'],
|
||||||
|
data: [
|
||||||
|
{ value: '0/2:00', text: "Every two hours" },
|
||||||
|
{ value: '0/6:00', text: "Every six hours" },
|
||||||
|
{ value: '2,22:30', text: "At 02:30 and 22:30" },
|
||||||
|
{ value: '00:00', text: "At 00:00" },
|
||||||
|
{ value: '08..17:00/30', text: "From 08:00 to 17:30 every 30 minutes" },
|
||||||
|
{ value: 'HOUR:MINUTE', text: "Custom schedule" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
tpl: [
|
||||||
|
'<ul class="x-list-plain"><tpl for=".">',
|
||||||
|
'<li role="option" class="x-boundlist-item">{text}</li>',
|
||||||
|
'</tpl></ul>',
|
||||||
|
],
|
||||||
|
|
||||||
|
displayTpl: [
|
||||||
|
'<tpl for=".">',
|
||||||
|
'{value}',
|
||||||
|
'</tpl>',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.prunesimulator.DayOfWeekSelector', {
|
||||||
|
extend: 'Ext.form.field.ComboBox',
|
||||||
|
alias: 'widget.prunesimulatorDayOfWeekSelector',
|
||||||
|
|
||||||
|
editable: false,
|
||||||
|
|
||||||
|
displayField: 'text',
|
||||||
|
valueField: 'value',
|
||||||
|
queryMode: 'local',
|
||||||
|
|
||||||
|
store: {
|
||||||
|
field: ['value', 'text'],
|
||||||
|
data: [
|
||||||
|
{ value: 'mon', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[1]) },
|
||||||
|
{ value: 'tue', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[2]) },
|
||||||
|
{ value: 'wed', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[3]) },
|
||||||
|
{ value: 'thu', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[4]) },
|
||||||
|
{ value: 'fri', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[5]) },
|
||||||
|
{ value: 'sat', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[6]) },
|
||||||
|
{ value: 'sun', text: Ext.util.Format.htmlDecode(Ext.Date.dayNames[0]) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('pbs-prune-list', {
|
||||||
|
extend: 'Ext.data.Model',
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: 'backuptime',
|
||||||
|
type: 'date',
|
||||||
|
dateFormat: 'timestamp',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'mark',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'keepName',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.prunesimulator.PruneList', {
|
||||||
|
extend: 'Ext.panel.Panel',
|
||||||
|
alias: 'widget.prunesimulatorPruneList',
|
||||||
|
|
||||||
|
initComponent: function() {
|
||||||
|
let me = this;
|
||||||
|
|
||||||
|
if (!me.store) {
|
||||||
|
throw "no store specified";
|
||||||
|
}
|
||||||
|
|
||||||
|
me.items = [
|
||||||
|
{
|
||||||
|
xtype: 'grid',
|
||||||
|
store: me.store,
|
||||||
|
border: false,
|
||||||
|
columns: [
|
||||||
|
{
|
||||||
|
header: 'Backup Time',
|
||||||
|
dataIndex: 'backuptime',
|
||||||
|
renderer: function(value, metaData, record) {
|
||||||
|
let text = Ext.Date.format(value, 'Y-m-d H:i:s');
|
||||||
|
if (record.data.mark === 'keep') {
|
||||||
|
if (me.useColors) {
|
||||||
|
let bgColor = COLORS[record.data.keepName];
|
||||||
|
let textColor = TEXT_COLORS[record.data.keepName];
|
||||||
|
return '<div style="background-color: ' + bgColor + '; ' +
|
||||||
|
'color: ' + textColor + ';">' + text + '</div>';
|
||||||
|
} else {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return '<div style="text-decoration: line-through;">' + text + '</div>';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
flex: 1,
|
||||||
|
sortable: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Keep (reason)',
|
||||||
|
dataIndex: 'mark',
|
||||||
|
renderer: function(value, metaData, record) {
|
||||||
|
if (record.data.mark === 'keep') {
|
||||||
|
if (record.data.keepCount) {
|
||||||
|
return 'keep (' + record.data.keepName +
|
||||||
|
': ' + record.data.keepCount + ')';
|
||||||
|
} else {
|
||||||
|
return 'keep (' + record.data.keepName + ')';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
width: 200,
|
||||||
|
sortable: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
me.callParent();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.prunesimulator.WeekTable', {
|
||||||
|
extend: 'Ext.panel.Panel',
|
||||||
|
alias: 'widget.prunesimulatorWeekTable',
|
||||||
|
|
||||||
|
reload: function() {
|
||||||
|
let me = this;
|
||||||
|
let backups = me.store.data.items;
|
||||||
|
|
||||||
|
let html = '<table class="cal">';
|
||||||
|
|
||||||
|
let now = new Date(NOW.getTime());
|
||||||
|
let skip = 7 - parseInt(Ext.Date.format(now, 'N'), 10);
|
||||||
|
let tableStartDate = Ext.Date.add(now, Ext.Date.DAY, skip);
|
||||||
|
|
||||||
|
let bIndex = 0;
|
||||||
|
|
||||||
|
for (let i = 0; bIndex < backups.length; i++) {
|
||||||
|
html += '<tr>';
|
||||||
|
|
||||||
|
for (let j = 0; j < 7; j++) {
|
||||||
|
let date = Ext.Date.subtract(tableStartDate, Ext.Date.DAY, j + 7 * i);
|
||||||
|
let currentDay = Ext.Date.format(date, 'd/m/Y');
|
||||||
|
|
||||||
|
let dayOfWeekCls = Ext.Date.format(date, 'D').toLowerCase();
|
||||||
|
let firstOfMonthCls = Ext.Date.format(date, 'd') === '01'
|
||||||
|
? 'first-of-month'
|
||||||
|
: '';
|
||||||
|
html += `<td class="cal-day ${dayOfWeekCls} ${firstOfMonthCls}">`;
|
||||||
|
|
||||||
|
const isBackupOnDay = function(backup, day) {
|
||||||
|
return backup && Ext.Date.format(backup.data.backuptime, 'd/m/Y') === day;
|
||||||
|
};
|
||||||
|
|
||||||
|
let backup = backups[bIndex];
|
||||||
|
|
||||||
|
html += '<table><tr>';
|
||||||
|
html += `<th class="cal-day-date">${Ext.Date.format(date, 'D, d M Y')}</th>`;
|
||||||
|
|
||||||
|
while (isBackupOnDay(backup, currentDay)) {
|
||||||
|
html += '<tr><td>';
|
||||||
|
|
||||||
|
let text = Ext.Date.format(backup.data.backuptime, 'H:i');
|
||||||
|
if (backup.data.mark === 'remove') {
|
||||||
|
html += `<span class="strikethrough">${text}</span>`;
|
||||||
|
} else {
|
||||||
|
if (backup.data.keepCount) {
|
||||||
|
text += ` (${backup.data.keepName} ${backup.data.keepCount})`;
|
||||||
|
} else {
|
||||||
|
text += ` (${backup.data.keepName})`;
|
||||||
|
}
|
||||||
|
if (me.useColors) {
|
||||||
|
let bgColor = COLORS[backup.data.keepName];
|
||||||
|
let textColor = TEXT_COLORS[backup.data.keepName];
|
||||||
|
html += `<span style="background-color: ${bgColor};
|
||||||
|
color: ${textColor};">${text}</span>`;
|
||||||
|
} else {
|
||||||
|
html += `<span class="black">${text}</span>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
html += '</td></tr>';
|
||||||
|
backup = backups[++bIndex];
|
||||||
|
}
|
||||||
|
html += '</table>';
|
||||||
|
html += '</div>';
|
||||||
|
html += '</td>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += '</tr>';
|
||||||
|
}
|
||||||
|
|
||||||
|
me.setHtml(html);
|
||||||
|
},
|
||||||
|
|
||||||
|
initComponent: function() {
|
||||||
|
let me = this;
|
||||||
|
|
||||||
|
if (!me.store) {
|
||||||
|
throw "no store specified";
|
||||||
|
}
|
||||||
|
|
||||||
|
let reload = function() {
|
||||||
|
me.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
me.store.on("datachanged", reload);
|
||||||
|
|
||||||
|
me.callParent();
|
||||||
|
|
||||||
|
me.reload();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.PruneSimulatorKeepInput', {
|
||||||
|
extend: 'Ext.form.field.Number',
|
||||||
|
alias: 'widget.prunesimulatorKeepInput',
|
||||||
|
|
||||||
|
allowBlank: true,
|
||||||
|
fieldGroup: 'keep',
|
||||||
|
minValue: 1,
|
||||||
|
|
||||||
|
listeners: {
|
||||||
|
afterrender: function(field) {
|
||||||
|
this.triggers.clear.setVisible(field.value !== null);
|
||||||
|
},
|
||||||
|
change: function(field, newValue, oldValue) {
|
||||||
|
this.triggers.clear.setVisible(newValue !== null);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
triggers: {
|
||||||
|
clear: {
|
||||||
|
cls: 'clear-trigger',
|
||||||
|
weight: -1,
|
||||||
|
handler: function() {
|
||||||
|
this.triggers.clear.setVisible(false);
|
||||||
|
this.setValue(null);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.define('PBS.PruneSimulatorPanel', {
|
||||||
|
extend: 'Ext.panel.Panel',
|
||||||
|
alias: 'widget.prunesimulatorPanel',
|
||||||
|
|
||||||
|
viewModel: {
|
||||||
|
},
|
||||||
|
|
||||||
|
getValues: function() {
|
||||||
|
let me = this;
|
||||||
|
|
||||||
|
let values = {};
|
||||||
|
|
||||||
|
Ext.Array.each(me.query('[isFormField]'), function(field) {
|
||||||
|
let data = field.getSubmitData();
|
||||||
|
Ext.Object.each(data, function(name, val) {
|
||||||
|
values[name] = val;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return values;
|
||||||
|
},
|
||||||
|
|
||||||
|
controller: {
|
||||||
|
xclass: 'Ext.app.ViewController',
|
||||||
|
|
||||||
|
init: function(view) {
|
||||||
|
this.reloadFull(); // initial load
|
||||||
|
this.switchColor(true);
|
||||||
|
},
|
||||||
|
|
||||||
|
control: {
|
||||||
|
'field[fieldGroup=keep]': { change: 'reloadPrune' },
|
||||||
|
},
|
||||||
|
|
||||||
|
reloadFull: function() {
|
||||||
|
let me = this;
|
||||||
|
let view = me.getView();
|
||||||
|
|
||||||
|
let params = view.getValues();
|
||||||
|
|
||||||
|
let [hourSpec, minuteSpec] = params['schedule-time'].split(':');
|
||||||
|
|
||||||
|
if (!hourSpec || !minuteSpec) {
|
||||||
|
Ext.Msg.alert('Error', 'Invalid schedule');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let matchTimeSpec = function(timeSpec, rangeMin, rangeMax) {
|
||||||
|
let specValues = timeSpec.split(',');
|
||||||
|
let matches = {};
|
||||||
|
|
||||||
|
let assertValid = function(value) {
|
||||||
|
let num = Number(value);
|
||||||
|
if (isNaN(num)) {
|
||||||
|
throw value + " is not an integer";
|
||||||
|
} else if (value < rangeMin || value > rangeMax) {
|
||||||
|
throw "number '" + value + "' is not in the range '" + rangeMin + ".." + rangeMax + "'";
|
||||||
|
}
|
||||||
|
return num;
|
||||||
|
};
|
||||||
|
|
||||||
|
specValues.forEach(function(value) {
|
||||||
|
if (value.includes('..')) {
|
||||||
|
let [start, end] = value.split('..');
|
||||||
|
start = assertValid(start);
|
||||||
|
end = assertValid(end);
|
||||||
|
if (start > end) {
|
||||||
|
throw "interval start is bigger then interval end '" + start + " > " + end + "'";
|
||||||
|
}
|
||||||
|
for (let i = start; i <= end; i++) {
|
||||||
|
matches[i] = 1;
|
||||||
|
}
|
||||||
|
} else if (value.includes('/')) {
|
||||||
|
let [start, step] = value.split('/');
|
||||||
|
start = assertValid(start);
|
||||||
|
step = assertValid(step);
|
||||||
|
for (let i = start; i <= rangeMax; i += step) {
|
||||||
|
matches[i] = 1;
|
||||||
|
}
|
||||||
|
} else if (value === '*') {
|
||||||
|
for (let i = rangeMin; i <= rangeMax; i++) {
|
||||||
|
matches[i] = 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
value = assertValid(value);
|
||||||
|
matches[value] = 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Object.keys(matches);
|
||||||
|
};
|
||||||
|
|
||||||
|
let hours, minutes;
|
||||||
|
|
||||||
|
try {
|
||||||
|
hours = matchTimeSpec(hourSpec, 0, 23);
|
||||||
|
minutes = matchTimeSpec(minuteSpec, 0, 59);
|
||||||
|
} catch (err) {
|
||||||
|
Ext.Msg.alert('Error', err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let backups = me.populateFromSchedule(
|
||||||
|
params['schedule-weekdays'],
|
||||||
|
hours,
|
||||||
|
minutes,
|
||||||
|
params.numberOfWeeks,
|
||||||
|
);
|
||||||
|
|
||||||
|
me.pruneSelect(backups, params);
|
||||||
|
|
||||||
|
view.pruneStore.setData(backups);
|
||||||
|
},
|
||||||
|
|
||||||
|
reloadPrune: function() {
|
||||||
|
let me = this;
|
||||||
|
let view = me.getView();
|
||||||
|
|
||||||
|
let params = view.getValues();
|
||||||
|
|
||||||
|
let backups = [];
|
||||||
|
view.pruneStore.getData().items.forEach(function(item) {
|
||||||
|
backups.push({
|
||||||
|
backuptime: item.data.backuptime,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
me.pruneSelect(backups, params);
|
||||||
|
|
||||||
|
view.pruneStore.setData(backups);
|
||||||
|
},
|
||||||
|
|
||||||
|
// backups are sorted descending by date
|
||||||
|
populateFromSchedule: function(weekdays, hours, minutes, weekCount) {
|
||||||
|
let weekdayFlags = [
|
||||||
|
weekdays.includes('sun'),
|
||||||
|
weekdays.includes('mon'),
|
||||||
|
weekdays.includes('tue'),
|
||||||
|
weekdays.includes('wed'),
|
||||||
|
weekdays.includes('thu'),
|
||||||
|
weekdays.includes('fri'),
|
||||||
|
weekdays.includes('sat'),
|
||||||
|
];
|
||||||
|
|
||||||
|
let todaysDate = new Date(NOW.getTime());
|
||||||
|
|
||||||
|
let timesOnSingleDay = [];
|
||||||
|
|
||||||
|
hours.forEach(function(hour) {
|
||||||
|
minutes.forEach(function(minute) {
|
||||||
|
todaysDate.setHours(hour);
|
||||||
|
todaysDate.setMinutes(minute);
|
||||||
|
timesOnSingleDay.push(todaysDate.getTime());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ordering here and iterating backwards through days
|
||||||
|
// ensures that everything is ordered
|
||||||
|
timesOnSingleDay.sort(function(a, b) {
|
||||||
|
return a < b;
|
||||||
|
});
|
||||||
|
|
||||||
|
let backups = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < 7 * weekCount; i++) {
|
||||||
|
let daysDate = Ext.Date.subtract(todaysDate, Ext.Date.DAY, i);
|
||||||
|
let weekday = parseInt(Ext.Date.format(daysDate, 'w'), 10);
|
||||||
|
if (weekdayFlags[weekday]) {
|
||||||
|
timesOnSingleDay.forEach(function(time) {
|
||||||
|
backups.push({
|
||||||
|
backuptime: Ext.Date.subtract(new Date(time), Ext.Date.DAY, i),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return backups;
|
||||||
|
},
|
||||||
|
|
||||||
|
pruneMark: function(backups, keepCount, keepName, idFunc) {
|
||||||
|
if (!keepCount) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let alreadyIncluded = {};
|
||||||
|
let newlyIncluded = {};
|
||||||
|
let newlyIncludedCount = 0;
|
||||||
|
|
||||||
|
let finished = false;
|
||||||
|
|
||||||
|
backups.forEach(function(backup) {
|
||||||
|
let mark = backup.mark;
|
||||||
|
let id = idFunc(backup);
|
||||||
|
|
||||||
|
if (finished || alreadyIncluded[id]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mark) {
|
||||||
|
if (mark === 'keep') {
|
||||||
|
alreadyIncluded[id] = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!newlyIncluded[id]) {
|
||||||
|
if (newlyIncludedCount >= keepCount) {
|
||||||
|
finished = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
newlyIncluded[id] = true;
|
||||||
|
newlyIncludedCount++;
|
||||||
|
backup.mark = 'keep';
|
||||||
|
backup.keepName = keepName;
|
||||||
|
backup.keepCount = newlyIncludedCount;
|
||||||
|
} else {
|
||||||
|
backup.mark = 'remove';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
// backups need to be sorted descending by date
|
||||||
|
pruneSelect: function(backups, keepParams) {
|
||||||
|
let me = this;
|
||||||
|
|
||||||
|
if (Number(keepParams['keep-last']) +
|
||||||
|
Number(keepParams['keep-hourly']) +
|
||||||
|
Number(keepParams['keep-daily']) +
|
||||||
|
Number(keepParams['keep-weekly']) +
|
||||||
|
Number(keepParams['keep-monthly']) +
|
||||||
|
Number(keepParams['keep-yearly']) === 0) {
|
||||||
|
backups.forEach(function(backup) {
|
||||||
|
backup.mark = 'keep';
|
||||||
|
backup.keepName = 'keep-all';
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
me.pruneMark(backups, keepParams['keep-last'], 'keep-last', function(backup) {
|
||||||
|
return backup.backuptime;
|
||||||
|
});
|
||||||
|
me.pruneMark(backups, keepParams['keep-hourly'], 'keep-hourly', function(backup) {
|
||||||
|
return Ext.Date.format(backup.backuptime, 'H/d/m/Y');
|
||||||
|
});
|
||||||
|
me.pruneMark(backups, keepParams['keep-daily'], 'keep-daily', function(backup) {
|
||||||
|
return Ext.Date.format(backup.backuptime, 'd/m/Y');
|
||||||
|
});
|
||||||
|
me.pruneMark(backups, keepParams['keep-weekly'], 'keep-weekly', function(backup) {
|
||||||
|
// ISO-8601 week and week-based year
|
||||||
|
return Ext.Date.format(backup.backuptime, 'W/o');
|
||||||
|
});
|
||||||
|
me.pruneMark(backups, keepParams['keep-monthly'], 'keep-monthly', function(backup) {
|
||||||
|
return Ext.Date.format(backup.backuptime, 'm/Y');
|
||||||
|
});
|
||||||
|
me.pruneMark(backups, keepParams['keep-yearly'], 'keep-yearly', function(backup) {
|
||||||
|
return Ext.Date.format(backup.backuptime, 'Y');
|
||||||
|
});
|
||||||
|
|
||||||
|
backups.forEach(function(backup) {
|
||||||
|
backup.mark = backup.mark || 'remove';
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
toggleColors: function(checkbox, checked) {
|
||||||
|
this.switchColor(checked);
|
||||||
|
},
|
||||||
|
|
||||||
|
switchColor: function(useColors) {
|
||||||
|
let me = this;
|
||||||
|
let view = me.getView();
|
||||||
|
|
||||||
|
const getStyle = name =>
|
||||||
|
`background-color: ${COLORS[name]}; color: ${TEXT_COLORS[name]};`;
|
||||||
|
|
||||||
|
for (const field of view.query('[isFormField]')) {
|
||||||
|
if (field.fieldGroup !== 'keep') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (useColors) {
|
||||||
|
field.setFieldStyle(getStyle(field.name));
|
||||||
|
} else {
|
||||||
|
field.setFieldStyle('background-color: white; color: #444;');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
me.lookup('weekTable').useColors = useColors;
|
||||||
|
me.lookup('pruneList').useColors = useColors;
|
||||||
|
|
||||||
|
me.reloadPrune();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
keepItems: [
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-last',
|
||||||
|
fieldLabel: 'keep-last',
|
||||||
|
value: 4,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-hourly',
|
||||||
|
fieldLabel: 'keep-hourly',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-daily',
|
||||||
|
fieldLabel: 'keep-daily',
|
||||||
|
value: 5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-weekly',
|
||||||
|
fieldLabel: 'keep-weekly',
|
||||||
|
value: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-monthly',
|
||||||
|
fieldLabel: 'keep-monthly',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorKeepInput',
|
||||||
|
name: 'keep-yearly',
|
||||||
|
fieldLabel: 'keep-yearly',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
|
||||||
|
initComponent: function() {
|
||||||
|
var me = this;
|
||||||
|
|
||||||
|
me.pruneStore = Ext.create('Ext.data.Store', {
|
||||||
|
model: 'pbs-prune-list',
|
||||||
|
sorters: { property: 'backuptime', direction: 'DESC' },
|
||||||
|
});
|
||||||
|
|
||||||
|
me.items = [
|
||||||
|
{
|
||||||
|
xtype: 'panel',
|
||||||
|
layout: {
|
||||||
|
type: 'hbox',
|
||||||
|
align: 'stretch',
|
||||||
|
},
|
||||||
|
border: false,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'View',
|
||||||
|
layout: 'anchor',
|
||||||
|
flex: 1,
|
||||||
|
border: false,
|
||||||
|
bodyPadding: 10,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
xtype: 'checkbox',
|
||||||
|
name: 'showCalendar',
|
||||||
|
reference: 'showCalendar',
|
||||||
|
fieldLabel: 'Show Calendar:',
|
||||||
|
checked: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'checkbox',
|
||||||
|
name: 'showColors',
|
||||||
|
reference: 'showColors',
|
||||||
|
fieldLabel: 'Show Colors:',
|
||||||
|
checked: true,
|
||||||
|
handler: 'toggleColors',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ xtype: "panel", width: 1, border: 1 },
|
||||||
|
{
|
||||||
|
xtype: 'form',
|
||||||
|
layout: 'anchor',
|
||||||
|
flex: 1,
|
||||||
|
border: false,
|
||||||
|
title: 'Simulated Backup Schedule',
|
||||||
|
defaults: {
|
||||||
|
labelWidth: 120,
|
||||||
|
},
|
||||||
|
bodyPadding: 10,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorDayOfWeekSelector',
|
||||||
|
name: 'schedule-weekdays',
|
||||||
|
fieldLabel: 'Day of week',
|
||||||
|
value: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'],
|
||||||
|
allowBlank: false,
|
||||||
|
multiSelect: true,
|
||||||
|
padding: '0 0 0 10',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorCalendarEvent',
|
||||||
|
name: 'schedule-time',
|
||||||
|
allowBlank: false,
|
||||||
|
value: '0/6:00',
|
||||||
|
fieldLabel: 'Backup schedule',
|
||||||
|
padding: '0 0 0 10',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'numberfield',
|
||||||
|
name: 'numberOfWeeks',
|
||||||
|
allowBlank: false,
|
||||||
|
fieldLabel: 'Number of weeks',
|
||||||
|
minValue: 1,
|
||||||
|
value: 15,
|
||||||
|
maxValue: 260, // five years
|
||||||
|
padding: '0 0 0 10',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'button',
|
||||||
|
name: 'schedule-button',
|
||||||
|
text: 'Update Schedule',
|
||||||
|
formBind: true,
|
||||||
|
handler: 'reloadFull',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'panel',
|
||||||
|
layout: {
|
||||||
|
type: 'hbox',
|
||||||
|
align: 'stretch',
|
||||||
|
},
|
||||||
|
flex: 1,
|
||||||
|
border: false,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
layout: 'anchor',
|
||||||
|
title: 'Prune Options',
|
||||||
|
border: false,
|
||||||
|
bodyPadding: 10,
|
||||||
|
scrollable: true,
|
||||||
|
items: me.keepItems,
|
||||||
|
flex: 1,
|
||||||
|
},
|
||||||
|
{ xtype: "panel", width: 1, border: 1 },
|
||||||
|
{
|
||||||
|
layout: 'fit',
|
||||||
|
title: 'Backups',
|
||||||
|
border: false,
|
||||||
|
xtype: 'prunesimulatorPruneList',
|
||||||
|
store: me.pruneStore,
|
||||||
|
reference: 'pruneList',
|
||||||
|
flex: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
layout: 'anchor',
|
||||||
|
title: 'Calendar',
|
||||||
|
autoScroll: true,
|
||||||
|
flex: 2,
|
||||||
|
xtype: 'prunesimulatorWeekTable',
|
||||||
|
reference: 'weekTable',
|
||||||
|
store: me.pruneStore,
|
||||||
|
bind: {
|
||||||
|
hidden: '{!showCalendar.checked}',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
me.callParent();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Ext.create('Ext.container.Viewport', {
|
||||||
|
layout: 'border',
|
||||||
|
renderTo: Ext.getBody(),
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorPanel',
|
||||||
|
title: 'Proxmox Backup Server - Prune Simulator',
|
||||||
|
region: 'west',
|
||||||
|
layout: {
|
||||||
|
type: 'vbox',
|
||||||
|
align: 'stretch',
|
||||||
|
pack: 'start',
|
||||||
|
},
|
||||||
|
flex: 3,
|
||||||
|
maxWidth: 1090,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
xtype: 'prunesimulatorDocumentation',
|
||||||
|
title: 'Usage',
|
||||||
|
border: false,
|
||||||
|
flex: 2,
|
||||||
|
region: 'center',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,6 +1,8 @@
|
|||||||
Storage
|
Storage
|
||||||
=======
|
=======
|
||||||
|
|
||||||
|
.. _storage_disk_management:
|
||||||
|
|
||||||
Disk Management
|
Disk Management
|
||||||
---------------
|
---------------
|
||||||
|
|
||||||
@ -57,7 +59,7 @@ create a datastore at the location ``/mnt/datastore/store1``:
|
|||||||
You can also create a ``zpool`` with various raid levels from **Administration
|
You can also create a ``zpool`` with various raid levels from **Administration
|
||||||
-> Disks -> Zpool** in the web interface, or by using ``zpool create``. The command
|
-> Disks -> Zpool** in the web interface, or by using ``zpool create``. The command
|
||||||
below creates a mirrored ``zpool`` using two disks (``sdb`` & ``sdc``) and
|
below creates a mirrored ``zpool`` using two disks (``sdb`` & ``sdc``) and
|
||||||
mounts it on the root directory (default):
|
mounts it under ``/mnt/datastore/zpool1``:
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
@ -85,7 +87,7 @@ display S.M.A.R.T. attributes from the web interface or by using the command:
|
|||||||
|
|
||||||
.. _datastore_intro:
|
.. _datastore_intro:
|
||||||
|
|
||||||
:term:`DataStore`
|
:term:`Datastore`
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
A datastore refers to a location at which backups are stored. The current
|
A datastore refers to a location at which backups are stored. The current
|
||||||
@ -107,7 +109,7 @@ is stored in the file ``/etc/proxmox-backup/datastore.cfg``.
|
|||||||
Datastore Configuration
|
Datastore Configuration
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-datastore.png
|
.. image:: images/screenshots/pbs-gui-datastore-content.png
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Datastore Overview
|
:alt: Datastore Overview
|
||||||
|
|
||||||
@ -121,14 +123,17 @@ number of backups to keep in that store. :ref:`backup-pruning` and
|
|||||||
periodically based on a configured schedule (see :ref:`calendar-events`) per datastore.
|
periodically based on a configured schedule (see :ref:`calendar-events`) per datastore.
|
||||||
|
|
||||||
|
|
||||||
|
.. _storage_datastore_create:
|
||||||
|
|
||||||
Creating a Datastore
|
Creating a Datastore
|
||||||
^^^^^^^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^^^^^^^
|
||||||
.. image:: images/screenshots/pbs-gui-datastore-create-general.png
|
.. image:: images/screenshots/pbs-gui-datastore-create-general.png
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Create a datastore
|
:alt: Create a datastore
|
||||||
|
|
||||||
You can create a new datastore from the web GUI, by navigating to **Datastore** in
|
You can create a new datastore from the web interface, by clicking **Add
|
||||||
the menu tree and clicking **Create**. Here:
|
Datastore** in the side menu, under the **Datastore** section. In the setup
|
||||||
|
window:
|
||||||
|
|
||||||
* *Name* refers to the name of the datastore
|
* *Name* refers to the name of the datastore
|
||||||
* *Backing Path* is the path to the directory upon which you want to create the
|
* *Backing Path* is the path to the directory upon which you want to create the
|
||||||
@ -136,7 +141,9 @@ the menu tree and clicking **Create**. Here:
|
|||||||
* *GC Schedule* refers to the time and intervals at which garbage collection
|
* *GC Schedule* refers to the time and intervals at which garbage collection
|
||||||
runs
|
runs
|
||||||
* *Prune Schedule* refers to the frequency at which pruning takes place
|
* *Prune Schedule* refers to the frequency at which pruning takes place
|
||||||
* *Prune Options* set the amount of backups which you would like to keep (see :ref:`backup-pruning`).
|
* *Prune Options* set the amount of backups which you would like to keep (see
|
||||||
|
:ref:`backup-pruning`).
|
||||||
|
* *Comment* can be used to add some contextual information to the datastore.
|
||||||
|
|
||||||
Alternatively you can create a new datastore from the command line. The
|
Alternatively you can create a new datastore from the command line. The
|
||||||
following command creates a new datastore called ``store1`` on :file:`/backup/disk1/store1`
|
following command creates a new datastore called ``store1`` on :file:`/backup/disk1/store1`
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
.. _sysadmin_host_administration:
|
||||||
|
|
||||||
Host System Administration
|
Host System Administration
|
||||||
==========================
|
==========================
|
||||||
|
|
||||||
|
@ -41,11 +41,12 @@ users:
|
|||||||
:alt: Add a new user
|
:alt: Add a new user
|
||||||
|
|
||||||
The superuser has full administration rights on everything, so you
|
The superuser has full administration rights on everything, so you
|
||||||
normally want to add other users with less privileges. You can create a new
|
normally want to add other users with less privileges. You can add a new
|
||||||
user with the ``user create`` subcommand or through the web interface, under
|
user with the ``user create`` subcommand or through the web
|
||||||
**Configuration -> User Management**. The ``create`` subcommand lets you specify
|
interface, under the **User Management** tab of **Configuration -> Access
|
||||||
many options like ``--email`` or ``--password``. You can update or change any
|
Control**. The ``create`` subcommand lets you specify many options like
|
||||||
user properties using the ``update`` subcommand later (**Edit** in the GUI):
|
``--email`` or ``--password``. You can update or change any user properties
|
||||||
|
using the ``update`` subcommand later (**Edit** in the GUI):
|
||||||
|
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
@ -90,6 +91,10 @@ Or completely remove the user with:
|
|||||||
API Tokens
|
API Tokens
|
||||||
----------
|
----------
|
||||||
|
|
||||||
|
.. image:: images/screenshots/pbs-gui-apitoken-overview.png
|
||||||
|
:align: right
|
||||||
|
:alt: API Token Overview
|
||||||
|
|
||||||
Any authenticated user can generate API tokens which can in turn be used to
|
Any authenticated user can generate API tokens which can in turn be used to
|
||||||
configure various clients, instead of directly providing the username and
|
configure various clients, instead of directly providing the username and
|
||||||
password.
|
password.
|
||||||
@ -104,6 +109,10 @@ the realm and a tokenname (``user@realm!tokenname``), and a secret value. Both
|
|||||||
need to be provided to the client in place of the user ID (``user@realm``) and
|
need to be provided to the client in place of the user ID (``user@realm``) and
|
||||||
the user password, respectively.
|
the user password, respectively.
|
||||||
|
|
||||||
|
.. image:: images/screenshots/pbs-gui-apitoken-secret-value.png
|
||||||
|
:align: right
|
||||||
|
:alt: API secret value
|
||||||
|
|
||||||
The API token is passed from the client to the server by setting the
|
The API token is passed from the client to the server by setting the
|
||||||
``Authorization`` HTTP header with method ``PBSAPIToken`` to the value
|
``Authorization`` HTTP header with method ``PBSAPIToken`` to the value
|
||||||
``TOKENID:TOKENSECRET``.
|
``TOKENID:TOKENSECRET``.
|
||||||
@ -184,7 +193,7 @@ following roles exist:
|
|||||||
**RemoteSyncOperator**
|
**RemoteSyncOperator**
|
||||||
Is allowed to read data from a remote.
|
Is allowed to read data from a remote.
|
||||||
|
|
||||||
.. image:: images/screenshots/pbs-gui-permissions-add.png
|
.. image:: images/screenshots/pbs-gui-user-management-add-user.png
|
||||||
:align: right
|
:align: right
|
||||||
:alt: Add permissions for user
|
:alt: Add permissions for user
|
||||||
|
|
||||||
@ -221,11 +230,11 @@ You can list the ACLs of each user/token using the following command:
|
|||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
# proxmox-backup-manager acl list
|
# proxmox-backup-manager acl list
|
||||||
┌──────────┬──────────────────┬───────────┬────────────────┐
|
┌──────────┬───────────────────┬───────────┬────────────────┐
|
||||||
│ ugid │ path │ propagate │ roleid │
|
│ ugid │ path │ propagate │ roleid │
|
||||||
╞══════════╪══════════════════╪═══════════╪════════════════╡
|
╞══════════╪═══════════════════╪═══════════╪════════════════╡
|
||||||
│ john@pbs │ /datastore/disk1 │ 1 │ DatastoreAdmin │
|
│ john@pbs │ /datastore/store1 │ 1 │ DatastoreAdmin │
|
||||||
└──────────┴──────────────────┴───────────┴────────────────┘
|
└──────────┴───────────────────┴───────────┴────────────────┘
|
||||||
|
|
||||||
A single user/token can be assigned multiple permission sets for different datastores.
|
A single user/token can be assigned multiple permission sets for different datastores.
|
||||||
|
|
||||||
@ -258,7 +267,7 @@ you can use the ``proxmox-backup-manager user permission`` command:
|
|||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
# proxmox-backup-manager user permissions john@pbs -- path /datastore/store1
|
# proxmox-backup-manager user permissions john@pbs --path /datastore/store1
|
||||||
Privileges with (*) have the propagate flag set
|
Privileges with (*) have the propagate flag set
|
||||||
|
|
||||||
Path: /datastore/store1
|
Path: /datastore/store1
|
||||||
@ -267,9 +276,10 @@ you can use the ``proxmox-backup-manager user permission`` command:
|
|||||||
- Datastore.Modify (*)
|
- Datastore.Modify (*)
|
||||||
- Datastore.Prune (*)
|
- Datastore.Prune (*)
|
||||||
- Datastore.Read (*)
|
- Datastore.Read (*)
|
||||||
|
- Datastore.Verify (*)
|
||||||
|
|
||||||
# proxmox-backup-manager acl update /datastore/store1 DatastoreBackup --auth-id 'john@pbs!client1'
|
# proxmox-backup-manager acl update /datastore/store1 DatastoreBackup --auth-id 'john@pbs!client1'
|
||||||
# proxmox-backup-manager user permissions 'john@pbs!test' -- path /datastore/store1
|
# proxmox-backup-manager user permissions 'john@pbs!client1' --path /datastore/store1
|
||||||
Privileges with (*) have the propagate flag set
|
Privileges with (*) have the propagate flag set
|
||||||
|
|
||||||
Path: /datastore/store1
|
Path: /datastore/store1
|
||||||
|
@ -9,7 +9,7 @@ DYNAMIC_UNITS := \
|
|||||||
proxmox-backup.service \
|
proxmox-backup.service \
|
||||||
proxmox-backup-proxy.service
|
proxmox-backup-proxy.service
|
||||||
|
|
||||||
all: $(UNITS) $(DYNAMIC_UNITS) pbstest-beta.list
|
all: $(UNITS) $(DYNAMIC_UNITS) pbs-enterprise.list
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -f $(DYNAMIC_UNITS)
|
rm -f $(DYNAMIC_UNITS)
|
||||||
|
1
etc/pbs-enterprise.list
Normal file
@ -0,0 +1 @@
|
|||||||
|
deb https://enterprise.proxmox.com/debian/pbs buster pbs-enterprise
|
@ -1 +0,0 @@
|
|||||||
deb http://download.proxmox.com/debian/pbs buster pbstest
|
|
@ -12,7 +12,6 @@ use proxmox::{http_err, list_subdirs_api_method};
|
|||||||
use crate::tools::ticket::{self, Empty, Ticket};
|
use crate::tools::ticket::{self, Empty, Ticket};
|
||||||
use crate::auth_helpers::*;
|
use crate::auth_helpers::*;
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
use crate::tools::{FileLogOptions, FileLogger};
|
|
||||||
|
|
||||||
use crate::config::acl as acl_config;
|
use crate::config::acl as acl_config;
|
||||||
use crate::config::acl::{PRIVILEGES, PRIV_SYS_AUDIT, PRIV_PERMISSIONS_MODIFY};
|
use crate::config::acl::{PRIVILEGES, PRIV_SYS_AUDIT, PRIV_PERMISSIONS_MODIFY};
|
||||||
@ -144,20 +143,13 @@ fn create_ticket(
|
|||||||
port: Option<u16>,
|
port: Option<u16>,
|
||||||
rpcenv: &mut dyn RpcEnvironment,
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<Value, Error> {
|
) -> Result<Value, Error> {
|
||||||
let logger_options = FileLogOptions {
|
|
||||||
append: true,
|
|
||||||
prefix_time: true,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut auth_log = FileLogger::new("/var/log/proxmox-backup/api/auth.log", logger_options)?;
|
|
||||||
|
|
||||||
match authenticate_user(&username, &password, path, privs, port) {
|
match authenticate_user(&username, &password, path, privs, port) {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
let ticket = Ticket::new("PBS", &username)?.sign(private_auth_key(), None)?;
|
let ticket = Ticket::new("PBS", &username)?.sign(private_auth_key(), None)?;
|
||||||
|
|
||||||
let token = assemble_csrf_prevention_token(csrf_secret(), &username);
|
let token = assemble_csrf_prevention_token(csrf_secret(), &username);
|
||||||
|
|
||||||
auth_log.log(format!("successful auth for user '{}'", username));
|
crate::server::rest::auth_logger()?.log(format!("successful auth for user '{}'", username));
|
||||||
|
|
||||||
Ok(json!({
|
Ok(json!({
|
||||||
"username": username,
|
"username": username,
|
||||||
@ -180,7 +172,7 @@ fn create_ticket(
|
|||||||
username,
|
username,
|
||||||
err.to_string()
|
err.to_string()
|
||||||
);
|
);
|
||||||
auth_log.log(&msg);
|
crate::server::rest::auth_logger()?.log(&msg);
|
||||||
log::error!("{}", msg);
|
log::error!("{}", msg);
|
||||||
|
|
||||||
Err(http_err!(UNAUTHORIZED, "permission check failed."))
|
Err(http_err!(UNAUTHORIZED, "permission check failed."))
|
||||||
|
@ -75,7 +75,7 @@ pub struct UserWithTokens {
|
|||||||
pub lastname: Option<String>,
|
pub lastname: Option<String>,
|
||||||
#[serde(skip_serializing_if="Option::is_none")]
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
pub email: Option<String>,
|
pub email: Option<String>,
|
||||||
#[serde(skip_serializing_if="Vec::is_empty")]
|
#[serde(skip_serializing_if="Vec::is_empty", default)]
|
||||||
pub tokens: Vec<user::ApiToken>,
|
pub tokens: Vec<user::ApiToken>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -268,6 +268,21 @@ pub fn read_user(userid: Userid, mut rpcenv: &mut dyn RpcEnvironment) -> Result<
|
|||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[api()]
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all="kebab-case")]
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
pub enum DeletableProperty {
|
||||||
|
/// Delete the comment property.
|
||||||
|
comment,
|
||||||
|
/// Delete the firstname property.
|
||||||
|
firstname,
|
||||||
|
/// Delete the lastname property.
|
||||||
|
lastname,
|
||||||
|
/// Delete the email property.
|
||||||
|
email,
|
||||||
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
protected: true,
|
protected: true,
|
||||||
input: {
|
input: {
|
||||||
@ -303,6 +318,14 @@ pub fn read_user(userid: Userid, mut rpcenv: &mut dyn RpcEnvironment) -> Result<
|
|||||||
schema: user::EMAIL_SCHEMA,
|
schema: user::EMAIL_SCHEMA,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
delete: {
|
||||||
|
description: "List of properties to delete.",
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
items: {
|
||||||
|
type: DeletableProperty,
|
||||||
|
}
|
||||||
|
},
|
||||||
digest: {
|
digest: {
|
||||||
optional: true,
|
optional: true,
|
||||||
schema: PROXMOX_CONFIG_DIGEST_SCHEMA,
|
schema: PROXMOX_CONFIG_DIGEST_SCHEMA,
|
||||||
@ -326,6 +349,7 @@ pub fn update_user(
|
|||||||
firstname: Option<String>,
|
firstname: Option<String>,
|
||||||
lastname: Option<String>,
|
lastname: Option<String>,
|
||||||
email: Option<String>,
|
email: Option<String>,
|
||||||
|
delete: Option<Vec<DeletableProperty>>,
|
||||||
digest: Option<String>,
|
digest: Option<String>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
|
||||||
@ -340,6 +364,17 @@ pub fn update_user(
|
|||||||
|
|
||||||
let mut data: user::User = config.lookup("user", userid.as_str())?;
|
let mut data: user::User = config.lookup("user", userid.as_str())?;
|
||||||
|
|
||||||
|
if let Some(delete) = delete {
|
||||||
|
for delete_prop in delete {
|
||||||
|
match delete_prop {
|
||||||
|
DeletableProperty::comment => data.comment = None,
|
||||||
|
DeletableProperty::firstname => data.firstname = None,
|
||||||
|
DeletableProperty::lastname => data.lastname = None,
|
||||||
|
DeletableProperty::email => data.email = None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(comment) = comment {
|
if let Some(comment) = comment {
|
||||||
let comment = comment.trim().to_string();
|
let comment = comment.trim().to_string();
|
||||||
if comment.is_empty() {
|
if comment.is_empty() {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::collections::{HashSet, HashMap};
|
use std::collections::HashSet;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::os::unix::ffi::OsStrExt;
|
use std::os::unix::ffi::OsStrExt;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
@ -125,19 +125,6 @@ fn get_all_snapshot_files(
|
|||||||
Ok((manifest, files))
|
Ok((manifest, files))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn group_backups(backup_list: Vec<BackupInfo>) -> HashMap<String, Vec<BackupInfo>> {
|
|
||||||
|
|
||||||
let mut group_hash = HashMap::new();
|
|
||||||
|
|
||||||
for info in backup_list {
|
|
||||||
let group_id = info.backup_dir.group().group_path().to_str().unwrap().to_owned();
|
|
||||||
let time_list = group_hash.entry(group_id).or_insert(vec![]);
|
|
||||||
time_list.push(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
group_hash
|
|
||||||
}
|
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
input: {
|
input: {
|
||||||
properties: {
|
properties: {
|
||||||
@ -171,39 +158,64 @@ fn list_groups(
|
|||||||
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
||||||
|
|
||||||
let datastore = DataStore::lookup_datastore(&store)?;
|
let datastore = DataStore::lookup_datastore(&store)?;
|
||||||
|
let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
|
||||||
|
|
||||||
let backup_list = BackupInfo::list_backups(&datastore.base_path())?;
|
let backup_groups = BackupInfo::list_backup_groups(&datastore.base_path())?;
|
||||||
|
|
||||||
let group_hash = group_backups(backup_list);
|
let group_info = backup_groups
|
||||||
|
.into_iter()
|
||||||
|
.fold(Vec::new(), |mut group_info, group| {
|
||||||
|
let owner = match datastore.get_owner(&group) {
|
||||||
|
Ok(auth_id) => auth_id,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to get owner of group '{}/{}' - {}",
|
||||||
|
&store,
|
||||||
|
group,
|
||||||
|
err);
|
||||||
|
return group_info;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
|
||||||
|
return group_info;
|
||||||
|
}
|
||||||
|
|
||||||
let mut groups = Vec::new();
|
let snapshots = match group.list_backups(&datastore.base_path()) {
|
||||||
|
Ok(snapshots) => snapshots,
|
||||||
|
Err(_) => {
|
||||||
|
return group_info;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
for (_group_id, mut list) in group_hash {
|
let backup_count: u64 = snapshots.len() as u64;
|
||||||
|
if backup_count == 0 {
|
||||||
|
return group_info;
|
||||||
|
}
|
||||||
|
|
||||||
BackupInfo::sort_list(&mut list, false);
|
let last_backup = snapshots
|
||||||
|
.iter()
|
||||||
|
.fold(&snapshots[0], |last, curr| {
|
||||||
|
if curr.is_finished()
|
||||||
|
&& curr.backup_dir.backup_time() > last.backup_dir.backup_time() {
|
||||||
|
curr
|
||||||
|
} else {
|
||||||
|
last
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
let info = &list[0];
|
group_info.push(GroupListItem {
|
||||||
|
backup_type: group.backup_type().to_string(),
|
||||||
|
backup_id: group.backup_id().to_string(),
|
||||||
|
last_backup: last_backup.backup_dir.backup_time(),
|
||||||
|
owner: Some(owner),
|
||||||
|
backup_count,
|
||||||
|
files: last_backup.files,
|
||||||
|
});
|
||||||
|
|
||||||
let group = info.backup_dir.group();
|
group_info
|
||||||
|
});
|
||||||
|
|
||||||
let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
|
Ok(group_info)
|
||||||
let owner = datastore.get_owner(group)?;
|
|
||||||
if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let result_item = GroupListItem {
|
|
||||||
backup_type: group.backup_type().to_string(),
|
|
||||||
backup_id: group.backup_id().to_string(),
|
|
||||||
last_backup: info.backup_dir.backup_time(),
|
|
||||||
backup_count: list.len() as u64,
|
|
||||||
files: info.files.clone(),
|
|
||||||
owner: Some(owner),
|
|
||||||
};
|
|
||||||
groups.push(result_item);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(groups)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
@ -351,43 +363,56 @@ pub fn list_snapshots (
|
|||||||
let user_info = CachedUserInfo::new()?;
|
let user_info = CachedUserInfo::new()?;
|
||||||
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
||||||
|
|
||||||
|
let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
|
||||||
|
|
||||||
let datastore = DataStore::lookup_datastore(&store)?;
|
let datastore = DataStore::lookup_datastore(&store)?;
|
||||||
|
|
||||||
let base_path = datastore.base_path();
|
let base_path = datastore.base_path();
|
||||||
|
|
||||||
let backup_list = BackupInfo::list_backups(&base_path)?;
|
let groups = match (backup_type, backup_id) {
|
||||||
|
(Some(backup_type), Some(backup_id)) => {
|
||||||
|
let mut groups = Vec::with_capacity(1);
|
||||||
|
groups.push(BackupGroup::new(backup_type, backup_id));
|
||||||
|
groups
|
||||||
|
},
|
||||||
|
(Some(backup_type), None) => {
|
||||||
|
BackupInfo::list_backup_groups(&base_path)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|group| group.backup_type() == backup_type)
|
||||||
|
.collect()
|
||||||
|
},
|
||||||
|
(None, Some(backup_id)) => {
|
||||||
|
BackupInfo::list_backup_groups(&base_path)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|group| group.backup_id() == backup_id)
|
||||||
|
.collect()
|
||||||
|
},
|
||||||
|
_ => BackupInfo::list_backup_groups(&base_path)?,
|
||||||
|
};
|
||||||
|
|
||||||
let mut snapshots = vec![];
|
let info_to_snapshot_list_item = |group: &BackupGroup, owner, info: BackupInfo| {
|
||||||
|
let backup_type = group.backup_type().to_string();
|
||||||
|
let backup_id = group.backup_id().to_string();
|
||||||
|
let backup_time = info.backup_dir.backup_time();
|
||||||
|
|
||||||
for info in backup_list {
|
match get_all_snapshot_files(&datastore, &info) {
|
||||||
let group = info.backup_dir.group();
|
|
||||||
if let Some(ref backup_type) = backup_type {
|
|
||||||
if backup_type != group.backup_type() { continue; }
|
|
||||||
}
|
|
||||||
if let Some(ref backup_id) = backup_id {
|
|
||||||
if backup_id != group.backup_id() { continue; }
|
|
||||||
}
|
|
||||||
|
|
||||||
let list_all = (user_privs & PRIV_DATASTORE_AUDIT) != 0;
|
|
||||||
let owner = datastore.get_owner(group)?;
|
|
||||||
|
|
||||||
if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut size = None;
|
|
||||||
|
|
||||||
let (comment, verification, files) = match get_all_snapshot_files(&datastore, &info) {
|
|
||||||
Ok((manifest, files)) => {
|
Ok((manifest, files)) => {
|
||||||
size = Some(files.iter().map(|x| x.size.unwrap_or(0)).sum());
|
|
||||||
// extract the first line from notes
|
// extract the first line from notes
|
||||||
let comment: Option<String> = manifest.unprotected["notes"]
|
let comment: Option<String> = manifest.unprotected["notes"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.and_then(|notes| notes.lines().next())
|
.and_then(|notes| notes.lines().next())
|
||||||
.map(String::from);
|
.map(String::from);
|
||||||
|
|
||||||
let verify = manifest.unprotected["verify_state"].clone();
|
let fingerprint = match manifest.fingerprint() {
|
||||||
let verify: Option<SnapshotVerifyState> = match serde_json::from_value(verify) {
|
Ok(fp) => fp,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("error parsing fingerprint: '{}'", err);
|
||||||
|
None
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let verification = manifest.unprotected["verify_state"].clone();
|
||||||
|
let verification: Option<SnapshotVerifyState> = match serde_json::from_value(verification) {
|
||||||
Ok(verify) => verify,
|
Ok(verify) => verify,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!("error parsing verification state : '{}'", err);
|
eprintln!("error parsing verification state : '{}'", err);
|
||||||
@ -395,88 +420,114 @@ pub fn list_snapshots (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
(comment, verify, files)
|
let size = Some(files.iter().map(|x| x.size.unwrap_or(0)).sum());
|
||||||
|
|
||||||
|
SnapshotListItem {
|
||||||
|
backup_type,
|
||||||
|
backup_id,
|
||||||
|
backup_time,
|
||||||
|
comment,
|
||||||
|
verification,
|
||||||
|
fingerprint,
|
||||||
|
files,
|
||||||
|
size,
|
||||||
|
owner,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!("error during snapshot file listing: '{}'", err);
|
eprintln!("error during snapshot file listing: '{}'", err);
|
||||||
(
|
let files = info
|
||||||
None,
|
|
||||||
None,
|
|
||||||
info
|
|
||||||
.files
|
.files
|
||||||
.iter()
|
.into_iter()
|
||||||
.map(|x| BackupContent {
|
.map(|x| BackupContent {
|
||||||
filename: x.to_string(),
|
filename: x.to_string(),
|
||||||
size: None,
|
size: None,
|
||||||
crypt_mode: None,
|
crypt_mode: None,
|
||||||
})
|
})
|
||||||
.collect()
|
.collect();
|
||||||
)
|
|
||||||
|
SnapshotListItem {
|
||||||
|
backup_type,
|
||||||
|
backup_id,
|
||||||
|
backup_time,
|
||||||
|
comment: None,
|
||||||
|
verification: None,
|
||||||
|
fingerprint: None,
|
||||||
|
files,
|
||||||
|
size: None,
|
||||||
|
owner,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
|
|
||||||
let result_item = SnapshotListItem {
|
|
||||||
backup_type: group.backup_type().to_string(),
|
|
||||||
backup_id: group.backup_id().to_string(),
|
|
||||||
backup_time: info.backup_dir.backup_time(),
|
|
||||||
comment,
|
|
||||||
verification,
|
|
||||||
files,
|
|
||||||
size,
|
|
||||||
owner: Some(owner),
|
|
||||||
};
|
|
||||||
|
|
||||||
snapshots.push(result_item);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(snapshots)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_snapshots_count(store: &DataStore) -> Result<Counts, Error> {
|
|
||||||
let base_path = store.base_path();
|
|
||||||
let backup_list = BackupInfo::list_backups(&base_path)?;
|
|
||||||
let mut groups = HashSet::new();
|
|
||||||
|
|
||||||
let mut result = Counts {
|
|
||||||
ct: None,
|
|
||||||
host: None,
|
|
||||||
vm: None,
|
|
||||||
other: None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
for info in backup_list {
|
groups
|
||||||
let group = info.backup_dir.group();
|
.iter()
|
||||||
|
.try_fold(Vec::new(), |mut snapshots, group| {
|
||||||
|
let owner = match datastore.get_owner(group) {
|
||||||
|
Ok(auth_id) => auth_id,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to get owner of group '{}/{}' - {}",
|
||||||
|
&store,
|
||||||
|
group,
|
||||||
|
err);
|
||||||
|
return Ok(snapshots);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
let id = group.backup_id();
|
if !list_all && check_backup_owner(&owner, &auth_id).is_err() {
|
||||||
let backup_type = group.backup_type();
|
return Ok(snapshots);
|
||||||
|
}
|
||||||
|
|
||||||
let mut new_id = false;
|
let group_backups = group.list_backups(&datastore.base_path())?;
|
||||||
|
|
||||||
if groups.insert(format!("{}-{}", &backup_type, &id)) {
|
snapshots.extend(
|
||||||
new_id = true;
|
group_backups
|
||||||
}
|
.into_iter()
|
||||||
|
.map(|info| info_to_snapshot_list_item(&group, Some(owner.clone()), info))
|
||||||
|
);
|
||||||
|
|
||||||
let mut counts = match backup_type {
|
Ok(snapshots)
|
||||||
"ct" => result.ct.take().unwrap_or(Default::default()),
|
})
|
||||||
"host" => result.host.take().unwrap_or(Default::default()),
|
}
|
||||||
"vm" => result.vm.take().unwrap_or(Default::default()),
|
|
||||||
_ => result.other.take().unwrap_or(Default::default()),
|
|
||||||
};
|
|
||||||
|
|
||||||
counts.snapshots += 1;
|
fn get_snapshots_count(store: &DataStore, filter_owner: Option<&Authid>) -> Result<Counts, Error> {
|
||||||
if new_id {
|
let base_path = store.base_path();
|
||||||
counts.groups +=1;
|
let groups = BackupInfo::list_backup_groups(&base_path)?;
|
||||||
}
|
|
||||||
|
|
||||||
match backup_type {
|
groups.iter()
|
||||||
"ct" => result.ct = Some(counts),
|
.filter(|group| {
|
||||||
"host" => result.host = Some(counts),
|
let owner = match store.get_owner(&group) {
|
||||||
"vm" => result.vm = Some(counts),
|
Ok(owner) => owner,
|
||||||
_ => result.other = Some(counts),
|
Err(err) => {
|
||||||
}
|
eprintln!("Failed to get owner of group '{}/{}' - {}",
|
||||||
}
|
store.name(),
|
||||||
|
group,
|
||||||
|
err);
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
Ok(result)
|
match filter_owner {
|
||||||
|
Some(filter) => check_backup_owner(&owner, filter).is_ok(),
|
||||||
|
None => true,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.try_fold(Counts::default(), |mut counts, group| {
|
||||||
|
let snapshot_count = group.list_backups(&base_path)?.len() as u64;
|
||||||
|
|
||||||
|
let type_count = match group.backup_type() {
|
||||||
|
"ct" => counts.ct.get_or_insert(Default::default()),
|
||||||
|
"vm" => counts.vm.get_or_insert(Default::default()),
|
||||||
|
"host" => counts.host.get_or_insert(Default::default()),
|
||||||
|
_ => counts.other.get_or_insert(Default::default()),
|
||||||
|
};
|
||||||
|
|
||||||
|
type_count.groups += 1;
|
||||||
|
type_count.snapshots += snapshot_count;
|
||||||
|
|
||||||
|
Ok(counts)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
@ -485,7 +536,14 @@ fn get_snapshots_count(store: &DataStore) -> Result<Counts, Error> {
|
|||||||
store: {
|
store: {
|
||||||
schema: DATASTORE_SCHEMA,
|
schema: DATASTORE_SCHEMA,
|
||||||
},
|
},
|
||||||
|
verbose: {
|
||||||
|
type: bool,
|
||||||
|
default: false,
|
||||||
|
optional: true,
|
||||||
|
description: "Include additional information like snapshot counts and GC status.",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
},
|
},
|
||||||
returns: {
|
returns: {
|
||||||
type: DataStoreStatus,
|
type: DataStoreStatus,
|
||||||
@ -497,13 +555,30 @@ fn get_snapshots_count(store: &DataStore) -> Result<Counts, Error> {
|
|||||||
/// Get datastore status.
|
/// Get datastore status.
|
||||||
pub fn status(
|
pub fn status(
|
||||||
store: String,
|
store: String,
|
||||||
|
verbose: bool,
|
||||||
_info: &ApiMethod,
|
_info: &ApiMethod,
|
||||||
_rpcenv: &mut dyn RpcEnvironment,
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<DataStoreStatus, Error> {
|
) -> Result<DataStoreStatus, Error> {
|
||||||
let datastore = DataStore::lookup_datastore(&store)?;
|
let datastore = DataStore::lookup_datastore(&store)?;
|
||||||
let storage = crate::tools::disks::disk_usage(&datastore.base_path())?;
|
let storage = crate::tools::disks::disk_usage(&datastore.base_path())?;
|
||||||
let counts = get_snapshots_count(&datastore)?;
|
let (counts, gc_status) = if verbose {
|
||||||
let gc_status = datastore.last_gc_status();
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
|
let store_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
||||||
|
let filter_owner = if store_privs & PRIV_DATASTORE_AUDIT != 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(&auth_id)
|
||||||
|
};
|
||||||
|
|
||||||
|
let counts = Some(get_snapshots_count(&datastore, filter_owner)?);
|
||||||
|
let gc_status = Some(datastore.last_gc_status());
|
||||||
|
|
||||||
|
(counts, gc_status)
|
||||||
|
} else {
|
||||||
|
(None, None)
|
||||||
|
};
|
||||||
|
|
||||||
Ok(DataStoreStatus {
|
Ok(DataStoreStatus {
|
||||||
total: storage.total,
|
total: storage.total,
|
||||||
@ -636,7 +711,7 @@ pub fn verify(
|
|||||||
verify_all_backups(datastore, worker.clone(), worker.upid(), owner, None)?
|
verify_all_backups(datastore, worker.clone(), worker.upid(), owner, None)?
|
||||||
};
|
};
|
||||||
if failed_dirs.len() > 0 {
|
if failed_dirs.len() > 0 {
|
||||||
worker.log("Failed to verify following snapshots:");
|
worker.log("Failed to verify the following snapshots/groups:");
|
||||||
for dir in failed_dirs {
|
for dir in failed_dirs {
|
||||||
worker.log(format!("\t{}", dir));
|
worker.log(format!("\t{}", dir));
|
||||||
}
|
}
|
||||||
@ -902,15 +977,7 @@ pub fn garbage_collection_status(
|
|||||||
type: Array,
|
type: Array,
|
||||||
items: {
|
items: {
|
||||||
description: "Datastore name and description.",
|
description: "Datastore name and description.",
|
||||||
properties: {
|
type: DataStoreListItem,
|
||||||
store: {
|
|
||||||
schema: DATASTORE_SCHEMA,
|
|
||||||
},
|
|
||||||
comment: {
|
|
||||||
optional: true,
|
|
||||||
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
@ -922,7 +989,7 @@ fn get_datastore_list(
|
|||||||
_param: Value,
|
_param: Value,
|
||||||
_info: &ApiMethod,
|
_info: &ApiMethod,
|
||||||
rpcenv: &mut dyn RpcEnvironment,
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<Value, Error> {
|
) -> Result<Vec<DataStoreListItem>, Error> {
|
||||||
|
|
||||||
let (config, _digest) = datastore::config()?;
|
let (config, _digest) = datastore::config()?;
|
||||||
|
|
||||||
@ -935,11 +1002,12 @@ fn get_datastore_list(
|
|||||||
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
let user_privs = user_info.lookup_privs(&auth_id, &["datastore", &store]);
|
||||||
let allowed = (user_privs & (PRIV_DATASTORE_AUDIT| PRIV_DATASTORE_BACKUP)) != 0;
|
let allowed = (user_privs & (PRIV_DATASTORE_AUDIT| PRIV_DATASTORE_BACKUP)) != 0;
|
||||||
if allowed {
|
if allowed {
|
||||||
let mut entry = json!({ "store": store });
|
list.push(
|
||||||
if let Some(comment) = data["comment"].as_str() {
|
DataStoreListItem {
|
||||||
entry["comment"] = comment.into();
|
store: store.clone(),
|
||||||
}
|
comment: data["comment"].as_str().map(String::from),
|
||||||
list.push(entry);
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,11 +2,16 @@ use anyhow::{format_err, Error};
|
|||||||
|
|
||||||
use proxmox::api::router::SubdirMap;
|
use proxmox::api::router::SubdirMap;
|
||||||
use proxmox::{list_subdirs_api_method, sortable};
|
use proxmox::{list_subdirs_api_method, sortable};
|
||||||
use proxmox::api::{api, ApiMethod, Router, RpcEnvironment};
|
use proxmox::api::{api, ApiMethod, Permission, Router, RpcEnvironment};
|
||||||
|
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
use crate::server::do_verification_job;
|
use crate::server::do_verification_job;
|
||||||
use crate::server::jobstate::{Job, JobState};
|
use crate::server::jobstate::{Job, JobState};
|
||||||
|
use crate::config::acl::{
|
||||||
|
PRIV_DATASTORE_AUDIT,
|
||||||
|
PRIV_DATASTORE_VERIFY,
|
||||||
|
};
|
||||||
|
use crate::config::cached_user_info::CachedUserInfo;
|
||||||
use crate::config::verify;
|
use crate::config::verify;
|
||||||
use crate::config::verify::{VerificationJobConfig, VerificationJobStatus};
|
use crate::config::verify::{VerificationJobConfig, VerificationJobStatus};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
@ -23,10 +28,14 @@ use crate::server::UPID;
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
returns: {
|
returns: {
|
||||||
description: "List configured jobs and their status.",
|
description: "List configured jobs and their status (filtered by access)",
|
||||||
type: Array,
|
type: Array,
|
||||||
items: { type: verify::VerificationJobStatus },
|
items: { type: verify::VerificationJobStatus },
|
||||||
},
|
},
|
||||||
|
access: {
|
||||||
|
permission: &Permission::Anybody,
|
||||||
|
description: "Requires Datastore.Audit or Datastore.Verify on datastore.",
|
||||||
|
},
|
||||||
)]
|
)]
|
||||||
/// List all verification jobs
|
/// List all verification jobs
|
||||||
pub fn list_verification_jobs(
|
pub fn list_verification_jobs(
|
||||||
@ -34,6 +43,10 @@ pub fn list_verification_jobs(
|
|||||||
_param: Value,
|
_param: Value,
|
||||||
mut rpcenv: &mut dyn RpcEnvironment,
|
mut rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<Vec<VerificationJobStatus>, Error> {
|
) -> Result<Vec<VerificationJobStatus>, Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
|
let required_privs = PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_VERIFY;
|
||||||
|
|
||||||
let (config, digest) = verify::config()?;
|
let (config, digest) = verify::config()?;
|
||||||
|
|
||||||
@ -41,6 +54,11 @@ pub fn list_verification_jobs(
|
|||||||
.convert_to_typed_array("verification")?
|
.convert_to_typed_array("verification")?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|job: &VerificationJobStatus| {
|
.filter(|job: &VerificationJobStatus| {
|
||||||
|
let privs = user_info.lookup_privs(&auth_id, &["datastore", &job.store]);
|
||||||
|
if privs & required_privs == 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(store) = &store {
|
if let Some(store) = &store {
|
||||||
&job.store == store
|
&job.store == store
|
||||||
} else {
|
} else {
|
||||||
@ -90,7 +108,11 @@ pub fn list_verification_jobs(
|
|||||||
schema: JOB_ID_SCHEMA,
|
schema: JOB_ID_SCHEMA,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
access: {
|
||||||
|
permission: &Permission::Anybody,
|
||||||
|
description: "Requires Datastore.Verify on job's datastore.",
|
||||||
|
},
|
||||||
)]
|
)]
|
||||||
/// Runs a verification job manually.
|
/// Runs a verification job manually.
|
||||||
fn run_verification_job(
|
fn run_verification_job(
|
||||||
@ -98,10 +120,13 @@ fn run_verification_job(
|
|||||||
_info: &ApiMethod,
|
_info: &ApiMethod,
|
||||||
rpcenv: &mut dyn RpcEnvironment,
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<String, Error> {
|
) -> Result<String, Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
let (config, _digest) = verify::config()?;
|
let (config, _digest) = verify::config()?;
|
||||||
let verification_job: VerificationJobConfig = config.lookup("verification", &id)?;
|
let verification_job: VerificationJobConfig = config.lookup("verification", &id)?;
|
||||||
|
|
||||||
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
user_info.check_privs(&auth_id, &["datastore", &verification_job.store], PRIV_DATASTORE_VERIFY, true)?;
|
||||||
|
|
||||||
let job = Job::new("verificationjob", &id)?;
|
let job = Job::new("verificationjob", &id)?;
|
||||||
|
|
||||||
|
@ -311,6 +311,10 @@ pub const BACKUP_API_SUBDIRS: SubdirMap = &[
|
|||||||
"previous", &Router::new()
|
"previous", &Router::new()
|
||||||
.download(&API_METHOD_DOWNLOAD_PREVIOUS)
|
.download(&API_METHOD_DOWNLOAD_PREVIOUS)
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"previous_backup_time", &Router::new()
|
||||||
|
.get(&API_METHOD_GET_PREVIOUS_BACKUP_TIME)
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"speedtest", &Router::new()
|
"speedtest", &Router::new()
|
||||||
.upload(&API_METHOD_UPLOAD_SPEEDTEST)
|
.upload(&API_METHOD_UPLOAD_SPEEDTEST)
|
||||||
@ -694,6 +698,28 @@ fn finish_backup (
|
|||||||
Ok(Value::Null)
|
Ok(Value::Null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sortable]
|
||||||
|
pub const API_METHOD_GET_PREVIOUS_BACKUP_TIME: ApiMethod = ApiMethod::new(
|
||||||
|
&ApiHandler::Sync(&get_previous_backup_time),
|
||||||
|
&ObjectSchema::new(
|
||||||
|
"Get previous backup time.",
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
fn get_previous_backup_time(
|
||||||
|
_param: Value,
|
||||||
|
_info: &ApiMethod,
|
||||||
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
|
) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let env: &BackupEnvironment = rpcenv.as_ref();
|
||||||
|
|
||||||
|
let backup_time = env.last_backup.as_ref().map(|info| info.backup_dir.backup_time());
|
||||||
|
|
||||||
|
Ok(json!(backup_time))
|
||||||
|
}
|
||||||
|
|
||||||
#[sortable]
|
#[sortable]
|
||||||
pub const API_METHOD_DOWNLOAD_PREVIOUS: ApiMethod = ApiMethod::new(
|
pub const API_METHOD_DOWNLOAD_PREVIOUS: ApiMethod = ApiMethod::new(
|
||||||
&ApiHandler::AsyncHttp(&download_previous),
|
&ApiHandler::AsyncHttp(&download_previous),
|
||||||
|
@ -5,6 +5,7 @@ use serde_json::Value;
|
|||||||
use ::serde::{Deserialize, Serialize};
|
use ::serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use proxmox::api::{api, Router, RpcEnvironment, Permission};
|
use proxmox::api::{api, Router, RpcEnvironment, Permission};
|
||||||
|
use proxmox::api::schema::parse_property_string;
|
||||||
use proxmox::tools::fs::open_file_locked;
|
use proxmox::tools::fs::open_file_locked;
|
||||||
|
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
@ -68,6 +69,14 @@ pub fn list_datastores(
|
|||||||
optional: true,
|
optional: true,
|
||||||
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
||||||
},
|
},
|
||||||
|
"notify-user": {
|
||||||
|
optional: true,
|
||||||
|
type: Userid,
|
||||||
|
},
|
||||||
|
"notify": {
|
||||||
|
optional: true,
|
||||||
|
schema: DATASTORE_NOTIFY_STRING_SCHEMA,
|
||||||
|
},
|
||||||
"gc-schedule": {
|
"gc-schedule": {
|
||||||
optional: true,
|
optional: true,
|
||||||
schema: GC_SCHEDULE_SCHEMA,
|
schema: GC_SCHEDULE_SCHEMA,
|
||||||
@ -187,6 +196,12 @@ pub enum DeletableProperty {
|
|||||||
keep_monthly,
|
keep_monthly,
|
||||||
/// Delete the keep-yearly property
|
/// Delete the keep-yearly property
|
||||||
keep_yearly,
|
keep_yearly,
|
||||||
|
/// Delete the verify-new property
|
||||||
|
verify_new,
|
||||||
|
/// Delete the notify-user property
|
||||||
|
notify_user,
|
||||||
|
/// Delete the notify property
|
||||||
|
notify,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
@ -200,6 +215,14 @@ pub enum DeletableProperty {
|
|||||||
optional: true,
|
optional: true,
|
||||||
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
||||||
},
|
},
|
||||||
|
"notify-user": {
|
||||||
|
optional: true,
|
||||||
|
type: Userid,
|
||||||
|
},
|
||||||
|
"notify": {
|
||||||
|
optional: true,
|
||||||
|
schema: DATASTORE_NOTIFY_STRING_SCHEMA,
|
||||||
|
},
|
||||||
"gc-schedule": {
|
"gc-schedule": {
|
||||||
optional: true,
|
optional: true,
|
||||||
schema: GC_SCHEDULE_SCHEMA,
|
schema: GC_SCHEDULE_SCHEMA,
|
||||||
@ -232,6 +255,12 @@ pub enum DeletableProperty {
|
|||||||
optional: true,
|
optional: true,
|
||||||
schema: PRUNE_SCHEMA_KEEP_YEARLY,
|
schema: PRUNE_SCHEMA_KEEP_YEARLY,
|
||||||
},
|
},
|
||||||
|
"verify-new": {
|
||||||
|
description: "If enabled, all new backups will be verified right after completion.",
|
||||||
|
type: bool,
|
||||||
|
optional: true,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
delete: {
|
delete: {
|
||||||
description: "List of properties to delete.",
|
description: "List of properties to delete.",
|
||||||
type: Array,
|
type: Array,
|
||||||
@ -262,6 +291,9 @@ pub fn update_datastore(
|
|||||||
keep_weekly: Option<u64>,
|
keep_weekly: Option<u64>,
|
||||||
keep_monthly: Option<u64>,
|
keep_monthly: Option<u64>,
|
||||||
keep_yearly: Option<u64>,
|
keep_yearly: Option<u64>,
|
||||||
|
verify_new: Option<bool>,
|
||||||
|
notify: Option<String>,
|
||||||
|
notify_user: Option<Userid>,
|
||||||
delete: Option<Vec<DeletableProperty>>,
|
delete: Option<Vec<DeletableProperty>>,
|
||||||
digest: Option<String>,
|
digest: Option<String>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
@ -290,6 +322,9 @@ pub fn update_datastore(
|
|||||||
DeletableProperty::keep_weekly => { data.keep_weekly = None; },
|
DeletableProperty::keep_weekly => { data.keep_weekly = None; },
|
||||||
DeletableProperty::keep_monthly => { data.keep_monthly = None; },
|
DeletableProperty::keep_monthly => { data.keep_monthly = None; },
|
||||||
DeletableProperty::keep_yearly => { data.keep_yearly = None; },
|
DeletableProperty::keep_yearly => { data.keep_yearly = None; },
|
||||||
|
DeletableProperty::verify_new => { data.verify_new = None; },
|
||||||
|
DeletableProperty::notify => { data.notify = None; },
|
||||||
|
DeletableProperty::notify_user => { data.notify_user = None; },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -322,6 +357,19 @@ pub fn update_datastore(
|
|||||||
if keep_monthly.is_some() { data.keep_monthly = keep_monthly; }
|
if keep_monthly.is_some() { data.keep_monthly = keep_monthly; }
|
||||||
if keep_yearly.is_some() { data.keep_yearly = keep_yearly; }
|
if keep_yearly.is_some() { data.keep_yearly = keep_yearly; }
|
||||||
|
|
||||||
|
if let Some(notify_str) = notify {
|
||||||
|
let value = parse_property_string(¬ify_str, &DatastoreNotify::API_SCHEMA)?;
|
||||||
|
let notify: DatastoreNotify = serde_json::from_value(value)?;
|
||||||
|
if let DatastoreNotify { gc: None, verify: None, sync: None } = notify {
|
||||||
|
data.notify = None;
|
||||||
|
} else {
|
||||||
|
data.notify = Some(notify_str);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if verify_new.is_some() { data.verify_new = verify_new; }
|
||||||
|
|
||||||
|
if notify_user.is_some() { data.notify_user = notify_user; }
|
||||||
|
|
||||||
config.set_data(&name, "datastore", &data)?;
|
config.set_data(&name, "datastore", &data)?;
|
||||||
|
|
||||||
datastore::save_config(&config)?;
|
datastore::save_config(&config)?;
|
||||||
|
@ -1,11 +1,13 @@
|
|||||||
use anyhow::{bail, Error};
|
use anyhow::{bail, format_err, Error};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use ::serde::{Deserialize, Serialize};
|
use ::serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use proxmox::api::{api, ApiMethod, Router, RpcEnvironment, Permission};
|
use proxmox::api::{api, ApiMethod, Router, RpcEnvironment, Permission};
|
||||||
|
use proxmox::http_err;
|
||||||
use proxmox::tools::fs::open_file_locked;
|
use proxmox::tools::fs::open_file_locked;
|
||||||
|
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
|
use crate::client::{HttpClient, HttpClientOptions};
|
||||||
use crate::config::cached_user_info::CachedUserInfo;
|
use crate::config::cached_user_info::CachedUserInfo;
|
||||||
use crate::config::remote;
|
use crate::config::remote;
|
||||||
use crate::config::acl::{PRIV_REMOTE_AUDIT, PRIV_REMOTE_MODIFY};
|
use crate::config::acl::{PRIV_REMOTE_AUDIT, PRIV_REMOTE_MODIFY};
|
||||||
@ -76,7 +78,7 @@ pub fn list_remotes(
|
|||||||
optional: true,
|
optional: true,
|
||||||
default: 8007,
|
default: 8007,
|
||||||
},
|
},
|
||||||
userid: {
|
"auth-id": {
|
||||||
type: Authid,
|
type: Authid,
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
@ -176,7 +178,7 @@ pub enum DeletableProperty {
|
|||||||
type: u16,
|
type: u16,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
userid: {
|
"auth-id": {
|
||||||
optional: true,
|
optional: true,
|
||||||
type: Authid,
|
type: Authid,
|
||||||
},
|
},
|
||||||
@ -212,7 +214,7 @@ pub fn update_remote(
|
|||||||
comment: Option<String>,
|
comment: Option<String>,
|
||||||
host: Option<String>,
|
host: Option<String>,
|
||||||
port: Option<u16>,
|
port: Option<u16>,
|
||||||
userid: Option<Authid>,
|
auth_id: Option<Authid>,
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
fingerprint: Option<String>,
|
fingerprint: Option<String>,
|
||||||
delete: Option<Vec<DeletableProperty>>,
|
delete: Option<Vec<DeletableProperty>>,
|
||||||
@ -250,7 +252,7 @@ pub fn update_remote(
|
|||||||
}
|
}
|
||||||
if let Some(host) = host { data.host = host; }
|
if let Some(host) = host { data.host = host; }
|
||||||
if port.is_some() { data.port = port; }
|
if port.is_some() { data.port = port; }
|
||||||
if let Some(userid) = userid { data.userid = userid; }
|
if let Some(auth_id) = auth_id { data.auth_id = auth_id; }
|
||||||
if let Some(password) = password { data.password = password; }
|
if let Some(password) = password { data.password = password; }
|
||||||
|
|
||||||
if let Some(fingerprint) = fingerprint { data.fingerprint = Some(fingerprint); }
|
if let Some(fingerprint) = fingerprint { data.fingerprint = Some(fingerprint); }
|
||||||
@ -282,6 +284,17 @@ pub fn update_remote(
|
|||||||
/// Remove a remote from the configuration file.
|
/// Remove a remote from the configuration file.
|
||||||
pub fn delete_remote(name: String, digest: Option<String>) -> Result<(), Error> {
|
pub fn delete_remote(name: String, digest: Option<String>) -> Result<(), Error> {
|
||||||
|
|
||||||
|
use crate::config::sync::{self, SyncJobConfig};
|
||||||
|
|
||||||
|
let (sync_jobs, _) = sync::config()?;
|
||||||
|
|
||||||
|
let job_list: Vec<SyncJobConfig> = sync_jobs.convert_to_typed_array("sync")?;
|
||||||
|
for job in job_list {
|
||||||
|
if job.remote == name {
|
||||||
|
bail!("remote '{}' is used by sync job '{}' (datastore '{}')", name, job.id, job.store);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let _lock = open_file_locked(remote::REMOTE_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
let _lock = open_file_locked(remote::REMOTE_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
||||||
|
|
||||||
let (mut config, expected_digest) = remote::config()?;
|
let (mut config, expected_digest) = remote::config()?;
|
||||||
@ -301,10 +314,83 @@ pub fn delete_remote(name: String, digest: Option<String>) -> Result<(), Error>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper to get client for remote.cfg entry
|
||||||
|
pub async fn remote_client(remote: remote::Remote) -> Result<HttpClient, Error> {
|
||||||
|
let options = HttpClientOptions::new()
|
||||||
|
.password(Some(remote.password.clone()))
|
||||||
|
.fingerprint(remote.fingerprint.clone());
|
||||||
|
|
||||||
|
let client = HttpClient::new(
|
||||||
|
&remote.host,
|
||||||
|
remote.port.unwrap_or(8007),
|
||||||
|
&remote.auth_id,
|
||||||
|
options)?;
|
||||||
|
let _auth_info = client.login() // make sure we can auth
|
||||||
|
.await
|
||||||
|
.map_err(|err| format_err!("remote connection to '{}' failed - {}", remote.host, err))?;
|
||||||
|
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
name: {
|
||||||
|
schema: REMOTE_ID_SCHEMA,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
permission: &Permission::Privilege(&["remote", "{name}"], PRIV_REMOTE_AUDIT, false),
|
||||||
|
},
|
||||||
|
returns: {
|
||||||
|
description: "List the accessible datastores.",
|
||||||
|
type: Array,
|
||||||
|
items: {
|
||||||
|
description: "Datastore name and description.",
|
||||||
|
type: DataStoreListItem,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
/// List datastores of a remote.cfg entry
|
||||||
|
pub async fn scan_remote_datastores(name: String) -> Result<Vec<DataStoreListItem>, Error> {
|
||||||
|
let (remote_config, _digest) = remote::config()?;
|
||||||
|
let remote: remote::Remote = remote_config.lookup("remote", &name)?;
|
||||||
|
|
||||||
|
let map_remote_err = |api_err| {
|
||||||
|
http_err!(INTERNAL_SERVER_ERROR,
|
||||||
|
"failed to scan remote '{}' - {}",
|
||||||
|
&name,
|
||||||
|
api_err)
|
||||||
|
};
|
||||||
|
|
||||||
|
let client = remote_client(remote)
|
||||||
|
.await
|
||||||
|
.map_err(map_remote_err)?;
|
||||||
|
let api_res = client
|
||||||
|
.get("api2/json/admin/datastore", None)
|
||||||
|
.await
|
||||||
|
.map_err(map_remote_err)?;
|
||||||
|
let parse_res = match api_res.get("data") {
|
||||||
|
Some(data) => serde_json::from_value::<Vec<DataStoreListItem>>(data.to_owned()),
|
||||||
|
None => bail!("remote {} did not return any datastore list data", &name),
|
||||||
|
};
|
||||||
|
|
||||||
|
match parse_res {
|
||||||
|
Ok(parsed) => Ok(parsed),
|
||||||
|
Err(_) => bail!("Failed to parse remote scan api result."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SCAN_ROUTER: Router = Router::new()
|
||||||
|
.get(&API_METHOD_SCAN_REMOTE_DATASTORES);
|
||||||
|
|
||||||
const ITEM_ROUTER: Router = Router::new()
|
const ITEM_ROUTER: Router = Router::new()
|
||||||
.get(&API_METHOD_READ_REMOTE)
|
.get(&API_METHOD_READ_REMOTE)
|
||||||
.put(&API_METHOD_UPDATE_REMOTE)
|
.put(&API_METHOD_UPDATE_REMOTE)
|
||||||
.delete(&API_METHOD_DELETE_REMOTE);
|
.delete(&API_METHOD_DELETE_REMOTE)
|
||||||
|
.subdirs(&[("scan", &SCAN_ROUTER)]);
|
||||||
|
|
||||||
pub const ROUTER: Router = Router::new()
|
pub const ROUTER: Router = Router::new()
|
||||||
.get(&API_METHOD_LIST_REMOTES)
|
.get(&API_METHOD_LIST_REMOTES)
|
||||||
|
@ -58,7 +58,7 @@ pub fn check_sync_job_modify_access(
|
|||||||
&& owner.user() == auth_id.user())
|
&& owner.user() == auth_id.user())
|
||||||
},
|
},
|
||||||
// default sync owner
|
// default sync owner
|
||||||
None => auth_id == Authid::backup_auth_id(),
|
None => auth_id == Authid::root_auth_id(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// same permission as changing ownership after syncing
|
// same permission as changing ownership after syncing
|
||||||
@ -511,7 +511,7 @@ acl:1:/remote/remote1/remotestore1:write@pbs:RemoteSyncOperator
|
|||||||
job.owner = Some(read_auth_id.clone());
|
job.owner = Some(read_auth_id.clone());
|
||||||
assert_eq!(check_sync_job_modify_access(&user_info, &write_auth_id, &job), false);
|
assert_eq!(check_sync_job_modify_access(&user_info, &write_auth_id, &job), false);
|
||||||
|
|
||||||
// also not to the default 'backup@pam'
|
// also not to the default 'root@pam'
|
||||||
job.owner = None;
|
job.owner = None;
|
||||||
assert_eq!(check_sync_job_modify_access(&user_info, &write_auth_id, &job), false);
|
assert_eq!(check_sync_job_modify_access(&user_info, &write_auth_id, &job), false);
|
||||||
|
|
||||||
|
@ -9,10 +9,11 @@ use crate::api2::types::*;
|
|||||||
|
|
||||||
use crate::config::acl::{
|
use crate::config::acl::{
|
||||||
PRIV_DATASTORE_AUDIT,
|
PRIV_DATASTORE_AUDIT,
|
||||||
PRIV_DATASTORE_BACKUP,
|
|
||||||
PRIV_DATASTORE_VERIFY,
|
PRIV_DATASTORE_VERIFY,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::config::cached_user_info::CachedUserInfo;
|
||||||
|
|
||||||
use crate::config::verify::{self, VerificationJobConfig};
|
use crate::config::verify::{self, VerificationJobConfig};
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
@ -25,10 +26,8 @@ use crate::config::verify::{self, VerificationJobConfig};
|
|||||||
items: { type: verify::VerificationJobConfig },
|
items: { type: verify::VerificationJobConfig },
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
permission: &Permission::Privilege(
|
permission: &Permission::Anybody,
|
||||||
&["datastore", "{store}"],
|
description: "Requires Datastore.Audit or Datastore.Verify on datastore.",
|
||||||
PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP | PRIV_DATASTORE_VERIFY,
|
|
||||||
true),
|
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// List all verification jobs
|
/// List all verification jobs
|
||||||
@ -36,11 +35,22 @@ pub fn list_verification_jobs(
|
|||||||
_param: Value,
|
_param: Value,
|
||||||
mut rpcenv: &mut dyn RpcEnvironment,
|
mut rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<Vec<VerificationJobConfig>, Error> {
|
) -> Result<Vec<VerificationJobConfig>, Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
|
let required_privs = PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_VERIFY;
|
||||||
|
|
||||||
let (config, digest) = verify::config()?;
|
let (config, digest) = verify::config()?;
|
||||||
|
|
||||||
let list = config.convert_to_typed_array("verification")?;
|
let list = config.convert_to_typed_array("verification")?;
|
||||||
|
|
||||||
|
let list = list.into_iter()
|
||||||
|
.filter(|job: &VerificationJobConfig| {
|
||||||
|
let privs = user_info.lookup_privs(&auth_id, &["datastore", &job.store]);
|
||||||
|
|
||||||
|
privs & required_privs != 00
|
||||||
|
}).collect();
|
||||||
|
|
||||||
rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
|
rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
|
||||||
|
|
||||||
Ok(list)
|
Ok(list)
|
||||||
@ -76,19 +86,24 @@ pub fn list_verification_jobs(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
permission: &Permission::Privilege(
|
permission: &Permission::Anybody,
|
||||||
&["datastore", "{store}"],
|
description: "Requires Datastore.Verify on job's datastore.",
|
||||||
PRIV_DATASTORE_VERIFY,
|
|
||||||
true),
|
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// Create a new verification job.
|
/// Create a new verification job.
|
||||||
pub fn create_verification_job(param: Value) -> Result<(), Error> {
|
pub fn create_verification_job(
|
||||||
|
param: Value,
|
||||||
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
rpcenv: &mut dyn RpcEnvironment
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
let verification_job: verify::VerificationJobConfig = serde_json::from_value(param.clone())?;
|
let verification_job: verify::VerificationJobConfig = serde_json::from_value(param.clone())?;
|
||||||
|
|
||||||
|
user_info.check_privs(&auth_id, &["datastore", &verification_job.store], PRIV_DATASTORE_VERIFY, false)?;
|
||||||
|
|
||||||
|
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
||||||
|
|
||||||
let (mut config, _digest) = verify::config()?;
|
let (mut config, _digest) = verify::config()?;
|
||||||
|
|
||||||
if let Some(_) = config.sections.get(&verification_job.id) {
|
if let Some(_) = config.sections.get(&verification_job.id) {
|
||||||
@ -117,10 +132,8 @@ pub fn create_verification_job(param: Value) -> Result<(), Error> {
|
|||||||
type: verify::VerificationJobConfig,
|
type: verify::VerificationJobConfig,
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
permission: &Permission::Privilege(
|
permission: &Permission::Anybody,
|
||||||
&["datastore", "{store}"],
|
description: "Requires Datastore.Audit or Datastore.Verify on job's datastore.",
|
||||||
PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_BACKUP | PRIV_DATASTORE_VERIFY,
|
|
||||||
true),
|
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// Read a verification job configuration.
|
/// Read a verification job configuration.
|
||||||
@ -128,9 +141,16 @@ pub fn read_verification_job(
|
|||||||
id: String,
|
id: String,
|
||||||
mut rpcenv: &mut dyn RpcEnvironment,
|
mut rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<VerificationJobConfig, Error> {
|
) -> Result<VerificationJobConfig, Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
let (config, digest) = verify::config()?;
|
let (config, digest) = verify::config()?;
|
||||||
|
|
||||||
let verification_job = config.lookup("verification", &id)?;
|
let verification_job: verify::VerificationJobConfig = config.lookup("verification", &id)?;
|
||||||
|
|
||||||
|
let required_privs = PRIV_DATASTORE_AUDIT | PRIV_DATASTORE_VERIFY;
|
||||||
|
user_info.check_privs(&auth_id, &["datastore", &verification_job.store], required_privs, true)?;
|
||||||
|
|
||||||
rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
|
rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
|
||||||
|
|
||||||
Ok(verification_job)
|
Ok(verification_job)
|
||||||
@ -193,10 +213,8 @@ pub enum DeletableProperty {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
permission: &Permission::Privilege(
|
permission: &Permission::Anybody,
|
||||||
&["datastore", "{store}"],
|
description: "Requires Datastore.Verify on job's datastore.",
|
||||||
PRIV_DATASTORE_VERIFY,
|
|
||||||
true),
|
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// Update verification job config.
|
/// Update verification job config.
|
||||||
@ -209,7 +227,10 @@ pub fn update_verification_job(
|
|||||||
schedule: Option<String>,
|
schedule: Option<String>,
|
||||||
delete: Option<Vec<DeletableProperty>>,
|
delete: Option<Vec<DeletableProperty>>,
|
||||||
digest: Option<String>,
|
digest: Option<String>,
|
||||||
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
||||||
|
|
||||||
@ -223,7 +244,10 @@ pub fn update_verification_job(
|
|||||||
|
|
||||||
let mut data: verify::VerificationJobConfig = config.lookup("verification", &id)?;
|
let mut data: verify::VerificationJobConfig = config.lookup("verification", &id)?;
|
||||||
|
|
||||||
if let Some(delete) = delete {
|
// check existing store
|
||||||
|
user_info.check_privs(&auth_id, &["datastore", &data.store], PRIV_DATASTORE_VERIFY, true)?;
|
||||||
|
|
||||||
|
if let Some(delete) = delete {
|
||||||
for delete_prop in delete {
|
for delete_prop in delete {
|
||||||
match delete_prop {
|
match delete_prop {
|
||||||
DeletableProperty::IgnoreVerified => { data.ignore_verified = None; },
|
DeletableProperty::IgnoreVerified => { data.ignore_verified = None; },
|
||||||
@ -243,7 +267,12 @@ pub fn update_verification_job(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(store) = store { data.store = store; }
|
if let Some(store) = store {
|
||||||
|
// check new store
|
||||||
|
user_info.check_privs(&auth_id, &["datastore", &store], PRIV_DATASTORE_VERIFY, true)?;
|
||||||
|
data.store = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
if ignore_verified.is_some() { data.ignore_verified = ignore_verified; }
|
if ignore_verified.is_some() { data.ignore_verified = ignore_verified; }
|
||||||
if outdated_after.is_some() { data.outdated_after = outdated_after; }
|
if outdated_after.is_some() { data.outdated_after = outdated_after; }
|
||||||
@ -270,19 +299,26 @@ pub fn update_verification_job(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
permission: &Permission::Privilege(
|
permission: &Permission::Anybody,
|
||||||
&["datastore", "{store}"],
|
description: "Requires Datastore.Verify on job's datastore.",
|
||||||
PRIV_DATASTORE_VERIFY,
|
|
||||||
true),
|
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// Remove a verification job configuration
|
/// Remove a verification job configuration
|
||||||
pub fn delete_verification_job(id: String, digest: Option<String>) -> Result<(), Error> {
|
pub fn delete_verification_job(
|
||||||
|
id: String,
|
||||||
|
digest: Option<String>,
|
||||||
|
rpcenv: &mut dyn RpcEnvironment,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
|
||||||
|
let user_info = CachedUserInfo::new()?;
|
||||||
|
|
||||||
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
let _lock = open_file_locked(verify::VERIFICATION_CFG_LOCKFILE, std::time::Duration::new(10, 0), true)?;
|
||||||
|
|
||||||
let (mut config, expected_digest) = verify::config()?;
|
let (mut config, expected_digest) = verify::config()?;
|
||||||
|
|
||||||
|
let job: verify::VerificationJobConfig = config.lookup("verification", &id)?;
|
||||||
|
user_info.check_privs(&auth_id, &["datastore", &job.store], PRIV_DATASTORE_VERIFY, true)?;
|
||||||
|
|
||||||
if let Some(ref digest) = digest {
|
if let Some(ref digest) = digest {
|
||||||
let digest = proxmox::tools::hex_to_digest(digest)?;
|
let digest = proxmox::tools::hex_to_digest(digest)?;
|
||||||
crate::tools::detect_modified_configuration_file(&digest, &expected_digest)?;
|
crate::tools::detect_modified_configuration_file(&digest, &expected_digest)?;
|
||||||
|
@ -34,7 +34,7 @@ pub mod subscription;
|
|||||||
pub(crate) mod rrd;
|
pub(crate) mod rrd;
|
||||||
|
|
||||||
mod journal;
|
mod journal;
|
||||||
mod services;
|
pub(crate) mod services;
|
||||||
mod status;
|
mod status;
|
||||||
mod syslog;
|
mod syslog;
|
||||||
mod time;
|
mod time;
|
||||||
|
@ -1,12 +1,13 @@
|
|||||||
use anyhow::{Error, bail, format_err};
|
use anyhow::{Error, bail, format_err};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use proxmox::list_subdirs_api_method;
|
use proxmox::list_subdirs_api_method;
|
||||||
use proxmox::api::{api, RpcEnvironment, RpcEnvironmentType, Permission};
|
use proxmox::api::{api, RpcEnvironment, RpcEnvironmentType, Permission};
|
||||||
use proxmox::api::router::{Router, SubdirMap};
|
use proxmox::api::router::{Router, SubdirMap};
|
||||||
|
|
||||||
use crate::server::WorkerTask;
|
use crate::server::WorkerTask;
|
||||||
use crate::tools::{apt, http};
|
use crate::tools::{apt, http, subscription};
|
||||||
|
|
||||||
use crate::config::acl::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY};
|
use crate::config::acl::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY};
|
||||||
use crate::api2::types::{Authid, APTUpdateInfo, NODE_SCHEMA, UPID_SCHEMA};
|
use crate::api2::types::{Authid, APTUpdateInfo, NODE_SCHEMA, UPID_SCHEMA};
|
||||||
@ -202,9 +203,34 @@ fn apt_get_changelog(
|
|||||||
let changelog_url = &pkg_info[0].change_log_url;
|
let changelog_url = &pkg_info[0].change_log_url;
|
||||||
// FIXME: use 'apt-get changelog' for proxmox packages as well, once repo supports it
|
// FIXME: use 'apt-get changelog' for proxmox packages as well, once repo supports it
|
||||||
if changelog_url.starts_with("http://download.proxmox.com/") {
|
if changelog_url.starts_with("http://download.proxmox.com/") {
|
||||||
let changelog = crate::tools::runtime::block_on(http::get_string(changelog_url))
|
let changelog = crate::tools::runtime::block_on(http::get_string(changelog_url, None))
|
||||||
.map_err(|err| format_err!("Error downloading changelog from '{}': {}", changelog_url, err))?;
|
.map_err(|err| format_err!("Error downloading changelog from '{}': {}", changelog_url, err))?;
|
||||||
return Ok(json!(changelog));
|
return Ok(json!(changelog));
|
||||||
|
|
||||||
|
} else if changelog_url.starts_with("https://enterprise.proxmox.com/") {
|
||||||
|
let sub = match subscription::read_subscription()? {
|
||||||
|
Some(sub) => sub,
|
||||||
|
None => bail!("cannot retrieve changelog from enterprise repo: no subscription info found")
|
||||||
|
};
|
||||||
|
let (key, id) = match sub.key {
|
||||||
|
Some(key) => {
|
||||||
|
match sub.serverid {
|
||||||
|
Some(id) => (key, id),
|
||||||
|
None =>
|
||||||
|
bail!("cannot retrieve changelog from enterprise repo: no server id found")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => bail!("cannot retrieve changelog from enterprise repo: no subscription key found")
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut auth_header = HashMap::new();
|
||||||
|
auth_header.insert("Authorization".to_owned(),
|
||||||
|
format!("Basic {}", base64::encode(format!("{}:{}", key, id))));
|
||||||
|
|
||||||
|
let changelog = crate::tools::runtime::block_on(http::get_string(changelog_url, Some(&auth_header)))
|
||||||
|
.map_err(|err| format_err!("Error downloading changelog from '{}': {}", changelog_url, err))?;
|
||||||
|
return Ok(json!(changelog));
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
let mut command = std::process::Command::new("apt-get");
|
let mut command = std::process::Command::new("apt-get");
|
||||||
command.arg("changelog");
|
command.arg("changelog");
|
||||||
@ -215,12 +241,128 @@ fn apt_get_changelog(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
node: {
|
||||||
|
schema: NODE_SCHEMA,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
returns: {
|
||||||
|
description: "List of more relevant packages.",
|
||||||
|
type: Array,
|
||||||
|
items: {
|
||||||
|
type: APTUpdateInfo,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
permission: &Permission::Privilege(&[], PRIV_SYS_AUDIT, false),
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
/// Get package information for important Proxmox Backup Server packages.
|
||||||
|
pub fn get_versions() -> Result<Vec<APTUpdateInfo>, Error> {
|
||||||
|
const PACKAGES: &[&str] = &[
|
||||||
|
"ifupdown2",
|
||||||
|
"libjs-extjs",
|
||||||
|
"proxmox-backup",
|
||||||
|
"proxmox-backup-docs",
|
||||||
|
"proxmox-backup-client",
|
||||||
|
"proxmox-backup-server",
|
||||||
|
"proxmox-mini-journalreader",
|
||||||
|
"proxmox-widget-toolkit",
|
||||||
|
"pve-xtermjs",
|
||||||
|
"smartmontools",
|
||||||
|
"zfsutils-linux",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn unknown_package(package: String, extra_info: Option<String>) -> APTUpdateInfo {
|
||||||
|
APTUpdateInfo {
|
||||||
|
package,
|
||||||
|
title: "unknown".into(),
|
||||||
|
arch: "unknown".into(),
|
||||||
|
description: "unknown".into(),
|
||||||
|
version: "unknown".into(),
|
||||||
|
old_version: "unknown".into(),
|
||||||
|
origin: "unknown".into(),
|
||||||
|
priority: "unknown".into(),
|
||||||
|
section: "unknown".into(),
|
||||||
|
change_log_url: "unknown".into(),
|
||||||
|
extra_info,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let is_kernel = |name: &str| name.starts_with("pve-kernel-");
|
||||||
|
|
||||||
|
let mut packages: Vec<APTUpdateInfo> = Vec::new();
|
||||||
|
let pbs_packages = apt::list_installed_apt_packages(
|
||||||
|
|filter| {
|
||||||
|
filter.installed_version == Some(filter.active_version)
|
||||||
|
&& (is_kernel(filter.package) || PACKAGES.contains(&filter.package))
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
let running_kernel = format!(
|
||||||
|
"running kernel: {}",
|
||||||
|
nix::sys::utsname::uname().release().to_owned()
|
||||||
|
);
|
||||||
|
if let Some(proxmox_backup) = pbs_packages.iter().find(|pkg| pkg.package == "proxmox-backup") {
|
||||||
|
let mut proxmox_backup = proxmox_backup.clone();
|
||||||
|
proxmox_backup.extra_info = Some(running_kernel);
|
||||||
|
packages.push(proxmox_backup);
|
||||||
|
} else {
|
||||||
|
packages.push(unknown_package("proxmox-backup".into(), Some(running_kernel)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let version = crate::api2::version::PROXMOX_PKG_VERSION;
|
||||||
|
let release = crate::api2::version::PROXMOX_PKG_RELEASE;
|
||||||
|
let daemon_version_info = Some(format!("running version: {}.{}", version, release));
|
||||||
|
if let Some(pkg) = pbs_packages.iter().find(|pkg| pkg.package == "proxmox-backup-server") {
|
||||||
|
let mut pkg = pkg.clone();
|
||||||
|
pkg.extra_info = daemon_version_info;
|
||||||
|
packages.push(pkg);
|
||||||
|
} else {
|
||||||
|
packages.push(unknown_package("proxmox-backup".into(), daemon_version_info));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut kernel_pkgs: Vec<APTUpdateInfo> = pbs_packages
|
||||||
|
.iter()
|
||||||
|
.filter(|pkg| is_kernel(&pkg.package))
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
// make sure the cache mutex gets dropped before the next call to list_installed_apt_packages
|
||||||
|
{
|
||||||
|
let cache = apt_pkg_native::Cache::get_singleton();
|
||||||
|
kernel_pkgs.sort_by(|left, right| {
|
||||||
|
cache
|
||||||
|
.compare_versions(&left.old_version, &right.old_version)
|
||||||
|
.reverse()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
packages.append(&mut kernel_pkgs);
|
||||||
|
|
||||||
|
// add entry for all packages we're interested in, even if not installed
|
||||||
|
for pkg in PACKAGES.iter() {
|
||||||
|
if pkg == &"proxmox-backup" || pkg == &"proxmox-backup-server" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match pbs_packages.iter().find(|item| &item.package == pkg) {
|
||||||
|
Some(apt_pkg) => packages.push(apt_pkg.to_owned()),
|
||||||
|
None => packages.push(unknown_package(pkg.to_string(), None)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(packages)
|
||||||
|
}
|
||||||
|
|
||||||
const SUBDIRS: SubdirMap = &[
|
const SUBDIRS: SubdirMap = &[
|
||||||
("changelog", &Router::new().get(&API_METHOD_APT_GET_CHANGELOG)),
|
("changelog", &Router::new().get(&API_METHOD_APT_GET_CHANGELOG)),
|
||||||
("update", &Router::new()
|
("update", &Router::new()
|
||||||
.get(&API_METHOD_APT_UPDATE_AVAILABLE)
|
.get(&API_METHOD_APT_UPDATE_AVAILABLE)
|
||||||
.post(&API_METHOD_APT_UPDATE_DATABASE)
|
.post(&API_METHOD_APT_UPDATE_DATABASE)
|
||||||
),
|
),
|
||||||
|
("versions", &Router::new().get(&API_METHOD_GET_VERSIONS)),
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const ROUTER: Router = Router::new()
|
pub const ROUTER: Router = Router::new()
|
||||||
|
@ -142,6 +142,18 @@ pub fn create_datastore_disk(
|
|||||||
bail!("disk '{}' is already in use.", disk);
|
bail!("disk '{}' is already in use.", disk);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mount_point = format!("/mnt/datastore/{}", &name);
|
||||||
|
|
||||||
|
// check if the default path does exist already and bail if it does
|
||||||
|
let default_path = std::path::PathBuf::from(&mount_point);
|
||||||
|
|
||||||
|
match std::fs::metadata(&default_path) {
|
||||||
|
Err(_) => {}, // path does not exist
|
||||||
|
Ok(_) => {
|
||||||
|
bail!("path {:?} already exists", default_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let upid_str = WorkerTask::new_thread(
|
let upid_str = WorkerTask::new_thread(
|
||||||
"dircreate", Some(name.clone()), auth_id, to_stdout, move |worker|
|
"dircreate", Some(name.clone()), auth_id, to_stdout, move |worker|
|
||||||
{
|
{
|
||||||
@ -160,7 +172,7 @@ pub fn create_datastore_disk(
|
|||||||
let uuid = get_fs_uuid(&partition)?;
|
let uuid = get_fs_uuid(&partition)?;
|
||||||
let uuid_path = format!("/dev/disk/by-uuid/{}", uuid);
|
let uuid_path = format!("/dev/disk/by-uuid/{}", uuid);
|
||||||
|
|
||||||
let (mount_unit_name, mount_point) = create_datastore_mount_unit(&name, filesystem, &uuid_path)?;
|
let mount_unit_name = create_datastore_mount_unit(&name, &mount_point, filesystem, &uuid_path)?;
|
||||||
|
|
||||||
systemd::reload_daemon()?;
|
systemd::reload_daemon()?;
|
||||||
systemd::enable_unit(&mount_unit_name)?;
|
systemd::enable_unit(&mount_unit_name)?;
|
||||||
@ -243,11 +255,11 @@ pub const ROUTER: Router = Router::new()
|
|||||||
|
|
||||||
fn create_datastore_mount_unit(
|
fn create_datastore_mount_unit(
|
||||||
datastore_name: &str,
|
datastore_name: &str,
|
||||||
|
mount_point: &str,
|
||||||
fs_type: FileSystemType,
|
fs_type: FileSystemType,
|
||||||
what: &str,
|
what: &str,
|
||||||
) -> Result<(String, String), Error> {
|
) -> Result<String, Error> {
|
||||||
|
|
||||||
let mount_point = format!("/mnt/datastore/{}", datastore_name);
|
|
||||||
let mut mount_unit_name = systemd::escape_unit(&mount_point, true);
|
let mut mount_unit_name = systemd::escape_unit(&mount_point, true);
|
||||||
mount_unit_name.push_str(".mount");
|
mount_unit_name.push_str(".mount");
|
||||||
|
|
||||||
@ -265,7 +277,7 @@ fn create_datastore_mount_unit(
|
|||||||
|
|
||||||
let mount = SystemdMountSection {
|
let mount = SystemdMountSection {
|
||||||
What: what.to_string(),
|
What: what.to_string(),
|
||||||
Where: mount_point.clone(),
|
Where: mount_point.to_string(),
|
||||||
Type: Some(fs_type.to_string()),
|
Type: Some(fs_type.to_string()),
|
||||||
Options: Some(String::from("defaults")),
|
Options: Some(String::from("defaults")),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@ -278,5 +290,5 @@ fn create_datastore_mount_unit(
|
|||||||
|
|
||||||
systemd::config::save_systemd_mount(&mount_unit_path, &config)?;
|
systemd::config::save_systemd_mount(&mount_unit_path, &config)?;
|
||||||
|
|
||||||
Ok((mount_unit_name, mount_point))
|
Ok(mount_unit_name)
|
||||||
}
|
}
|
||||||
|
@ -243,7 +243,7 @@ pub fn zpool_details(
|
|||||||
permission: &Permission::Privilege(&["system", "disks"], PRIV_SYS_MODIFY, false),
|
permission: &Permission::Privilege(&["system", "disks"], PRIV_SYS_MODIFY, false),
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
/// Create a new ZFS pool.
|
/// Create a new ZFS pool. Will be mounted under '/mnt/datastore/<name>'.
|
||||||
pub fn create_zpool(
|
pub fn create_zpool(
|
||||||
name: String,
|
name: String,
|
||||||
devices: String,
|
devices: String,
|
||||||
@ -303,10 +303,11 @@ pub fn create_zpool(
|
|||||||
bail!("{:?} needs at least {} disks.", raidlevel, min_disks);
|
bail!("{:?} needs at least {} disks.", raidlevel, min_disks);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mount_point = format!("/mnt/datastore/{}", &name);
|
||||||
|
|
||||||
// check if the default path does exist already and bail if it does
|
// check if the default path does exist already and bail if it does
|
||||||
// otherwise we get an error on mounting
|
// otherwise 'zpool create' aborts after partitioning, but before creating the pool
|
||||||
let mut default_path = std::path::PathBuf::from("/");
|
let default_path = std::path::PathBuf::from(&mount_point);
|
||||||
default_path.push(&name);
|
|
||||||
|
|
||||||
match std::fs::metadata(&default_path) {
|
match std::fs::metadata(&default_path) {
|
||||||
Err(_) => {}, // path does not exist
|
Err(_) => {}, // path does not exist
|
||||||
@ -322,7 +323,7 @@ pub fn create_zpool(
|
|||||||
|
|
||||||
|
|
||||||
let mut command = std::process::Command::new("zpool");
|
let mut command = std::process::Command::new("zpool");
|
||||||
command.args(&["create", "-o", &format!("ashift={}", ashift), &name]);
|
command.args(&["create", "-o", &format!("ashift={}", ashift), "-m", &mount_point, &name]);
|
||||||
|
|
||||||
match raidlevel {
|
match raidlevel {
|
||||||
ZfsRaidLevel::Single => {
|
ZfsRaidLevel::Single => {
|
||||||
@ -371,7 +372,6 @@ pub fn create_zpool(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if add_datastore {
|
if add_datastore {
|
||||||
let mount_point = format!("/{}", name);
|
|
||||||
crate::api2::config::datastore::create_datastore(json!({ "name": name, "path": mount_point }))?
|
crate::api2::config::datastore::create_datastore(json!({ "name": name, "path": mount_point }))?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,7 +22,7 @@ static SERVICE_NAME_LIST: [&str; 7] = [
|
|||||||
"systemd-timesyncd",
|
"systemd-timesyncd",
|
||||||
];
|
];
|
||||||
|
|
||||||
fn real_service_name(service: &str) -> &str {
|
pub fn real_service_name(service: &str) -> &str {
|
||||||
|
|
||||||
// since postfix package 3.1.0-3.1 the postfix unit is only here
|
// since postfix package 3.1.0-3.1 the postfix unit is only here
|
||||||
// to manage subinstances, of which the default is called "-".
|
// to manage subinstances, of which the default is called "-".
|
||||||
|
@ -134,12 +134,18 @@ fn get_syslog(
|
|||||||
mut rpcenv: &mut dyn RpcEnvironment,
|
mut rpcenv: &mut dyn RpcEnvironment,
|
||||||
) -> Result<Value, Error> {
|
) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let service = if let Some(service) = param["service"].as_str() {
|
||||||
|
Some(crate::api2::node::services::real_service_name(service))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
let (count, lines) = dump_journal(
|
let (count, lines) = dump_journal(
|
||||||
param["start"].as_u64(),
|
param["start"].as_u64(),
|
||||||
param["limit"].as_u64(),
|
param["limit"].as_u64(),
|
||||||
param["since"].as_str(),
|
param["since"].as_str(),
|
||||||
param["until"].as_str(),
|
param["until"].as_str(),
|
||||||
param["service"].as_str())?;
|
service)?;
|
||||||
|
|
||||||
rpcenv["total"] = Value::from(count);
|
rpcenv["total"] = Value::from(count);
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{BufRead, BufReader};
|
use std::io::{BufRead, BufReader};
|
||||||
|
|
||||||
use anyhow::{Error};
|
use anyhow::{bail, Error};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
use proxmox::api::{api, Router, RpcEnvironment, Permission};
|
use proxmox::api::{api, Router, RpcEnvironment, Permission};
|
||||||
@ -9,19 +9,117 @@ use proxmox::api::router::SubdirMap;
|
|||||||
use proxmox::{identity, list_subdirs_api_method, sortable};
|
use proxmox::{identity, list_subdirs_api_method, sortable};
|
||||||
|
|
||||||
use crate::tools;
|
use crate::tools;
|
||||||
|
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
|
use crate::api2::pull::check_pull_privs;
|
||||||
|
|
||||||
use crate::server::{self, UPID, TaskState, TaskListInfoIterator};
|
use crate::server::{self, UPID, TaskState, TaskListInfoIterator};
|
||||||
use crate::config::acl::{PRIV_SYS_AUDIT, PRIV_SYS_MODIFY};
|
use crate::config::acl::{
|
||||||
|
PRIV_DATASTORE_MODIFY,
|
||||||
|
PRIV_DATASTORE_VERIFY,
|
||||||
|
PRIV_SYS_AUDIT,
|
||||||
|
PRIV_SYS_MODIFY,
|
||||||
|
};
|
||||||
use crate::config::cached_user_info::CachedUserInfo;
|
use crate::config::cached_user_info::CachedUserInfo;
|
||||||
|
|
||||||
|
// matches respective job execution privileges
|
||||||
|
fn check_job_privs(auth_id: &Authid, user_info: &CachedUserInfo, upid: &UPID) -> Result<(), Error> {
|
||||||
|
match (upid.worker_type.as_str(), &upid.worker_id) {
|
||||||
|
("verificationjob", Some(workerid)) => {
|
||||||
|
if let Some(captures) = VERIFICATION_JOB_WORKER_ID_REGEX.captures(&workerid) {
|
||||||
|
if let Some(store) = captures.get(1) {
|
||||||
|
return user_info.check_privs(&auth_id,
|
||||||
|
&["datastore", store.as_str()],
|
||||||
|
PRIV_DATASTORE_VERIFY,
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
("syncjob", Some(workerid)) => {
|
||||||
|
if let Some(captures) = SYNC_JOB_WORKER_ID_REGEX.captures(&workerid) {
|
||||||
|
let remote = captures.get(1);
|
||||||
|
let remote_store = captures.get(2);
|
||||||
|
let local_store = captures.get(3);
|
||||||
|
|
||||||
|
if let (Some(remote), Some(remote_store), Some(local_store)) =
|
||||||
|
(remote, remote_store, local_store) {
|
||||||
|
|
||||||
|
return check_pull_privs(&auth_id,
|
||||||
|
local_store.as_str(),
|
||||||
|
remote.as_str(),
|
||||||
|
remote_store.as_str(),
|
||||||
|
false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
("garbage_collection", Some(workerid)) => {
|
||||||
|
return user_info.check_privs(&auth_id,
|
||||||
|
&["datastore", &workerid],
|
||||||
|
PRIV_DATASTORE_MODIFY,
|
||||||
|
true)
|
||||||
|
},
|
||||||
|
("prune", Some(workerid)) => {
|
||||||
|
return user_info.check_privs(&auth_id,
|
||||||
|
&["datastore",
|
||||||
|
&workerid],
|
||||||
|
PRIV_DATASTORE_MODIFY,
|
||||||
|
true);
|
||||||
|
},
|
||||||
|
_ => bail!("not a scheduled job task"),
|
||||||
|
};
|
||||||
|
|
||||||
|
bail!("not a scheduled job task");
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the store out of the worker_id
|
||||||
|
fn check_job_store(upid: &UPID, store: &str) -> bool {
|
||||||
|
match (upid.worker_type.as_str(), &upid.worker_id) {
|
||||||
|
(workertype, Some(workerid)) if workertype.starts_with("verif") => {
|
||||||
|
if let Some(captures) = VERIFICATION_JOB_WORKER_ID_REGEX.captures(&workerid) {
|
||||||
|
if let Some(jobstore) = captures.get(1) {
|
||||||
|
return store == jobstore.as_str();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return workerid == store;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("syncjob", Some(workerid)) => {
|
||||||
|
if let Some(captures) = SYNC_JOB_WORKER_ID_REGEX.captures(&workerid) {
|
||||||
|
if let Some(local_store) = captures.get(3) {
|
||||||
|
return store == local_store.as_str();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("prune", Some(workerid))
|
||||||
|
| ("backup", Some(workerid))
|
||||||
|
| ("garbage_collection", Some(workerid)) => {
|
||||||
|
return workerid == store || workerid.starts_with(&format!("{}:", store));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
};
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
fn check_task_access(auth_id: &Authid, upid: &UPID) -> Result<(), Error> {
|
fn check_task_access(auth_id: &Authid, upid: &UPID) -> Result<(), Error> {
|
||||||
let task_auth_id = &upid.auth_id;
|
let task_auth_id = &upid.auth_id;
|
||||||
if auth_id == task_auth_id
|
if auth_id == task_auth_id
|
||||||
|| (task_auth_id.is_token() && &Authid::from(task_auth_id.user().clone()) == auth_id) {
|
|| (task_auth_id.is_token() && &Authid::from(task_auth_id.user().clone()) == auth_id) {
|
||||||
|
// task owner can always read
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
let user_info = CachedUserInfo::new()?;
|
let user_info = CachedUserInfo::new()?;
|
||||||
user_info.check_privs(auth_id, &["system", "tasks"], PRIV_SYS_AUDIT, false)
|
|
||||||
|
let task_privs = user_info.lookup_privs(auth_id, &["system", "tasks"]);
|
||||||
|
if task_privs & PRIV_SYS_AUDIT != 0 {
|
||||||
|
// allowed to read all tasks in general
|
||||||
|
Ok(())
|
||||||
|
} else if check_job_privs(&auth_id, &user_info, upid).is_ok() {
|
||||||
|
// job which the user/token could have configured/manually executed
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
bail!("task access not allowed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -387,21 +485,8 @@ pub fn list_tasks(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(store) = store {
|
if let Some(store) = store {
|
||||||
// Note: useful to select all tasks spawned by proxmox-backup-client
|
if !check_job_store(&info.upid, store) {
|
||||||
let worker_id = match &info.upid.worker_id {
|
return None;
|
||||||
Some(w) => w,
|
|
||||||
None => return None, // skip
|
|
||||||
};
|
|
||||||
|
|
||||||
if info.upid.worker_type == "backup" || info.upid.worker_type == "restore" ||
|
|
||||||
info.upid.worker_type == "prune"
|
|
||||||
{
|
|
||||||
let prefix = format!("{}:", store);
|
|
||||||
if !worker_id.starts_with(&prefix) { return None; }
|
|
||||||
} else if info.upid.worker_type == "garbage_collection" {
|
|
||||||
if worker_id != store { return None; }
|
|
||||||
} else {
|
|
||||||
return None; // skip
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -9,7 +9,7 @@ use proxmox::api::{ApiMethod, Router, RpcEnvironment, Permission};
|
|||||||
|
|
||||||
use crate::server::{WorkerTask, jobstate::Job};
|
use crate::server::{WorkerTask, jobstate::Job};
|
||||||
use crate::backup::DataStore;
|
use crate::backup::DataStore;
|
||||||
use crate::client::{HttpClient, HttpClientOptions, BackupRepository, pull::pull_store};
|
use crate::client::{HttpClient, BackupRepository, pull::pull_store};
|
||||||
use crate::api2::types::*;
|
use crate::api2::types::*;
|
||||||
use crate::config::{
|
use crate::config::{
|
||||||
remote,
|
remote,
|
||||||
@ -50,17 +50,9 @@ pub async fn get_pull_parameters(
|
|||||||
let (remote_config, _digest) = remote::config()?;
|
let (remote_config, _digest) = remote::config()?;
|
||||||
let remote: remote::Remote = remote_config.lookup("remote", remote)?;
|
let remote: remote::Remote = remote_config.lookup("remote", remote)?;
|
||||||
|
|
||||||
let options = HttpClientOptions::new()
|
let src_repo = BackupRepository::new(Some(remote.auth_id.clone()), Some(remote.host.clone()), remote.port, remote_store.to_string());
|
||||||
.password(Some(remote.password.clone()))
|
|
||||||
.fingerprint(remote.fingerprint.clone());
|
|
||||||
|
|
||||||
let src_repo = BackupRepository::new(Some(remote.userid.clone()), Some(remote.host.clone()), remote.port, remote_store.to_string());
|
|
||||||
|
|
||||||
let client = HttpClient::new(&src_repo.host(), src_repo.port(), &src_repo.auth_id(), options)?;
|
|
||||||
let _auth_info = client.login() // make sure we can auth
|
|
||||||
.await
|
|
||||||
.map_err(|err| format_err!("remote connection to '{}' failed - {}", remote.host, err))?;
|
|
||||||
|
|
||||||
|
let client = crate::api2::config::remote::remote_client(remote).await?;
|
||||||
|
|
||||||
Ok((client, src_repo, tgt_store))
|
Ok((client, src_repo, tgt_store))
|
||||||
}
|
}
|
||||||
@ -72,14 +64,18 @@ pub fn do_sync_job(
|
|||||||
schedule: Option<String>,
|
schedule: Option<String>,
|
||||||
) -> Result<String, Error> {
|
) -> Result<String, Error> {
|
||||||
|
|
||||||
let job_id = job.jobname().to_string();
|
let job_id = format!("{}:{}:{}:{}",
|
||||||
|
sync_job.remote,
|
||||||
|
sync_job.remote_store,
|
||||||
|
sync_job.store,
|
||||||
|
job.jobname());
|
||||||
let worker_type = job.jobtype().to_string();
|
let worker_type = job.jobtype().to_string();
|
||||||
|
|
||||||
let email = crate::server::lookup_user_email(auth_id.user());
|
let (email, notify) = crate::server::lookup_datastore_notify_settings(&sync_job.store);
|
||||||
|
|
||||||
let upid_str = WorkerTask::spawn(
|
let upid_str = WorkerTask::spawn(
|
||||||
&worker_type,
|
&worker_type,
|
||||||
Some(job.jobname().to_string()),
|
Some(job_id.clone()),
|
||||||
auth_id.clone(),
|
auth_id.clone(),
|
||||||
false,
|
false,
|
||||||
move |worker| async move {
|
move |worker| async move {
|
||||||
@ -92,7 +88,7 @@ pub fn do_sync_job(
|
|||||||
let worker_future = async move {
|
let worker_future = async move {
|
||||||
|
|
||||||
let delete = sync_job.remove_vanished.unwrap_or(true);
|
let delete = sync_job.remove_vanished.unwrap_or(true);
|
||||||
let sync_owner = sync_job.owner.unwrap_or(Authid::backup_auth_id().clone());
|
let sync_owner = sync_job.owner.unwrap_or(Authid::root_auth_id().clone());
|
||||||
let (client, src_repo, tgt_store) = get_pull_parameters(&sync_job.store, &sync_job.remote, &sync_job.remote_store).await?;
|
let (client, src_repo, tgt_store) = get_pull_parameters(&sync_job.store, &sync_job.remote, &sync_job.remote_store).await?;
|
||||||
|
|
||||||
worker.log(format!("Starting datastore sync job '{}'", job_id));
|
worker.log(format!("Starting datastore sync job '{}'", job_id));
|
||||||
@ -126,7 +122,7 @@ pub fn do_sync_job(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(email) = email {
|
if let Some(email) = email {
|
||||||
if let Err(err) = crate::server::send_sync_status(&email, &sync_job2, &result) {
|
if let Err(err) = crate::server::send_sync_status(&email, notify, &sync_job2, &result) {
|
||||||
eprintln!("send sync notification failed: {}", err);
|
eprintln!("send sync notification failed: {}", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -103,6 +103,7 @@ fn datastore_status(
|
|||||||
"total": status.total,
|
"total": status.total,
|
||||||
"used": status.used,
|
"used": status.used,
|
||||||
"avail": status.avail,
|
"avail": status.avail,
|
||||||
|
"gc-status": datastore.last_gc_status(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let rrd_dir = format!("datastore/{}", store);
|
let rrd_dir = format!("datastore/{}", store);
|
||||||
@ -152,6 +153,8 @@ fn datastore_status(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
entry["history-start"] = start.into();
|
||||||
|
entry["history-delta"] = reso.into();
|
||||||
entry["history"] = history.into();
|
entry["history"] = history.into();
|
||||||
|
|
||||||
// we skip the calculation for datastores with not enough data
|
// we skip the calculation for datastores with not enough data
|
||||||
|
@ -5,7 +5,7 @@ use proxmox::api::{api, schema::*};
|
|||||||
use proxmox::const_regex;
|
use proxmox::const_regex;
|
||||||
use proxmox::{IPRE, IPRE_BRACKET, IPV4RE, IPV6RE, IPV4OCTET, IPV6H16, IPV6LS32};
|
use proxmox::{IPRE, IPRE_BRACKET, IPV4RE, IPV6RE, IPV4OCTET, IPV6H16, IPV6LS32};
|
||||||
|
|
||||||
use crate::backup::{CryptMode, BACKUP_ID_REGEX};
|
use crate::backup::{CryptMode, Fingerprint, BACKUP_ID_REGEX};
|
||||||
use crate::server::UPID;
|
use crate::server::UPID;
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
@ -59,6 +59,11 @@ const_regex!{
|
|||||||
/// any identifier command line tools work with.
|
/// any identifier command line tools work with.
|
||||||
pub PROXMOX_SAFE_ID_REGEX = concat!(r"^", PROXMOX_SAFE_ID_REGEX_STR!(), r"$");
|
pub PROXMOX_SAFE_ID_REGEX = concat!(r"^", PROXMOX_SAFE_ID_REGEX_STR!(), r"$");
|
||||||
|
|
||||||
|
/// Regex for verification jobs 'DATASTORE:ACTUAL_JOB_ID'
|
||||||
|
pub VERIFICATION_JOB_WORKER_ID_REGEX = concat!(r"^(", PROXMOX_SAFE_ID_REGEX_STR!(), r"):");
|
||||||
|
/// Regex for sync jobs 'REMOTE:REMOTE_DATASTORE:LOCAL_DATASTORE:ACTUAL_JOB_ID'
|
||||||
|
pub SYNC_JOB_WORKER_ID_REGEX = concat!(r"^(", PROXMOX_SAFE_ID_REGEX_STR!(), r"):(", PROXMOX_SAFE_ID_REGEX_STR!(), r"):(", PROXMOX_SAFE_ID_REGEX_STR!(), r"):");
|
||||||
|
|
||||||
pub SINGLE_LINE_COMMENT_REGEX = r"^[[:^cntrl:]]*$";
|
pub SINGLE_LINE_COMMENT_REGEX = r"^[[:^cntrl:]]*$";
|
||||||
|
|
||||||
pub HOSTNAME_REGEX = r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?)$";
|
pub HOSTNAME_REGEX = r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?)$";
|
||||||
@ -370,6 +375,25 @@ pub const BLOCKDEVICE_NAME_SCHEMA: Schema = StringSchema::new("Block device name
|
|||||||
|
|
||||||
// Complex type definitions
|
// Complex type definitions
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
properties: {
|
||||||
|
store: {
|
||||||
|
schema: DATASTORE_SCHEMA,
|
||||||
|
},
|
||||||
|
comment: {
|
||||||
|
optional: true,
|
||||||
|
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all="kebab-case")]
|
||||||
|
/// Basic information about a datastore.
|
||||||
|
pub struct DataStoreListItem {
|
||||||
|
pub store: String,
|
||||||
|
pub comment: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
properties: {
|
properties: {
|
||||||
"backup-type": {
|
"backup-type": {
|
||||||
@ -460,6 +484,10 @@ pub struct SnapshotVerifyState {
|
|||||||
type: SnapshotVerifyState,
|
type: SnapshotVerifyState,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
fingerprint: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
files: {
|
files: {
|
||||||
items: {
|
items: {
|
||||||
schema: BACKUP_ARCHIVE_NAME_SCHEMA
|
schema: BACKUP_ARCHIVE_NAME_SCHEMA
|
||||||
@ -484,6 +512,9 @@ pub struct SnapshotListItem {
|
|||||||
/// The result of the last run verify task
|
/// The result of the last run verify task
|
||||||
#[serde(skip_serializing_if="Option::is_none")]
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
pub verification: Option<SnapshotVerifyState>,
|
pub verification: Option<SnapshotVerifyState>,
|
||||||
|
/// Fingerprint of encryption key
|
||||||
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub fingerprint: Option<Fingerprint>,
|
||||||
/// List of contained archive files.
|
/// List of contained archive files.
|
||||||
pub files: Vec<BackupContent>,
|
pub files: Vec<BackupContent>,
|
||||||
/// Overall snapshot size (sum of all archive sizes).
|
/// Overall snapshot size (sum of all archive sizes).
|
||||||
@ -668,7 +699,7 @@ pub struct TypeCounts {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
/// Counts of groups/snapshots per BackupType.
|
/// Counts of groups/snapshots per BackupType.
|
||||||
pub struct Counts {
|
pub struct Counts {
|
||||||
/// The counts for CT backups
|
/// The counts for CT backups
|
||||||
@ -683,8 +714,14 @@ pub struct Counts {
|
|||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
properties: {
|
properties: {
|
||||||
"gc-status": { type: GarbageCollectionStatus, },
|
"gc-status": {
|
||||||
counts: { type: Counts, }
|
type: GarbageCollectionStatus,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
counts: {
|
||||||
|
type: Counts,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
)]
|
)]
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@ -698,9 +735,11 @@ pub struct DataStoreStatus {
|
|||||||
/// Available space (bytes).
|
/// Available space (bytes).
|
||||||
pub avail: u64,
|
pub avail: u64,
|
||||||
/// Status of last GC
|
/// Status of last GC
|
||||||
pub gc_status: GarbageCollectionStatus,
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub gc_status: Option<GarbageCollectionStatus>,
|
||||||
/// Group/Snapshot counts
|
/// Group/Snapshot counts
|
||||||
pub counts: Counts,
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub counts: Option<Counts>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
@ -1129,7 +1168,7 @@ pub enum RRDTimeFrameResolution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[api()]
|
#[api()]
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "PascalCase")]
|
#[serde(rename_all = "PascalCase")]
|
||||||
/// Describes a package for which an update is available.
|
/// Describes a package for which an update is available.
|
||||||
pub struct APTUpdateInfo {
|
pub struct APTUpdateInfo {
|
||||||
@ -1153,4 +1192,52 @@ pub struct APTUpdateInfo {
|
|||||||
pub section: String,
|
pub section: String,
|
||||||
/// URL under which the package's changelog can be retrieved
|
/// URL under which the package's changelog can be retrieved
|
||||||
pub change_log_url: String,
|
pub change_log_url: String,
|
||||||
|
/// Custom extra field for additional package information
|
||||||
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub extra_info: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[api()]
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
/// When do we send notifications
|
||||||
|
pub enum Notify {
|
||||||
|
/// Never send notification
|
||||||
|
Never,
|
||||||
|
/// Send notifications for failed and sucessful jobs
|
||||||
|
Always,
|
||||||
|
/// Send notifications for failed jobs only
|
||||||
|
Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
properties: {
|
||||||
|
gc: {
|
||||||
|
type: Notify,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
verify: {
|
||||||
|
type: Notify,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
sync: {
|
||||||
|
type: Notify,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
/// Datastore notify settings
|
||||||
|
pub struct DatastoreNotify {
|
||||||
|
/// Garbage collection settings
|
||||||
|
pub gc: Option<Notify>,
|
||||||
|
/// Verify job setting
|
||||||
|
pub verify: Option<Notify>,
|
||||||
|
/// Sync job setting
|
||||||
|
pub sync: Option<Notify>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const DATASTORE_NOTIFY_STRING_SCHEMA: Schema = StringSchema::new(
|
||||||
|
"Datastore notification setting")
|
||||||
|
.format(&ApiStringFormat::PropertyString(&DatastoreNotify::API_SCHEMA))
|
||||||
|
.schema();
|
||||||
|
@ -450,11 +450,6 @@ impl Userid {
|
|||||||
&self.data
|
&self.data
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the "backup@pam" user id.
|
|
||||||
pub fn backup_userid() -> &'static Self {
|
|
||||||
&*BACKUP_USERID
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the "root@pam" user id.
|
/// Get the "root@pam" user id.
|
||||||
pub fn root_userid() -> &'static Self {
|
pub fn root_userid() -> &'static Self {
|
||||||
&*ROOT_USERID
|
&*ROOT_USERID
|
||||||
@ -462,7 +457,6 @@ impl Userid {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
pub static ref BACKUP_USERID: Userid = Userid::new("backup@pam".to_string(), 6);
|
|
||||||
pub static ref ROOT_USERID: Userid = Userid::new("root@pam".to_string(), 4);
|
pub static ref ROOT_USERID: Userid = Userid::new("root@pam".to_string(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -596,11 +590,6 @@ impl Authid {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the "backup@pam" auth id.
|
|
||||||
pub fn backup_auth_id() -> &'static Self {
|
|
||||||
&*BACKUP_AUTHID
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the "root@pam" auth id.
|
/// Get the "root@pam" auth id.
|
||||||
pub fn root_auth_id() -> &'static Self {
|
pub fn root_auth_id() -> &'static Self {
|
||||||
&*ROOT_AUTHID
|
&*ROOT_AUTHID
|
||||||
@ -608,7 +597,6 @@ impl Authid {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
pub static ref BACKUP_AUTHID: Authid = Authid::from(Userid::new("backup@pam".to_string(), 6));
|
|
||||||
pub static ref ROOT_AUTHID: Authid = Authid::from(Userid::new("root@pam".to_string(), 4));
|
pub static ref ROOT_AUTHID: Authid = Authid::from(Userid::new("root@pam".to_string(), 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -327,26 +327,20 @@ impl BackupInfo {
|
|||||||
Ok(files)
|
Ok(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_backups(base_path: &Path) -> Result<Vec<BackupInfo>, Error> {
|
pub fn list_backup_groups(base_path: &Path) -> Result<Vec<BackupGroup>, Error> {
|
||||||
let mut list = Vec::new();
|
let mut list = Vec::new();
|
||||||
|
|
||||||
tools::scandir(libc::AT_FDCWD, base_path, &BACKUP_TYPE_REGEX, |l0_fd, backup_type, file_type| {
|
tools::scandir(libc::AT_FDCWD, base_path, &BACKUP_TYPE_REGEX, |l0_fd, backup_type, file_type| {
|
||||||
if file_type != nix::dir::Type::Directory { return Ok(()); }
|
if file_type != nix::dir::Type::Directory { return Ok(()); }
|
||||||
tools::scandir(l0_fd, backup_type, &BACKUP_ID_REGEX, |l1_fd, backup_id, file_type| {
|
tools::scandir(l0_fd, backup_type, &BACKUP_ID_REGEX, |_, backup_id, file_type| {
|
||||||
if file_type != nix::dir::Type::Directory { return Ok(()); }
|
if file_type != nix::dir::Type::Directory { return Ok(()); }
|
||||||
tools::scandir(l1_fd, backup_id, &BACKUP_DATE_REGEX, |l2_fd, backup_time_string, file_type| {
|
|
||||||
if file_type != nix::dir::Type::Directory { return Ok(()); }
|
|
||||||
|
|
||||||
let backup_dir = BackupDir::with_rfc3339(backup_type, backup_id, backup_time_string)?;
|
list.push(BackupGroup::new(backup_type, backup_id));
|
||||||
|
|
||||||
let files = list_backup_files(l2_fd, backup_time_string)?;
|
Ok(())
|
||||||
|
|
||||||
list.push(BackupInfo { backup_dir, files });
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(list)
|
Ok(list)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -154,9 +154,11 @@ impl ChunkStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
|
pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
|
||||||
|
|
||||||
let (chunk_path, _digest_str) = self.chunk_path(digest);
|
let (chunk_path, _digest_str) = self.chunk_path(digest);
|
||||||
|
self.cond_touch_path(&chunk_path, fail_if_not_exist)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cond_touch_path(&self, path: &Path, fail_if_not_exist: bool) -> Result<bool, Error> {
|
||||||
const UTIME_NOW: i64 = (1 << 30) - 1;
|
const UTIME_NOW: i64 = (1 << 30) - 1;
|
||||||
const UTIME_OMIT: i64 = (1 << 30) - 2;
|
const UTIME_OMIT: i64 = (1 << 30) - 2;
|
||||||
|
|
||||||
@ -167,7 +169,7 @@ impl ChunkStore {
|
|||||||
|
|
||||||
use nix::NixPath;
|
use nix::NixPath;
|
||||||
|
|
||||||
let res = chunk_path.with_nix_path(|cstr| unsafe {
|
let res = path.with_nix_path(|cstr| unsafe {
|
||||||
let tmp = libc::utimensat(-1, cstr.as_ptr(), ×[0], libc::AT_SYMLINK_NOFOLLOW);
|
let tmp = libc::utimensat(-1, cstr.as_ptr(), ×[0], libc::AT_SYMLINK_NOFOLLOW);
|
||||||
nix::errno::Errno::result(tmp)
|
nix::errno::Errno::result(tmp)
|
||||||
})?;
|
})?;
|
||||||
@ -177,7 +179,7 @@ impl ChunkStore {
|
|||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
bail!("update atime failed for chunk {:?} - {}", chunk_path, err);
|
bail!("update atime failed for chunk/file {:?} - {}", path, err);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
@ -328,49 +330,13 @@ impl ChunkStore {
|
|||||||
let lock = self.mutex.lock();
|
let lock = self.mutex.lock();
|
||||||
|
|
||||||
if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
|
if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
|
||||||
if bad {
|
if stat.st_atime < min_atime {
|
||||||
// filename validity checked in iterator
|
|
||||||
let orig_filename = std::ffi::CString::new(&filename.to_bytes()[..64])?;
|
|
||||||
match fstatat(
|
|
||||||
dirfd,
|
|
||||||
orig_filename.as_c_str(),
|
|
||||||
nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW)
|
|
||||||
{
|
|
||||||
Ok(_) => {
|
|
||||||
match unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
|
|
||||||
Err(err) =>
|
|
||||||
crate::task_warn!(
|
|
||||||
worker,
|
|
||||||
"unlinking corrupt chunk {:?} failed on store '{}' - {}",
|
|
||||||
filename,
|
|
||||||
self.name,
|
|
||||||
err,
|
|
||||||
),
|
|
||||||
Ok(_) => {
|
|
||||||
status.removed_bad += 1;
|
|
||||||
status.removed_bytes += stat.st_size as u64;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(nix::Error::Sys(nix::errno::Errno::ENOENT)) => {
|
|
||||||
// chunk hasn't been rewritten yet, keep .bad file
|
|
||||||
status.still_bad += 1;
|
|
||||||
},
|
|
||||||
Err(err) => {
|
|
||||||
// some other error, warn user and keep .bad file around too
|
|
||||||
status.still_bad += 1;
|
|
||||||
crate::task_warn!(
|
|
||||||
worker,
|
|
||||||
"error during stat on '{:?}' - {}",
|
|
||||||
orig_filename,
|
|
||||||
err,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if stat.st_atime < min_atime {
|
|
||||||
//let age = now - stat.st_atime;
|
//let age = now - stat.st_atime;
|
||||||
//println!("UNLINK {} {:?}", age/(3600*24), filename);
|
//println!("UNLINK {} {:?}", age/(3600*24), filename);
|
||||||
if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
|
if let Err(err) = unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir) {
|
||||||
|
if bad {
|
||||||
|
status.still_bad += 1;
|
||||||
|
}
|
||||||
bail!(
|
bail!(
|
||||||
"unlinking chunk {:?} failed on store '{}' - {}",
|
"unlinking chunk {:?} failed on store '{}' - {}",
|
||||||
filename,
|
filename,
|
||||||
@ -378,13 +344,23 @@ impl ChunkStore {
|
|||||||
err,
|
err,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
status.removed_chunks += 1;
|
if bad {
|
||||||
|
status.removed_bad += 1;
|
||||||
|
} else {
|
||||||
|
status.removed_chunks += 1;
|
||||||
|
}
|
||||||
status.removed_bytes += stat.st_size as u64;
|
status.removed_bytes += stat.st_size as u64;
|
||||||
} else if stat.st_atime < oldest_writer {
|
} else if stat.st_atime < oldest_writer {
|
||||||
status.pending_chunks += 1;
|
if bad {
|
||||||
|
status.still_bad += 1;
|
||||||
|
} else {
|
||||||
|
status.pending_chunks += 1;
|
||||||
|
}
|
||||||
status.pending_bytes += stat.st_size as u64;
|
status.pending_bytes += stat.st_size as u64;
|
||||||
} else {
|
} else {
|
||||||
status.disk_chunks += 1;
|
if !bad {
|
||||||
|
status.disk_chunks += 1;
|
||||||
|
}
|
||||||
status.disk_bytes += stat.st_size as u64;
|
status.disk_bytes += stat.st_size as u64;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,8 @@
|
|||||||
//! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption)
|
//! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption)
|
||||||
//! for a short introduction.
|
//! for a short introduction.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::fmt::Display;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
use anyhow::{bail, Error};
|
use anyhow::{bail, Error};
|
||||||
@ -15,8 +17,15 @@ use openssl::pkcs5::pbkdf2_hmac;
|
|||||||
use openssl::symm::{decrypt_aead, Cipher, Crypter, Mode};
|
use openssl::symm::{decrypt_aead, Cipher, Crypter, Mode};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::tools::format::{as_fingerprint, bytes_as_fingerprint};
|
||||||
|
|
||||||
use proxmox::api::api;
|
use proxmox::api::api;
|
||||||
|
|
||||||
|
// openssl::sha::sha256(b"Proxmox Backup Encryption Key Fingerprint")
|
||||||
|
const FINGERPRINT_INPUT: [u8; 32] = [ 110, 208, 239, 119, 71, 31, 255, 77,
|
||||||
|
85, 199, 168, 254, 74, 157, 182, 33,
|
||||||
|
97, 64, 127, 19, 76, 114, 93, 223,
|
||||||
|
48, 153, 45, 37, 236, 69, 237, 38, ];
|
||||||
#[api(default: "encrypt")]
|
#[api(default: "encrypt")]
|
||||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "kebab-case")]
|
#[serde(rename_all = "kebab-case")]
|
||||||
@ -30,6 +39,30 @@ pub enum CryptMode {
|
|||||||
SignOnly,
|
SignOnly,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||||
|
#[serde(transparent)]
|
||||||
|
/// 32-byte fingerprint, usually calculated with SHA256.
|
||||||
|
pub struct Fingerprint {
|
||||||
|
#[serde(with = "bytes_as_fingerprint")]
|
||||||
|
bytes: [u8; 32],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fingerprint {
|
||||||
|
pub fn new(bytes: [u8; 32]) -> Self {
|
||||||
|
Self { bytes }
|
||||||
|
}
|
||||||
|
pub fn bytes(&self) -> &[u8; 32] {
|
||||||
|
&self.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Display as short key ID
|
||||||
|
impl Display for Fingerprint {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "{}", as_fingerprint(&self.bytes[0..8]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Encryption Configuration with secret key
|
/// Encryption Configuration with secret key
|
||||||
///
|
///
|
||||||
/// This structure stores the secret key and provides helpers for
|
/// This structure stores the secret key and provides helpers for
|
||||||
@ -101,6 +134,10 @@ impl CryptConfig {
|
|||||||
tag
|
tag
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint(&self) -> Fingerprint {
|
||||||
|
Fingerprint::new(self.compute_digest(&FINGERPRINT_INPUT))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> {
|
pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> {
|
||||||
let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?;
|
let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?;
|
||||||
crypter.aad_update(b"")?; //??
|
crypter.aad_update(b"")?; //??
|
||||||
@ -219,7 +256,13 @@ impl CryptConfig {
|
|||||||
) -> Result<Vec<u8>, Error> {
|
) -> Result<Vec<u8>, Error> {
|
||||||
|
|
||||||
let modified = proxmox::tools::time::epoch_i64();
|
let modified = proxmox::tools::time::epoch_i64();
|
||||||
let key_config = super::KeyConfig { kdf: None, created, modified, data: self.enc_key.to_vec() };
|
let key_config = super::KeyConfig {
|
||||||
|
kdf: None,
|
||||||
|
created,
|
||||||
|
modified,
|
||||||
|
data: self.enc_key.to_vec(),
|
||||||
|
fingerprint: Some(self.fingerprint()),
|
||||||
|
};
|
||||||
let data = serde_json::to_string(&key_config)?.as_bytes().to_vec();
|
let data = serde_json::to_string(&key_config)?.as_bytes().to_vec();
|
||||||
|
|
||||||
let mut buffer = vec![0u8; rsa.size() as usize];
|
let mut buffer = vec![0u8; rsa.size() as usize];
|
||||||
|
@ -446,6 +446,17 @@ impl DataStore {
|
|||||||
file_name,
|
file_name,
|
||||||
err,
|
err,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// touch any corresponding .bad files to keep them around, meaning if a chunk is
|
||||||
|
// rewritten correctly they will be removed automatically, as well as if no index
|
||||||
|
// file requires the chunk anymore (won't get to this loop then)
|
||||||
|
for i in 0..=9 {
|
||||||
|
let bad_ext = format!("{}.bad", i);
|
||||||
|
let mut bad_path = PathBuf::new();
|
||||||
|
bad_path.push(self.chunk_path(digest).0);
|
||||||
|
bad_path.set_extension(bad_ext);
|
||||||
|
self.chunk_store.cond_touch_path(&bad_path, false)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -219,7 +219,6 @@ impl IndexFile for DynamicIndexReader {
|
|||||||
(csum, chunk_end)
|
(csum, chunk_end)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::cast_ptr_alignment)]
|
|
||||||
fn chunk_info(&self, pos: usize) -> Option<ChunkReadInfo> {
|
fn chunk_info(&self, pos: usize) -> Option<ChunkReadInfo> {
|
||||||
if pos >= self.index.len() {
|
if pos >= self.index.len() {
|
||||||
return None;
|
return None;
|
||||||
|
@ -2,9 +2,34 @@ use anyhow::{bail, format_err, Context, Error};
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::backup::{CryptConfig, Fingerprint};
|
||||||
|
|
||||||
|
use proxmox::api::api;
|
||||||
use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
|
use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
|
||||||
use proxmox::try_block;
|
use proxmox::try_block;
|
||||||
|
|
||||||
|
#[api(default: "scrypt")]
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
/// Key derivation function for password protected encryption keys.
|
||||||
|
pub enum Kdf {
|
||||||
|
/// Do not encrypt the key.
|
||||||
|
None,
|
||||||
|
|
||||||
|
/// Encrypt they key with a password using SCrypt.
|
||||||
|
Scrypt,
|
||||||
|
|
||||||
|
/// Encrtypt the Key with a password using PBKDF2
|
||||||
|
PBKDF2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Kdf {
|
||||||
|
#[inline]
|
||||||
|
fn default() -> Self {
|
||||||
|
Kdf::Scrypt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize, Debug)]
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
pub enum KeyDerivationConfig {
|
pub enum KeyDerivationConfig {
|
||||||
Scrypt {
|
Scrypt {
|
||||||
@ -66,6 +91,9 @@ pub struct KeyConfig {
|
|||||||
pub modified: i64,
|
pub modified: i64,
|
||||||
#[serde(with = "proxmox::tools::serde::bytes_as_base64")]
|
#[serde(with = "proxmox::tools::serde::bytes_as_base64")]
|
||||||
pub data: Vec<u8>,
|
pub data: Vec<u8>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
#[serde(default)]
|
||||||
|
pub fingerprint: Option<Fingerprint>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn store_key_config(
|
pub fn store_key_config(
|
||||||
@ -103,15 +131,25 @@ pub fn store_key_config(
|
|||||||
pub fn encrypt_key_with_passphrase(
|
pub fn encrypt_key_with_passphrase(
|
||||||
raw_key: &[u8],
|
raw_key: &[u8],
|
||||||
passphrase: &[u8],
|
passphrase: &[u8],
|
||||||
|
kdf: Kdf,
|
||||||
) -> Result<KeyConfig, Error> {
|
) -> Result<KeyConfig, Error> {
|
||||||
|
|
||||||
let salt = proxmox::sys::linux::random_data(32)?;
|
let salt = proxmox::sys::linux::random_data(32)?;
|
||||||
|
|
||||||
let kdf = KeyDerivationConfig::Scrypt {
|
let kdf = match kdf {
|
||||||
n: 65536,
|
Kdf::Scrypt => KeyDerivationConfig::Scrypt {
|
||||||
r: 8,
|
n: 65536,
|
||||||
p: 1,
|
r: 8,
|
||||||
salt,
|
p: 1,
|
||||||
|
salt,
|
||||||
|
},
|
||||||
|
Kdf::PBKDF2 => KeyDerivationConfig::PBKDF2 {
|
||||||
|
iter: 65535,
|
||||||
|
salt,
|
||||||
|
},
|
||||||
|
Kdf::None => {
|
||||||
|
bail!("No key derivation function specified");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let derived_key = kdf.derive_key(passphrase)?;
|
let derived_key = kdf.derive_key(passphrase)?;
|
||||||
@ -142,28 +180,22 @@ pub fn encrypt_key_with_passphrase(
|
|||||||
created,
|
created,
|
||||||
modified: created,
|
modified: created,
|
||||||
data: enc_data,
|
data: enc_data,
|
||||||
|
fingerprint: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_and_decrypt_key(
|
pub fn load_and_decrypt_key(
|
||||||
path: &std::path::Path,
|
path: &std::path::Path,
|
||||||
passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
|
passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
|
||||||
) -> Result<([u8;32], i64), Error> {
|
) -> Result<([u8;32], i64, Fingerprint), Error> {
|
||||||
do_load_and_decrypt_key(path, passphrase)
|
|
||||||
.with_context(|| format!("failed to load decryption key from {:?}", path))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn do_load_and_decrypt_key(
|
|
||||||
path: &std::path::Path,
|
|
||||||
passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
|
|
||||||
) -> Result<([u8;32], i64), Error> {
|
|
||||||
decrypt_key(&file_get_contents(&path)?, passphrase)
|
decrypt_key(&file_get_contents(&path)?, passphrase)
|
||||||
|
.with_context(|| format!("failed to load decryption key from {:?}", path))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decrypt_key(
|
pub fn decrypt_key(
|
||||||
mut keydata: &[u8],
|
mut keydata: &[u8],
|
||||||
passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
|
passphrase: &dyn Fn() -> Result<Vec<u8>, Error>,
|
||||||
) -> Result<([u8;32], i64), Error> {
|
) -> Result<([u8;32], i64, Fingerprint), Error> {
|
||||||
let key_config: KeyConfig = serde_json::from_reader(&mut keydata)?;
|
let key_config: KeyConfig = serde_json::from_reader(&mut keydata)?;
|
||||||
|
|
||||||
let raw_data = key_config.data;
|
let raw_data = key_config.data;
|
||||||
@ -203,5 +235,13 @@ pub fn decrypt_key(
|
|||||||
let mut result = [0u8; 32];
|
let mut result = [0u8; 32];
|
||||||
result.copy_from_slice(&key);
|
result.copy_from_slice(&key);
|
||||||
|
|
||||||
Ok((result, created))
|
let fingerprint = match key_config.fingerprint {
|
||||||
|
Some(fingerprint) => fingerprint,
|
||||||
|
None => {
|
||||||
|
let crypt_config = CryptConfig::new(result.clone())?;
|
||||||
|
crypt_config.fingerprint()
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok((result, created, fingerprint))
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ use std::path::Path;
|
|||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
use ::serde::{Deserialize, Serialize};
|
use ::serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::backup::{BackupDir, CryptMode, CryptConfig};
|
use crate::backup::{BackupDir, CryptMode, CryptConfig, Fingerprint};
|
||||||
|
|
||||||
pub const MANIFEST_BLOB_NAME: &str = "index.json.blob";
|
pub const MANIFEST_BLOB_NAME: &str = "index.json.blob";
|
||||||
pub const MANIFEST_LOCK_NAME: &str = ".index.json.lck";
|
pub const MANIFEST_LOCK_NAME: &str = ".index.json.lck";
|
||||||
@ -223,12 +223,48 @@ impl BackupManifest {
|
|||||||
if let Some(crypt_config) = crypt_config {
|
if let Some(crypt_config) = crypt_config {
|
||||||
let sig = self.signature(crypt_config)?;
|
let sig = self.signature(crypt_config)?;
|
||||||
manifest["signature"] = proxmox::tools::digest_to_hex(&sig).into();
|
manifest["signature"] = proxmox::tools::digest_to_hex(&sig).into();
|
||||||
|
let fingerprint = &crypt_config.fingerprint();
|
||||||
|
manifest["unprotected"]["key-fingerprint"] = serde_json::to_value(fingerprint)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let manifest = serde_json::to_string_pretty(&manifest).unwrap().into();
|
let manifest = serde_json::to_string_pretty(&manifest).unwrap().into();
|
||||||
Ok(manifest)
|
Ok(manifest)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint(&self) -> Result<Option<Fingerprint>, Error> {
|
||||||
|
match &self.unprotected["key-fingerprint"] {
|
||||||
|
Value::Null => Ok(None),
|
||||||
|
value => Ok(Some(serde_json::from_value(value.clone())?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if a BackupManifest and a CryptConfig share a valid fingerprint combination.
|
||||||
|
///
|
||||||
|
/// An unsigned manifest is valid with any or no CryptConfig.
|
||||||
|
/// A signed manifest is only valid with a matching CryptConfig.
|
||||||
|
pub fn check_fingerprint(&self, crypt_config: Option<&CryptConfig>) -> Result<(), Error> {
|
||||||
|
if let Some(fingerprint) = self.fingerprint()? {
|
||||||
|
match crypt_config {
|
||||||
|
None => bail!(
|
||||||
|
"missing key - manifest was created with key {}",
|
||||||
|
fingerprint,
|
||||||
|
),
|
||||||
|
Some(crypt_config) => {
|
||||||
|
let config_fp = crypt_config.fingerprint();
|
||||||
|
if config_fp != fingerprint {
|
||||||
|
bail!(
|
||||||
|
"wrong key - manifest's key {} does not match provided key {}",
|
||||||
|
fingerprint,
|
||||||
|
config_fp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Try to read the manifest. This verifies the signature if there is a crypt_config.
|
/// Try to read the manifest. This verifies the signature if there is a crypt_config.
|
||||||
pub fn from_data(data: &[u8], crypt_config: Option<&CryptConfig>) -> Result<BackupManifest, Error> {
|
pub fn from_data(data: &[u8], crypt_config: Option<&CryptConfig>) -> Result<BackupManifest, Error> {
|
||||||
let json: Value = serde_json::from_slice(data)?;
|
let json: Value = serde_json::from_slice(data)?;
|
||||||
@ -237,6 +273,19 @@ impl BackupManifest {
|
|||||||
if let Some(ref crypt_config) = crypt_config {
|
if let Some(ref crypt_config) = crypt_config {
|
||||||
if let Some(signature) = signature {
|
if let Some(signature) = signature {
|
||||||
let expected_signature = proxmox::tools::digest_to_hex(&Self::json_signature(&json, crypt_config)?);
|
let expected_signature = proxmox::tools::digest_to_hex(&Self::json_signature(&json, crypt_config)?);
|
||||||
|
|
||||||
|
let fingerprint = &json["unprotected"]["key-fingerprint"];
|
||||||
|
if fingerprint != &Value::Null {
|
||||||
|
let fingerprint = serde_json::from_value(fingerprint.clone())?;
|
||||||
|
let config_fp = crypt_config.fingerprint();
|
||||||
|
if config_fp != fingerprint {
|
||||||
|
bail!(
|
||||||
|
"wrong key - unable to verify signature since manifest's key {} does not match provided key {}",
|
||||||
|
fingerprint,
|
||||||
|
config_fp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
if signature != expected_signature {
|
if signature != expected_signature {
|
||||||
bail!("wrong signature in manifest");
|
bail!("wrong signature in manifest");
|
||||||
}
|
}
|
||||||
|
@ -498,28 +498,38 @@ pub fn verify_all_backups(
|
|||||||
) -> Result<Vec<String>, Error> {
|
) -> Result<Vec<String>, Error> {
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
|
|
||||||
|
task_log!(worker, "verify datastore {}", datastore.name());
|
||||||
|
|
||||||
if let Some(owner) = &owner {
|
if let Some(owner) = &owner {
|
||||||
task_log!(
|
task_log!(worker, "limiting to backups owned by {}", owner);
|
||||||
worker,
|
|
||||||
"verify datastore {} - limiting to backups owned by {}",
|
|
||||||
datastore.name(),
|
|
||||||
owner
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let filter_by_owner = |group: &BackupGroup| {
|
let filter_by_owner = |group: &BackupGroup| {
|
||||||
if let Some(owner) = &owner {
|
match (datastore.get_owner(group), &owner) {
|
||||||
match datastore.get_owner(group) {
|
(Ok(ref group_owner), Some(owner)) => {
|
||||||
Ok(ref group_owner) => {
|
group_owner == owner
|
||||||
group_owner == owner
|
|| (group_owner.is_token()
|
||||||
|| (group_owner.is_token()
|
&& !owner.is_token()
|
||||||
&& !owner.is_token()
|
&& group_owner.user() == owner.user())
|
||||||
&& group_owner.user() == owner.user())
|
},
|
||||||
},
|
(Ok(_), None) => true,
|
||||||
Err(_) => false,
|
(Err(err), Some(_)) => {
|
||||||
}
|
// intentionally not in task log
|
||||||
} else {
|
// the task user might not be allowed to see this group!
|
||||||
true
|
println!("Failed to get owner of group '{}' - {}", group, err);
|
||||||
|
false
|
||||||
|
},
|
||||||
|
(Err(err), None) => {
|
||||||
|
// we don't filter by owner, but we want to log the error
|
||||||
|
task_log!(
|
||||||
|
worker,
|
||||||
|
"Failed to get owner of group '{} - {}",
|
||||||
|
group,
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
errors.push(group.to_string());
|
||||||
|
true
|
||||||
|
},
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -532,8 +542,7 @@ pub fn verify_all_backups(
|
|||||||
Err(err) => {
|
Err(err) => {
|
||||||
task_log!(
|
task_log!(
|
||||||
worker,
|
worker,
|
||||||
"verify datastore {} - unable to list backups: {}",
|
"unable to list backups: {}",
|
||||||
datastore.name(),
|
|
||||||
err,
|
err,
|
||||||
);
|
);
|
||||||
return Ok(errors);
|
return Ok(errors);
|
||||||
@ -553,7 +562,7 @@ pub fn verify_all_backups(
|
|||||||
// start with 64 chunks since we assume there are few corrupt ones
|
// start with 64 chunks since we assume there are few corrupt ones
|
||||||
let corrupt_chunks = Arc::new(Mutex::new(HashSet::with_capacity(64)));
|
let corrupt_chunks = Arc::new(Mutex::new(HashSet::with_capacity(64)));
|
||||||
|
|
||||||
task_log!(worker, "verify datastore {} ({} snapshots)", datastore.name(), snapshot_count);
|
task_log!(worker, "found {} snapshots", snapshot_count);
|
||||||
|
|
||||||
let mut done = 0;
|
let mut done = 0;
|
||||||
for group in list {
|
for group in list {
|
||||||
|
@ -76,6 +76,7 @@ async fn run() -> Result<(), Error> {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
"proxmox-backup.service",
|
||||||
);
|
);
|
||||||
|
|
||||||
server::write_pid(buildcfg::PROXMOX_BACKUP_API_PID_FN)?;
|
server::write_pid(buildcfg::PROXMOX_BACKUP_API_PID_FN)?;
|
||||||
|
@ -32,11 +32,11 @@ use proxmox::{
|
|||||||
use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
|
use pxar::accessor::{MaybeReady, ReadAt, ReadAtOperation};
|
||||||
|
|
||||||
use proxmox_backup::tools;
|
use proxmox_backup::tools;
|
||||||
|
use proxmox_backup::api2::access::user::UserWithTokens;
|
||||||
use proxmox_backup::api2::types::*;
|
use proxmox_backup::api2::types::*;
|
||||||
use proxmox_backup::api2::version;
|
use proxmox_backup::api2::version;
|
||||||
use proxmox_backup::client::*;
|
use proxmox_backup::client::*;
|
||||||
use proxmox_backup::pxar::catalog::*;
|
use proxmox_backup::pxar::catalog::*;
|
||||||
use proxmox_backup::config::user::complete_userid;
|
|
||||||
use proxmox_backup::backup::{
|
use proxmox_backup::backup::{
|
||||||
archive_type,
|
archive_type,
|
||||||
decrypt_key,
|
decrypt_key,
|
||||||
@ -53,7 +53,6 @@ use proxmox_backup::backup::{
|
|||||||
ChunkStream,
|
ChunkStream,
|
||||||
CryptConfig,
|
CryptConfig,
|
||||||
CryptMode,
|
CryptMode,
|
||||||
DataBlob,
|
|
||||||
DynamicIndexReader,
|
DynamicIndexReader,
|
||||||
FixedChunkStream,
|
FixedChunkStream,
|
||||||
FixedIndexReader,
|
FixedIndexReader,
|
||||||
@ -193,8 +192,12 @@ pub fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn connect(server: &str, port: u16, auth_id: &Authid) -> Result<HttpClient, Error> {
|
fn connect(repo: &BackupRepository) -> Result<HttpClient, Error> {
|
||||||
|
connect_do(repo.host(), repo.port(), repo.auth_id())
|
||||||
|
.map_err(|err| format_err!("error building client for repository {} - {}", repo, err))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connect_do(server: &str, port: u16, auth_id: &Authid) -> Result<HttpClient, Error> {
|
||||||
let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
|
let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
|
||||||
|
|
||||||
use std::env::VarError::*;
|
use std::env::VarError::*;
|
||||||
@ -366,7 +369,7 @@ async fn list_backup_groups(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
|
let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
|
||||||
|
|
||||||
@ -435,7 +438,7 @@ async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Erro
|
|||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
param.as_object_mut().unwrap().remove("repository");
|
param.as_object_mut().unwrap().remove("repository");
|
||||||
|
|
||||||
@ -452,112 +455,6 @@ async fn change_backup_owner(group: String, mut param: Value) -> Result<(), Erro
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
|
||||||
input: {
|
|
||||||
properties: {
|
|
||||||
repository: {
|
|
||||||
schema: REPO_URL_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
group: {
|
|
||||||
type: String,
|
|
||||||
description: "Backup group.",
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
"output-format": {
|
|
||||||
schema: OUTPUT_FORMAT,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)]
|
|
||||||
/// List backup snapshots.
|
|
||||||
async fn list_snapshots(param: Value) -> Result<Value, Error> {
|
|
||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
|
||||||
|
|
||||||
let output_format = get_output_format(¶m);
|
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
|
||||||
|
|
||||||
let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() {
|
|
||||||
Some(path.parse()?)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
|
|
||||||
|
|
||||||
record_repository(&repo);
|
|
||||||
|
|
||||||
let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
|
|
||||||
let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
|
|
||||||
let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?;
|
|
||||||
Ok(snapshot.relative_path().to_str().unwrap().to_owned())
|
|
||||||
};
|
|
||||||
|
|
||||||
let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
|
|
||||||
let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
|
|
||||||
let mut filenames = Vec::new();
|
|
||||||
for file in &item.files {
|
|
||||||
filenames.push(file.filename.to_string());
|
|
||||||
}
|
|
||||||
Ok(tools::format::render_backup_file_list(&filenames[..]))
|
|
||||||
};
|
|
||||||
|
|
||||||
let options = default_table_format_options()
|
|
||||||
.sortby("backup-type", false)
|
|
||||||
.sortby("backup-id", false)
|
|
||||||
.sortby("backup-time", false)
|
|
||||||
.column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
|
|
||||||
.column(ColumnConfig::new("size").renderer(tools::format::render_bytes_human_readable))
|
|
||||||
.column(ColumnConfig::new("files").renderer(render_files))
|
|
||||||
;
|
|
||||||
|
|
||||||
let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
|
|
||||||
|
|
||||||
format_and_print_result_full(&mut data, info, &output_format, &options);
|
|
||||||
|
|
||||||
Ok(Value::Null)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[api(
|
|
||||||
input: {
|
|
||||||
properties: {
|
|
||||||
repository: {
|
|
||||||
schema: REPO_URL_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
snapshot: {
|
|
||||||
type: String,
|
|
||||||
description: "Snapshot path.",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)]
|
|
||||||
/// Forget (remove) backup snapshots.
|
|
||||||
async fn forget_snapshots(param: Value) -> Result<Value, Error> {
|
|
||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
|
||||||
|
|
||||||
let path = tools::required_string_param(¶m, "snapshot")?;
|
|
||||||
let snapshot: BackupDir = path.parse()?;
|
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
|
|
||||||
|
|
||||||
let result = client.delete(&path, Some(json!({
|
|
||||||
"backup-type": snapshot.group().backup_type(),
|
|
||||||
"backup-id": snapshot.group().backup_id(),
|
|
||||||
"backup-time": snapshot.backup_time(),
|
|
||||||
}))).await?;
|
|
||||||
|
|
||||||
record_repository(&repo);
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
input: {
|
input: {
|
||||||
properties: {
|
properties: {
|
||||||
@ -573,7 +470,7 @@ async fn api_login(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
client.login().await?;
|
client.login().await?;
|
||||||
|
|
||||||
record_repository(&repo);
|
record_repository(&repo);
|
||||||
@ -630,7 +527,7 @@ async fn api_version(param: Value) -> Result<(), Error> {
|
|||||||
|
|
||||||
let repo = extract_repository_from_value(¶m);
|
let repo = extract_repository_from_value(¶m);
|
||||||
if let Ok(repo) = repo {
|
if let Ok(repo) = repo {
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
match client.get("api2/json/version", None).await {
|
match client.get("api2/json/version", None).await {
|
||||||
Ok(mut result) => version_info["server"] = result["data"].take(),
|
Ok(mut result) => version_info["server"] = result["data"].take(),
|
||||||
@ -651,58 +548,6 @@ async fn api_version(param: Value) -> Result<(), Error> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[api(
|
|
||||||
input: {
|
|
||||||
properties: {
|
|
||||||
repository: {
|
|
||||||
schema: REPO_URL_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
snapshot: {
|
|
||||||
type: String,
|
|
||||||
description: "Snapshot path.",
|
|
||||||
},
|
|
||||||
"output-format": {
|
|
||||||
schema: OUTPUT_FORMAT,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)]
|
|
||||||
/// List snapshot files.
|
|
||||||
async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
|
|
||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
|
||||||
|
|
||||||
let path = tools::required_string_param(¶m, "snapshot")?;
|
|
||||||
let snapshot: BackupDir = path.parse()?;
|
|
||||||
|
|
||||||
let output_format = get_output_format(¶m);
|
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/files", repo.store());
|
|
||||||
|
|
||||||
let mut result = client.get(&path, Some(json!({
|
|
||||||
"backup-type": snapshot.group().backup_type(),
|
|
||||||
"backup-id": snapshot.group().backup_id(),
|
|
||||||
"backup-time": snapshot.backup_time(),
|
|
||||||
}))).await?;
|
|
||||||
|
|
||||||
record_repository(&repo);
|
|
||||||
|
|
||||||
let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
|
|
||||||
|
|
||||||
let mut data: Value = result["data"].take();
|
|
||||||
|
|
||||||
let options = default_table_format_options();
|
|
||||||
|
|
||||||
format_and_print_result_full(&mut data, info, &output_format, &options);
|
|
||||||
|
|
||||||
Ok(Value::Null)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
input: {
|
input: {
|
||||||
properties: {
|
properties: {
|
||||||
@ -724,7 +569,7 @@ async fn start_garbage_collection(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let output_format = get_output_format(¶m);
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
|
let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
|
||||||
|
|
||||||
@ -798,7 +643,10 @@ fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Err
|
|||||||
let keydata = match (keyfile, key_fd) {
|
let keydata = match (keyfile, key_fd) {
|
||||||
(None, None) => None,
|
(None, None) => None,
|
||||||
(Some(_), Some(_)) => bail!("--keyfile and --keyfd are mutually exclusive"),
|
(Some(_), Some(_)) => bail!("--keyfile and --keyfd are mutually exclusive"),
|
||||||
(Some(keyfile), None) => Some(file_get_contents(keyfile)?),
|
(Some(keyfile), None) => {
|
||||||
|
eprintln!("Using encryption key file: {}", keyfile);
|
||||||
|
Some(file_get_contents(keyfile)?)
|
||||||
|
},
|
||||||
(None, Some(fd)) => {
|
(None, Some(fd)) => {
|
||||||
let input = unsafe { std::fs::File::from_raw_fd(fd) };
|
let input = unsafe { std::fs::File::from_raw_fd(fd) };
|
||||||
let mut data = Vec::new();
|
let mut data = Vec::new();
|
||||||
@ -806,6 +654,7 @@ fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Err
|
|||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
format_err!("error reading encryption key from fd {}: {}", fd, err)
|
format_err!("error reading encryption key from fd {}: {}", fd, err)
|
||||||
})?;
|
})?;
|
||||||
|
eprintln!("Using encryption key from file descriptor");
|
||||||
Some(data)
|
Some(data)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -813,7 +662,10 @@ fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Err
|
|||||||
Ok(match (keydata, crypt_mode) {
|
Ok(match (keydata, crypt_mode) {
|
||||||
// no parameters:
|
// no parameters:
|
||||||
(None, None) => match key::read_optional_default_encryption_key()? {
|
(None, None) => match key::read_optional_default_encryption_key()? {
|
||||||
Some(key) => (Some(key), CryptMode::Encrypt),
|
Some(key) => {
|
||||||
|
eprintln!("Encrypting with default encryption key!");
|
||||||
|
(Some(key), CryptMode::Encrypt)
|
||||||
|
},
|
||||||
None => (None, CryptMode::None),
|
None => (None, CryptMode::None),
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -823,7 +675,10 @@ fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Err
|
|||||||
// just --crypt-mode other than none
|
// just --crypt-mode other than none
|
||||||
(None, Some(crypt_mode)) => match key::read_optional_default_encryption_key()? {
|
(None, Some(crypt_mode)) => match key::read_optional_default_encryption_key()? {
|
||||||
None => bail!("--crypt-mode without --keyfile and no default key file available"),
|
None => bail!("--crypt-mode without --keyfile and no default key file available"),
|
||||||
Some(key) => (Some(key), crypt_mode),
|
Some(key) => {
|
||||||
|
eprintln!("Encrypting with default encryption key!");
|
||||||
|
(Some(key), crypt_mode)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// just --keyfile
|
// just --keyfile
|
||||||
@ -861,6 +716,11 @@ fn keyfile_parameters(param: &Value) -> Result<(Option<Vec<u8>>, CryptMode), Err
|
|||||||
description: "Path to file.",
|
description: "Path to file.",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"all-file-systems": {
|
||||||
|
type: Boolean,
|
||||||
|
description: "Include all mounted subdirectories.",
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
keyfile: {
|
keyfile: {
|
||||||
schema: KEYFILE_SCHEMA,
|
schema: KEYFILE_SCHEMA,
|
||||||
optional: true,
|
optional: true,
|
||||||
@ -1036,7 +896,7 @@ async fn create_backup(
|
|||||||
|
|
||||||
let backup_time = backup_time_opt.unwrap_or_else(|| epoch_i64());
|
let backup_time = backup_time_opt.unwrap_or_else(|| epoch_i64());
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
record_repository(&repo);
|
record_repository(&repo);
|
||||||
|
|
||||||
println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?);
|
println!("Starting backup: {}/{}/{}", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time)?);
|
||||||
@ -1050,7 +910,8 @@ async fn create_backup(
|
|||||||
let (crypt_config, rsa_encrypted_key) = match keydata {
|
let (crypt_config, rsa_encrypted_key) = match keydata {
|
||||||
None => (None, None),
|
None => (None, None),
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
let (key, created) = decrypt_key(&key, &key::get_encryption_key_password)?;
|
let (key, created, fingerprint) = decrypt_key(&key, &key::get_encryption_key_password)?;
|
||||||
|
println!("Encryption key fingerprint: {}", fingerprint);
|
||||||
|
|
||||||
let crypt_config = CryptConfig::new(key)?;
|
let crypt_config = CryptConfig::new(key)?;
|
||||||
|
|
||||||
@ -1059,6 +920,8 @@ async fn create_backup(
|
|||||||
let pem_data = file_get_contents(path)?;
|
let pem_data = file_get_contents(path)?;
|
||||||
let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
|
let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
|
||||||
let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
|
let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
|
||||||
|
println!("Master key '{:?}'", path);
|
||||||
|
|
||||||
(Some(Arc::new(crypt_config)), Some(enc_key))
|
(Some(Arc::new(crypt_config)), Some(enc_key))
|
||||||
}
|
}
|
||||||
_ => (Some(Arc::new(crypt_config)), None),
|
_ => (Some(Arc::new(crypt_config)), None),
|
||||||
@ -1077,8 +940,40 @@ async fn create_backup(
|
|||||||
false
|
false
|
||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await {
|
let download_previous_manifest = match client.previous_backup_time().await {
|
||||||
Some(Arc::new(previous_manifest))
|
Ok(Some(backup_time)) => {
|
||||||
|
println!(
|
||||||
|
"Downloading previous manifest ({})",
|
||||||
|
strftime_local("%c", backup_time)?
|
||||||
|
);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
println!("No previous manifest available.");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
// Fallback for outdated server, TODO remove/bubble up with 2.0
|
||||||
|
true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let previous_manifest = if download_previous_manifest {
|
||||||
|
match client.download_previous_manifest().await {
|
||||||
|
Ok(previous_manifest) => {
|
||||||
|
match previous_manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref)) {
|
||||||
|
Ok(()) => Some(Arc::new(previous_manifest)),
|
||||||
|
Err(err) => {
|
||||||
|
println!("Couldn't re-use previous manifest - {}", err);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
println!("Couldn't download previous manifest - {}", err);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@ -1339,7 +1234,7 @@ async fn restore(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
record_repository(&repo);
|
record_repository(&repo);
|
||||||
|
|
||||||
@ -1361,7 +1256,8 @@ async fn restore(param: Value) -> Result<Value, Error> {
|
|||||||
let crypt_config = match keydata {
|
let crypt_config = match keydata {
|
||||||
None => None,
|
None => None,
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
let (key, _) = decrypt_key(&key, &key::get_encryption_key_password)?;
|
let (key, _, fingerprint) = decrypt_key(&key, &key::get_encryption_key_password)?;
|
||||||
|
eprintln!("Encryption key fingerprint: '{}'", fingerprint);
|
||||||
Some(Arc::new(CryptConfig::new(key)?))
|
Some(Arc::new(CryptConfig::new(key)?))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1377,6 +1273,7 @@ async fn restore(param: Value) -> Result<Value, Error> {
|
|||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
let (manifest, backup_index_data) = client.download_manifest().await?;
|
let (manifest, backup_index_data) = client.download_manifest().await?;
|
||||||
|
manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?;
|
||||||
|
|
||||||
let (archive_name, archive_type) = parse_archive_type(archive_name);
|
let (archive_name, archive_type) = parse_archive_type(archive_name);
|
||||||
|
|
||||||
@ -1473,81 +1370,6 @@ async fn restore(param: Value) -> Result<Value, Error> {
|
|||||||
Ok(Value::Null)
|
Ok(Value::Null)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
|
||||||
input: {
|
|
||||||
properties: {
|
|
||||||
repository: {
|
|
||||||
schema: REPO_URL_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
snapshot: {
|
|
||||||
type: String,
|
|
||||||
description: "Group/Snapshot path.",
|
|
||||||
},
|
|
||||||
logfile: {
|
|
||||||
type: String,
|
|
||||||
description: "The path to the log file you want to upload.",
|
|
||||||
},
|
|
||||||
keyfile: {
|
|
||||||
schema: KEYFILE_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
"keyfd": {
|
|
||||||
schema: KEYFD_SCHEMA,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
"crypt-mode": {
|
|
||||||
type: CryptMode,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)]
|
|
||||||
/// Upload backup log file.
|
|
||||||
async fn upload_log(param: Value) -> Result<Value, Error> {
|
|
||||||
|
|
||||||
let logfile = tools::required_string_param(¶m, "logfile")?;
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
|
||||||
|
|
||||||
let snapshot = tools::required_string_param(¶m, "snapshot")?;
|
|
||||||
let snapshot: BackupDir = snapshot.parse()?;
|
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
|
||||||
|
|
||||||
let (keydata, crypt_mode) = keyfile_parameters(¶m)?;
|
|
||||||
|
|
||||||
let crypt_config = match keydata {
|
|
||||||
None => None,
|
|
||||||
Some(key) => {
|
|
||||||
let (key, _created) = decrypt_key(&key, &key::get_encryption_key_password)?;
|
|
||||||
let crypt_config = CryptConfig::new(key)?;
|
|
||||||
Some(Arc::new(crypt_config))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let data = file_get_contents(logfile)?;
|
|
||||||
|
|
||||||
// fixme: howto sign log?
|
|
||||||
let blob = match crypt_mode {
|
|
||||||
CryptMode::None | CryptMode::SignOnly => DataBlob::encode(&data, None, true)?,
|
|
||||||
CryptMode::Encrypt => DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?,
|
|
||||||
};
|
|
||||||
|
|
||||||
let raw_data = blob.into_inner();
|
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
|
|
||||||
|
|
||||||
let args = json!({
|
|
||||||
"backup-type": snapshot.group().backup_type(),
|
|
||||||
"backup-id": snapshot.group().backup_id(),
|
|
||||||
"backup-time": snapshot.backup_time(),
|
|
||||||
});
|
|
||||||
|
|
||||||
let body = hyper::Body::from(raw_data);
|
|
||||||
|
|
||||||
client.upload("application/octet-stream", body, &path, Some(args)).await
|
|
||||||
}
|
|
||||||
|
|
||||||
const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
|
const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
|
||||||
&ApiHandler::Async(&prune),
|
&ApiHandler::Async(&prune),
|
||||||
&ObjectSchema::new(
|
&ObjectSchema::new(
|
||||||
@ -1583,7 +1405,7 @@ fn prune<'a>(
|
|||||||
async fn prune_async(mut param: Value) -> Result<Value, Error> {
|
async fn prune_async(mut param: Value) -> Result<Value, Error> {
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
|
let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
|
||||||
|
|
||||||
@ -1669,7 +1491,7 @@ async fn status(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let output_format = get_output_format(¶m);
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
let path = format!("api2/json/admin/datastore/{}/status", repo.store());
|
let path = format!("api2/json/admin/datastore/{}/status", repo.store());
|
||||||
|
|
||||||
@ -1904,6 +1726,33 @@ fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<Stri
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn complete_auth_id(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
|
||||||
|
proxmox_backup::tools::runtime::main(async { complete_auth_id_do(param).await })
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn complete_auth_id_do(param: &HashMap<String, String>) -> Vec<String> {
|
||||||
|
|
||||||
|
let mut result = vec![];
|
||||||
|
|
||||||
|
let repo = match extract_repository_from_map(param) {
|
||||||
|
Some(v) => v,
|
||||||
|
_ => return result,
|
||||||
|
};
|
||||||
|
|
||||||
|
let data = try_get(&repo, "api2/json/access/users?include_tokens=true").await;
|
||||||
|
|
||||||
|
if let Ok(parsed) = serde_json::from_value::<Vec<UserWithTokens>>(data) {
|
||||||
|
for user in parsed {
|
||||||
|
result.push(user.userid.to_string());
|
||||||
|
for token in user.tokens {
|
||||||
|
result.push(token.tokenid.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
use proxmox_backup::client::RemoteChunkReader;
|
use proxmox_backup::client::RemoteChunkReader;
|
||||||
/// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
|
/// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
|
||||||
/// async use!
|
/// async use!
|
||||||
@ -1958,26 +1807,9 @@ fn main() {
|
|||||||
.completion_cb("repository", complete_repository)
|
.completion_cb("repository", complete_repository)
|
||||||
.completion_cb("keyfile", tools::complete_file_name);
|
.completion_cb("keyfile", tools::complete_file_name);
|
||||||
|
|
||||||
let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
|
|
||||||
.arg_param(&["snapshot", "logfile"])
|
|
||||||
.completion_cb("snapshot", complete_backup_snapshot)
|
|
||||||
.completion_cb("logfile", tools::complete_file_name)
|
|
||||||
.completion_cb("keyfile", tools::complete_file_name)
|
|
||||||
.completion_cb("repository", complete_repository);
|
|
||||||
|
|
||||||
let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
|
let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
|
||||||
.completion_cb("repository", complete_repository);
|
.completion_cb("repository", complete_repository);
|
||||||
|
|
||||||
let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
|
|
||||||
.arg_param(&["group"])
|
|
||||||
.completion_cb("group", complete_backup_group)
|
|
||||||
.completion_cb("repository", complete_repository);
|
|
||||||
|
|
||||||
let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
|
|
||||||
.arg_param(&["snapshot"])
|
|
||||||
.completion_cb("repository", complete_repository)
|
|
||||||
.completion_cb("snapshot", complete_backup_snapshot);
|
|
||||||
|
|
||||||
let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
|
let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
|
||||||
.completion_cb("repository", complete_repository);
|
.completion_cb("repository", complete_repository);
|
||||||
|
|
||||||
@ -1988,11 +1820,6 @@ fn main() {
|
|||||||
.completion_cb("archive-name", complete_archive_name)
|
.completion_cb("archive-name", complete_archive_name)
|
||||||
.completion_cb("target", tools::complete_file_name);
|
.completion_cb("target", tools::complete_file_name);
|
||||||
|
|
||||||
let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
|
|
||||||
.arg_param(&["snapshot"])
|
|
||||||
.completion_cb("repository", complete_repository)
|
|
||||||
.completion_cb("snapshot", complete_backup_snapshot);
|
|
||||||
|
|
||||||
let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
|
let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
|
||||||
.arg_param(&["group"])
|
.arg_param(&["group"])
|
||||||
.completion_cb("group", complete_backup_group)
|
.completion_cb("group", complete_backup_group)
|
||||||
@ -2013,21 +1840,18 @@ fn main() {
|
|||||||
let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER)
|
let change_owner_cmd_def = CliCommand::new(&API_METHOD_CHANGE_BACKUP_OWNER)
|
||||||
.arg_param(&["group", "new-owner"])
|
.arg_param(&["group", "new-owner"])
|
||||||
.completion_cb("group", complete_backup_group)
|
.completion_cb("group", complete_backup_group)
|
||||||
.completion_cb("new-owner", complete_userid)
|
.completion_cb("new-owner", complete_auth_id)
|
||||||
.completion_cb("repository", complete_repository);
|
.completion_cb("repository", complete_repository);
|
||||||
|
|
||||||
let cmd_def = CliCommandMap::new()
|
let cmd_def = CliCommandMap::new()
|
||||||
.insert("backup", backup_cmd_def)
|
.insert("backup", backup_cmd_def)
|
||||||
.insert("upload-log", upload_log_cmd_def)
|
|
||||||
.insert("forget", forget_cmd_def)
|
|
||||||
.insert("garbage-collect", garbage_collect_cmd_def)
|
.insert("garbage-collect", garbage_collect_cmd_def)
|
||||||
.insert("list", list_cmd_def)
|
.insert("list", list_cmd_def)
|
||||||
.insert("login", login_cmd_def)
|
.insert("login", login_cmd_def)
|
||||||
.insert("logout", logout_cmd_def)
|
.insert("logout", logout_cmd_def)
|
||||||
.insert("prune", prune_cmd_def)
|
.insert("prune", prune_cmd_def)
|
||||||
.insert("restore", restore_cmd_def)
|
.insert("restore", restore_cmd_def)
|
||||||
.insert("snapshots", snapshots_cmd_def)
|
.insert("snapshot", snapshot_mgtm_cli())
|
||||||
.insert("files", files_cmd_def)
|
|
||||||
.insert("status", status_cmd_def)
|
.insert("status", status_cmd_def)
|
||||||
.insert("key", key::cli())
|
.insert("key", key::cli())
|
||||||
.insert("mount", mount_cmd_def())
|
.insert("mount", mount_cmd_def())
|
||||||
@ -2037,7 +1861,13 @@ fn main() {
|
|||||||
.insert("task", task_mgmt_cli())
|
.insert("task", task_mgmt_cli())
|
||||||
.insert("version", version_cmd_def)
|
.insert("version", version_cmd_def)
|
||||||
.insert("benchmark", benchmark_cmd_def)
|
.insert("benchmark", benchmark_cmd_def)
|
||||||
.insert("change-owner", change_owner_cmd_def);
|
.insert("change-owner", change_owner_cmd_def)
|
||||||
|
|
||||||
|
.alias(&["files"], &["snapshot", "files"])
|
||||||
|
.alias(&["forget"], &["snapshot", "forget"])
|
||||||
|
.alias(&["upload-log"], &["snapshot", "upload-log"])
|
||||||
|
.alias(&["snapshots"], &["snapshot", "list"])
|
||||||
|
;
|
||||||
|
|
||||||
let rpcenv = CliEnvironment::new();
|
let rpcenv = CliEnvironment::new();
|
||||||
run_cli_command(cmd_def, rpcenv, Some(|future| {
|
run_cli_command(cmd_def, rpcenv, Some(|future| {
|
||||||
|
@ -245,7 +245,7 @@ async fn task_stop(param: Value) -> Result<Value, Error> {
|
|||||||
|
|
||||||
let mut client = connect()?;
|
let mut client = connect()?;
|
||||||
|
|
||||||
let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
|
let path = format!("api2/json/nodes/localhost/tasks/{}", tools::percent_encode_component(upid_str));
|
||||||
let _ = client.delete(&path, None).await?;
|
let _ = client.delete(&path, None).await?;
|
||||||
|
|
||||||
Ok(Value::Null)
|
Ok(Value::Null)
|
||||||
@ -363,6 +363,43 @@ async fn report() -> Result<Value, Error> {
|
|||||||
Ok(Value::Null)
|
Ok(Value::Null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
verbose: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
default: false,
|
||||||
|
description: "Output verbose package information. It is ignored if output-format is specified.",
|
||||||
|
},
|
||||||
|
"output-format": {
|
||||||
|
schema: OUTPUT_FORMAT,
|
||||||
|
optional: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// List package versions for important Proxmox Backup Server packages.
|
||||||
|
async fn get_versions(verbose: bool, param: Value) -> Result<Value, Error> {
|
||||||
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
|
let packages = crate::api2::node::apt::get_versions()?;
|
||||||
|
let mut packages = json!(if verbose { &packages[..] } else { &packages[1..2] });
|
||||||
|
|
||||||
|
let options = default_table_format_options()
|
||||||
|
.disable_sort()
|
||||||
|
.noborder(true) // just not helpfull for version info which gets copy pasted often
|
||||||
|
.column(ColumnConfig::new("Package"))
|
||||||
|
.column(ColumnConfig::new("Version"))
|
||||||
|
.column(ColumnConfig::new("ExtraInfo").header("Extra Info"))
|
||||||
|
;
|
||||||
|
let schema = &crate::api2::node::apt::API_RETURN_SCHEMA_GET_VERSIONS;
|
||||||
|
|
||||||
|
format_and_print_result_full(&mut packages, schema, &output_format, &options);
|
||||||
|
|
||||||
|
Ok(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|
||||||
proxmox_backup::tools::setup_safe_path_env();
|
proxmox_backup::tools::setup_safe_path_env();
|
||||||
@ -396,6 +433,9 @@ fn main() {
|
|||||||
)
|
)
|
||||||
.insert("report",
|
.insert("report",
|
||||||
CliCommand::new(&API_METHOD_REPORT)
|
CliCommand::new(&API_METHOD_REPORT)
|
||||||
|
)
|
||||||
|
.insert("versions",
|
||||||
|
CliCommand::new(&API_METHOD_GET_VERSIONS)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
@ -413,29 +453,13 @@ pub fn complete_remote_datastore_name(_arg: &str, param: &HashMap<String, String
|
|||||||
|
|
||||||
let _ = proxmox::try_block!({
|
let _ = proxmox::try_block!({
|
||||||
let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
|
let remote = param.get("remote").ok_or_else(|| format_err!("no remote"))?;
|
||||||
let (remote_config, _digest) = config::remote::config()?;
|
|
||||||
|
|
||||||
let remote: config::remote::Remote = remote_config.lookup("remote", &remote)?;
|
let data = crate::tools::runtime::block_on(async move {
|
||||||
|
crate::api2::config::remote::scan_remote_datastores(remote.clone()).await
|
||||||
|
})?;
|
||||||
|
|
||||||
let options = HttpClientOptions::new()
|
for item in data {
|
||||||
.password(Some(remote.password.clone()))
|
list.push(item.store);
|
||||||
.fingerprint(remote.fingerprint.clone());
|
|
||||||
|
|
||||||
let client = HttpClient::new(
|
|
||||||
&remote.host,
|
|
||||||
remote.port.unwrap_or(8007),
|
|
||||||
&remote.userid,
|
|
||||||
options,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let result = crate::tools::runtime::block_on(client.get("api2/json/admin/datastore", None))?;
|
|
||||||
|
|
||||||
if let Some(data) = result["data"].as_array() {
|
|
||||||
for item in data {
|
|
||||||
if let Some(store) = item["store"].as_str() {
|
|
||||||
list.push(store.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::sync::{Arc};
|
use std::sync::Arc;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::os::unix::io::AsRawFd;
|
use std::os::unix::io::AsRawFd;
|
||||||
|
|
||||||
@ -74,6 +74,10 @@ async fn run() -> Result<(), Error> {
|
|||||||
bail!("unable to inititialize syslog - {}", err);
|
bail!("unable to inititialize syslog - {}", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Note: To debug early connection error use
|
||||||
|
// PROXMOX_DEBUG=1 ./target/release/proxmox-backup-proxy
|
||||||
|
let debug = std::env::var("PROXMOX_DEBUG").is_ok();
|
||||||
|
|
||||||
let _ = public_auth_key(); // load with lazy_static
|
let _ = public_auth_key(); // load with lazy_static
|
||||||
let _ = csrf_secret(); // load with lazy_static
|
let _ = csrf_secret(); // load with lazy_static
|
||||||
|
|
||||||
@ -86,7 +90,6 @@ async fn run() -> Result<(), Error> {
|
|||||||
config.add_alias("xtermjs", "/usr/share/pve-xtermjs");
|
config.add_alias("xtermjs", "/usr/share/pve-xtermjs");
|
||||||
config.add_alias("locale", "/usr/share/pbs-i18n");
|
config.add_alias("locale", "/usr/share/pbs-i18n");
|
||||||
config.add_alias("widgettoolkit", "/usr/share/javascript/proxmox-widget-toolkit");
|
config.add_alias("widgettoolkit", "/usr/share/javascript/proxmox-widget-toolkit");
|
||||||
config.add_alias("css", "/usr/share/javascript/proxmox-backup/css");
|
|
||||||
config.add_alias("docs", "/usr/share/doc/proxmox-backup/html");
|
config.add_alias("docs", "/usr/share/doc/proxmox-backup/html");
|
||||||
|
|
||||||
let mut indexpath = PathBuf::from(buildcfg::JS_DIR);
|
let mut indexpath = PathBuf::from(buildcfg::JS_DIR);
|
||||||
@ -116,25 +119,12 @@ async fn run() -> Result<(), Error> {
|
|||||||
let server = daemon::create_daemon(
|
let server = daemon::create_daemon(
|
||||||
([0,0,0,0,0,0,0,0], 8007).into(),
|
([0,0,0,0,0,0,0,0], 8007).into(),
|
||||||
|listener, ready| {
|
|listener, ready| {
|
||||||
let connections = proxmox_backup::tools::async_io::StaticIncoming::from(listener)
|
|
||||||
.map_err(Error::from)
|
|
||||||
.try_filter_map(move |(sock, _addr)| {
|
|
||||||
let acceptor = Arc::clone(&acceptor);
|
|
||||||
async move {
|
|
||||||
sock.set_nodelay(true).unwrap();
|
|
||||||
|
|
||||||
let _ = set_tcp_keepalive(sock.as_raw_fd(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME);
|
let connections = accept_connections(listener, acceptor, debug);
|
||||||
|
let connections = hyper::server::accept::from_stream(connections);
|
||||||
Ok(tokio_openssl::accept(&acceptor, sock)
|
|
||||||
.await
|
|
||||||
.ok() // handshake errors aren't be fatal, so return None to filter
|
|
||||||
)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let connections = proxmox_backup::tools::async_io::HyperAccept(connections);
|
|
||||||
|
|
||||||
Ok(ready
|
Ok(ready
|
||||||
.and_then(|_| hyper::Server::builder(connections)
|
.and_then(|_| hyper::Server::builder(connections)
|
||||||
.serve(rest_server)
|
.serve(rest_server)
|
||||||
.with_graceful_shutdown(server::shutdown_future())
|
.with_graceful_shutdown(server::shutdown_future())
|
||||||
.map_err(Error::from)
|
.map_err(Error::from)
|
||||||
@ -143,6 +133,7 @@ async fn run() -> Result<(), Error> {
|
|||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
"proxmox-backup-proxy.service",
|
||||||
);
|
);
|
||||||
|
|
||||||
server::write_pid(buildcfg::PROXMOX_BACKUP_PROXY_PID_FN)?;
|
server::write_pid(buildcfg::PROXMOX_BACKUP_PROXY_PID_FN)?;
|
||||||
@ -170,6 +161,72 @@ async fn run() -> Result<(), Error> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn accept_connections(
|
||||||
|
mut listener: tokio::net::TcpListener,
|
||||||
|
acceptor: Arc<openssl::ssl::SslAcceptor>,
|
||||||
|
debug: bool,
|
||||||
|
) -> tokio::sync::mpsc::Receiver<Result<tokio_openssl::SslStream<tokio::net::TcpStream>, Error>> {
|
||||||
|
|
||||||
|
const MAX_PENDING_ACCEPTS: usize = 1024;
|
||||||
|
|
||||||
|
let (sender, receiver) = tokio::sync::mpsc::channel(MAX_PENDING_ACCEPTS);
|
||||||
|
|
||||||
|
let accept_counter = Arc::new(());
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
match listener.accept().await {
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("error accepting tcp connection: {}", err);
|
||||||
|
}
|
||||||
|
Ok((sock, _addr)) => {
|
||||||
|
sock.set_nodelay(true).unwrap();
|
||||||
|
let _ = set_tcp_keepalive(sock.as_raw_fd(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME);
|
||||||
|
let acceptor = Arc::clone(&acceptor);
|
||||||
|
let mut sender = sender.clone();
|
||||||
|
|
||||||
|
if Arc::strong_count(&accept_counter) > MAX_PENDING_ACCEPTS {
|
||||||
|
eprintln!("connection rejected - to many open connections");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let accept_counter = accept_counter.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let accept_future = tokio::time::timeout(
|
||||||
|
Duration::new(10, 0), tokio_openssl::accept(&acceptor, sock));
|
||||||
|
|
||||||
|
let result = accept_future.await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Ok(connection)) => {
|
||||||
|
if let Err(_) = sender.send(Ok(connection)).await {
|
||||||
|
if debug {
|
||||||
|
eprintln!("detect closed connection channel");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(err)) => {
|
||||||
|
if debug {
|
||||||
|
eprintln!("https handshake failed - {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
if debug {
|
||||||
|
eprintln!("https handshake timeout");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(accept_counter); // decrease reference count
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
receiver
|
||||||
|
}
|
||||||
|
|
||||||
fn start_stat_generator() {
|
fn start_stat_generator() {
|
||||||
let abort_future = server::shutdown_future();
|
let abort_future = server::shutdown_future();
|
||||||
let future = Box::pin(run_stat_generator());
|
let future = Box::pin(run_stat_generator());
|
||||||
@ -320,7 +377,7 @@ async fn schedule_datastore_garbage_collection() {
|
|||||||
Err(_) => continue, // could not get lock
|
Err(_) => continue, // could not get lock
|
||||||
};
|
};
|
||||||
|
|
||||||
let auth_id = Authid::backup_auth_id();
|
let auth_id = Authid::root_auth_id();
|
||||||
|
|
||||||
if let Err(err) = crate::server::do_garbage_collection_job(job, datastore, auth_id, Some(event_str), false) {
|
if let Err(err) = crate::server::do_garbage_collection_job(job, datastore, auth_id, Some(event_str), false) {
|
||||||
eprintln!("unable to start garbage collection job on datastore {} - {}", store, err);
|
eprintln!("unable to start garbage collection job on datastore {} - {}", store, err);
|
||||||
@ -383,7 +440,7 @@ async fn schedule_datastore_prune() {
|
|||||||
Err(_) => continue, // could not get lock
|
Err(_) => continue, // could not get lock
|
||||||
};
|
};
|
||||||
|
|
||||||
let auth_id = Authid::backup_auth_id().clone();
|
let auth_id = Authid::root_auth_id().clone();
|
||||||
if let Err(err) = do_prune_job(job, prune_options, store.clone(), &auth_id, Some(event_str)) {
|
if let Err(err) = do_prune_job(job, prune_options, store.clone(), &auth_id, Some(event_str)) {
|
||||||
eprintln!("unable to start datastore prune job {} - {}", &store, err);
|
eprintln!("unable to start datastore prune job {} - {}", &store, err);
|
||||||
}
|
}
|
||||||
@ -427,7 +484,7 @@ async fn schedule_datastore_sync_jobs() {
|
|||||||
Err(_) => continue, // could not get lock
|
Err(_) => continue, // could not get lock
|
||||||
};
|
};
|
||||||
|
|
||||||
let auth_id = Authid::backup_auth_id().clone();
|
let auth_id = Authid::root_auth_id().clone();
|
||||||
if let Err(err) = do_sync_job(job, job_config, &auth_id, Some(event_str)) {
|
if let Err(err) = do_sync_job(job, job_config, &auth_id, Some(event_str)) {
|
||||||
eprintln!("unable to start datastore sync job {} - {}", &job_id, err);
|
eprintln!("unable to start datastore sync job {} - {}", &job_id, err);
|
||||||
}
|
}
|
||||||
@ -463,7 +520,7 @@ async fn schedule_datastore_verify_jobs() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let worker_type = "verificationjob";
|
let worker_type = "verificationjob";
|
||||||
let auth_id = Authid::backup_auth_id().clone();
|
let auth_id = Authid::root_auth_id().clone();
|
||||||
if check_schedule(worker_type, &event_str, &job_id) {
|
if check_schedule(worker_type, &event_str, &job_id) {
|
||||||
let job = match Job::new(&worker_type, &job_id) {
|
let job = match Job::new(&worker_type, &job_id) {
|
||||||
Ok(job) => job,
|
Ok(job) => job,
|
||||||
@ -503,7 +560,7 @@ async fn schedule_task_log_rotate() {
|
|||||||
if let Err(err) = WorkerTask::new_thread(
|
if let Err(err) = WorkerTask::new_thread(
|
||||||
worker_type,
|
worker_type,
|
||||||
None,
|
None,
|
||||||
Authid::backup_auth_id().clone(),
|
Authid::root_auth_id().clone(),
|
||||||
false,
|
false,
|
||||||
move |worker| {
|
move |worker| {
|
||||||
job.start(&worker.upid().to_string())?;
|
job.start(&worker.upid().to_string())?;
|
||||||
@ -524,16 +581,23 @@ async fn schedule_task_log_rotate() {
|
|||||||
let mut logrotate = LogRotate::new(buildcfg::API_ACCESS_LOG_FN, true)
|
let mut logrotate = LogRotate::new(buildcfg::API_ACCESS_LOG_FN, true)
|
||||||
.ok_or_else(|| format_err!("could not get API access log file names"))?;
|
.ok_or_else(|| format_err!("could not get API access log file names"))?;
|
||||||
|
|
||||||
let has_rotated = logrotate.rotate(max_size, None, Some(max_files))?;
|
if logrotate.rotate(max_size, None, Some(max_files))? {
|
||||||
if has_rotated {
|
|
||||||
println!("rotated access log, telling daemons to re-open log file");
|
println!("rotated access log, telling daemons to re-open log file");
|
||||||
proxmox_backup::tools::runtime::block_on(command_reopen_logfiles())?;
|
proxmox_backup::tools::runtime::block_on(command_reopen_logfiles())?;
|
||||||
|
|
||||||
worker.log(format!("API access log was rotated"));
|
worker.log(format!("API access log was rotated"));
|
||||||
} else {
|
} else {
|
||||||
worker.log(format!("API access log was not rotated"));
|
worker.log(format!("API access log was not rotated"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut logrotate = LogRotate::new(buildcfg::API_AUTH_LOG_FN, true)
|
||||||
|
.ok_or_else(|| format_err!("could not get API auth log file names"))?;
|
||||||
|
|
||||||
|
if logrotate.rotate(max_size, None, Some(max_files))? {
|
||||||
|
worker.log(format!("API authentication log was rotated"));
|
||||||
|
} else {
|
||||||
|
worker.log(format!("API authentication log was not rotated"));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -555,16 +619,22 @@ async fn command_reopen_logfiles() -> Result<(), Error> {
|
|||||||
// only care about the most recent daemon instance for each, proxy & api, as other older ones
|
// only care about the most recent daemon instance for each, proxy & api, as other older ones
|
||||||
// should not respond to new requests anyway, but only finish their current one and then exit.
|
// should not respond to new requests anyway, but only finish their current one and then exit.
|
||||||
let sock = server::our_ctrl_sock();
|
let sock = server::our_ctrl_sock();
|
||||||
server::send_command(sock, serde_json::json!({
|
let f1 = server::send_command(sock, serde_json::json!({
|
||||||
"command": "api-access-log-reopen",
|
"command": "api-access-log-reopen",
|
||||||
})).await?;
|
}));
|
||||||
|
|
||||||
let pid = server::read_pid(buildcfg::PROXMOX_BACKUP_API_PID_FN)?;
|
let pid = server::read_pid(buildcfg::PROXMOX_BACKUP_API_PID_FN)?;
|
||||||
let sock = server::ctrl_sock_from_pid(pid);
|
let sock = server::ctrl_sock_from_pid(pid);
|
||||||
server::send_command(sock, serde_json::json!({
|
let f2 = server::send_command(sock, serde_json::json!({
|
||||||
"command": "api-access-log-reopen",
|
"command": "api-access-log-reopen",
|
||||||
})).await?;
|
}));
|
||||||
Ok(())
|
|
||||||
|
match futures::join!(f1, f2) {
|
||||||
|
(Err(e1), Err(e2)) => Err(format_err!("reopen commands failed, proxy: {}; api: {}", e1, e2)),
|
||||||
|
(Err(e1), Ok(_)) => Err(format_err!("reopen commands failed, proxy: {}", e1)),
|
||||||
|
(Ok(_), Err(e2)) => Err(format_err!("reopen commands failed, api: {}", e2)),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_stat_generator() {
|
async fn run_stat_generator() {
|
||||||
|
@ -151,7 +151,7 @@ pub async fn benchmark(
|
|||||||
let crypt_config = match keyfile {
|
let crypt_config = match keyfile {
|
||||||
None => None,
|
None => None,
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
let (key, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
|
let (key, _, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
|
||||||
let crypt_config = CryptConfig::new(key)?;
|
let crypt_config = CryptConfig::new(key)?;
|
||||||
Some(Arc::new(crypt_config))
|
Some(Arc::new(crypt_config))
|
||||||
}
|
}
|
||||||
@ -225,7 +225,7 @@ async fn test_upload_speed(
|
|||||||
|
|
||||||
let backup_time = proxmox::tools::time::epoch_i64();
|
let backup_time = proxmox::tools::time::epoch_i64();
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
record_repository(&repo);
|
record_repository(&repo);
|
||||||
|
|
||||||
if verbose { eprintln!("Connecting to backup server"); }
|
if verbose { eprintln!("Connecting to backup server"); }
|
||||||
|
@ -73,13 +73,13 @@ async fn dump_catalog(param: Value) -> Result<Value, Error> {
|
|||||||
let crypt_config = match keydata {
|
let crypt_config = match keydata {
|
||||||
None => None,
|
None => None,
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
let (key, _created) = decrypt_key(&key, &get_encryption_key_password)?;
|
let (key, _created, _fingerprint) = decrypt_key(&key, &get_encryption_key_password)?;
|
||||||
let crypt_config = CryptConfig::new(key)?;
|
let crypt_config = CryptConfig::new(key)?;
|
||||||
Some(Arc::new(crypt_config))
|
Some(Arc::new(crypt_config))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
let client = BackupReader::start(
|
let client = BackupReader::start(
|
||||||
client,
|
client,
|
||||||
@ -92,6 +92,7 @@ async fn dump_catalog(param: Value) -> Result<Value, Error> {
|
|||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
let (manifest, _) = client.download_manifest().await?;
|
let (manifest, _) = client.download_manifest().await?;
|
||||||
|
manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?;
|
||||||
|
|
||||||
let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
|
let index = client.download_dynamic_index(&manifest, CATALOG_NAME).await?;
|
||||||
|
|
||||||
@ -153,7 +154,7 @@ async fn dump_catalog(param: Value) -> Result<Value, Error> {
|
|||||||
/// Shell to interactively inspect and restore snapshots.
|
/// Shell to interactively inspect and restore snapshots.
|
||||||
async fn catalog_shell(param: Value) -> Result<(), Error> {
|
async fn catalog_shell(param: Value) -> Result<(), Error> {
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
let path = tools::required_string_param(¶m, "snapshot")?;
|
let path = tools::required_string_param(¶m, "snapshot")?;
|
||||||
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
||||||
|
|
||||||
@ -170,7 +171,7 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
|
|||||||
let crypt_config = match keydata {
|
let crypt_config = match keydata {
|
||||||
None => None,
|
None => None,
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
let (key, _created) = decrypt_key(&key, &get_encryption_key_password)?;
|
let (key, _created, _fingerprint) = decrypt_key(&key, &get_encryption_key_password)?;
|
||||||
let crypt_config = CryptConfig::new(key)?;
|
let crypt_config = CryptConfig::new(key)?;
|
||||||
Some(Arc::new(crypt_config))
|
Some(Arc::new(crypt_config))
|
||||||
}
|
}
|
||||||
@ -199,6 +200,7 @@ async fn catalog_shell(param: Value) -> Result<(), Error> {
|
|||||||
.open("/tmp")?;
|
.open("/tmp")?;
|
||||||
|
|
||||||
let (manifest, _) = client.download_manifest().await?;
|
let (manifest, _) = client.download_manifest().await?;
|
||||||
|
manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?;
|
||||||
|
|
||||||
let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
|
let index = client.download_dynamic_index(&manifest, &server_archive_name).await?;
|
||||||
let most_used = index.find_most_used_chunks(8);
|
let most_used = index.find_most_used_chunks(8);
|
||||||
|
@ -4,14 +4,28 @@ use std::process::{Stdio, Command};
|
|||||||
|
|
||||||
use anyhow::{bail, format_err, Error};
|
use anyhow::{bail, format_err, Error};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
use proxmox::api::api;
|
use proxmox::api::api;
|
||||||
use proxmox::api::cli::{CliCommand, CliCommandMap};
|
use proxmox::api::cli::{
|
||||||
|
ColumnConfig,
|
||||||
|
CliCommand,
|
||||||
|
CliCommandMap,
|
||||||
|
format_and_print_result_full,
|
||||||
|
get_output_format,
|
||||||
|
OUTPUT_FORMAT,
|
||||||
|
};
|
||||||
use proxmox::sys::linux::tty;
|
use proxmox::sys::linux::tty;
|
||||||
use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
|
use proxmox::tools::fs::{file_get_contents, replace_file, CreateOptions};
|
||||||
|
|
||||||
use proxmox_backup::backup::{
|
use proxmox_backup::backup::{
|
||||||
encrypt_key_with_passphrase, load_and_decrypt_key, store_key_config, KeyConfig,
|
encrypt_key_with_passphrase,
|
||||||
|
load_and_decrypt_key,
|
||||||
|
store_key_config,
|
||||||
|
CryptConfig,
|
||||||
|
Kdf,
|
||||||
|
KeyConfig,
|
||||||
|
KeyDerivationConfig,
|
||||||
};
|
};
|
||||||
use proxmox_backup::tools;
|
use proxmox_backup::tools;
|
||||||
|
|
||||||
@ -71,27 +85,6 @@ pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
|
|||||||
bail!("no password input mechanism available");
|
bail!("no password input mechanism available");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[api(
|
|
||||||
default: "scrypt",
|
|
||||||
)]
|
|
||||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
|
||||||
#[serde(rename_all = "kebab-case")]
|
|
||||||
/// Key derivation function for password protected encryption keys.
|
|
||||||
pub enum Kdf {
|
|
||||||
/// Do not encrypt the key.
|
|
||||||
None,
|
|
||||||
|
|
||||||
/// Encrypt they key with a password using SCrypt.
|
|
||||||
Scrypt,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Kdf {
|
|
||||||
#[inline]
|
|
||||||
fn default() -> Self {
|
|
||||||
Kdf::Scrypt
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
input: {
|
input: {
|
||||||
properties: {
|
properties: {
|
||||||
@ -120,7 +113,10 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
|
|||||||
|
|
||||||
let kdf = kdf.unwrap_or_default();
|
let kdf = kdf.unwrap_or_default();
|
||||||
|
|
||||||
let key = proxmox::sys::linux::random_data(32)?;
|
let mut key_array = [0u8; 32];
|
||||||
|
proxmox::sys::linux::fill_with_random_data(&mut key_array)?;
|
||||||
|
let crypt_config = CryptConfig::new(key_array.clone())?;
|
||||||
|
let key = key_array.to_vec();
|
||||||
|
|
||||||
match kdf {
|
match kdf {
|
||||||
Kdf::None => {
|
Kdf::None => {
|
||||||
@ -134,10 +130,11 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
|
|||||||
created,
|
created,
|
||||||
modified: created,
|
modified: created,
|
||||||
data: key,
|
data: key,
|
||||||
|
fingerprint: Some(crypt_config.fingerprint()),
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
Kdf::Scrypt => {
|
Kdf::Scrypt | Kdf::PBKDF2 => {
|
||||||
// always read passphrase from tty
|
// always read passphrase from tty
|
||||||
if !tty::stdin_isatty() {
|
if !tty::stdin_isatty() {
|
||||||
bail!("unable to read passphrase - no tty");
|
bail!("unable to read passphrase - no tty");
|
||||||
@ -145,7 +142,8 @@ fn create(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error> {
|
|||||||
|
|
||||||
let password = tty::read_and_verify_password("Encryption Key Password: ")?;
|
let password = tty::read_and_verify_password("Encryption Key Password: ")?;
|
||||||
|
|
||||||
let key_config = encrypt_key_with_passphrase(&key, &password)?;
|
let mut key_config = encrypt_key_with_passphrase(&key, &password, kdf)?;
|
||||||
|
key_config.fingerprint = Some(crypt_config.fingerprint());
|
||||||
|
|
||||||
store_key_config(&path, false, key_config)?;
|
store_key_config(&path, false, key_config)?;
|
||||||
}
|
}
|
||||||
@ -188,7 +186,7 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
|
|||||||
bail!("unable to change passphrase - no tty");
|
bail!("unable to change passphrase - no tty");
|
||||||
}
|
}
|
||||||
|
|
||||||
let (key, created) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
|
let (key, created, fingerprint) = load_and_decrypt_key(&path, &get_encryption_key_password)?;
|
||||||
|
|
||||||
match kdf {
|
match kdf {
|
||||||
Kdf::None => {
|
Kdf::None => {
|
||||||
@ -202,14 +200,16 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
|
|||||||
created, // keep original value
|
created, // keep original value
|
||||||
modified,
|
modified,
|
||||||
data: key.to_vec(),
|
data: key.to_vec(),
|
||||||
|
fingerprint: Some(fingerprint),
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
Kdf::Scrypt => {
|
Kdf::Scrypt | Kdf::PBKDF2 => {
|
||||||
let password = tty::read_and_verify_password("New Password: ")?;
|
let password = tty::read_and_verify_password("New Password: ")?;
|
||||||
|
|
||||||
let mut new_key_config = encrypt_key_with_passphrase(&key, &password)?;
|
let mut new_key_config = encrypt_key_with_passphrase(&key, &password, kdf)?;
|
||||||
new_key_config.created = created; // keep original value
|
new_key_config.created = created; // keep original value
|
||||||
|
new_key_config.fingerprint = Some(fingerprint);
|
||||||
|
|
||||||
store_key_config(&path, true, new_key_config)?;
|
store_key_config(&path, true, new_key_config)?;
|
||||||
}
|
}
|
||||||
@ -218,6 +218,91 @@ fn change_passphrase(kdf: Option<Kdf>, path: Option<String>) -> Result<(), Error
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
properties: {
|
||||||
|
kdf: {
|
||||||
|
type: Kdf,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
/// Encryption Key Information
|
||||||
|
struct KeyInfo {
|
||||||
|
/// Path to key
|
||||||
|
path: String,
|
||||||
|
kdf: Kdf,
|
||||||
|
/// Key creation time
|
||||||
|
pub created: i64,
|
||||||
|
/// Key modification time
|
||||||
|
pub modified: i64,
|
||||||
|
/// Key fingerprint
|
||||||
|
pub fingerprint: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
path: {
|
||||||
|
description: "Key file. Without this the default key's metadata will be shown.",
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
"output-format": {
|
||||||
|
schema: OUTPUT_FORMAT,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
/// Print the encryption key's metadata.
|
||||||
|
fn show_key(
|
||||||
|
path: Option<String>,
|
||||||
|
param: Value,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let path = match path {
|
||||||
|
Some(path) => PathBuf::from(path),
|
||||||
|
None => {
|
||||||
|
let path = find_default_encryption_key()?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
format_err!("no encryption file provided and no default file found")
|
||||||
|
})?;
|
||||||
|
path
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
let config: KeyConfig = serde_json::from_slice(&file_get_contents(path.clone())?)?;
|
||||||
|
|
||||||
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
|
let info = KeyInfo {
|
||||||
|
path: format!("{:?}", path),
|
||||||
|
kdf: match config.kdf {
|
||||||
|
Some(KeyDerivationConfig::PBKDF2 { .. }) => Kdf::PBKDF2,
|
||||||
|
Some(KeyDerivationConfig::Scrypt { .. }) => Kdf::Scrypt,
|
||||||
|
None => Kdf::None,
|
||||||
|
},
|
||||||
|
created: config.created,
|
||||||
|
modified: config.modified,
|
||||||
|
fingerprint: match config.fingerprint {
|
||||||
|
Some(ref fp) => Some(format!("{}", fp)),
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let options = proxmox::api::cli::default_table_format_options()
|
||||||
|
.column(ColumnConfig::new("path"))
|
||||||
|
.column(ColumnConfig::new("kdf"))
|
||||||
|
.column(ColumnConfig::new("created").renderer(tools::format::render_epoch))
|
||||||
|
.column(ColumnConfig::new("modified").renderer(tools::format::render_epoch))
|
||||||
|
.column(ColumnConfig::new("fingerprint"));
|
||||||
|
|
||||||
|
let schema = &KeyInfo::API_SCHEMA;
|
||||||
|
|
||||||
|
format_and_print_result_full(&mut serde_json::to_value(info)?, schema, &output_format, &options);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[api(
|
#[api(
|
||||||
input: {
|
input: {
|
||||||
properties: {
|
properties: {
|
||||||
@ -313,13 +398,47 @@ fn paper_key(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let data = file_get_contents(&path)?;
|
let data = file_get_contents(&path)?;
|
||||||
let data = std::str::from_utf8(&data)?;
|
let data = String::from_utf8(data)?;
|
||||||
|
|
||||||
|
let (data, is_private_key) = if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
|
||||||
|
let lines: Vec<String> = data
|
||||||
|
.lines()
|
||||||
|
.map(|s| s.trim_end())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.map(String::from)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
|
||||||
|
bail!("unexpected key format");
|
||||||
|
}
|
||||||
|
|
||||||
|
if lines.len() < 20 {
|
||||||
|
bail!("unexpected key format");
|
||||||
|
}
|
||||||
|
|
||||||
|
(lines, true)
|
||||||
|
} else {
|
||||||
|
match serde_json::from_str::<KeyConfig>(&data) {
|
||||||
|
Ok(key_config) => {
|
||||||
|
let lines = serde_json::to_string_pretty(&key_config)?
|
||||||
|
.lines()
|
||||||
|
.map(String::from)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
(lines, false)
|
||||||
|
},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Couldn't parse '{:?}' as KeyConfig - {}", path, err);
|
||||||
|
bail!("Neither a PEM-formatted private key, nor a PBS key file.");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let format = output_format.unwrap_or(PaperkeyFormat::Html);
|
let format = output_format.unwrap_or(PaperkeyFormat::Html);
|
||||||
|
|
||||||
match format {
|
match format {
|
||||||
PaperkeyFormat::Html => paperkey_html(data, subject),
|
PaperkeyFormat::Html => paperkey_html(&data, subject, is_private_key),
|
||||||
PaperkeyFormat::Text => paperkey_text(data, subject),
|
PaperkeyFormat::Text => paperkey_text(&data, subject, is_private_key),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -337,6 +456,10 @@ pub fn cli() -> CliCommandMap {
|
|||||||
.arg_param(&["path"])
|
.arg_param(&["path"])
|
||||||
.completion_cb("path", tools::complete_file_name);
|
.completion_cb("path", tools::complete_file_name);
|
||||||
|
|
||||||
|
let key_show_cmd_def = CliCommand::new(&API_METHOD_SHOW_KEY)
|
||||||
|
.arg_param(&["path"])
|
||||||
|
.completion_cb("path", tools::complete_file_name);
|
||||||
|
|
||||||
let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
|
let paper_key_cmd_def = CliCommand::new(&API_METHOD_PAPER_KEY)
|
||||||
.arg_param(&["path"])
|
.arg_param(&["path"])
|
||||||
.completion_cb("path", tools::complete_file_name);
|
.completion_cb("path", tools::complete_file_name);
|
||||||
@ -346,10 +469,11 @@ pub fn cli() -> CliCommandMap {
|
|||||||
.insert("create-master-key", key_create_master_key_cmd_def)
|
.insert("create-master-key", key_create_master_key_cmd_def)
|
||||||
.insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
|
.insert("import-master-pubkey", key_import_master_pubkey_cmd_def)
|
||||||
.insert("change-passphrase", key_change_passphrase_cmd_def)
|
.insert("change-passphrase", key_change_passphrase_cmd_def)
|
||||||
|
.insert("show", key_show_cmd_def)
|
||||||
.insert("paperkey", paper_key_cmd_def)
|
.insert("paperkey", paper_key_cmd_def)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
fn paperkey_html(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
|
||||||
|
|
||||||
let img_size_pt = 500;
|
let img_size_pt = 500;
|
||||||
|
|
||||||
@ -378,21 +502,7 @@ fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
println!("<p>Subject: {}</p>", subject);
|
println!("<p>Subject: {}</p>", subject);
|
||||||
}
|
}
|
||||||
|
|
||||||
if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
|
if is_private {
|
||||||
let lines: Vec<String> = data.lines()
|
|
||||||
.map(|s| s.trim_end())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.map(String::from)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
|
|
||||||
bail!("unexpected key format");
|
|
||||||
}
|
|
||||||
|
|
||||||
if lines.len() < 20 {
|
|
||||||
bail!("unexpected key format");
|
|
||||||
}
|
|
||||||
|
|
||||||
const BLOCK_SIZE: usize = 20;
|
const BLOCK_SIZE: usize = 20;
|
||||||
let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
|
let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
|
||||||
|
|
||||||
@ -413,8 +523,7 @@ fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
|
|
||||||
println!("</p>");
|
println!("</p>");
|
||||||
|
|
||||||
let data = data.join("\n");
|
let qr_code = generate_qr_code("svg", data)?;
|
||||||
let qr_code = generate_qr_code("svg", data.as_bytes())?;
|
|
||||||
let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
|
let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
|
||||||
|
|
||||||
println!("<center>");
|
println!("<center>");
|
||||||
@ -430,16 +539,13 @@ fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let key_config: KeyConfig = serde_json::from_str(&data)?;
|
|
||||||
let key_text = serde_json::to_string_pretty(&key_config)?;
|
|
||||||
|
|
||||||
println!("<div style=\"page-break-inside: avoid\">");
|
println!("<div style=\"page-break-inside: avoid\">");
|
||||||
|
|
||||||
println!("<p>");
|
println!("<p>");
|
||||||
|
|
||||||
println!("-----BEGIN PROXMOX BACKUP KEY-----");
|
println!("-----BEGIN PROXMOX BACKUP KEY-----");
|
||||||
|
|
||||||
for line in key_text.lines() {
|
for line in lines {
|
||||||
println!("{}", line);
|
println!("{}", line);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -447,7 +553,7 @@ fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
|
|
||||||
println!("</p>");
|
println!("</p>");
|
||||||
|
|
||||||
let qr_code = generate_qr_code("svg", key_text.as_bytes())?;
|
let qr_code = generate_qr_code("svg", lines)?;
|
||||||
let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
|
let qr_code = base64::encode_config(&qr_code, base64::STANDARD_NO_PAD);
|
||||||
|
|
||||||
println!("<center>");
|
println!("<center>");
|
||||||
@ -464,27 +570,13 @@ fn paperkey_html(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn paperkey_text(data: &str, subject: Option<String>) -> Result<(), Error> {
|
fn paperkey_text(lines: &[String], subject: Option<String>, is_private: bool) -> Result<(), Error> {
|
||||||
|
|
||||||
if let Some(subject) = subject {
|
if let Some(subject) = subject {
|
||||||
println!("Subject: {}\n", subject);
|
println!("Subject: {}\n", subject);
|
||||||
}
|
}
|
||||||
|
|
||||||
if data.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") {
|
if is_private {
|
||||||
let lines: Vec<String> = data.lines()
|
|
||||||
.map(|s| s.trim_end())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.map(String::from)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if !lines[lines.len()-1].starts_with("-----END ENCRYPTED PRIVATE KEY-----") {
|
|
||||||
bail!("unexpected key format");
|
|
||||||
}
|
|
||||||
|
|
||||||
if lines.len() < 20 {
|
|
||||||
bail!("unexpected key format");
|
|
||||||
}
|
|
||||||
|
|
||||||
const BLOCK_SIZE: usize = 5;
|
const BLOCK_SIZE: usize = 5;
|
||||||
let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
|
let blocks = (lines.len() + BLOCK_SIZE -1)/BLOCK_SIZE;
|
||||||
|
|
||||||
@ -499,8 +591,7 @@ fn paperkey_text(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
for l in start..end {
|
for l in start..end {
|
||||||
println!("{:-2}: {}", l, lines[l]);
|
println!("{:-2}: {}", l, lines[l]);
|
||||||
}
|
}
|
||||||
let data = data.join("\n");
|
let qr_code = generate_qr_code("utf8i", data)?;
|
||||||
let qr_code = generate_qr_code("utf8i", data.as_bytes())?;
|
|
||||||
let qr_code = String::from_utf8(qr_code)
|
let qr_code = String::from_utf8(qr_code)
|
||||||
.map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
|
.map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
|
||||||
println!("{}", qr_code);
|
println!("{}", qr_code);
|
||||||
@ -510,14 +601,13 @@ fn paperkey_text(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let key_config: KeyConfig = serde_json::from_str(&data)?;
|
|
||||||
let key_text = serde_json::to_string_pretty(&key_config)?;
|
|
||||||
|
|
||||||
println!("-----BEGIN PROXMOX BACKUP KEY-----");
|
println!("-----BEGIN PROXMOX BACKUP KEY-----");
|
||||||
println!("{}", key_text);
|
for line in lines {
|
||||||
|
println!("{}", line);
|
||||||
|
}
|
||||||
println!("-----END PROXMOX BACKUP KEY-----");
|
println!("-----END PROXMOX BACKUP KEY-----");
|
||||||
|
|
||||||
let qr_code = generate_qr_code("utf8i", key_text.as_bytes())?;
|
let qr_code = generate_qr_code("utf8i", &lines)?;
|
||||||
let qr_code = String::from_utf8(qr_code)
|
let qr_code = String::from_utf8(qr_code)
|
||||||
.map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
|
.map_err(|_| format_err!("Failed to read qr code (got non-utf8 data)"))?;
|
||||||
|
|
||||||
@ -526,8 +616,7 @@ fn paperkey_text(data: &str, subject: Option<String>) -> Result<(), Error> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_qr_code(output_type: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
|
fn generate_qr_code(output_type: &str, lines: &[String]) -> Result<Vec<u8>, Error> {
|
||||||
|
|
||||||
let mut child = Command::new("qrencode")
|
let mut child = Command::new("qrencode")
|
||||||
.args(&["-t", output_type, "-m0", "-s1", "-lm", "--output", "-"])
|
.args(&["-t", output_type, "-m0", "-s1", "-lm", "--output", "-"])
|
||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
@ -537,7 +626,8 @@ fn generate_qr_code(output_type: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
|
|||||||
{
|
{
|
||||||
let stdin = child.stdin.as_mut()
|
let stdin = child.stdin.as_mut()
|
||||||
.ok_or_else(|| format_err!("Failed to open stdin"))?;
|
.ok_or_else(|| format_err!("Failed to open stdin"))?;
|
||||||
stdin.write_all(data)
|
let data = lines.join("\n");
|
||||||
|
stdin.write_all(data.as_bytes())
|
||||||
.map_err(|_| format_err!("Failed to write to stdin"))?;
|
.map_err(|_| format_err!("Failed to write to stdin"))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,6 +8,8 @@ mod task;
|
|||||||
pub use task::*;
|
pub use task::*;
|
||||||
mod catalog;
|
mod catalog;
|
||||||
pub use catalog::*;
|
pub use catalog::*;
|
||||||
|
mod snapshot;
|
||||||
|
pub use snapshot::*;
|
||||||
|
|
||||||
pub mod key;
|
pub mod key;
|
||||||
|
|
||||||
|
@ -163,7 +163,7 @@ fn mount(
|
|||||||
async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
|
async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
let archive_name = tools::required_string_param(¶m, "archive-name")?;
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
let target = param["target"].as_str();
|
let target = param["target"].as_str();
|
||||||
|
|
||||||
@ -182,7 +182,9 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
|
|||||||
let crypt_config = match keyfile {
|
let crypt_config = match keyfile {
|
||||||
None => None,
|
None => None,
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
let (key, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
|
println!("Encryption key file: '{:?}'", path);
|
||||||
|
let (key, _, fingerprint) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?;
|
||||||
|
println!("Encryption key fingerprint: '{}'", fingerprint);
|
||||||
Some(Arc::new(CryptConfig::new(key)?))
|
Some(Arc::new(CryptConfig::new(key)?))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -212,6 +214,7 @@ async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> {
|
|||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
let (manifest, _) = client.download_manifest().await?;
|
let (manifest, _) = client.download_manifest().await?;
|
||||||
|
manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?;
|
||||||
|
|
||||||
let file_info = manifest.lookup_file_info(&server_archive_name)?;
|
let file_info = manifest.lookup_file_info(&server_archive_name)?;
|
||||||
|
|
||||||
|
416
src/bin/proxmox_backup_client/snapshot.rs
Normal file
@ -0,0 +1,416 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use anyhow::Error;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
use proxmox::{
|
||||||
|
api::{api, cli::*},
|
||||||
|
tools::fs::file_get_contents,
|
||||||
|
};
|
||||||
|
|
||||||
|
use proxmox_backup::{
|
||||||
|
tools,
|
||||||
|
api2::types::*,
|
||||||
|
backup::{
|
||||||
|
CryptMode,
|
||||||
|
CryptConfig,
|
||||||
|
DataBlob,
|
||||||
|
BackupGroup,
|
||||||
|
decrypt_key,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
REPO_URL_SCHEMA,
|
||||||
|
KEYFILE_SCHEMA,
|
||||||
|
KEYFD_SCHEMA,
|
||||||
|
BackupDir,
|
||||||
|
api_datastore_list_snapshots,
|
||||||
|
complete_backup_snapshot,
|
||||||
|
complete_backup_group,
|
||||||
|
complete_repository,
|
||||||
|
connect,
|
||||||
|
extract_repository_from_value,
|
||||||
|
record_repository,
|
||||||
|
keyfile_parameters,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
type: String,
|
||||||
|
description: "Backup group.",
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
"output-format": {
|
||||||
|
schema: OUTPUT_FORMAT,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// List backup snapshots.
|
||||||
|
async fn list_snapshots(param: Value) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
|
let group: Option<BackupGroup> = if let Some(path) = param["group"].as_str() {
|
||||||
|
Some(path.parse()?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut data = api_datastore_list_snapshots(&client, repo.store(), group).await?;
|
||||||
|
|
||||||
|
record_repository(&repo);
|
||||||
|
|
||||||
|
let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
|
||||||
|
let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
|
||||||
|
let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time)?;
|
||||||
|
Ok(snapshot.relative_path().to_str().unwrap().to_owned())
|
||||||
|
};
|
||||||
|
|
||||||
|
let render_files = |_v: &Value, record: &Value| -> Result<String, Error> {
|
||||||
|
let item: SnapshotListItem = serde_json::from_value(record.to_owned())?;
|
||||||
|
let mut filenames = Vec::new();
|
||||||
|
for file in &item.files {
|
||||||
|
filenames.push(file.filename.to_string());
|
||||||
|
}
|
||||||
|
Ok(tools::format::render_backup_file_list(&filenames[..]))
|
||||||
|
};
|
||||||
|
|
||||||
|
let options = default_table_format_options()
|
||||||
|
.sortby("backup-type", false)
|
||||||
|
.sortby("backup-id", false)
|
||||||
|
.sortby("backup-time", false)
|
||||||
|
.column(ColumnConfig::new("backup-id").renderer(render_snapshot_path).header("snapshot"))
|
||||||
|
.column(ColumnConfig::new("size").renderer(tools::format::render_bytes_human_readable))
|
||||||
|
.column(ColumnConfig::new("files").renderer(render_files))
|
||||||
|
;
|
||||||
|
|
||||||
|
let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOTS;
|
||||||
|
|
||||||
|
format_and_print_result_full(&mut data, info, &output_format, &options);
|
||||||
|
|
||||||
|
Ok(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
type: String,
|
||||||
|
description: "Snapshot path.",
|
||||||
|
},
|
||||||
|
"output-format": {
|
||||||
|
schema: OUTPUT_FORMAT,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// List snapshot files.
|
||||||
|
async fn list_snapshot_files(param: Value) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
|
let path = tools::required_string_param(¶m, "snapshot")?;
|
||||||
|
let snapshot: BackupDir = path.parse()?;
|
||||||
|
|
||||||
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
|
let path = format!("api2/json/admin/datastore/{}/files", repo.store());
|
||||||
|
|
||||||
|
let mut result = client.get(&path, Some(json!({
|
||||||
|
"backup-type": snapshot.group().backup_type(),
|
||||||
|
"backup-id": snapshot.group().backup_id(),
|
||||||
|
"backup-time": snapshot.backup_time(),
|
||||||
|
}))).await?;
|
||||||
|
|
||||||
|
record_repository(&repo);
|
||||||
|
|
||||||
|
let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES;
|
||||||
|
|
||||||
|
let mut data: Value = result["data"].take();
|
||||||
|
|
||||||
|
let options = default_table_format_options();
|
||||||
|
|
||||||
|
format_and_print_result_full(&mut data, info, &output_format, &options);
|
||||||
|
|
||||||
|
Ok(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
type: String,
|
||||||
|
description: "Snapshot path.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// Forget (remove) backup snapshots.
|
||||||
|
async fn forget_snapshots(param: Value) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
|
let path = tools::required_string_param(¶m, "snapshot")?;
|
||||||
|
let snapshot: BackupDir = path.parse()?;
|
||||||
|
|
||||||
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
|
let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
|
||||||
|
|
||||||
|
let result = client.delete(&path, Some(json!({
|
||||||
|
"backup-type": snapshot.group().backup_type(),
|
||||||
|
"backup-id": snapshot.group().backup_id(),
|
||||||
|
"backup-time": snapshot.backup_time(),
|
||||||
|
}))).await?;
|
||||||
|
|
||||||
|
record_repository(&repo);
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
type: String,
|
||||||
|
description: "Group/Snapshot path.",
|
||||||
|
},
|
||||||
|
logfile: {
|
||||||
|
type: String,
|
||||||
|
description: "The path to the log file you want to upload.",
|
||||||
|
},
|
||||||
|
keyfile: {
|
||||||
|
schema: KEYFILE_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
"keyfd": {
|
||||||
|
schema: KEYFD_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
"crypt-mode": {
|
||||||
|
type: CryptMode,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// Upload backup log file.
|
||||||
|
async fn upload_log(param: Value) -> Result<Value, Error> {
|
||||||
|
|
||||||
|
let logfile = tools::required_string_param(¶m, "logfile")?;
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
|
||||||
|
let snapshot = tools::required_string_param(¶m, "snapshot")?;
|
||||||
|
let snapshot: BackupDir = snapshot.parse()?;
|
||||||
|
|
||||||
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
|
let (keydata, crypt_mode) = keyfile_parameters(¶m)?;
|
||||||
|
|
||||||
|
let crypt_config = match keydata {
|
||||||
|
None => None,
|
||||||
|
Some(key) => {
|
||||||
|
let (key, _created, _) = decrypt_key(&key, &crate::key::get_encryption_key_password)?;
|
||||||
|
let crypt_config = CryptConfig::new(key)?;
|
||||||
|
Some(Arc::new(crypt_config))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let data = file_get_contents(logfile)?;
|
||||||
|
|
||||||
|
// fixme: howto sign log?
|
||||||
|
let blob = match crypt_mode {
|
||||||
|
CryptMode::None | CryptMode::SignOnly => DataBlob::encode(&data, None, true)?,
|
||||||
|
CryptMode::Encrypt => DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
let raw_data = blob.into_inner();
|
||||||
|
|
||||||
|
let path = format!("api2/json/admin/datastore/{}/upload-backup-log", repo.store());
|
||||||
|
|
||||||
|
let args = json!({
|
||||||
|
"backup-type": snapshot.group().backup_type(),
|
||||||
|
"backup-id": snapshot.group().backup_id(),
|
||||||
|
"backup-time": snapshot.backup_time(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let body = hyper::Body::from(raw_data);
|
||||||
|
|
||||||
|
client.upload("application/octet-stream", body, &path, Some(args)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
type: String,
|
||||||
|
description: "Snapshot path.",
|
||||||
|
},
|
||||||
|
"output-format": {
|
||||||
|
schema: OUTPUT_FORMAT,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// Show notes
|
||||||
|
async fn show_notes(param: Value) -> Result<Value, Error> {
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
let path = tools::required_string_param(¶m, "snapshot")?;
|
||||||
|
|
||||||
|
let snapshot: BackupDir = path.parse()?;
|
||||||
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
|
let path = format!("api2/json/admin/datastore/{}/notes", repo.store());
|
||||||
|
|
||||||
|
let args = json!({
|
||||||
|
"backup-type": snapshot.group().backup_type(),
|
||||||
|
"backup-id": snapshot.group().backup_id(),
|
||||||
|
"backup-time": snapshot.backup_time(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
|
let mut result = client.get(&path, Some(args)).await?;
|
||||||
|
|
||||||
|
let notes = result["data"].take();
|
||||||
|
|
||||||
|
if output_format == "text" {
|
||||||
|
if let Some(notes) = notes.as_str() {
|
||||||
|
println!("{}", notes);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
format_and_print_result(
|
||||||
|
&json!({
|
||||||
|
"notes": notes,
|
||||||
|
}),
|
||||||
|
&output_format,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[api(
|
||||||
|
input: {
|
||||||
|
properties: {
|
||||||
|
repository: {
|
||||||
|
schema: REPO_URL_SCHEMA,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
type: String,
|
||||||
|
description: "Snapshot path.",
|
||||||
|
},
|
||||||
|
notes: {
|
||||||
|
type: String,
|
||||||
|
description: "The Notes.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)]
|
||||||
|
/// Update Notes
|
||||||
|
async fn update_notes(param: Value) -> Result<Value, Error> {
|
||||||
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
|
let path = tools::required_string_param(¶m, "snapshot")?;
|
||||||
|
let notes = tools::required_string_param(¶m, "notes")?;
|
||||||
|
|
||||||
|
let snapshot: BackupDir = path.parse()?;
|
||||||
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
|
let path = format!("api2/json/admin/datastore/{}/notes", repo.store());
|
||||||
|
|
||||||
|
let args = json!({
|
||||||
|
"backup-type": snapshot.group().backup_type(),
|
||||||
|
"backup-id": snapshot.group().backup_id(),
|
||||||
|
"backup-time": snapshot.backup_time(),
|
||||||
|
"notes": notes,
|
||||||
|
});
|
||||||
|
|
||||||
|
client.put(&path, Some(args)).await?;
|
||||||
|
|
||||||
|
Ok(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notes_cli() -> CliCommandMap {
|
||||||
|
CliCommandMap::new()
|
||||||
|
.insert(
|
||||||
|
"show",
|
||||||
|
CliCommand::new(&API_METHOD_SHOW_NOTES)
|
||||||
|
.arg_param(&["snapshot"])
|
||||||
|
.completion_cb("snapshot", complete_backup_snapshot),
|
||||||
|
)
|
||||||
|
.insert(
|
||||||
|
"update",
|
||||||
|
CliCommand::new(&API_METHOD_UPDATE_NOTES)
|
||||||
|
.arg_param(&["snapshot", "notes"])
|
||||||
|
.completion_cb("snapshot", complete_backup_snapshot),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn snapshot_mgtm_cli() -> CliCommandMap {
|
||||||
|
CliCommandMap::new()
|
||||||
|
.insert("notes", notes_cli())
|
||||||
|
.insert(
|
||||||
|
"list",
|
||||||
|
CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
|
||||||
|
.arg_param(&["group"])
|
||||||
|
.completion_cb("group", complete_backup_group)
|
||||||
|
.completion_cb("repository", complete_repository)
|
||||||
|
)
|
||||||
|
.insert(
|
||||||
|
"files",
|
||||||
|
CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
|
||||||
|
.arg_param(&["snapshot"])
|
||||||
|
.completion_cb("repository", complete_repository)
|
||||||
|
.completion_cb("snapshot", complete_backup_snapshot)
|
||||||
|
)
|
||||||
|
.insert(
|
||||||
|
"forget",
|
||||||
|
CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
|
||||||
|
.arg_param(&["snapshot"])
|
||||||
|
.completion_cb("repository", complete_repository)
|
||||||
|
.completion_cb("snapshot", complete_backup_snapshot)
|
||||||
|
)
|
||||||
|
.insert(
|
||||||
|
"upload-log",
|
||||||
|
CliCommand::new(&API_METHOD_UPLOAD_LOG)
|
||||||
|
.arg_param(&["snapshot", "logfile"])
|
||||||
|
.completion_cb("snapshot", complete_backup_snapshot)
|
||||||
|
.completion_cb("logfile", tools::complete_file_name)
|
||||||
|
.completion_cb("keyfile", tools::complete_file_name)
|
||||||
|
.completion_cb("repository", complete_repository)
|
||||||
|
)
|
||||||
|
}
|
@ -48,7 +48,7 @@ async fn task_list(param: Value) -> Result<Value, Error> {
|
|||||||
let output_format = get_output_format(¶m);
|
let output_format = get_output_format(¶m);
|
||||||
|
|
||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
let limit = param["limit"].as_u64().unwrap_or(50) as usize;
|
let limit = param["limit"].as_u64().unwrap_or(50) as usize;
|
||||||
let running = !param["all"].as_bool().unwrap_or(false);
|
let running = !param["all"].as_bool().unwrap_or(false);
|
||||||
@ -96,7 +96,7 @@ async fn task_log(param: Value) -> Result<Value, Error> {
|
|||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
let upid = tools::required_string_param(¶m, "upid")?;
|
let upid = tools::required_string_param(¶m, "upid")?;
|
||||||
|
|
||||||
let client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let client = connect(&repo)?;
|
||||||
|
|
||||||
display_task_log(client, upid, true).await?;
|
display_task_log(client, upid, true).await?;
|
||||||
|
|
||||||
@ -122,9 +122,9 @@ async fn task_stop(param: Value) -> Result<Value, Error> {
|
|||||||
let repo = extract_repository_from_value(¶m)?;
|
let repo = extract_repository_from_value(¶m)?;
|
||||||
let upid_str = tools::required_string_param(¶m, "upid")?;
|
let upid_str = tools::required_string_param(¶m, "upid")?;
|
||||||
|
|
||||||
let mut client = connect(repo.host(), repo.port(), repo.auth_id())?;
|
let mut client = connect(&repo)?;
|
||||||
|
|
||||||
let path = format!("api2/json/nodes/localhost/tasks/{}", upid_str);
|
let path = format!("api2/json/nodes/localhost/tasks/{}", tools::percent_encode_component(upid_str));
|
||||||
let _ = client.delete(&path, None).await?;
|
let _ = client.delete(&path, None).await?;
|
||||||
|
|
||||||
Ok(Value::Null)
|
Ok(Value::Null)
|
||||||
|
@ -16,9 +16,14 @@ pub const PROXMOX_BACKUP_RUN_DIR: &str = PROXMOX_BACKUP_RUN_DIR_M!();
|
|||||||
/// namespaced directory for persistent logging
|
/// namespaced directory for persistent logging
|
||||||
pub const PROXMOX_BACKUP_LOG_DIR: &str = PROXMOX_BACKUP_LOG_DIR_M!();
|
pub const PROXMOX_BACKUP_LOG_DIR: &str = PROXMOX_BACKUP_LOG_DIR_M!();
|
||||||
|
|
||||||
/// logfile for all API reuests handled by the proxy and privileged API daemons
|
/// logfile for all API reuests handled by the proxy and privileged API daemons. Note that not all
|
||||||
|
/// failed logins can be logged here with full information, use the auth log for that.
|
||||||
pub const API_ACCESS_LOG_FN: &str = concat!(PROXMOX_BACKUP_LOG_DIR_M!(), "/api/access.log");
|
pub const API_ACCESS_LOG_FN: &str = concat!(PROXMOX_BACKUP_LOG_DIR_M!(), "/api/access.log");
|
||||||
|
|
||||||
|
/// logfile for any failed authentication, via ticket or via token, and new successfull ticket
|
||||||
|
/// creations. This file can be useful for fail2ban.
|
||||||
|
pub const API_AUTH_LOG_FN: &str = concat!(PROXMOX_BACKUP_LOG_DIR_M!(), "/api/auth.log");
|
||||||
|
|
||||||
/// the PID filename for the unprivileged proxy daemon
|
/// the PID filename for the unprivileged proxy daemon
|
||||||
pub const PROXMOX_BACKUP_PROXY_PID_FN: &str = concat!(PROXMOX_BACKUP_RUN_DIR_M!(), "/proxy.pid");
|
pub const PROXMOX_BACKUP_PROXY_PID_FN: &str = concat!(PROXMOX_BACKUP_RUN_DIR_M!(), "/proxy.pid");
|
||||||
|
|
||||||
|
@ -475,6 +475,13 @@ impl BackupWriter {
|
|||||||
Ok(index)
|
Ok(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Retrieve backup time of last backup
|
||||||
|
pub async fn previous_backup_time(&self) -> Result<Option<i64>, Error> {
|
||||||
|
let data = self.h2.get("previous_backup_time", None).await?;
|
||||||
|
serde_json::from_value(data)
|
||||||
|
.map_err(|err| format_err!("Failed to parse backup time value returned by server - {}", err))
|
||||||
|
}
|
||||||
|
|
||||||
/// Download backup manifest (index.json) of last backup
|
/// Download backup manifest (index.json) of last backup
|
||||||
pub async fn download_previous_manifest(&self) -> Result<BackupManifest, Error> {
|
pub async fn download_previous_manifest(&self) -> Result<BackupManifest, Error> {
|
||||||
|
|
||||||
|
@ -405,6 +405,9 @@ impl HttpClient {
|
|||||||
///
|
///
|
||||||
/// Login is done on demand, so this is only required if you need
|
/// Login is done on demand, so this is only required if you need
|
||||||
/// access to authentication data in 'AuthInfo'.
|
/// access to authentication data in 'AuthInfo'.
|
||||||
|
///
|
||||||
|
/// Note: tickets a periodially re-newed, so one can use this
|
||||||
|
/// to query changed ticket.
|
||||||
pub async fn login(&self) -> Result<AuthInfo, Error> {
|
pub async fn login(&self) -> Result<AuthInfo, Error> {
|
||||||
if let Some(future) = &self.first_auth {
|
if let Some(future) = &self.first_auth {
|
||||||
future.listen().await?;
|
future.listen().await?;
|
||||||
@ -531,6 +534,15 @@ impl HttpClient {
|
|||||||
self.request(req).await
|
self.request(req).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn put(
|
||||||
|
&mut self,
|
||||||
|
path: &str,
|
||||||
|
data: Option<Value>,
|
||||||
|
) -> Result<Value, Error> {
|
||||||
|
let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?;
|
||||||
|
self.request(req).await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn download(
|
pub async fn download(
|
||||||
&mut self,
|
&mut self,
|
||||||
path: &str,
|
path: &str,
|
||||||
|
@ -3,6 +3,7 @@ use std::task::{Context, Poll};
|
|||||||
|
|
||||||
use anyhow::{Error};
|
use anyhow::{Error};
|
||||||
use futures::*;
|
use futures::*;
|
||||||
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::backup::ChunkInfo;
|
use crate::backup::ChunkInfo;
|
||||||
|
|
||||||
@ -15,7 +16,9 @@ pub trait MergeKnownChunks: Sized {
|
|||||||
fn merge_known_chunks(self) -> MergeKnownChunksQueue<Self>;
|
fn merge_known_chunks(self) -> MergeKnownChunksQueue<Self>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pin_project]
|
||||||
pub struct MergeKnownChunksQueue<S> {
|
pub struct MergeKnownChunksQueue<S> {
|
||||||
|
#[pin]
|
||||||
input: S,
|
input: S,
|
||||||
buffer: Option<MergedChunkInfo>,
|
buffer: Option<MergedChunkInfo>,
|
||||||
}
|
}
|
||||||
@ -39,10 +42,10 @@ where
|
|||||||
type Item = Result<MergedChunkInfo, Error>;
|
type Item = Result<MergedChunkInfo, Error>;
|
||||||
|
|
||||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||||
let this = unsafe { self.get_unchecked_mut() };
|
let mut this = self.project();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match ready!(unsafe { Pin::new_unchecked(&mut this.input) }.poll_next(cx)) {
|
match ready!(this.input.as_mut().poll_next(cx)) {
|
||||||
Some(Err(err)) => return Poll::Ready(Some(Err(err))),
|
Some(Err(err)) => return Poll::Ready(Some(Err(err))),
|
||||||
None => {
|
None => {
|
||||||
if let Some(last) = this.buffer.take() {
|
if let Some(last) = this.buffer.take() {
|
||||||
@ -58,13 +61,13 @@ where
|
|||||||
|
|
||||||
match last {
|
match last {
|
||||||
None => {
|
None => {
|
||||||
this.buffer = Some(MergedChunkInfo::Known(list));
|
*this.buffer = Some(MergedChunkInfo::Known(list));
|
||||||
// continue
|
// continue
|
||||||
}
|
}
|
||||||
Some(MergedChunkInfo::Known(mut last_list)) => {
|
Some(MergedChunkInfo::Known(mut last_list)) => {
|
||||||
last_list.extend_from_slice(&list);
|
last_list.extend_from_slice(&list);
|
||||||
let len = last_list.len();
|
let len = last_list.len();
|
||||||
this.buffer = Some(MergedChunkInfo::Known(last_list));
|
*this.buffer = Some(MergedChunkInfo::Known(last_list));
|
||||||
|
|
||||||
if len >= 64 {
|
if len >= 64 {
|
||||||
return Poll::Ready(this.buffer.take().map(Ok));
|
return Poll::Ready(this.buffer.take().map(Ok));
|
||||||
@ -72,7 +75,7 @@ where
|
|||||||
// continue
|
// continue
|
||||||
}
|
}
|
||||||
Some(MergedChunkInfo::New(_)) => {
|
Some(MergedChunkInfo::New(_)) => {
|
||||||
this.buffer = Some(MergedChunkInfo::Known(list));
|
*this.buffer = Some(MergedChunkInfo::Known(list));
|
||||||
return Poll::Ready(last.map(Ok));
|
return Poll::Ready(last.map(Ok));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -80,7 +83,7 @@ where
|
|||||||
MergedChunkInfo::New(chunk_info) => {
|
MergedChunkInfo::New(chunk_info) => {
|
||||||
let new = MergedChunkInfo::New(chunk_info);
|
let new = MergedChunkInfo::New(chunk_info);
|
||||||
if let Some(last) = this.buffer.take() {
|
if let Some(last) = this.buffer.take() {
|
||||||
this.buffer = Some(new);
|
*this.buffer = Some(new);
|
||||||
return Poll::Ready(Some(Ok(last)));
|
return Poll::Ready(Some(Ok(last)));
|
||||||
} else {
|
} else {
|
||||||
return Poll::Ready(Some(Ok(new)));
|
return Poll::Ready(Some(Ok(new)));
|
||||||
|
@ -103,7 +103,7 @@ async fn pull_index_chunks<I: IndexFile>(
|
|||||||
|
|
||||||
let bytes = bytes.load(Ordering::SeqCst);
|
let bytes = bytes.load(Ordering::SeqCst);
|
||||||
|
|
||||||
worker.log(format!("downloaded {} bytes ({} MiB/s)", bytes, (bytes as f64)/(1024.0*1024.0*elapsed)));
|
worker.log(format!("downloaded {} bytes ({:.2} MiB/s)", bytes, (bytes as f64)/(1024.0*1024.0*elapsed)));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -410,7 +410,8 @@ pub async fn pull_group(
|
|||||||
|
|
||||||
list.sort_unstable_by(|a, b| a.backup_time.cmp(&b.backup_time));
|
list.sort_unstable_by(|a, b| a.backup_time.cmp(&b.backup_time));
|
||||||
|
|
||||||
let auth_info = client.login().await?;
|
client.login().await?; // make sure auth is complete
|
||||||
|
|
||||||
let fingerprint = client.fingerprint();
|
let fingerprint = client.fingerprint();
|
||||||
|
|
||||||
let last_sync = tgt_store.last_successful_backup(group)?;
|
let last_sync = tgt_store.last_successful_backup(group)?;
|
||||||
@ -447,6 +448,9 @@ pub async fn pull_group(
|
|||||||
if last_sync_time > backup_time { continue; }
|
if last_sync_time > backup_time { continue; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// get updated auth_info (new tickets)
|
||||||
|
let auth_info = client.login().await?;
|
||||||
|
|
||||||
let options = HttpClientOptions::new()
|
let options = HttpClientOptions::new()
|
||||||
.password(Some(auth_info.ticket.clone()))
|
.password(Some(auth_info.ticket.clone()))
|
||||||
.fingerprint(fingerprint.clone());
|
.fingerprint(fingerprint.clone());
|
||||||
@ -524,7 +528,16 @@ pub async fn pull_store(
|
|||||||
for (groups_done, item) in list.into_iter().enumerate() {
|
for (groups_done, item) in list.into_iter().enumerate() {
|
||||||
let group = BackupGroup::new(&item.backup_type, &item.backup_id);
|
let group = BackupGroup::new(&item.backup_type, &item.backup_id);
|
||||||
|
|
||||||
let (owner, _lock_guard) = tgt_store.create_locked_backup_group(&group, &auth_id)?;
|
let (owner, _lock_guard) = match tgt_store.create_locked_backup_group(&group, &auth_id) {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(err) => {
|
||||||
|
worker.log(format!("sync group {}/{} failed - group lock failed: {}",
|
||||||
|
item.backup_type, item.backup_id, err));
|
||||||
|
errors = true; // do not stop here, instead continue
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// permission check
|
// permission check
|
||||||
if auth_id != owner { // only the owner is allowed to create additional snapshots
|
if auth_id != owner { // only the owner is allowed to create additional snapshots
|
||||||
worker.log(format!("sync group {}/{} failed - owner check failed ({} != {})",
|
worker.log(format!("sync group {}/{} failed - owner check failed ({} != {})",
|
||||||
|
@ -2,6 +2,7 @@ use anyhow::{bail, Error};
|
|||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
use super::HttpClient;
|
use super::HttpClient;
|
||||||
|
use crate::tools;
|
||||||
|
|
||||||
pub async fn display_task_log(
|
pub async fn display_task_log(
|
||||||
client: HttpClient,
|
client: HttpClient,
|
||||||
@ -9,7 +10,7 @@ pub async fn display_task_log(
|
|||||||
strip_date: bool,
|
strip_date: bool,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
|
||||||
let path = format!("api2/json/nodes/localhost/tasks/{}/log", upid_str);
|
let path = format!("api2/json/nodes/localhost/tasks/{}/log", tools::percent_encode_component(upid_str));
|
||||||
|
|
||||||
let mut start = 1;
|
let mut start = 1;
|
||||||
let limit = 500;
|
let limit = 500;
|
||||||
|
@ -32,6 +32,14 @@ pub const DIR_NAME_SCHEMA: Schema = StringSchema::new("Directory name").schema()
|
|||||||
path: {
|
path: {
|
||||||
schema: DIR_NAME_SCHEMA,
|
schema: DIR_NAME_SCHEMA,
|
||||||
},
|
},
|
||||||
|
"notify-user": {
|
||||||
|
optional: true,
|
||||||
|
type: Userid,
|
||||||
|
},
|
||||||
|
"notify": {
|
||||||
|
optional: true,
|
||||||
|
schema: DATASTORE_NOTIFY_STRING_SCHEMA,
|
||||||
|
},
|
||||||
comment: {
|
comment: {
|
||||||
optional: true,
|
optional: true,
|
||||||
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
schema: SINGLE_LINE_COMMENT_SCHEMA,
|
||||||
@ -101,6 +109,12 @@ pub struct DataStoreConfig {
|
|||||||
/// If enabled, all backups will be verified right after completion.
|
/// If enabled, all backups will be verified right after completion.
|
||||||
#[serde(skip_serializing_if="Option::is_none")]
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
pub verify_new: Option<bool>,
|
pub verify_new: Option<bool>,
|
||||||
|
/// Send job email notification to this user
|
||||||
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub notify_user: Option<Userid>,
|
||||||
|
/// Send notification only for job errors
|
||||||
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
|
pub notify: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init() -> SectionConfig {
|
fn init() -> SectionConfig {
|
||||||
|
@ -44,7 +44,7 @@ pub const REMOTE_PASSWORD_SCHEMA: Schema = StringSchema::new("Password or auth t
|
|||||||
description: "The (optional) port",
|
description: "The (optional) port",
|
||||||
type: u16,
|
type: u16,
|
||||||
},
|
},
|
||||||
userid: {
|
"auth-id": {
|
||||||
type: Authid,
|
type: Authid,
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
@ -57,6 +57,7 @@ pub const REMOTE_PASSWORD_SCHEMA: Schema = StringSchema::new("Password or auth t
|
|||||||
}
|
}
|
||||||
)]
|
)]
|
||||||
#[derive(Serialize,Deserialize)]
|
#[derive(Serialize,Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
/// Remote properties.
|
/// Remote properties.
|
||||||
pub struct Remote {
|
pub struct Remote {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@ -65,7 +66,7 @@ pub struct Remote {
|
|||||||
pub host: String,
|
pub host: String,
|
||||||
#[serde(skip_serializing_if="Option::is_none")]
|
#[serde(skip_serializing_if="Option::is_none")]
|
||||||
pub port: Option<u16>,
|
pub port: Option<u16>,
|
||||||
pub userid: Authid,
|
pub auth_id: Authid,
|
||||||
#[serde(skip_serializing_if="String::is_empty")]
|
#[serde(skip_serializing_if="String::is_empty")]
|
||||||
#[serde(with = "proxmox::tools::serde::string_as_base64")]
|
#[serde(with = "proxmox::tools::serde::string_as_base64")]
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
@ -89,7 +89,21 @@ struct HardLinkInfo {
|
|||||||
st_ino: u64,
|
st_ino: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// In case we want to collect them or redirect them we can just add this here:
|
/// TODO: make a builder for the create_archive call for fewer parameters and add a method to add a
|
||||||
|
/// logger which does not write to stderr.
|
||||||
|
struct Logger;
|
||||||
|
|
||||||
|
impl std::io::Write for Logger {
|
||||||
|
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||||
|
std::io::stderr().write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
std::io::stderr().flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// And the error case.
|
||||||
struct ErrorReporter;
|
struct ErrorReporter;
|
||||||
|
|
||||||
impl std::io::Write for ErrorReporter {
|
impl std::io::Write for ErrorReporter {
|
||||||
@ -116,6 +130,7 @@ struct Archiver<'a, 'b> {
|
|||||||
device_set: Option<HashSet<u64>>,
|
device_set: Option<HashSet<u64>>,
|
||||||
hardlinks: HashMap<HardLinkInfo, (PathBuf, LinkOffset)>,
|
hardlinks: HashMap<HardLinkInfo, (PathBuf, LinkOffset)>,
|
||||||
errors: ErrorReporter,
|
errors: ErrorReporter,
|
||||||
|
logger: Logger,
|
||||||
file_copy_buffer: Vec<u8>,
|
file_copy_buffer: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -181,6 +196,7 @@ where
|
|||||||
device_set,
|
device_set,
|
||||||
hardlinks: HashMap::new(),
|
hardlinks: HashMap::new(),
|
||||||
errors: ErrorReporter,
|
errors: ErrorReporter,
|
||||||
|
logger: Logger,
|
||||||
file_copy_buffer: vec::undefined(4 * 1024 * 1024),
|
file_copy_buffer: vec::undefined(4 * 1024 * 1024),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -221,7 +237,15 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
let old_patterns_count = self.patterns.len();
|
let old_patterns_count = self.patterns.len();
|
||||||
self.read_pxar_excludes(dir.as_raw_fd())?;
|
self.read_pxar_excludes(dir.as_raw_fd())?;
|
||||||
|
|
||||||
let file_list = self.generate_directory_file_list(&mut dir, is_root)?;
|
let mut file_list = self.generate_directory_file_list(&mut dir, is_root)?;
|
||||||
|
|
||||||
|
if is_root && old_patterns_count > 0 {
|
||||||
|
file_list.push(FileListEntry {
|
||||||
|
name: CString::new(".pxarexclude-cli").unwrap(),
|
||||||
|
path: PathBuf::new(),
|
||||||
|
stat: unsafe { std::mem::zeroed() },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let dir_fd = dir.as_raw_fd();
|
let dir_fd = dir.as_raw_fd();
|
||||||
|
|
||||||
@ -231,7 +255,7 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
let file_name = file_entry.name.to_bytes();
|
let file_name = file_entry.name.to_bytes();
|
||||||
|
|
||||||
if is_root && file_name == b".pxarexclude-cli" {
|
if is_root && file_name == b".pxarexclude-cli" {
|
||||||
self.encode_pxarexclude_cli(encoder, &file_entry.name)?;
|
self.encode_pxarexclude_cli(encoder, &file_entry.name, old_patterns_count)?;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -363,8 +387,9 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
&mut self,
|
&mut self,
|
||||||
encoder: &mut Encoder,
|
encoder: &mut Encoder,
|
||||||
file_name: &CStr,
|
file_name: &CStr,
|
||||||
|
patterns_count: usize,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let content = generate_pxar_excludes_cli(&self.patterns);
|
let content = generate_pxar_excludes_cli(&self.patterns[..patterns_count]);
|
||||||
|
|
||||||
if let Some(ref mut catalog) = self.catalog {
|
if let Some(ref mut catalog) = self.catalog {
|
||||||
catalog.add_file(file_name, content.len() as u64, 0)?;
|
catalog.add_file(file_name, content.len() as u64, 0)?;
|
||||||
@ -388,14 +413,6 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
|
|
||||||
let mut file_list = Vec::new();
|
let mut file_list = Vec::new();
|
||||||
|
|
||||||
if is_root && !self.patterns.is_empty() {
|
|
||||||
file_list.push(FileListEntry {
|
|
||||||
name: CString::new(".pxarexclude-cli").unwrap(),
|
|
||||||
path: PathBuf::new(),
|
|
||||||
stat: unsafe { std::mem::zeroed() },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for file in dir.iter() {
|
for file in dir.iter() {
|
||||||
let file = file?;
|
let file = file?;
|
||||||
|
|
||||||
@ -409,10 +426,6 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if file_name_bytes == b".pxarexclude" {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let os_file_name = OsStr::from_bytes(file_name_bytes);
|
let os_file_name = OsStr::from_bytes(file_name_bytes);
|
||||||
assert_single_path_component(os_file_name)?;
|
assert_single_path_component(os_file_name)?;
|
||||||
let full_path = self.path.join(os_file_name);
|
let full_path = self.path.join(os_file_name);
|
||||||
@ -427,9 +440,10 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
Err(err) => bail!("stat failed on {:?}: {}", full_path, err),
|
Err(err) => bail!("stat failed on {:?}: {}", full_path, err),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let match_path = PathBuf::from("/").join(full_path.clone());
|
||||||
if self
|
if self
|
||||||
.patterns
|
.patterns
|
||||||
.matches(full_path.as_os_str().as_bytes(), Some(stat.st_mode as u32))
|
.matches(match_path.as_os_str().as_bytes(), Some(stat.st_mode as u32))
|
||||||
== Some(MatchType::Exclude)
|
== Some(MatchType::Exclude)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@ -632,6 +646,7 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = if skip_contents {
|
let result = if skip_contents {
|
||||||
|
writeln!(self.logger, "skipping mount point: {:?}", self.path)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
self.archive_dir_contents(&mut encoder, dir, false)
|
self.archive_dir_contents(&mut encoder, dir, false)
|
||||||
@ -657,7 +672,12 @@ impl<'a, 'b> Archiver<'a, 'b> {
|
|||||||
let mut remaining = file_size;
|
let mut remaining = file_size;
|
||||||
let mut out = encoder.create_file(metadata, file_name, file_size)?;
|
let mut out = encoder.create_file(metadata, file_name, file_size)?;
|
||||||
while remaining != 0 {
|
while remaining != 0 {
|
||||||
let mut got = file.read(&mut self.file_copy_buffer[..])?;
|
let mut got = match file.read(&mut self.file_copy_buffer[..]) {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(got) => got,
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||||
|
Err(err) => bail!(err),
|
||||||
|
};
|
||||||
if got as u64 > remaining {
|
if got as u64 > remaining {
|
||||||
self.report_file_grew_while_reading()?;
|
self.report_file_grew_while_reading()?;
|
||||||
got = remaining as usize;
|
got = remaining as usize;
|
||||||
|
@ -4,14 +4,18 @@ use serde_json::json;
|
|||||||
use handlebars::{Handlebars, Helper, Context, RenderError, RenderContext, Output, HelperResult};
|
use handlebars::{Handlebars, Helper, Context, RenderError, RenderContext, Output, HelperResult};
|
||||||
|
|
||||||
use proxmox::tools::email::sendmail;
|
use proxmox::tools::email::sendmail;
|
||||||
|
use proxmox::api::schema::parse_property_string;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
config::datastore::DataStoreConfig,
|
||||||
config::verify::VerificationJobConfig,
|
config::verify::VerificationJobConfig,
|
||||||
config::sync::SyncJobConfig,
|
config::sync::SyncJobConfig,
|
||||||
api2::types::{
|
api2::types::{
|
||||||
APTUpdateInfo,
|
APTUpdateInfo,
|
||||||
GarbageCollectionStatus,
|
GarbageCollectionStatus,
|
||||||
Userid,
|
Userid,
|
||||||
|
Notify,
|
||||||
|
DatastoreNotify,
|
||||||
},
|
},
|
||||||
tools::format::HumanByte,
|
tools::format::HumanByte,
|
||||||
};
|
};
|
||||||
@ -77,7 +81,7 @@ const VERIFY_ERR_TEMPLATE: &str = r###"
|
|||||||
Job ID: {{job.id}}
|
Job ID: {{job.id}}
|
||||||
Datastore: {{job.store}}
|
Datastore: {{job.store}}
|
||||||
|
|
||||||
Verification failed on these snapshots:
|
Verification failed on these snapshots/groups:
|
||||||
|
|
||||||
{{#each errors}}
|
{{#each errors}}
|
||||||
{{this~}}
|
{{this~}}
|
||||||
@ -188,11 +192,21 @@ fn send_job_status_mail(
|
|||||||
|
|
||||||
pub fn send_gc_status(
|
pub fn send_gc_status(
|
||||||
email: &str,
|
email: &str,
|
||||||
|
notify: DatastoreNotify,
|
||||||
datastore: &str,
|
datastore: &str,
|
||||||
status: &GarbageCollectionStatus,
|
status: &GarbageCollectionStatus,
|
||||||
result: &Result<(), Error>,
|
result: &Result<(), Error>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
|
||||||
|
match notify.gc {
|
||||||
|
None => { /* send notifications by default */ },
|
||||||
|
Some(notify) => {
|
||||||
|
if notify == Notify::Never || (result.is_ok() && notify == Notify::Error) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let (fqdn, port) = get_server_url();
|
let (fqdn, port) = get_server_url();
|
||||||
let mut data = json!({
|
let mut data = json!({
|
||||||
"datastore": datastore,
|
"datastore": datastore,
|
||||||
@ -237,6 +251,7 @@ pub fn send_gc_status(
|
|||||||
|
|
||||||
pub fn send_verify_status(
|
pub fn send_verify_status(
|
||||||
email: &str,
|
email: &str,
|
||||||
|
notify: DatastoreNotify,
|
||||||
job: VerificationJobConfig,
|
job: VerificationJobConfig,
|
||||||
result: &Result<Vec<String>, Error>,
|
result: &Result<Vec<String>, Error>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
@ -248,8 +263,11 @@ pub fn send_verify_status(
|
|||||||
"port": port,
|
"port": port,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let mut result_is_ok = false;
|
||||||
|
|
||||||
let text = match result {
|
let text = match result {
|
||||||
Ok(errors) if errors.is_empty() => {
|
Ok(errors) if errors.is_empty() => {
|
||||||
|
result_is_ok = true;
|
||||||
HANDLEBARS.render("verify_ok_template", &data)?
|
HANDLEBARS.render("verify_ok_template", &data)?
|
||||||
}
|
}
|
||||||
Ok(errors) => {
|
Ok(errors) => {
|
||||||
@ -262,6 +280,15 @@ pub fn send_verify_status(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
match notify.verify {
|
||||||
|
None => { /* send notifications by default */ },
|
||||||
|
Some(notify) => {
|
||||||
|
if notify == Notify::Never || (result_is_ok && notify == Notify::Error) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let subject = match result {
|
let subject = match result {
|
||||||
Ok(errors) if errors.is_empty() => format!(
|
Ok(errors) if errors.is_empty() => format!(
|
||||||
"Verify Datastore '{}' successful",
|
"Verify Datastore '{}' successful",
|
||||||
@ -280,10 +307,20 @@ pub fn send_verify_status(
|
|||||||
|
|
||||||
pub fn send_sync_status(
|
pub fn send_sync_status(
|
||||||
email: &str,
|
email: &str,
|
||||||
|
notify: DatastoreNotify,
|
||||||
job: &SyncJobConfig,
|
job: &SyncJobConfig,
|
||||||
result: &Result<(), Error>,
|
result: &Result<(), Error>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
|
||||||
|
match notify.sync {
|
||||||
|
None => { /* send notifications by default */ },
|
||||||
|
Some(notify) => {
|
||||||
|
if notify == Notify::Never || (result.is_ok() && notify == Notify::Error) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let (fqdn, port) = get_server_url();
|
let (fqdn, port) = get_server_url();
|
||||||
let mut data = json!({
|
let mut data = json!({
|
||||||
"job": job,
|
"job": job,
|
||||||
@ -360,16 +397,10 @@ pub fn send_updates_available(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Lookup users email address
|
/// Lookup users email address
|
||||||
///
|
fn lookup_user_email(userid: &Userid) -> Option<String> {
|
||||||
/// For "backup@pam", this returns the address from "root@pam".
|
|
||||||
pub fn lookup_user_email(userid: &Userid) -> Option<String> {
|
|
||||||
|
|
||||||
use crate::config::user::{self, User};
|
use crate::config::user::{self, User};
|
||||||
|
|
||||||
if userid == Userid::backup_userid() {
|
|
||||||
return lookup_user_email(Userid::root_userid());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(user_config) = user::cached_config() {
|
if let Ok(user_config) = user::cached_config() {
|
||||||
if let Ok(user) = user_config.lookup::<User>("user", userid.as_str()) {
|
if let Ok(user) = user_config.lookup::<User>("user", userid.as_str()) {
|
||||||
return user.email.clone();
|
return user.email.clone();
|
||||||
@ -379,6 +410,41 @@ pub fn lookup_user_email(userid: &Userid) -> Option<String> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Lookup Datastore notify settings
|
||||||
|
pub fn lookup_datastore_notify_settings(
|
||||||
|
store: &str,
|
||||||
|
) -> (Option<String>, DatastoreNotify) {
|
||||||
|
|
||||||
|
let mut email = None;
|
||||||
|
|
||||||
|
let notify = DatastoreNotify { gc: None, verify: None, sync: None };
|
||||||
|
|
||||||
|
let (config, _digest) = match crate::config::datastore::config() {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => return (email, notify),
|
||||||
|
};
|
||||||
|
|
||||||
|
let config: DataStoreConfig = match config.lookup("datastore", store) {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => return (email, notify),
|
||||||
|
};
|
||||||
|
|
||||||
|
email = match config.notify_user {
|
||||||
|
Some(ref userid) => lookup_user_email(userid),
|
||||||
|
None => lookup_user_email(Userid::root_userid()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let notify_str = config.notify.unwrap_or(String::new());
|
||||||
|
|
||||||
|
if let Ok(value) = parse_property_string(¬ify_str, &DatastoreNotify::API_SCHEMA) {
|
||||||
|
if let Ok(notify) = serde_json::from_value(value) {
|
||||||
|
return (email, notify);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(email, notify)
|
||||||
|
}
|
||||||
|
|
||||||
// Handlerbar helper functions
|
// Handlerbar helper functions
|
||||||
|
|
||||||
fn handlebars_humam_bytes_helper(
|
fn handlebars_humam_bytes_helper(
|
||||||
|
@ -17,10 +17,10 @@ pub fn do_garbage_collection_job(
|
|||||||
to_stdout: bool,
|
to_stdout: bool,
|
||||||
) -> Result<String, Error> {
|
) -> Result<String, Error> {
|
||||||
|
|
||||||
let email = crate::server::lookup_user_email(auth_id.user());
|
|
||||||
|
|
||||||
let store = datastore.name().to_string();
|
let store = datastore.name().to_string();
|
||||||
|
|
||||||
|
let (email, notify) = crate::server::lookup_datastore_notify_settings(&store);
|
||||||
|
|
||||||
let worker_type = job.jobtype().to_string();
|
let worker_type = job.jobtype().to_string();
|
||||||
let upid_str = WorkerTask::new_thread(
|
let upid_str = WorkerTask::new_thread(
|
||||||
&worker_type,
|
&worker_type,
|
||||||
@ -50,7 +50,7 @@ pub fn do_garbage_collection_job(
|
|||||||
|
|
||||||
if let Some(email) = email {
|
if let Some(email) = email {
|
||||||
let gc_status = datastore.last_gc_status();
|
let gc_status = datastore.last_gc_status();
|
||||||
if let Err(err) = crate::server::send_gc_status(&email, &store, &gc_status, &result) {
|
if let Err(err) = crate::server::send_gc_status(&email, notify, &store, &gc_status, &result) {
|
||||||
eprintln!("send gc notification failed: {}", err);
|
eprintln!("send gc notification failed: {}", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,7 @@ fn files() -> Vec<&'static str> {
|
|||||||
fn commands() -> Vec<(&'static str, Vec<&'static str>)> {
|
fn commands() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||||
vec![
|
vec![
|
||||||
// ("<command>", vec![<arg [, arg]>])
|
// ("<command>", vec![<arg [, arg]>])
|
||||||
|
("proxmox-backup-manager", vec!["versions", "--verbose"]),
|
||||||
("df", vec!["-h"]),
|
("df", vec!["-h"]),
|
||||||
("lsblk", vec!["--ascii"]),
|
("lsblk", vec!["--ascii"]),
|
||||||
("zpool", vec!["status"]),
|
("zpool", vec!["status"]),
|
||||||
@ -54,10 +55,10 @@ pub fn generate_report() -> String {
|
|||||||
.map(|file_name| {
|
.map(|file_name| {
|
||||||
let content = match file_read_optional_string(Path::new(file_name)) {
|
let content = match file_read_optional_string(Path::new(file_name)) {
|
||||||
Ok(Some(content)) => content,
|
Ok(Some(content)) => content,
|
||||||
Ok(None) => String::from("# file does not exists"),
|
Ok(None) => String::from("# file does not exist"),
|
||||||
Err(err) => err.to_string(),
|
Err(err) => err.to_string(),
|
||||||
};
|
};
|
||||||
format!("# cat '{}'\n{}", file_name, content)
|
format!("$ cat '{}'\n{}", file_name, content)
|
||||||
})
|
})
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join("\n\n");
|
.join("\n\n");
|
||||||
@ -73,14 +74,14 @@ pub fn generate_report() -> String {
|
|||||||
Ok(output) => String::from_utf8_lossy(&output.stdout).to_string(),
|
Ok(output) => String::from_utf8_lossy(&output.stdout).to_string(),
|
||||||
Err(err) => err.to_string(),
|
Err(err) => err.to_string(),
|
||||||
};
|
};
|
||||||
format!("# `{} {}`\n{}", command, args.join(" "), output)
|
format!("$ `{} {}`\n{}", command, args.join(" "), output)
|
||||||
})
|
})
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join("\n\n");
|
.join("\n\n");
|
||||||
|
|
||||||
let function_outputs = function_calls()
|
let function_outputs = function_calls()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(desc, function)| format!("# {}\n{}", desc, function()))
|
.map(|(desc, function)| format!("$ {}\n{}", desc, function()))
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join("\n\n");
|
.join("\n\n");
|
||||||
|
|
||||||
|
@ -164,6 +164,15 @@ fn log_response(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pub fn auth_logger() -> Result<FileLogger, Error> {
|
||||||
|
let logger_options = tools::FileLogOptions {
|
||||||
|
append: true,
|
||||||
|
prefix_time: true,
|
||||||
|
owned_by_backup: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
FileLogger::new(crate::buildcfg::API_AUTH_LOG_FN, logger_options)
|
||||||
|
}
|
||||||
|
|
||||||
fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
|
fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
@ -614,6 +623,10 @@ fn check_auth(
|
|||||||
.ok_or_else(|| format_err!("failed to split API token header"))?;
|
.ok_or_else(|| format_err!("failed to split API token header"))?;
|
||||||
let tokenid: Authid = tokenid.parse()?;
|
let tokenid: Authid = tokenid.parse()?;
|
||||||
|
|
||||||
|
if !user_info.is_active_auth_id(&tokenid) {
|
||||||
|
bail!("user account or token disabled or expired.");
|
||||||
|
}
|
||||||
|
|
||||||
let tokensecret = parts.next()
|
let tokensecret = parts.next()
|
||||||
.ok_or_else(|| format_err!("failed to split API token header"))?;
|
.ok_or_else(|| format_err!("failed to split API token header"))?;
|
||||||
let tokensecret = percent_decode_str(tokensecret)
|
let tokensecret = percent_decode_str(tokensecret)
|
||||||
@ -687,6 +700,10 @@ async fn handle_request(
|
|||||||
match auth_result {
|
match auth_result {
|
||||||
Ok(authid) => rpcenv.set_auth_id(Some(authid.to_string())),
|
Ok(authid) => rpcenv.set_auth_id(Some(authid.to_string())),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
let peer = peer.ip();
|
||||||
|
auth_logger()?
|
||||||
|
.log(format!("authentication failure; rhost={} msg={}", peer, err));
|
||||||
|
|
||||||
// always delay unauthorized calls by 3 seconds (from start of request)
|
// always delay unauthorized calls by 3 seconds (from start of request)
|
||||||
let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
|
let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
|
||||||
tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
|
tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
|
||||||
|
@ -48,13 +48,15 @@ pub fn do_verification_job(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let email = crate::server::lookup_user_email(auth_id.user());
|
let (email, notify) = crate::server::lookup_datastore_notify_settings(&verification_job.store);
|
||||||
|
|
||||||
let job_id = job.jobname().to_string();
|
let job_id = format!("{}:{}",
|
||||||
|
&verification_job.store,
|
||||||
|
job.jobname());
|
||||||
let worker_type = job.jobtype().to_string();
|
let worker_type = job.jobtype().to_string();
|
||||||
let upid_str = WorkerTask::new_thread(
|
let upid_str = WorkerTask::new_thread(
|
||||||
&worker_type,
|
&worker_type,
|
||||||
Some(job.jobname().to_string()),
|
Some(job_id.clone()),
|
||||||
auth_id.clone(),
|
auth_id.clone(),
|
||||||
false,
|
false,
|
||||||
move |worker| {
|
move |worker| {
|
||||||
@ -67,8 +69,15 @@ pub fn do_verification_job(
|
|||||||
|
|
||||||
let result = verify_all_backups(datastore, worker.clone(), worker.upid(), None, Some(&filter));
|
let result = verify_all_backups(datastore, worker.clone(), worker.upid(), None, Some(&filter));
|
||||||
let job_result = match result {
|
let job_result = match result {
|
||||||
Ok(ref errors) if errors.is_empty() => Ok(()),
|
Ok(ref failed_dirs) if failed_dirs.is_empty() => Ok(()),
|
||||||
Ok(_) => Err(format_err!("verification failed - please check the log for details")),
|
Ok(ref failed_dirs) => {
|
||||||
|
worker.log("Failed to verify the following snapshots/groups:");
|
||||||
|
for dir in failed_dirs {
|
||||||
|
worker.log(format!("\t{}", dir));
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(format_err!("verification failed - please check the log for details"))
|
||||||
|
},
|
||||||
Err(_) => Err(format_err!("verification failed - job aborted")),
|
Err(_) => Err(format_err!("verification failed - job aborted")),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -84,7 +93,7 @@ pub fn do_verification_job(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(email) = email {
|
if let Some(email) = email {
|
||||||
if let Err(err) = crate::server::send_verify_status(&email, verification_job, &result) {
|
if let Err(err) = crate::server::send_verify_status(&email, notify, verification_job, &result) {
|
||||||
eprintln!("send verify notification failed: {}", err);
|
eprintln!("send verify notification failed: {}", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -55,7 +55,9 @@ pub async fn worker_is_active(upid: &UPID) -> Result<bool, Error> {
|
|||||||
let sock = server::ctrl_sock_from_pid(upid.pid);
|
let sock = server::ctrl_sock_from_pid(upid.pid);
|
||||||
let cmd = json!({
|
let cmd = json!({
|
||||||
"command": "worker-task-status",
|
"command": "worker-task-status",
|
||||||
"upid": upid.to_string(),
|
"args": {
|
||||||
|
"upid": upid.to_string(),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
let status = super::send_command(sock, cmd).await?;
|
let status = super::send_command(sock, cmd).await?;
|
||||||
|
|
||||||
@ -127,7 +129,9 @@ pub async fn abort_worker(upid: UPID) -> Result<(), Error> {
|
|||||||
let sock = server::ctrl_sock_from_pid(upid.pid);
|
let sock = server::ctrl_sock_from_pid(upid.pid);
|
||||||
let cmd = json!({
|
let cmd = json!({
|
||||||
"command": "worker-task-abort",
|
"command": "worker-task-abort",
|
||||||
"upid": upid.to_string(),
|
"args": {
|
||||||
|
"upid": upid.to_string(),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
super::send_command(sock, cmd).map_ok(|_| ()).await
|
super::send_command(sock, cmd).map_ok(|_| ()).await
|
||||||
}
|
}
|
||||||
|
119
src/tools.rs
@ -5,16 +5,14 @@ use std::any::Any;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::hash::BuildHasher;
|
use std::hash::BuildHasher;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{self, BufRead, ErrorKind, Read, Seek, SeekFrom};
|
use std::io::{self, BufRead, Read, Seek, SeekFrom};
|
||||||
use std::os::unix::io::RawFd;
|
use std::os::unix::io::RawFd;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use anyhow::{bail, format_err, Error};
|
use anyhow::{bail, format_err, Error};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use openssl::hash::{hash, DigestBytes, MessageDigest};
|
use openssl::hash::{hash, DigestBytes, MessageDigest};
|
||||||
use percent_encoding::AsciiSet;
|
use percent_encoding::{utf8_percent_encode, AsciiSet};
|
||||||
|
|
||||||
use proxmox::tools::vec;
|
|
||||||
|
|
||||||
pub use proxmox::tools::fd::Fd;
|
pub use proxmox::tools::fd::Fd;
|
||||||
|
|
||||||
@ -25,45 +23,43 @@ pub mod borrow;
|
|||||||
pub mod cert;
|
pub mod cert;
|
||||||
pub mod daemon;
|
pub mod daemon;
|
||||||
pub mod disks;
|
pub mod disks;
|
||||||
pub mod fs;
|
|
||||||
pub mod format;
|
pub mod format;
|
||||||
pub mod lru_cache;
|
pub mod fs;
|
||||||
pub mod runtime;
|
pub mod fuse_loop;
|
||||||
pub mod ticket;
|
pub mod http;
|
||||||
pub mod statistics;
|
|
||||||
pub mod systemd;
|
|
||||||
pub mod nom;
|
|
||||||
pub mod logrotate;
|
pub mod logrotate;
|
||||||
pub mod loopdev;
|
pub mod loopdev;
|
||||||
pub mod fuse_loop;
|
pub mod lru_cache;
|
||||||
|
pub mod nom;
|
||||||
|
pub mod runtime;
|
||||||
pub mod socket;
|
pub mod socket;
|
||||||
|
pub mod statistics;
|
||||||
pub mod subscription;
|
pub mod subscription;
|
||||||
|
pub mod systemd;
|
||||||
|
pub mod ticket;
|
||||||
|
pub mod xattr;
|
||||||
pub mod zip;
|
pub mod zip;
|
||||||
pub mod http;
|
|
||||||
|
|
||||||
mod parallel_handler;
|
pub mod parallel_handler;
|
||||||
pub use parallel_handler::*;
|
pub use parallel_handler::ParallelHandler;
|
||||||
|
|
||||||
mod wrapped_reader_stream;
|
mod wrapped_reader_stream;
|
||||||
pub use wrapped_reader_stream::*;
|
pub use wrapped_reader_stream::{AsyncReaderStream, StdChannelStream, WrappedReaderStream};
|
||||||
|
|
||||||
mod async_channel_writer;
|
mod async_channel_writer;
|
||||||
pub use async_channel_writer::*;
|
pub use async_channel_writer::AsyncChannelWriter;
|
||||||
|
|
||||||
|
|
||||||
mod std_channel_writer;
|
mod std_channel_writer;
|
||||||
pub use std_channel_writer::*;
|
pub use std_channel_writer::StdChannelWriter;
|
||||||
|
|
||||||
pub mod xattr;
|
|
||||||
|
|
||||||
mod process_locker;
|
mod process_locker;
|
||||||
pub use process_locker::*;
|
pub use process_locker::{ProcessLocker, ProcessLockExclusiveGuard, ProcessLockSharedGuard};
|
||||||
|
|
||||||
mod file_logger;
|
mod file_logger;
|
||||||
pub use file_logger::*;
|
pub use file_logger::{FileLogger, FileLogOptions};
|
||||||
|
|
||||||
mod broadcast_future;
|
mod broadcast_future;
|
||||||
pub use broadcast_future::*;
|
pub use broadcast_future::{BroadcastData, BroadcastFuture};
|
||||||
|
|
||||||
/// The `BufferedRead` trait provides a single function
|
/// The `BufferedRead` trait provides a single function
|
||||||
/// `buffered_read`. It returns a reference to an internal buffer. The
|
/// `buffered_read`. It returns a reference to an internal buffer. The
|
||||||
@ -75,76 +71,6 @@ pub trait BufferedRead {
|
|||||||
fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>;
|
fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Split a file into equal sized chunks. The last chunk may be
|
|
||||||
/// smaller. Note: We cannot implement an `Iterator`, because iterators
|
|
||||||
/// cannot return a borrowed buffer ref (we want zero-copy)
|
|
||||||
pub fn file_chunker<C, R>(mut file: R, chunk_size: usize, mut chunk_cb: C) -> Result<(), Error>
|
|
||||||
where
|
|
||||||
C: FnMut(usize, &[u8]) -> Result<bool, Error>,
|
|
||||||
R: Read,
|
|
||||||
{
|
|
||||||
const READ_BUFFER_SIZE: usize = 4 * 1024 * 1024; // 4M
|
|
||||||
|
|
||||||
if chunk_size > READ_BUFFER_SIZE {
|
|
||||||
bail!("chunk size too large!");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut buf = vec::undefined(READ_BUFFER_SIZE);
|
|
||||||
|
|
||||||
let mut pos = 0;
|
|
||||||
let mut file_pos = 0;
|
|
||||||
loop {
|
|
||||||
let mut eof = false;
|
|
||||||
let mut tmp = &mut buf[..];
|
|
||||||
// try to read large portions, at least chunk_size
|
|
||||||
while pos < chunk_size {
|
|
||||||
match file.read(tmp) {
|
|
||||||
Ok(0) => {
|
|
||||||
eof = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Ok(n) => {
|
|
||||||
pos += n;
|
|
||||||
if pos > chunk_size {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
tmp = &mut tmp[n..];
|
|
||||||
}
|
|
||||||
Err(ref e) if e.kind() == ErrorKind::Interrupted => { /* try again */ }
|
|
||||||
Err(e) => bail!("read chunk failed - {}", e.to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut start = 0;
|
|
||||||
while start + chunk_size <= pos {
|
|
||||||
if !(chunk_cb)(file_pos, &buf[start..start + chunk_size])? {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
file_pos += chunk_size;
|
|
||||||
start += chunk_size;
|
|
||||||
}
|
|
||||||
if eof {
|
|
||||||
if start < pos {
|
|
||||||
(chunk_cb)(file_pos, &buf[start..pos])?;
|
|
||||||
//file_pos += pos - start;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
let rest = pos - start;
|
|
||||||
if rest > 0 {
|
|
||||||
let ptr = buf.as_mut_ptr();
|
|
||||||
unsafe {
|
|
||||||
std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest);
|
|
||||||
}
|
|
||||||
pos = rest;
|
|
||||||
} else {
|
|
||||||
pos = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn json_object_to_query(data: Value) -> Result<String, Error> {
|
pub fn json_object_to_query(data: Value) -> Result<String, Error> {
|
||||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||||
|
|
||||||
@ -363,6 +289,11 @@ pub fn extract_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// percent encode a url component
|
||||||
|
pub fn percent_encode_component(comp: &str) -> String {
|
||||||
|
utf8_percent_encode(comp, percent_encoding::NON_ALPHANUMERIC).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn join(data: &Vec<String>, sep: char) -> String {
|
pub fn join(data: &Vec<String>, sep: char) -> String {
|
||||||
let mut list = String::new();
|
let mut list = String::new();
|
||||||
|
|
||||||
|
@ -128,19 +128,26 @@ fn get_changelog_url(
|
|||||||
None => bail!("incompatible filename, doesn't match regex")
|
None => bail!("incompatible filename, doesn't match regex")
|
||||||
};
|
};
|
||||||
|
|
||||||
return Ok(format!("http://download.proxmox.com/{}/{}_{}.changelog",
|
if component == "pbs-enterprise" {
|
||||||
base, package, version));
|
return Ok(format!("https://enterprise.proxmox.com/{}/{}_{}.changelog",
|
||||||
|
base, package, version));
|
||||||
|
} else {
|
||||||
|
return Ok(format!("http://download.proxmox.com/{}/{}_{}.changelog",
|
||||||
|
base, package, version));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bail!("unknown origin ({}) or component ({})", origin, component)
|
bail!("unknown origin ({}) or component ({})", origin, component)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FilterData<'a> {
|
pub struct FilterData<'a> {
|
||||||
// this is version info returned by APT
|
/// package name
|
||||||
|
pub package: &'a str,
|
||||||
|
/// this is version info returned by APT
|
||||||
pub installed_version: Option<&'a str>,
|
pub installed_version: Option<&'a str>,
|
||||||
pub candidate_version: &'a str,
|
pub candidate_version: &'a str,
|
||||||
|
|
||||||
// this is the version info the filter is supposed to check
|
/// this is the version info the filter is supposed to check
|
||||||
pub active_version: &'a str,
|
pub active_version: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -270,6 +277,7 @@ where
|
|||||||
let mut long_desc = "".to_owned();
|
let mut long_desc = "".to_owned();
|
||||||
|
|
||||||
let fd = FilterData {
|
let fd = FilterData {
|
||||||
|
package: package.as_str(),
|
||||||
installed_version: current_version.as_deref(),
|
installed_version: current_version.as_deref(),
|
||||||
candidate_version: &candidate_version,
|
candidate_version: &candidate_version,
|
||||||
active_version: &version,
|
active_version: &version,
|
||||||
@ -353,6 +361,7 @@ where
|
|||||||
},
|
},
|
||||||
priority: priority_res,
|
priority: priority_res,
|
||||||
section: section_res,
|
section: section_res,
|
||||||
|
extra_info: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,18 +16,18 @@ pub enum EitherStream<L, R> {
|
|||||||
Right(R),
|
Right(R),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<L: AsyncRead, R: AsyncRead> AsyncRead for EitherStream<L, R> {
|
impl<L: AsyncRead + Unpin, R: AsyncRead + Unpin> AsyncRead for EitherStream<L, R> {
|
||||||
fn poll_read(
|
fn poll_read(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context,
|
cx: &mut Context,
|
||||||
buf: &mut [u8],
|
buf: &mut [u8],
|
||||||
) -> Poll<Result<usize, io::Error>> {
|
) -> Poll<Result<usize, io::Error>> {
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_read(cx, buf)
|
Pin::new(s).poll_read(cx, buf)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_read(cx, buf)
|
Pin::new(s).poll_read(cx, buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -47,51 +47,51 @@ impl<L: AsyncRead, R: AsyncRead> AsyncRead for EitherStream<L, R> {
|
|||||||
where
|
where
|
||||||
B: bytes::BufMut,
|
B: bytes::BufMut,
|
||||||
{
|
{
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_read_buf(cx, buf)
|
Pin::new(s).poll_read_buf(cx, buf)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_read_buf(cx, buf)
|
Pin::new(s).poll_read_buf(cx, buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<L: AsyncWrite, R: AsyncWrite> AsyncWrite for EitherStream<L, R> {
|
impl<L: AsyncWrite + Unpin, R: AsyncWrite + Unpin> AsyncWrite for EitherStream<L, R> {
|
||||||
fn poll_write(
|
fn poll_write(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context,
|
cx: &mut Context,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
) -> Poll<Result<usize, io::Error>> {
|
) -> Poll<Result<usize, io::Error>> {
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_write(cx, buf)
|
Pin::new(s).poll_write(cx, buf)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_write(cx, buf)
|
Pin::new(s).poll_write(cx, buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_flush(cx)
|
Pin::new(s).poll_flush(cx)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_flush(cx)
|
Pin::new(s).poll_flush(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_shutdown(cx)
|
Pin::new(s).poll_shutdown(cx)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_shutdown(cx)
|
Pin::new(s).poll_shutdown(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -104,12 +104,12 @@ impl<L: AsyncWrite, R: AsyncWrite> AsyncWrite for EitherStream<L, R> {
|
|||||||
where
|
where
|
||||||
B: bytes::Buf,
|
B: bytes::Buf,
|
||||||
{
|
{
|
||||||
match unsafe { self.get_unchecked_mut() } {
|
match self.get_mut() {
|
||||||
EitherStream::Left(ref mut s) => {
|
EitherStream::Left(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_write_buf(cx, buf)
|
Pin::new(s).poll_write_buf(cx, buf)
|
||||||
}
|
}
|
||||||
EitherStream::Right(ref mut s) => {
|
EitherStream::Right(ref mut s) => {
|
||||||
unsafe { Pin::new_unchecked(s) }.poll_write_buf(cx, buf)
|
Pin::new(s).poll_write_buf(cx, buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -180,7 +180,7 @@ pub struct HyperAccept<T>(pub T);
|
|||||||
|
|
||||||
impl<T, I> hyper::server::accept::Accept for HyperAccept<T>
|
impl<T, I> hyper::server::accept::Accept for HyperAccept<T>
|
||||||
where
|
where
|
||||||
T: TryStream<Ok = I>,
|
T: TryStream<Ok = I> + Unpin,
|
||||||
I: AsyncRead + AsyncWrite,
|
I: AsyncRead + AsyncWrite,
|
||||||
{
|
{
|
||||||
type Conn = I;
|
type Conn = I;
|
||||||
@ -190,7 +190,7 @@ where
|
|||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context,
|
cx: &mut Context,
|
||||||
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
|
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
|
||||||
let this = unsafe { self.map_unchecked_mut(|this| &mut this.0) };
|
let this = Pin::new(&mut self.get_mut().0);
|
||||||
this.try_poll_next(cx)
|
this.try_poll_next(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|