Compare commits

..

656 Commits

Author SHA1 Message Date
Thomas Lamprecht
5a2e6ccf77 api: tape restore: avoid throwing away ns mapping, use target_store instead
avoid assembling a hash mapping of namespaces only to not use it,
i.e., throw it away then anyway

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 16:59:57 +02:00
Thomas Lamprecht
f31e32a006 api: tape restore: some code cleanups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 16:55:13 +02:00
Thomas Lamprecht
2ad96e1635 api: tape restore: split/rework datastore/namespace map implementation
The split out helpers will (partially) be used in later patches for
call sites where we only need parts of the info assembled here.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 16:47:27 +02:00
Thomas Lamprecht
7bc2e240b1 api: tape restore: use HumanByte for friendlier total/throughput reporting
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 10:45:13 +02:00
Thomas Lamprecht
20a04cf07c api: tape restore: refactor some code parts shorter
not wanting to play code golf here, but bloat in code makes it often
also harder to read, so try to reduce some of that without making it
to terse.

No semantic change intended.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 10:42:47 +02:00
Thomas Lamprecht
a40ffb92ac code formatting fixups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 10:38:33 +02:00
Thomas Lamprecht
e2aeff40eb tape: use inline variable in formats for code reduction
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 10:38:33 +02:00
Thomas Lamprecht
d20137e5a9 tree wide: typo fixes through codespell
Most, not all, found and fixes using `codespell -wci3 -L crate`

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-05 10:34:10 +02:00
Thomas Lamprecht
6a35698796 bump version to 2.2.3-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 16:30:20 +02:00
Thomas Lamprecht
2981cdd4c0 api: datastore status: use cheaper any_privs_below over can_access_any_namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:34:42 +02:00
Thomas Lamprecht
8c9c6c0755 api: list datastore: avoid iterating over NS for priv check, use AclTree
Make the assumption that if a user has any privilege that would make
an NS and (parts) of its content visible they also should be able to
know about the datastore and very basic errors on lookup (path
existence and maintenance mode) even if that NS doesn't even exists
(yet), as they could, e.g., make or view a backup and find out
anyway.

This avoids iterating over parts of the whole datastore folder tree
on disk, doing a priv check on each, swapping IO to virtual in memory
checks on info we got available already anyway, is always a good idea
after all

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:34:42 +02:00
Thomas Lamprecht
2c69b69108 config: cached user info: expose new any_privs_below
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:29:45 +02:00
Thomas Lamprecht
0bed1f2956 config: any_priv_below: plural name & switch to slice of &str for path
s/any_priv_below/any_privs_below/ for consistency and switch from a
single &str for the path param to the slice-ref string variant, as
that allows to use it more often without allocation.

Also allow passing the whole path as single &str element in the slice
by splitting each component on '/' like we do in other parts
nowadays. Note though that we need to omit the leading slash then.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:29:45 +02:00
Thomas Lamprecht
4ef6b7d1f0 config: s/propagating/only_propagated/ and style nits
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:29:45 +02:00
Stefan Sterz
87d8aa4278 pbs-config: acl-tree: add any_priv_below
`any_priv_below()` checks if a given AuthId has any given privileges
on a sub-tree of the AclTree. to do so, it first takes into account
propagating privileges on the path itself and then uses a depth-first
search to check if any of the provided privileges are set on any
node of the sub-tree pointed to by the path.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:29:45 +02:00
Thomas Lamprecht
51d900d187 datastore: swap ConfigVersionCache with digest for change detection
We got the digest available anyway, and it's only 16 bytes more to
save (compared to last_generation and the recently removed last_time,
both being 64 bit = 8 bytes each)

Side benefit, we detect config changes made manually (e.g., `vim
datacenter.cfg`) immediately.

Note that we could restructure the maintenance mode checking to only
be done after checking if there's a cached datastore, in which case
using the generation could make sense to decide if we need to re-load
it again before blindly loading the config anyway. As that's not only
some (not exactly hard but not really trivial like a typo fix either)
restructuring work but also means we'd lose the "detect manual
changes" again I'd rather keep using the digest.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-04 15:26:50 +02:00
Thomas Lamprecht
519ca9d010 datastore: make unsafe fn public again, useful for example/test
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 17:10:17 +02:00
Thomas Lamprecht
615a50c108 datastore: make unsafe functions only visible in their own crate
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 13:42:42 +02:00
Thomas Lamprecht
f418f4e48b api: list datastores: avoid unsafe datastore open
to avoid the problematic open fresh datastore with fresh chunkstore
with, and that's the actual problematic part, fresh process locker.
As the latter uses posix record locks which are pretty dangreous as
they operate on a path level (not FD level) and thus closing any file
opened (even if it wasn't opened for locking at all) drops all active
locks on the same file on completely unrelated file descriptors -.-

Also, no operation wasn't exactly correct for this thing in the first
place, but we cannot use Operation::Lookup either, as we're currently
indeed using a rather stupid-simple way and *are* reading.

So until we optimize this to allow querying the AclTree if there's
any priv XYZ below a path, use the Operation::Read.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 13:31:29 +02:00
Thomas Lamprecht
c66fa32c08 datastore: add safety doc comment for unsafe opens
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 10:58:33 +02:00
Thomas Lamprecht
2515ff35c2 datastore: reduce chunk store open visibility and comment pitfalls
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 10:15:41 +02:00
Thomas Lamprecht
33a1ef7aae datastore: rename non-telling map to datastore_cache
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 10:11:09 +02:00
Thomas Lamprecht
9c12e82006 datastore: drop bogus last_update stale-cache mechanism
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 10:04:16 +02:00
Thomas Lamprecht
9f19057036 config: version cache: fix ordering of datastore generation increase
Fixes: 118deb4d (pbs-datastore: use ConfigVersionCache for datastore)
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-03 09:18:09 +02:00
Thomas Lamprecht
c7f7236b88 datastore: more concise comment
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 17:48:08 +02:00
Thomas Lamprecht
fdefe192ac bump version to 2.2.2-3
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 17:38:52 +02:00
Thomas Lamprecht
1ed8698b7e docs: faq: more specific eol date
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 17:38:52 +02:00
Dominik Csapak
0bd9c87010 datastore: lookup: reuse ChunkStore on stale datastore re-open
When re-opening a datastore due to the cached entry being stale
(config change) but also if the last re-open was >60s ago). On
datastore open the chunk store was also re-opened, which in turn
creates a new ProcessLocker, loosing any existing shared lock which
can cause conflicts between long running (24h+) backups  and GC.

To fix this, reuse the existing ChunkStore, and thus  its
ProcessLocker, when creating a up-to-date datastore instance on
lookup, since only the datastore config should be reloaded. This is
fine as the ChunkStore path is not updatable over our API.

This was always a potential issue but got exposed in practice by
commit 118deb4db8e709b02704bc66c0551bfa7e4369ed which introduced the
unconditional "re-open after 60s" mechanism.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
 [ T: reword commit message a bit and reference commit that made the
   issue much more likely ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 17:00:49 +02:00
Thomas Lamprecht
fbfb64a6b2 tree wide: clippy lint fixes
most (not all) where done automatically

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 15:59:55 +02:00
Thomas Lamprecht
c39852abdc client: clippy lints
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 15:57:33 +02:00
Thomas Lamprecht
1ec167ee8c api types: clippy lints
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-02 15:57:07 +02:00
Fabian Grünbichler
11ca834317 update to nix 0.24 / rustyline 9 / proxmox-sys 0.3
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-06-02 14:33:33 +02:00
Fabian Grünbichler
68a6e970d4 bump tokio-util to 0.7
along with the rest of tokio/futures/hyper/openssl being updated - this
is the only one we explicitly depend on that had a non-compatible
version number.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-06-02 09:41:38 +02:00
Thomas Lamprecht
4e851c26a2 bump version to 2.2.2-2
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 17:00:02 +02:00
Thomas Lamprecht
ceb815d295 server: remove jobstate: ignore removal error due to file not found
we want to remove lock and state file anyway, so not found is all
right

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 16:40:09 +02:00
Thomas Lamprecht
14433718fb bump version to 2.2.2-1
same story as last time

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 15:09:43 +02:00
Thomas Lamprecht
3dc8783af7 manager cli: output more info when transforming prune jobs
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 15:09:20 +02:00
Thomas Lamprecht
6d89534929 bump version to 2.2.2-1
re-bump for small fixes discovered before any upload

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 14:34:03 +02:00
Thomas Lamprecht
aa19d5b917 manager cli: output more info when skipping prune tranforms
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 14:31:53 +02:00
Thomas Lamprecht
a8d3f1943b api types: prune keep options: also check weekly in keeps_something
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 14:30:24 +02:00
Thomas Lamprecht
3cf12ffac9 bump version to 2.2.2-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-06-01 13:04:37 +02:00
Fabian Grünbichler
2017a47eec Cargo.toml: add missing patch sections
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-06-01 11:01:23 +02:00
Thomas Lamprecht
21185350fb ui: add prune job worker task description and renderer
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-31 13:11:23 +02:00
Thomas Lamprecht
17b079918e ui: prune & gc: relay activate/deactivate events to sub panels
which allows us also to drop the initial manual load in the init,
which would also trigger if the tab isn't visible.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-31 10:02:12 +02:00
Thomas Lamprecht
fbfc439372 ui: system config: improve bottom margins and scroll behavior
setting scrollable on the parent tab panel makes not much sense and
will always add a scroll bar that can scroll a few pixels, even if
there's enough space.
Rather set it to true (= auto) in the actual panels that hold the
content.

Also set a bottom margin so that users can see the "end" of the panel
at the bottom, otherwise it looked like it had a start and sides, but
no bottom.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-31 07:03:31 +02:00
Thomas Lamprecht
27d3a232d0 ui: prune jobs: avoid duplicate params through nested input panels
input panel collect all form fields below them, so nesting two
input panels needs a bit of special care to avoid that each of the
panels adds the data of the deeper nested ones, resulting in
duplicate parameters that the backend then chokes one.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 15:15:42 +02:00
Thomas Lamprecht
1fa6083bc8 ui: prune & gc: disallow collapse and add bottom margin
the intra-panel margin is still the same (10 + 0 == 7 + 3) but one
can now see the bottom border.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 15:02:08 +02:00
Wolfgang Bumiller
aa32a46171 api: disable setting prune options in datastore.cfg
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 14:48:15 +02:00
Wolfgang Bumiller
6283d7d13a stop executing datastore prune job
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 14:47:57 +02:00
Wolfgang Bumiller
d4dd7ac842 api: don't use PRUNE perms for prune jobs
just stick to MODIFY so we don't need to give the prune jobs
an owner for now

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 14:33:06 +02:00
Wolfgang Bumiller
451da4923b drop unused import
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 14:01:22 +02:00
Thomas Lamprecht
f15e094408 d/postinst: transform prune tasks from datastore cfg to new prune job
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 13:58:45 +02:00
Wolfgang Bumiller
134779664e manager: hidden command to move datastore prune opts into jobs
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Thomas Lamprecht
9ce2f903fb ui: rework prune job view/edit
Fix missing load on initial view, re-use the prune input panel for
editing and avoid using a tab panel for a single tab, rework also
some columns widths and various other small parts-

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 13:58:43 +02:00
Thomas Lamprecht
6802a68356 ui: re-integrate prune into prune & GC panel
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
c69884a459 ui: add ui for prune jobs
similar to verification/sync jobs, the prune settings on the
datastore are deprecated

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
93205cbe92 tests: switch to PruneJobOptions
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
434dd3cc84 client: switch to PruneJobsOptions
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
dba37e212b add prune jobs api
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
db4b8683cf add prune job config
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
5557af0efb api-types: add PruneJobConfig
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Wolfgang Bumiller
8721b42e2f api: add some missing sorted macro calls
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-30 13:58:43 +02:00
Thomas Lamprecht
5408e30ab1 d/postinst: fix upper version for applying sync.cfg remove-vanished default
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-30 13:40:24 +02:00
Thomas Lamprecht
70493f1823 ui: datastore content: better cope with restricted privs on parent namespaces
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 16:09:48 +02:00
Thomas Lamprecht
069720f510 ui: datastore content: only mask the treeview, not the top bar
so that an user can try to reload again easily for non-persistent
errors

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 16:06:21 +02:00
Thomas Lamprecht
a93c96823c ui: datastore content: avoid duplicate masking on load error
we already handle that manually in the onLoad and want to further
extend that, so drop the more generic monStoreError

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 16:02:44 +02:00
Thomas Lamprecht
2393943fbb api: namespace list: fix restrictive priv checking
This endpoint only lists all accessible namespace, and one doesn't
necessarily needs to have permissions on the parent itself just to
have OK ACLs on deeper down NS.

So, drop the upfront check on parent but explicitly avoid leaking if
a NS exists or not, i.e., only do so if they got access on the parent
NS.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 11:14:01 +02:00
Thomas Lamprecht
49d604aec1 ui: datastore options: avoid breakage if rrd store cannot be queried
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 10:59:42 +02:00
Thomas Lamprecht
246275e203 ui: datastore options: avoid breakage if active-ops cannot be queried
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 10:59:25 +02:00
Thomas Lamprecht
c9fb0f3887 ui: datastore summary: cope with optional gc-stats
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 10:58:38 +02:00
Thomas Lamprecht
84de101272 api: status: include empty entry for stores with ns-only privs
I.e., for those that only got permissions on a sub namespace and
those that onlöy got BACKUP_READ, as both they could just list and
count themselves too after all, so not exactly secret info.

The UI needs some adaptions to cope with gc-stats and usage being
optional, will be done in a next commit.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-27 10:55:48 +02:00
Thomas Lamprecht
de77a20d3d api: move can_access_any_namespace helper to hierarchy
to prepare for reuse

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 13:35:33 +02:00
Thomas Lamprecht
997c96d6a3 datastore status: impl empty-status constructor for item type
we can now use it for the error case and will further use it for the
can access namespace but not datastore case in a future patch

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 13:34:00 +02:00
Thomas Lamprecht
513da8ed10 docs: fix yet another typo
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 13:26:56 +02:00
Thomas Lamprecht
e87e4499fd docs: fix some typos
The s/Namesapce/Namespace/ one was reported in the forum [0] and so I
figured I do a quick scan for others too using codespell.

[0]: https://forum.proxmox.com/threads/109724/post-472744

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 13:08:52 +02:00
Thomas Lamprecht
a19b8c2e24 pbs-config: clippy fixes
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 11:42:13 +02:00
Thomas Lamprecht
b8858d5186 datastore: avoid unsafe transmute, use to_ne_bytes
which is stable since rustc 1.32 but wasn't available in out
toolchain when this was originally written in commit 7bc1d7277

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 11:42:13 +02:00
Thomas Lamprecht
bc001e12e2 datastore: clippy fixes
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-26 11:42:13 +02:00
Fabian Grünbichler
abd8248520 tree-wide: remove DatastoreWithNamespace
instead move the acl_path helper to BackupNamespace, and introduce a new
helper for printing a store+ns when logging/generating error messages.

Suggested-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-26 11:42:10 +02:00
Fabian Grünbichler
974a3e521a api: datastore: cleanup store/ns handling
this should just avoid some clones, no semantic changes intended.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
ea2e91e52f move and unify namespace priv helpers
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
77bd14f68a sync/pull: cleanup priv checks and logging
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
d1fba4de1d include privilege names in check_privs error
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
3e4994a54f api: tape: use check_privs instead of manual lookup
these all contain the path in the error message already, so no (new)
potential for leakage..

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
75b377219d api: backup env: use check_privs
it includes the path, which might be helpful when users are switching to
using namespaces. datastore and namespace lookup happens after, so this
doesn't leak anything.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
c8dc51e41f api: namespace: check privs directly
instead of doing a manual lookup and check - this changes the returned
error slightly since check_privs will include the checked ACL path, but
that is okay here, checks are before we even lookup the namespace/store,
so no chance to leak anything.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
7d0dbaa013 priv checks: use priv_to_priv_names and include path
where appropriate. these should never leak anything sensitive, as we
check privs before checking existence or existence is already known at
that point via other privileges.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
efa62d44d4 api: add new priv to priv name helper
for usage in permission check error messages, to allow easily indicating
which privs are missing.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
210ded9803 priv handling: use DatastoreWithNamespace
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
99e1399729 api: tape: restore: improve permission checks
no redundant store+namespace mapping, and synchronize namespace creation
check with that of manual creation and creation as part of sync.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
0aa5815fb6 verify_job: fix priv check
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
bb5c77fffa api2: reader env: fix priv checks
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
ebfcf75e14 acl: fix handling of sub-components containing '/'
previously with an ACL for the path "/foo/bar" without propagation and a
check for `&["foo", "bar/baz"] this code would return the ACL (roles)
for "/foo/bar" for the path "/foo/bar/baz".

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
83e3000349 sync job: don't require privs on datastore
syncing to a namespace only requires privileges on the namespace (and
potentially its children during execution).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
4a4dd66c26 api: list snapshots: fix log param order
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
b9b2d635fe sync job: fix worker ID parsing
the namespace is optional, but should be captured to allow ACL checks
for unprivileged non-job-owners.

also add FIXME for other job types and workers that (might) need
updating.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-25 17:18:56 +02:00
Fabian Grünbichler
9f8aa8c5e2 debug: recover: allow overriding output-path
including to STDOUT.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Tested-by: Hannes Laimer <h.laimer@proxmox.com>
2022-05-24 11:46:04 +02:00
Fabian Grünbichler
b11693b2f7 debug: move outfile_or_stdout to module for reuse
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Tested-by: Hannes Laimer <h.laimer@proxmox.com>
2022-05-24 11:45:59 +02:00
Fabian Grünbichler
53435bc4d5 debug: recover: allow ignoring missing/corrupt chunks
replacing them with chunks of zero bytes.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Tested-by: Hannes Laimer <h.laimer@proxmox.com>
2022-05-24 11:45:54 +02:00
Dominik Csapak
8bec3ff691 tape/pool_writer: give proper types to 'contains_snapshot'
instead of a string. The underlying catalog implementation has to
care about how this is formatted, not the external caller

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-23 16:20:13 +02:00
Dominik Csapak
789e22d905 proxmox-tape: use correct api call for 'load-media-from-slot'
it's a 'post' api call, not 'put'

reported here:
https://forum.proxmox.com/threads/lto8.109946/
and here:
https://forum.proxmox.com/threads/cant-clear-tape.86454/

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-23 16:14:41 +02:00
Fabian Grünbichler
a1c30e0194 cargo fmt
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-23 16:12:22 +02:00
Fabian Grünbichler
d4c6e68bf0 fix typo
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-23 15:05:38 +02:00
Thomas Lamprecht
e642344f98 ui: datastore content: enable recursive/depth selector for prune all
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 13:35:01 +02:00
Thomas Lamprecht
d4574bb138 ui: prune input: support opt-in recursive/max-depth field
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 13:34:17 +02:00
Thomas Lamprecht
26b40687b3 prune datastore: add depth info to tak log
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 13:32:45 +02:00
Thomas Lamprecht
e3c26aea31 prune datastore: support max-depth and improve priv checks
use the relatively new variant of ListAccessibleBackupGroups to also
allow pruning the groups that one doesn't own but has the respective
privileges on their namespace level.

This was previously handled by the API endpoint itself, which was ok
as long as only one level was looked at.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 13:31:09 +02:00
Thomas Lamprecht
65aba79a9b prune datastore: rework tak log
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 13:23:24 +02:00
Thomas Lamprecht
4b6a653a0f verify filter: improve comment
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:36:51 +02:00
Thomas Lamprecht
3c41d86010 verify all: adhere to NS privs for non-owned groups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:36:06 +02:00
Thomas Lamprecht
93821e87e6 accessible group iter: rename "new" to "new_owned"
to clarify that it's only returning owned backups that way.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:34:06 +02:00
Thomas Lamprecht
f12f408e91 api: datastore status: adhere to NS privs for non-owner
Not only check all owned backup groups, but also all that an auth_id
has DATASTORE_AUDIT or DATASTORE_READ on the whole namespace.

best viewed with whitespace change ignore (-w)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:32:35 +02:00
Thomas Lamprecht
71cad8cac0 accessible group iter: add owner override and owner + extra priv handling
The "owner override" privs will skip the owner check completely if
the authid has a permission for any of the bitwise OR'd privs
requested on the namespace level.

The "owner and privs" are for the case where being the owner is not
enough, e.g., pruning, if set they need to match all, not just any,
on the namespace, otherwise we don't even look at the groups from the
current NS level.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:27:58 +02:00
Thomas Lamprecht
49bea6b5d9 accessible group iter: allow NS descending with DATASTORE_READ
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-19 12:26:48 +02:00
Thomas Lamprecht
f7247e2b84 ui: datastore content: add icons to top bar prune/verify buttons
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 18:37:20 +02:00
Thomas Lamprecht
5664b41c30 ui: acl view: make path column flex, but enforce minWidth
with namespaces the paths can get pretty complex, so make the path
column take some flex space too, but not too much to avoid making it
look odd for the short paths we have otherwise

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 18:22:17 +02:00
Thomas Lamprecht
33612525e1 ui: datastore permissions: allow ACL path edit & query namespaces
Without namespaces this had not much use, but now that we can have
permissions below we should allow so.

For convenience also query the namsepaces here and add them to the
list of available ACL paths, the read-dir shouldn't be that expensive
(albeit, we could cache them in the frontend)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 18:14:37 +02:00
Thomas Lamprecht
a502bc5617 ui: small style cleanups/refactoring
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 18:04:16 +02:00
Thomas Lamprecht
8772ca727c api types: verify job: fix doc comment typo
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 15:45:55 +02:00
Thomas Lamprecht
7f3b4a94e6 api types: verify job: allow outdated-afer == 0 for backward compat
We can have those in existing verify jobs configs, and that'd break
stuff. So, even while the "bad" commit got released only recently
with `2.1.6-1` (14 April 2022), we still need to cope with those that
used it, and using some serde parser magic to transform on read only
is hard here due to section config (json-value and verify currently
happen before we can do anything about it)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 15:39:59 +02:00
Thomas Lamprecht
327d14b3d1 Revert "verify: allow '0' days for reverification"
This reverts commit 7a1a5d206d7f526baaa39b86ecb462a870b641c1.

We could already cause the behavior by simply setting ignore-verified
to false, aas that flag is basically an on/off switch for even
considering outdated-after or not.

So avoid the extra logic and just make the gui use the previously
existing way.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 12:53:08 +02:00
Thomas Lamprecht
0f8fd71093 cargo: update commented-out path patched dependencies
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 09:00:41 +02:00
Thomas Lamprecht
8d3b84e719 d/changelog: fixup last entry
as this obviously is released...

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-18 08:45:53 +02:00
Thomas Lamprecht
d1d328d582 bump version to 2.2.1-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 14:03:30 +02:00
Thomas Lamprecht
72e344a1b4 ui: namespace & maintenance mode: refer to onlineHelp
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 14:03:00 +02:00
Thomas Lamprecht
f71a4ce6d6 docs: client usage: add some hints for namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:55:21 +02:00
Thomas Lamprecht
a3b1026753 docs: some textwidth cleanups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:55:04 +02:00
Dominik Csapak
5e1b17018b ui: namespace selector: show picker empty text if no namespace
by filtering out the empty namespace from the api, and putting
manually a div with the grid-empty xclass around the gettext

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
 [ T: reword commit message ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:40:27 +02:00
Thomas Lamprecht
9615d9a6b6 ui: tape restore: reword comment w.r.t. mapping value
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:35:55 +02:00
Dominik Csapak
3ae4dab4b9 ui: tape restore: fix form validation for datastore mapping
'defaultStore' can be '' or null, so check for truthyness also, we
want the mapping to be a formField so that the validation triggers
and the restore button gets en/disabled accordingly. We still have to
call 'getValue' manually, because the onGetValues will get it as
string instead of an array

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:35:21 +02:00
Oguz Bektas
d74172bfc1 node info: fix typo in product name
s/Bacckup/Backup

Signed-off-by: Oguz Bektas <o.bektas@proxmox.com>
2022-05-17 13:30:36 +02:00
Thomas Lamprecht
2e9a9f94a4 update online help reference info
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:30:11 +02:00
Thomas Lamprecht
ed9797d67e storage: add some initial namespace docs
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:29:02 +02:00
Thomas Lamprecht
56f0ce27ac docs: storage: refer to options
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:28:50 +02:00
Thomas Lamprecht
67d4131158 docs: basic maintenance mode section
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:28:24 +02:00
Thomas Lamprecht
acbb19498a docs: also mention Sync in heading of Managing Remotes
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:28:05 +02:00
Thomas Lamprecht
187ec50488 docs: refer more to screenshots all over the place
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:27:37 +02:00
Thomas Lamprecht
b3116e5680 docs: update and add screenshots
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 13:27:09 +02:00
Thomas Lamprecht
77baca66eb ui: datastore list: drop duplicate errorBox reference, neither is used
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 11:07:46 +02:00
Thomas Lamprecht
e7ddae292a ui: datastore selector: move maintenance mode inline with icon
else it's a lot of wasted space for the ordinary case, that hasn't
permanent maintenance modes activated, and even if, their admins
should be used to it, so not the best space/usability ROI there
either.

Just use the icon as visual clue and add a tooltip for the
maintenance mode info.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 10:49:31 +02:00
Dominik Csapak
c15b058db7 ui: form/DataStoreSelector: show maintenance mode in selector
to not having to query the activeTasks everywhere, change the renderer
to omit the check/spinner when no activeTasks are given

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-17 10:40:56 +02:00
Thomas Lamprecht
8af1fa5477 ui: use base 10 (SI) for all storage related displays
matches what we do for (most) of such things in PVE since 7.0 there
and also what the disk management gui shows, further disks are sold
with SI units for their advertised capacity, so its more fitting
there too.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 10:21:26 +02:00
Thomas Lamprecht
f61d822efa ui: utils: add depreacation comment to render_size_usage
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 10:21:26 +02:00
Thomas Lamprecht
d0e3f5dd5c ui: server status: fix missing space in title
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 10:21:26 +02:00
Thomas Lamprecht
16e605583f ui: server status: use power of two base for memory and swap
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 10:21:26 +02:00
Wolfgang Bumiller
62e5cf1e8c pbs-client: fix symbolic mode display for 'other' mode
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-17 10:20:57 +02:00
Thomas Lamprecht
76bc66b9bd ui: sync/verify jobs: use pmxDisplayEditField to fix editing
commit bd21a63b only fixed sync, not verify, and we can do better by
using a display-edit field.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:48:03 +02:00
Dominik Csapak
bd21a63bd2 ui: sync job: don't send 'id' on edit
we cannot change the id, and even if we send the same, the backend
does not allow 'duplicate' parameters (the id is in the url already)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:47:56 +02:00
Dominik Csapak
d14512c82d ui: datastore/Summary: correctly show the io-delay chart
by checking if *any* record has data, not only the first
this would prevent the chart from being shown for e.g. newly added
datastores, or for datastores after the server was offline for some time

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:47:56 +02:00
Thomas Lamprecht
e5cf0e3eda ui: update online help reference
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:47:56 +02:00
Thomas Lamprecht
14f140d1c5 docs: storage: show gui disk management screenshot
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:47:56 +02:00
Thomas Lamprecht
1d592668ac docs: update/add some screenshots
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-17 09:47:56 +02:00
Thomas Lamprecht
2c0fae66b3 docs: certs: fix odd image referencing and drop duplicate usage
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 19:27:06 +02:00
Stoiko Ivanov
cbd7db1d7f docs: certificates
manually adapt to differences between PMG and PBS

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-16 19:27:06 +02:00
Stoiko Ivanov
6189b956b6 docs: add certificate-management.rst
the file certificate-managment.rst is generated from the pmg-docs repo

by running:
```
asciidoc -b $(pwd)/asciidoc/pmg-docbook \
-f asciidoc/asciidoc-pmg.conf -o - pmg-ssl-certificate.adoc | \
pandoc -f docbook -t rst --shift-heading-level-by=1 \
-o certificate-mangement-auto.rst

sed -ri 's/__/_/' certificate-mangement-auto.rst
sed -ri 's/\{pmg\}/`Proxmox Backup`_/g' certificate-mangement-auto.rst
sed -ri 's/\{PMG\}/`Proxmox Backup`_/g' certificate-mangement-auto.rst
sed -ri 's/Proxmox Mail Gateway/`Proxmox Backup`_/g' \
certificate-mangement-auto.rst
sed -ri 's/pmg-([a-zA-Z0-9_-]*).png/pbs-\1.png/g' \
certificate-mangement-auto.rst
sed -ri 's/pmgproxy/proxmox-backup-proxy/g' \
certificate-mangement-auto.rst
sed -ri 's/pmgconfig/proxmox-backup-manager/g' \
certificate-mangement-auto.rst
sed -ri 's/pmg-daily/proxmox-backup-daily-update/g' \
certificate-mangement-auto.rst
sed -ri 's/\/etc\/pmg\/node.conf/\/etc\/proxmox-backup\/node.cfg/g' \
certificate-mangement-auto.rst
sed -ri 's/\/etc\/pmg\/acme/\/etc\/proxmox-backup\/acme/g' \
certificate-mangement-auto.rst
sed -ri \
's/\/etc\/pmg\/pmg-api.pem/\/etc\/proxmox-backup\/proxy.pem/g' \
certificate-mangement-auto.rst
sed -ri 's/screenshot/screenshots/g' certificate-mangement-auto.rst

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-16 19:27:06 +02:00
Thomas Lamprecht
c2add820a4 docs: add certificate related screenshots
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 19:27:06 +02:00
Stoiko Ivanov
e1dc2d2210 docs: use case-matching keys for glossary
this silences warnings a la:
```
WARNING: term container not found in case sensitive match.made a
reference to Container instead
```
the issue is purely cosmetic during build, and should vanish in a newer
version of sphinx-doc [0].

[0] https://github.com/sphinx-doc/sphinx/issues/7636

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-16 19:27:06 +02:00
Stoiko Ivanov
bffc923420 docs: cleanup and readd command-line-tools
the collection of descriptions of our cli tools was dropped in
04e24b14f0c51f01a1f8afe2d0eff124c1095758

I'll readd it to the sysadmin.rst, since the (related) service daemons
also got moved here.

additionally add the newly added cli-tools to both
command-line-tools.rst and command-syntax.rst, and put both in the same
order

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-16 19:27:06 +02:00
Stoiko Ivanov
c760a67278 docs: silence duplicate label warnings.
by reindroducing the trailing ',' after local-zfs.rst
and adding the missing 'traffic-control.rst' to the list
of files/patterns to be excluded.

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-16 19:27:06 +02:00
Thomas Lamprecht
0181b0f1f7 bump version to 2.2.0-2
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 19:01:19 +02:00
Fabian Grünbichler
d22363ad08 BackupDir/BackupGroup: add ns to Debug impl
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
7784698948 BackupGroup: stop implementing Display
this shouldn't be printed/logged - use DatastoreWithNamespace /
pbs_api_types::BackupGroup instead.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
3697161800 prune: fix workerid issues
properly encode the namespace as separate field both for manual prunes
and the job. fix the access checks as well now that the job doesn't use
the jobid as workerid anymore.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
e13303fca6 tree-wide: prefer api-type BackupGroup for logging
together with DatastoreWithNamespace where needed, to not forget
namespace information.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
eefa297aa0 BackupDir: stop implementing Display
the api type implements it already, all call sites should rather use
DatastoreWithName and pbs_api_types::BackupDir for logging/..

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
5ae393af15 tape/verify: use print_ns_and_snapshot
in those few places where we actually want to use/print the full,
NS-included path.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
f2fe00f1e2 BackupDir: fix manifest_lock_path
this definitely shouldn't rely on BackupDir's Display implementation..

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
1afce610c7 tree-wide: prefer api-type BackupDir for logging
in combination with DatastoreWithNamespace to not lose the namespace
information.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Fabian Grünbichler
f15601f1c9 BackupDir: add group/dir accessors
for getting the respective api type references for convenient
printing/logging.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:49:19 +02:00
Thomas Lamprecht
90915ab629 ui: verify/sync: allow to optionally override ID again
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 18:48:44 +02:00
Thomas Lamprecht
ebab1e5ed9 api: namespace create: lookup datastore with corret operation
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 18:26:55 +02:00
Hannes Laimer
6da6bafeac ui: add maintenance mask to DataStoreListSummary
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-05-16 18:10:35 +02:00
Thomas Lamprecht
067c77329b docs: acl path: add a namespace related example
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 18:10:13 +02:00
Fabian Grünbichler
8c4131708a docs: add namespace section to sync documentation
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 18:09:15 +02:00
Thomas Lamprecht
a7646fe42a Revert "fix #4001: datastore/catalog: add number of files to directory entry"
causes trouble with UI and is inconsistent as its still missing in
file restore (daemon)

We probably want to use a separate property to safe this to avoid
confusion with size.

This reverts commit 66ad63bac23359b8ede822496f68ebde843cf988.
2022-05-16 17:51:35 +02:00
Thomas Lamprecht
dadaa9e2f0 ui: verify outdated: disallow blank and drop wrong empty text
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 16:46:06 +02:00
Thomas Lamprecht
6a7b673872 ui: switch summary repo status to widget toolkit one
Not only can we remove a few lines of duplicated code, we also get
the "link to repo management" for free.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 15:56:33 +02:00
Fabian Grünbichler
0606432e9b d/control: use regular versioned build-dependency
although the full variant is provided by the current librust-log-dev
package, it won't be once it gets bumped to the next upstream version.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 15:52:39 +02:00
Fabian Ebner
7ebd97e8ea ui: fix setting protection in namespace
The ns parameter would not be included previously.

Signed-off-by: Fabian Ebner <f.ebner@proxmox.com>
2022-05-16 15:29:55 +02:00
Thomas Lamprecht
44df558d66 docs: terminology: add namespaces and slightly restructure
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 15:28:00 +02:00
Fabian Grünbichler
9c75e2f3e1 build: bump required log version
else logging using "{var}" in format strings doesn't work properly.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 15:02:07 +02:00
Wolfgang Bumiller
4adb574d74 client: add completion callbacks for ns parameters
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-16 11:59:14 +02:00
Wolfgang Bumiller
fb840eda4d pbs-client: namespace completion helper
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-16 11:58:13 +02:00
Thomas Lamprecht
007388f053 bump version to 2.2.0-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 11:06:18 +02:00
Thomas Lamprecht
1d9ba1cc8b docs: add "Objects and Paths" section and fix perm scrot
we show the add-user one twice in this chapter, one should actually
be add-permission

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 10:56:19 +02:00
Thomas Lamprecht
63e98028cc api types: namespace: fix typo in error message
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 09:50:17 +02:00
Fabian Grünbichler
e3ea577011 pull: use API BackupDir for log messages
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-16 09:43:28 +02:00
Thomas Lamprecht
6bfc94ea19 api types: BackupNamespace: fix depth check on pushing subdir to ns
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 09:37:38 +02:00
Thomas Lamprecht
1f2126fd7c api types: BackupNamespace: remove unused, commented out code
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 09:37:38 +02:00
Thomas Lamprecht
456456483e datastore: ns iter: clamp depth to MAX_NAMESPACE_DEPTH from datastore root
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 09:37:38 +02:00
Thomas Lamprecht
3eb15257b9 ui: permission path selector: add some more path suggestions
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 08:44:49 +02:00
Thomas Lamprecht
597398cb48 docs: rework access control, list available privileges
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-16 08:00:40 +02:00
Thomas Lamprecht
3d2baf4170 ui: datastore: use safe destroy as base for dialog
only ask the name of the current NS, not the full NS path to avoid
too long input requirements on deep levels.

needs a few smaller hacks, ideally we would pull out the basic stuff
from Edit window in some EditBase window and let both, SafeDestroy
and Edit window derive from that, for better common, in sync
features.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:47:44 +02:00
Thomas Lamprecht
3aafa61362 namespace deletion: propagate delete-groups=false but ENOTEMPTY as error
after all we couldn't delete all that got requested, ideally this
should become a task where we can log what got deleted and what
not...

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:32:49 +02:00
Thomas Lamprecht
60b9676fa2 ui: datastore: allow deleting currently shown namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:04:50 +02:00
Thomas Lamprecht
e5824cd61f ui: content: reload tree on succesful datastore add
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:03:16 +02:00
Thomas Lamprecht
508d644e87 ui: tree NS entries: remove commented out qtip
we won't use that, it's to invasive

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:02:38 +02:00
Thomas Lamprecht
b0166d4e8d api: cargo fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:01:57 +02:00
Thomas Lamprecht
ca3f8757ba datastore: clippy fixes
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 16:01:09 +02:00
Thomas Lamprecht
118e984996 datastore: move backup dir/group/namespace iter to own module
no changes in interface for users of the crate as we re-export
anyway, so more for avoiding to crowd the datastore module to much

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 15:59:43 +02:00
Thomas Lamprecht
45ba884d0d ui: content: fix tooltip for forgetting snapshot
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 14:09:25 +02:00
Thomas Lamprecht
d1f9cceada namespace deletion: make destroying groups separate choice
And make that opt-in in the API endpoint, to avoid bad surprises by
default.

If not set we'll only prune empty namespaces.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 14:09:25 +02:00
Stefan Sterz
4ac8ec11fb fix #4001: ui: add prefix to files downloaded through the pxar browser
Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 14:09:25 +02:00
Stefan Sterz
66ad63bac2 fix #4001: datastore/catalog: add number of files to directory entry
When listing the content of a catalog, add the number of files
contained in the directory as its size. Also removes redundant code,
the `mtime` and the `size` of a file is already set when creating the
archive entry, but we naturally need to override the size now for
directories.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-15 14:08:51 +02:00
Thomas Lamprecht
9ec82aefb4 ui: prune all: add namespace info in title
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:57:05 +02:00
Thomas Lamprecht
e3cda36ba5 ui: move prune input panel into own file
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:51:54 +02:00
Thomas Lamprecht
5d05f334f1 ui: prune group: add NS info to title
restructure it a bit for better UX

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:47:13 +02:00
Thomas Lamprecht
a3d61f3fba ui: remote target ns selector: add clear trigger
like we have for the local NS selector

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:40:52 +02:00
Thomas Lamprecht
ed289736cf ui: improve render_optional_namespace slighly
it maybe should still simple get dropped and replaced with
(empty)Text 'Root' or 'Root Namespace'

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:39:56 +02:00
Thomas Lamprecht
dc193e8197 ui: remote target ns selector: fix clearing value on edit
never makes sense to clear the value due to remote or remoteStore
change as we weren't enabled then in the first place.

This fixes clearing the currently set namespace on editing an
existing job, which always made it seem like the Root namespace was
selected, even if the originalValue was correct (thus the dirty-form
reset/ok behaviour still worked, making it even more confusing)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 18:29:12 +02:00
Thomas Lamprecht
1f71e44172 client: make change-owner and prune namespace aware
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 17:16:25 +02:00
Thomas Lamprecht
7da520ae46 hierachy: ListAccessibleBackupGroups make store also a lifetime'd ref
avoid some extra Arc::clone, even if they're not really expensive
(just some atomics)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 14:56:34 +02:00
Thomas Lamprecht
cbde538c0c ui: maintenance mode: opinionated code cleanup
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 14:51:57 +02:00
Thomas Lamprecht
cf1b029b3f ui: ACL edit: set default focus on a non-combobox element
to avoid making it "jump" in the users face by immediately opening
the picker on window open.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 14:50:40 +02:00
Thomas Lamprecht
4f897c8cf9 ui: namespace selector: set queryMode to local
to avoid that the comobox triggers automatic API request with the
queryParam default `query` GET param on manual typing (e.g., for
filtering) from the user, we have all data already loaded and locally
available.

https://docs.sencha.com/extjs/7.0.0/classic/Ext.form.field.ComboBox.html#cfg-queryMode

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 14:48:36 +02:00
Thomas Lamprecht
2e63a46414 ui: trigger datastore update after maintenance mode edit
This provides immediate feedback for adding the respective icon in
the navigation tree entry most of the time, and we can then increase
the query period of the datastore list store to the original 15
again, as it was lowered to 5 seconds for just this reason in commit
fbd6f54f39b243e5

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 14:39:02 +02:00
Thomas Lamprecht
9f4d9abbf6 ui: fix storeId casing to register store correctly
we query that store to add the datastore specific ACL paths to
improve UX there, this failed a while due the StoreManager lookup
always failing as the store wasn't registered in the StoreManager due
to using storeid vs. correct storeId

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-14 12:28:03 +02:00
Thomas Lamprecht
8122eaadaa cargo fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 16:59:32 +02:00
Thomas Lamprecht
22cfad134f api: datastore status: make counts recurse over all accesible namespaces
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 16:49:42 +02:00
Thomas Lamprecht
de27ebc6b6 hierachy: add lifetime to ListAccessibleBackupGroups so that owner can be ref
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 16:48:56 +02:00
Dominik Csapak
74391d1c32 docs: tape: add information about namespaces
which are backed up, how to use the new parameters and how to map
them during restore

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 15:45:17 +02:00
Dominik Csapak
fca84a4b94 docs: tape/restore: mention single snapshot restore
what it is, how to use it and the caveats

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 15:45:17 +02:00
Dominik Csapak
602319f9fc docs: tape: remove note about global content namespace
that is actually not true, we save the datastore in the chunk archives
as well as the snapshot archives, otherwise we could not backup
multiple datastores to a single media-set.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 15:45:17 +02:00
Dominik Csapak
8d2a9b2904 cli: proxmox-tape: fix ns/depth parameter
was forgotten after recent rebase

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 15:45:17 +02:00
Thomas Lamprecht
c8e93b31ff bump version to 2.1.10-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 14:26:38 +02:00
Thomas Lamprecht
cf99333b83 ui: adapt to s/backup-ns/ns/ api param change
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 14:21:52 +02:00
Dominik Csapak
b70a12e723 ui: tape/Restore: allow simple namespace mapping
add a default namespace selector (of the current default store)
and a namespace selector per target datastore (for media-sets with
multiple datastores).

to achieve that we have to change the way we handle the mapping field a bit:
* don't use it as field directly (otherwise the value gets stringified),
  but use the 'getValue' method in 'onGetValues'.
* set the defaultStore there, not only that we have one
  (with this we can now easily show it as emptytext for each store)
* add a reference to the widgets to the record so that we can access
  them in the respective change handler (also clean those references up,
  else we have a cyclic reference between record <-> widget)

in onGetValues, if we have multiple datastores, the mapping grid does
all the work for us, otherwise, we have to create the ns mapping
ourselves there.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:09:53 +02:00
Dominik Csapak
f6b09e83cb ui: tape/BackupJobEdit: add onlineHelp
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:09:53 +02:00
Dominik Csapak
6f836d3ffa ui: tape/Backup: add namespace + max-depth to backup job edit window
like we do for sync

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:09:53 +02:00
Dominik Csapak
80df7caded ui: tape/Backup: add namespace and recursion field for manual backup
and change the layout to two columns, because the window was getting
too tall.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:09:53 +02:00
Dominik Csapak
12d334615b api: tape/backup: fix namespace/max-depth parameters
by adding the 'default' serde hint and renaming 'recursion_depth' to
'max_depth' (to be in line with sync job config)

also add the logic to actually add/update the tape backup job config

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:09:53 +02:00
Dominik Csapak
1e37156a6b ui: tape/BackupOverview: show namespaces as their own level above groups
since the namespaces are in the snapshot path we get here, we must parse
them out, else we confuse the first namespace with the group.

for now, show all namespaces on the same level (so not nested), and
do not allow for preselecting a namespace for restoring

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:32 +02:00
Fabian Grünbichler
e49bd1e98f tape: media catalog: use match for magic check
like in other parts of the code

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 14:08:32 +02:00
Fabian Grünbichler
707c48ad46 tape: bump catalog/snapshot archive magic
the snapshot string format is not backwards compatible since it now has
an in-line namespace prefix. it's possible to select which magic to use
at the start of the backup, since a tape backup job knows whether it
operates on non-root namespaces up-front.

the MediaCatalog itself also has a similar incompatible change, but
there
- updating existing catalogs in-place
- not knowing what the catalog will contain in the future when initially
  creating/opening it
makes bumping the magic there harder. since the tape contents are
sufficiently guarded by the other two bumps, ignoring the
backwards-incomaptible change of the on-disk catalogs seems like an okay
tradeoff.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 14:08:32 +02:00
Dominik Csapak
07ffb86451 api: tape/restore: add namespace mapping
by adding a new parameter 'namespaces', which contains a mapping
for a namespace like this:

store=datastore,source=foo,target=bar,max-depth=2

if source or target are omitted the root namespace is used for its value

this mapping can be given several times (on the cli) or as an array (via
api) to have mappings for multiple datastores

if a specific snapshot list is given simultaneously, the given snapshots
will be restored according to this mapping, or to the source namespace
if no mapping was found.

to do this, we reutilize the restore_list_worker, but change it so that
it does not hold a lock for the duration of the restore, but fails
if the snapshot does exist at the end. also the snapshot will now
be temporarily restored into the target datastore into the
'.tmp/<media-set-uuid>' folder.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:32 +02:00
Dominik Csapak
fc99c2791b api: tape/restore: check and create target namespace
checks the privilegs for the target namespace. If that does not exist,
try to recursively create them while checking the privileges.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:32 +02:00
Dominik Csapak
6b61d319c5 api: tape/restore: add optional namespace map to DataStoreMap
and change the interface from 'get_datastore' to 'get_targets'

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:32 +02:00
Dominik Csapak
be97e0a55b tape: add namespaces mapping type
and the relevant parser for it

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:32 +02:00
Dominik Csapak
999293bbca tape: add namespaces/recursion depth to tape backup jobs
and manual api via TapeBackupJobSetup

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 14:08:31 +02:00
Dominik Csapak
9c65e6ab4a tape: fix snapshot path in catalog and snapshot_archive
both used the 'Display' trait of pbs_datastore::BackupDir, which is not
intended to be serialized anywhere. Instead, manually format the path
using the print_ns_and_snapshot helper, and conversely, parse with
'parse_ns_and_snapshot'. to be a bit safer, change the register_snapshot
signature to take a BackupNamespace and BackupDir instead of a string.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 13:52:50 +02:00
Dominik Csapak
1e4e1514d3 pbs-api-types: add parse and print ns_and_snapshot
these are helpers for the few cases where we want to print and parse
from a format that has the namespace and snapshot combined, like for
the on-tape catalog and snapshot archive.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 13:52:50 +02:00
Dominik Csapak
05b7175a56 tape: notify when arriving at end of media
when continuing a media set, we first move to the end of the tape and
start with the next (chunk) archive. If that takes long, the task logs
last line is 'moving to end of media' even if we already startet
writing. To make this less confusing, log that we arrived at the
end of the media.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-13 13:52:50 +02:00
Wolfgang Bumiller
bc21ade293 tree-wide: rename 'backup-ns' API parameters to 'ns'
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-13 13:46:13 +02:00
Thomas Lamprecht
f07e660153 ui: move max NS prefix length logic to reduced max-depth selector
for better re-usability in the future and it felt a bit odd to have
such specific logic in the sync job edit directly

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 13:15:02 +02:00
Thomas Lamprecht
addcb7803e datastore: inline some format variables
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 12:42:41 +02:00
Thomas Lamprecht
1ddfae5499 api types: set NS_MAX_DEPTH schema default to MAX_NAMESPACE_DEPTH
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 12:32:25 +02:00
Thomas Lamprecht
54d315c951 ui: group filter: make also local filter NS aware
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-13 12:32:25 +02:00
Fabian Grünbichler
9dde8cd625 ui: sync: add reduced max-depth selector
that allows setting the limit based on sync namespace prefix lengths.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 12:20:29 +02:00
Fabian Grünbichler
87be232d1c pull/sync: clamp (local) max-depth if unset
to handle the unlikely case of `ns` being deeper than `remote-ns`,
`max-depth` being set to `None` and a too-deep sub-ns of `ns` existing.
such a sub-ns cannot have been created by a previous run of this sync
job, so avoid unexpectedly removing it.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 12:07:22 +02:00
Fabian Grünbichler
e40c7fb906 api: split max-depth schema/types
into the regular one (with default == MAX) and the one used for
pull/sync, where the default is 'None' which actually means the remote
end reduces the scope of sync automatically (or, if needed,
backwards-compat mode without any remote namespaces at all).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 12:07:22 +02:00
Fabian Grünbichler
66abc4cb7d namespaces: move max-depth check to api type
and use it when creating a sync job, and simplify the check on updating
(only check the final, resulting config instead of each intermediate
version).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 12:07:22 +02:00
Fabian Grünbichler
11567dfbad pull/sync: correctly query with remote-ns as parent
else (grand)-parents and siblings/cousins of remote-ns are also
included, and mapping the remote-ns prefix fails.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-13 12:07:22 +02:00
Fabian Grünbichler
7a3e777ded pull/sync: detect remote lack of namespace support
and fall back to only syncing the root namespace, if possible. the sync
job will still be marked as failed to prompt the admin to resolve the
situation:
- explicitly mark the job as syncing *only* the root namespace
- or upgrade remote end to support namespaces

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-12 17:00:38 +02:00
Fabian Grünbichler
b9310489cf pull/sync: treat unset max-depth as full recursion
to be consistent with tape backup and verification jobs.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-12 17:00:38 +02:00
Fabian Grünbichler
d9aad37f2f pull: pass params as non-ref in pull_store
so that it's possible to modify them in-place without cloning.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-12 16:26:26 +02:00
Thomas Lamprecht
2a088b9975 datastore: drop bogus chunk size check, can cause trouble
other sizes can happen in legitimate and illegitimate ways:
 - illegitimate: encryped chunks and bad actor client
 - legitimate: same chunk but newer zstd version (or compression
   level) can compress it better (or worse) so the

Ideally we could take the actual smaller chunk so that improved zstd
tech gets leveraged, but we could only allow to do that for
un-encrypted ones.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 15:41:20 +02:00
Thomas Lamprecht
78e1ee5230 bump version to 2.1.9-2
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 14:28:16 +02:00
Dominik Csapak
c7d42dac97 ui: navigation tree: fix losing datastore selection on store load
instead of using 'replaceChild', simply set the appropriate
properties. When using the 'nodeUpdate' (protected function of extjs,
intended to be overwritten) instead of the private 'updateNode', it
will be called when the properties change

This way, the treenode stays the same and it can keep the selection

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-12 14:28:16 +02:00
Wolfgang Bumiller
8ca7cccf5f file-restore: add namespace support to qemu part
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-12 13:35:34 +02:00
Thomas Lamprecht
e30a2e9058 ui: content: fix various tree-checks from action handlers
they all still used some odd side effects of the tree structure to
decided what record type they operated on, just move them over to the
new `ty` record.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 13:28:20 +02:00
Thomas Lamprecht
08982a3746 rest: example: fix comment width
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:57:51 +02:00
Thomas Lamprecht
42fb291c7c cargo fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:54:21 +02:00
Fabian Ebner
e9b9f33aee rest server: daemon: update PID file before sending MAINPID notification
There is a race upon reload, where it can happen that:
1. systemd forks off /bin/kill -HUP $MAINPID
2. Current instance forks off new one and notifies systemd with the
   new MAINPID.
3. systemd sets new MAINPID.
4. systemd receives SIGCHLD for the kill process (which is the current
   control process for the service) and reads the PID of the old
   instance from the PID file, resetting MAINPID to the PID of the old
   instance.
5. Old instance exits.
6. systemd receives SIGCHLD for the old instance, reads the PID of the
   old instance from the PID file once more. systemd sees that the
   MAINPID matches the child PID and considers the service exited.
7. systemd receivese notification from the new PID and is confused.
   The service won't get active, because the notification wasn't
   handled.

To fix it, update the PID file before sending the MAINPID
notification, similar to what a comment in systemd's
src/core/service.c suggests:
> /* Forking services may occasionally move to a new PID.
>  * As long as they update the PID file before exiting the old
>  * PID, they're fine. */
but for our Type=notify "before sending the notification" rather than
"before exiting", because otherwise, the mix-up in 4. could still
happen (although it might not actually be problematic without the
mix-up in 6., it still seems better to avoid).

Signed-off-by: Fabian Ebner <f.ebner@proxmox.com>
2022-05-12 11:53:54 +02:00
Thomas Lamprecht
f4d246072d ui: avoid ascending to upper NS on double click of current
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:48:27 +02:00
Thomas Lamprecht
15808a9023 ui: add namespace: preselect current NS as parent for new one
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:47:14 +02:00
Thomas Lamprecht
e22ad28302 GC scheduling: avoid triggering operation tracking error for upfront checks
without that one gets a "failed to lookup datastore X" in the log for
every datastore that is in read-only or offline maintenance mode,
even if they aren't scheduled for GC anyway.

Avoid that by first opening the datastore through a Lookup operation,
and only re-open it as Write op once we know that GC needs to get
scheduled for it.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:36:56 +02:00
Thomas Lamprecht
0408f60b58 datastore: add new Lookup for operations tracking
We sometimes need to do some in-memory only stuff, e.g., to check if
GC is already running for a datastore, which is a try_lock on a mutex
that is in-memory.

Actually the whole thing would be nicer if we could guarantee to hold
the correct contract statically, e.g., like
https://docs.rust-embedded.org/book/static-guarantees/design-contracts.html

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 11:36:56 +02:00
Hannes Laimer
d4d730e589 proxy: rrd: skip update disk stats for offline datastores
RDD update did not use lookup_datastore() and therefore bypassed
the maintenance mode checks. This adds the needed check directly.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-05-12 11:36:56 +02:00
Wolfgang Bumiller
5b460ef525 client: add --ns parameters to snapshot commands
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-12 11:02:06 +02:00
Wolfgang Bumiller
03d4f43d5a client: rename --backup-ns to --ns in backup command
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-05-12 10:43:56 +02:00
Stoiko Ivanov
5225817de6 docs: zfs: update documentation about ZED
This closely follows commit aa425868069818167ff0a3cca5c64a2acc88173e
in pve-docs.

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-12 10:08:30 +02:00
Stoiko Ivanov
0ae5f76277 docs: local-zfs: minor cleanup and adaptation
fixes a few small glitches in the markup.

rephrases a few PVEisms (PBS will not swap when starting a backup to
an external storage)

add zstd to available compression algorithms

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-12 10:08:30 +02:00
Stoiko Ivanov
09d903034f docs: system-booting: (re)add screenshots
add the grub+systemdboot screen from a PBS system (taken via
spice-viewer).

The alingment of left/right looked better to me than keeping both on the
right).

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-12 10:08:30 +02:00
Stoiko Ivanov
9eb804006c docs: add system-booting from pve-docs
and transform to reST.

semantic changes to the content are:
* s/{pve}/`Proxmox Backup`_/g
* changing footnotes to parenthesized notes (did not see footnote use in
  the current docs)
* removed the comment about systems setup before the introduction of
  p-b-t (which was introduced before pbs)

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-12 10:08:30 +02:00
Stoiko Ivanov
6e3391c85b docs: sysadmin: adapt kernel-specifics for PBS
while all statements here are technically true - adding all
virtualization improvements is not relevant for proxmox backup in most
cases.
The intel nic driver seems like a left-over from a time (pre PVE 5.1)
where the pve-kernel included the out-of-tree drivers.

Signed-off-by: Stoiko Ivanov <s.ivanov@proxmox.com>
2022-05-12 10:08:30 +02:00
Thomas Lamprecht
71139be203 bump version to 2.1.9-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:48:51 +02:00
Thomas Lamprecht
fbca018229 ui: content: code cleanups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
7e8b24bd8c ui: content: show namespaces also inline and rework node type detection
this not only makes the action disable/hide checks simpler, but also
prepares the view a bit for the idea of adding a new API endpoint
that returns the whole datastore content tree as structured JSON so
that it can be directly loaded into a tree store.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
fe79687c59 pull group: add error context for cleanup_unreferenced_files
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
9ccf933be5 datastore: move update_manifest into BackupDir impl
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
87cdc327b9 sync: pull snapshot: use template variables for bloat reduction
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
5566099849 datastore: move cleanup_unreferenced_files to BackupDir impl and fix NS awareness
sync failed on cleanup due to always trying to do so in the root NS

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
92b9cc1554 ui: remote target selectors: code cleanups
just a small start...

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
0e3de42aa7 ui: sync job: use namespace selector for localNS
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Thomas Lamprecht
8c29bca57c ui: move remote target datastore/ns selectors to own file
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Fabian Grünbichler
d895b26bb9 ui: add namespace fields to sync
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:40:43 +02:00
Fabian Grünbichler
c06c1b4bd7 sync/pull: make namespace aware
Allow pulling all groups from a certain source namespace, and
possibly sub namespaces until max-depth, into a target namespace.

If any sub-namespaces get pulled, they will be mapped relatively from
the source parent namespace to the target parent namespace.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
31aa38b684 ui: verify job: fix add-job on datastore-agnostic level
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
9d8090626c ui: namespace selector: allow to set datastore dynamically
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
6b4d057370 api-types: rework BackupNamespace::map_prefix
to use slice::strip_prefix() from std

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
53d073ec1a datastore: minor cleanup
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
30ccc3003e datastore: relative path fixup
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
bc4af01559 ui: datastore content: make verify-all more flexible
allow to specify the namespace, max_depth and also the re-verify/skip
behavior.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
d83ce0d0c7 ui: fix group backup comment NS awareness
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
ad7741a294 ui: verify job: make namespace and max-depth aware
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
a327f918af ui: add verifyOutdatedAfter component
mainly as separate component for the trigger

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
0b1edf297b verify job: support max-depth config
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
59229bd7f1 api: verify: support namespaces
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
8e82cc807c add ns-recursive and acl/authid aware backup group iter
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
d4037525a8 remote scan/completion: add namespace support
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
40d495de6d api: add DatastoreWithNamespace helper struct
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
d3a570eb79 ui: fix wrong call to htmlEncode
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
9f8fb928f1 ui: add namespace renderer
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
226a4e68da client: add basic namespace commands
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
473063e9ec api: ns management: fix permission checks
we do not have normal GET variables available in the checks provided
by the rest server from the api macro, so do it manually.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
93b0659ff2 ui: datastore: more NS awareness
verify is actually not yet ready in the backend

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
e8112eb37b ui: datastore content: show root node for better UX with NS
that way it's easier to see on which NS one currently operates and
allows better distinguishing of root NS and some sub ns named "Root"

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
6f5753cfa3 api-types: allow empty namespace
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
3c09413a0a client: don't pass empty backup-ns
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
028346e42c ui: content view: improve empty text
reference NS so that users get a hint where they are currently
hierarchy-wise, and clarify that we found no *accessible* snapshots,
on this level, i.e., there can be some that we just cannot see due to
only having access on lover level NS or being different owners.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
bc06c7b4e9 api: namespace: return popped component
helpful for places where namespaces need to be (re)created

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
7a404dc53d api: datastore: further unify check helpers
this is the most common sequence of checks we have in this file, so
let's have a single place where we implement it.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
c939698414 api: datastore: load datastore & check owner helper
these happen together very often.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
1909ece229 api: datastore: lookup after checking privs
else this could leak existence of datastore.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
2bc2435a96 api: datastore: refactor priv checks
the helper now takes both high-privilege and lesser-privilege privs, so
the resulting bool can be used to quickly check whether additional
checks like group ownership are needed or not.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
a724f5fd47 api: datastore: unify access checks
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
133d718fe4 split the namespace out of BackupGroup/Dir api types
We decided to go this route because it'll most likely be
safer in the API as we need to explicitly add namespaces
support to the various API endpoints this way.

For example, 'pull' should have 2 namespaces: local and
remote, and the GroupFilter (which would otherwise contain
exactly *one* namespace parameter) needs to be applied for
both sides (to decide what to pull from the remote, and what
to *remove* locally as cleanup).

The *datastore* types still contain the namespace and have a
`.backup_ns()` getter.

Note that the datastore's `Display` implementations are no
longer safe to use as a deserializable string.

Additionally, some datastore based methods now have been
exposed via the BackupGroup/BackupDir types to avoid a
"round trip" in code.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
1baf9030ad ui: datastore prune: support passing namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
2f5417f845 prune: allow passing namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
a7f5e64154 ui: datastore content: allow to create new namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
55ffd4a946 ui: utils: also provided me.SAFE_ID_RE
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
94135ccca2 ui: datastore content: allow to select namespace to show
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
968270ae3d ui: add namespace selector combobox
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
d45506d4a4 api: backup create: enforce that namespace exists
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
cabda57f0a api: backup create: make permission check namespace aware
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
7d6fc15b20 api: datastore: make permission checks namespace aware
We probably can combine the base permission + owner check, but for
now add explicit ones to upfront so that the change is simpler as
only one thing is done.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
18934ae56b api: namespace management endpoints
allow to list any namespace with privileges on it and allow to create
and delete namespaces if the user has modify permissions on the parent
namespace.

Creation is only allowed if the parent NS already exists.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
15a9272495 datastore: add max-depth to recursive namespace iter
on depth == 0 we only yield the anchor ns, this simplifies usage in
the API as for, e.g. list-snapthos the depth == 0 means only the
snapshots from the passed namespace, nothing below.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
08aa5fe7aa api: add NS_MAX_DEPTH_SCHEMA
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
 [ T: renamed from NAMESPACE_RECURSION_DEPTH_SCHEMA & moved to from
   jobs to datastore ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
e687d1b8ee api: add prefix-mapping helper to BackupNamespace
given a namespace, a source prefix and a target prefix this helper
strips the source prefix and replaces it with the target one (erroring
out if the prefix doesn't match).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
c12a075b83 api: derive UpdaterType for BackupNamespace
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
c5648f1920 config: acl tree: allow path components to be paths too
will be used for namespaces

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
dc3d716bdb datastore: add create_namespace
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
6dd8a2ced0 BackupNamespace: fix deserialize of root NS
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
be5b3ebfdd api-types: fixup backup-ns being optional
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
c18d481fd7 pbs-client: don't include empty backup-ns in requests
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
68857aecb3 client: add --ns parameter to snapshot list
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
352e13db9d api types: BackupNamespace add pop & parent helpers
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
220b66077c api-types: more regex fixups
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
2772159692 api-types: add missing slash in optional ns path regex
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
89ae3c3255 client: more backup namespace support
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
13d6de3787 datastore: include namespace in full_path
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
33f2c2a1bf api: add remaining missing backup-ns parameters
these are the ones for non-#[api] methods, also fill in the
namespace in prune operations

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
4c7cc5b39e datastore: add helpers to destroy whole namespaces
The behavior on "any snapshot was protected" isn't yet ideal, as we
then do not cleanup any (sub) namespace, even if some of them where
cleaned from groups & snapshots completely. But that isn't easy to do
with our current depth-first pre-order iterator behavior, and it's
also not completely wrong either, the user can re-do the removal on
the sub-namespaces, so leave that for later.

Should get moved to a datastore::BackupNamespace type once/if we get
one

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
90e3869690 datastore: add single-level and recursive namespace iterators
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
02ec2ae9b8 api types: namespace: add from_parent_ns helper
will be used in the (recursive) namespace iterator

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
c2425132c4 api types: namespace: include problematic component in error
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
11ffd737e3 datastore: add backup_ns accessor
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Wolfgang Bumiller
8c74349b08 api-types: add namespace to BackupGroup
Make it easier by adding an helper accepting either group or
directory

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
42103c467d ns: max depth: set constant to upper inclusive boundary
makes usage a bit simpler, e.g., the api maximum can use that 1:1
then.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
b68bd900c1 api-types: add BackupNamespace type
The idea is to have namespaces in a datastore to allow grouping and
namespacing backups from different (but similar trusted) sources,
e.g., different PVE clusters, geo sites, use-cases or company
service-branches, without separating the underlying
deduplication domain and thus blowing up data and (GC/verify)
resource usage.

To avoid namespace ID clashes with anything existing or future
usecases use a intermediate `ns` level on *each* depth.

The current implementation treats that as internal and thus hides
that fact from the API, iow., the namespace path the users passes
along or gets returned won't include the `ns` level, they do not
matter there at all.

The max-depth of 8 is chosen with the following in mind:
- assume that end-users already are in a deeper level of a hierarchy,
  most often they'll start at level one or two, as the higher ones
  are used by the seller/admin to namespace different users/groups,
  so lower than four would be very limiting for a lot of target use
  cases

- all the more, a PBS could be used as huge second level archive in a
  big company, so one could imagine a namespace structure like:
  /<state>/<intra-state-location>/<datacenter>/<company-branch>/<workload-type>/<service-type>/
  e.g.: /us/east-coast/dc12345/financial/report-storage/cassandra/
  that's six levels that one can imagine for a reasonable use-case,
  leave some room for the ones harder to imagine ;-)

- on the other hand, we do not want to allow unlimited levels as we
  have request parameter limits and deep nesting can create other
  issues as well (e.g., stack exhaustion), so doubling the minimum
  level of 4 (1st point) we got room to breath even for the
  more odd (or huge) use cases (2nd point)

- a per-level length of 32 (-1 due to separator) is enough to use
  telling names, making lives of users and admin simpler, but not
  blowing up parameter total length with the max depth of 8

- 8 * 32 = 256 which is nice buffer size

Much thanks for Wolfgang for all the great work on the type
implementation and assisting greatly with the design.

Co-authored-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Co-authored-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Thomas Lamprecht
77337b3b4c api types: BackupType: add iter for enum
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-12 09:33:50 +02:00
Fabian Grünbichler
b6c8717cc2 completion: fix 'group-filter' parameter name
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-10 12:06:34 +02:00
Fabian Grünbichler
dfea916ca7 proxmox-backup-manager: add limit to pull
seems to have been forgotten initially.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-10 11:54:50 +02:00
Thomas Lamprecht
d49025064c datastore: chunk store: leverage new format str variable reference
makes it often compact enough for rustfmt to move it into a single
line

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-10 09:46:51 +02:00
Dominik Csapak
dd612daab0 chunk_store: insert_chunk: write chunk again if it is empty on disk
and issue a warning. We can do this, because we know an empty chunk
cannot be valid, and we (assumedly) have a valid chunk in memory.

Having empty chunks on disk is currently possible when PBS crashes,
but the rename of the chunk was flushed to disk, when the actual data
was not.

If it's not empty but there is a size mismatch, return an error.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-10 08:47:40 +02:00
Dominik Csapak
8915c1e74a api: tape/restore: skip snapshot if owner check failed
instead of aborting the whole restore

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-09 13:56:16 +02:00
Dominik Csapak
c94d2867c1 api: tape/restore: fix wrong datastore locking
used_datastores returned the 'target', but in the full_restore_worker,
we interpreted it as the source and searched for a mapping
(which we then locked)

since we cannot return a HashSet of Arc<T> (missing Hash trait on DataStore),
we have now a map of source -> target

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-05-09 13:37:03 +02:00
Thomas Lamprecht
0b232f2edc drop mut on some http client usages
thanks to commit 70142e607dda43fc778f39d52dc7bb3bba088cd3 from
proxmox repos's proxmox-http crate

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-05 10:50:51 +02:00
Thomas Lamprecht
2c64201e64 update proxmox-http b-d to 0.6.1
so that we can drop some mut on http client usages

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-05 10:50:49 +02:00
Thomas Lamprecht
41c1a17999 router change made one level of rpcenv mut superfluous
Created via `cargo fix`.  see commit
47acc8dc8f68ed2c5db69b1678b479e05b0a3194 from proxmox-rs

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-05 10:00:29 +02:00
Thomas Lamprecht
aefbaa4dc6 update proxmox-router b-d to 1.2.2
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-05 09:54:18 +02:00
Thomas Lamprecht
60ed7aeae6 bump version to 2.1.8-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-02 17:36:22 +02:00
Fabian Grünbichler
29c56859b0 pull: add some comments
and remove already fixed fixmes.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
 [ T: squash in cargo fmt fixup for some trailing ws ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-02 14:10:26 +02:00
Fabian Grünbichler
aa07391764 pull: remove unnecessary pub visibility
pull_store is the entrypoint used by other code, the rest does not need
to be visible at all.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-02 14:09:56 +02:00
Fabian Grünbichler
df768ebea9 pull: filter local removal candidates by owner
else this might remove groups which are not part of the pull scope. note
that setting/using remove_vanished already checks the required privs
earlier.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-05-02 14:09:56 +02:00
Dominik Csapak
20814a3986 proxmox-backup-proxy: stop accept() loop on daemon shutdown
On reload the old process hands over to the new process but needs to
keep running until all its worker tasks are finished to avoid
breaking a in-progress action like a xterm.js web shell or a backup
creation/restore.

During that wait time the receiving channel was already closed, but
the TCP sockt accept listener was still left active by mistake.

That paired with the `SO_REUSEPORT` being set on the underlying
socket, made the kernel choose either the old or new process for new
incoming connections, both still listened for them after all and
reuse-port + multiple processes is often used as load-balancer
mechanism.

As the old proxy accepted connections but didn't process them anymore
one could observer sporadic connection failures on any API call, well
any new connection to the proxy, depending on which process got the
it assigned.

The fix is to stop accepting new connections one we shutdown, so poll
the shutdown_future too during accept and just exit the accept-loop
on shutdown.

Note: This part of the code, nor other parts that could influence it,
wasn't changed at all in recent times, so it's still unresolved for
why it pops up only now.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Co-authored-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
 [ T: add more (root cause) info and reword a bit ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-02 10:31:33 +02:00
Dominik Csapak
8550de7403 api: status: return gc-status again
Returning the GC status was dropped by mistake in commit 762f7d15
("datastore status: factor out api type DataStoreStatusListItem")

As this is considered a breaking change which we also felt, due to
the gc-status being used in the web interface for the datastore
overview list (not the dashboard), re add it.

Fixes: 762f7d15
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
 [ T: add reference to breaking commit, reword message ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-05-02 10:11:01 +02:00
Thomas Lamprecht
0f198b82f5 cargo fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-28 10:26:00 +02:00
Thomas Lamprecht
a0781d7b9e bump version to 2.1.7-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:54:28 +02:00
Hannes Laimer
f732942089 ui: add tooltip to datastore in maintenance mode
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Hannes Laimer
1b7479c968 ui: utils: add function for parsing maintenance mode
...since the same code is used is more than one place

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Hannes Laimer
fbd6f54f39 ui: update datastore list more often
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Hannes Laimer
adf5dcba8d ui: update icon in datastore list when in maintenance mode
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Hannes Laimer
e022d13cf3 api2: DataStoreListItem add maintenance info
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Hannes Laimer
dd09432a90 ui: add summary mask when in maintenance mode
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-27 19:21:19 +02:00
Dominik Csapak
6ddd69c5ce file-restore: add 'timeout' and 'json-error' parameter
timeout limits the code with the given timeout in seconds, and
'json-error' return json to stdout when the call returns an error like
this:

{
    "msg": "error message",
    "error": true,
    "code": <HTTP_STATUS_CODE>, // if it was an http error
}

with both options set, a client can more easily determine if the call
ran into a timeout (since it will return a 503 error), and can poll
it again

both is done behind new parameters, so that we can stay backwards-compatible

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:19:57 +02:00
Dominik Csapak
25be1fa0d7 file-restore: factor out 'list_files'
we'll want to reuse that in a later patch

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:19:57 +02:00
Dominik Csapak
8eaa46ffea restore-daemon: avoid auto-mounting zpools
the duration of mounting zpools not only correspond to the number of disks,
but also to the content (many subvols for example) which we cannot know
beforehand. so avoid mounting them at the start, and mount it only when
the user requests a listing/extraction with the zpool in path

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:19:57 +02:00
Dominik Csapak
4d76ab91e4 restore-daemon: put blocking code into 'block_in_place'
DISK_STATE.lock() and '.resolve()' can both block since they access
the disks. Putting them into a 'block_in_place' makes tokio move it
out in its own thread to avoid that the executor isn't able to
progress any other futures in the mean time.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:18:44 +02:00
Dominik Csapak
436a48d611 restore-daemon: start disk initialization in parallel to the api
this way, the vm can start up faster, and the actual disk init happens
in parallel. this avoids unnecessary timeouts when starting the vm

if the call panics, we still abort the vm with an error

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-27 19:18:44 +02:00
Thomas Lamprecht
274ac755a1 api types: datastore status: reword doc comment of estimated_full_date
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-25 11:48:25 +02:00
Thomas Lamprecht
579362f743 ui: update generated OnlineHelpInfo map
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-25 10:17:21 +02:00
Stefan Sterz
f3b02a9b86 fix #3067: ui: add a separate notes view for longer markdown notes
since markdown notes might be rather long, this commit adds a tab
similar to pve's datacenter or node notes. requires a bump of the
widget toolkit in order to use the `pmxNotesView`.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
2022-04-25 08:39:39 +02:00
Stefan Sterz
684a402931 fix #3067: docs: add markdown primer from pve to pbs
this copies the markdown primer from the pve docs to allow access to
it via the help buttons in the gui

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
2022-04-25 08:39:39 +02:00
Thomas Lamprecht
1eef52c206 datastore: move blob loading into BackupDir impl and adapt call sites
data blobs can only appear in a BackupDir (snapshot) in the backup
hierachy, so makes more sense that it lives in there.

As it wasn't widely used anyway it's easy to move the single
non-package call site over to the new one directly and drop the
implementation from Datastore completely.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 20:16:58 +02:00
Thomas Lamprecht
f03649b8f3 datastore: move destroying group or dir into respective impl
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 20:14:39 +02:00
Thomas Lamprecht
5c9c23b6b2 datastore: move manifest locking into BackupDir impl
the manifest is owned by the backup dir (snapshot) so it should also
handle locking, makes no sense to have the implementation somewhere
higher up.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 20:10:43 +02:00
Thomas Lamprecht
b298e9f16e datastore: s/fail_if_not_exist/assert_exists/
avoid putting whole sentences in parameter names

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 20:10:34 +02:00
Thomas Lamprecht
cc295e2c7a datastore: improve backup group/snapshot iters
move the check for directory before doing the OSString -> String
conversion, which should be a bit more efficient.

Also let the match return the entry in the non-skip/return case to
reduce indentation level for the inner "yield element" part, making
it slightly easier to follow.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 20:02:58 +02:00
Thomas Lamprecht
4b77d300a2 datastore: replace manual path assembly by group/dir full_path
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 19:57:20 +02:00
Thomas Lamprecht
df5c6a11cd datastore: list snapshots iter: report group dir in error
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-24 19:57:10 +02:00
Dominik Csapak
07a683d266 pbs-client: extract: add top-level dir in tar.zst
when download a folder, include that folder as first entry (except '/')

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-22 11:35:55 +02:00
Dominik Csapak
7098f5d885 pbs-client: extract: rewrite create_zip with sequential decoder
instead of an async recursive function. Not only is it less code,
recursive futures are not really nice and it should be faster too.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-22 11:35:53 +02:00
Thomas Lamprecht
f37d8540e1 server pull: fix comment w.r.t. initial downloaded chunk capacity
> The hash set will be able to hold at least capacity elements
> without reallocating. If capacity is 0, the hash set will not
> allocate.
-- rustdoc, HashSet::with_capacity

So, the number we pass is the amount of chunk "IDs" we safe, which is
then 64Ki, not 16Ki and thus the size we can reference too is also
256 GiB, not 64 GiB.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-21 15:55:03 +02:00
Dietmar Maurer
eb1cd24e21 pbs-tape: sgutils2: check sense data when status is 'CHECK_CONDITION'
Some raid controllers return a 'transport error' when we expected a
'sense error'. it seems the correct way to check the sense data is when
either the result category is 'SENSE' or when the status is 'CHECK_CONDITION',
so do that. (similar to how 'sg_raw' returns the errors)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-04-21 09:35:52 +02:00
Wolfgang Bumiller
6da20161f0 reference the datastore in BackupGroup/Dir
And drop the base_path parameter on a first bunch of
functions (more reordering will follow).

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 15:31:04 +02:00
Wolfgang Bumiller
bb628c295a api-types: DataStoreConfig::new for testing
so our examples can more easily access a datastore without
going over a configuration & cache

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 15:31:04 +02:00
Fabian Grünbichler
2c88dc97fd api2: read_remote: also return RemoteWithoutPassword
like for the index, instead of manually stripping it.

this (and the previous change) is backwards-compatible since `Remote`
already skipped serializing empty strings, so the returned JSON is
identical.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-04-20 13:58:41 +02:00
Wolfgang Bumiller
6b0c6492f7 datastore: cleanup and document backup group/dir openers
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 13:24:57 +02:00
Wolfgang Bumiller
10a0059602 datastore: drop Hash from BackupGroup
same as for Eq/Ord/...

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 13:08:44 +02:00
Wolfgang Bumiller
5203cfcff9 datastore: drop PartialEq and PartialOrd from BackupGroup
Same as previous commits: this will be linked to a
particular DataStore and Eq/Ord is now only part of the
api types, for now.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 12:23:14 +02:00
Wolfgang Bumiller
cf320b6ba1 datastore: drop Eq and PartialEq from BackupDir
Same as previous commit: this is supposed to be connected to
a datastore and Eq/PartialEq only make sense for the
api-type part.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 12:22:57 +02:00
Wolfgang Bumiller
5116453b6d datastore: drop Ord from BackupGroup
This one is supposed to be linked to a datastore instance,
so it won't be Ord for now.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 12:20:30 +02:00
Wolfgang Bumiller
db87d93efc make datastore BackupGroup/Dir ctors private
And use the api-types for their contents.

These are supposed to be instances for a datastore, the pure
specifications are the ones in pbs_api_types which should be
preferred in crates like clients which do not need to deal
with the datastore directly.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 11:56:23 +02:00
Wolfgang Bumiller
38aa71fcc8 api-types: use BackupType for GroupFilter::BackupType
instead of a string

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 11:49:01 +02:00
Wolfgang Bumiller
1f6a45c938 rename BackupDir's group_path to relative_group_path
datastore's group_path will be moved to BackupDir soon and
this is required to be able to properly distinguish them

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 10:04:02 +02:00
Wolfgang Bumiller
b444eb68af api-types: datastore type improvements
let BackupGroup implement Hash

let BackupGroup and BackupDir be AsRef<BackupGroup>
let BackupDir be AsRef<BackupDir>

the pbs-datastore types will implement these AsRefs as well

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 10:03:39 +02:00
Wolfgang Bumiller
2d5c20c8f5 datastore: remove unused list_files function
it also doesn't belong into this type

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 10:00:33 +02:00
Wolfgang Bumiller
c4b2d26cdb datastore: move last_backup from BackupInfo to BackupGroup
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-20 10:00:25 +02:00
Dietmar Maurer
fe94c9962e AuthId: derive Ord and PartialOrd
So the we can sort...

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-04-20 09:58:52 +02:00
Dietmar Maurer
24cb5c7a81 RemoteWithoutPassword: new API type
To make it explicit that we do not return the password.

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-04-20 09:42:46 +02:00
Wolfgang Bumiller
988d575dbb api-types: introduce BackupType enum and Group/Dir api types
The type is a real enum.

All are API types and implement Display and FromStr. The
ordering is the same as it is in pbs-datastore.

Also, they are now flattened into a few structs instead of
being copied manually.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 13:12:46 +02:00
Thomas Lamprecht
33eb23d57e datastore: add snapshot iterator and provide example
will be more used in the future, when the upend-datastore master plan
comes in effect.

also a preparatory work for namespaces

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
249dde8b63 backup: switch over to streaming Iterator improving memory usage
Avoid collecting the whole group list in memory only to iterate and
filter over it again.

Note that the change could result in a indentation change, so best
viewed with `-w` flag.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
7b125de3e1 datastore: add helper to get a iterator for backup groups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
de015ce7e1 datastore: implement Iterator for backup group listing
While currently it's still only used in a collected() way, most call
sites can be switched over to use the iterator directly, as often
they already convert the not-so-cheap, in-memory vector back in
.into_iter() anyway.

somewhat also preparatory (yak shaving) work for namespaces

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
72f8154571 api datastore: some code cleanups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
693f3285eb datastore: backup info: drop deprecated list_backup_groups
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
7d9cb8c458 replace deprecated list_backup_group from BackupInfo with Datastore one
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
c90dbb5c7b datastore: move list_backup_groups into Datastore impl
Having that as static method in BackupInfo makes zero sense and just
complicates call sites, which need to extract the base_path from the
store manually upfront.

Mark old fn as deprecated so that we can do the move in a separate
step.

It's also planned to add an Iterator impl for this to allow more
efficient usage in the future.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-15 12:38:16 +02:00
Thomas Lamprecht
bdfa637058 client: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 14:25:05 +02:00
Thomas Lamprecht
f9a5beaa15 backup client: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 14:06:15 +02:00
Thomas Lamprecht
00ae34dfda tools: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 14:05:17 +02:00
Thomas Lamprecht
9531d2c570 rust fmt for pbs src
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 14:03:46 +02:00
Thomas Lamprecht
ee0ea73500 server: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 14:01:25 +02:00
Thomas Lamprecht
dc7a5b3491 api: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 13:33:01 +02:00
Thomas Lamprecht
35f151e010 config: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 13:32:04 +02:00
Thomas Lamprecht
42c2b5bec9 datastore: rustfmt whole package
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 13:27:53 +02:00
Thomas Lamprecht
fb3c007f8a d/changelog: fixup released
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-14 09:48:00 +02:00
Thomas Lamprecht
ff7568f1d9 bump version to 2.1.6-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-13 17:31:21 +02:00
Thomas Lamprecht
1fd46218ea cli: tape key-restore: print more info for better ux
as getting the marker error if we passed valid json (but not valid
key) is confusing

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-13 16:59:47 +02:00
Thomas Lamprecht
ede9dc0d1a api: tape key restore: fix optional param handling and code refactoring
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-13 16:59:47 +02:00
Markus Frank
ae60eed310 proxmox-tape: api: restore_key-code moved to tape-encryption-keys
The restore_key api-endpoint is tape/drive/{drive}/restore-key.
Since I cannot set the url parameter for the drivename to null or
undefined, when restoring by exported-key, I moved the
added restore_key-api-code to
"create_key aka POST api2/json/config/tape-encryption-keys" and
added an ApiHandler call in the cli's "restore_key" to call
"create_key" in the api.

Signed-off-by: Markus Frank <m.frank@proxmox.com>
2022-04-13 16:31:17 +02:00
Wolfgang Bumiller
e3746a329e pbs-client: pxar: avoid some more clones
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:30:40 +02:00
Wolfgang Bumiller
7546e9c997 pbs-client: pxar: avoid some vec extensions
The `Components` `Iterator` has an `as_path()` method to get
the remainder as a borrowed path. This is more efficient
iterating and joining the components into a new `PathBuf`.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:28:01 +02:00
Wolfgang Bumiller
0bb4036f25 pbs-client: pxar: drop link_to_pathbuf
pxar's Hardlink and Symlink structs implement `AsRef<OsStr>`
and have an `.as_os_str()` method.

Simply use `Path::new(link)`.

Also, the function was not very well written, and we don't
always need an owned copy.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:18:31 +02:00
Wolfgang Bumiller
84d3af3a0e pbs-client: pxar: fmt
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:17:20 +02:00
Dominik Csapak
055eab54ff ui: datastore/Content: enable tar download in ui
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:08:34 +02:00
Dominik Csapak
984ddb2ff2 api: admin/datastore: add tar support for pxar_file_download
by using the newly added 'create_tar' and the 'ZstdEncoder'

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:08:26 +02:00
Dominik Csapak
23af572d3f pbs-client: add 'create_tar' helper function
similar to create_zip, uses an accessor to write a tar into an output
that implements AsyncWrite, but we use a Decoder to iterate instead
of having a recursive function. This is done so that we get the
entries in the correct order, and it should be faster as well.

Includes files, directories, symlinks, hardlink, block/char devs, fifos
into the tar. If the hardlink points to outside the current dir to
archive, promote the first instance to a 'real' file, and use a
hardlink for the rest.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 10:05:08 +02:00
Wolfgang Bumiller
99f09fd3c1 bump proxmox-compression dependency to 0.1.1
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 09:37:20 +02:00
Wolfgang Bumiller
da7a71115c bump d/control
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:21:18 +02:00
Wolfgang Bumiller
ebb85c1ca3 bump proxmox-schema dependency to 1.3.1 for streaming attribute
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:20:27 +02:00
Wolfgang Bumiller
fb6e48f402 bump proxmox-router dependency to 1.2
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:17:08 +02:00
Dominik Csapak
b7c3eaa981 api: admin/datastore: enable streaming for some api calls
namely /admin/datastore/{store}/snapshots
and /nodes/{node}/tasks

since those are api calls where the result can get quite large
with this change, the serialization is now streaming instead of making
a `Value` in memory.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:13:42 +02:00
Dominik Csapak
32e2b5abe6 adapt to the new ApiHandler variants
namely 'StreamingSync' and 'StreamingAsync'
in rest-server by using the new formatter function,
and in the debug binary by using 'to_value'

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:13:40 +02:00
Dominik Csapak
2ef2c0fe0c proxmox-rest-server: OutputFormatter: add new format_data_streaming method
that takes the data in form of a `Box<dyn SerializableReturn + Send>`
instead of a Value.

Implement it in json and extjs formatter, by starting a thread and
stream the serialized data via a `BufWriter<SenderWriter>` and use
the Receiver side as a stream for the response body.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-13 08:13:36 +02:00
Thomas Lamprecht
9c3b29bd8f ui: datastore options: maintenance mode related refactorings
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 16:54:56 +02:00
Thomas Lamprecht
3c8f240712 ui: datastore options: fix active-ops-tracking store leak
without this the store stayed active in the background and kept
updating every 3s for every datastore the ui was opened.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 16:21:41 +02:00
Thomas Lamprecht
6353e22c00 ui: datastore options: factor out update stop/start to controller
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 16:18:43 +02:00
Wolfgang Bumiller
38774184a9 tree-wide: replace serde_json::from_value(a_value.clone())
`&Value` itself implements `Deserializer` and can therefore
be passed directly to `T::deserialize` without requiring an
intermediate `clone()`. (This also enables optionally
borrowing strings if the result has a short enough lifetime)

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-12 16:12:15 +02:00
Thomas Lamprecht
845baef61b ui: maintenance mode: also render message
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 16:12:15 +02:00
Thomas Lamprecht
73ce2ae1c7 ui: maintenance mode: refactor renderer
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 16:12:12 +02:00
Hannes Laimer
556eda0537 ui: add option to change the maintenance type
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Hannes Laimer
5fd823c3f2 api: add get_active_operations endpoint
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Hannes Laimer
758c6ed588 api: make maintenance_type updatable
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Hannes Laimer
4bc84a6549 pbs-datastore: add active operations tracking
Saves the currently active read/write operation counts in a file. The
file is updated whenever a reference returned by lookup_datastore is
dropped and whenever a reference is returned by lookup_datastore. The
files are locked before every access, there is one file per datastore.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Hannes Laimer
e9d2fc9362 datastore: add check for maintenance in lookup
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Hannes Laimer
2a05c75ff1 api-types: add maintenance type
+ bump proxmox-schema dep to 1.2.1 (for quoted property string)

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-04-12 15:29:14 +02:00
Thomas Lamprecht
66b88dadba ui: node config: avoid split listeners
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-12 15:29:03 +02:00
Wolfgang Bumiller
9ee2ef2e55 client: drop unnecessary clone
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-12 12:34:52 +02:00
Thomas Lamprecht
12558e0dde tree wide: some stylistic clippy fixes
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-11 08:14:28 +02:00
Thomas Lamprecht
b22d785c18 api types: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 18:00:18 +02:00
Thomas Lamprecht
4ad118c613 cli: backup manager: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 17:50:35 +02:00
Thomas Lamprecht
6082d75966 tests: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 17:49:26 +02:00
Thomas Lamprecht
4de1c42c20 tape: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 17:49:03 +02:00
Thomas Lamprecht
429bc9d0a2 restore daemon: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 17:47:20 +02:00
Thomas Lamprecht
a22d338831 examples: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-10 17:44:34 +02:00
Thomas Lamprecht
1e724828b4 rest server: log rotation: refactor and comment improvements
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-07 14:04:18 +02:00
Thomas Lamprecht
40853461d1 rest server: log rotation: fix off-by-one for max_days
The entries in a file go from oldest end-time in the first time to
newest end-time in the last line. So, just because the first line is
older than the cut-off time, the remaining one doesn't necessarily
have to be old enough too. What we can know for sure that older than
the current checked rotations of the task archive are definitively up
for deletion.

Another possibility would be to check the last line, but as scanning
backwards is more expensive/complex to do while only being an actual
improvement in a very specific edge case (it's more likely to have a
mixed time-cutoff vs. task-log-file boundary than that those are
aligned)

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-07 12:58:32 +02:00
Dominik Csapak
416194d799 rest-server: add option to rotate task logs by 'max_days' instead of 'max_files'
and use it with the configurable: 'task_log_max_days' of the node config

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-06 17:12:49 +02:00
Dominik Csapak
eb419c5267 config/node: add 'task_log_max_days' config
to be able to configure the maximum days to keep task logs

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-06 17:10:02 +02:00
Dominik Csapak
baefc29544 rest-server: cleanup_old_tasks: improve error handling
by not bubbling up most errors, and continuing on. this avoids that we
stop cleaning up because e.g. one directory was missing.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-06 17:10:02 +02:00
Thomas Lamprecht
b23adfd4ee pbs tape: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 17:00:29 +02:00
Thomas Lamprecht
a527b54f84 pbs fuse loop: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:59:54 +02:00
Fabian Ebner
b2df21bb02 docs: client: file exclusion: add note about leading slash
It's not documented yet and not intuitive:
https://forum.proxmox.com/threads/98810
https://forum.proxmox.com/threads/107143

Signed-off-by: Fabian Ebner <f.ebner@proxmox.com>
2022-04-06 16:59:00 +02:00
Fabian Ebner
2b323a359d pxar: create: add entry: fix anchored path pattern matching
Similar to 874bd545 ("pxar: fix anchored exclusion at archive root"),
but this time for inclusion. Because of the inconsistency, it could
happen that a file included in generate_directory_file_list() got
excluded in add_entry(), e.g. with a .pxarexclude file like
> *
> !/supposed-to-be-included

Reported-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Fabian Ebner <f.ebner@proxmox.com>
2022-04-06 16:58:08 +02:00
Thomas Lamprecht
48fcee6a50 pxar bin: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:58:04 +02:00
Thomas Lamprecht
c650378a39 pbs build config: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:57:36 +02:00
Thomas Lamprecht
40ea990c05 file restore: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:57:07 +02:00
Thomas Lamprecht
aaaa10894d rrd: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:56:33 +02:00
Thomas Lamprecht
41583796b1 rest server: rust fmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:55:39 +02:00
Wolfgang Bumiller
b300e6fbc2 use BufReader/Writer for Files passed to serde_json::from_reader/writer
As serde_json will otherwise read files 1 byte at a time.
Writing is a bit better, but syntacitcal elements (quotes, braces,
commas) still often show up as single write syscalls, so use BufWriter
there as well.

Note that while we do store the file in the resulting objects, we do not
need to keep the buffered read/writers as we always `seek` to the
beginning on further file operations.

Reported-by: Mark Schouten <mark@tuxis.nl>
Link: https://lists.proxmox.com/pipermail/pbs-devel/2022-April/004909.html
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-04-06 16:40:35 +02:00
Thomas Lamprecht
085ae87380 api: tape: rust format
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:31:49 +02:00
Thomas Lamprecht
938a1f137c cli: tape: rust format
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:27:32 +02:00
Thomas Lamprecht
5525ec246f tape: key recovery: refcator and split string/file case for cli params
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-04-06 16:25:34 +02:00
Markus Frank
b676dbce78 fix #3854 paperkey import to proxmox-tape
added a parameter to the cli for importing tape key via a json-parameter or
via reading a exported paperkey-file or json-file.
For this i also added a backupkey parameter to the api, but here it only
accepts json.

The cli interprets the parameter first as json-string, then json-file
and last as paperkey-file.

functionality:
proxmox-tape key paperkey [fingerprint of existing key] > paperkey.backup
proxmox-tape key restore --backupkey paperkey.backup # key from line above
proxmox-tape key restore --backupkey paperkey.json # only the json
proxmox-tape key restore --backupkey '{"kdf": {"Scrypt": ...' # json as string

for importing the key as paperkey-file it is irrelevant, if the paperkey got exported as html
or txt.

Signed-off-by: Markus Frank <m.frank@proxmox.com>
2022-04-06 13:39:56 +02:00
Dominik Csapak
7c22932c64 pbs-client: print error when we couldn't download previous fidx/didx
When we have a previous manifest, we try to download the fidx/didx files
to get the known chunks list. We continue if that fails (which is ok),
but we did not print any error, leading to a confusing backup output,
since the users would expect that chunks will be reused.

Printing the error should at least make it apparent that something did
not work correctly.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-04-06 10:12:29 +02:00
Stefan Sterz
2b422b82fb fix #3067: api: add support for multi-line comments in node.cfg
add support for multi-line comments to node.cfg and the api, similar to
how pve handles multi-line comments

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
Acked-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-23 10:43:43 +01:00
Wolfgang Bumiller
9e2b423e27 tools: improve PhantomData usage
The ticket doesn't contain a `T`, it's stringified. We only
produce a new T when verifying.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-22 12:41:14 +01:00
Dominik Csapak
39ffb75d91 api: datastore_status: restore api/gui compatibility
the latest changes to this api call changed/removed some things that
were actually necessary for the gui. Readd those and document them this
time.

The change from u64 to i64 limits us to 8EiB of Datastore sizes (instead if
16EiB) but if we reach that, we must adapt most other parts to use 128bit
sizes anyway

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-03-22 10:31:25 +01:00
Dietmar Maurer
762f7d15dc datastore status: factor out api type DataStoreStatusListItem
And use the rust type instead of json::Value.
2022-03-20 09:38:50 +01:00
Markus Frank
80ab05e40c fix #3934 tape owner-selector to Authid
changed pmxUserSelector to pbsAuthidSelector, because it is currently
not possible to restore with a api token via gui.

Signed-off-by: Markus Frank <m.frank@proxmox.com>
2022-03-17 10:13:18 +01:00
Stefan Sterz
e099bd0717 ui: fix panel height in the dashboard
this fixes an issue where the layout looks misaligned in three column
layouts

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
2022-03-11 12:52:50 +01:00
Stefan Sterz
171a00ca97 tape, docs, api: fix miscellaneous typos
Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-03-11 12:52:06 +01:00
Wolfgang Bumiller
c8322f8a33 config: don't manually track padding size
make ConfigVersionCacheData a #[repr(C)] union to fix its
size and let it transparently `Deref{,Mut}` to its actual
contents

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-10 10:32:46 +01:00
Thomas Lamprecht
eb080f361a docs: tape: minor wording tweaks
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-03-09 10:44:37 +01:00
Dominik Csapak
bd0300917e docs: improve tape-backup examples
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-03-09 10:44:37 +01:00
Wolfgang Bumiller
787c6550d4 proxmox-backup-debug api: fewer cloning
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-09 10:10:54 +01:00
Dominik Csapak
c6140c62ab proxmox-backup-debug api: rustfmt fixes
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-09 10:10:54 +01:00
Dominik Csapak
9735f5de84 proxmox-backup-debug api: parse parameters before sending to api
when we use http to make the api call, we have to parse the parameters
before, else we might send the string "true" instead of the boolean true
and the api rejects it with a 'Parameter verification error'.

We already have all api call schemas here, so parsing is possible.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-09 10:10:54 +01:00
Fabian Grünbichler
a07ace0d1e regex: bump to 1.5.5
to ensure CVE fix for DoS on untrusted RE is picked up where it matters

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-03-09 09:55:36 +01:00
Dominik Csapak
904ce33d9f tools: parse_objset_stat: drop the unecessary 'objset-' from the log
'objset_id' already contains that, so the error was
"could not parse 'objset-objset-0xFFFF' stat file"

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-08 09:13:05 +01:00
Dominik Csapak
6dd5944772 tools: zfs_dataset_stats: remove dataset <-> obset file mapping on error
this can only real fail for two reasons:
* the format is wrong:
    this should not happen unless the format changed, then it will
    happen every time
* the file can't be read:
    this can happen if a user deletes and recreates a dataset manually,
    since the mapped file does not exist anymore but the dataset does

for the second case, delete the mapping from the hashmap, so that the
next call will refresh the mapping with the correct file

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-08 09:12:52 +01:00
Dominik Csapak
dcd1518e10 api/config: use http_bail for 'not found' errors
the api should return a 404 error for entries that do not exist

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-08 09:09:25 +01:00
Dominik Csapak
8d6425aa24 api/config: use param_bail for parameter errors
when using the 'extjs' formatter, it marks them in a way, so that
the gui can mark the form fields with the error

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-08 09:09:22 +01:00
Dietmar Maurer
4042eedf18 Username schema: set min_length to 1
Just to get a better error message (the regex already requires min_length 1)

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-03-07 13:47:06 +01:00
Dietmar Maurer
1c8efc0062 cleanup: move BasicRealmInfo to pbs-api-types
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-03-07 08:06:55 +01:00
Wolfgang Bumiller
a9a15a9ab4 bump d/control
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-04 09:53:41 +01:00
Wolfgang Bumiller
bd4562e4b1 bump proxmox-schema dep to 1.3
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-03-04 09:50:21 +01:00
Thomas Lamprecht
e1f9553f2d pbs-config: improve semi-useful comment
commenting that version_cache.increase_datastore_generation increases
the, well, version is rather superfluous. Also avoid the use of "we",
which is always ambiguous in code comments.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-03-01 09:54:39 +01:00
Dominik Csapak
118deb4db8 pbs-datastore: use ConfigVersionCache for datastore
instead of relying on the content of some configs

previously, we always read and parsed the config file, and only
generated a new config object when the path or the 'verify-new' option
changed.

now, we increase the datastore generation on config save, and if that
changed (or the last load is 1 minute in the past), we always
generate a new object

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-03-01 08:16:27 +01:00
Dominik Csapak
9c96e5368a docs: add tape schedule examples
just a few examples how one could configure tape pools and jobs.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-03-01 08:10:53 +01:00
Dominik Csapak
83b5076dce docs: explain retention time for event allocation policy in more detail
'when the calendar event' triggers was too vague, it could mean for
the current media-set or the next time. Apart from that, it was not
technically correct all the time, since we take the start time of
the next media set if that exists first.

The idea here is that we begin the retention when the media set is
finished.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-03-01 08:08:18 +01:00
Dominik Csapak
fef61684b4 datastore: add tuning option for chunk order
currently, we sort chunks by inode when verifying or backing up to tape.
we get the inode# by stat'ing each chunk, which may be more expensive
than the gains of reading the chunks in order

Since that is highly dependent on the underlying storage of the datastore,
introduce a tuning option  so that the admin can tune that behaviour
for each datastore.

The default stays the same (sorting by inode)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-02-23 09:06:03 +01:00
Thomas Lamprecht
118f8589a9 client cli: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-22 11:50:46 +01:00
Thomas Lamprecht
c2f84841b6 bin: daily-update: use syslog/log crates instead of printing to stderr
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-22 10:58:44 +01:00
Thomas Lamprecht
b0728103b6 bin: daily-update: make single checks/updates fail gracefully
avoid that the acme renewal is skipped due to bailing out earlier
from a subscription or apt update error.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-22 10:27:00 +01:00
Thomas Lamprecht
00d41438b9 bin: daily-update: use from_millis instead of big nanosecond value
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-22 10:25:40 +01:00
Thomas Lamprecht
50654b22df bin: daily-update: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-21 15:52:28 +01:00
Wolfgang Bumiller
d96c7da31f bump d/control
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-21 14:25:54 +01:00
Wolfgang Bumiller
9c890d72b9 bump proxmox-async dep to 0.4
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-21 14:25:37 +01:00
Wolfgang Bumiller
229c1788c1 bump proxmox-lang dep to 1.1
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-21 14:24:24 +01:00
Dominik Csapak
f26d7ca5c5 use io_format_err, io_bail, io_err_other from proxmox-lang
and move the comment from the local io_bail in pbs-client/src/pxar/fuse.rs
to the only use

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-21 14:24:13 +01:00
Dominik Csapak
b066586a47 depend on new 'proxmox-compression' crate
the compression utilities live there now

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-21 14:23:43 +01:00
Thomas Lamprecht
0d7873cf09 cargo: bump schema dependency
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-18 15:04:22 +01:00
Thomas Lamprecht
667476f19d cli client: backup: better use of our api macro capabilities
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-18 15:04:22 +01:00
Thomas Lamprecht
a1b800c232 cli client: backup: refactor/cleanup of (dry-run) logs
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-18 15:04:22 +01:00
Markus Frank
4b8395ee0e fix #3323: cli client: add dry-run option for backup command
adds a dry-run parameter for "proxmox-backup-client backup".
With this parameter on it simply prints out what would be uploaded,
instead of uploading it.

Signed-off-by: Markus Frank <m.frank@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-18 15:04:22 +01:00
Dominik Csapak
dcd9c17fff tape/pool_writer: skip already backed up chunks in iterator
currently, the iterator goes over *all* chunks of the index, even
those already backed up by a previous snapshots in the same tape
backup. this is bad since for each iterator, we stat each chunk to
sort by inode number. so to avoid stat'ing the same chunks over
and over for consecutive snapshots, add a 'skip_fn' to the iterator
and in the pool writer and check the catalog_set if we can skip it

this means we can drop the later check for the catalog_set
(since we don't modify that here)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-02-18 10:40:41 +01:00
Thomas Lamprecht
f30757df50 rrd: extract data: avoid always calculating start-time fallback
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-15 07:59:55 +01:00
Thomas Lamprecht
ac20cb1f65 rrd: avoid intermediate index, directly loop over data
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-15 07:59:55 +01:00
Thomas Lamprecht
c19af51ecb rrd cache: code style, avoid useless intermediate mutable
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-15 07:59:12 +01:00
Dietmar Maurer
d6644e29fe move src/shared_rate_limiter.rs to src/tools/shared_rate_limiter.rs
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-02-14 14:57:56 +01:00
Dietmar Maurer
260147bd73 ParallelHandler: avoid re-export (cleanup)
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-02-14 14:12:39 +01:00
Dietmar Maurer
e705b3057f rename cached_traffic_control.rs to traffic_control_cache.rs, improve dev docs
Keep things inside crate::traffic_control_cache (do not pollute root namespace).

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-02-14 13:45:44 +01:00
Dietmar Maurer
192ece47fb rrd_cache: add developer docs
and make RRD_CACHE private (please use get_rrd_cache instead).

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-02-14 12:07:10 +01:00
Thomas Lamprecht
7739004815 ui: fixup title case
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-14 11:37:49 +01:00
Matthias Heiserer
11363a6a69 ui: node options: add support for selecting default language
Allows setting the default language in Configuration/Other/General

Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-14 11:37:26 +01:00
Stefan Sterz
41adda1c64 fix #3853: tape cli: add force flag to key change-passphrase
Adds the '--force' flag to the proxmox-tape command allowing users
with root privileges to overwrite the passphrase of a given key.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
2022-02-14 09:52:20 +01:00
Stefan Sterz
77d6d7a22c fix #3853: api: add force option to tape key change-passphrase
When force is used, the current passphrase is not required. Instead
it will be read from the file pointed to by TAPE_KEYS_FILENAME and
the old key configuration will be overwritten using the new
passphrase. Requires super user privileges.

Signed-off-by: Stefan Sterz <s.sterz@proxmox.com>
2022-02-14 09:52:20 +01:00
Wolfgang Bumiller
5b93835744 rest-server: bump schema to 1.2 and use convenience methods
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-11 14:09:45 +01:00
Wolfgang Bumiller
fd7f760304 proxmox-rest-server: add missing 'derive' feature
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-11 13:57:48 +01:00
Thomas Lamprecht
af6fdb9d0d tools: disk: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-10 18:39:56 +01:00
Thomas Lamprecht
a1c906cb02 api: node/disk: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-10 13:12:15 +01:00
Fabian Grünbichler
dcf5a0f62d misc clippy fixes
the trivial ones ;)

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-02-08 14:57:16 +01:00
Aaron Lauterer
bb9e503964 report: add tape, traffic control and disk infos
Signed-off-by: Aaron Lauterer <a.lauterer@proxmox.com>
2022-02-07 15:37:06 +01:00
Aaron Lauterer
b2fc573a62 report: move subscription info further up
This is something that is checked all the time. Having it further up
saves on scrolling and brings it into better alignment with PVE & PMG
regarding where in the report the info is located.

Signed-off-by: Aaron Lauterer <a.lauterer@proxmox.com>
2022-02-07 15:37:06 +01:00
Matthias Heiserer
415da09826 node config: add english to translation enum for default-lang
Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-07 15:24:38 +01:00
Matthias Heiserer
5ffa68d2c4 api: node config: add default-lang integration
Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-07 15:24:38 +01:00
Thomas Lamprecht
e7668a3eea ui: webauthn: decrease upgrade frequency from 1s to 2.5s
this is nothing to important and nothing that'll get changed *that*
often, so 2.5s is more than enough.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-07 15:20:22 +01:00
Thomas Lamprecht
21898bb831 ui: webauthn: fix stopping store upgrades on destroy
`deactivate` is only triggered if we switch to a different tab on
the same navigation level, but if we switch to a completely different
component (e.g., fom `Options -> Others` to `Datastore foo`) we can
only work with the destroy event, use the before one as else we
cannot access the view controllers method anymore.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-07 15:19:47 +01:00
Dominik Csapak
7b944ff11a re-use PROXMOX_DEBUG env variable to control log level filter
So that we can make 'log::debug' messages actually appear in the
syslog.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-04 11:21:47 +01:00
Markus Frank
fce49eab30 fix #3856 hint parameter is not optional
For the API the parameter --hint is not optional. This patch fixes
the man page and cli command doesn't send an API call, if the
parameter does not exist.

Signed-off-by: Markus Frank <m.frank@proxmox.com>
2022-02-03 14:49:25 +01:00
Thomas Lamprecht
af35bc8b9c proxy: refactor gui-language logic
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-03 13:12:02 +01:00
Thomas Lamprecht
e5e48b01ad rest: add cookie_from_header helper
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-03 13:12:02 +01:00
Thomas Lamprecht
5d74f79643 proxy: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-03 13:12:02 +01:00
Matthias Heiserer
b0427dda76 docs: fix typo in tape backup
Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
2022-02-03 13:12:02 +01:00
Thomas Lamprecht
70ba718ce9 node config: avoid "allow" annotation
We rename those anyway for serialization so we do not need to bother
with spelling them in an non-idiomatic way just because i18n has it
like that.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-02-03 13:12:02 +01:00
Matthias Heiserer
68811af9f9 fix #3103. node config: allow to configure default UI language
This language is only used if none is set in the cookies.

Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
2022-02-03 13:12:02 +01:00
Wolfgang Bumiller
163629e62e bump proxmox-acme-rs dependency to 0.4
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-02-02 13:18:47 +01:00
Dominik Csapak
1993d98695 traffic-control: use SocketAddr from 'accept()'
instead of getting the 'peer_addr()' from the socket.
The advantage is that we must get this and thus can drop the mapping
from result -> option, and can drop the testing for None and a test case

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-31 09:58:14 +01:00
Dominik Csapak
127c5ac3a9 ui: datastore/Content: improve verification actions
verifying a single snapshot is now never skipped because of recent verify
verifying a group will now reverify after 29 days to be consistent
with the 'All OK (old)' display

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-27 15:31:55 +01:00
Dominik Csapak
7a1a5d206d verify: allow '0' days for reverification
and let it mean that we will always reverify

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-27 15:31:55 +01:00
Thomas Lamprecht
7a524f1048 bump version to 2.1.5-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-26 16:24:11 +01:00
Thomas Lamprecht
1d3b253721 README: update for bullseye
and start with a higher level for "h1" headlines

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-26 16:19:21 +01:00
Thomas Lamprecht
1f8b29f578 file restore: scale per-round delay up dynamically
Avoids latency for restore-VMs that are finished fast but not ready
yet the first round while not checking to often for slower ones, iow,
we assume that the start up distribution is looking like a chi-square
Χ² with k=3.

With 25*round we get at max 45 rounds totalling to 25.875 s delay and
1.125 max between-round delay, which still provides an ok reaction
time.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-26 16:12:58 +01:00
Thomas Lamprecht
48ce3d00a4 file restore: always wait up to 25s
the timeout for connecting may be much shorter if we get a response
(which doesn't needs to be Ok, e.g., "Connection refused"), so
instead of trying a fixed amount of 60 times lets try for 25s
independent of how often that will be then.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-26 16:04:43 +01:00
Dietmar Maurer
d91a0f9fc9 Set MMAP_THRESHOLD to a fixed value (128K)
glibc's malloc has a misguided heuristic to detect transient allocations that
will just result in allocation sizes below 32 MiB never using mmap.

That it turn means that those relatively big allocations are on the heap where
cleanup and returning memory to the OS is harder to do and easier to be blocked
by long living, small allocations at the top (end) of the heap.

Observing the malloc size distribution in a file-level backup run:

@size:
[0]                   14 |                                                    |
[1]                25214 |@@@@@                                               |
[2, 4)              9090 |@                                                   |
[4, 8)             12987 |@@                                                  |
[8, 16)            93453 |@@@@@@@@@@@@@@@@@@@@                                |
[16, 32)           30255 |@@@@@@                                              |
[32, 64)          237445 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
[64, 128)          32692 |@@@@@@@                                             |
[128, 256)         22296 |@@@@                                                |
[256, 512)         16177 |@@@                                                 |
[512, 1K)           5139 |@                                                   |
[1K, 2K)            3352 |                                                    |
[2K, 4K)             214 |                                                    |
[4K, 8K)            1568 |                                                    |
[8K, 16K)             95 |                                                    |
[16K, 32K)          3457 |                                                    |
[32K, 64K)          3175 |                                                    |
[64K, 128K)          161 |                                                    |
[128K, 256K)         453 |                                                    |
[256K, 512K)          93 |                                                    |
[512K, 1M)            74 |                                                    |
[1M, 2M)             774 |                                                    |
[2M, 4M)             319 |                                                    |
[4M, 8M)             700 |                                                    |
[8M, 16M)             93 |                                                    |
[16M, 32M)            18 |                                                    |

We see that all allocations will be on the heap, and that while most
allocations are small, the relatively few big ones will still make up most of
the RSS and if blocked from being released back to the OS result in much higher
peak and average usage for the program than actually required.

Avoiding the "dynamic" mmap-threshold increasement algorithm and fixing it at
the original default of 128 KiB reduces RSS size by factor 10-20 when running
backups. As with memory mappings other mappings or the heap can never block
freeing the memory fully back to the OS.

But, the drawback of using mmap is more wasted space for unaligned or small
allocation sizes, and the fact that the kernel allegedly zeros out the data
before giving it to user space. The former doesn't really matter for us when
using it only for allocations bigger than 128 KiB, and the latter is a
trade-off, using 10 to 20 times less memory brings its own performance
improvement possibilities for the whole system after all ;-)

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
 [ Thomas: added to comment & commit message + extra-empty-line fixes ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-26 14:10:54 +01:00
Thomas Lamprecht
3af17d8919 bump version to 2.1.4-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-21 10:48:42 +01:00
Dominik Csapak
98983a9dab pbs-tools: LruCache: implement Drop
this fixes the leaked memory for the cache, as we had only pointers
in the map/list which were freed, not the underlying chunks

moves the 'clear' implementation out of the trait bounds so that
Drop can reuse it

this is used e.g. for file download from a pxar

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-01-20 11:24:34 +01:00
Matthias Heiserer
e92df23806 docs: make external hyperlinks clickable
rustdoc lints detected that two external hyperlinks were not
clickable.

The short cut used is only available for internal links, otherwise
one needs to use the Markdown syntax, so either [Text](URL) or <URL>.

Signed-off-by: Matthias Heiserer <m.heiserer@proxmox.com>
[ T: commit message text width, mention markdown ]
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-18 15:54:33 +01:00
Fabian Grünbichler
5ee8dd784f ciphers: improve option naming
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-01-14 11:02:07 +01:00
Hannes Laimer
f37167aeff api2: make tls ciphers updatable
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-14 11:02:07 +01:00
Hannes Laimer
2eba3967b2 proxy: use ciphers from config if set
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-14 11:02:07 +01:00
Fabian Grünbichler
1d552d2dd5 ciphers: simplify API schema
these need to be checked (and are) via libssl anyway before persisting,
and newer versions might contain new ciphers/variants/... (and things
like @STRENGTH or @SECLEVEL=n were missing).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-01-14 11:02:07 +01:00
Hannes Laimer
1ec7f7e6f2 config: add tls ciphers to NodeConfig
for TLS 1.3 and for TLS <= 1.2

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-14 11:02:07 +01:00
Thomas Lamprecht
8ad9eb779e bump version to 2.1.3-1
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 16:49:33 +01:00
Fabian Grünbichler
18ba1b2249 api-types: relax NODENAME_SCHEMA
there isn't really a concept of 'nodes' in PBS (yet) anyway - and if
there ever is, it needs to be handled by the rest-server / specific API
endpoints (like in PVE), and not by the schema.

this allows dropping proxmox-sys from pbs-api-types (and thus nix and
some other transitive deps as well).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-01-12 15:42:58 +01:00
Fabian Grünbichler
e2e587e3c7 api-types: move RsaPubKeyInfo to pbs-client
it's the only thing requiring openssl in pbs-api-types, and it's only
used by the client to pretty-print the 'master' key, which is
client-specific.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2022-01-12 15:42:58 +01:00
Thomas Lamprecht
c10a6755f0 docs: fix some typos
the `congestion` typo has been mentioned in the forum:
https://forum.proxmox.com/threads/proxmox-backup-server-2-1-released.100240/#post-443370

fixed a few surrounding ones and ones that `codespell` found in
addition to that.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 15:19:59 +01:00
Thomas Lamprecht
d43aca148f ui: sys config: add icons to tabs
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 12:41:28 +01:00
Thomas Lamprecht
5dfe3b66ab ui: sys config: code cleanup/refactoring
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 12:41:28 +01:00
Thomas Lamprecht
50c0840146 ui: sys config: merge webauthn and general options into one tab
To much wasted space else.
Also rename "Options" to "Others", while it's not _that_ much better
it's slightly more intuitive than config -> options (which has some
redundancy)...

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 12:41:25 +01:00
Thomas Lamprecht
2e02a859cf fix #3058: ui: improve remote edit UX by clarifying ID vs host
also fixup missing emptyText for fingerprint (adapted from PVE's PBS
storage addition) and code-style in surrounding areas a bit

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2022-01-12 09:38:59 +01:00
Dominik Csapak
64c075b6c2 ui: hide rrd chart for io delay if no io_ticks are returned
it makes no sense to show a completely empty graph

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-11 11:43:10 +01:00
Dominik Csapak
f27b6086b1 api/admin/datastore: rrd: do not include io_ticks for zfs datastores
since it is not possible to collect them, do not return them here either

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-11 11:42:09 +01:00
Dominik Csapak
7c069e82d1 fix #3743: extract zfs dataset io stats from /proc/spl/kstat/zfs/POOL/objset-*
Recently, ZFS removed the pool global io stats from
/proc/spl/kstat/zfs/POOL/io with no replacement.

To gather stats about the datastores, access now the objset specific
entries there. To be able to make that efficient, cache a map of
dataset <-> obset ids, so that we do not have to parse all files each time.

We update the cache each time we try to get the info for a dataset
where we do not have a mapping.

We cannot update it on datastore add/remove since that happens in the
proxmox-backup daemon, while we need the info here in proxmox-backup-proxy.

Sadly with this we lose the io wait metric, but it seems that this is no
longer tracked in zfs at all, so nothing we can do for that.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2022-01-11 08:45:55 +01:00
Dietmar Maurer
b44483a853 datastore status: do not count empty groups
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2022-01-07 08:40:22 +01:00
Wolfgang Bumiller
ba857cbe68 tools::config: error on newlines in string values
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2022-01-05 10:04:04 +01:00
Hannes Laimer
c772a4a683 ui: add new options tab under configuration
... and add from-email + move http-proxy there

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-04 08:24:17 +01:00
Hannes Laimer
e466526137 server: use configured email-from for sending mail
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-04 08:09:27 +01:00
Hannes Laimer
62222ed068 api2: make email-from updatable
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-04 08:09:27 +01:00
Hannes Laimer
f06b5283b0 config: add email-from to NodeConfig
Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
2022-01-04 08:05:34 +01:00
Fabian Grünbichler
645d52308b TimeSpan: parse via FromStr
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
7f6c169b25 use schema verify methods
the old, deprecated ones only forward to these anyway.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
9987872382 rrd: drop redundant field names
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
6f1c26b083 tree-wide: is_ok/is_err()
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
3afecb8409 tree-wide: use is_empty() and similar
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
540fca5c9e tree-wide: cleanup manual map/flatten
found with clippy, best viewed with `-w` ;)

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
8ff886773f view_task_result: remove unnecessary &mut
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
aa174e8e8a tree-wide: drop redundant clones
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 15:02:07 +01:00
Fabian Grünbichler
0a7f902e2a tape: multi-volume: fix overflow check
the part number cannot go above 255 at the moment, but if it ever gets
bumped to a bigger integer type this boundary wouldn't cause a
compile-error. explicitly checking for overflowing u8 makes this a bit
more future-proof, and shuts up clippy as well ;)

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 13:55:33 +01:00
Fabian Grünbichler
9a37bd6c84 tree-wide: fix needless borrows
found and fixed via clippy

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-30 13:55:33 +01:00
Fabian Grünbichler
a0c69902c8 fix #3763: disable renegotiation
requires openssl crate with fix[0], like our packaged one.

0: https://github.com/sfackler/rust-openssl/pull/1584

Tested-by: Stoiko Ivanov s.ivanov@proxmox.com
Reviewed-by: Stoiko Ivanov s.ivanov@proxmox.com

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-27 09:09:26 +01:00
Wolfgang Bumiller
f30ada6bbe bump d/control
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-12-16 11:25:02 +01:00
Wolfgang Bumiller
c3b8e74fdf bump regex dep to 1.5
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-12-16 11:25:02 +01:00
Wolfgang Bumiller
9fa3026a08 cleanup schema function calls
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-12-16 11:25:02 +01:00
Wolfgang Bumiller
821aa8eae6 bump proxmox-schema to 1.1
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-12-16 11:25:02 +01:00
Thomas Lamprecht
0b50c18ed0 ui: group filter: add hint that filter are additive
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-16 11:19:49 +01:00
Thomas Lamprecht
25e41aa802 restore-daemon: fix use of deprecated env_logger::from_env function
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-16 11:12:36 +01:00
Thomas Lamprecht
ff6b6cd74d drop unused imports of proxmox_sys::identity
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-16 11:09:38 +01:00
Dominik Csapak
48910f9b0a api: zfs: create zpool with relatime=on
some operations (e.g. garbage collection/restore/etc.) are very read
intensive on the chunks, and having atime=on and relatime=off (zfs default)
makes those write intensive operations too. Additionally, 'ext4' defaults to
relatime, so also change the default for api-created zpools.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-16 10:56:04 +01:00
Dominik Csapak
dfe5c4c494 ui: fix opening settings window in datastore panel
When a user directly opened the webui with a fragment that is not
the summary, opening of the 'my settings' window fails because the
initial set of the columns field triggers a state change, which in turn
tries to trigger 'updateColumns'. That fails though, since the columns
were not even rendered yet (because we are on a different tab).

To fix this, simply return when the panel is not rendered yet.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-15 15:56:59 +01:00
Thomas Lamprecht
beb1d6f362 buildsys: drop hack that moved testing after dh_install
the motivation for this was that we required to build some stuff with
different feature flags before the big-split when openid (that still
links to the dependency-greedy) got added, to avoid that binaries
that do not use openid at all also got linked to its dependencies.

This is now fixed since a bit and thus we should be able to drop the
test-reorder hack.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-15 14:25:32 +01:00
Thomas Lamprecht
323ad7ddc0 fix #3794: api types: set backup time lower limit to 1
Some users want to import historical backups but they run into the
original lower backuo-time limit one can pass. That original limit
was derived from the initial PBS development start in 2019, it was
assumed that no older backup can exist with PBS before it existing,
but imports of older backups is a legitimate thing.

I pondered using 683071200 (1991-08-25), aka the first time Linux was
publicly announced by Linus Torvalds as new limit but at the end I
did not wanted to risk that and backup software is IMO to serious for
such easter eggs, so I went for 1, to differ between the bogus 0 some
tools fallback too if there's something off with time.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-15 14:13:49 +01:00
Thomas Lamprecht
1f53f6128f cargo: update commented-out local path override for convenience
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-15 13:46:50 +01:00
Thomas Lamprecht
4912d5f0e3 ui: calendar event: add once daily example and clarify workday one
similar to PVE, copying over the remaining commit message:

Using 00:00 with relying on the implied default is sub optimal as its
a bit of a magic example that new users may not understand as easily.
So spell it out explicitly, even if there'd be a shorter version
possible.

We also had some request for the once-daily every day, and its a
sensible example to have in general, could help getting the
difference between an hour list and a single one.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-07 18:54:26 +01:00
Dietmar Maurer
d4877712f8 pbs-client: avoid mut self in http_client methods.
It is not necessary, so avoid it. The client can now be used
with multiple threads (without using a Mutex).

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-04 14:44:05 +01:00
Dominik Csapak
7549114c9f adapt compute_next_event to new signature
the 'utc' flag is now contained in the event itself and not given
as a flag to 'compute_next_event' anymore

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-02 10:40:58 +01:00
Thomas Lamprecht
c72f8784a5 ui: group filter: merge duplicate filters
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-01 14:30:45 +01:00
Thomas Lamprecht
6a5a60ebfd ui: group filter: cleanup and comment more
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-01 14:30:45 +01:00
Dominik Csapak
f49cd6c135 ui: form/GroupFilter: copy records for the pbsGroupSelectors
store.getData() returns an 'Ext.util.Collection' which is a special
class that does more than being an array of records. Namely, it can
have 'observers' which can react on the change of the collection

Here, the 'onWidgetAttach' callback will be called twice on the first
row add and the widgets (and thus stores) are cached by extjs. When
doing a 'setData' of a Collection, it tries to add the store as an
observer, but due to the above caching and multiple calling this fails
since the store is already an observer.

For this reason, we want to actually copy the records (which neither
the store, nor the Collection has a method for...)

This gives us an additional benefit: The different pbsGroupSelectors can
sort independently now, before it was all linked to the original store's
collection.

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-01 14:30:45 +01:00
Dominik Csapak
b3c7567e3c ui: form/GroupFilter: improve group load callback handling
if 'me' is already destroyed here, return
if records is 'null' (which can happen on a not successful load),
load an empty list instead

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-01 14:30:45 +01:00
Dominik Csapak
d0d970f70b ui: form/GroupFilter: correctly resolve the reference cycle
'record[widget]' does not contain anything since the widgets are
in the 'widgets' property so delete that

we also have to remove the 'record' entry of the widget so that
the widget does not have a link to the record anymore

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
2021-12-01 14:30:45 +01:00
Fabian Grünbichler
f66d814792 fix broken format strings
Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-01 12:46:37 +01:00
Fabian Grünbichler
b25e07b3ce deps: env_logger update to 0.9
and removal from main crate, not needed there anymore.

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
2021-12-01 12:46:37 +01:00
Dietmar Maurer
0e994eb938 pbs-api-types: remove proxmox-sys dependency for target wasm
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-01 09:49:52 +01:00
Dietmar Maurer
1a211f0d96 pbs-api-types: remove openssl dependency for target wasm
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-01 09:28:47 +01:00
Dietmar Maurer
f7fde5c81b pbs-api-types: remove libc dependency
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-01 09:10:25 +01:00
Dietmar Maurer
af5a55509d pbs-api-types: removbe usused nix dependency
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-01 09:08:25 +01:00
Dominik Csapak
68b6c1202c remove use of deprecated functions from proxmox-time
Depend on proxmox-time 1.1.1

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-12-01 07:23:18 +01:00
Dominik Csapak
ad72fda1d6 ui: SyncJobEdit: add second tab with group filters
adds a second tab and adapts the styling to our usual one (border/padding)

adds a change listener to the remote datastore selector to change the
remote + datastore on the group filters

remaining changes are mostly indentation changes

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-01 06:46:56 +01:00
Dominik Csapak
705f4b0d95 ui: tape/BackupJobEdit: add second tab with group filters
adds a second tab and adapts the styling to our usual one (border/padding)

adds a change listener to the datastore selector to change it on the
group filters

remaining changes are mostly indentation changes

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-01 06:44:37 +01:00
Dominik Csapak
65bd918ac3 ui: add GroupFilter form field(container)
this contains a grid + button + hidden field which lets the user
add group filters one by one. the first column is the type selector
(type, group, regex) and the second column shows the relevant
input field (groupselector, kvcombobox for type, and textfield for regex)

i had to hack a little to get access to the widgets of the
fieldcontainer, since we cannot simply access the widget of a column
from another column (which we need to show the correct one when changing
the type), also we cannot traverse the widget hirachy in the usual way,
since extjs seems to build it differently for widgetcolumns.

to solve this, i added references of the widgets to the record, and a
reference of the record to the widgets. since this is now a cyclic
reference, i solve that in 'removeFilter' and in 'beforedestroy' of the grid
by removing the references again

also contains a small css style to remove the padding in the rows

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-01 06:42:31 +01:00
Dominik Csapak
7d4d8f47c9 ui: add GroupSelector
to select either a group from a datastore

for now it is expected to set the data in the store manually

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
2021-12-01 06:41:21 +01:00
Wolfgang Bumiller
73fba2edea fix a warning in io_return macro
newer compilers warn about the semicolon there, so put
braces around it

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-11-29 11:26:25 +01:00
Wolfgang Bumiller
e25982f24e remove unused identity macro
this is not required anymore by the sortable macro

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-11-29 11:24:02 +01:00
Wolfgang Bumiller
368daf13fd bump d/control
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-11-29 11:20:52 +01:00
Wolfgang Bumiller
e6e2927e72 update proxmox-tfa to 2.0
and fix still-very-bad updater usage in config api call...

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2021-11-29 11:19:50 +01:00
Dietmar Maurer
0fee4ff2a4 pbs-tape: do not depend on pbs-tools
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 13:17:58 +01:00
Dietmar Maurer
3dcea3ce33 fix typo in comment
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 13:15:35 +01:00
Dietmar Maurer
726b9d4469 use proxmox-sys 0.2.1 and proxmox-io 1.0.1
And remove unused code from pbs-tools.

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 12:30:03 +01:00
Dietmar Maurer
577095e2f7 move pbs-tools/src/percent_encoding.rs to pbs-api-types/src/percent_encoding.rs
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 11:48:52 +01:00
Dietmar Maurer
f35e187f16 fix StdChannelWriter usage
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 11:27:20 +01:00
Dietmar Maurer
e2b12ce988 StdChannelWriter: avoid using anyhow::Error
Use a generic implementation to allow different error types.
2021-11-25 11:14:56 +01:00
Dietmar Maurer
92ef0b56d8 move pbs-tools/src/str.rs to pbs-client/src/pxar/create.rs
Code is only used there.

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 10:43:22 +01:00
Dietmar Maurer
8a8a1850d0 remove trait BufferedRead from pbs-tools/src/io.rs
We do not need it.

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 09:45:47 +01:00
Dietmar Maurer
fddb9bcc3e remove pbs-tools/src/sys.rs
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 09:01:29 +01:00
Dietmar Maurer
0df179c2b4 remove pbs-tools/src/cli.rs
Code is only used once in src/bin/proxmox_backup_debug/inspect.rs, so
move it into that file.

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-25 08:33:10 +01:00
Dietmar Maurer
689ed51397 openid_login: improve error message for disabled users. 2021-11-25 07:29:33 +01:00
Dietmar Maurer
3c56335d7b update debian/control 2021-11-25 06:49:26 +01:00
Dietmar Maurer
9eb58647c1 pbs-datastore: use hex::serde feature
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-24 13:06:14 +01:00
Dietmar Maurer
0ff214bedd debian/control: add librust-proxmox-serde 2021-11-24 10:58:01 +01:00
Dietmar Maurer
25877d05ac update to proxmox-sys 0.2 crate
- imported pbs-api-types/src/common_regex.rs from old proxmox crate
- use hex crate to generate/parse hex digest
- remove all reference to proxmox crate (use proxmox-sys and
  proxmox-serde instead)

Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
2021-11-24 10:32:27 +01:00
480 changed files with 27010 additions and 15464 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "proxmox-backup" name = "proxmox-backup"
version = "2.1.2" version = "2.2.3"
authors = [ authors = [
"Dietmar Maurer <dietmar@proxmox.com>", "Dietmar Maurer <dietmar@proxmox.com>",
"Dominik Csapak <d.csapak@proxmox.com>", "Dominik Csapak <d.csapak@proxmox.com>",
@ -49,7 +49,6 @@ bytes = "1.0"
cidr = "0.2.1" cidr = "0.2.1"
crc32fast = "1" crc32fast = "1"
endian_trait = { version = "0.6", features = ["arrays"] } endian_trait = { version = "0.6", features = ["arrays"] }
env_logger = "0.7"
flate2 = "1.0" flate2 = "1.0"
anyhow = "1.0" anyhow = "1.0"
thiserror = "1.0" thiserror = "1.0"
@ -61,16 +60,16 @@ http = "0.2"
hyper = { version = "0.14", features = [ "full" ] } hyper = { version = "0.14", features = [ "full" ] }
lazy_static = "1.4" lazy_static = "1.4"
libc = "0.2" libc = "0.2"
log = "0.4" log = "0.4.17"
nix = "0.19.1" nix = "0.24"
num-traits = "0.2" num-traits = "0.2"
once_cell = "1.3.1" once_cell = "1.3.1"
openssl = "0.10" openssl = "0.10.38" # currently patched!
pam = "0.7" pam = "0.7"
pam-sys = "0.5" pam-sys = "0.5"
percent-encoding = "2.1" percent-encoding = "2.1"
regex = "1.2" regex = "1.5.5"
rustyline = "7" rustyline = "9"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
siphasher = "0.3" siphasher = "0.3"
@ -78,7 +77,7 @@ syslog = "4.0"
tokio = { version = "1.6", features = [ "fs", "io-util", "io-std", "macros", "net", "parking_lot", "process", "rt", "rt-multi-thread", "signal", "time" ] } tokio = { version = "1.6", features = [ "fs", "io-util", "io-std", "macros", "net", "parking_lot", "process", "rt", "rt-multi-thread", "signal", "time" ] }
tokio-openssl = "0.6.1" tokio-openssl = "0.6.1"
tokio-stream = "0.1.0" tokio-stream = "0.1.0"
tokio-util = { version = "0.6", features = [ "codec", "io" ] } tokio-util = { version = "0.7", features = [ "codec", "io" ] }
tower-service = "0.3.0" tower-service = "0.3.0"
udev = "0.4" udev = "0.4"
url = "2.1" url = "2.1"
@ -94,22 +93,24 @@ zstd = { version = "0.6", features = [ "bindgen" ] }
pathpatterns = "0.1.2" pathpatterns = "0.1.2"
pxar = { version = "0.10.1", features = [ "tokio-io" ] } pxar = { version = "0.10.1", features = [ "tokio-io" ] }
proxmox = { version = "0.15.3", features = [ "sortable-macro" ] } proxmox-http = { version = "0.6.1", features = [ "client", "http-helpers", "websocket" ] }
proxmox-http = { version = "0.5.4", features = [ "client", "http-helpers", "websocket" ] }
proxmox-io = "1" proxmox-io = "1"
proxmox-lang = "1" proxmox-lang = "1.1"
proxmox-router = { version = "1.1", features = [ "cli" ] } proxmox-router = { version = "1.2.2", features = [ "cli" ] }
proxmox-schema = { version = "1", features = [ "api-macro" ] } proxmox-schema = { version = "1.3.1", features = [ "api-macro" ] }
proxmox-section-config = "1" proxmox-section-config = "1"
proxmox-tfa = { version = "1.3", features = [ "api", "api-types" ] } proxmox-tfa = { version = "2", features = [ "api", "api-types" ] }
proxmox-time = "1" proxmox-time = "1.1.2"
proxmox-uuid = "1" proxmox-uuid = "1"
proxmox-shared-memory = "0.1.1" proxmox-serde = "0.1"
proxmox-sys = "0.1.2" proxmox-shared-memory = "0.2"
proxmox-sys = { version = "0.3", features = [ "sortable-macro" ] }
proxmox-compression = "0.1"
proxmox-acme-rs = "0.3"
proxmox-acme-rs = "0.4"
proxmox-apt = "0.8.0" proxmox-apt = "0.8.0"
proxmox-async = "0.2" proxmox-async = "0.4"
proxmox-openid = "0.9.0" proxmox-openid = "0.9.0"
pbs-api-types = { path = "pbs-api-types" } pbs-api-types = { path = "pbs-api-types" }
@ -125,10 +126,25 @@ pbs-tape = { path = "pbs-tape" }
# Local path overrides # Local path overrides
# NOTE: You must run `cargo update` after changing this for it to take effect! # NOTE: You must run `cargo update` after changing this for it to take effect!
[patch.crates-io] [patch.crates-io]
#proxmox = { path = "../proxmox/proxmox" } #proxmox-acme-rs = { path = "../proxmox-acme-rs" }
#proxmox-apt = { path = "../proxmox-apt" }
#proxmox-async = { path = "../proxmox/proxmox-async" }
#proxmox-compression = { path = "../proxmox/proxmox-compression" }
#proxmox-borrow = { path = "../proxmox/proxmox-borrow" }
#proxmox-fuse = { path = "../proxmox-fuse" }
#proxmox-http = { path = "../proxmox/proxmox-http" } #proxmox-http = { path = "../proxmox/proxmox-http" }
#proxmox-tfa = { path = "../proxmox/proxmox-tfa" } #proxmox-io = { path = "../proxmox/proxmox-io" }
#proxmox-lang = { path = "../proxmox/proxmox-lang" }
#proxmox-openid = { path = "../proxmox-openid-rs" }
#proxmox-router = { path = "../proxmox/proxmox-router" }
#proxmox-schema = { path = "../proxmox/proxmox-schema" } #proxmox-schema = { path = "../proxmox/proxmox-schema" }
#proxmox-section-config = { path = "../proxmox/proxmox-section-config" }
#proxmox-shared-memory = { path = "../proxmox/proxmox-shared-memory" }
#proxmox-sys = { path = "../proxmox/proxmox-sys" }
#proxmox-serde = { path = "../proxmox/proxmox-serde" }
#proxmox-tfa = { path = "../proxmox/proxmox-tfa" }
#proxmox-time = { path = "../proxmox/proxmox-time" }
#proxmox-uuid = { path = "../proxmox/proxmox-uuid" }
#pxar = { path = "../pxar" } #pxar = { path = "../pxar" }
[features] [features]

View File

@ -221,9 +221,6 @@ install: $(COMPILED_BINS)
install -m755 $(COMPILEDIR)/$(i) $(DESTDIR)$(LIBEXECDIR)/proxmox-backup/ ;) install -m755 $(COMPILEDIR)/$(i) $(DESTDIR)$(LIBEXECDIR)/proxmox-backup/ ;)
$(MAKE) -C www install $(MAKE) -C www install
$(MAKE) -C docs install $(MAKE) -C docs install
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
$(MAKE) test # HACK, only test now to avoid clobbering build files with wrong config
endif
.PHONY: upload .PHONY: upload
upload: ${SERVER_DEB} ${CLIENT_DEB} ${RESTORE_DEB} ${DOC_DEB} ${DEBUG_DEB} upload: ${SERVER_DEB} ${CLIENT_DEB} ${RESTORE_DEB} ${DOC_DEB} ${DEBUG_DEB}

View File

@ -1,3 +1,7 @@
Build & Release Notes
*********************
``rustup`` Toolchain ``rustup`` Toolchain
==================== ====================
@ -40,41 +44,44 @@ example for proxmox crate above).
Build Build
===== =====
on Debian Buster on Debian 11 Bullseye
Setup: Setup:
1. # echo 'deb http://download.proxmox.com/debian/devel/ buster main' >> /etc/apt/sources.list.d/proxmox-devel.list 1. # echo 'deb http://download.proxmox.com/debian/devel/ bullseye main' | sudo tee /etc/apt/sources.list.d/proxmox-devel.list
2. # sudo wget http://download.proxmox.com/debian/proxmox-ve-release-6.x.gpg -O /etc/apt/trusted.gpg.d/proxmox-ve-release-6.x.gpg 2. # sudo wget https://enterprise.proxmox.com/debian/proxmox-release-bullseye.gpg -O /etc/apt/trusted.gpg.d/proxmox-release-bullseye.gpg
3. # sudo apt update 3. # sudo apt update
4. # sudo apt install devscripts debcargo clang 4. # sudo apt install devscripts debcargo clang
5. # git clone git://git.proxmox.com/git/proxmox-backup.git 5. # git clone git://git.proxmox.com/git/proxmox-backup.git
6. # sudo mk-build-deps -ir 6. # cd proxmox-backup; sudo mk-build-deps -ir
Note: 2. may be skipped if you already added the PVE or PBS package repository Note: 2. may be skipped if you already added the PVE or PBS package repository
You are now able to build using the Makefile or cargo itself. You are now able to build using the Makefile or cargo itself, e.g.::
# make deb-all
# # or for a non-package build
# cargo build --all --release
Design Notes Design Notes
============ ************
Here are some random thought about the software design (unless I find a better place). Here are some random thought about the software design (unless I find a better place).
Large chunk sizes Large chunk sizes
----------------- =================
It is important to notice that large chunk sizes are crucial for It is important to notice that large chunk sizes are crucial for performance.
performance. We have a multi-user system, where different people can do We have a multi-user system, where different people can do different operations
different operations on a datastore at the same time, and most operation on a datastore at the same time, and most operation involves reading a series
involves reading a series of chunks. of chunks.
So what is the maximal theoretical speed we can get when reading a So what is the maximal theoretical speed we can get when reading a series of
series of chunks? Reading a chunk sequence need the following steps: chunks? Reading a chunk sequence need the following steps:
- seek to the first chunk start location - seek to the first chunk's start location
- read the chunk data - read the chunk data
- seek to the first chunk start location - seek to the next chunk's start location
- read the chunk data - read the chunk data
- ... - ...

402
debian/changelog vendored
View File

@ -1,3 +1,405 @@
rust-proxmox-backup (2.2.3-1) bullseye; urgency=medium
* datastore: swap dirtying the datastore cache every 60s by just using the
available config digest to detect any changes accuratly when the actually
happen
* api: datastore list and datastore status: avoid opening datastore and
possibly iterating over namespace (for lesser privileged users), but
rather use the in-memory ACL tree directly to check if there's access to
any namespace below.
-- Proxmox Support Team <support@proxmox.com> Sat, 04 Jun 2022 16:30:05 +0200
rust-proxmox-backup (2.2.2-3) bullseye; urgency=medium
* datastore: lookup: reuse ChunkStore on stale datastore re-open
* bump tokio (async framework) dependency
-- Proxmox Support Team <support@proxmox.com> Thu, 02 Jun 2022 17:25:01 +0200
rust-proxmox-backup (2.2.2-2) bullseye; urgency=medium
* improvement of error handling when removing status files and locks from
jobs that were never executed.
-- Proxmox Support Team <support@proxmox.com> Wed, 01 Jun 2022 16:22:22 +0200
rust-proxmox-backup (2.2.2-1) bullseye; urgency=medium
* Revert "verify: allow '0' days for reverification", was already possible
by setting "ignore-verified" to false
* ui: datastore permissions: allow ACL path edit & query namespaces
* accessible group iter: allow NS descending with DATASTORE_READ privilege
* prune datastore: rework worker tak log
* prune datastore: support max-depth and improve priv checks
* ui: prune input: support opt-in recursive/max-depth field
* add prune job config and api, allowing one to setup a scheduled pruning
for a specific namespace only
* ui: add ui for prune jobs
* api: disable setting prune options in datastore.cfg and transform any
existing prune tasks from datastore config to new prune job config in a
post installation hook
* proxmox-tape: use correct api call for 'load-media-from-slot'
* avoid overly strict privilege restrictions for some API endpoints and
actions when using namespaces. Better support navigating the user
interface when only having Datastore.Admin on a (sub) namespace.
* include required privilege names in some permission errors
* docs: fix some typos
* api: status: include empty entry for stores with ns-only privs
* ui: datastore options: avoid breakage if rrd store ore active-ops cannot
be queried
* ui: datastore content: only mask the inner treeview, not the top bar on
error to allow a user to trigger a manual reload
* ui: system config: improve bottom margins and scroll behavior
-- Proxmox Support Team <support@proxmox.com> Wed, 01 Jun 2022 15:09:36 +0200
rust-proxmox-backup (2.2.1-1) bullseye; urgency=medium
* docs: update some screenshots and add new ones
* docs: port overcertificate management chapters from Proxmox VE
* ui: datastore/Summary: correctly show the io-delay chart
* ui: sync/verify jobs: use pmxDisplayEditField to fix editing
* ui: server status: use power of two base for memory and swap
* ui: use base 10 (SI) for all storage related displays
* ui: datastore selector: show maintenance mode in selector
* docs: basic maintenance mode section
* docs: storage: refer to options
* storage: add some initial namespace docs
* ui: tape restore: fix form validation for datastore mapping
* ui: namespace selector: show picker empty text if no namespace
-- Proxmox Support Team <support@proxmox.com> Tue, 17 May 2022 13:56:50 +0200
rust-proxmox-backup (2.2.0-2) bullseye; urgency=medium
* client: add CLI auto-completion callbacks for ns parameters
* ui: fix setting protection in namespace
* ui: switch summary repo status to widget toolkit one
* ui: verify outdated: disallow blank and drop wrong empty text
* docs: add namespace section to sync documentation
* ui: datastore summary: add maintenance mask for offline entries
* ui: verify/sync: allow to optionally override ID again
* prune: fix workerid issues
-- Proxmox Support Team <support@proxmox.com> Mon, 16 May 2022 19:01:13 +0200
rust-proxmox-backup (2.2.0-1) bullseye; urgency=medium
* cli: improve namespace integration in proxmox-backup-client and
proxmox-tape
* docs: tape: add information about namespaces
* api: datastore status: make counts for groups and snapshots iterate over
all accessible namespaces recursively
* ui: fix storeId casing to register store correctly, so that we can query
it again for the ACL permission path selector
* ui: trigger datastore update after maintenance mode edit
* ui: namespace selector: set queryMode to local to avoid bogus background
requests on typing
* ui: sync job: fix clearing value of remote target-namespace by mistake on
edit
* ui: remote target ns selector: add clear trigger
* ui: prune group: add namespace info to title
* fix #4001: ui: add prefix to files downloaded through the pxar browser
* ui: datastore: reload content tree on successful datastore add
* ui: datastore: allow deleting currently shown namespace
* docs: rework access control, list available privileges
* docs: access control: add "Objects and Paths" section and fix
add-permission screenshot
-- Proxmox Support Team <support@proxmox.com> Mon, 16 May 2022 11:06:05 +0200
rust-proxmox-backup (2.1.10-1) bullseye; urgency=medium
* datastore: drop bogus chunk size check, can cause trouble
* pull/sync: detect remote lack of namespace support
* pull/sync: correctly query with remote-ns as parent
* ui: sync: add reduced max-depth selector
* ui: group filter: make also local filter NS aware
* api types: set NS_MAX_DEPTH schema default to MAX_NAMESPACE_DEPTH instead
of 0
* tape: notify when arriving at end of media
* tree-wide: rename 'backup-ns' API parameters to 'ns'
* tape: add namespaces/recursion depth to tape backup jobs
* api: tape/restore: add namespace mapping
* tape: bump catalog/snapshot archive magic
* ui: tape: backup overview: show namespaces as their own level above groups
* ui: tape restore: allow simple namespace mapping
-- Proxmox Support Team <support@proxmox.com> Fri, 13 May 2022 14:26:32 +0200
rust-proxmox-backup (2.1.9-2) bullseye; urgency=medium
* api: tape restore: lock the target datastore, not the source one
* chunk store: force write chunk again if it exist but its metadata length
is zero
* completion: fix 'group-filter' parameter name
* implement backup namespaces for datastores, allowing one to reuse a single
chunkstore deduplication domain for multiple sources without naming
conflicts and with fine-grained access control.
* make various datastore related API calls backup namespace aware
* make sync and pull backup namespace aware
* ui: datastore content: show namespaces but only one level at a time
* ui: make various datastore related UI components namespace aware
* fix various bugs, add namespace support to file-restore
-- Proxmox Support Team <support@proxmox.com> Thu, 12 May 2022 14:25:53 +0200
rust-proxmox-backup (2.1.8-1) bullseye; urgency=medium
* api: status: return gc-status again
* proxmox-backup-proxy: stop accept() loop on daemon shutdown to avoid that
new request get accepted while the REST stack is already stopped, for
example on the reload triggered by a package upgrade.
* pull: improve filtering local removal candidates
-- Proxmox Support Team <support@proxmox.com> Mon, 02 May 2022 17:36:11 +0200
rust-proxmox-backup (2.1.7-1) bullseye; urgency=medium
* pbs-tape: sgutils2: check sense data when status is 'CHECK_CONDITION'
* rework & refactor datastore implementation for a more hierarchical access
structure
* datastore: implement Iterator for backup group and snapshot listing to
allow more efficient access for cases where we do not need the whole list
in memory
* pbs-client: extract: rewrite create_zip with sequential decoder
* pbs-client: extract: add top-level dir in tar.zst
* fix #3067: ui: add a separate notes view for longer markdown notes and
copy the markdown primer from Proxmox VE to Proxmox Backup Server docs
* restore-daemon: start disk initialization in parallel to the api
* restore-daemon: put blocking code into 'block_in_place'
* restore-daemon: avoid auto-pre-mounting zpools completely, the upfront
(time) cost can be to big to pay up initially, e.g., if there are many
subvolumes present, so only mount on demand.
* file-restore: add 'timeout' and 'json-error' parameter
* ui: add summary mask when in maintenance mode
* ui: update datastore's navigation icon and tooltip if it is in maintenance
mode
-- Proxmox Support Team <support@proxmox.com> Wed, 27 Apr 2022 19:53:53 +0200
rust-proxmox-backup (2.1.6-1) bullseye; urgency=medium
* api: verify: allow passing '0 days' for immediate re-verification
* fix #3103. node configuration: allow to configure default UI language
* fix #3856: tape: encryption key's password hint parameter is not optional
* re-use PROXMOX_DEBUG environment variable to control log level filter
* ui: WebAuthn: fix stopping store upgrades on destroy and decrease interval
* report: add tape, traffic control and disk infos and tune output order
* fix #3853: cli/api: add force option to tape key change-passphrase
* fix #3323: cli client: add dry-run option for backup command
* tape: make iterating over chunks to backup smarter to avoid some work
* bin: daily-update: make single checks/updates fail gracefully and log
to syslog directly instead of going through stdout indirectly.
* datastore: allow to turn of inode-sorting for chunk iteration. While inode
sorting benefits read-performance on block devices with higher latency
(e.g., spinning disks), it's also some extra work to get the metadata
required for sorting, so its a trade-off. For setups that have either very
slow or very fast metadata IO the benefits may turn into a net cost.
* docs: explain retention time for event allocation policy in more detail
* docs: add tape schedule examples
* proxmox-backup-debug api: parse parameters before sending to api
* ui: fix panel height in the dashboard for three-column view mode
* fix #3934 tape owner-selector to auth-id (user OR token)
* fix #3067: api: add support for multi-line comments in the node
configuration
* pbs-client: print error when we couldn't download previous FIDX/DIDX for
incremental change tracking
* fix #3854 add command to import a key from a file (json or paper-key
format) to proxmox-tape
* improve IO access pattern for some scenarios like TFA with high user and
login count or the file-restore-for-block-backup VM's internal driver.
* pxar create: fix anchored path pattern matching when adding entries
* docs: client: file exclusion: add note about leading slash
* rest-server: add option to rotate task logs by 'max_days' instead of
'max_files'
* pbs-datastore: add active operations tracking and use it to implement a
graceful transition into the also newly added maintenance mode (read-only
or offline) for datastores. Note that the UI implementation may still show
some rough edges if a datastore is in offline mode for maintenance.
* add new streaming-response type for API call responses and enable it for
the snapshot and task-log list, which can both get rather big. This avoids
allocation of a potentially big intermediate memory buffer and thus
overall memory usage.
* pxar: accompany existing .zip download support with a tar.zst(d) one. The
tar archive supports more file types (e.g., hard links or device nodes)
and zstd allows for a efficient but still effective compression.
-- Proxmox Support Team <support@proxmox.com> Wed, 13 Apr 2022 17:00:53 +0200
rust-proxmox-backup (2.1.5-1) bullseye; urgency=medium
* tell system allocator to always use mmap for allocations >= 128 KiB to
improve reclaimability of free'd memory to the OS and reduce peak and avg.
RSS consumption
* file restore: always wait up to 25s for the file-restore-VM to have
scanned all possible filesystems in a backup. While theoretically there
are some edge cases where the tool waits less now, most common ones should
be waiting more compared to the 12s "worst" case previously.
-- Proxmox Support Team <support@proxmox.com> Wed, 26 Jan 2022 16:23:09 +0100
rust-proxmox-backup (2.1.4-1) bullseye; urgency=medium
* config: add tls ciphers to NodeConfig
* pbs-tools: improve memory foot print of LRU Cache
* update dependencies to avoid a ref-count leak in async helpers
-- Proxmox Support Team <support@proxmox.com> Fri, 21 Jan 2022 10:48:14 +0100
rust-proxmox-backup (2.1.3-1) bullseye; urgency=medium
* fix #3618: proxmox-async: zip: add conditional EFS flag to zip files to
improve non-ascii code point extraction under windows.
* OpenID Connect login: improve error message for disabled users
* ui: tape: backup job: add second tab for group-filters to add/edit window
* ui: sync job: add second tab for group-filters to add/edit window
* ui: calendar event: add once daily example and clarify the workday one
* fix #3794: api types: set backup time (since the UNIX epoch) lower limit
to 1
* ui: fix opening settings window in datastore panel
* api: zfs: create zpool with `relatime=on` flag set
* fix #3763: disable SSL/TLS renegotiation
* node config: add email-from parameter to control notification sender
address
* ui: configuration: rename the "Authentication" tab to "Other" and add a
"General" section with HTTP-proxy and email-from settings
* datastore stats: not include the unavailable `io_ticks` for ZFS
datastores
* ui: hide RRD chart for IO delay if no `io_ticks` are returned
* fix #3058: ui: improve remote edit UX by clarifying ID vs host fields
* docs: fix some minor typos
* api-types: relax nodename API schema, make it a simple regex check like in
Proxmox VE
-- Proxmox Support Team <support@proxmox.com> Wed, 12 Jan 2022 16:49:13 +0100
rust-proxmox-backup (2.1.2-1) bullseye; urgency=medium rust-proxmox-backup (2.1.2-1) bullseye; urgency=medium
* docs: backup-client: fix wrong reference * docs: backup-client: fix wrong reference

66
debian/control vendored
View File

@ -16,7 +16,7 @@ Build-Depends: debhelper (>= 12),
librust-crossbeam-channel-0.5+default-dev, librust-crossbeam-channel-0.5+default-dev,
librust-endian-trait-0.6+arrays-dev, librust-endian-trait-0.6+arrays-dev,
librust-endian-trait-0.6+default-dev, librust-endian-trait-0.6+default-dev,
librust-env-logger-0.7+default-dev, librust-env-logger-0.9+default-dev,
librust-flate2-1+default-dev, librust-flate2-1+default-dev,
librust-foreign-types-0.3+default-dev, librust-foreign-types-0.3+default-dev,
librust-futures-0.3+default-dev, librust-futures-0.3+default-dev,
@ -24,56 +24,58 @@ Build-Depends: debhelper (>= 12),
librust-h2-0.3+stream-dev, librust-h2-0.3+stream-dev,
librust-handlebars-3+default-dev, librust-handlebars-3+default-dev,
librust-hex-0.4+default-dev (>= 0.4.3-~~), librust-hex-0.4+default-dev (>= 0.4.3-~~),
librust-hex-0.4+serde-dev (>= 0.4.3-~~),
librust-http-0.2+default-dev, librust-http-0.2+default-dev,
librust-hyper-0.14+default-dev (>= 0.14.5-~~), librust-hyper-0.14+default-dev (>= 0.14.5-~~),
librust-hyper-0.14+full-dev (>= 0.14.5-~~), librust-hyper-0.14+full-dev (>= 0.14.5-~~),
librust-lazy-static-1+default-dev (>= 1.4-~~), librust-lazy-static-1+default-dev (>= 1.4-~~),
librust-libc-0.2+default-dev, librust-libc-0.2+default-dev,
librust-log-0.4+default-dev, librust-log-0.4+default-dev (>= 0.4.17-~~) <!nocheck>,
librust-nix-0.19+default-dev (>= 0.19.1-~~), librust-nix-0.24+default-dev,
librust-nom-5+default-dev (>= 5.1-~~), librust-nom-5+default-dev (>= 5.1-~~),
librust-num-traits-0.2+default-dev, librust-num-traits-0.2+default-dev,
librust-once-cell-1+default-dev (>= 1.3.1-~~), librust-once-cell-1+default-dev (>= 1.3.1-~~),
librust-openssl-0.10+default-dev, librust-openssl-0.10+default-dev (>= 0.10.38-~~),
librust-pam-0.7+default-dev, librust-pam-0.7+default-dev,
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-lite-0.2+default-dev, librust-pin-project-lite-0.2+default-dev,
librust-proxmox-0.15+default-dev (>= 0.15.3-~~), librust-proxmox-acme-rs-0.4+default-dev,
librust-proxmox-0.15+sortable-macro-dev (>= 0.15.3-~~),
librust-proxmox-0.15+tokio-dev (>= 0.15.3-~~),
librust-proxmox-acme-rs-0.3+default-dev,
librust-proxmox-apt-0.8+default-dev, librust-proxmox-apt-0.8+default-dev,
librust-proxmox-async-0.2+default-dev, librust-proxmox-async-0.4+default-dev,
librust-proxmox-borrow-1+default-dev, librust-proxmox-borrow-1+default-dev,
librust-proxmox-compression-0.1+default-dev (>= 0.1.1-~~),
librust-proxmox-fuse-0.1+default-dev (>= 0.1.1-~~), librust-proxmox-fuse-0.1+default-dev (>= 0.1.1-~~),
librust-proxmox-http-0.5+client-dev (>= 0.5.4-~~), librust-proxmox-http-0.6+client-dev (>= 0.6.1-~~),
librust-proxmox-http-0.5+default-dev (>= 0.5.4-~~), librust-proxmox-http-0.6+default-dev (>= 0.6.1-~~),
librust-proxmox-http-0.5+http-helpers-dev (>= 0.5.4-~~), librust-proxmox-http-0.6+http-helpers-dev (>= 0.6.1-~~),
librust-proxmox-http-0.5+websocket-dev (>= 0.5.4-~~), librust-proxmox-http-0.6+websocket-dev (>= 0.6.1-~~),
librust-proxmox-io-1+default-dev, librust-proxmox-io-1+default-dev (>= 1.0.1-~~),
librust-proxmox-io-1+tokio-dev, librust-proxmox-io-1+tokio-dev (>= 1.0.1-~~),
librust-proxmox-lang-1+default-dev, librust-proxmox-lang-1+default-dev (>= 1.1-~~),
librust-proxmox-openid-0.9+default-dev, librust-proxmox-openid-0.9+default-dev,
librust-proxmox-router-1+cli-dev (>= 1.1-~~), librust-proxmox-router-1+cli-dev (>= 1.2-~~),
librust-proxmox-router-1+default-dev (>= 1.1-~~), librust-proxmox-router-1+default-dev (>= 1.2.2-~~),
librust-proxmox-schema-1+api-macro-dev (>= 1.0.1-~~), librust-proxmox-schema-1+api-macro-dev (>= 1.3.1-~~),
librust-proxmox-schema-1+default-dev (>= 1.0.1-~~), librust-proxmox-schema-1+default-dev (>= 1.3.1-~~),
librust-proxmox-schema-1+upid-api-impl-dev (>= 1.0.1-~~), librust-proxmox-schema-1+upid-api-impl-dev (>= 1.3.1-~~),
librust-proxmox-section-config-1+default-dev, librust-proxmox-section-config-1+default-dev,
librust-proxmox-shared-memory-0.1+default-dev (>= 0.1.1-~~), librust-proxmox-serde-0.1+default-dev,
librust-proxmox-sys-0.1+default-dev (>= 0.1.2-~~), librust-proxmox-shared-memory-0.2+default-dev,
librust-proxmox-tfa-1+api-dev (>= 1.3-~~), librust-proxmox-sys-0.3+default-dev,
librust-proxmox-tfa-1+api-types-dev (>= 1.3-~~), librust-proxmox-sys-0.3+logrotate-dev,
librust-proxmox-tfa-1+default-dev (>= 1.3-~~), librust-proxmox-sys-0.3+sortable-macro-dev,
librust-proxmox-time-1+default-dev (>= 1.1-~~), librust-proxmox-tfa-2+api-dev,
librust-proxmox-tfa-2+api-types-dev,
librust-proxmox-tfa-2+default-dev,
librust-proxmox-time-1+default-dev (>= 1.1.2-~~),
librust-proxmox-uuid-1+default-dev, librust-proxmox-uuid-1+default-dev,
librust-proxmox-uuid-1+serde-dev, librust-proxmox-uuid-1+serde-dev,
librust-pxar-0.10+default-dev (>= 0.10.1-~~), librust-pxar-0.10+default-dev (>= 0.10.1-~~),
librust-pxar-0.10+tokio-io-dev (>= 0.10.1-~~), librust-pxar-0.10+tokio-io-dev (>= 0.10.1-~~),
librust-regex-1+default-dev (>= 1.2-~~), librust-regex-1+default-dev (>= 1.5.5-~~),
librust-rustyline-7+default-dev, librust-rustyline-9+default-dev,
librust-serde-1+default-dev, librust-serde-1+default-dev,
librust-serde-1+derive-dev, librust-serde-1+derive-dev,
librust-serde-cbor-0.11+default-dev (>= 0.11.1-~~), librust-serde-cbor-0.11+default-dev (>= 0.11.1-~~),
@ -96,9 +98,9 @@ Build-Depends: debhelper (>= 12),
librust-tokio-1+time-dev (>= 1.6-~~), librust-tokio-1+time-dev (>= 1.6-~~),
librust-tokio-openssl-0.6+default-dev (>= 0.6.1-~~), librust-tokio-openssl-0.6+default-dev (>= 0.6.1-~~),
librust-tokio-stream-0.1+default-dev, librust-tokio-stream-0.1+default-dev,
librust-tokio-util-0.6+codec-dev, librust-tokio-util-0.7+codec-dev,
librust-tokio-util-0.6+default-dev, librust-tokio-util-0.7+default-dev,
librust-tokio-util-0.6+io-dev, librust-tokio-util-0.7+io-dev,
librust-tower-service-0.3+default-dev, librust-tower-service-0.3+default-dev,
librust-udev-0.4+default-dev, librust-udev-0.4+default-dev,
librust-url-2+default-dev (>= 2.1-~~), librust-url-2+default-dev (>= 2.1-~~),

9
debian/postinst vendored
View File

@ -41,7 +41,14 @@ case "$1" in
flock -w 30 /var/log/proxmox-backup/tasks/active.lock sed -i 's/:termproxy::\([^@]\+\): /:termproxy::\1@pam: /' /var/log/proxmox-backup/tasks/active || true flock -w 30 /var/log/proxmox-backup/tasks/active.lock sed -i 's/:termproxy::\([^@]\+\): /:termproxy::\1@pam: /' /var/log/proxmox-backup/tasks/active || true
fi fi
if dpkg --compare-versions "$2" 'lt' '7.1-1' && test -e /etc/proxmox-backup/sync.cfg; then if dpkg --compare-versions "$2" 'lt' '2.2.2~'; then
echo "moving prune schedule from datacenter config to new prune job config"
proxmox-backup-manager update-to-prune-jobs-config \
|| echo "Failed to move prune jobs, please check manually"
true
fi
if dpkg --compare-versions "$2" 'lt' '2.1.3~' && test -e /etc/proxmox-backup/sync.cfg; then
prev_job="" prev_job=""
# read from HERE doc because POSIX sh limitations # read from HERE doc because POSIX sh limitations

3
debian/rules vendored
View File

@ -32,9 +32,6 @@ override_dh_auto_build:
override_dh_missing: override_dh_missing:
dh_missing --fail-missing dh_missing --fail-missing
override_dh_auto_test:
# ignore here to avoid rebuilding the binaries with the wrong target
override_dh_auto_install: override_dh_auto_install:
dh_auto_install -- \ dh_auto_install -- \
PROXY_USER=backup \ PROXY_USER=backup \

View File

@ -71,7 +71,7 @@ Environment Variables
.. Note:: Passwords must be valid UTF-8 and may not contain newlines. For your .. Note:: Passwords must be valid UTF-8 and may not contain newlines. For your
convienience, Proxmox Backup Server only uses the first line as password, so convenience, Proxmox Backup Server only uses the first line as password, so
you can add arbitrary comments after the first newline. you can add arbitrary comments after the first newline.
@ -120,11 +120,11 @@ This will prompt you for a password, then upload a file archive named
(i.e. ``--include-dev /boot/efi``). You can use this option (i.e. ``--include-dev /boot/efi``). You can use this option
multiple times for each mount point that should be included. multiple times for each mount point that should be included.
The ``--repository`` option can get quite long and is used by all The ``--repository`` option can get quite long and is used by all commands. You
commands. You can avoid having to enter this value by setting the can avoid having to enter this value by setting the environment variable
environment variable ``PBS_REPOSITORY``. Note that if you would like this to ``PBS_REPOSITORY``. Note that if you would like this to remain set over
remain set over multiple sessions, you should instead add the below line to your multiple sessions, you should instead add the below line to your ``.bashrc``
``.bashrc`` file. file.
.. code-block:: console .. code-block:: console
@ -142,9 +142,16 @@ you want to back up two disks mounted at ``/mnt/disk1`` and ``/mnt/disk2``:
This creates a backup of both disks. This creates a backup of both disks.
The backup command takes a list of backup specifications, which If you want to use a namespace for the backup target you can add the `--ns`
include the archive name on the server, the type of the archive, and the parameter:
archive source at the client. The format is:
.. code-block:: console
# proxmox-backup-client backup disk1.pxar:/mnt/disk1 disk2.pxar:/mnt/disk2 --ns a/b/c
The backup command takes a list of backup specifications, which include the
archive name on the server, the type of the archive, and the archive source at
the client. The format is:
<archive-name>.<type>:<source-path> <archive-name>.<type>:<source-path>
@ -159,21 +166,25 @@ device images. To create a backup of a block device, run the following command:
Excluding Files/Directories from a Backup Excluding Files/Directories from a Backup
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes it is desired to exclude certain files or directories from a backup archive. Sometimes it is desired to exclude certain files or directories from a backup
To tell the Proxmox Backup client when and how to ignore files and directories, archive. To tell the Proxmox Backup client when and how to ignore files and
place a text file named ``.pxarexclude`` in the filesystem hierarchy. directories, place a text file named ``.pxarexclude`` in the filesystem
Whenever the backup client encounters such a file in a directory, it interprets hierarchy. Whenever the backup client encounters such a file in a directory,
each line as a glob match pattern for files and directories that are to be excluded it interprets each line as a glob match pattern for files and directories that
from the backup. are to be excluded from the backup.
The file must contain a single glob pattern per line. Empty lines and lines The file must contain a single glob pattern per line. Empty lines and lines
starting with ``#`` (indicating a comment) are ignored. starting with ``#`` (indicating a comment) are ignored.
A ``!`` at the beginning of a line reverses the glob match pattern from an exclusion A ``!`` at the beginning of a line reverses the glob match pattern from an
to an explicit inclusion. This makes it possible to exclude all entries in a exclusion to an explicit inclusion. This makes it possible to exclude all
directory except for a few single files/subdirectories. entries in a directory except for a few single files/subdirectories.
Lines ending in ``/`` match only on directories. Lines ending in ``/`` match only on directories.
The directory containing the ``.pxarexclude`` file is considered to be the root of The directory containing the ``.pxarexclude`` file is considered to be the root
the given patterns. It is only possible to match files in this directory and its subdirectories. of the given patterns. It is only possible to match files in this directory and
its subdirectories.
.. Note:: Patterns without a leading ``/`` will also match in subdirectories,
while patterns with a leading ``/`` will only match in the current directory.
``\`` is used to escape special glob characters. ``\`` is used to escape special glob characters.
``?`` matches any single character. ``?`` matches any single character.
@ -182,15 +193,15 @@ the given patterns. It is only possible to match files in this directory and its
the pattern ``**/*.tmp``, it would exclude all files ending in ``.tmp`` within the pattern ``**/*.tmp``, it would exclude all files ending in ``.tmp`` within
a directory and its subdirectories. a directory and its subdirectories.
``[...]`` matches a single character from any of the provided characters within ``[...]`` matches a single character from any of the provided characters within
the brackets. ``[!...]`` does the complementary and matches any single character the brackets. ``[!...]`` does the complementary and matches any single
not contained within the brackets. It is also possible to specify ranges with two character not contained within the brackets. It is also possible to specify
characters separated by ``-``. For example, ``[a-z]`` matches any lowercase ranges with two characters separated by ``-``. For example, ``[a-z]`` matches
alphabetic character, and ``[0-9]`` matches any single digit. any lowercase alphabetic character, and ``[0-9]`` matches any single digit.
The order of the glob match patterns defines whether a file is included or The order of the glob match patterns defines whether a file is included or
excluded, that is to say, later entries override earlier ones. excluded, that is to say, later entries override earlier ones.
This is also true for match patterns encountered deeper down the directory tree, This is also true for match patterns encountered deeper down the directory
which can override a previous exclusion. tree, which can override a previous exclusion.
.. Note:: Excluded directories will **not** be read by the backup client. Thus, .. Note:: Excluded directories will **not** be read by the backup client. Thus,
a ``.pxarexclude`` file in an excluded subdirectory will have no effect. a ``.pxarexclude`` file in an excluded subdirectory will have no effect.
@ -405,6 +416,11 @@ list command provides a list of all the snapshots on the server:
├────────────────────────────────┼─────────────┼────────────────────────────────────┤ ├────────────────────────────────┼─────────────┼────────────────────────────────────┤
... ...
.. tip:: List will by default only output the backup snapshots of the root
namespace itself. To list backups from another namespace use the ``--ns
<ns>`` option
You can inspect the catalog to find specific files. You can inspect the catalog to find specific files.
.. code-block:: console .. code-block:: console
@ -562,10 +578,10 @@ user that has ``Datastore.Modify`` privileges on the datastore.
# proxmox-backup-client change-owner vm/103 john@pbs # proxmox-backup-client change-owner vm/103 john@pbs
This can also be done from within the web interface, by navigating to the 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 `Content` section of the datastore that contains the backup group and selecting
selecting the user icon under the `Actions` column. Common cases for this could the user icon under the `Actions` column. Common cases for this could be to
be to change the owner of a sync job from ``root@pam``, or to repurpose a change the owner of a sync job from ``root@pam``, or to repurpose a backup
backup group. group.
.. _backup-pruning: .. _backup-pruning:
@ -573,16 +589,24 @@ backup group.
Pruning and Removing Backups Pruning and Removing Backups
---------------------------- ----------------------------
You can manually delete a backup snapshot using the ``forget`` You can manually delete a backup snapshot using the ``forget`` command:
command:
.. code-block:: console .. code-block:: console
# proxmox-backup-client snapshot 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 snapshot. They
snapshot. They will be inaccessible and unrecoverable. will be inaccessible and *unrecoverable*.
Don't forget to add the namespace ``--ns`` parameter if you want to forget a
snapshot that is contained in the root namespace:
.. code-block:: console
# proxmox-backup-client snapshot forget <snapshot> --ns <ns>
Although manual removal is sometimes required, the ``prune`` Although manual removal is sometimes required, the ``prune``

View File

@ -0,0 +1,333 @@
.. _sysadmin_certificate_management:
Certificate Management
----------------------
Access to the API and thus the web-based administration interface is always
encrypted through ``https``. Each `Proxmox Backup`_ host creates by default its
own (self-signed) certificate. This certificate is used for encrypted
communication with the hosts ``proxmox-backup-proxy`` service, for any API
call between a user or backup-client and the web-interface.
Certificate verification when sending backups to a `Proxmox Backup`_ server
is either done based on pinning the certificate fingerprints in the storage/remote
configuration, or by using certificates, signed by a trusted certificate authority.
.. _sysadmin_certs_api_gui:
Certificates for the API and SMTP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`Proxmox Backup`_ stores it certificate and key in:
- ``/etc/proxmox-backup/proxy.pem``
- ``/etc/proxmox-backup/proxy.key``
You have the following options for the certificate:
1. Keep using the default self-signed certificate in
``/etc/proxmox-backup/proxy.pem``.
2. Use an externally provided certificate (for example, signed by a
commercial Certificate Authority (CA)).
3. Use an ACME provider like Lets Encrypt to get a trusted certificate
with automatic renewal; this is also integrated in the `Proxmox Backup`_
API and web interface.
Certificates are managed through the `Proxmox Backup`_
web-interface/API or using the the ``proxmox-backup-manager`` CLI tool.
.. _sysadmin_certs_upload_custom:
Upload Custom Certificate
~~~~~~~~~~~~~~~~~~~~~~~~~
If you already have a certificate which you want to use for a Proxmox
Mail Gateway host, you can simply upload that certificate over the web
interface.
.. image:: images/screenshots/pbs-gui-certs-upload-custom.png
:align: right
:alt: Upload a custom certificate
Note that any certificate key files must not be password protected.
.. _sysadmin_certs_get_trusted_acme_cert:
Trusted certificates via Lets Encrypt (ACME)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`Proxmox Backup`_ includes an implementation of the **A**\ utomatic
**C**\ ertificate **M**\ anagement **E**\ nvironment (**ACME**)
protocol, allowing `Proxmox Backup`_ admins to use an ACME provider
like Lets Encrypt for easy setup of TLS certificates, which are
accepted and trusted by modern operating systems and web browsers out of
the box.
Currently, the two ACME endpoints implemented are the `Lets Encrypt
(LE) <https://letsencrypt.org>`_ production and staging environments.
Our ACME client supports validation of ``http-01`` challenges using a
built-in web server and validation of ``dns-01`` challenges using a DNS
plugin supporting all the DNS API endpoints
`acme.sh <https://acme.sh>`_ does.
.. _sysadmin_certs_acme_account:
ACME Account
^^^^^^^^^^^^
.. image:: images/screenshots/pbs-gui-acme-create-account.png
:align: right
:alt: Create ACME Account
You need to register an ACME account per cluster, with the endpoint you
want to use. The email address used for that account will serve as the
contact point for renewal-due or similar notifications from the ACME
endpoint.
You can register or deactivate ACME accounts over the web interface
``Certificates -> ACME Accounts`` or using the ``proxmox-backup-manager`` command
line tool.
::
proxmox-backup-manager acme account register <account-name> <mail@example.com>
.. tip::
Because of
`rate-limits <https://letsencrypt.org/docs/rate-limits/>`_ you
should use LE ``staging`` for experiments or if you use ACME for the
very first time until all is working there, and only then switch over
to the production directory.
.. _sysadmin_certs_acme_plugins:
ACME Plugins
^^^^^^^^^^^^
The ACME plugins role is to provide automatic verification that you,
and thus the `Proxmox Backup`_ server under your operation, are the
real owner of a domain. This is the basic building block of automatic
certificate management.
The ACME protocol specifies different types of challenges, for example
the ``http-01``, where a web server provides a file with a specific
token to prove that it controls a domain. Sometimes this isnt possible,
either because of technical limitations or if the address of a record is
not reachable from the public internet. The ``dns-01`` challenge can be
used in such cases. This challenge is fulfilled by creating a certain
DNS record in the domains zone.
.. image:: images/screenshots/pbs-gui-acme-create-challenge-plugin.png
:align: right
:alt: Create ACME Account
`Proxmox Backup`_ supports both of those challenge types out of the
box, you can configure plugins either over the web interface under
``Certificates -> ACME Challenges``, or using the
``proxmox-backup-manager acme plugin add`` command.
ACME Plugin configurations are stored in ``/etc/proxmox-backup/acme/plugins.cfg``.
.. _domains:
Domains
^^^^^^^
You can add new or manage existing domain entries under
``Certificates``, or using the ``proxmox-backup-manager`` command.
.. image:: images/screenshots/pbs-gui-acme-add-domain.png
:align: right
:alt: Add a Domain for ACME verification
After configuring the desired domain(s) for a node and ensuring that the
desired ACME account is selected, you can order your new certificate
over the web-interface. On success, the interface will reload after
roughly 10 seconds.
Renewal will happen `automatically <#sysadmin-certs-acme-automatic-renewal>`_
.. _sysadmin_certs_acme_http_challenge:
ACME HTTP Challenge Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~
There is always an implicitly configured ``standalone`` plugin for
validating ``http-01`` challenges via the built-in web server spawned on
port 80.
.. note::
The name ``standalone`` means that it can provide the validation on
its own, without any third party service.
There are a few prerequisites to use this for certificate management
with Lets Encrypts ACME.
- You have to accept the ToS of Lets Encrypt to register an account.
- **Port 80** of the node needs to be reachable from the internet.
- There **must** be no other listener on port 80.
- The requested (sub)domain needs to resolve to a public IP of the
`Proxmox Backup`_ host.
.. _sysadmin_certs_acme_dns_challenge:
ACME DNS API Challenge Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On systems where external access for validation via the ``http-01``
method is not possible or desired, it is possible to use the ``dns-01``
validation method. This validation method requires a DNS server that
allows provisioning of ``TXT`` records via an API.
.. _sysadmin_certs_acme_dns_api_config:
Configuring ACME DNS APIs for validation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
`Proxmox Backup`_ re-uses the DNS plugins developed for the
``acme.sh`` [1]_ project. Please refer to its documentation for details
on configuration of specific APIs.
The easiest way to configure a new plugin with the DNS API is using the
web interface (``Certificates -> ACME Accounts/Challenges``).
Here you can add a new challenge plugin by selecting your API provider
and entering the credential data to access your account over their API.
.. tip::
See the acme.sh `How to use DNS
API <https://github.com/acmesh-official/acme.sh/wiki/dnsapi#how-to-use-dns-api>`_
wiki for more detailed information about getting API credentials for
your provider. Configuration values do not need to be quoted with
single or double quotes; for some plugins that is even an error.
As there are many DNS providers and API endpoints, `Proxmox Backup`_
automatically generates the form for the credentials, but not all
providers are annotated yet. For those you will see a bigger text area,
into which you simply need to copy all the credentials
``KEY``\ =\ ``VALUE`` pairs.
.. _dns_validation_through_cname_alias:
DNS Validation through CNAME Alias
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A special ``alias`` mode can be used to handle validation on a different
domain/DNS server, in case your primary/real DNS does not support
provisioning via an API. Manually set up a permanent ``CNAME`` record
for ``_acme-challenge.domain1.example`` pointing to
``_acme-challenge.domain2.example``, and set the ``alias`` property in
the `Proxmox Backup`_ node configuration file ``/etc/proxmox-backup/node.cfg``
to ``domain2.example`` to allow the DNS server of ``domain2.example`` to
validate all challenges for ``domain1.example``.
.. _sysadmin_certs_acme_dns_wildcard:
Wildcard Certificates
^^^^^^^^^^^^^^^^^^^^^
Wildcard DNS names start with a ``*.`` prefix and are considered valid
for all (one-level) subdomain names of the verified domain. So a
certificate for ``*.domain.example`` is valid for ``foo.domain.example``
and ``bar.domain.example``, but not for ``baz.foo.domain.example``.
Currently, you can only create wildcard certificates with the `DNS
challenge
type <https://letsencrypt.org/docs/challenge-types/#dns-01-challenge>`_.
.. _combination_of_plugins:
Combination of Plugins
^^^^^^^^^^^^^^^^^^^^^^
Combining ``http-01`` and ``dns-01`` validation is possible in case your
node is reachable via multiple domains with different requirements / DNS
provisioning capabilities. Mixing DNS APIs from multiple providers or
instances is also possible by specifying different plugin instances per
domain.
.. tip::
Accessing the same service over multiple domains increases complexity
and should be avoided if possible.
.. _sysadmin_certs_acme_automatic_renewal:
Automatic renewal of ACME certificates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a node has been successfully configured with an ACME-provided
certificate (either via ``proxmox-backup-manager`` or via the web-interface/API), the
certificate will be renewed automatically by the ``proxmox-backup-daily-update.service``.
Currently, renewal is triggered if the certificate either has already
expired or if it will expire in the next 30 days.
.. _manually_change_certificate_over_command_line:
Manually Change Certificate over Command-Line
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want to get rid of certificate verification warnings, you have to
generate a valid certificate for your server.
Log in to your `Proxmox Backup`_ via ssh or use the console:
::
openssl req -newkey rsa:2048 -nodes -keyout key.pem -out req.pem
Follow the instructions on the screen, for example:
::
Country Name (2 letter code) [AU]: AT
State or Province Name (full name) [Some-State]:Vienna
Locality Name (eg, city) []:Vienna
Organization Name (eg, company) [Internet Widgits Pty Ltd]: Proxmox GmbH
Organizational Unit Name (eg, section) []:Proxmox Backup
Common Name (eg, YOUR name) []: yourproxmox.yourdomain.com
Email Address []:support@yourdomain.com
Please enter the following 'extra' attributes to be sent with your certificate request
A challenge password []: not necessary
An optional company name []: not necessary
After you have finished the certificate request, you have to send the
file ``req.pem`` to your Certification Authority (CA). The CA will issue
the certificate (BASE64 encoded), based on your request save this file
as ``cert.pem`` to your `Proxmox Backup`_.
To activate the new certificate, do the following on your `Proxmox Backup`_
::
cp key.pem /etc/proxmox-backup/proxy.key
cp cert.pem /etc/proxmox-backup/proxy.pem
Then restart the API servers:
::
systemctl restart proxmox-backup-proxy
Test your new certificate, using your browser.
.. note::
To transfer files to and from your `Proxmox Backup`_, you can use
secure copy: If your desktop runs Linux, you can use the ``scp``
command line tool. If your desktop PC runs windows, please use an scp
client like WinSCP (see https://winscp.net/).
.. [1]
acme.sh https://github.com/acmesh-official/acme.sh

View File

@ -6,22 +6,37 @@ Command Line Tools
.. include:: proxmox-backup-client/description.rst .. include:: proxmox-backup-client/description.rst
``proxmox-file-restore``
~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: proxmox-file-restore/description.rst
``proxmox-backup-manager`` ``proxmox-backup-manager``
~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: proxmox-backup-manager/description.rst .. include:: proxmox-backup-manager/description.rst
``proxmox-tape``
~~~~~~~~~~~~~~~~
.. include:: proxmox-tape/description.rst
``pmt``
~~~~~~~
.. include:: pmt/description.rst
``pmtx``
~~~~~~~~
.. include:: pmtx/description.rst
``pxar`` ``pxar``
~~~~~~~~ ~~~~~~~~
.. include:: pxar/description.rst .. include:: pxar/description.rst
``proxmox-file-restore``
~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: proxmox-file-restore/description.rst
``proxmox-backup-debug`` ``proxmox-backup-debug``
~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: proxmox-backup-debug/description.rst .. include:: proxmox-backup-debug/description.rst

View File

@ -51,3 +51,13 @@ The following commands are available in an interactive restore shell:
-------- --------
.. include:: pxar/synopsis.rst .. include:: pxar/synopsis.rst
``proxmox-file-restore``
------------------------
.. include:: proxmox-file-restore/synopsis.rst
``proxmox-backup-debug``
------------------------
.. include:: proxmox-backup-debug/synopsis.rst

View File

@ -77,7 +77,7 @@ project = 'Proxmox Backup'
copyright = '2019-2021, Proxmox Server Solutions GmbH' copyright = '2019-2021, Proxmox Server Solutions GmbH'
author = 'Proxmox Support Team' author = 'Proxmox Support Team'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as a replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
@ -108,11 +108,14 @@ today_fmt = '%A, %d %B %Y'
exclude_patterns = [ exclude_patterns = [
'_build', 'Thumbs.db', '.DS_Store', '_build', 'Thumbs.db', '.DS_Store',
'*/man1.rst', '*/man1.rst',
'certificate-management.rst',
'config/*/man5.rst', 'config/*/man5.rst',
'epilog.rst', 'epilog.rst',
'pbs-copyright.rst', 'pbs-copyright.rst',
'local-zfs.rst' 'local-zfs.rst',
'package-repositories.rst', 'package-repositories.rst',
'system-booting.rst',
'traffic-control.rst',
] ]
# The reST default role (used for this markup: `text`) to use for all # The reST default role (used for this markup: `text`) to use for all

View File

@ -35,7 +35,7 @@
.. _ZFS: https://en.wikipedia.org/wiki/ZFS .. _ZFS: https://en.wikipedia.org/wiki/ZFS
.. _Proxmox VE: https://pve.proxmox.com .. _Proxmox VE: https://pve.proxmox.com
.. _RFC3399: https://tools.ietf.org/html/rfc3339 .. _RFC3339: https://tools.ietf.org/html/rfc3339
.. _UTC: https://en.wikipedia.org/wiki/Coordinated_Universal_Time .. _UTC: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
.. _ISO Week date: https://en.wikipedia.org/wiki/ISO_week_date .. _ISO Week date: https://en.wikipedia.org/wiki/ISO_week_date

View File

@ -29,7 +29,7 @@ How long will my Proxmox Backup Server version be supported?
+=======================+======================+===============+============+====================+ +=======================+======================+===============+============+====================+
|Proxmox Backup 2.x | Debian 11 (Bullseye) | 2021-07 | tba | tba | |Proxmox Backup 2.x | Debian 11 (Bullseye) | 2021-07 | tba | tba |
+-----------------------+----------------------+---------------+------------+--------------------+ +-----------------------+----------------------+---------------+------------+--------------------+
|Proxmox Backup 1.x | Debian 10 (Buster) | 2020-11 | ~Q2/2022 | Q2-Q3/2022 | |Proxmox Backup 1.x | Debian 10 (Buster) | 2020-11 | 2022-08 | 2022-07 |
+-----------------------+----------------------+---------------+------------+--------------------+ +-----------------------+----------------------+---------------+------------+--------------------+

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 132 KiB

View File

@ -50,6 +50,7 @@ in the section entitled "GNU Free Documentation License".
file-formats.rst file-formats.rst
backup-protocol.rst backup-protocol.rst
calendarevents.rst calendarevents.rst
markdown-primer.rst
glossary.rst glossary.rst
GFDL.rst GFDL.rst

View File

@ -5,10 +5,11 @@ What is Proxmox Backup Server?
------------------------------ ------------------------------
Proxmox Backup Server is an enterprise-class, client-server backup solution that Proxmox Backup Server is an enterprise-class, client-server backup solution that
is capable of backing up :term:`virtual machine`\ s, :term:`container`\ s, and is capable of backing up :term:`virtual machine<Virtual machine>`\ s,
physical hosts. It is specially optimized for the `Proxmox Virtual Environment`_ :term:`container<Container>`\ s, and physical hosts. It is specially optimized
platform and allows you to back up your data securely, even between remote for the `Proxmox Virtual Environment`_ platform and allows you to back up your
sites, providing easy management through a web-based user interface. data securely, even between remote sites, providing easy management through a
web-based user interface.
It supports deduplication, compression, and authenticated It supports deduplication, compression, and authenticated
encryption (AE_). Using :term:`Rust` as the implementation language guarantees encryption (AE_). Using :term:`Rust` as the implementation language guarantees
@ -34,18 +35,18 @@ For QEMU_ and LXC_ within `Proxmox Virtual Environment`_, we deliver an
integrated client. integrated client.
A single backup is allowed to contain several archives. For example, when you A single backup is allowed to contain several archives. For example, when you
backup a :term:`virtual machine`, each disk is stored as a separate archive backup a :term:`virtual machine<Virtual machine>`, each disk is stored as a
inside that backup. The VM configuration itself is stored as an extra file. separate archive inside that backup. The VM configuration itself is stored as
This way, it's easy to access and restore only the important parts of the an extra file. This way, it's easy to access and restore only the important
backup, without the need to scan the whole backup. parts of the backup, without the need to scan the whole backup.
Main Features Main Features
------------- -------------
:Support for Proxmox VE: The `Proxmox Virtual Environment`_ is fully :Support for Proxmox VE: The `Proxmox Virtual Environment`_ is fully
supported, and you can easily backup :term:`virtual machine`\ s and supported, and you can easily backup :term:`virtual machine<Virtual machine>`\ s and
:term:`container`\ s. :term:`container<Container>`\ s.
:Performance: The whole software stack is written in :term:`Rust`, :Performance: The whole software stack is written in :term:`Rust`,
in order to provide high speed and memory efficiency. in order to provide high speed and memory efficiency.

View File

@ -191,12 +191,12 @@ With `systemd-boot`:
.. code-block:: console .. code-block:: console
# pve-efiboot-tool format <new disk's ESP> # proxmox-boot-tool format <new ESP>
# pve-efiboot-tool init <new disk's ESP> # proxmox-boot-tool init <new ESP>
.. NOTE:: `ESP` stands for EFI System Partition, which is setup as partition #2 on .. NOTE:: `ESP` stands for EFI System Partition, which is setup as partition #2 on
bootable disks setup by the {pve} installer since version 5.4. For details, see bootable disks setup by the `Proxmox Backup`_ installer. For details, see
xref:sysboot_systemd_boot_setup[Setting up a new partition for use as synced ESP]. :ref:`Setting up a new partition for use as synced ESP <systembooting-proxmox-boot-setup>`.
With `grub`: With `grub`:
@ -211,27 +211,22 @@ Usually `grub.cfg` is located in `/boot/grub/grub.cfg`
Activate e-mail notification Activate e-mail notification
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ZFS comes with an event daemon, which monitors events generated by the ZFS comes with an event daemon ``ZED``, which monitors events generated by the
ZFS kernel module. The daemon can also send emails on ZFS events like ZFS kernel module. The daemon can also send emails on ZFS events like pool
pool errors. Newer ZFS packages ship the daemon in a separate package, errors. Newer ZFS packages ship the daemon in a separate package ``zfs-zed``,
and you can install it using `apt-get`: which should already be installed by default in `Proxmox Backup`_.
.. code-block:: console You can configure the daemon via the file ``/etc/zfs/zed.d/zed.rc`` with your
favorite editor. The required setting for email notification is
# apt-get install zfs-zed ``ZED_EMAIL_ADDR``, which is set to ``root`` by default.
To activate the daemon, it is necessary to to uncomment the ZED_EMAIL_ADDR
setting, in the file `/etc/zfs/zed.d/zed.rc`.
.. code-block:: console .. code-block:: console
ZED_EMAIL_ADDR="root" ZED_EMAIL_ADDR="root"
Please note that Proxmox Backup forwards mails to `root` to the email address Please note that `Proxmox Backup`_ forwards mails to `root` to the email address
configured for the root user. configured for the root user.
IMPORTANT: The only setting that is required is `ZED_EMAIL_ADDR`. All
other settings are optional.
Limit ZFS memory usage Limit ZFS memory usage
^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
@ -254,6 +249,7 @@ The above example limits the usage to 8 GiB ('8 * 2^30^').
configuration in `/etc/modprobe.d/zfs.conf`, with: configuration in `/etc/modprobe.d/zfs.conf`, with:
.. code-block:: console .. code-block:: console
options zfs zfs_arc_min=8589934591 options zfs zfs_arc_min=8589934591
options zfs zfs_arc_max=8589934592 options zfs zfs_arc_max=8589934592
@ -273,8 +269,7 @@ Swap on ZFS
^^^^^^^^^^^ ^^^^^^^^^^^
Swap-space created on a zvol may cause some issues, such as blocking the Swap-space created on a zvol may cause some issues, such as blocking the
server or generating a high IO load, often seen when starting a Backup server or generating a high IO load.
to an external Storage.
We strongly recommend using enough memory, so that you normally do not We strongly recommend using enough memory, so that you normally do not
run into low memory situations. Should you need or want to add swap, it is run into low memory situations. Should you need or want to add swap, it is
@ -311,18 +306,20 @@ ZFS compression
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
To activate compression: To activate compression:
.. code-block:: console .. code-block:: console
# zpool set compression=lz4 <pool> # zpool set compression=lz4 <pool>
We recommend using the `lz4` algorithm, since it adds very little CPU overhead. We recommend using the `lz4` algorithm, since it adds very little CPU overhead.
Other algorithms such as `lzjb` and `gzip-N` (where `N` is an integer from `1-9` Other algorithms such as `lzjb`, `zstd` and `gzip-N` (where `N` is an integer from `1-9`
representing the compression ratio, where 1 is fastest and 9 is best representing the compression ratio, where 1 is fastest and 9 is best
compression) are also available. Depending on the algorithm and how compression) are also available. Depending on the algorithm and how
compressible the data is, having compression enabled can even increase I/O compressible the data is, having compression enabled can even increase I/O
performance. performance.
You can disable compression at any time with: You can disable compression at any time with:
.. code-block:: console .. code-block:: console
# zfs set compression=off <dataset> # zfs set compression=off <dataset>

View File

@ -173,6 +173,10 @@ scheduled verification, garbage-collection and synchronization tasks results.
By default, notifications are sent to the email address configured for the By default, notifications are sent to the email address configured for the
`root@pam` user. You can instead set this user for each datastore. `root@pam` user. You can instead set this user for each datastore.
.. image:: images/screenshots/pbs-gui-datastore-options.png
:align: right
:alt: Datastore Options
You can also change the level of notification received per task type, the You can also change the level of notification received per task type, the
following options are available: following options are available:
@ -182,3 +186,20 @@ following options are available:
* Errors: send a notification for any scheduled task that results in an error * Errors: send a notification for any scheduled task that results in an error
* Never: do not send any notification at all * Never: do not send any notification at all
.. _maintenance_mode:
Maintenance Mode
----------------
Proxmox Backup Server implements setting the `read-only` and `offline`
maintenance modes for a datastore.
Once enabled, depending on the mode, new reads and/or writes to the datastore
are blocked, allowing an administrator to safely execute maintenance tasks, for
example, on the underlying storage.
Internally Proxmox Backup Server tracks whether each datastore access is a
write or read operation, so that it can gracefully enter the respective mode,
by allowing conflicting operations that started before enabling the maintenance
mode to finish.

View File

@ -1,5 +1,5 @@
Managing Remotes Managing Remotes & Sync
================ =======================
.. _backup_remote: .. _backup_remote:
@ -107,6 +107,7 @@ of the specified criteria are synced. The available criteria are:
# proxmox-backup-manager sync-job update ID --group-filter group:vm/100 # proxmox-backup-manager sync-job update ID --group-filter group:vm/100
* regular expression matched against the full group identifier * regular expression matched against the full group identifier
.. todo:: add example for regex .. todo:: add example for regex
The same filter is applied to local groups for handling of the The same filter is applied to local groups for handling of the
@ -114,12 +115,93 @@ The same filter is applied to local groups for handling of the
.. note:: The ``protected`` flag of remote backup snapshots will not be synced. .. note:: The ``protected`` flag of remote backup snapshots will not be synced.
Namespace Support
^^^^^^^^^^^^^^^^^
Sync jobs can be configured to not only sync datastores, but also sub-sets of
datastores in the form of namespaces or namespace sub-trees. The following
parameters influence how namespaces are treated as part of a sync job
execution:
- ``remote-ns``: the remote namespace anchor (default: the root namespace)
- ``ns``: the local namespace anchor (default: the root namespace)
- ``max-depth``: whether to recursively iterate over sub-namespaces of the remote
namespace anchor (default: `None`)
If ``max-depth`` is set to `0`, groups are synced from ``remote-ns`` into
``ns``, without any recursion. If it is set to `None` (left empty), recursion
depth will depend on the value of ``remote-ns`` and the remote side's
availability of namespace support:
- ``remote-ns`` set to something other than the root namespace: remote *must*
support namespaces, full recursion starting at ``remote-ns``.
- ``remote-ns`` set to root namespace and remote *supports* namespaces: full
recursion starting at root namespace.
- ``remote-ns`` set to root namespace and remote *does not support* namespaces:
backwards-compat mode, only root namespace will be synced into ``ns``, no
recursion.
Any other value of ``max-depth`` will limit recursion to at most ``max-depth``
levels, for example: ``remote-ns`` set to `location_a/department_b` and
``max-depth`` set to `1` will result in `location_a/department_b` and at most
one more level of sub-namespaces being synced.
The namespace tree starting at ``remote-ns`` will be mapped into ``ns`` up to a
depth of ``max-depth``.
For example, with the following namespaces at the remote side:
- `location_a`
- `location_a/department_x`
- `location_a/department_x/team_one`
- `location_a/department_x/team_two`
- `location_a/department_y`
- `location_a/department_y/team_one`
- `location_a/department_y/team_two`
- `location_b`
and ``remote-ns`` being set to `location_a/department_x` and ``ns`` set to
`location_a_dep_x` resulting in the following namespace tree on the sync
target:
- `location_a_dep_x` (containing the remote's `location_a/department_x`)
- `location_a_dep_x/team_one` (containing the remote's `location_a/department_x/team_one`)
- `location_a_dep_x/team_two` (containing the remote's `location_a/department_x/team_two`)
with the rest of the remote namespaces and groups not being synced (by this
sync job).
If a remote namespace is included in the sync job scope, but does not exist
locally, it will be created (provided the sync job owner has sufficient
privileges).
If the ``remove-vanished`` option is set, namespaces that are included in the
sync job scope but only exist locally are treated as vanished and removed
(provided the sync job owner has sufficient privileges).
.. note:: All other limitations on sync scope (such as remote user/API token
privileges, group filters) also apply for sync jobs involving one or
multiple namespaces.
Bandwidth Limit Bandwidth Limit
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
Syncing datastores to an archive can produce lots of traffic and impact other Syncing a datastore to an archive can produce lots of traffic and impact other
users of the network. So, to avoid network or storage congetsion you can limit users of the network. So, to avoid network or storage congestion you can limit
the bandwith of the sync job by setting the ``rate-in`` option either in the the bandwidth of the sync job by setting the ``rate-in`` option either in the
web interface or using the ``proxmox-backup-manager`` command-line tool: web interface or using the ``proxmox-backup-manager`` command-line tool:
.. code-block:: console .. code-block:: console

178
docs/markdown-primer.rst Normal file
View File

@ -0,0 +1,178 @@
.. _markdown-primer:
Markdown Primer
===============
"Markdown is a text-to-HTML conversion tool for web writers. Markdown allows
you to write using an easy-to-read, easy-to-write plain text format, then
convertit to structurally valid XHTML (or HTML)."
-- John Gruber, https://daringfireball.net/projects/markdown/
The Proxmox Backup Server (PBS) web-interface has support for using Markdown to
rendering rich text formatting in node and virtual guest notes.
PBS supports CommonMark with most extensions of GFM (GitHub Flavoured Markdown),
like tables or task-lists.
.. _markdown_basics:
Markdown Basics
---------------
Note that we only describe the basics here, please search the web for more
extensive resources, for example on https://www.markdownguide.org/
Headings
~~~~~~~~
.. code-block:: md
# This is a Heading h1
## This is a Heading h2
##### This is a Heading h5
Emphasis
~~~~~~~~
Use ``*text*`` or ``_text_`` for emphasis.
Use ``**text**`` or ``__text__`` for bold, heavy-weight text.
Combinations are also possible, for example:
.. code-block:: md
_You **can** combine them_
Links
~~~~~
You can use automatic detection of links, for example,
``https://forum.proxmox.com/`` would transform it into a clickable link.
You can also control the link text, for example:
.. code-block:: md
Now, [the part in brackets will be the link text](https://forum.proxmox.com/).
Lists
~~~~~
Unordered Lists
^^^^^^^^^^^^^^^
Use ``*`` or ``-`` for unordered lists, for example:
.. code-block:: md
* Item 1
* Item 2
* Item 2a
* Item 2b
Adding an indentation can be used to created nested lists.
Ordered Lists
^^^^^^^^^^^^^
.. code-block:: md
1. Item 1
1. Item 2
1. Item 3
1. Item 3a
1. Item 3b
NOTE: The integer of ordered lists does not need to be correct, they will be numbered automatically.
Task Lists
^^^^^^^^^^
Task list use a empty box ``[ ]`` for unfinished tasks and a box with an `X` for finished tasks.
For example:
.. code-block:: md
- [X] First task already done!
- [X] Second one too
- [ ] This one is still to-do
- [ ] So is this one
Tables
~~~~~~
Tables use the pipe symbol ``|`` to separate columns, and ``-`` to separate the
table header from the table body, in that separation one can also set the text
alignment, making one column left-, center-, or right-aligned.
.. code-block:: md
| Left columns | Right columns | Some | More | Cols.| Centering Works Too
| ------------- |--------------:|--------|------|------|:------------------:|
| left foo | right foo | First | Row | Here | >center< |
| left bar | right bar | Second | Row | Here | 12345 |
| left baz | right baz | Third | Row | Here | Test |
| left zab | right zab | Fourth | Row | Here | ☁️☁️☁️ |
| left rab | right rab | And | Last | Here | The End |
Note that you do not need to align the columns nicely with white space, but that makes
editing tables easier.
Block Quotes
~~~~~~~~~~~~
You can enter block quotes by prefixing a line with ``>``, similar as in plain-text emails.
.. code-block:: md
> Markdown is a lightweight markup language with plain-text-formatting syntax,
> created in 2004 by John Gruber with Aaron Swartz.
>
>> Markdown is often used to format readme files, for writing messages in online discussion forums,
>> and to create rich text using a plain text editor.
Code and Snippets
~~~~~~~~~~~~~~~~~
You can use backticks to avoid processing for a few word or paragraphs. That is useful for
avoiding that a code or configuration hunk gets mistakenly interpreted as markdown.
Inline code
^^^^^^^^^^^
Surrounding part of a line with single backticks allows to write code inline,
for examples:
.. code-block:: md
This hosts IP address is `10.0.0.1`.
Whole blocks of code
^^^^^^^^^^^^^^^^^^^^
For code blocks spanning several lines you can use triple-backticks to start
and end such a block, for example:
.. code-block:: md
```
# This is the network config I want to remember here
auto vmbr2
iface vmbr2 inet static
address 10.0.0.1/24
bridge-ports ens20
bridge-stp off
bridge-fd 0
bridge-vlan-aware yes
bridge-vids 2-4094
```

View File

@ -3,6 +3,10 @@
Network Management Network Management
================== ==================
.. image:: images/screenshots/pbs-gui-system-config.png
:align: right
:alt: System and Network Configuration Overview
Proxmox Backup Server provides both a web interface and a command line tool for Proxmox Backup Server provides both a web interface and a command line tool for
network configuration. You can find the configuration options in the web network configuration. You can find the configuration options in the web
interface under the **Network Interfaces** section of the **Configuration** menu interface under the **Network Interfaces** section of the **Configuration** menu
@ -31,10 +35,6 @@ To get a list of available interfaces, use the following command:
│ ens19 │ eth │ 1 │ manual │ │ │ │ │ ens19 │ eth │ 1 │ manual │ │ │ │
└───────┴────────┴───────────┴────────┴─────────────┴──────────────┴──────────────┘ └───────┴────────┴───────────┴────────┴─────────────┴──────────────┴──────────────┘
.. image:: images/screenshots/pbs-gui-network-create-bond.png
:align: right
:alt: Add a network interface
To add a new network interface, use the ``create`` subcommand with the relevant To add a new network interface, use the ``create`` subcommand with the relevant
parameters. For example, you may want to set up a bond, for the purpose of parameters. For example, you may want to set up a bond, for the purpose of
network redundancy. The following command shows a template for creating the bond shown network redundancy. The following command shows a template for creating the bond shown
@ -44,6 +44,10 @@ in the list above:
# proxmox-backup-manager network create bond0 --type bond --bond_mode active-backup --slaves ens18,ens19 --autostart true --cidr x.x.x.x/x --gateway x.x.x.x # proxmox-backup-manager network create bond0 --type bond --bond_mode active-backup --slaves ens18,ens19 --autostart true --cidr x.x.x.x/x --gateway x.x.x.x
.. image:: images/screenshots/pbs-gui-network-create-bond.png
:align: right
:alt: Add a network interface
You can make changes to the configuration of a network interface with the You can make changes to the configuration of a network interface with the
``update`` subcommand: ``update`` subcommand:

View File

@ -27,6 +27,10 @@ update``.
In addition, you need a package repository from Proxmox to get Proxmox Backup In addition, you need a package repository from Proxmox to get Proxmox Backup
updates. updates.
.. image:: images/screenshots/pbs-gui-administration-apt-repos.png
:align: right
:alt: APT Repository Management in the Web Interface
.. _package_repos_secure_apt: .. _package_repos_secure_apt:
SecureApt SecureApt

View File

@ -51,7 +51,7 @@ ENVIRONMENT
:CHANGER: If set, replaces the `--device` option :CHANGER: If set, replaces the `--device` option
:PROXMOX_TAPE_DRIVE: If set, use the Proxmox Backup Server :PROXMOX_TAPE_DRIVE: If set, use the Proxmox Backup Server
configuration to find the associcated changer device. configuration to find the associated changer device.
.. include:: ../pbs-copyright.rst .. include:: ../pbs-copyright.rst

View File

@ -11,8 +11,13 @@ Disk Management
:alt: List of disks :alt: List of disks
Proxmox Backup Server comes with a set of disk utilities, which are Proxmox Backup Server comes with a set of disk utilities, which are
accessed using the ``disk`` subcommand. This subcommand allows you to initialize accessed using the ``disk`` subcommand or the web interface. This subcommand
disks, create various filesystems, and get information about the disks. allows you to initialize disks, create various filesystems, and get information
about the disks.
.. image:: images/screenshots/pbs-gui-disks.png
:align: right
:alt: Web Interface Administration: Disks
To view the disks connected to the system, navigate to **Administration -> To view the disks connected to the system, navigate to **Administration ->
Storage/Disks** in the web interface or use the ``list`` subcommand of Storage/Disks** in the web interface or use the ``list`` subcommand of
@ -90,6 +95,10 @@ display S.M.A.R.T. attributes from the web interface or by using the command:
:term:`Datastore` :term:`Datastore`
----------------- -----------------
.. image:: images/screenshots/pbs-gui-datastore-summary.png
:align: right
:alt: Datastore Usage Overview
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
implementation uses a directory inside a standard Unix file system (``ext4``, implementation uses a directory inside a standard Unix file system (``ext4``,
``xfs`` or ``zfs``) to store the backup data. ``xfs`` or ``zfs``) to store the backup data.
@ -111,7 +120,7 @@ Datastore Configuration
.. image:: images/screenshots/pbs-gui-datastore-content.png .. image:: images/screenshots/pbs-gui-datastore-content.png
:align: right :align: right
:alt: Datastore Overview :alt: Datastore Content Overview
You can configure multiple datastores. A minimum of one datastore needs to be You can configure multiple datastores. A minimum of one datastore needs to be
configured. The datastore is identified by a simple *name* and points to a configured. The datastore is identified by a simple *name* and points to a
@ -128,7 +137,7 @@ run periodically, based on a configured schedule (see
Creating a Datastore Creating a Datastore
^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
.. image:: images/screenshots/pbs-gui-datastore-create-general.png .. image:: images/screenshots/pbs-gui-datastore-create.png
:align: right :align: right
:alt: Create a datastore :alt: Create a datastore
@ -252,3 +261,57 @@ categorized by checksum, after a backup operation has been executed.
276490 drwxr-x--- 1 backup backup 1.1M Jul 8 12:35 . 276490 drwxr-x--- 1 backup backup 1.1M Jul 8 12:35 .
Once you uploaded some backups, or created namespaces, you may see the Backup
Type (`ct`, `vm`, `host`) and the start of the namespace hierarchy (`ns`).
.. _storage_namespaces:
Backup Namespaces
~~~~~~~~~~~~~~~~~
A datastore can host many backups as long as the underlying storage is big
enough and provides the performance required for one's use case.
But, without any hierarchy or separation its easy to run into naming conflicts,
especially when using the same datastore for multiple Proxmox VE instances or
multiple users.
The backup namespace hierarchy allows you to clearly separate different users
or backup sources in general, avoiding naming conflicts and providing
well-organized backup content view.
Each namespace level can host any backup type, CT, VM or Host but also other
namespaces, up to a depth of 8 level, where the root namespace is the first
level.
Namespace Permissions
^^^^^^^^^^^^^^^^^^^^^
You can make the permission configuration of a datastore more fine-grained by
setting permissions only on a specific namespace.
To see a datastore you need permission that has at least one of `AUDIT`,
`MODIFY`, `READ` or `BACKUP` privilege on any namespace it contains.
To create or delete a namespace you require the modify privilege on the parent
namespace. So, to initially create namespaces you need to have a permission
with a access role that includes the `MODIFY` privilege on the datastore itself.
For backup groups the existing privilege rules still apply, you either need a
powerful permission or be the owner of the backup group, nothing changed here.
.. todo:: continue
Options
~~~~~~~
.. image:: images/screenshots/pbs-gui-datastore-options.png
:align: right
:alt: Datastore Options
There are a few per-datastore options:
* :ref:`Notifications <maintenance_notification>`
* :ref:`Maintenance Mode <maintenance_mode>`
* Verification of incoming backups

View File

@ -15,10 +15,8 @@ through that channel. In addition, we provide our own package
repository to roll out all Proxmox related packages. This includes repository to roll out all Proxmox related packages. This includes
updates to some Debian packages when necessary. updates to some Debian packages when necessary.
We also deliver a specially optimized Linux kernel, where we enable We also deliver a specially optimized Linux kernel, based on the Ubuntu
all required virtualization and container features. That kernel kernel. That kernel includes drivers for ZFS_.
includes drivers for ZFS_, as well as several hardware drivers. For example,
we ship Intel network card drivers to support their newest hardware.
The following sections will concentrate on backup related topics. They The following sections will concentrate on backup related topics. They
will explain things which are different on `Proxmox Backup`_, or will explain things which are different on `Proxmox Backup`_, or
@ -28,4 +26,10 @@ please refer to the standard Debian documentation.
.. include:: local-zfs.rst .. include:: local-zfs.rst
.. include:: system-booting.rst
.. include:: certificate-management.rst
.. include:: services.rst .. include:: services.rst
.. include:: command-line-tools.rst

379
docs/system-booting.rst Normal file
View File

@ -0,0 +1,379 @@
.. _chapter-systembooting:
Host Bootloader
---------------
`Proxmox Backup`_ currently uses one of two bootloaders depending on the disk setup
selected in the installer.
For EFI Systems installed with ZFS as the root filesystem ``systemd-boot`` is
used. All other deployments use the standard ``grub`` bootloader (this usually
also applies to systems which are installed on top of Debian).
.. _systembooting-installer-part-scheme:
Partitioning Scheme Used by the Installer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The `Proxmox Backup`_ installer creates 3 partitions on all disks selected for
installation.
The created partitions are:
* a 1 MB BIOS Boot Partition (gdisk type EF02)
* a 512 MB EFI System Partition (ESP, gdisk type EF00)
* a third partition spanning the set ``hdsize`` parameter or the remaining space
used for the chosen storage type
Systems using ZFS as root filesystem are booted with a kernel and initrd image
stored on the 512 MB EFI System Partition. For legacy BIOS systems, ``grub`` is
used, for EFI systems ``systemd-boot`` is used. Both are installed and configured
to point to the ESPs.
``grub`` in BIOS mode (``--target i386-pc``) is installed onto the BIOS Boot
Partition of all selected disks on all systems booted with ``grub`` (These are
all installs with root on ``ext4`` or ``xfs`` and installs with root on ZFS on
non-EFI systems).
.. _systembooting-proxmox-boot-tool:
Synchronizing the content of the ESP with ``proxmox-boot-tool``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``proxmox-boot-tool`` is a utility used to keep the contents of the EFI System
Partitions properly configured and synchronized. It copies certain kernel
versions to all ESPs and configures the respective bootloader to boot from
the ``vfat`` formatted ESPs. In the context of ZFS as root filesystem this means
that you can use all optional features on your root pool instead of the subset
which is also present in the ZFS implementation in ``grub`` or having to create a
separate small boot-pool (see: `Booting ZFS on root with grub
<https://github.com/zfsonlinux/zfs/wiki/Debian-Stretch-Root-on-ZFS>`_).
In setups with redundancy all disks are partitioned with an ESP, by the
installer. This ensures the system boots even if the first boot device fails
or if the BIOS can only boot from a particular disk.
The ESPs are not kept mounted during regular operation. This helps to prevent
filesystem corruption to the ``vfat`` formatted ESPs in case of a system crash,
and removes the need to manually adapt ``/etc/fstab`` in case the primary boot
device fails.
``proxmox-boot-tool`` handles the following tasks:
* formatting and setting up a new partition
* copying and configuring new kernel images and initrd images to all listed ESPs
* synchronizing the configuration on kernel upgrades and other maintenance tasks
* managing the list of kernel versions which are synchronized
* configuring the boot-loader to boot a particular kernel version (pinning)
You can view the currently configured ESPs and their state by running:
.. code-block:: console
# proxmox-boot-tool status
.. _systembooting-proxmox-boot-setup:
Setting up a new partition for use as synced ESP
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To format and initialize a partition as synced ESP, e.g., after replacing a
failed vdev in an rpool, ``proxmox-boot-tool`` from ``pve-kernel-helper`` can be used.
WARNING: the ``format`` command will format the ``<partition>``, make sure to pass
in the right device/partition!
For example, to format an empty partition ``/dev/sda2`` as ESP, run the following:
.. code-block:: console
# proxmox-boot-tool format /dev/sda2
To setup an existing, unmounted ESP located on ``/dev/sda2`` for inclusion in
`Proxmox Backup`_'s kernel update synchronization mechanism, use the following:
.. code-block:: console
# proxmox-boot-tool init /dev/sda2
Afterwards `/etc/kernel/proxmox-boot-uuids`` should contain a new line with the
UUID of the newly added partition. The ``init`` command will also automatically
trigger a refresh of all configured ESPs.
.. _systembooting-proxmox-boot-refresh:
Updating the configuration on all ESPs
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To copy and configure all bootable kernels and keep all ESPs listed in
``/etc/kernel/proxmox-boot-uuids`` in sync you just need to run:
.. code-block:: console
# proxmox-boot-tool refresh
(The equivalent to running ``update-grub`` systems with ``ext4`` or ``xfs`` on root).
This is necessary should you make changes to the kernel commandline, or want to
sync all kernels and initrds.
.. NOTE:: Both ``update-initramfs`` and ``apt`` (when necessary) will automatically
trigger a refresh.
Kernel Versions considered by ``proxmox-boot-tool``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following kernel versions are configured by default:
* the currently running kernel
* the version being newly installed on package updates
* the two latest already installed kernels
* the latest version of the second-to-last kernel series (e.g. 5.0, 5.3), if applicable
* any manually selected kernels
Manually keeping a kernel bootable
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Should you wish to add a certain kernel and initrd image to the list of
bootable kernels use ``proxmox-boot-tool kernel add``.
For example run the following to add the kernel with ABI version ``5.0.15-1-pve``
to the list of kernels to keep installed and synced to all ESPs:
.. code-block:: console
# proxmox-boot-tool kernel add 5.0.15-1-pve
``proxmox-boot-tool kernel list`` will list all kernel versions currently selected
for booting:
.. code-block:: console
# proxmox-boot-tool kernel list
Manually selected kernels:
5.0.15-1-pve
Automatically selected kernels:
5.0.12-1-pve
4.15.18-18-pve
Run ``proxmox-boot-tool kernel remove`` to remove a kernel from the list of
manually selected kernels, for example:
.. code-block:: console
# proxmox-boot-tool kernel remove 5.0.15-1-pve
.. NOTE:: It's required to run ``proxmox-boot-tool refresh`` to update all EFI System
Partitions (ESPs) after a manual kernel addition or removal from above.
.. _systembooting-determine-bootloader:
Determine which Bootloader is Used
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. image:: images/screenshots/boot-grub.png
:target: _images/boot-grub.png
:align: left
:alt: Grub boot screen
The simplest and most reliable way to determine which bootloader is used, is to
watch the boot process of the `Proxmox Backup`_ node.
You will either see the blue box of ``grub`` or the simple black on white
``systemd-boot``.
.. image:: images/screenshots/boot-systemdboot.png
:target: _images/boot-systemdboot.png
:align: right
:alt: systemd-boot screen
Determining the bootloader from a running system might not be 100% accurate. The
safest way is to run the following command:
.. code-block:: console
# efibootmgr -v
If it returns a message that EFI variables are not supported, ``grub`` is used in
BIOS/Legacy mode.
If the output contains a line that looks similar to the following, ``grub`` is
used in UEFI mode.
.. code-block:: console
Boot0005* proxmox [...] File(\EFI\proxmox\grubx64.efi)
If the output contains a line similar to the following, ``systemd-boot`` is used.
.. code-block:: console
Boot0006* Linux Boot Manager [...] File(\EFI\systemd\systemd-bootx64.efi)
By running:
.. code-block:: console
# proxmox-boot-tool status
you can find out if ``proxmox-boot-tool`` is configured, which is a good
indication of how the system is booted.
.. _systembooting-grub:
Grub
~~~~
``grub`` has been the de-facto standard for booting Linux systems for many years
and is quite well documented
(see the `Grub Manual
<https://www.gnu.org/software/grub/manual/grub/grub.html>`_).
Configuration
^^^^^^^^^^^^^
Changes to the ``grub`` configuration are done via the defaults file
``/etc/default/grub`` or config snippets in ``/etc/default/grub.d``. To regenerate
the configuration file after a change to the configuration run:
.. code-block:: console
# update-grub
.. NOTE:: Systems using ``proxmox-boot-tool`` will call
``proxmox-boot-tool refresh`` upon ``update-grub``
.. _systembooting-systemdboot:
Systemd-boot
~~~~~~~~~~~~
``systemd-boot`` is a lightweight EFI bootloader. It reads the kernel and initrd
images directly from the EFI Service Partition (ESP) where it is installed.
The main advantage of directly loading the kernel from the ESP is that it does
not need to reimplement the drivers for accessing the storage. In `Proxmox
Backup`_ :ref:`proxmox-boot-tool <systembooting-proxmox-boot-tool>` is used to
keep the configuration on the ESPs synchronized.
.. _systembooting-systemd-boot-config:
Configuration
^^^^^^^^^^^^^
``systemd-boot`` is configured via the file ``loader/loader.conf`` in the root
directory of an EFI System Partition (ESP). See the ``loader.conf(5)`` manpage
for details.
Each bootloader entry is placed in a file of its own in the directory
``loader/entries/``
An example entry.conf looks like this (``/`` refers to the root of the ESP):
.. code-block:: console
title Proxmox
version 5.0.15-1-pve
options root=ZFS=rpool/ROOT/pve-1 boot=zfs
linux /EFI/proxmox/5.0.15-1-pve/vmlinuz-5.0.15-1-pve
initrd /EFI/proxmox/5.0.15-1-pve/initrd.img-5.0.15-1-pve
.. _systembooting-edit-kernel-cmdline:
Editing the Kernel Commandline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can modify the kernel commandline in the following places, depending on the
bootloader used:
Grub
^^^^
The kernel commandline needs to be placed in the variable
``GRUB_CMDLINE_LINUX_DEFAULT`` in the file ``/etc/default/grub``. Running
``update-grub`` appends its content to all ``linux`` entries in
``/boot/grub/grub.cfg``.
Systemd-boot
^^^^^^^^^^^^
The kernel commandline needs to be placed as one line in ``/etc/kernel/cmdline``.
To apply your changes, run ``proxmox-boot-tool refresh``, which sets it as the
``option`` line for all config files in ``loader/entries/proxmox-*.conf``.
.. _systembooting-kernel-pin:
Override the Kernel-Version for next Boot
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To select a kernel that is not currently the default kernel, you can either:
* use the boot loader menu that is displayed at the beginning of the boot
process
* use the ``proxmox-boot-tool`` to ``pin`` the system to a kernel version either
once or permanently (until pin is reset).
This should help you work around incompatibilities between a newer kernel
version and the hardware.
.. NOTE:: Such a pin should be removed as soon as possible so that all current
security patches of the latest kernel are also applied to the system.
For example: To permanently select the version ``5.15.30-1-pve`` for booting you
would run:
.. code-block:: console
# proxmox-boot-tool kernel pin 5.15.30-1-pve
.. TIP:: The pinning functionality works for all `Proxmox Backup`_ systems, not only those using
``proxmox-boot-tool`` to synchronize the contents of the ESPs, if your system
does not use ``proxmox-boot-tool`` for synchronizing you can also skip the
``proxmox-boot-tool refresh`` call in the end.
You can also set a kernel version to be booted on the next system boot only.
This is for example useful to test if an updated kernel has resolved an issue,
which caused you to ``pin`` a version in the first place:
.. code-block:: console
# proxmox-boot-tool kernel pin 5.15.30-1-pve --next-boot
To remove any pinned version configuration use the ``unpin`` subcommand:
.. code-block:: console
# proxmox-boot-tool kernel unpin
While ``unpin`` has a ``--next-boot`` option as well, it is used to clear a pinned
version set with ``--next-boot``. As that happens already automatically on boot,
invonking it manually is of little use.
After setting, or clearing pinned versions you also need to synchronize the
content and configuration on the ESPs by running the ``refresh`` subcommand.
.. TIP:: You will be prompted to automatically do for ``proxmox-boot-tool`` managed
systems if you call the tool interactively.
.. code-block:: console
# proxmox-boot-tool refresh

View File

@ -500,7 +500,7 @@ a single media pool, so a job only uses tapes from that pool.
is less space efficient, because the media from the last set is less space efficient, because the media from the last set
may not be fully written, leaving the remaining space unused. may not be fully written, leaving the remaining space unused.
The advantage is that this procudes media sets of minimal The advantage is that this produces media sets of minimal
size. Small sets are easier to handle, can be moved more conveniently size. Small sets are easier to handle, can be moved more conveniently
to an off-site vault, and can be restored much faster. to an off-site vault, and can be restored much faster.
@ -519,8 +519,9 @@ a single media pool, so a job only uses tapes from that pool.
This balances between space efficiency and media count. This balances between space efficiency and media count.
.. NOTE:: Retention period starts when the calendar event .. NOTE:: Retention period starts on the creation time of the next
triggers. media-set or, if that does not exist, when the calendar event
triggers the next time after the current media-set start time.
Additionally, the following events may allocate a new media set: Additionally, the following events may allocate a new media set:
@ -564,13 +565,6 @@ a single media pool, so a job only uses tapes from that pool.
the password. Please make sure to remember the password, in case the password. Please make sure to remember the password, in case
you need to restore the key. you need to restore the key.
.. NOTE:: We use global content namespace, meaning we do not store the
source datastore name. Because of this, it is impossible to distinguish
store1:/vm/100 from store2:/vm/100. Please use different media pools
if the sources are from different namespaces with conflicting names
(for example, if the sources are from different Proxmox VE clusters).
.. image:: images/screenshots/pbs-gui-tape-pools-add.png .. image:: images/screenshots/pbs-gui-tape-pools-add.png
:align: right :align: right
:alt: Tape Backup: Add a media pool :alt: Tape Backup: Add a media pool
@ -687,6 +681,16 @@ To remove a job, please use:
# proxmox-tape backup-job remove job2 # proxmox-tape backup-job remove job2
By default, all (recursive) namespaces of the datastore are included in a tape
backup. You can specify a single namespace with ``ns`` and a depth with
``max-depth``. For example:
.. code-block:: console
# proxmox-tape backup-job update job2 --ns mynamespace --max-depth 3
If no `max-depth` is given, it will include all recursive namespaces.
.. image:: images/screenshots/pbs-gui-tape-backup-jobs-add.png .. image:: images/screenshots/pbs-gui-tape-backup-jobs-add.png
:align: right :align: right
:alt: Tape Backup: Add a backup job :alt: Tape Backup: Add a backup job
@ -803,6 +807,16 @@ The following options are available:
media set into import-export slots. The operator can then pick up media set into import-export slots. The operator can then pick up
those tapes and move them to a media vault. those tapes and move them to a media vault.
--ns The namespace to backup.
If you only want to backup a specific namespace. If omitted, the root
namespaces is assumed.
--max-depth The depth to recurse namespaces.
``0`` means no recursion at all (only the given namespace). If omitted,
all namespaces are recursed (below the the given one).
Restore from Tape Restore from Tape
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
@ -837,6 +851,53 @@ data disk (datastore):
# proxmox-tape restore 9da37a55-aac7-4deb-91c6-482b3b675f30 mystore # proxmox-tape restore 9da37a55-aac7-4deb-91c6-482b3b675f30 mystore
Single Snapshot Restore
^^^^^^^^^^^^^^^^^^^^^^^
Sometimes it is not necessary to restore a whole media-set, but only some
specific snapshots from the tape. This can be achieved with the ``snapshots``
parameter:
.. code-block:: console
// proxmox-tape restore <media-set-uuid> <datastore> [<snapshot>]
# proxmox-tape restore 9da37a55-aac7-4deb-91c6-482b3b675f30 mystore sourcestore:host/hostname/2022-01-01T00:01:00Z
This first restores the snapshot to a temporary location, then restores the relevant
chunk archives, and finally restores the snapshot data to the target datastore.
The ``snapshot`` parameter can be given multiple times, so one can restore
multiple snapshots with one restore action.
.. NOTE:: When using the single snapshot restore, the tape must be traversed
more than once, which, if you restore many snapshots at once, can take longer
than restoring the whole datastore.
Namespaces
^^^^^^^^^^
It is also possible to select and map specific namespaces from a media-set
during a restore. This is possible with the ``namespaces`` parameter.
The format of the parameter is
.. code-block:: console
store=<source-datastore>[,source=<source-ns>][,target=<target-ns>][,max-depth=<depth>]
If ``source`` or ``target`` is not given, the root namespace is assumed.
When no ``max-depth`` is given, the source namespace will be fully recursed.
An example restore command:
.. code-block:: console
# proxmox-tape restore 9da37a55-aac7-4deb-91c6-482b3b675f30 mystore --namespaces store=sourcedatastore,source=ns1,target=ns2,max-depth=2
The parameter can be given multiple times. It can also be combined with the
``snapshots`` parameter to only restore those snapshots and map them to different
namespaces.
Update Inventory Update Inventory
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
@ -978,3 +1039,76 @@ This command does the following:
- run drive cleaning operation - run drive cleaning operation
- unload the cleaning tape (to slot 3) - unload the cleaning tape (to slot 3)
Example Setups
--------------
Here are a few example setups for how to manage media pools and schedules.
This is not an exhaustive list, and there are many more possible combinations
of useful settings.
Single Continued Media Set
~~~~~~~~~~~~~~~~~~~~~~~~~~
The most simple setup: always continue the media-set and never expire.
Allocation policy:
continue
Retention policy:
keep
This setup has the advantage of being easy to manage and is re-using the benefits
from deduplication as much as possible. But, it's also prone to a failure of
any single tape, which would render all backups referring to chunks from that
tape unusable.
If you want to start a new media-set manually, you can set the currently
writable media of the set either to 'full', or set the location to an
offsite vault.
Weekday Scheme
~~~~~~~~~~~~~~
A slightly more complex scheme, where the goal is to have an independent
tape or media set for each weekday, for example from Monday to Friday.
This can be solved by having a separate media pool for each day, so 'Monday',
'Tuesday', etc.
Allocation policy:
should be 'mon' for the 'Monday' pool, 'tue' for the Tuesday pool and so on.
Retention policy:
overwrite
There should be a (or more) tape-backup jobs for each pool on the corresponding
weekday. This scheme is still very manageable with one media set per weekday,
and could be easily moved off-site.
Multiple Pools with Different Policies
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Complex setups are also possible with multiple media pools configured with
different allocation and retention policies.
An example would be to have two media pools. The first configured with weekly
allocation and a few weeks of retention:
Allocation policy:
mon
Retention policy:
3 weeks
The second pool configured yearly allocation that does not expire:
Allocation policy:
yearly
Retention policy:
keep
In combination with suited prune settings and tape backup schedules, this
achieves long-term storage of some backups, while keeping the current
backups on smaller media sets that get expired every three plus the current
week (~ 4 weeks).

View File

@ -61,6 +61,15 @@ The manifest contains a list of all backed up files, and their
sizes and checksums. It is used to verify the consistency of a sizes and checksums. It is used to verify the consistency of a
backup. backup.
Backup Namespace
----------------
Namespaces allow for the reuse of a single chunk store deduplication domain for
multiple sources, while avoiding naming conflicts and getting more fine-grained
access control.
Essentially they're implemented as simple directory structure and need no
separate configuration.
Backup Type Backup Type
----------- -----------
@ -68,13 +77,14 @@ Backup Type
The backup server groups backups by *type*, where *type* is one of: The backup server groups backups by *type*, where *type* is one of:
``vm`` ``vm``
This type is used for :term:`virtual machine`\ s. It typically This type is used for :term:`virtual machine<Virtual machine>`\ s. It
consists of the virtual machine's configuration file and an image archive typically consists of the virtual machine's configuration file and an image
for each disk. archive for each disk.
``ct`` ``ct``
This type is used for :term:`container`\ s. It consists of the container's This type is used for :term:`container<Container>`\ s. It consists of the
configuration and a single file archive for the filesystem's contents. container's configuration and a single file archive for the filesystem's
contents.
``host`` ``host``
This type is used for file/directory backups created from within a machine. This type is used for file/directory backups created from within a machine.
@ -82,25 +92,25 @@ The backup server groups backups by *type*, where *type* is one of:
or container. Such backups may contain file and image archives; there are no or container. Such backups may contain file and image archives; there are no
restrictions in this regard. restrictions in this regard.
Backup ID Backup ID
--------- ---------
A unique ID. Usually the virtual machine or container ID. ``host`` A unique ID for a specific Backup Type and Backup Namespace. Usually the
type backups normally use the hostname. virtual machine or container ID. ``host`` type backups normally use the
hostname.
Backup Time Backup Time
----------- -----------
The time when the backup was made. The time when the backup was made with second resolution.
Backup Group Backup Group
------------ ------------
The tuple ``<type>/<ID>`` is called a backup group. Such a group The tuple ``<type>/<id>`` is called a backup group. Such a group may contain
may contain one or more backup snapshots. one or more backup snapshots.
.. _term_backup_snapshot: .. _term_backup_snapshot:
@ -116,7 +126,7 @@ uniquely identifies a specific backup within a datastore.
vm/104/2019-10-09T08:01:06Z vm/104/2019-10-09T08:01:06Z
host/elsa/2019-11-08T09:48:14Z host/elsa/2019-11-08T09:48:14Z
As you can see, the time format is RFC3399_ with Coordinated As you can see, the time format is RFC3339_ with Coordinated
Universal Time (UTC_, identified by the trailing *Z*). Universal Time (UTC_, identified by the trailing *Z*).

View File

@ -21,7 +21,7 @@ You can manage the traffic controls either over the web-interface or using the
tool. tool.
.. note:: Sync jobs on the server are not affected by its rate-in limits. If .. note:: Sync jobs on the server are not affected by its rate-in limits. If
you want to limit the incomming traffic that a pull-based sync job you want to limit the incoming traffic that a pull-based sync job
generates, you need to setup a job-specific rate-in limit. See generates, you need to setup a job-specific rate-in limit. See
:ref:`syncjobs`. :ref:`syncjobs`.

View File

@ -157,34 +157,133 @@ Access Control
-------------- --------------
By default, new users and API tokens do not have any permissions. Instead you By default, new users and API tokens do not have any permissions. Instead you
need to specify what is allowed and what is not. You can do this by assigning need to specify what is allowed and what is not.
roles to users/tokens on specific objects, like datastores or remotes. The
following roles exist: Proxmox Backup Server uses a role and path based permission management system.
An entry in the permissions table allows a user, group or token to take on a
specific role when accessing an 'object' or 'path'. This means that such an
access rule can be represented as a triple of '(path, user, role)', '(path,
group, role)' or '(path, token, role)', with the role containing a set of
allowed actions, and the path representing the target of these actions.
Privileges
~~~~~~~~~~
Privileges are the atoms that access roles are made off. They are internally
used to enforce the actual permission checks in the API.
We currently support the following privileges:
**Sys.Audit**
Sys.Audit allows one to know about the system and its status.
**Sys.Modify**
Sys.Modify allows one to modify system-level configuration and apply updates.
**Sys.PowerManagement**
Sys.Modify allows one to to poweroff or reboot the system.
**Datastore.Audit**
Datastore.Audit allows one to know about a datastore, including reading the
configuration entry and listing its contents.
**Datastore.Allocate**
Datastore.Allocate allows one to create or deleting datastores.
**Datastore.Modify**
Datastore.Modify allows one to modify a datastore and its contents, and to
create or delete namespaces inside a datastore.
**Datastore.Read**
Datastore.Read allows one to read arbitrary backup contents, independent of
the backup group owner.
**Datastore.Verify**
Allows verifying the backup snapshots in a datastore.
**Datastore.Backup**
Datastore.Backup allows one create new backup snapshot and gives one also the
privileges of Datastore.Read and Datastore.Verify, but only if the backup
group is owned by the user or one of its tokens.
**Datastore.Prune**
Datastore.Prune allows one to delete snapshots, but additionally requires
backup ownership
**Permissions.Modify**
Permissions.Modify allows one to modifying ACLs
.. note:: One can always configure privileges for their own API tokens, as
they will clamped by the users privileges anyway.
**Remote.Audit**
Remote.Audit allows one to read the remote and the sync configuration entries
**Remote.Modify**
Remote.Modify allows one to modify the remote configuration
**Remote.Read**
Remote.Read allows one to read data from a configured `Remote`
**Sys.Console**
Sys.Console allows one to access to the system's console, note that for all
but `root@pam` a valid system login is still required.
**Tape.Audit**
Tape.Audit allows one to read the configuration and status of tape drives,
changers and backups
**Tape.Modify**
Tape.Modify allows one to modify the configuration of tape drives, changers
and backups
**Tape.Write**
Tape.Write allows one to write to a tape media
**Tape.Read**
Tape.Read allows one to read tape backup configuration and contents from a
tape media
**Realm.Allocate**
Realm.Allocate allows one to view, create, modify and delete authentication
realms for users
Access Roles
~~~~~~~~~~~~
An access role combines one or more privileges into something that can be
assigned to an user or API token on an object path.
Currently there are only built-in roles, that means, you cannot create your
own, custom role.
The following roles exist:
**NoAccess** **NoAccess**
Disable Access - nothing is allowed. Disable Access - nothing is allowed.
**Admin** **Admin**
Can do anything. Can do anything, on the object path assigned.
**Audit** **Audit**
Can view things, but is not allowed to change settings. Can view the status and configuration of things, but is not allowed to change
settings.
**DatastoreAdmin** **DatastoreAdmin**
Can do anything on datastores. Can do anything on *existing* datastores.
**DatastoreAudit** **DatastoreAudit**
Can view datastore settings and list content. But Can view datastore metrics, settings and list content. But is not allowed to
is not allowed to read the actual data. read the actual data.
**DatastoreReader** **DatastoreReader**
Can Inspect datastore content and do restores. Can inspect a datastore's or namespaces content and do restores.
**DatastoreBackup** **DatastoreBackup**
Can backup and restore owned backups. Can backup and restore owned backups.
**DatastorePowerUser** **DatastorePowerUser**
Can backup, restore, and prune owned backups. Can backup, restore, and prune *owned* backups.
**RemoteAdmin** **RemoteAdmin**
Can do anything on remotes. Can do anything on remotes.
@ -195,19 +294,62 @@ following roles exist:
**RemoteSyncOperator** **RemoteSyncOperator**
Is allowed to read data from a remote. Is allowed to read data from a remote.
**TapeAudit** **TapeAdmin**
Can view tape related configuration and status
**TapeAdministrat**
Can do anything related to tape backup Can do anything related to tape backup
**TapeAudit**
Can view tape related metrics, configuration and status
**TapeOperator** **TapeOperator**
Can do tape backup and restore (but no configuration changes) Can do tape backup and restore, but cannot change any configuration
**TapeReader** **TapeReader**
Can read and inspect tape configuration and media content Can read and inspect tape configuration and media content
.. image:: images/screenshots/pbs-gui-user-management-add-user.png Objects and Paths
~~~~~~~~~~~~~~~~~
Access permissions are assigned to objects, such as a datastore, a namespace or
some system resources.
We use file system like paths to address these objects. These paths form a
natural tree, and permissions of higher levels (shorter paths) can optionally
be propagated down within this hierarchy.
Paths can be templated, that means they can refer to the actual id of an
configuration entry. When an API call requires permissions on a templated
path, the path may contain references to parameters of the API call. These
references are specified in curly braces.
Some examples are:
* `/datastore`: Access to *all* datastores on a Proxmox Backup server
* `/datastore/{store}`: Access to a specific datastore on a Proxmox Backup
server
* `/datastore/{store}/{ns}`: Access to a specific namespace on a specific
datastore
* `/remote`: Access to all remote entries
* `/system/network`: Access to configuring the host network
* `/tape/`: Access to tape devices, pools and jobs
* `/access/users`: User administration
* `/access/openid/{id}`: Administrative access to a specific OpenID Connect realm
Inheritance
^^^^^^^^^^^
As mentioned earlier, object paths form a file system like tree, and
permissions can be inherited by objects down that tree through the propagate
flag, which is set by default. We use the following inheritance rules:
* Permissions for API tokens are always clamped to the one of the user.
* Permissions on deeper, more specific levels replace those inherited from an
upper level.
Configuration & Management
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. image:: images/screenshots/pbs-gui-permissions-add.png
:align: right :align: right
:alt: Add permissions for user :alt: Add permissions for user

View File

@ -3,7 +3,6 @@ use anyhow::Error;
// chacha20-poly1305 // chacha20-poly1305
fn rate_test(name: &str, bench: &dyn Fn() -> usize) { fn rate_test(name: &str, bench: &dyn Fn() -> usize) {
print!("{:<20} ", name); print!("{:<20} ", name);
let start = std::time::SystemTime::now(); let start = std::time::SystemTime::now();
@ -14,20 +13,19 @@ fn rate_test(name: &str, bench: &dyn Fn() -> usize) {
loop { loop {
bytes += bench(); bytes += bench();
let elapsed = start.elapsed().unwrap(); let elapsed = start.elapsed().unwrap();
if elapsed > duration { break; } if elapsed > duration {
break;
}
} }
let elapsed = start.elapsed().unwrap(); let elapsed = start.elapsed().unwrap();
let elapsed = (elapsed.as_secs() as f64) + let elapsed = (elapsed.as_secs() as f64) + (elapsed.subsec_millis() as f64) / 1000.0;
(elapsed.subsec_millis() as f64)/1000.0;
println!("{:>8.1} MB/s", (bytes as f64)/(elapsed*1024.0*1024.0)); println!("{:>8.1} MB/s", (bytes as f64) / (elapsed * 1024.0 * 1024.0));
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let input = proxmox_sys::linux::random_data(1024 * 1024)?;
let input = proxmox::sys::linux::random_data(1024*1024)?;
rate_test("crc32", &|| { rate_test("crc32", &|| {
let mut crchasher = crc32fast::Hasher::new(); let mut crchasher = crc32fast::Hasher::new();
@ -46,35 +44,23 @@ fn main() -> Result<(), Error> {
input.len() input.len()
}); });
let key = proxmox::sys::linux::random_data(32)?; let key = proxmox_sys::linux::random_data(32)?;
let iv = proxmox::sys::linux::random_data(16)?; let iv = proxmox_sys::linux::random_data(16)?;
let cipher = openssl::symm::Cipher::aes_256_gcm(); let cipher = openssl::symm::Cipher::aes_256_gcm();
rate_test("aes-256-gcm", &|| { rate_test("aes-256-gcm", &|| {
let mut tag = [0u8;16]; let mut tag = [0u8; 16];
openssl::symm::encrypt_aead( openssl::symm::encrypt_aead(cipher, &key, Some(&iv), b"", &input, &mut tag).unwrap();
cipher,
&key,
Some(&iv),
b"",
&input,
&mut tag).unwrap();
input.len() input.len()
}); });
let cipher = openssl::symm::Cipher::chacha20_poly1305(); let cipher = openssl::symm::Cipher::chacha20_poly1305();
rate_test("chacha20-poly1305", &|| { rate_test("chacha20-poly1305", &|| {
let mut tag = [0u8;16]; let mut tag = [0u8; 16];
openssl::symm::encrypt_aead( openssl::symm::encrypt_aead(cipher, &key, Some(&iv[..12]), b"", &input, &mut tag).unwrap();
cipher,
&key,
Some(&iv[..12]),
b"",
&input,
&mut tag).unwrap();
input.len() input.len()
}); });

View File

@ -1,7 +1,7 @@
use anyhow::{Error}; use anyhow::Error;
use proxmox_schema::*;
use proxmox_router::cli::*; use proxmox_router::cli::*;
use proxmox_schema::*;
#[api( #[api(
input: { input: {
@ -16,9 +16,7 @@ use proxmox_router::cli::*;
/// Echo command. Print the passed text. /// Echo command. Print the passed text.
/// ///
/// Returns: nothing /// Returns: nothing
fn echo_command( fn echo_command(text: String) -> Result<(), Error> {
text: String,
) -> Result<(), Error> {
println!("{}", text); println!("{}", text);
Ok(()) Ok(())
} }
@ -37,9 +35,7 @@ fn echo_command(
/// Hello command. /// Hello command.
/// ///
/// Returns: nothing /// Returns: nothing
fn hello_command( fn hello_command(verbose: Option<bool>) -> Result<(), Error> {
verbose: Option<bool>,
) -> Result<(), Error> {
if verbose.unwrap_or(false) { if verbose.unwrap_or(false) {
println!("Hello, how are you!"); println!("Hello, how are you!");
} else { } else {
@ -54,7 +50,6 @@ fn hello_command(
/// ///
/// Returns: nothing /// Returns: nothing
fn quit_command() -> Result<(), Error> { fn quit_command() -> Result<(), Error> {
println!("Goodbye."); println!("Goodbye.");
std::process::exit(0); std::process::exit(0);
@ -64,8 +59,9 @@ fn cli_definition() -> CommandLineInterface {
let cmd_def = CliCommandMap::new() let cmd_def = CliCommandMap::new()
.insert("quit", CliCommand::new(&API_METHOD_QUIT_COMMAND)) .insert("quit", CliCommand::new(&API_METHOD_QUIT_COMMAND))
.insert("hello", CliCommand::new(&API_METHOD_HELLO_COMMAND)) .insert("hello", CliCommand::new(&API_METHOD_HELLO_COMMAND))
.insert("echo", CliCommand::new(&API_METHOD_ECHO_COMMAND) .insert(
.arg_param(&["text"]) "echo",
CliCommand::new(&API_METHOD_ECHO_COMMAND).arg_param(&["text"]),
) )
.insert_help(); .insert_help();
@ -73,7 +69,6 @@ fn cli_definition() -> CommandLineInterface {
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let helper = CliHelper::new(cli_definition()); let helper = CliHelper::new(cli_definition());
let mut rl = rustyline::Editor::<CliHelper>::new(); let mut rl = rustyline::Editor::<CliHelper>::new();

View File

@ -2,15 +2,14 @@ use std::io::Write;
use anyhow::Error; use anyhow::Error;
use pbs_api_types::Authid; use pbs_api_types::{Authid, BackupNamespace, BackupType};
use pbs_client::{HttpClient, HttpClientOptions, BackupReader}; use pbs_client::{BackupReader, HttpClient, HttpClientOptions};
pub struct DummyWriter { pub struct DummyWriter {
bytes: usize, bytes: usize,
} }
impl Write for DummyWriter { impl Write for DummyWriter {
fn write(&mut self, data: &[u8]) -> Result<usize, std::io::Error> { fn write(&mut self, data: &[u8]) -> Result<usize, std::io::Error> {
self.bytes += data.len(); self.bytes += data.len();
Ok(data.len()) Ok(data.len())
@ -21,9 +20,7 @@ impl Write for DummyWriter {
} }
} }
async fn run() -> Result<(), Error> { async fn run() -> Result<(), Error> {
let host = "localhost"; let host = "localhost";
let auth_id = Authid::root_auth_id(); let auth_id = Authid::root_auth_id();
@ -36,8 +33,15 @@ async fn run() -> Result<(), Error> {
let backup_time = proxmox_time::parse_rfc3339("2019-06-28T10:49:48Z")?; let backup_time = proxmox_time::parse_rfc3339("2019-06-28T10:49:48Z")?;
let client = BackupReader::start(client, None, "store2", "host", "elsa", backup_time, true) let client = BackupReader::start(
.await?; client,
None,
"store2",
&BackupNamespace::root(),
&(BackupType::Host, "elsa".to_string(), backup_time).into(),
true,
)
.await?;
let start = std::time::SystemTime::now(); let start = std::time::SystemTime::now();
@ -50,10 +54,13 @@ async fn run() -> Result<(), Error> {
} }
let elapsed = start.elapsed().unwrap(); let elapsed = start.elapsed().unwrap();
let elapsed = (elapsed.as_secs() as f64) + let elapsed = (elapsed.as_secs() as f64) + (elapsed.subsec_millis() as f64) / 1000.0;
(elapsed.subsec_millis() as f64)/1000.0;
println!("Downloaded {} bytes, {} MB/s", bytes, (bytes as f64)/(elapsed*1024.0*1024.0)); println!(
"Downloaded {} bytes, {} MB/s",
bytes,
(bytes as f64) / (elapsed * 1024.0 * 1024.0)
);
Ok(()) Ok(())
} }

View File

@ -1,6 +1,6 @@
use std::thread;
use std::path::PathBuf;
use std::io::Write; use std::io::Write;
use std::path::PathBuf;
use std::thread;
use anyhow::{bail, Error}; use anyhow::{bail, Error};
@ -19,15 +19,15 @@ use anyhow::{bail, Error};
// Error: detected shrunk file "./dyntest1/testfile0.dat" (22020096 < 12679380992) // Error: detected shrunk file "./dyntest1/testfile0.dat" (22020096 < 12679380992)
fn create_large_file(path: PathBuf) { fn create_large_file(path: PathBuf) {
println!("TEST {:?}", path); println!("TEST {:?}", path);
let mut file = std::fs::OpenOptions::new() let mut file = std::fs::OpenOptions::new()
.write(true) .write(true)
.create_new(true) .create_new(true)
.open(&path).unwrap(); .open(&path)
.unwrap();
let buffer = vec![0u8; 64*1024]; let buffer = vec![0u8; 64 * 1024];
loop { loop {
for _ in 0..64 { for _ in 0..64 {
@ -40,7 +40,6 @@ fn create_large_file(path: PathBuf) {
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let base = PathBuf::from("dyntest1"); let base = PathBuf::from("dyntest1");
let _ = std::fs::create_dir(&base); let _ = std::fs::create_dir(&base);

View File

@ -2,7 +2,7 @@ extern crate proxmox_backup;
// also see https://www.johndcook.com/blog/standard_deviation/ // also see https://www.johndcook.com/blog/standard_deviation/
use anyhow::{Error}; use anyhow::Error;
use std::io::{Read, Write}; use std::io::{Read, Write};
use pbs_datastore::Chunker; use pbs_datastore::Chunker;
@ -21,7 +21,6 @@ struct ChunkWriter {
} }
impl ChunkWriter { impl ChunkWriter {
fn new(chunk_size: usize) -> Self { fn new(chunk_size: usize) -> Self {
ChunkWriter { ChunkWriter {
chunker: Chunker::new(chunk_size), chunker: Chunker::new(chunk_size),
@ -37,7 +36,6 @@ impl ChunkWriter {
} }
fn record_stat(&mut self, chunk_size: f64) { fn record_stat(&mut self, chunk_size: f64) {
self.chunk_count += 1; self.chunk_count += 1;
if self.chunk_count == 1 { if self.chunk_count == 1 {
@ -45,28 +43,30 @@ impl ChunkWriter {
self.m_new = chunk_size; self.m_new = chunk_size;
self.s_old = 0.0; self.s_old = 0.0;
} else { } else {
self.m_new = self.m_old + (chunk_size - self.m_old)/(self.chunk_count as f64); self.m_new = self.m_old + (chunk_size - self.m_old) / (self.chunk_count as f64);
self.s_new = self.s_old + self.s_new = self.s_old + (chunk_size - self.m_old) * (chunk_size - self.m_new);
(chunk_size - self.m_old)*(chunk_size - self.m_new);
// set up for next iteration // set up for next iteration
self.m_old = self.m_new; self.m_old = self.m_new;
self.s_old = self.s_new; self.s_old = self.s_new;
} }
let variance = if self.chunk_count > 1 { let variance = if self.chunk_count > 1 {
self.s_new/((self.chunk_count -1)as f64) self.s_new / ((self.chunk_count - 1) as f64)
} else { 0.0 }; } else {
0.0
};
let std_deviation = variance.sqrt(); let std_deviation = variance.sqrt();
let deviation_per = (std_deviation*100.0)/self.m_new; let deviation_per = (std_deviation * 100.0) / self.m_new;
println!("COUNT {:10} SIZE {:10} MEAN {:10} DEVIATION {:3}%", self.chunk_count, chunk_size, self.m_new as usize, deviation_per as usize); println!(
"COUNT {:10} SIZE {:10} MEAN {:10} DEVIATION {:3}%",
self.chunk_count, chunk_size, self.m_new as usize, deviation_per as usize
);
} }
} }
impl Write for ChunkWriter { impl Write for ChunkWriter {
fn write(&mut self, data: &[u8]) -> std::result::Result<usize, std::io::Error> { fn write(&mut self, data: &[u8]) -> std::result::Result<usize, std::io::Error> {
let chunker = &mut self.chunker; let chunker = &mut self.chunker;
let pos = chunker.scan(data); let pos = chunker.scan(data);
@ -80,7 +80,6 @@ impl Write for ChunkWriter {
self.last_chunk = self.chunk_offset; self.last_chunk = self.chunk_offset;
Ok(pos) Ok(pos)
} else { } else {
self.chunk_offset += data.len(); self.chunk_offset += data.len();
Ok(data.len()) Ok(data.len())
@ -93,23 +92,23 @@ impl Write for ChunkWriter {
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let mut file = std::fs::File::open("/dev/urandom")?; let mut file = std::fs::File::open("/dev/urandom")?;
let mut bytes = 0; let mut bytes = 0;
let mut buffer = [0u8; 64*1024]; let mut buffer = [0u8; 64 * 1024];
let mut writer = ChunkWriter::new(4096*1024); let mut writer = ChunkWriter::new(4096 * 1024);
loop { loop {
file.read_exact(&mut buffer)?; file.read_exact(&mut buffer)?;
bytes += buffer.len(); bytes += buffer.len();
writer.write_all(&buffer)?; writer.write_all(&buffer)?;
if bytes > 1024*1024*1024 { break; } if bytes > 1024 * 1024 * 1024 {
break;
}
} }
Ok(()) Ok(())

View File

@ -3,17 +3,16 @@ extern crate proxmox_backup;
use pbs_datastore::Chunker; use pbs_datastore::Chunker;
fn main() { fn main() {
let mut buffer = Vec::new(); let mut buffer = Vec::new();
for i in 0..20*1024*1024 { for i in 0..20 * 1024 * 1024 {
for j in 0..4 { for j in 0..4 {
let byte = ((i >> (j<<3))&0xff) as u8; let byte = ((i >> (j << 3)) & 0xff) as u8;
//println!("BYTE {}", byte); //println!("BYTE {}", byte);
buffer.push(byte); buffer.push(byte);
} }
} }
let mut chunker = Chunker::new(64*1024); let mut chunker = Chunker::new(64 * 1024);
let count = 5; let count = 5;
@ -39,11 +38,14 @@ fn main() {
} }
let elapsed = start.elapsed().unwrap(); let elapsed = start.elapsed().unwrap();
let elapsed = (elapsed.as_secs() as f64) + let elapsed = (elapsed.as_secs() as f64) + (elapsed.subsec_millis() as f64) / 1000.0;
(elapsed.subsec_millis() as f64)/1000.0;
let mbytecount = ((count*buffer.len()) as f64) / (1024.0*1024.0); let mbytecount = ((count * buffer.len()) as f64) / (1024.0 * 1024.0);
let avg_chunk_size = mbytecount/(chunk_count as f64); let avg_chunk_size = mbytecount / (chunk_count as f64);
let mbytes_per_sec = mbytecount/elapsed; let mbytes_per_sec = mbytecount / elapsed;
println!("SPEED = {} MB/s, avg chunk size = {} KB", mbytes_per_sec, avg_chunk_size*1024.0); println!(
"SPEED = {} MB/s, avg chunk size = {} KB",
mbytes_per_sec,
avg_chunk_size * 1024.0
);
} }

View File

@ -1,4 +1,4 @@
use anyhow::{Error}; use anyhow::Error;
use futures::*; use futures::*;
extern crate proxmox_backup; extern crate proxmox_backup;
@ -19,7 +19,6 @@ fn main() {
} }
async fn run() -> Result<(), Error> { async fn run() -> Result<(), Error> {
let file = tokio::fs::File::open("random-test.dat").await?; let file = tokio::fs::File::open("random-test.dat").await?;
let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
@ -34,7 +33,7 @@ async fn run() -> Result<(), Error> {
let mut repeat = 0; let mut repeat = 0;
let mut stream_len = 0; let mut stream_len = 0;
while let Some(chunk) = chunk_stream.try_next().await? { while let Some(chunk) = chunk_stream.try_next().await? {
if chunk.len() > 16*1024*1024 { if chunk.len() > 16 * 1024 * 1024 {
panic!("Chunk too large {}", chunk.len()); panic!("Chunk too large {}", chunk.len());
} }
@ -44,10 +43,19 @@ async fn run() -> Result<(), Error> {
println!("Got chunk {}", chunk.len()); println!("Got chunk {}", chunk.len());
} }
let speed = ((stream_len*1_000_000)/(1024*1024))/(start_time.elapsed().as_micros() as usize); let speed =
println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed); ((stream_len * 1_000_000) / (1024 * 1024)) / (start_time.elapsed().as_micros() as usize);
println!("Average chunk size was {} bytes.", stream_len/repeat); println!(
println!("time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); "Uploaded {} chunks in {} seconds ({} MB/s).",
repeat,
start_time.elapsed().as_secs(),
speed
);
println!("Average chunk size was {} bytes.", stream_len / repeat);
println!(
"time per request: {} microseconds.",
(start_time.elapsed().as_micros()) / (repeat as u128)
);
Ok(()) Ok(())
} }

View File

@ -1,10 +1,9 @@
use anyhow::{Error}; use anyhow::Error;
use pbs_client::{HttpClient, HttpClientOptions, BackupWriter}; use pbs_api_types::{Authid, BackupNamespace, BackupType};
use pbs_api_types::Authid; use pbs_client::{BackupWriter, HttpClient, HttpClientOptions};
async fn upload_speed() -> Result<f64, Error> { async fn upload_speed() -> Result<f64, Error> {
let host = "localhost"; let host = "localhost";
let datastore = "store2"; let datastore = "store2";
@ -18,7 +17,16 @@ async fn upload_speed() -> Result<f64, Error> {
let backup_time = proxmox_time::epoch_i64(); let backup_time = proxmox_time::epoch_i64();
let client = BackupWriter::start(client, None, datastore, "host", "speedtest", backup_time, false, true).await?; let client = BackupWriter::start(
client,
None,
datastore,
&BackupNamespace::root(),
&(BackupType::Host, "speedtest".to_string(), backup_time).into(),
false,
true,
)
.await?;
println!("start upload speed test"); println!("start upload speed test");
let res = client.upload_speedtest(true).await?; let res = client.upload_speedtest(true).await?;
@ -26,7 +34,7 @@ async fn upload_speed() -> Result<f64, Error> {
Ok(res) Ok(res)
} }
fn main() { fn main() {
match proxmox_async::runtime::main(upload_speed()) { match proxmox_async::runtime::main(upload_speed()) {
Ok(mbs) => { Ok(mbs) => {
println!("average upload speed: {} MB/s", mbs); println!("average upload speed: {} MB/s", mbs);

View File

@ -9,14 +9,13 @@ description = "general API type helpers for PBS"
anyhow = "1.0" anyhow = "1.0"
hex = "0.4.3" hex = "0.4.3"
lazy_static = "1.4" lazy_static = "1.4"
libc = "0.2" percent-encoding = "2.1"
nix = "0.19.1" regex = "1.5.5"
openssl = "0.10"
regex = "1.2"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_plain = "1"
proxmox = "0.15.3"
proxmox-lang = "1.0.0" proxmox-lang = "1.0.0"
proxmox-schema = { version = "1.0.1", features = [ "api-macro" ] } proxmox-schema = { version = "1.2.1", features = [ "api-macro" ] }
proxmox-time = "1.1" proxmox-serde = "0.1"
proxmox-time = "1.1.1"
proxmox-uuid = { version = "1.0.0", features = [ "serde" ] } proxmox-uuid = { version = "1.0.0", features = [ "serde" ] }

View File

@ -73,6 +73,17 @@ constnamedbitmap! {
} }
} }
pub fn privs_to_priv_names(privs: u64) -> Vec<&'static str> {
PRIVILEGES
.iter()
.fold(Vec::new(), |mut priv_names, (name, value)| {
if value & privs != 0 {
priv_names.push(name);
}
priv_names
})
}
/// Admin always has all privileges. It can do everything except a few actions /// Admin always has all privileges. It can do everything except a few actions
/// which are limited to the 'root@pam` superuser /// which are limited to the 'root@pam` superuser
pub const ROLE_ADMIN: u64 = u64::MAX; pub const ROLE_ADMIN: u64 = u64::MAX;

View File

@ -0,0 +1,78 @@
//! Predefined Regular Expressions
//!
//! This is a collection of useful regular expressions
use lazy_static::lazy_static;
use regex::Regex;
#[rustfmt::skip]
#[macro_export]
macro_rules! IPV4OCTET { () => (r"(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])") }
#[rustfmt::skip]
#[macro_export]
macro_rules! IPV6H16 { () => (r"(?:[0-9a-fA-F]{1,4})") }
#[rustfmt::skip]
#[macro_export]
macro_rules! IPV6LS32 { () => (concat!(r"(?:(?:", IPV4RE!(), "|", IPV6H16!(), ":", IPV6H16!(), "))" )) }
/// Returns the regular expression string to match IPv4 addresses
#[rustfmt::skip]
#[macro_export]
macro_rules! IPV4RE { () => (concat!(r"(?:(?:", IPV4OCTET!(), r"\.){3}", IPV4OCTET!(), ")")) }
/// Returns the regular expression string to match IPv6 addresses
#[rustfmt::skip]
#[macro_export]
macro_rules! IPV6RE { () => (concat!(r"(?:",
r"(?:(?:", r"(?:", IPV6H16!(), r":){6})", IPV6LS32!(), r")|",
r"(?:(?:", r"::(?:", IPV6H16!(), r":){5})", IPV6LS32!(), r")|",
r"(?:(?:(?:", IPV6H16!(), r")?::(?:", IPV6H16!(), r":){4})", IPV6LS32!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,1}", IPV6H16!(), r")?::(?:", IPV6H16!(), r":){3})", IPV6LS32!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,2}", IPV6H16!(), r")?::(?:", IPV6H16!(), r":){2})", IPV6LS32!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,3}", IPV6H16!(), r")?::(?:", IPV6H16!(), r":){1})", IPV6LS32!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,4}", IPV6H16!(), r")?::", ")", IPV6LS32!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,5}", IPV6H16!(), r")?::", ")", IPV6H16!(), r")|",
r"(?:(?:(?:(?:", IPV6H16!(), r":){0,6}", IPV6H16!(), r")?::", ")))"))
}
/// Returns the regular expression string to match IP addresses (v4 or v6)
#[rustfmt::skip]
#[macro_export]
macro_rules! IPRE { () => (concat!(r"(?:", IPV4RE!(), "|", IPV6RE!(), ")")) }
/// Regular expression string to match IP addresses where IPv6 addresses require brackets around
/// them, while for IPv4 they are forbidden.
#[rustfmt::skip]
#[macro_export]
macro_rules! IPRE_BRACKET { () => (
concat!(r"(?:",
IPV4RE!(),
r"|\[(?:",
IPV6RE!(),
r")\]",
r")"))
}
lazy_static! {
pub static ref IP_REGEX: Regex = Regex::new(concat!(r"^", IPRE!(), r"$")).unwrap();
pub static ref IP_BRACKET_REGEX: Regex =
Regex::new(concat!(r"^", IPRE_BRACKET!(), r"$")).unwrap();
pub static ref SHA256_HEX_REGEX: Regex = Regex::new(r"^[a-f0-9]{64}$").unwrap();
pub static ref SYSTEMD_DATETIME_REGEX: Regex =
Regex::new(r"^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$").unwrap();
}
#[test]
fn test_regexes() {
assert!(IP_REGEX.is_match("127.0.0.1"));
assert!(IP_REGEX.is_match("::1"));
assert!(IP_REGEX.is_match("2014:b3a::27"));
assert!(IP_REGEX.is_match("2014:b3a::192.168.0.1"));
assert!(IP_REGEX.is_match("2014:b3a:0102:adf1:1234:4321:4afA:BCDF"));
assert!(IP_BRACKET_REGEX.is_match("127.0.0.1"));
assert!(IP_BRACKET_REGEX.is_match("[::1]"));
assert!(IP_BRACKET_REGEX.is_match("[2014:b3a::27]"));
assert!(IP_BRACKET_REGEX.is_match("[2014:b3a::192.168.0.1]"));
assert!(IP_BRACKET_REGEX.is_match("[2014:b3a:0102:adf1:1234:4321:4afA:BCDF]"));
}

View File

@ -51,7 +51,8 @@ impl std::str::FromStr for Fingerprint {
fn from_str(s: &str) -> Result<Self, Error> { fn from_str(s: &str) -> Result<Self, Error> {
let mut tmp = s.to_string(); let mut tmp = s.to_string();
tmp.retain(|c| c != ':'); tmp.retain(|c| c != ':');
let bytes = proxmox::tools::hex_to_digest(&tmp)?; let mut bytes = [0u8; 32];
hex::decode_to_slice(&tmp, &mut bytes)?;
Ok(Fingerprint::new(bytes)) Ok(Fingerprint::new(bytes))
} }
} }
@ -61,18 +62,16 @@ fn as_fingerprint(bytes: &[u8]) -> String {
.as_bytes() .as_bytes()
.chunks(2) .chunks(2)
.map(|v| unsafe { std::str::from_utf8_unchecked(v) }) // it's a hex string .map(|v| unsafe { std::str::from_utf8_unchecked(v) }) // it's a hex string
.collect::<Vec<&str>>().join(":") .collect::<Vec<&str>>()
.join(":")
} }
pub mod bytes_as_fingerprint { pub mod bytes_as_fingerprint {
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use serde::{Deserialize, Serializer, Deserializer}; use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>( pub fn serialize<S>(bytes: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error>
bytes: &[u8; 32],
serializer: S,
) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
{ {
@ -80,9 +79,7 @@ pub mod bytes_as_fingerprint {
serializer.serialize_str(&s) serializer.serialize_str(&s)
} }
pub fn deserialize<'de, D>( pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
deserializer: D,
) -> Result<[u8; 32], D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {

File diff suppressed because it is too large Load Diff

View File

@ -53,20 +53,18 @@ impl SizeUnit {
11..=20 => SizeUnit::Kibi, 11..=20 => SizeUnit::Kibi,
_ => SizeUnit::Byte, _ => SizeUnit::Byte,
} }
} else if size >= 1_000_000_000_000_000.0 {
SizeUnit::PByte
} else if size >= 1_000_000_000_000.0 {
SizeUnit::TByte
} else if size >= 1_000_000_000.0 {
SizeUnit::GByte
} else if size >= 1_000_000.0 {
SizeUnit::MByte
} else if size >= 1_000.0 {
SizeUnit::KByte
} else { } else {
if size >= 1_000_000_000_000_000.0 { SizeUnit::Byte
SizeUnit::PByte
} else if size >= 1_000_000_000_000.0 {
SizeUnit::TByte
} else if size >= 1_000_000_000.0 {
SizeUnit::GByte
} else if size >= 1_000_000.0 {
SizeUnit::MByte
} else if size >= 1_000.0 {
SizeUnit::KByte
} else {
SizeUnit::Byte
}
} }
} }
} }
@ -103,7 +101,8 @@ fn strip_unit(v: &str) -> (&str, SizeUnit) {
}; };
let mut unit = SizeUnit::Byte; let mut unit = SizeUnit::Byte;
(v.strip_suffix(|c: char| match c { #[rustfmt::skip]
let value = v.strip_suffix(|c: char| match c {
'k' | 'K' if !binary => { unit = SizeUnit::KByte; true } 'k' | 'K' if !binary => { unit = SizeUnit::KByte; true }
'm' | 'M' if !binary => { unit = SizeUnit::MByte; true } 'm' | 'M' if !binary => { unit = SizeUnit::MByte; true }
'g' | 'G' if !binary => { unit = SizeUnit::GByte; true } 'g' | 'G' if !binary => { unit = SizeUnit::GByte; true }
@ -116,7 +115,9 @@ fn strip_unit(v: &str) -> (&str, SizeUnit) {
't' | 'T' if binary => { unit = SizeUnit::Tebi; true } 't' | 'T' if binary => { unit = SizeUnit::Tebi; true }
'p' | 'P' if binary => { unit = SizeUnit::Pebi; true } 'p' | 'P' if binary => { unit = SizeUnit::Pebi; true }
_ => false _ => false
}).unwrap_or(v).trim_end(), unit) }).unwrap_or(v).trim_end();
(value, unit)
} }
/// Byte size which can be displayed in a human friendly way /// Byte size which can be displayed in a human friendly way
@ -156,13 +157,19 @@ impl HumanByte {
/// Create a new instance with optimal binary unit computed /// Create a new instance with optimal binary unit computed
pub fn new_binary(size: f64) -> Self { pub fn new_binary(size: f64) -> Self {
let unit = SizeUnit::auto_scale(size, true); let unit = SizeUnit::auto_scale(size, true);
HumanByte { size: size / unit.factor(), unit } HumanByte {
size: size / unit.factor(),
unit,
}
} }
/// Create a new instance with optimal decimal unit computed /// Create a new instance with optimal decimal unit computed
pub fn new_decimal(size: f64) -> Self { pub fn new_decimal(size: f64) -> Self {
let unit = SizeUnit::auto_scale(size, false); let unit = SizeUnit::auto_scale(size, false);
HumanByte { size: size / unit.factor(), unit } HumanByte {
size: size / unit.factor(),
unit,
}
} }
/// Returns the size as u64 number of bytes /// Returns the size as u64 number of bytes
@ -216,8 +223,8 @@ impl std::str::FromStr for HumanByte {
} }
} }
proxmox::forward_deserialize_to_from_str!(HumanByte); proxmox_serde::forward_deserialize_to_from_str!(HumanByte);
proxmox::forward_serialize_to_display!(HumanByte); proxmox_serde::forward_serialize_to_display!(HumanByte);
#[test] #[test]
fn test_human_byte_parser() -> Result<(), Error> { fn test_human_byte_parser() -> Result<(), Error> {
@ -230,7 +237,12 @@ fn test_human_byte_parser() -> Result<(), Error> {
bail!("got unexpected size for '{}' ({} != {})", v, h.size, size); bail!("got unexpected size for '{}' ({} != {})", v, h.size, size);
} }
if h.unit != unit { if h.unit != unit {
bail!("got unexpected unit for '{}' ({:?} != {:?})", v, h.unit, unit); bail!(
"got unexpected unit for '{}' ({:?} != {:?})",
v,
h.unit,
unit
);
} }
let new = h.to_string(); let new = h.to_string();
@ -267,7 +279,12 @@ fn test_human_byte_parser() -> Result<(), Error> {
assert_eq!(&format!("{:.7}", h), "1.2345678 B"); assert_eq!(&format!("{:.7}", h), "1.2345678 B");
assert_eq!(&format!("{:.8}", h), "1.2345678 B"); assert_eq!(&format!("{:.8}", h), "1.2345678 B");
assert!(test("987654321", 987654321.0, SizeUnit::Byte, "987654321 B")); assert!(test(
"987654321",
987654321.0,
SizeUnit::Byte,
"987654321 B"
));
assert!(test("1300b", 1300.0, SizeUnit::Byte, "1300 B")); assert!(test("1300b", 1300.0, SizeUnit::Byte, "1300 B"));
assert!(test("1300B", 1300.0, SizeUnit::Byte, "1300 B")); assert!(test("1300B", 1300.0, SizeUnit::Byte, "1300 B"));

View File

@ -7,18 +7,18 @@ use serde::{Deserialize, Serialize};
use proxmox_schema::*; use proxmox_schema::*;
use crate::{ use crate::{
Userid, Authid, RateLimitConfig, Authid, BackupNamespace, BackupType, RateLimitConfig, Userid, BACKUP_GROUP_SCHEMA,
REMOTE_ID_SCHEMA, DRIVE_NAME_SCHEMA, MEDIA_POOL_NAME_SCHEMA, BACKUP_NAMESPACE_SCHEMA, DATASTORE_SCHEMA, DRIVE_NAME_SCHEMA, MEDIA_POOL_NAME_SCHEMA,
SINGLE_LINE_COMMENT_SCHEMA, PROXMOX_SAFE_ID_FORMAT, DATASTORE_SCHEMA, NS_MAX_DEPTH_REDUCED_SCHEMA, PROXMOX_SAFE_ID_FORMAT, REMOTE_ID_SCHEMA,
BACKUP_GROUP_SCHEMA, BACKUP_TYPE_SCHEMA, SINGLE_LINE_COMMENT_SCHEMA,
}; };
const_regex!{ const_regex! {
/// Regex for verification jobs 'DATASTORE:ACTUAL_JOB_ID' /// Regex for verification jobs 'DATASTORE:ACTUAL_JOB_ID'
pub VERIFICATION_JOB_WORKER_ID_REGEX = concat!(r"^(", PROXMOX_SAFE_ID_REGEX_STR!(), r"):"); 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' /// Regex for sync jobs 'REMOTE:REMOTE_DATASTORE:LOCAL_DATASTORE:(?:LOCAL_NS_ANCHOR:)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 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")(?::(", BACKUP_NS_RE!(), r"))?:");
} }
pub const JOB_ID_SCHEMA: Schema = StringSchema::new("Job ID.") pub const JOB_ID_SCHEMA: Schema = StringSchema::new("Job ID.")
@ -27,34 +27,41 @@ pub const JOB_ID_SCHEMA: Schema = StringSchema::new("Job ID.")
.max_length(32) .max_length(32)
.schema(); .schema();
pub const SYNC_SCHEDULE_SCHEMA: Schema = StringSchema::new( pub const SYNC_SCHEDULE_SCHEMA: Schema = StringSchema::new("Run sync job at specified schedule.")
"Run sync job at specified schedule.") .format(&ApiStringFormat::VerifyFn(
.format(&ApiStringFormat::VerifyFn(proxmox_time::verify_calendar_event)) proxmox_time::verify_calendar_event,
))
.type_text("<calendar-event>") .type_text("<calendar-event>")
.schema(); .schema();
pub const GC_SCHEDULE_SCHEMA: Schema = StringSchema::new( pub const GC_SCHEDULE_SCHEMA: Schema =
"Run garbage collection job at specified schedule.") StringSchema::new("Run garbage collection job at specified schedule.")
.format(&ApiStringFormat::VerifyFn(proxmox_time::verify_calendar_event)) .format(&ApiStringFormat::VerifyFn(
proxmox_time::verify_calendar_event,
))
.type_text("<calendar-event>")
.schema();
pub const PRUNE_SCHEDULE_SCHEMA: Schema = StringSchema::new("Run prune job at specified schedule.")
.format(&ApiStringFormat::VerifyFn(
proxmox_time::verify_calendar_event,
))
.type_text("<calendar-event>") .type_text("<calendar-event>")
.schema(); .schema();
pub const PRUNE_SCHEDULE_SCHEMA: Schema = StringSchema::new( pub const VERIFICATION_SCHEDULE_SCHEMA: Schema =
"Run prune job at specified schedule.") StringSchema::new("Run verify job at specified schedule.")
.format(&ApiStringFormat::VerifyFn(proxmox_time::verify_calendar_event)) .format(&ApiStringFormat::VerifyFn(
.type_text("<calendar-event>") proxmox_time::verify_calendar_event,
.schema(); ))
.type_text("<calendar-event>")
pub const VERIFICATION_SCHEDULE_SCHEMA: Schema = StringSchema::new( .schema();
"Run verify job at specified schedule.")
.format(&ApiStringFormat::VerifyFn(proxmox_time::verify_calendar_event))
.type_text("<calendar-event>")
.schema();
pub const REMOVE_VANISHED_BACKUPS_SCHEMA: Schema = BooleanSchema::new( pub const REMOVE_VANISHED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
"Delete vanished backups. This remove the local copy if the remote backup was deleted.") "Delete vanished backups. This remove the local copy if the remote backup was deleted.",
.default(false) )
.schema(); .default(false)
.schema();
#[api( #[api(
properties: { properties: {
@ -80,17 +87,17 @@ pub const REMOVE_VANISHED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
}, },
} }
)] )]
#[derive(Serialize,Deserialize,Default)] #[derive(Serialize, Deserialize, Default)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Job Scheduling Status /// Job Scheduling Status
pub struct JobScheduleStatus { pub struct JobScheduleStatus {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub next_run: Option<i64>, pub next_run: Option<i64>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub last_run_state: Option<String>, pub last_run_state: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub last_run_upid: Option<String>, pub last_run_upid: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub last_run_endtime: Option<i64>, pub last_run_endtime: Option<i64>,
} }
@ -134,20 +141,23 @@ pub struct DatastoreNotify {
pub sync: Option<Notify>, pub sync: Option<Notify>,
} }
pub const DATASTORE_NOTIFY_STRING_SCHEMA: Schema = StringSchema::new( pub const DATASTORE_NOTIFY_STRING_SCHEMA: Schema =
"Datastore notification setting") StringSchema::new("Datastore notification setting")
.format(&ApiStringFormat::PropertyString(&DatastoreNotify::API_SCHEMA)) .format(&ApiStringFormat::PropertyString(
.schema(); &DatastoreNotify::API_SCHEMA,
))
.schema();
pub const IGNORE_VERIFIED_BACKUPS_SCHEMA: Schema = BooleanSchema::new( pub const IGNORE_VERIFIED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
"Do not verify backups that are already verified if their verification is not outdated.") "Do not verify backups that are already verified if their verification is not outdated.",
.default(true) )
.schema(); .default(true)
.schema();
pub const VERIFICATION_OUTDATED_AFTER_SCHEMA: Schema = IntegerSchema::new( pub const VERIFICATION_OUTDATED_AFTER_SCHEMA: Schema =
"Days after that a verification becomes outdated") IntegerSchema::new("Days after that a verification becomes outdated. (0 is deprecated)'")
.minimum(1) .minimum(0)
.schema(); .schema();
#[api( #[api(
properties: { properties: {
@ -173,29 +183,53 @@ pub const VERIFICATION_OUTDATED_AFTER_SCHEMA: Schema = IntegerSchema::new(
optional: true, optional: true,
schema: VERIFICATION_SCHEDULE_SCHEMA, schema: VERIFICATION_SCHEDULE_SCHEMA,
}, },
ns: {
optional: true,
schema: BACKUP_NAMESPACE_SCHEMA,
},
"max-depth": {
optional: true,
schema: crate::NS_MAX_DEPTH_SCHEMA,
},
} }
)] )]
#[derive(Serialize,Deserialize,Updater)] #[derive(Serialize, Deserialize, Updater)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Verification Job /// Verification Job
pub struct VerificationJobConfig { pub struct VerificationJobConfig {
/// unique ID to address this job /// unique ID to address this job
#[updater(skip)] #[updater(skip)]
pub id: String, pub id: String,
/// the datastore ID this verificaiton job affects /// the datastore ID this verification job affects
pub store: String, pub store: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// if not set to false, check the age of the last snapshot verification to filter /// if not set to false, check the age of the last snapshot verification to filter
/// out recent ones, depending on 'outdated_after' configuration. /// out recent ones, depending on 'outdated_after' configuration.
pub ignore_verified: Option<bool>, pub ignore_verified: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// Reverify snapshots after X days, never if 0. Ignored if 'ignore_verified' is false. /// Reverify snapshots after X days, never if 0. Ignored if 'ignore_verified' is false.
pub outdated_after: Option<i64>, pub outdated_after: Option<i64>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// when to schedule this job in calendar event notation /// when to schedule this job in calendar event notation
pub schedule: Option<String>, pub schedule: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
/// on which backup namespace to run the verification recursively
pub ns: Option<BackupNamespace>,
#[serde(skip_serializing_if = "Option::is_none", default)]
/// how deep the verify should go from the `ns` level downwards. Passing 0 verifies only the
/// snapshots on the same level as the passed `ns`, or the datastore root if none.
pub max_depth: Option<usize>,
}
impl VerificationJobConfig {
pub fn acl_path(&self) -> Vec<&str> {
match self.ns.as_ref() {
Some(ns) => ns.acl_path(&self.store),
None => vec!["datastore", &self.store],
}
}
} }
#[api( #[api(
@ -208,8 +242,8 @@ pub struct VerificationJobConfig {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Status of Verification Job /// Status of Verification Job
pub struct VerificationJobStatus { pub struct VerificationJobStatus {
#[serde(flatten)] #[serde(flatten)]
@ -252,26 +286,38 @@ pub struct VerificationJobStatus {
schema: GROUP_FILTER_LIST_SCHEMA, schema: GROUP_FILTER_LIST_SCHEMA,
optional: true, optional: true,
}, },
ns: {
type: BackupNamespace,
optional: true,
},
"max-depth": {
schema: crate::NS_MAX_DEPTH_SCHEMA,
optional: true,
},
} }
)] )]
#[derive(Serialize,Deserialize,Clone,Updater)] #[derive(Serialize, Deserialize, Clone, Updater)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Tape Backup Job Setup /// Tape Backup Job Setup
pub struct TapeBackupJobSetup { pub struct TapeBackupJobSetup {
pub store: String, pub store: String,
pub pool: String, pub pool: String,
pub drive: String, pub drive: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub eject_media: Option<bool>, pub eject_media: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub export_media_set: Option<bool>, pub export_media_set: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub latest_only: Option<bool>, pub latest_only: Option<bool>,
/// Send job email notification to this user /// Send job email notification to this user
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub notify_user: Option<Userid>, pub notify_user: Option<Userid>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub group_filter: Option<Vec<GroupFilter>>, pub group_filter: Option<Vec<GroupFilter>>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ns: Option<BackupNamespace>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub max_depth: Option<usize>,
} }
#[api( #[api(
@ -292,17 +338,17 @@ pub struct TapeBackupJobSetup {
}, },
} }
)] )]
#[derive(Serialize,Deserialize,Clone,Updater)] #[derive(Serialize, Deserialize, Clone, Updater)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Tape Backup Job /// Tape Backup Job
pub struct TapeBackupJobConfig { pub struct TapeBackupJobConfig {
#[updater(skip)] #[updater(skip)]
pub id: String, pub id: String,
#[serde(flatten)] #[serde(flatten)]
pub setup: TapeBackupJobSetup, pub setup: TapeBackupJobSetup,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub schedule: Option<String>, pub schedule: Option<String>,
} }
@ -316,8 +362,8 @@ pub struct TapeBackupJobConfig {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Status of Tape Backup Job /// Status of Tape Backup Job
pub struct TapeBackupJobStatus { pub struct TapeBackupJobStatus {
#[serde(flatten)] #[serde(flatten)]
@ -325,7 +371,7 @@ pub struct TapeBackupJobStatus {
#[serde(flatten)] #[serde(flatten)]
pub status: JobScheduleStatus, pub status: JobScheduleStatus,
/// Next tape used (best guess) /// Next tape used (best guess)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub next_media_label: Option<String>, pub next_media_label: Option<String>,
} }
@ -333,7 +379,7 @@ pub struct TapeBackupJobStatus {
/// Filter for matching `BackupGroup`s, for use with `BackupGroup::filter`. /// Filter for matching `BackupGroup`s, for use with `BackupGroup::filter`.
pub enum GroupFilter { pub enum GroupFilter {
/// BackupGroup type - either `vm`, `ct`, or `host`. /// BackupGroup type - either `vm`, `ct`, or `host`.
BackupType(String), BackupType(BackupType),
/// Full identifier of BackupGroup, including type /// Full identifier of BackupGroup, including type
Group(String), Group(String),
/// A regular expression matched against the full identifier of the BackupGroup /// A regular expression matched against the full identifier of the BackupGroup
@ -344,9 +390,9 @@ impl std::str::FromStr for GroupFilter {
type Err = anyhow::Error; type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.split_once(":") { match s.split_once(':') {
Some(("group", value)) => parse_simple_value(value, &BACKUP_GROUP_SCHEMA).map(|_| GroupFilter::Group(value.to_string())), Some(("group", value)) => BACKUP_GROUP_SCHEMA.parse_simple_value(value).map(|_| GroupFilter::Group(value.to_string())),
Some(("type", value)) => parse_simple_value(value, &BACKUP_TYPE_SCHEMA).map(|_| GroupFilter::BackupType(value.to_string())), Some(("type", value)) => Ok(GroupFilter::BackupType(value.parse()?)),
Some(("regex", value)) => Ok(GroupFilter::Regex(Regex::new(value)?)), Some(("regex", value)) => Ok(GroupFilter::Regex(Regex::new(value)?)),
Some((ty, _value)) => Err(format_err!("expected 'group', 'type' or 'regex' prefix, got '{}'", ty)), Some((ty, _value)) => Err(format_err!("expected 'group', 'type' or 'regex' prefix, got '{}'", ty)),
None => Err(format_err!("input doesn't match expected format '<group:GROUP||type:<vm|ct|host>|regex:REGEX>'")), None => Err(format_err!("input doesn't match expected format '<group:GROUP||type:<vm|ct|host>|regex:REGEX>'")),
@ -365,8 +411,8 @@ impl std::fmt::Display for GroupFilter {
} }
} }
proxmox::forward_deserialize_to_from_str!(GroupFilter); proxmox_serde::forward_deserialize_to_from_str!(GroupFilter);
proxmox::forward_serialize_to_display!(GroupFilter); proxmox_serde::forward_serialize_to_display!(GroupFilter);
fn verify_group_filter(input: &str) -> Result<(), anyhow::Error> { fn verify_group_filter(input: &str) -> Result<(), anyhow::Error> {
GroupFilter::from_str(input).map(|_| ()) GroupFilter::from_str(input).map(|_| ())
@ -378,7 +424,8 @@ pub const GROUP_FILTER_SCHEMA: Schema = StringSchema::new(
.type_text("<type:<vm|ct|host>|group:GROUP|regex:RE>") .type_text("<type:<vm|ct|host>|group:GROUP|regex:RE>")
.schema(); .schema();
pub const GROUP_FILTER_LIST_SCHEMA: Schema = ArraySchema::new("List of group filters.", &GROUP_FILTER_SCHEMA).schema(); pub const GROUP_FILTER_LIST_SCHEMA: Schema =
ArraySchema::new("List of group filters.", &GROUP_FILTER_SCHEMA).schema();
#[api( #[api(
properties: { properties: {
@ -388,6 +435,10 @@ pub const GROUP_FILTER_LIST_SCHEMA: Schema = ArraySchema::new("List of group fil
store: { store: {
schema: DATASTORE_SCHEMA, schema: DATASTORE_SCHEMA,
}, },
ns: {
type: BackupNamespace,
optional: true,
},
"owner": { "owner": {
type: Authid, type: Authid,
optional: true, optional: true,
@ -398,10 +449,18 @@ pub const GROUP_FILTER_LIST_SCHEMA: Schema = ArraySchema::new("List of group fil
"remote-store": { "remote-store": {
schema: DATASTORE_SCHEMA, schema: DATASTORE_SCHEMA,
}, },
"remote-ns": {
type: BackupNamespace,
optional: true,
},
"remove-vanished": { "remove-vanished": {
schema: REMOVE_VANISHED_BACKUPS_SCHEMA, schema: REMOVE_VANISHED_BACKUPS_SCHEMA,
optional: true, optional: true,
}, },
"max-depth": {
schema: NS_MAX_DEPTH_REDUCED_SCHEMA,
optional: true,
},
comment: { comment: {
optional: true, optional: true,
schema: SINGLE_LINE_COMMENT_SCHEMA, schema: SINGLE_LINE_COMMENT_SCHEMA,
@ -419,29 +478,44 @@ pub const GROUP_FILTER_LIST_SCHEMA: Schema = ArraySchema::new("List of group fil
}, },
} }
)] )]
#[derive(Serialize,Deserialize,Clone,Updater)] #[derive(Serialize, Deserialize, Clone, Updater)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Sync Job /// Sync Job
pub struct SyncJobConfig { pub struct SyncJobConfig {
#[updater(skip)] #[updater(skip)]
pub id: String, pub id: String,
pub store: String, pub store: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub ns: Option<BackupNamespace>,
#[serde(skip_serializing_if = "Option::is_none")]
pub owner: Option<Authid>, pub owner: Option<Authid>,
pub remote: String, pub remote: String,
pub remote_store: String, pub remote_store: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub remote_ns: Option<BackupNamespace>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remove_vanished: Option<bool>, pub remove_vanished: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_depth: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub schedule: Option<String>, pub schedule: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub group_filter: Option<Vec<GroupFilter>>, pub group_filter: Option<Vec<GroupFilter>>,
#[serde(flatten)] #[serde(flatten)]
pub limit: RateLimitConfig, pub limit: RateLimitConfig,
} }
impl SyncJobConfig {
pub fn acl_path(&self) -> Vec<&str> {
match self.ns.as_ref() {
Some(ns) => ns.acl_path(&self.store),
None => vec!["datastore", &self.store],
}
}
}
#[api( #[api(
properties: { properties: {
config: { config: {
@ -452,9 +526,8 @@ pub struct SyncJobConfig {
}, },
}, },
)] )]
#[derive(Serialize, Deserialize)]
#[derive(Serialize,Deserialize)] #[serde(rename_all = "kebab-case")]
#[serde(rename_all="kebab-case")]
/// Status of Sync Job /// Status of Sync Job
pub struct SyncJobStatus { pub struct SyncJobStatus {
#[serde(flatten)] #[serde(flatten)]
@ -462,3 +535,186 @@ pub struct SyncJobStatus {
#[serde(flatten)] #[serde(flatten)]
pub status: JobScheduleStatus, pub status: JobScheduleStatus,
} }
/// These are used separately without `ns`/`max-depth` sometimes in the API, specifically in the API
/// call to prune a specific group, where `max-depth` makes no sense.
#[api(
properties: {
"keep-last": {
schema: crate::PRUNE_SCHEMA_KEEP_LAST,
optional: true,
},
"keep-hourly": {
schema: crate::PRUNE_SCHEMA_KEEP_HOURLY,
optional: true,
},
"keep-daily": {
schema: crate::PRUNE_SCHEMA_KEEP_DAILY,
optional: true,
},
"keep-weekly": {
schema: crate::PRUNE_SCHEMA_KEEP_WEEKLY,
optional: true,
},
"keep-monthly": {
schema: crate::PRUNE_SCHEMA_KEEP_MONTHLY,
optional: true,
},
"keep-yearly": {
schema: crate::PRUNE_SCHEMA_KEEP_YEARLY,
optional: true,
},
}
)]
#[derive(Serialize, Deserialize, Default, Updater)]
#[serde(rename_all = "kebab-case")]
/// Common pruning options
pub struct KeepOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_last: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_hourly: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_daily: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_weekly: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_monthly: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub keep_yearly: Option<u64>,
}
impl KeepOptions {
pub fn keeps_something(&self) -> bool {
self.keep_last.unwrap_or(0)
+ self.keep_hourly.unwrap_or(0)
+ self.keep_daily.unwrap_or(0)
+ self.keep_weekly.unwrap_or(0)
+ self.keep_monthly.unwrap_or(0)
+ self.keep_yearly.unwrap_or(0)
> 0
}
}
#[api(
properties: {
keep: {
type: KeepOptions,
},
ns: {
type: BackupNamespace,
optional: true,
},
"max-depth": {
schema: NS_MAX_DEPTH_REDUCED_SCHEMA,
optional: true,
},
}
)]
#[derive(Serialize, Deserialize, Default, Updater)]
#[serde(rename_all = "kebab-case")]
/// Common pruning options
pub struct PruneJobOptions {
#[serde(flatten)]
pub keep: KeepOptions,
/// The (optional) recursion depth
#[serde(skip_serializing_if = "Option::is_none")]
pub max_depth: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ns: Option<BackupNamespace>,
}
impl PruneJobOptions {
pub fn keeps_something(&self) -> bool {
self.keep.keeps_something()
}
pub fn acl_path<'a>(&'a self, store: &'a str) -> Vec<&'a str> {
match &self.ns {
Some(ns) => ns.acl_path(store),
None => vec!["datastore", store],
}
}
}
#[api(
properties: {
disable: {
type: Boolean,
optional: true,
default: false,
},
id: {
schema: JOB_ID_SCHEMA,
},
store: {
schema: DATASTORE_SCHEMA,
},
schedule: {
schema: PRUNE_SCHEDULE_SCHEMA,
optional: true,
},
comment: {
optional: true,
schema: SINGLE_LINE_COMMENT_SCHEMA,
},
options: {
type: PruneJobOptions,
},
},
)]
#[derive(Deserialize, Serialize, Updater)]
#[serde(rename_all = "kebab-case")]
/// Prune configuration.
pub struct PruneJobConfig {
/// unique ID to address this job
#[updater(skip)]
pub id: String,
pub store: String,
/// Disable this job.
#[serde(default, skip_serializing_if = "is_false")]
#[updater(serde(skip_serializing_if = "Option::is_none"))]
pub disable: bool,
pub schedule: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(flatten)]
pub options: PruneJobOptions,
}
impl PruneJobConfig {
pub fn acl_path(&self) -> Vec<&str> {
self.options.acl_path(&self.store)
}
}
fn is_false(b: &bool) -> bool {
!b
}
#[api(
properties: {
config: {
type: PruneJobConfig,
},
status: {
type: JobScheduleStatus,
},
},
)]
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
/// Status of prune job
pub struct PruneJobStatus {
#[serde(flatten)]
pub config: PruneJobConfig,
#[serde(flatten)]
pub status: JobScheduleStatus,
}

View File

@ -39,7 +39,7 @@ impl Default for Kdf {
/// Encryption Key Information /// Encryption Key Information
pub struct KeyInfo { pub struct KeyInfo {
/// Path to key (if stored in a file) /// Path to key (if stored in a file)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>, pub path: Option<String>,
pub kdf: Kdf, pub kdf: Kdf,
/// Key creation time /// Key creation time
@ -47,10 +47,9 @@ pub struct KeyInfo {
/// Key modification time /// Key modification time
pub modified: i64, pub modified: i64,
/// Key fingerprint /// Key fingerprint
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub fingerprint: Option<String>, pub fingerprint: Option<String>,
/// Password hint /// Password hint
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub hint: Option<String>, pub hint: Option<String>,
} }

View File

@ -1,12 +1,13 @@
//! Basic API types used by most of the PBS code. //! Basic API types used by most of the PBS code.
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use anyhow::bail;
pub mod common_regex;
pub mod percent_encoding;
use proxmox_schema::{ use proxmox_schema::{
api, const_regex, ApiStringFormat, ApiType, ArraySchema, Schema, StringSchema, ReturnType, api, const_regex, ApiStringFormat, ApiType, ArraySchema, ReturnType, Schema, StringSchema,
}; };
use proxmox::{IPRE, IPRE_BRACKET, IPV4OCTET, IPV4RE, IPV6H16, IPV6LS32, IPV6RE};
use proxmox_time::parse_daily_duration; use proxmox_time::parse_daily_duration;
#[rustfmt::skip] #[rustfmt::skip]
@ -25,14 +26,44 @@ macro_rules! BACKUP_TYPE_RE { () => (r"(?:host|vm|ct)") }
#[macro_export] #[macro_export]
macro_rules! BACKUP_TIME_RE { () => (r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z") } macro_rules! BACKUP_TIME_RE { () => (r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z") }
#[rustfmt::skip]
#[macro_export]
macro_rules! BACKUP_NS_RE {
() => (
concat!("(?:",
"(?:", PROXMOX_SAFE_ID_REGEX_STR!(), r"/){0,7}", PROXMOX_SAFE_ID_REGEX_STR!(),
")?")
);
}
#[rustfmt::skip]
#[macro_export]
macro_rules! BACKUP_NS_PATH_RE {
() => (
concat!(r"(?:ns/", PROXMOX_SAFE_ID_REGEX_STR!(), r"/){0,7}ns/", PROXMOX_SAFE_ID_REGEX_STR!(), r"/")
);
}
#[rustfmt::skip] #[rustfmt::skip]
#[macro_export] #[macro_export]
macro_rules! SNAPSHOT_PATH_REGEX_STR { macro_rules! SNAPSHOT_PATH_REGEX_STR {
() => ( () => (
concat!(r"(", BACKUP_TYPE_RE!(), ")/(", BACKUP_ID_RE!(), ")/(", BACKUP_TIME_RE!(), r")") concat!(
r"(", BACKUP_TYPE_RE!(), ")/(", BACKUP_ID_RE!(), ")/(", BACKUP_TIME_RE!(), r")",
)
); );
} }
#[rustfmt::skip]
#[macro_export]
macro_rules! GROUP_OR_SNAPSHOT_PATH_REGEX_STR {
() => {
concat!(
r"(", BACKUP_TYPE_RE!(), ")/(", BACKUP_ID_RE!(), ")(?:/(", BACKUP_TIME_RE!(), r"))?",
)
};
}
mod acl; mod acl;
pub use acl::*; pub use acl::*;
@ -48,6 +79,9 @@ pub use jobs::*;
mod key_derivation; mod key_derivation;
pub use key_derivation::{Kdf, KeyInfo}; pub use key_derivation::{Kdf, KeyInfo};
mod maintenance;
pub use maintenance::*;
mod network; mod network;
pub use network::*; pub use network::*;
@ -67,7 +101,7 @@ pub use user::*;
pub use proxmox_schema::upid::*; pub use proxmox_schema::upid::*;
mod crypto; mod crypto;
pub use crypto::{CryptMode, Fingerprint, bytes_as_fingerprint}; pub use crypto::{bytes_as_fingerprint, CryptMode, Fingerprint};
pub mod file_restore; pub mod file_restore;
@ -86,7 +120,6 @@ pub use traffic_control::*;
mod zfs; mod zfs;
pub use zfs::*; pub use zfs::*;
#[rustfmt::skip] #[rustfmt::skip]
#[macro_use] #[macro_use]
mod local_macros { mod local_macros {
@ -122,6 +155,9 @@ const_regex! {
pub FINGERPRINT_SHA256_REGEX = r"^(?:[0-9a-fA-F][0-9a-fA-F])(?::[0-9a-fA-F][0-9a-fA-F]){31}$"; pub FINGERPRINT_SHA256_REGEX = r"^(?:[0-9a-fA-F][0-9a-fA-F])(?::[0-9a-fA-F][0-9a-fA-F]){31}$";
// just a rough check - dummy acceptor is used before persisting
pub OPENSSL_CIPHERS_REGEX = r"^[0-9A-Za-z_:, +!\-@=.]+$";
/// Regex for safe identifiers. /// Regex for safe identifiers.
/// ///
/// This /// This
@ -133,6 +169,8 @@ const_regex! {
pub SINGLE_LINE_COMMENT_REGEX = r"^[[:^cntrl:]]*$"; pub SINGLE_LINE_COMMENT_REGEX = r"^[[:^cntrl:]]*$";
pub MULTI_LINE_COMMENT_REGEX = r"(?m)^([[:^cntrl:]]*)$";
pub BACKUP_REPO_URL_REGEX = concat!( pub BACKUP_REPO_URL_REGEX = concat!(
r"^^(?:(?:(", r"^^(?:(?:(",
USER_ID_REGEX_STR!(), "|", APITOKEN_ID_REGEX_STR!(), USER_ID_REGEX_STR!(), "|", APITOKEN_ID_REGEX_STR!(),
@ -154,13 +192,17 @@ pub const CIDR_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&CIDR_REGEX);
pub const PVE_CONFIG_DIGEST_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&SHA256_HEX_REGEX); pub const PVE_CONFIG_DIGEST_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&SHA256_HEX_REGEX);
pub const PASSWORD_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&PASSWORD_REGEX); pub const PASSWORD_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&PASSWORD_REGEX);
pub const UUID_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&UUID_REGEX); pub const UUID_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&UUID_REGEX);
pub const BLOCKDEVICE_NAME_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&BLOCKDEVICE_NAME_REGEX); pub const BLOCKDEVICE_NAME_FORMAT: ApiStringFormat =
pub const SUBSCRIPTION_KEY_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&SUBSCRIPTION_KEY_REGEX); ApiStringFormat::Pattern(&BLOCKDEVICE_NAME_REGEX);
pub const SYSTEMD_DATETIME_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&SYSTEMD_DATETIME_REGEX); pub const SUBSCRIPTION_KEY_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&SUBSCRIPTION_KEY_REGEX);
pub const SYSTEMD_DATETIME_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&SYSTEMD_DATETIME_REGEX);
pub const HOSTNAME_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&HOSTNAME_REGEX); pub const HOSTNAME_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&HOSTNAME_REGEX);
pub const OPENSSL_CIPHERS_TLS_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&OPENSSL_CIPHERS_REGEX);
pub const DNS_ALIAS_FORMAT: ApiStringFormat = pub const DNS_ALIAS_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&DNS_ALIAS_REGEX);
ApiStringFormat::Pattern(&DNS_ALIAS_REGEX);
pub const DAILY_DURATION_FORMAT: ApiStringFormat = pub const DAILY_DURATION_FORMAT: ApiStringFormat =
ApiStringFormat::VerifyFn(|s| parse_daily_duration(s).map(drop)); ApiStringFormat::VerifyFn(|s| parse_daily_duration(s).map(drop));
@ -168,18 +210,15 @@ pub const DAILY_DURATION_FORMAT: ApiStringFormat =
pub const SEARCH_DOMAIN_SCHEMA: Schema = pub const SEARCH_DOMAIN_SCHEMA: Schema =
StringSchema::new("Search domain for host-name lookup.").schema(); StringSchema::new("Search domain for host-name lookup.").schema();
pub const FIRST_DNS_SERVER_SCHEMA: Schema = pub const FIRST_DNS_SERVER_SCHEMA: Schema = StringSchema::new("First name server IP address.")
StringSchema::new("First name server IP address.")
.format(&IP_FORMAT) .format(&IP_FORMAT)
.schema(); .schema();
pub const SECOND_DNS_SERVER_SCHEMA: Schema = pub const SECOND_DNS_SERVER_SCHEMA: Schema = StringSchema::new("Second name server IP address.")
StringSchema::new("Second name server IP address.")
.format(&IP_FORMAT) .format(&IP_FORMAT)
.schema(); .schema();
pub const THIRD_DNS_SERVER_SCHEMA: Schema = pub const THIRD_DNS_SERVER_SCHEMA: Schema = StringSchema::new("Third name server IP address.")
StringSchema::new("Third name server IP address.")
.format(&IP_FORMAT) .format(&IP_FORMAT)
.schema(); .schema();
@ -187,45 +226,47 @@ pub const HOSTNAME_SCHEMA: Schema = StringSchema::new("Hostname (as defined in R
.format(&HOSTNAME_FORMAT) .format(&HOSTNAME_FORMAT)
.schema(); .schema();
pub const DNS_NAME_FORMAT: ApiStringFormat = pub const OPENSSL_CIPHERS_TLS_1_2_SCHEMA: Schema =
ApiStringFormat::Pattern(&DNS_NAME_REGEX); StringSchema::new("OpenSSL cipher list used by the proxy for TLS <= 1.2")
.format(&OPENSSL_CIPHERS_TLS_FORMAT)
.schema();
pub const DNS_NAME_OR_IP_FORMAT: ApiStringFormat = pub const OPENSSL_CIPHERS_TLS_1_3_SCHEMA: Schema =
ApiStringFormat::Pattern(&DNS_NAME_OR_IP_REGEX); StringSchema::new("OpenSSL ciphersuites list used by the proxy for TLS 1.3")
.format(&OPENSSL_CIPHERS_TLS_FORMAT)
.schema();
pub const DNS_NAME_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&DNS_NAME_REGEX);
pub const DNS_NAME_OR_IP_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&DNS_NAME_OR_IP_REGEX);
pub const DNS_NAME_OR_IP_SCHEMA: Schema = StringSchema::new("DNS name or IP address.") pub const DNS_NAME_OR_IP_SCHEMA: Schema = StringSchema::new("DNS name or IP address.")
.format(&DNS_NAME_OR_IP_FORMAT) .format(&DNS_NAME_OR_IP_FORMAT)
.schema(); .schema();
pub const NODE_SCHEMA: Schema = StringSchema::new("Node name (or 'localhost')") pub const NODE_SCHEMA: Schema = StringSchema::new("Node name (or 'localhost')")
.format(&ApiStringFormat::VerifyFn(|node| { .format(&HOSTNAME_FORMAT)
if node == "localhost" || node == proxmox::tools::nodename() {
Ok(())
} else {
bail!("no such node '{}'", node);
}
}))
.schema(); .schema();
pub const TIME_ZONE_SCHEMA: Schema = StringSchema::new( pub const TIME_ZONE_SCHEMA: Schema = StringSchema::new(
"Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.") "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.",
.format(&SINGLE_LINE_COMMENT_FORMAT) )
.min_length(2) .format(&SINGLE_LINE_COMMENT_FORMAT)
.max_length(64) .min_length(2)
.schema(); .max_length(64)
.schema();
pub const BLOCKDEVICE_NAME_SCHEMA: Schema = StringSchema::new("Block device name (/sys/block/<name>).") pub const BLOCKDEVICE_NAME_SCHEMA: Schema =
.format(&BLOCKDEVICE_NAME_FORMAT) StringSchema::new("Block device name (/sys/block/<name>).")
.min_length(3) .format(&BLOCKDEVICE_NAME_FORMAT)
.max_length(64) .min_length(3)
.schema(); .max_length(64)
.schema();
pub const DISK_ARRAY_SCHEMA: Schema = ArraySchema::new( pub const DISK_ARRAY_SCHEMA: Schema =
"Disk name list.", &BLOCKDEVICE_NAME_SCHEMA) ArraySchema::new("Disk name list.", &BLOCKDEVICE_NAME_SCHEMA).schema();
.schema();
pub const DISK_LIST_SCHEMA: Schema = StringSchema::new( pub const DISK_LIST_SCHEMA: Schema = StringSchema::new("A list of disk names, comma separated.")
"A list of disk names, comma separated.")
.format(&ApiStringFormat::PropertyString(&DISK_ARRAY_SCHEMA)) .format(&ApiStringFormat::PropertyString(&DISK_ARRAY_SCHEMA))
.schema(); .schema();
@ -265,15 +306,21 @@ pub const SINGLE_LINE_COMMENT_SCHEMA: Schema = StringSchema::new("Comment (singl
.format(&SINGLE_LINE_COMMENT_FORMAT) .format(&SINGLE_LINE_COMMENT_FORMAT)
.schema(); .schema();
pub const SUBSCRIPTION_KEY_SCHEMA: Schema = StringSchema::new("Proxmox Backup Server subscription key.") pub const MULTI_LINE_COMMENT_FORMAT: ApiStringFormat =
.format(&SUBSCRIPTION_KEY_FORMAT) ApiStringFormat::Pattern(&MULTI_LINE_COMMENT_REGEX);
.min_length(15)
.max_length(16) pub const MULTI_LINE_COMMENT_SCHEMA: Schema = StringSchema::new("Comment (multiple lines).")
.format(&MULTI_LINE_COMMENT_FORMAT)
.schema(); .schema();
pub const SERVICE_ID_SCHEMA: Schema = StringSchema::new("Service ID.") pub const SUBSCRIPTION_KEY_SCHEMA: Schema =
.max_length(256) StringSchema::new("Proxmox Backup Server subscription key.")
.schema(); .format(&SUBSCRIPTION_KEY_FORMAT)
.min_length(15)
.max_length(16)
.schema();
pub const SERVICE_ID_SCHEMA: Schema = StringSchema::new("Service ID.").max_length(256).schema();
pub const PROXMOX_CONFIG_DIGEST_SCHEMA: Schema = StringSchema::new( pub const PROXMOX_CONFIG_DIGEST_SCHEMA: Schema = StringSchema::new(
"Prevent changes if current configuration file has different \ "Prevent changes if current configuration file has different \
@ -286,10 +333,8 @@ pub const PROXMOX_CONFIG_DIGEST_SCHEMA: Schema = StringSchema::new(
/// API schema format definition for repository URLs /// API schema format definition for repository URLs
pub const BACKUP_REPO_URL: ApiStringFormat = ApiStringFormat::Pattern(&BACKUP_REPO_URL_REGEX); pub const BACKUP_REPO_URL: ApiStringFormat = ApiStringFormat::Pattern(&BACKUP_REPO_URL_REGEX);
// Complex type definitions // Complex type definitions
#[api()] #[api()]
#[derive(Default, Serialize, Deserialize)] #[derive(Default, Serialize, Deserialize)]
/// Storage space usage information. /// Storage space usage information.
@ -308,39 +353,6 @@ pub const PASSWORD_HINT_SCHEMA: Schema = StringSchema::new("Password hint.")
.max_length(64) .max_length(64)
.schema(); .schema();
#[api]
#[derive(Deserialize, Serialize)]
/// RSA public key information
pub struct RsaPubKeyInfo {
/// Path to key (if stored in a file)
#[serde(skip_serializing_if="Option::is_none")]
pub path: Option<String>,
/// RSA exponent
pub exponent: String,
/// Hex-encoded RSA modulus
pub modulus: String,
/// Key (modulus) length in bits
pub length: usize,
}
impl std::convert::TryFrom<openssl::rsa::Rsa<openssl::pkey::Public>> for RsaPubKeyInfo {
type Error = anyhow::Error;
fn try_from(value: openssl::rsa::Rsa<openssl::pkey::Public>) -> Result<Self, Self::Error> {
let modulus = value.n().to_hex_str()?.to_string();
let exponent = value.e().to_dec_str()?.to_string();
let length = value.size() as usize * 8;
Ok(Self {
path: None,
exponent,
modulus,
length,
})
}
}
#[api()] #[api()]
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")] #[serde(rename_all = "PascalCase")]
@ -367,11 +379,10 @@ pub struct APTUpdateInfo {
/// 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 /// Custom extra field for additional package information
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub extra_info: Option<String>, pub extra_info: Option<String>,
} }
#[api()] #[api()]
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
@ -383,7 +394,6 @@ pub enum NodePowerCommand {
Shutdown, Shutdown,
} }
#[api()] #[api()]
#[derive(Eq, PartialEq, Debug, Serialize, Deserialize)] #[derive(Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
@ -422,19 +432,16 @@ pub struct TaskListItem {
/// The authenticated entity who started the task /// The authenticated entity who started the task
pub user: String, pub user: String,
/// The task end time (Epoch) /// The task end time (Epoch)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub endtime: Option<i64>, pub endtime: Option<i64>,
/// Task end status /// Task end status
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>, pub status: Option<String>,
} }
pub const NODE_TASKS_LIST_TASKS_RETURN_TYPE: ReturnType = ReturnType { pub const NODE_TASKS_LIST_TASKS_RETURN_TYPE: ReturnType = ReturnType {
optional: false, optional: false,
schema: &ArraySchema::new( schema: &ArraySchema::new("A list of tasks.", &TaskListItem::API_SCHEMA).schema(),
"A list of tasks.",
&TaskListItem::API_SCHEMA,
).schema(),
}; };
#[api()] #[api()]
@ -466,3 +473,44 @@ pub enum RRDTimeFrame {
/// Decade (10 years) /// Decade (10 years)
Decade, Decade,
} }
#[api]
#[derive(Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
/// type of the realm
pub enum RealmType {
/// The PAM realm
Pam,
/// The PBS realm
Pbs,
/// An OpenID Connect realm
OpenId,
}
#[api(
properties: {
realm: {
schema: REALM_ID_SCHEMA,
},
"type": {
type: RealmType,
},
comment: {
optional: true,
schema: SINGLE_LINE_COMMENT_SCHEMA,
},
},
)]
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
/// Basic Information about a realm
pub struct BasicRealmInfo {
pub realm: String,
#[serde(rename = "type")]
pub ty: RealmType,
/// True if it is the default realm
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
}

View File

@ -0,0 +1,92 @@
use anyhow::{bail, Error};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use proxmox_schema::{api, const_regex, ApiStringFormat, Schema, StringSchema};
const_regex! {
pub MAINTENANCE_MESSAGE_REGEX = r"^[[:^cntrl:]]*$";
}
pub const MAINTENANCE_MESSAGE_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&MAINTENANCE_MESSAGE_REGEX);
pub const MAINTENANCE_MESSAGE_SCHEMA: Schema =
StringSchema::new("Message describing the reason for the maintenance.")
.format(&MAINTENANCE_MESSAGE_FORMAT)
.max_length(64)
.schema();
#[derive(Clone, Copy, Debug)]
/// Operation requirements, used when checking for maintenance mode.
pub enum Operation {
/// for any read operation like backup restore or RRD metric collection
Read,
/// for any write/delete operation, like backup create or GC
Write,
/// for any purely logical operation on the in-memory state of the datastore, e.g., to check if
/// some mutex could be locked (e.g., GC already running?)
///
/// NOTE: one must *not* do any IO operations when only helding this Op state
Lookup,
// GarbageCollect or Delete?
}
#[api]
#[derive(Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
/// Maintenance type.
pub enum MaintenanceType {
// TODO:
// - Add "unmounting" once we got pluggable datastores
// - Add "GarbageCollection" or "DeleteOnly" as type and track GC (or all deletes) as separate
// operation, so that one can enable a mode where nothing new can be added but stuff can be
// cleaned
/// Only read operations are allowed on the datastore.
ReadOnly,
/// Neither read nor write operations are allowed on the datastore.
Offline,
}
#[api(
properties: {
type: {
type: MaintenanceType,
},
message: {
optional: true,
schema: MAINTENANCE_MESSAGE_SCHEMA,
}
},
default_key: "type",
)]
#[derive(Deserialize, Serialize)]
/// Maintenance mode
pub struct MaintenanceMode {
/// Type of maintenance ("read-only" or "offline").
#[serde(rename = "type")]
ty: MaintenanceType,
/// Reason for maintenance.
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
}
impl MaintenanceMode {
pub fn check(&self, operation: Option<Operation>) -> Result<(), Error> {
let message = percent_encoding::percent_decode_str(self.message.as_deref().unwrap_or(""))
.decode_utf8()
.unwrap_or(Cow::Borrowed(""));
if let Some(Operation::Lookup) = operation {
return Ok(());
} else if self.ty == MaintenanceType::Offline {
bail!("offline maintenance mode: {}", message);
} else if self.ty == MaintenanceType::ReadOnly {
if let Some(Operation::Write) = operation {
bail!("read-only maintenance mode: {}", message);
}
}
Ok(())
}
}

View File

@ -3,49 +3,43 @@ use serde::{Deserialize, Serialize};
use proxmox_schema::*; use proxmox_schema::*;
use crate::{ use crate::{
CIDR_FORMAT, CIDR_V4_FORMAT, CIDR_V6_FORMAT, IP_FORMAT, IP_V4_FORMAT, IP_V6_FORMAT,
PROXMOX_SAFE_ID_REGEX, PROXMOX_SAFE_ID_REGEX,
IP_V4_FORMAT, IP_V6_FORMAT, IP_FORMAT,
CIDR_V4_FORMAT, CIDR_V6_FORMAT, CIDR_FORMAT,
}; };
pub const NETWORK_INTERFACE_FORMAT: ApiStringFormat = pub const NETWORK_INTERFACE_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX); ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
pub const IP_V4_SCHEMA: Schema = pub const IP_V4_SCHEMA: Schema = StringSchema::new("IPv4 address.")
StringSchema::new("IPv4 address.")
.format(&IP_V4_FORMAT) .format(&IP_V4_FORMAT)
.max_length(15) .max_length(15)
.schema(); .schema();
pub const IP_V6_SCHEMA: Schema = pub const IP_V6_SCHEMA: Schema = StringSchema::new("IPv6 address.")
StringSchema::new("IPv6 address.")
.format(&IP_V6_FORMAT) .format(&IP_V6_FORMAT)
.max_length(39) .max_length(39)
.schema(); .schema();
pub const IP_SCHEMA: Schema = pub const IP_SCHEMA: Schema = StringSchema::new("IP (IPv4 or IPv6) address.")
StringSchema::new("IP (IPv4 or IPv6) address.")
.format(&IP_FORMAT) .format(&IP_FORMAT)
.max_length(39) .max_length(39)
.schema(); .schema();
pub const CIDR_V4_SCHEMA: Schema = pub const CIDR_V4_SCHEMA: Schema = StringSchema::new("IPv4 address with netmask (CIDR notation).")
StringSchema::new("IPv4 address with netmask (CIDR notation).")
.format(&CIDR_V4_FORMAT) .format(&CIDR_V4_FORMAT)
.max_length(18) .max_length(18)
.schema(); .schema();
pub const CIDR_V6_SCHEMA: Schema = pub const CIDR_V6_SCHEMA: Schema = StringSchema::new("IPv6 address with netmask (CIDR notation).")
StringSchema::new("IPv6 address with netmask (CIDR notation).")
.format(&CIDR_V6_FORMAT) .format(&CIDR_V6_FORMAT)
.max_length(43) .max_length(43)
.schema(); .schema();
pub const CIDR_SCHEMA: Schema = pub const CIDR_SCHEMA: Schema =
StringSchema::new("IP address (IPv4 or IPv6) with netmask (CIDR notation).") StringSchema::new("IP address (IPv4 or IPv6) with netmask (CIDR notation).")
.format(&CIDR_FORMAT) .format(&CIDR_FORMAT)
.max_length(43) .max_length(43)
.schema(); .schema();
#[api()] #[api()]
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
@ -127,17 +121,18 @@ pub enum NetworkInterfaceType {
pub const NETWORK_INTERFACE_NAME_SCHEMA: Schema = StringSchema::new("Network interface name.") pub const NETWORK_INTERFACE_NAME_SCHEMA: Schema = StringSchema::new("Network interface name.")
.format(&NETWORK_INTERFACE_FORMAT) .format(&NETWORK_INTERFACE_FORMAT)
.min_length(1) .min_length(1)
.max_length(libc::IFNAMSIZ-1) .max_length(15) // libc::IFNAMSIZ-1
.schema(); .schema();
pub const NETWORK_INTERFACE_ARRAY_SCHEMA: Schema = ArraySchema::new( pub const NETWORK_INTERFACE_ARRAY_SCHEMA: Schema =
"Network interface list.", &NETWORK_INTERFACE_NAME_SCHEMA) ArraySchema::new("Network interface list.", &NETWORK_INTERFACE_NAME_SCHEMA).schema();
.schema();
pub const NETWORK_INTERFACE_LIST_SCHEMA: Schema = StringSchema::new( pub const NETWORK_INTERFACE_LIST_SCHEMA: Schema =
"A list of network devices, comma separated.") StringSchema::new("A list of network devices, comma separated.")
.format(&ApiStringFormat::PropertyString(&NETWORK_INTERFACE_ARRAY_SCHEMA)) .format(&ApiStringFormat::PropertyString(
.schema(); &NETWORK_INTERFACE_ARRAY_SCHEMA,
))
.schema();
#[api( #[api(
properties: { properties: {
@ -232,48 +227,48 @@ pub struct Interface {
/// Interface type /// Interface type
#[serde(rename = "type")] #[serde(rename = "type")]
pub interface_type: NetworkInterfaceType, pub interface_type: NetworkInterfaceType,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<NetworkConfigMethod>, pub method: Option<NetworkConfigMethod>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub method6: Option<NetworkConfigMethod>, pub method6: Option<NetworkConfigMethod>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// IPv4 address with netmask /// IPv4 address with netmask
pub cidr: Option<String>, pub cidr: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// IPv4 gateway /// IPv4 gateway
pub gateway: Option<String>, pub gateway: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// IPv6 address with netmask /// IPv6 address with netmask
pub cidr6: Option<String>, pub cidr6: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// IPv6 gateway /// IPv6 gateway
pub gateway6: Option<String>, pub gateway6: Option<String>,
#[serde(skip_serializing_if="Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
pub options: Vec<String>, pub options: Vec<String>,
#[serde(skip_serializing_if="Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
pub options6: Vec<String>, pub options6: Vec<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comments: Option<String>, pub comments: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comments6: Option<String>, pub comments6: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
/// Maximum Transmission Unit /// Maximum Transmission Unit
pub mtu: Option<u64>, pub mtu: Option<u64>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub bridge_ports: Option<Vec<String>>, pub bridge_ports: Option<Vec<String>>,
/// Enable bridge vlan support. /// Enable bridge vlan support.
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub bridge_vlan_aware: Option<bool>, pub bridge_vlan_aware: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub slaves: Option<Vec<String>>, pub slaves: Option<Vec<String>>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub bond_mode: Option<LinuxBondMode>, pub bond_mode: Option<LinuxBondMode>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "bond-primary")] #[serde(rename = "bond-primary")]
pub bond_primary: Option<String>, pub bond_primary: Option<String>,
pub bond_xmit_hash_policy: Option<BondXmitHashPolicy>, pub bond_xmit_hash_policy: Option<BondXmitHashPolicy>,
@ -281,7 +276,7 @@ pub struct Interface {
impl Interface { impl Interface {
pub fn new(name: String) -> Self { pub fn new(name: String) -> Self {
Self { Self {
name, name,
interface_type: NetworkInterfaceType::Unknown, interface_type: NetworkInterfaceType::Unknown,
autostart: false, autostart: false,

View File

@ -1,42 +1,38 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{ use proxmox_schema::{api, ApiStringFormat, ArraySchema, Schema, StringSchema, Updater};
api, ApiStringFormat, ArraySchema, Schema, StringSchema, Updater,
};
use super::{ use super::{
PROXMOX_SAFE_ID_REGEX, PROXMOX_SAFE_ID_FORMAT, REALM_ID_SCHEMA, PROXMOX_SAFE_ID_FORMAT, PROXMOX_SAFE_ID_REGEX, REALM_ID_SCHEMA, SINGLE_LINE_COMMENT_SCHEMA,
SINGLE_LINE_COMMENT_SCHEMA,
}; };
pub const OPENID_SCOPE_FORMAT: ApiStringFormat = pub const OPENID_SCOPE_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
pub const OPENID_SCOPE_SCHEMA: Schema = StringSchema::new("OpenID Scope Name.") pub const OPENID_SCOPE_SCHEMA: Schema = StringSchema::new("OpenID Scope Name.")
.format(&OPENID_SCOPE_FORMAT) .format(&OPENID_SCOPE_FORMAT)
.schema(); .schema();
pub const OPENID_SCOPE_ARRAY_SCHEMA: Schema = ArraySchema::new( pub const OPENID_SCOPE_ARRAY_SCHEMA: Schema =
"Array of OpenId Scopes.", &OPENID_SCOPE_SCHEMA).schema(); ArraySchema::new("Array of OpenId Scopes.", &OPENID_SCOPE_SCHEMA).schema();
pub const OPENID_SCOPE_LIST_FORMAT: ApiStringFormat = pub const OPENID_SCOPE_LIST_FORMAT: ApiStringFormat =
ApiStringFormat::PropertyString(&OPENID_SCOPE_ARRAY_SCHEMA); ApiStringFormat::PropertyString(&OPENID_SCOPE_ARRAY_SCHEMA);
pub const OPENID_DEFAILT_SCOPE_LIST: &'static str = "email profile"; pub const OPENID_DEFAILT_SCOPE_LIST: &str = "email profile";
pub const OPENID_SCOPE_LIST_SCHEMA: Schema = StringSchema::new("OpenID Scope List") pub const OPENID_SCOPE_LIST_SCHEMA: Schema = StringSchema::new("OpenID Scope List")
.format(&OPENID_SCOPE_LIST_FORMAT) .format(&OPENID_SCOPE_LIST_FORMAT)
.default(OPENID_DEFAILT_SCOPE_LIST) .default(OPENID_DEFAILT_SCOPE_LIST)
.schema(); .schema();
pub const OPENID_ACR_FORMAT: ApiStringFormat = pub const OPENID_ACR_FORMAT: ApiStringFormat = ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
pub const OPENID_ACR_SCHEMA: Schema = StringSchema::new("OpenID Authentication Context Class Reference.") pub const OPENID_ACR_SCHEMA: Schema =
.format(&OPENID_SCOPE_FORMAT) StringSchema::new("OpenID Authentication Context Class Reference.")
.schema(); .format(&OPENID_SCOPE_FORMAT)
.schema();
pub const OPENID_ACR_ARRAY_SCHEMA: Schema = ArraySchema::new( pub const OPENID_ACR_ARRAY_SCHEMA: Schema =
"Array of OpenId ACRs.", &OPENID_ACR_SCHEMA).schema(); ArraySchema::new("Array of OpenId ACRs.", &OPENID_ACR_SCHEMA).schema();
pub const OPENID_ACR_LIST_FORMAT: ApiStringFormat = pub const OPENID_ACR_LIST_FORMAT: ApiStringFormat =
ApiStringFormat::PropertyString(&OPENID_ACR_ARRAY_SCHEMA); ApiStringFormat::PropertyString(&OPENID_ACR_ARRAY_SCHEMA);
@ -50,10 +46,12 @@ pub const OPENID_USERNAME_CLAIM_SCHEMA: Schema = StringSchema::new(
is up to the identity provider to guarantee the uniqueness. The \ is up to the identity provider to guarantee the uniqueness. The \
OpenID specification only guarantees that Subject ('sub') is \ OpenID specification only guarantees that Subject ('sub') is \
unique. Also make sure that the user is not allowed to change that \ unique. Also make sure that the user is not allowed to change that \
attribute by himself!") attribute by himself!",
.max_length(64) )
.min_length(1) .max_length(64)
.format(&PROXMOX_SAFE_ID_FORMAT) .schema(); .min_length(1)
.format(&PROXMOX_SAFE_ID_FORMAT)
.schema();
#[api( #[api(
properties: { properties: {
@ -92,7 +90,7 @@ pub const OPENID_USERNAME_CLAIM_SCHEMA: Schema = StringSchema::new(
}, },
)] )]
#[derive(Serialize, Deserialize, Updater)] #[derive(Serialize, Deserialize, Updater)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// OpenID configuration properties. /// OpenID configuration properties.
pub struct OpenIdRealmConfig { pub struct OpenIdRealmConfig {
#[updater(skip)] #[updater(skip)]
@ -101,21 +99,21 @@ pub struct OpenIdRealmConfig {
pub issuer_url: String, pub issuer_url: String,
/// OpenID Client ID /// OpenID Client ID
pub client_id: String, pub client_id: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub scopes: Option<String>, pub scopes: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub acr_values: Option<String>, pub acr_values: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub prompt: Option<String>, pub prompt: Option<String>,
/// OpenID Client Key /// OpenID Client Key
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub client_key: Option<String>, pub client_key: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
/// Automatically create users if they do not exist. /// Automatically create users if they do not exist.
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub autocreate: Option<bool>, pub autocreate: Option<bool>,
#[updater(skip)] #[updater(skip)]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub username_claim: Option<String>, pub username_claim: Option<String>,
} }

View File

@ -3,17 +3,19 @@ use serde::{Deserialize, Serialize};
use super::*; use super::*;
use proxmox_schema::*; use proxmox_schema::*;
pub const REMOTE_PASSWORD_SCHEMA: Schema = StringSchema::new("Password or auth token for remote host.") pub const REMOTE_PASSWORD_SCHEMA: Schema =
.format(&PASSWORD_FORMAT) StringSchema::new("Password or auth token for remote host.")
.min_length(1) .format(&PASSWORD_FORMAT)
.max_length(1024) .min_length(1)
.schema(); .max_length(1024)
.schema();
pub const REMOTE_PASSWORD_BASE64_SCHEMA: Schema = StringSchema::new("Password or auth token for remote host (stored as base64 string).") pub const REMOTE_PASSWORD_BASE64_SCHEMA: Schema =
.format(&PASSWORD_FORMAT) StringSchema::new("Password or auth token for remote host (stored as base64 string).")
.min_length(1) .format(&PASSWORD_FORMAT)
.max_length(1024) .min_length(1)
.schema(); .max_length(1024)
.schema();
pub const REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.") pub const REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.")
.format(&PROXMOX_SAFE_ID_FORMAT) .format(&PROXMOX_SAFE_ID_FORMAT)
@ -21,7 +23,6 @@ pub const REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.")
.max_length(32) .max_length(32)
.schema(); .schema();
#[api( #[api(
properties: { properties: {
comment: { comment: {
@ -45,17 +46,17 @@ pub const REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.")
}, },
}, },
)] )]
#[derive(Serialize,Deserialize,Updater)] #[derive(Serialize, Deserialize, Updater)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Remote configuration properties. /// Remote configuration properties.
pub struct RemoteConfig { pub struct RemoteConfig {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
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 auth_id: Authid, pub auth_id: Authid,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub fingerprint: Option<String>, pub fingerprint: Option<String>,
} }
@ -72,15 +73,34 @@ pub struct RemoteConfig {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Remote properties. /// Remote properties.
pub struct Remote { pub struct Remote {
pub name: String, pub name: String,
// Note: The stored password is base64 encoded // Note: The stored password is base64 encoded
#[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_serde::string_as_base64")]
pub password: String, pub password: String,
#[serde(flatten)] #[serde(flatten)]
pub config: RemoteConfig, pub config: RemoteConfig,
} }
#[api(
properties: {
name: {
schema: REMOTE_ID_SCHEMA,
},
config: {
type: RemoteConfig,
},
},
)]
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
/// Remote properties.
pub struct RemoteWithoutPassword {
pub name: String,
#[serde(flatten)]
pub config: RemoteConfig,
}

View File

@ -3,23 +3,23 @@ use ::serde::{Deserialize, Serialize};
use proxmox_schema::api; use proxmox_schema::api;
#[api()] #[api()]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Optional Device Identification Attributes /// Optional Device Identification Attributes
pub struct OptionalDeviceIdentification { pub struct OptionalDeviceIdentification {
/// Vendor (autodetected) /// Vendor (autodetected)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub vendor: Option<String>, pub vendor: Option<String>,
/// Model (autodetected) /// Model (autodetected)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>, pub model: Option<String>,
/// Serial number (autodetected) /// Serial number (autodetected)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub serial: Option<String>, pub serial: Option<String>,
} }
#[api()] #[api()]
#[derive(Debug,Serialize,Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Kind of device /// Kind of device
pub enum DeviceKind { pub enum DeviceKind {
@ -36,7 +36,7 @@ pub enum DeviceKind {
}, },
}, },
)] )]
#[derive(Debug,Serialize,Deserialize)] #[derive(Debug, Serialize, Deserialize)]
/// Tape device information /// Tape device information
pub struct TapeDeviceInfo { pub struct TapeDeviceInfo {
pub kind: DeviceKind, pub kind: DeviceKind,

View File

@ -4,13 +4,9 @@ use std::convert::TryFrom;
use anyhow::{bail, Error}; use anyhow::{bail, Error};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{api, Schema, IntegerSchema, StringSchema, Updater}; use proxmox_schema::{api, IntegerSchema, Schema, StringSchema, Updater};
use crate::{ use crate::{OptionalDeviceIdentification, CHANGER_NAME_SCHEMA, PROXMOX_SAFE_ID_FORMAT};
PROXMOX_SAFE_ID_FORMAT,
CHANGER_NAME_SCHEMA,
OptionalDeviceIdentification,
};
pub const DRIVE_NAME_SCHEMA: Schema = StringSchema::new("Drive Identifier.") pub const DRIVE_NAME_SCHEMA: Schema = StringSchema::new("Drive Identifier.")
.format(&PROXMOX_SAFE_ID_FORMAT) .format(&PROXMOX_SAFE_ID_FORMAT)
@ -18,16 +14,15 @@ pub const DRIVE_NAME_SCHEMA: Schema = StringSchema::new("Drive Identifier.")
.max_length(32) .max_length(32)
.schema(); .schema();
pub const LTO_DRIVE_PATH_SCHEMA: Schema = StringSchema::new( pub const LTO_DRIVE_PATH_SCHEMA: Schema =
"The path to a LTO SCSI-generic tape device (i.e. '/dev/sg0')") StringSchema::new("The path to a LTO SCSI-generic tape device (i.e. '/dev/sg0')").schema();
.schema();
pub const CHANGER_DRIVENUM_SCHEMA: Schema = IntegerSchema::new( pub const CHANGER_DRIVENUM_SCHEMA: Schema =
"Associated changer drive number (requires option changer)") IntegerSchema::new("Associated changer drive number (requires option changer)")
.minimum(0) .minimum(0)
.maximum(255) .maximum(255)
.default(0) .default(0)
.schema(); .schema();
#[api( #[api(
properties: { properties: {
@ -36,7 +31,7 @@ pub const CHANGER_DRIVENUM_SCHEMA: Schema = IntegerSchema::new(
} }
} }
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
/// Simulate tape drives (only for test and debug) /// Simulate tape drives (only for test and debug)
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct VirtualTapeDrive { pub struct VirtualTapeDrive {
@ -44,7 +39,7 @@ pub struct VirtualTapeDrive {
/// Path to directory /// Path to directory
pub path: String, pub path: String,
/// Virtual tape size /// Virtual tape size
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_size: Option<usize>, pub max_size: Option<usize>,
} }
@ -66,16 +61,16 @@ pub struct VirtualTapeDrive {
}, },
} }
)] )]
#[derive(Serialize,Deserialize,Updater)] #[derive(Serialize, Deserialize, Updater)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Lto SCSI tape driver /// Lto SCSI tape driver
pub struct LtoTapeDrive { pub struct LtoTapeDrive {
#[updater(skip)] #[updater(skip)]
pub name: String, pub name: String,
pub path: String, pub path: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub changer: Option<String>, pub changer: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub changer_drivenum: Option<u64>, pub changer_drivenum: Option<u64>,
} }
@ -89,7 +84,7 @@ pub struct LtoTapeDrive {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Drive list entry /// Drive list entry
pub struct DriveListEntry { pub struct DriveListEntry {
@ -98,12 +93,12 @@ pub struct DriveListEntry {
#[serde(flatten)] #[serde(flatten)]
pub info: OptionalDeviceIdentification, pub info: OptionalDeviceIdentification,
/// the state of the drive if locked /// the state of the drive if locked
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>, pub state: Option<String>,
} }
#[api()] #[api()]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
/// Medium auxiliary memory attributes (MAM) /// Medium auxiliary memory attributes (MAM)
pub struct MamAttribute { pub struct MamAttribute {
/// Attribute id /// Attribute id
@ -115,7 +110,7 @@ pub struct MamAttribute {
} }
#[api()] #[api()]
#[derive(Serialize,Deserialize,Copy,Clone,Debug)] #[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum TapeDensity { pub enum TapeDensity {
/// Unknown (no media loaded) /// Unknown (no media loaded)
Unknown, Unknown,
@ -168,7 +163,7 @@ impl TryFrom<u8> for TapeDensity {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Drive/Media status for Lto SCSI drives. /// Drive/Media status for Lto SCSI drives.
/// ///
@ -190,35 +185,35 @@ pub struct LtoDriveAndMediaStatus {
/// Tape density /// Tape density
pub density: TapeDensity, pub density: TapeDensity,
/// Media is write protected /// Media is write protected
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub write_protect: Option<bool>, pub write_protect: Option<bool>,
/// Tape Alert Flags /// Tape Alert Flags
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub alert_flags: Option<String>, pub alert_flags: Option<String>,
/// Current file number /// Current file number
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub file_number: Option<u64>, pub file_number: Option<u64>,
/// Current block number /// Current block number
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub block_number: Option<u64>, pub block_number: Option<u64>,
/// Medium Manufacture Date (epoch) /// Medium Manufacture Date (epoch)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub manufactured: Option<i64>, pub manufactured: Option<i64>,
/// Total Bytes Read in Medium Life /// Total Bytes Read in Medium Life
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub bytes_read: Option<u64>, pub bytes_read: Option<u64>,
/// Total Bytes Written in Medium Life /// Total Bytes Written in Medium Life
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub bytes_written: Option<u64>, pub bytes_written: Option<u64>,
/// Number of mounts for the current volume (i.e., Thread Count) /// Number of mounts for the current volume (i.e., Thread Count)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub volume_mounts: Option<u64>, pub volume_mounts: Option<u64>,
/// Count of the total number of times the medium has passed over /// Count of the total number of times the medium has passed over
/// the head. /// the head.
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub medium_passes: Option<u64>, pub medium_passes: Option<u64>,
/// Estimated tape wearout factor (assuming max. 16000 end-to-end passes) /// Estimated tape wearout factor (assuming max. 16000 end-to-end passes)
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub medium_wearout: Option<f64>, pub medium_wearout: Option<f64>,
} }

View File

@ -3,19 +3,15 @@ use ::serde::{Deserialize, Serialize};
use proxmox_schema::*; use proxmox_schema::*;
use proxmox_uuid::Uuid; use proxmox_uuid::Uuid;
use crate::{ use crate::{MediaLocation, MediaStatus, UUID_FORMAT};
UUID_FORMAT,
MediaStatus,
MediaLocation,
};
pub const MEDIA_SET_UUID_SCHEMA: Schema = pub const MEDIA_SET_UUID_SCHEMA: Schema = StringSchema::new(
StringSchema::new("MediaSet Uuid (We use the all-zero Uuid to reseve an empty media for a specific pool).") "MediaSet Uuid (We use the all-zero Uuid to reseve an empty media for a specific pool).",
.format(&UUID_FORMAT) )
.schema(); .format(&UUID_FORMAT)
.schema();
pub const MEDIA_UUID_SCHEMA: Schema = pub const MEDIA_UUID_SCHEMA: Schema = StringSchema::new("Media Uuid.")
StringSchema::new("Media Uuid.")
.format(&UUID_FORMAT) .format(&UUID_FORMAT)
.schema(); .schema();
@ -26,7 +22,7 @@ pub const MEDIA_UUID_SCHEMA: Schema =
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Media Set list entry /// Media Set list entry
pub struct MediaSetListEntry { pub struct MediaSetListEntry {
@ -56,7 +52,7 @@ pub struct MediaSetListEntry {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Media list entry /// Media list entry
pub struct MediaListEntry { pub struct MediaListEntry {
@ -72,18 +68,18 @@ pub struct MediaListEntry {
/// Catalog status OK /// Catalog status OK
pub catalog: bool, pub catalog: bool,
/// Media set name /// Media set name
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub media_set_name: Option<String>, pub media_set_name: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub media_set_uuid: Option<Uuid>, pub media_set_uuid: Option<Uuid>,
/// Media set seq_nr /// Media set seq_nr
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub seq_nr: Option<u64>, pub seq_nr: Option<u64>,
/// MediaSet creation time stamp /// MediaSet creation time stamp
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub media_set_ctime: Option<i64>, pub media_set_ctime: Option<i64>,
/// Media Pool /// Media Pool
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub pool: Option<String>, pub pool: Option<String>,
} }
@ -98,7 +94,7 @@ pub struct MediaListEntry {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Media label info /// Media label info
pub struct MediaIdFlat { pub struct MediaIdFlat {
@ -110,18 +106,18 @@ pub struct MediaIdFlat {
pub ctime: i64, pub ctime: i64,
// All MediaSet properties are optional here // All MediaSet properties are optional here
/// MediaSet Pool /// MediaSet Pool
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub pool: Option<String>, pub pool: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub media_set_uuid: Option<Uuid>, pub media_set_uuid: Option<Uuid>,
/// MediaSet media sequence number /// MediaSet media sequence number
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub seq_nr: Option<u64>, pub seq_nr: Option<u64>,
/// MediaSet Creation time stamp /// MediaSet Creation time stamp
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub media_set_ctime: Option<i64>, pub media_set_ctime: Option<i64>,
/// Encryption key fingerprint /// Encryption key fingerprint
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub encryption_key_fingerprint: Option<String>, pub encryption_key_fingerprint: Option<String>,
} }
@ -133,7 +129,7 @@ pub struct MediaIdFlat {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Label with optional Uuid /// Label with optional Uuid
pub struct LabelUuidMap { pub struct LabelUuidMap {
@ -153,7 +149,7 @@ pub struct LabelUuidMap {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Media content list entry /// Media content list entry
pub struct MediaContentEntry { pub struct MediaContentEntry {

View File

@ -1,6 +1,6 @@
use anyhow::{bail, Error}; use anyhow::{bail, Error};
use proxmox_schema::{parse_simple_value, ApiStringFormat, Schema, StringSchema}; use proxmox_schema::{ApiStringFormat, Schema, StringSchema};
use crate::{CHANGER_NAME_SCHEMA, PROXMOX_SAFE_ID_FORMAT}; use crate::{CHANGER_NAME_SCHEMA, PROXMOX_SAFE_ID_FORMAT};
@ -22,8 +22,8 @@ pub enum MediaLocation {
Vault(String), Vault(String),
} }
proxmox::forward_deserialize_to_from_str!(MediaLocation); proxmox_serde::forward_deserialize_to_from_str!(MediaLocation);
proxmox::forward_serialize_to_display!(MediaLocation); proxmox_serde::forward_serialize_to_display!(MediaLocation);
impl proxmox_schema::ApiType for MediaLocation { impl proxmox_schema::ApiType for MediaLocation {
const API_SCHEMA: Schema = StringSchema::new( const API_SCHEMA: Schema = StringSchema::new(
@ -33,10 +33,10 @@ impl proxmox_schema::ApiType for MediaLocation {
let location: MediaLocation = text.parse()?; let location: MediaLocation = text.parse()?;
match location { match location {
MediaLocation::Online(ref changer) => { MediaLocation::Online(ref changer) => {
parse_simple_value(changer, &CHANGER_NAME_SCHEMA)?; CHANGER_NAME_SCHEMA.parse_simple_value(changer)?;
} }
MediaLocation::Vault(ref vault) => { MediaLocation::Vault(ref vault) => {
parse_simple_value(vault, &VAULT_NAME_SCHEMA)?; VAULT_NAME_SCHEMA.parse_simple_value(vault)?;
} }
MediaLocation::Offline => { /* OK */ } MediaLocation::Offline => { /* OK */ }
} }

View File

@ -9,14 +9,12 @@ use std::str::FromStr;
use anyhow::Error; use anyhow::Error;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{api, Schema, StringSchema, ApiStringFormat, Updater}; use proxmox_schema::{api, ApiStringFormat, Schema, StringSchema, Updater};
use proxmox_time::{parse_calendar_event, parse_time_span, CalendarEvent, TimeSpan}; use proxmox_time::{CalendarEvent, TimeSpan};
use crate::{ use crate::{
PROXMOX_SAFE_ID_FORMAT, PROXMOX_SAFE_ID_FORMAT, SINGLE_LINE_COMMENT_FORMAT, SINGLE_LINE_COMMENT_SCHEMA,
SINGLE_LINE_COMMENT_FORMAT,
SINGLE_LINE_COMMENT_SCHEMA,
TAPE_ENCRYPTION_KEY_FINGERPRINT_SCHEMA, TAPE_ENCRYPTION_KEY_FINGERPRINT_SCHEMA,
}; };
@ -27,19 +25,22 @@ pub const MEDIA_POOL_NAME_SCHEMA: Schema = StringSchema::new("Media pool name.")
.schema(); .schema();
pub const MEDIA_SET_NAMING_TEMPLATE_SCHEMA: Schema = StringSchema::new( pub const MEDIA_SET_NAMING_TEMPLATE_SCHEMA: Schema = StringSchema::new(
"Media set naming template (may contain strftime() time format specifications).") "Media set naming template (may contain strftime() time format specifications).",
.format(&SINGLE_LINE_COMMENT_FORMAT) )
.min_length(2) .format(&SINGLE_LINE_COMMENT_FORMAT)
.max_length(64) .min_length(2)
.schema(); .max_length(64)
.schema();
pub const MEDIA_SET_ALLOCATION_POLICY_FORMAT: ApiStringFormat = pub const MEDIA_SET_ALLOCATION_POLICY_FORMAT: ApiStringFormat = ApiStringFormat::VerifyFn(|s| {
ApiStringFormat::VerifyFn(|s| { MediaSetPolicy::from_str(s)?; Ok(()) }); MediaSetPolicy::from_str(s)?;
Ok(())
});
pub const MEDIA_SET_ALLOCATION_POLICY_SCHEMA: Schema = StringSchema::new( pub const MEDIA_SET_ALLOCATION_POLICY_SCHEMA: Schema =
"Media set allocation policy ('continue', 'always', or a calendar event).") StringSchema::new("Media set allocation policy ('continue', 'always', or a calendar event).")
.format(&MEDIA_SET_ALLOCATION_POLICY_FORMAT) .format(&MEDIA_SET_ALLOCATION_POLICY_FORMAT)
.schema(); .schema();
/// Media set allocation policy /// Media set allocation policy
pub enum MediaSetPolicy { pub enum MediaSetPolicy {
@ -62,19 +63,21 @@ impl std::str::FromStr for MediaSetPolicy {
return Ok(MediaSetPolicy::AlwaysCreate); return Ok(MediaSetPolicy::AlwaysCreate);
} }
let event = parse_calendar_event(s)?; let event = s.parse()?;
Ok(MediaSetPolicy::CreateAt(event)) Ok(MediaSetPolicy::CreateAt(event))
} }
} }
pub const MEDIA_RETENTION_POLICY_FORMAT: ApiStringFormat = pub const MEDIA_RETENTION_POLICY_FORMAT: ApiStringFormat = ApiStringFormat::VerifyFn(|s| {
ApiStringFormat::VerifyFn(|s| { RetentionPolicy::from_str(s)?; Ok(()) }); RetentionPolicy::from_str(s)?;
Ok(())
});
pub const MEDIA_RETENTION_POLICY_SCHEMA: Schema = StringSchema::new( pub const MEDIA_RETENTION_POLICY_SCHEMA: Schema =
"Media retention policy ('overwrite', 'keep', or time span).") StringSchema::new("Media retention policy ('overwrite', 'keep', or time span).")
.format(&MEDIA_RETENTION_POLICY_FORMAT) .format(&MEDIA_RETENTION_POLICY_FORMAT)
.schema(); .schema();
/// Media retention Policy /// Media retention Policy
pub enum RetentionPolicy { pub enum RetentionPolicy {
@ -97,7 +100,7 @@ impl std::str::FromStr for RetentionPolicy {
return Ok(RetentionPolicy::KeepForever); return Ok(RetentionPolicy::KeepForever);
} }
let time_span = parse_time_span(s)?; let time_span = s.parse()?;
Ok(RetentionPolicy::ProtectFor(time_span)) Ok(RetentionPolicy::ProtectFor(time_span))
} }
@ -130,29 +133,29 @@ impl std::str::FromStr for RetentionPolicy {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize,Updater)] #[derive(Serialize, Deserialize, Updater)]
/// Media pool configuration /// Media pool configuration
pub struct MediaPoolConfig { pub struct MediaPoolConfig {
/// The pool name /// The pool name
#[updater(skip)] #[updater(skip)]
pub name: String, pub name: String,
/// Media Set allocation policy /// Media Set allocation policy
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub allocation: Option<String>, pub allocation: Option<String>,
/// Media retention policy /// Media retention policy
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub retention: Option<String>, pub retention: Option<String>,
/// Media set naming template (default "%c") /// Media set naming template (default "%c")
/// ///
/// The template is UTF8 text, and can include strftime time /// The template is UTF8 text, and can include strftime time
/// format specifications. /// format specifications.
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>, pub template: Option<String>,
/// Encryption key fingerprint /// Encryption key fingerprint
/// ///
/// If set, encrypt all data using the specified key. /// If set, encrypt all data using the specified key.
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub encrypt: Option<String>, pub encrypt: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
} }

View File

@ -24,31 +24,28 @@ pub use media::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{api, const_regex, Schema, StringSchema, ApiStringFormat}; use proxmox_schema::{api, const_regex, ApiStringFormat, Schema, StringSchema};
use proxmox_uuid::Uuid; use proxmox_uuid::Uuid;
use crate::{ use crate::{BackupType, BACKUP_ID_SCHEMA, FINGERPRINT_SHA256_FORMAT};
FINGERPRINT_SHA256_FORMAT, BACKUP_ID_SCHEMA, BACKUP_TYPE_SCHEMA,
};
const_regex!{ const_regex! {
pub TAPE_RESTORE_SNAPSHOT_REGEX = concat!(r"^", PROXMOX_SAFE_ID_REGEX_STR!(), r":", SNAPSHOT_PATH_REGEX_STR!(), r"$"); pub TAPE_RESTORE_SNAPSHOT_REGEX = concat!(r"^", PROXMOX_SAFE_ID_REGEX_STR!(), r":(:?", BACKUP_NS_PATH_RE!(),")?", SNAPSHOT_PATH_REGEX_STR!(), r"$");
} }
pub const TAPE_RESTORE_SNAPSHOT_FORMAT: ApiStringFormat = pub const TAPE_RESTORE_SNAPSHOT_FORMAT: ApiStringFormat =
ApiStringFormat::Pattern(&TAPE_RESTORE_SNAPSHOT_REGEX); ApiStringFormat::Pattern(&TAPE_RESTORE_SNAPSHOT_REGEX);
pub const TAPE_ENCRYPTION_KEY_FINGERPRINT_SCHEMA: Schema = StringSchema::new( pub const TAPE_ENCRYPTION_KEY_FINGERPRINT_SCHEMA: Schema =
"Tape encryption key fingerprint (sha256)." StringSchema::new("Tape encryption key fingerprint (sha256).")
) .format(&FINGERPRINT_SHA256_FORMAT)
.format(&FINGERPRINT_SHA256_FORMAT) .schema();
.schema();
pub const TAPE_RESTORE_SNAPSHOT_SCHEMA: Schema = StringSchema::new( pub const TAPE_RESTORE_SNAPSHOT_SCHEMA: Schema =
"A snapshot in the format: 'store:type/id/time") StringSchema::new("A snapshot in the format: 'store:[ns/namespace/...]type/id/time")
.format(&TAPE_RESTORE_SNAPSHOT_FORMAT) .format(&TAPE_RESTORE_SNAPSHOT_FORMAT)
.type_text("store:type/id/time") .type_text("store:[ns/namespace/...]type/id/time")
.schema(); .schema();
#[api( #[api(
properties: { properties: {
@ -69,7 +66,7 @@ pub const TAPE_RESTORE_SNAPSHOT_SCHEMA: Schema = StringSchema::new(
optional: true, optional: true,
}, },
"backup-type": { "backup-type": {
schema: BACKUP_TYPE_SCHEMA, type: BackupType,
optional: true, optional: true,
}, },
"backup-id": { "backup-id": {
@ -78,14 +75,14 @@ pub const TAPE_RESTORE_SNAPSHOT_SCHEMA: Schema = StringSchema::new(
}, },
}, },
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// Content list filter parameters /// Content list filter parameters
pub struct MediaContentListFilter { pub struct MediaContentListFilter {
pub pool: Option<String>, pub pool: Option<String>,
pub label_text: Option<String>, pub label_text: Option<String>,
pub media: Option<Uuid>, pub media: Option<Uuid>,
pub media_set: Option<Uuid>, pub media_set: Option<Uuid>,
pub backup_type: Option<String>, pub backup_type: Option<BackupType>,
pub backup_id: Option<String>, pub backup_id: Option<String>,
} }

View File

@ -1,16 +1,16 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{api, Schema, IntegerSchema, StringSchema, Updater}; use proxmox_schema::{api, IntegerSchema, Schema, StringSchema, Updater};
use crate::{ use crate::{
HumanByte, CIDR_SCHEMA, DAILY_DURATION_FORMAT, HumanByte, CIDR_SCHEMA, DAILY_DURATION_FORMAT, PROXMOX_SAFE_ID_FORMAT,
PROXMOX_SAFE_ID_FORMAT, SINGLE_LINE_COMMENT_SCHEMA, SINGLE_LINE_COMMENT_SCHEMA,
}; };
pub const TRAFFIC_CONTROL_TIMEFRAME_SCHEMA: Schema = StringSchema::new( pub const TRAFFIC_CONTROL_TIMEFRAME_SCHEMA: Schema =
"Timeframe to specify when the rule is actice.") StringSchema::new("Timeframe to specify when the rule is actice.")
.format(&DAILY_DURATION_FORMAT) .format(&DAILY_DURATION_FORMAT)
.schema(); .schema();
pub const TRAFFIC_CONTROL_ID_SCHEMA: Schema = StringSchema::new("Rule ID.") pub const TRAFFIC_CONTROL_ID_SCHEMA: Schema = StringSchema::new("Rule ID.")
.format(&PROXMOX_SAFE_ID_FORMAT) .format(&PROXMOX_SAFE_ID_FORMAT)
@ -18,15 +18,15 @@ pub const TRAFFIC_CONTROL_ID_SCHEMA: Schema = StringSchema::new("Rule ID.")
.max_length(32) .max_length(32)
.schema(); .schema();
pub const TRAFFIC_CONTROL_RATE_SCHEMA: Schema = IntegerSchema::new( pub const TRAFFIC_CONTROL_RATE_SCHEMA: Schema =
"Rate limit (for Token bucket filter) in bytes/second.") IntegerSchema::new("Rate limit (for Token bucket filter) in bytes/second.")
.minimum(100_000) .minimum(100_000)
.schema(); .schema();
pub const TRAFFIC_CONTROL_BURST_SCHEMA: Schema = IntegerSchema::new( pub const TRAFFIC_CONTROL_BURST_SCHEMA: Schema =
"Size of the token bucket (for Token bucket filter) in bytes.") IntegerSchema::new("Size of the token bucket (for Token bucket filter) in bytes.")
.minimum(1000) .minimum(1000)
.schema(); .schema();
#[api( #[api(
properties: { properties: {
@ -48,17 +48,17 @@ pub const TRAFFIC_CONTROL_BURST_SCHEMA: Schema = IntegerSchema::new(
}, },
}, },
)] )]
#[derive(Serialize,Deserialize,Default,Clone,Updater)] #[derive(Serialize, Deserialize, Default, Clone, Updater)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Rate Limit Configuration /// Rate Limit Configuration
pub struct RateLimitConfig { pub struct RateLimitConfig {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub rate_in: Option<HumanByte>, pub rate_in: Option<HumanByte>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub burst_in: Option<HumanByte>, pub burst_in: Option<HumanByte>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub rate_out: Option<HumanByte>, pub rate_out: Option<HumanByte>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub burst_out: Option<HumanByte>, pub burst_out: Option<HumanByte>,
} }
@ -100,13 +100,13 @@ impl RateLimitConfig {
}, },
}, },
)] )]
#[derive(Serialize,Deserialize, Updater)] #[derive(Serialize, Deserialize, Updater)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
/// Traffic control rule /// Traffic control rule
pub struct TrafficControlRule { pub struct TrafficControlRule {
#[updater(skip)] #[updater(skip)]
pub name: String, pub name: String,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
/// Rule applies to Source IPs within this networks /// Rule applies to Source IPs within this networks
pub network: Vec<String>, pub network: Vec<String>,
@ -117,6 +117,6 @@ pub struct TrafficControlRule {
// #[serde(skip_serializing_if="Option::is_none")] // #[serde(skip_serializing_if="Option::is_none")]
// pub shared: Option<bool>, // pub shared: Option<bool>,
/// Enable the rule at specific times /// Enable the rule at specific times
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub timeframe: Option<Vec<String>>, pub timeframe: Option<Vec<String>>,
} }

View File

@ -1,22 +1,22 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use proxmox_schema::{ use proxmox_schema::{api, BooleanSchema, IntegerSchema, Schema, StringSchema, Updater};
api, BooleanSchema, IntegerSchema, Schema, StringSchema, Updater,
};
use super::{SINGLE_LINE_COMMENT_FORMAT, SINGLE_LINE_COMMENT_SCHEMA};
use super::userid::{Authid, Userid, PROXMOX_TOKEN_ID_SCHEMA}; use super::userid::{Authid, Userid, PROXMOX_TOKEN_ID_SCHEMA};
use super::{SINGLE_LINE_COMMENT_FORMAT, SINGLE_LINE_COMMENT_SCHEMA};
pub const ENABLE_USER_SCHEMA: Schema = BooleanSchema::new( pub const ENABLE_USER_SCHEMA: Schema = BooleanSchema::new(
"Enable the account (default). You can set this to '0' to disable the account.") "Enable the account (default). You can set this to '0' to disable the account.",
.default(true) )
.schema(); .default(true)
.schema();
pub const EXPIRE_USER_SCHEMA: Schema = IntegerSchema::new( pub const EXPIRE_USER_SCHEMA: Schema = IntegerSchema::new(
"Account expiration date (seconds since epoch). '0' means no expiration date.") "Account expiration date (seconds since epoch). '0' means no expiration date.",
.default(0) )
.minimum(0) .default(0)
.schema(); .minimum(0)
.schema();
pub const FIRST_NAME_SCHEMA: Schema = StringSchema::new("First name.") pub const FIRST_NAME_SCHEMA: Schema = StringSchema::new("First name.")
.format(&SINGLE_LINE_COMMENT_FORMAT) .format(&SINGLE_LINE_COMMENT_FORMAT)
@ -75,23 +75,23 @@ pub const EMAIL_SCHEMA: Schema = StringSchema::new("E-Mail Address.")
}, },
} }
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
/// User properties with added list of ApiTokens /// User properties with added list of ApiTokens
pub struct UserWithTokens { pub struct UserWithTokens {
pub userid: Userid, pub userid: Userid,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub enable: Option<bool>, pub enable: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub expire: Option<i64>, pub expire: Option<i64>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub firstname: Option<String>, pub firstname: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
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", default)] #[serde(skip_serializing_if = "Vec::is_empty", default)]
pub tokens: Vec<ApiToken>, pub tokens: Vec<ApiToken>,
} }
@ -114,15 +114,15 @@ pub struct UserWithTokens {
}, },
} }
)] )]
#[derive(Serialize,Deserialize)] #[derive(Serialize, Deserialize)]
/// ApiToken properties. /// ApiToken properties.
pub struct ApiToken { pub struct ApiToken {
pub tokenid: Authid, pub tokenid: Authid,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub enable: Option<bool>, pub enable: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub expire: Option<i64>, pub expire: Option<i64>,
} }
@ -132,7 +132,7 @@ impl ApiToken {
return false; return false;
} }
if let Some(expire) = self.expire { if let Some(expire) = self.expire {
let now = proxmox_time::epoch_i64(); let now = proxmox_time::epoch_i64();
if expire > 0 && expire <= now { if expire > 0 && expire <= now {
return false; return false;
} }
@ -172,22 +172,22 @@ impl ApiToken {
}, },
} }
)] )]
#[derive(Serialize,Deserialize,Updater)] #[derive(Serialize, Deserialize, Updater)]
/// User properties. /// User properties.
pub struct User { pub struct User {
#[updater(skip)] #[updater(skip)]
pub userid: Userid, pub userid: Userid,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>, pub comment: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub enable: Option<bool>, pub enable: Option<bool>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub expire: Option<i64>, pub expire: Option<i64>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub firstname: Option<String>, pub firstname: Option<String>,
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
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>,
} }
@ -197,7 +197,7 @@ impl User {
return false; return false;
} }
if let Some(expire) = self.expire { if let Some(expire) = self.expire {
let now = proxmox_time::epoch_i64(); let now = proxmox_time::epoch_i64();
if expire > 0 && expire <= now { if expire > 0 && expire <= now {
return false; return false;
} }

View File

@ -39,15 +39,35 @@ use proxmox_schema::{
// slash is not allowed because it is used as pve API delimiter // slash is not allowed because it is used as pve API delimiter
// also see "man useradd" // also see "man useradd"
#[macro_export] #[macro_export]
macro_rules! USER_NAME_REGEX_STR { () => (r"(?:[^\s:/[:cntrl:]]+)") } macro_rules! USER_NAME_REGEX_STR {
() => {
r"(?:[^\s:/[:cntrl:]]+)"
};
}
#[macro_export] #[macro_export]
macro_rules! GROUP_NAME_REGEX_STR { () => (USER_NAME_REGEX_STR!()) } macro_rules! GROUP_NAME_REGEX_STR {
() => {
USER_NAME_REGEX_STR!()
};
}
#[macro_export] #[macro_export]
macro_rules! TOKEN_NAME_REGEX_STR { () => (PROXMOX_SAFE_ID_REGEX_STR!()) } macro_rules! TOKEN_NAME_REGEX_STR {
() => {
PROXMOX_SAFE_ID_REGEX_STR!()
};
}
#[macro_export] #[macro_export]
macro_rules! USER_ID_REGEX_STR { () => (concat!(USER_NAME_REGEX_STR!(), r"@", PROXMOX_SAFE_ID_REGEX_STR!())) } macro_rules! USER_ID_REGEX_STR {
() => {
concat!(USER_NAME_REGEX_STR!(), r"@", PROXMOX_SAFE_ID_REGEX_STR!())
};
}
#[macro_export] #[macro_export]
macro_rules! APITOKEN_ID_REGEX_STR { () => (concat!(USER_ID_REGEX_STR!() , r"!", TOKEN_NAME_REGEX_STR!())) } macro_rules! APITOKEN_ID_REGEX_STR {
() => {
concat!(USER_ID_REGEX_STR!(), r"!", TOKEN_NAME_REGEX_STR!())
};
}
const_regex! { const_regex! {
pub PROXMOX_USER_NAME_REGEX = concat!(r"^", USER_NAME_REGEX_STR!(), r"$"); pub PROXMOX_USER_NAME_REGEX = concat!(r"^", USER_NAME_REGEX_STR!(), r"$");
@ -101,6 +121,7 @@ pub const PROXMOX_AUTH_REALM_SCHEMA: Schema = PROXMOX_AUTH_REALM_STRING_SCHEMA.s
#[api( #[api(
type: String, type: String,
format: &PROXMOX_USER_NAME_FORMAT, format: &PROXMOX_USER_NAME_FORMAT,
min_length: 1,
)] )]
/// The user name part of a user id. /// The user name part of a user id.
/// ///
@ -237,7 +258,8 @@ impl TryFrom<String> for Realm {
type Error = Error; type Error = Error;
fn try_from(s: String) -> Result<Self, Error> { fn try_from(s: String) -> Result<Self, Error> {
PROXMOX_AUTH_REALM_STRING_SCHEMA.check_constraints(&s) PROXMOX_AUTH_REALM_STRING_SCHEMA
.check_constraints(&s)
.map_err(|_| format_err!("invalid realm"))?; .map_err(|_| format_err!("invalid realm"))?;
Ok(Self(s)) Ok(Self(s))
@ -248,7 +270,8 @@ impl<'a> TryFrom<&'a str> for &'a RealmRef {
type Error = Error; type Error = Error;
fn try_from(s: &'a str) -> Result<&'a RealmRef, Error> { fn try_from(s: &'a str) -> Result<&'a RealmRef, Error> {
PROXMOX_AUTH_REALM_STRING_SCHEMA.check_constraints(s) PROXMOX_AUTH_REALM_STRING_SCHEMA
.check_constraints(s)
.map_err(|_| format_err!("invalid realm"))?; .map_err(|_| format_err!("invalid realm"))?;
Ok(RealmRef::new(s)) Ok(RealmRef::new(s))
@ -304,7 +327,7 @@ impl PartialEq<Realm> for &RealmRef {
/// The token ID part of an API token authentication id. /// The token ID part of an API token authentication id.
/// ///
/// This alone does NOT uniquely identify the API token - use a full `Authid` for such use cases. /// This alone does NOT uniquely identify the API token - use a full `Authid` for such use cases.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] #[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq, Deserialize, Serialize)]
pub struct Tokenname(String); pub struct Tokenname(String);
/// A reference to a token name part of an authentication id. This alone does NOT uniquely identify /// A reference to a token name part of an authentication id. This alone does NOT uniquely identify
@ -397,7 +420,7 @@ impl<'a> TryFrom<&'a str> for &'a TokennameRef {
} }
/// A complete user id consisting of a user name and a realm /// A complete user id consisting of a user name and a realm
#[derive(Clone, Debug, PartialEq, Eq, Hash, UpdaterType)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd, UpdaterType)]
pub struct Userid { pub struct Userid {
data: String, data: String,
name_len: usize, name_len: usize,
@ -481,7 +504,8 @@ impl std::str::FromStr for Userid {
bail!("invalid user name in user id"); bail!("invalid user name in user id");
} }
PROXMOX_AUTH_REALM_STRING_SCHEMA.check_constraints(realm) PROXMOX_AUTH_REALM_STRING_SCHEMA
.check_constraints(realm)
.map_err(|_| format_err!("invalid realm in user id"))?; .map_err(|_| format_err!("invalid realm in user id"))?;
Ok(Self::from((UsernameRef::new(name), RealmRef::new(realm)))) Ok(Self::from((UsernameRef::new(name), RealmRef::new(realm))))
@ -502,7 +526,8 @@ impl TryFrom<String> for Userid {
bail!("invalid user name in user id"); bail!("invalid user name in user id");
} }
PROXMOX_AUTH_REALM_STRING_SCHEMA.check_constraints(&data[(name_len + 1)..]) PROXMOX_AUTH_REALM_STRING_SCHEMA
.check_constraints(&data[(name_len + 1)..])
.map_err(|_| format_err!("invalid realm in user id"))?; .map_err(|_| format_err!("invalid realm in user id"))?;
Ok(Self { data, name_len }) Ok(Self { data, name_len })
@ -528,10 +553,10 @@ impl PartialEq<String> for Userid {
} }
/// A complete authentication id consisting of a user id and an optional token name. /// A complete authentication id consisting of a user id and an optional token name.
#[derive(Clone, Debug, Eq, PartialEq, Hash, UpdaterType)] #[derive(Clone, Debug, Eq, PartialEq, Hash, UpdaterType, Ord, PartialOrd)]
pub struct Authid { pub struct Authid {
user: Userid, user: Userid,
tokenname: Option<Tokenname> tokenname: Option<Tokenname>,
} }
impl ApiType for Authid { impl ApiType for Authid {
@ -556,10 +581,7 @@ impl Authid {
} }
pub fn tokenname(&self) -> Option<&TokennameRef> { pub fn tokenname(&self) -> Option<&TokennameRef> {
match &self.tokenname { self.tokenname.as_deref()
Some(name) => Some(&name),
None => None,
}
} }
/// Get the "root@pam" auth id. /// Get the "root@pam" auth id.
@ -654,7 +676,7 @@ impl TryFrom<String> for Authid {
data.truncate(realm_end); data.truncate(realm_end);
let user:Userid = data.parse()?; let user: Userid = data.parse()?;
Ok(Self { user, tokenname }) Ok(Self { user, tokenname })
} }
@ -681,12 +703,15 @@ fn test_token_id() {
let token_userid = auth_id.user(); let token_userid = auth_id.user();
assert_eq!(&userid, token_userid); assert_eq!(&userid, token_userid);
assert!(auth_id.is_token()); assert!(auth_id.is_token());
assert_eq!(auth_id.tokenname().expect("Token has tokenname").as_str(), TokennameRef::new("bar").as_str()); assert_eq!(
auth_id.tokenname().expect("Token has tokenname").as_str(),
TokennameRef::new("bar").as_str()
);
assert_eq!(auth_id.to_string(), "test@pam!bar".to_string()); assert_eq!(auth_id.to_string(), "test@pam!bar".to_string());
} }
proxmox::forward_deserialize_to_from_str!(Userid); proxmox_serde::forward_deserialize_to_from_str!(Userid);
proxmox::forward_serialize_to_display!(Userid); proxmox_serde::forward_serialize_to_display!(Userid);
proxmox::forward_deserialize_to_from_str!(Authid); proxmox_serde::forward_deserialize_to_from_str!(Authid);
proxmox::forward_serialize_to_display!(Authid); proxmox_serde::forward_serialize_to_display!(Authid);

View File

@ -6,8 +6,7 @@ const_regex! {
pub ZPOOL_NAME_REGEX = r"^[a-zA-Z][a-z0-9A-Z\-_.:]+$"; pub ZPOOL_NAME_REGEX = r"^[a-zA-Z][a-z0-9A-Z\-_.:]+$";
} }
pub const ZFS_ASHIFT_SCHEMA: Schema = IntegerSchema::new( pub const ZFS_ASHIFT_SCHEMA: Schema = IntegerSchema::new("Pool sector size exponent.")
"Pool sector size exponent.")
.minimum(9) .minimum(9)
.maximum(16) .maximum(16)
.default(12) .default(12)
@ -59,7 +58,7 @@ pub enum ZfsRaidLevel {
#[api()] #[api()]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all="kebab-case")] #[serde(rename_all = "kebab-case")]
/// zpool list item /// zpool list item
pub struct ZpoolListItem { pub struct ZpoolListItem {
/// zpool name /// zpool name

View File

@ -1,6 +1,6 @@
[package] [package]
name = "pbs-buildcfg" name = "pbs-buildcfg"
version = "2.1.2" version = "2.2.3"
authors = ["Proxmox Support Team <support@proxmox.com>"] authors = ["Proxmox Support Team <support@proxmox.com>"]
edition = "2018" edition = "2018"
description = "macros used for pbs related paths such as configdir and rundir" description = "macros used for pbs related paths such as configdir and rundir"

View File

@ -5,19 +5,12 @@ use std::process::Command;
fn main() { fn main() {
let repoid = match env::var("REPOID") { let repoid = match env::var("REPOID") {
Ok(repoid) => repoid, Ok(repoid) => repoid,
Err(_) => { Err(_) => match Command::new("git").args(&["rev-parse", "HEAD"]).output() {
match Command::new("git") Ok(output) => String::from_utf8(output.stdout).unwrap(),
.args(&["rev-parse", "HEAD"]) Err(err) => {
.output() panic!("git rev-parse failed: {}", err);
{
Ok(output) => {
String::from_utf8(output.stdout).unwrap()
}
Err(err) => {
panic!("git rev-parse failed: {}", err);
}
} }
} },
}; };
println!("cargo:rustc-env=REPOID={}", repoid); println!("cargo:rustc-env=REPOID={}", repoid);

View File

@ -1,15 +1,13 @@
//! Exports configuration data from the build system //! Exports configuration data from the build system
pub const PROXMOX_PKG_VERSION: &str = pub const PROXMOX_PKG_VERSION: &str = concat!(
concat!( env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MAJOR"), ".",
".", env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_MINOR"), );
);
pub const PROXMOX_PKG_RELEASE: &str = env!("CARGO_PKG_VERSION_PATCH"); pub const PROXMOX_PKG_RELEASE: &str = env!("CARGO_PKG_VERSION_PATCH");
pub const PROXMOX_PKG_REPOID: &str = env!("REPOID"); pub const PROXMOX_PKG_REPOID: &str = env!("REPOID");
/// The configured configuration directory /// The configured configuration directory
pub const CONFIGDIR: &str = "/etc/proxmox-backup"; pub const CONFIGDIR: &str = "/etc/proxmox-backup";
pub const JS_DIR: &str = "/usr/share/javascript/proxmox-backup"; pub const JS_DIR: &str = "/usr/share/javascript/proxmox-backup";
@ -20,20 +18,38 @@ pub const BACKUP_USER_NAME: &str = "backup";
pub const BACKUP_GROUP_NAME: &str = "backup"; pub const BACKUP_GROUP_NAME: &str = "backup";
#[macro_export] #[macro_export]
macro_rules! PROXMOX_BACKUP_RUN_DIR_M { () => ("/run/proxmox-backup") } macro_rules! PROXMOX_BACKUP_RUN_DIR_M {
() => {
"/run/proxmox-backup"
};
}
#[macro_export] #[macro_export]
macro_rules! PROXMOX_BACKUP_STATE_DIR_M { () => ("/var/lib/proxmox-backup") } macro_rules! PROXMOX_BACKUP_STATE_DIR_M {
() => {
"/var/lib/proxmox-backup"
};
}
#[macro_export] #[macro_export]
macro_rules! PROXMOX_BACKUP_LOG_DIR_M { () => ("/var/log/proxmox-backup") } macro_rules! PROXMOX_BACKUP_LOG_DIR_M {
() => {
"/var/log/proxmox-backup"
};
}
#[macro_export] #[macro_export]
macro_rules! PROXMOX_BACKUP_CACHE_DIR_M { () => ("/var/cache/proxmox-backup") } macro_rules! PROXMOX_BACKUP_CACHE_DIR_M {
() => {
"/var/cache/proxmox-backup"
};
}
#[macro_export] #[macro_export]
macro_rules! PROXMOX_BACKUP_FILE_RESTORE_BIN_DIR_M { macro_rules! PROXMOX_BACKUP_FILE_RESTORE_BIN_DIR_M {
() => ("/usr/lib/x86_64-linux-gnu/proxmox-backup/file-restore") () => {
"/usr/lib/x86_64-linux-gnu/proxmox-backup/file-restore"
};
} }
/// namespaced directory for in-memory (tmpfs) run state /// namespaced directory for in-memory (tmpfs) run state
@ -65,8 +81,10 @@ pub const PROXMOX_BACKUP_INITRAMFS_FN: &str =
concat!(PROXMOX_BACKUP_CACHE_DIR_M!(), "/file-restore-initramfs.img"); concat!(PROXMOX_BACKUP_CACHE_DIR_M!(), "/file-restore-initramfs.img");
/// filename of the cached initramfs to use for debugging single file restore /// filename of the cached initramfs to use for debugging single file restore
pub const PROXMOX_BACKUP_INITRAMFS_DBG_FN: &str = pub const PROXMOX_BACKUP_INITRAMFS_DBG_FN: &str = concat!(
concat!(PROXMOX_BACKUP_CACHE_DIR_M!(), "/file-restore-initramfs-debug.img"); PROXMOX_BACKUP_CACHE_DIR_M!(),
"/file-restore-initramfs-debug.img"
);
/// filename of the kernel to use for booting single file restore VMs /// filename of the kernel to use for booting single file restore VMs
pub const PROXMOX_BACKUP_KERNEL_FN: &str = pub const PROXMOX_BACKUP_KERNEL_FN: &str =
@ -82,7 +100,9 @@ pub const PROXMOX_BACKUP_KERNEL_FN: &str =
/// ``` /// ```
#[macro_export] #[macro_export]
macro_rules! configdir { macro_rules! configdir {
($subdir:expr) => (concat!("/etc/proxmox-backup", $subdir)) ($subdir:expr) => {
concat!("/etc/proxmox-backup", $subdir)
};
} }
/// Prepend the run directory to a file name. /// Prepend the run directory to a file name.

View File

@ -10,33 +10,39 @@ anyhow = "1.0"
bitflags = "1.2.1" bitflags = "1.2.1"
bytes = "1.0" bytes = "1.0"
futures = "0.3" futures = "0.3"
hex = "0.4.3"
h2 = { version = "0.3", features = [ "stream" ] } h2 = { version = "0.3", features = [ "stream" ] }
http = "0.2" http = "0.2"
hyper = { version = "0.14", features = [ "full" ] } hyper = { version = "0.14", features = [ "full" ] }
lazy_static = "1.4" lazy_static = "1.4"
libc = "0.2" libc = "0.2"
nix = "0.19.1" nix = "0.24"
openssl = "0.10" openssl = "0.10"
percent-encoding = "2.1" percent-encoding = "2.1"
pin-project-lite = "0.2" pin-project-lite = "0.2"
regex = "1.2" regex = "1.5"
rustyline = "7" rustyline = "9"
serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
tokio = { version = "1.6", features = [ "fs", "signal" ] } tokio = { version = "1.6", features = [ "fs", "signal" ] }
tokio-stream = "0.1.0" tokio-stream = "0.1.0"
tower-service = "0.3.0" tower-service = "0.3.0"
xdg = "2.2" xdg = "2.2"
tar = "0.4"
pathpatterns = "0.1.2" pathpatterns = "0.1.2"
proxmox = "0.15.3"
proxmox-async = "0.2" proxmox-async = "0.4"
proxmox-compression = "0.1.1"
proxmox-fuse = "0.1.1" proxmox-fuse = "0.1.1"
proxmox-http = { version = "0.5.4", features = [ "client", "http-helpers", "websocket" ] } proxmox-http = { version = "0.6", features = [ "client", "http-helpers", "websocket" ] }
proxmox-io = { version = "1", features = [ "tokio" ] } proxmox-io = { version = "1.0.1", features = [ "tokio" ] }
proxmox-lang = "1" proxmox-lang = "1.1"
proxmox-router = { version = "1.1", features = [ "cli" ] } proxmox-router = { version = "1.2", features = [ "cli" ] }
proxmox-schema = "1" proxmox-schema = "1.3.1"
proxmox-time = "1" proxmox-time = "1"
proxmox-sys = "0.3"
pxar = { version = "0.10.1", features = [ "tokio-io" ] } pxar = { version = "0.10.1", features = [ "tokio-io" ] }
pbs-api-types = { path = "../pbs-api-types" } pbs-api-types = { path = "../pbs-api-types" }

View File

@ -1,25 +1,24 @@
use anyhow::{format_err, Error}; use anyhow::{format_err, Error};
use std::io::{Write, Seek, SeekFrom};
use std::fs::File; use std::fs::File;
use std::sync::Arc; use std::io::{Seek, SeekFrom, Write};
use std::os::unix::fs::OpenOptionsExt; use std::os::unix::fs::OpenOptionsExt;
use std::sync::Arc;
use futures::future::AbortHandle; use futures::future::AbortHandle;
use serde_json::{json, Value}; use serde_json::{json, Value};
use proxmox::tools::digest_to_hex; use pbs_api_types::{BackupDir, BackupNamespace};
use pbs_tools::crypt_config::CryptConfig;
use pbs_tools::sha::sha256;
use pbs_datastore::{PROXMOX_BACKUP_READER_PROTOCOL_ID_V1, BackupManifest};
use pbs_datastore::data_blob::DataBlob; use pbs_datastore::data_blob::DataBlob;
use pbs_datastore::data_blob_reader::DataBlobReader; use pbs_datastore::data_blob_reader::DataBlobReader;
use pbs_datastore::dynamic_index::DynamicIndexReader; use pbs_datastore::dynamic_index::DynamicIndexReader;
use pbs_datastore::fixed_index::FixedIndexReader; use pbs_datastore::fixed_index::FixedIndexReader;
use pbs_datastore::index::IndexFile; use pbs_datastore::index::IndexFile;
use pbs_datastore::manifest::MANIFEST_BLOB_NAME; use pbs_datastore::manifest::MANIFEST_BLOB_NAME;
use pbs_datastore::{BackupManifest, PROXMOX_BACKUP_READER_PROTOCOL_ID_V1};
use pbs_tools::crypt_config::CryptConfig;
use pbs_tools::sha::sha256;
use super::{HttpClient, H2Client}; use super::{H2Client, HttpClient};
/// Backup Reader /// Backup Reader
pub struct BackupReader { pub struct BackupReader {
@ -29,16 +28,18 @@ pub struct BackupReader {
} }
impl Drop for BackupReader { impl Drop for BackupReader {
fn drop(&mut self) { fn drop(&mut self) {
self.abort.abort(); self.abort.abort();
} }
} }
impl BackupReader { impl BackupReader {
fn new(h2: H2Client, abort: AbortHandle, crypt_config: Option<Arc<CryptConfig>>) -> Arc<Self> { fn new(h2: H2Client, abort: AbortHandle, crypt_config: Option<Arc<CryptConfig>>) -> Arc<Self> {
Arc::new(Self { h2, abort, crypt_config}) Arc::new(Self {
h2,
abort,
crypt_config,
})
} }
/// Create a new instance by upgrading the connection at '/api2/json/reader' /// Create a new instance by upgrading the connection at '/api2/json/reader'
@ -46,59 +47,55 @@ impl BackupReader {
client: HttpClient, client: HttpClient,
crypt_config: Option<Arc<CryptConfig>>, crypt_config: Option<Arc<CryptConfig>>,
datastore: &str, datastore: &str,
backup_type: &str, ns: &BackupNamespace,
backup_id: &str, backup: &BackupDir,
backup_time: i64,
debug: bool, debug: bool,
) -> Result<Arc<BackupReader>, Error> { ) -> Result<Arc<BackupReader>, Error> {
let mut param = json!({
let param = json!({ "backup-type": backup.ty(),
"backup-type": backup_type, "backup-id": backup.id(),
"backup-id": backup_id, "backup-time": backup.time,
"backup-time": backup_time,
"store": datastore, "store": datastore,
"debug": debug, "debug": debug,
}); });
let req = HttpClient::request_builder(client.server(), client.port(), "GET", "/api2/json/reader", Some(param)).unwrap();
let (h2, abort) = client.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())).await?; if !ns.is_root() {
param["ns"] = serde_json::to_value(ns)?;
}
let req = HttpClient::request_builder(
client.server(),
client.port(),
"GET",
"/api2/json/reader",
Some(param),
)
.unwrap();
let (h2, abort) = client
.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!()))
.await?;
Ok(BackupReader::new(h2, abort, crypt_config)) Ok(BackupReader::new(h2, abort, crypt_config))
} }
/// Execute a GET request /// Execute a GET request
pub async fn get( pub async fn get(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
&self,
path: &str,
param: Option<Value>,
) -> Result<Value, Error> {
self.h2.get(path, param).await self.h2.get(path, param).await
} }
/// Execute a PUT request /// Execute a PUT request
pub async fn put( pub async fn put(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
&self,
path: &str,
param: Option<Value>,
) -> Result<Value, Error> {
self.h2.put(path, param).await self.h2.put(path, param).await
} }
/// Execute a POST request /// Execute a POST request
pub async fn post( pub async fn post(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
&self,
path: &str,
param: Option<Value>,
) -> Result<Value, Error> {
self.h2.post(path, param).await self.h2.post(path, param).await
} }
/// Execute a GET request and send output to a writer /// Execute a GET request and send output to a writer
pub async fn download<W: Write + Send>( pub async fn download<W: Write + Send>(&self, file_name: &str, output: W) -> Result<(), Error> {
&self,
file_name: &str,
output: W,
) -> Result<(), Error> {
let path = "download"; let path = "download";
let param = json!({ "file-name": file_name }); let param = json!({ "file-name": file_name });
self.h2.download(path, Some(param), output).await self.h2.download(path, Some(param), output).await
@ -107,10 +104,7 @@ impl BackupReader {
/// Execute a special GET request and send output to a writer /// Execute a special GET request and send output to a writer
/// ///
/// This writes random data, and is only useful to test download speed. /// This writes random data, and is only useful to test download speed.
pub async fn speedtest<W: Write + Send>( pub async fn speedtest<W: Write + Send>(&self, output: W) -> Result<(), Error> {
&self,
output: W,
) -> Result<(), Error> {
self.h2.download("speedtest", None, output).await self.h2.download("speedtest", None, output).await
} }
@ -121,7 +115,7 @@ impl BackupReader {
output: W, output: W,
) -> Result<(), Error> { ) -> Result<(), Error> {
let path = "chunk"; let path = "chunk";
let param = json!({ "digest": digest_to_hex(digest) }); let param = json!({ "digest": hex::encode(digest) });
self.h2.download(path, Some(param), output).await self.h2.download(path, Some(param), output).await
} }
@ -133,14 +127,14 @@ impl BackupReader {
/// ///
/// The manifest signature is verified if we have a crypt_config. /// The manifest signature is verified if we have a crypt_config.
pub async fn download_manifest(&self) -> Result<(BackupManifest, Vec<u8>), Error> { pub async fn download_manifest(&self) -> Result<(BackupManifest, Vec<u8>), Error> {
let mut raw_data = Vec::with_capacity(64 * 1024); let mut raw_data = Vec::with_capacity(64 * 1024);
self.download(MANIFEST_BLOB_NAME, &mut raw_data).await?; self.download(MANIFEST_BLOB_NAME, &mut raw_data).await?;
let blob = DataBlob::load_from_reader(&mut &raw_data[..])?; let blob = DataBlob::load_from_reader(&mut &raw_data[..])?;
// no expected digest available // no expected digest available
let data = blob.decode(None, None)?; let data = blob.decode(None, None)?;
let manifest = BackupManifest::from_data(&data[..], self.crypt_config.as_ref().map(Arc::as_ref))?; let manifest =
BackupManifest::from_data(&data[..], self.crypt_config.as_ref().map(Arc::as_ref))?;
Ok((manifest, data)) Ok((manifest, data))
} }
@ -154,7 +148,6 @@ impl BackupReader {
manifest: &BackupManifest, manifest: &BackupManifest,
name: &str, name: &str,
) -> Result<DataBlobReader<'_, File>, Error> { ) -> Result<DataBlobReader<'_, File>, Error> {
let mut tmpfile = std::fs::OpenOptions::new() let mut tmpfile = std::fs::OpenOptions::new()
.write(true) .write(true)
.read(true) .read(true)
@ -181,7 +174,6 @@ impl BackupReader {
manifest: &BackupManifest, manifest: &BackupManifest,
name: &str, name: &str,
) -> Result<DynamicIndexReader, Error> { ) -> Result<DynamicIndexReader, Error> {
let mut tmpfile = std::fs::OpenOptions::new() let mut tmpfile = std::fs::OpenOptions::new()
.write(true) .write(true)
.read(true) .read(true)
@ -209,7 +201,6 @@ impl BackupReader {
manifest: &BackupManifest, manifest: &BackupManifest,
name: &str, name: &str,
) -> Result<FixedIndexReader, Error> { ) -> Result<FixedIndexReader, Error> {
let mut tmpfile = std::fs::OpenOptions::new() let mut tmpfile = std::fs::OpenOptions::new()
.write(true) .write(true)
.read(true) .read(true)

View File

@ -3,7 +3,7 @@ use std::fmt;
use anyhow::{format_err, Error}; use anyhow::{format_err, Error};
use pbs_api_types::{BACKUP_REPO_URL_REGEX, IP_V6_REGEX, Authid, Userid}; use pbs_api_types::{Authid, Userid, BACKUP_REPO_URL_REGEX, IP_V6_REGEX};
/// Reference remote backup locations /// Reference remote backup locations
/// ///
@ -21,15 +21,22 @@ pub struct BackupRepository {
} }
impl BackupRepository { impl BackupRepository {
pub fn new(
pub fn new(auth_id: Option<Authid>, host: Option<String>, port: Option<u16>, store: String) -> Self { auth_id: Option<Authid>,
host: Option<String>,
port: Option<u16>,
store: String,
) -> Self {
let host = match host { let host = match host {
Some(host) if (IP_V6_REGEX.regex_obj)().is_match(&host) => { Some(host) if (IP_V6_REGEX.regex_obj)().is_match(&host) => Some(format!("[{}]", host)),
Some(format!("[{}]", host))
},
other => other, other => other,
}; };
Self { auth_id, host, port, store } Self {
auth_id,
host,
port,
store,
}
} }
pub fn auth_id(&self) -> &Authid { pub fn auth_id(&self) -> &Authid {
@ -37,7 +44,7 @@ impl BackupRepository {
return auth_id; return auth_id;
} }
&Authid::root_auth_id() Authid::root_auth_id()
} }
pub fn user(&self) -> &Userid { pub fn user(&self) -> &Userid {
@ -70,7 +77,14 @@ impl BackupRepository {
impl fmt::Display for BackupRepository { impl fmt::Display for BackupRepository {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (&self.auth_id, &self.host, self.port) { match (&self.auth_id, &self.host, self.port) {
(Some(auth_id), _, _) => write!(f, "{}@{}:{}:{}", auth_id, self.host(), self.port(), self.store), (Some(auth_id), _, _) => write!(
f,
"{}@{}:{}:{}",
auth_id,
self.host(),
self.port(),
self.store
),
(None, Some(host), None) => write!(f, "{}:{}", host, self.store), (None, Some(host), None) => write!(f, "{}:{}", host, self.store),
(None, _, Some(port)) => write!(f, "{}:{}:{}", self.host(), port, self.store), (None, _, Some(port)) => write!(f, "{}:{}:{}", self.host(), port, self.store),
(None, None, None) => write!(f, "{}", self.store), (None, None, None) => write!(f, "{}", self.store),
@ -87,12 +101,15 @@ impl std::str::FromStr for BackupRepository {
/// `host` parts are optional, where `host` defaults to the local /// `host` parts are optional, where `host` defaults to the local
/// host, and `user` defaults to `root@pam`. /// host, and `user` defaults to `root@pam`.
fn from_str(url: &str) -> Result<Self, Self::Err> { fn from_str(url: &str) -> Result<Self, Self::Err> {
let cap = (BACKUP_REPO_URL_REGEX.regex_obj)()
let cap = (BACKUP_REPO_URL_REGEX.regex_obj)().captures(url) .captures(url)
.ok_or_else(|| format_err!("unable to parse repository url '{}'", url))?; .ok_or_else(|| format_err!("unable to parse repository url '{}'", url))?;
Ok(Self { Ok(Self {
auth_id: cap.get(1).map(|m| Authid::try_from(m.as_str().to_owned())).transpose()?, auth_id: cap
.get(1)
.map(|m| Authid::try_from(m.as_str().to_owned()))
.transpose()?,
host: cap.get(2).map(|m| m.as_str().to_owned()), host: cap.get(2).map(|m| m.as_str().to_owned()),
port: cap.get(3).map(|m| m.as_str().parse::<u16>()).transpose()?, port: cap.get(3).map(|m| m.as_str().parse::<u16>()).transpose()?,
store: cap[4].to_owned(), store: cap[4].to_owned(),

View File

@ -6,25 +6,29 @@ const_regex! {
BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(pxar|img|conf|log)):(.+)$"; BACKUPSPEC_REGEX = r"^([a-zA-Z0-9_-]+\.(pxar|img|conf|log)):(.+)$";
} }
pub const BACKUP_SOURCE_SCHEMA: Schema = StringSchema::new( pub const BACKUP_SOURCE_SCHEMA: Schema =
"Backup source specification ([<label>:<path>]).") StringSchema::new("Backup source specification ([<label>:<path>]).")
.format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX)) .format(&ApiStringFormat::Pattern(&BACKUPSPEC_REGEX))
.schema(); .schema();
pub enum BackupSpecificationType { PXAR, IMAGE, CONFIG, LOGFILE } pub enum BackupSpecificationType {
PXAR,
IMAGE,
CONFIG,
LOGFILE,
}
pub struct BackupSpecification { pub struct BackupSpecification {
pub archive_name: String, // left part pub archive_name: String, // left part
pub config_string: String, // right part pub config_string: String, // right part
pub spec_type: BackupSpecificationType, pub spec_type: BackupSpecificationType,
} }
pub fn parse_backup_specification(value: &str) -> Result<BackupSpecification, Error> { pub fn parse_backup_specification(value: &str) -> Result<BackupSpecification, Error> {
if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) { if let Some(caps) = (BACKUPSPEC_REGEX.regex_obj)().captures(value) {
let archive_name = caps.get(1).unwrap().as_str().into(); let archive_name = caps.get(1).unwrap().as_str().into();
let extension = caps.get(2).unwrap().as_str(); let extension = caps.get(2).unwrap().as_str();
let config_string = caps.get(3).unwrap().as_str().into(); let config_string = caps.get(3).unwrap().as_str().into();
let spec_type = match extension { let spec_type = match extension {
"pxar" => BackupSpecificationType::PXAR, "pxar" => BackupSpecificationType::PXAR,
"img" => BackupSpecificationType::IMAGE, "img" => BackupSpecificationType::IMAGE,
@ -32,7 +36,11 @@ pub fn parse_backup_specification(value: &str) -> Result<BackupSpecification, Er
"log" => BackupSpecificationType::LOGFILE, "log" => BackupSpecificationType::LOGFILE,
_ => bail!("unknown backup source type '{}'", extension), _ => bail!("unknown backup source type '{}'", extension),
}; };
return Ok(BackupSpecification { archive_name, config_string, spec_type }); return Ok(BackupSpecification {
archive_name,
config_string,
spec_type,
});
} }
bail!("unable to parse backup source specification '{}'", value); bail!("unable to parse backup source specification '{}'", value);

View File

@ -12,16 +12,14 @@ use tokio::io::AsyncReadExt;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
use proxmox::tools::digest_to_hex; use pbs_api_types::{BackupDir, BackupNamespace, HumanByte};
use pbs_api_types::HumanByte;
use pbs_tools::crypt_config::CryptConfig;
use pbs_datastore::{CATALOG_NAME, PROXMOX_BACKUP_PROTOCOL_ID_V1};
use pbs_datastore::data_blob::{ChunkInfo, DataBlob, DataChunkBuilder}; use pbs_datastore::data_blob::{ChunkInfo, DataBlob, DataChunkBuilder};
use pbs_datastore::dynamic_index::DynamicIndexReader; use pbs_datastore::dynamic_index::DynamicIndexReader;
use pbs_datastore::fixed_index::FixedIndexReader; use pbs_datastore::fixed_index::FixedIndexReader;
use pbs_datastore::index::IndexFile; use pbs_datastore::index::IndexFile;
use pbs_datastore::manifest::{ArchiveType, BackupManifest, MANIFEST_BLOB_NAME}; use pbs_datastore::manifest::{ArchiveType, BackupManifest, MANIFEST_BLOB_NAME};
use pbs_datastore::{CATALOG_NAME, PROXMOX_BACKUP_PROTOCOL_ID_V1};
use pbs_tools::crypt_config::CryptConfig;
use super::merge_known_chunks::{MergeKnownChunks, MergedChunkInfo}; use super::merge_known_chunks::{MergeKnownChunks, MergedChunkInfo};
@ -88,21 +86,24 @@ impl BackupWriter {
client: HttpClient, client: HttpClient,
crypt_config: Option<Arc<CryptConfig>>, crypt_config: Option<Arc<CryptConfig>>,
datastore: &str, datastore: &str,
backup_type: &str, ns: &BackupNamespace,
backup_id: &str, backup: &BackupDir,
backup_time: i64,
debug: bool, debug: bool,
benchmark: bool, benchmark: bool,
) -> Result<Arc<BackupWriter>, Error> { ) -> Result<Arc<BackupWriter>, Error> {
let param = json!({ let mut param = json!({
"backup-type": backup_type, "backup-type": backup.ty(),
"backup-id": backup_id, "backup-id": backup.id(),
"backup-time": backup_time, "backup-time": backup.time,
"store": datastore, "store": datastore,
"debug": debug, "debug": debug,
"benchmark": benchmark "benchmark": benchmark
}); });
if !ns.is_root() {
param["ns"] = serde_json::to_value(ns)?;
}
let req = HttpClient::request_builder( let req = HttpClient::request_builder(
client.server(), client.server(),
client.port(), client.port(),
@ -291,22 +292,28 @@ impl BackupWriter {
// try, but ignore errors // try, but ignore errors
match ArchiveType::from_path(archive_name) { match ArchiveType::from_path(archive_name) {
Ok(ArchiveType::FixedIndex) => { Ok(ArchiveType::FixedIndex) => {
let _ = self if let Err(err) = self
.download_previous_fixed_index( .download_previous_fixed_index(
archive_name, archive_name,
&manifest, &manifest,
known_chunks.clone(), known_chunks.clone(),
) )
.await; .await
{
eprintln!("Error downloading .fidx from previous manifest: {}", err);
}
} }
Ok(ArchiveType::DynamicIndex) => { Ok(ArchiveType::DynamicIndex) => {
let _ = self if let Err(err) = self
.download_previous_dynamic_index( .download_previous_dynamic_index(
archive_name, archive_name,
&manifest, &manifest,
known_chunks.clone(), known_chunks.clone(),
) )
.await; .await
{
eprintln!("Error downloading .didx from previous manifest: {}", err);
}
} }
_ => { /* do nothing */ } _ => { /* do nothing */ }
} }
@ -323,7 +330,7 @@ impl BackupWriter {
self.h2.clone(), self.h2.clone(),
wid, wid,
stream, stream,
&prefix, prefix,
known_chunks.clone(), known_chunks.clone(),
if options.encrypt { if options.encrypt {
self.crypt_config.clone() self.crypt_config.clone()
@ -389,7 +396,7 @@ impl BackupWriter {
"wid": wid , "wid": wid ,
"chunk-count": upload_stats.chunk_count, "chunk-count": upload_stats.chunk_count,
"size": upload_stats.size, "size": upload_stats.size,
"csum": proxmox::tools::digest_to_hex(&upload_stats.csum), "csum": hex::encode(&upload_stats.csum),
}); });
let _value = self.h2.post(&close_path, Some(param)).await?; let _value = self.h2.post(&close_path, Some(param)).await?;
Ok(BackupStats { Ok(BackupStats {
@ -481,7 +488,7 @@ impl BackupWriter {
let mut digest_list = vec![]; let mut digest_list = vec![];
let mut offset_list = vec![]; let mut offset_list = vec![];
for (offset, digest) in chunk_list { for (offset, digest) in chunk_list {
digest_list.push(digest_to_hex(&digest)); digest_list.push(hex::encode(&digest));
offset_list.push(offset); offset_list.push(offset);
} }
if verbose { println!("append chunks list len ({})", digest_list.len()); } if verbose { println!("append chunks list len ({})", digest_list.len()); }
@ -712,7 +719,7 @@ impl BackupWriter {
if let MergedChunkInfo::New(chunk_info) = merged_chunk_info { if let MergedChunkInfo::New(chunk_info) = merged_chunk_info {
let offset = chunk_info.offset; let offset = chunk_info.offset;
let digest = chunk_info.digest; let digest = chunk_info.digest;
let digest_str = digest_to_hex(&digest); let digest_str = hex::encode(&digest);
/* too verbose, needs finer verbosity setting granularity /* too verbose, needs finer verbosity setting granularity
if verbose { if verbose {

View File

@ -14,16 +14,16 @@ use nix::fcntl::OFlag;
use nix::sys::stat::Mode; use nix::sys::stat::Mode;
use pathpatterns::{MatchEntry, MatchList, MatchPattern, MatchType, PatternFlag}; use pathpatterns::{MatchEntry, MatchList, MatchPattern, MatchType, PatternFlag};
use proxmox::tools::fs::{create_path, CreateOptions};
use proxmox_router::cli::{self, CliCommand, CliCommandMap, CliHelper, CommandLineInterface}; use proxmox_router::cli::{self, CliCommand, CliCommandMap, CliHelper, CommandLineInterface};
use proxmox_schema::api; use proxmox_schema::api;
use proxmox_sys::fs::{create_path, CreateOptions};
use pxar::{EntryKind, Metadata}; use pxar::{EntryKind, Metadata};
use proxmox_async::runtime::block_in_place;
use pbs_datastore::catalog::{self, DirEntryAttribute}; use pbs_datastore::catalog::{self, DirEntryAttribute};
use proxmox_async::runtime::block_in_place;
use crate::pxar::Flags;
use crate::pxar::fuse::{Accessor, FileEntry}; use crate::pxar::fuse::{Accessor, FileEntry};
use crate::pxar::Flags;
type CatalogReader = pbs_datastore::catalog::CatalogReader<std::fs::File>; type CatalogReader = pbs_datastore::catalog::CatalogReader<std::fs::File>;
@ -91,10 +91,7 @@ pub fn catalog_shell_cli() -> CommandLineInterface {
"find", "find",
CliCommand::new(&API_METHOD_FIND_COMMAND).arg_param(&["pattern"]), CliCommand::new(&API_METHOD_FIND_COMMAND).arg_param(&["pattern"]),
) )
.insert( .insert("exit", CliCommand::new(&API_METHOD_EXIT))
"exit",
CliCommand::new(&API_METHOD_EXIT),
)
.insert_help(), .insert_help(),
) )
} }
@ -529,7 +526,7 @@ impl Shell {
}; };
let new_stack = let new_stack =
Self::lookup(&stack, &mut *catalog, accessor, Some(path), follow_symlinks).await?; Self::lookup(stack, &mut *catalog, accessor, Some(path), follow_symlinks).await?;
*stack = new_stack; *stack = new_stack;
@ -993,7 +990,7 @@ impl Shell {
&mut self.catalog, &mut self.catalog,
dir_stack, dir_stack,
extractor, extractor,
&match_list, match_list,
&self.accessor, &self.accessor,
)?; )?;
@ -1070,7 +1067,8 @@ impl<'a> ExtractorState<'a> {
} }
self.path.extend(&entry.name); self.path.extend(&entry.name);
self.extractor.set_path(OsString::from_vec(self.path.clone())); self.extractor
.set_path(OsString::from_vec(self.path.clone()));
self.handle_entry(entry).await?; self.handle_entry(entry).await?;
} }
@ -1118,11 +1116,12 @@ impl<'a> ExtractorState<'a> {
self.path_len_stack.push(self.path_len); self.path_len_stack.push(self.path_len);
self.path_len = self.path.len(); self.path_len = self.path.len();
Shell::walk_pxar_archive(&self.accessor, &mut self.dir_stack).await?; Shell::walk_pxar_archive(self.accessor, &mut self.dir_stack).await?;
let dir_pxar = self.dir_stack.last().unwrap().pxar.as_ref().unwrap(); let dir_pxar = self.dir_stack.last().unwrap().pxar.as_ref().unwrap();
let dir_meta = dir_pxar.entry().metadata().clone(); let dir_meta = dir_pxar.entry().metadata().clone();
let create = self.matches && match_result != Some(MatchType::Exclude); let create = self.matches && match_result != Some(MatchType::Exclude);
self.extractor.enter_directory(dir_pxar.file_name().to_os_string(), dir_meta, create)?; self.extractor
.enter_directory(dir_pxar.file_name().to_os_string(), dir_meta, create)?;
Ok(()) Ok(())
} }
@ -1141,7 +1140,7 @@ impl<'a> ExtractorState<'a> {
} }
(true, DirEntryAttribute::File { .. }) => { (true, DirEntryAttribute::File { .. }) => {
self.dir_stack.push(PathStackEntry::new(entry)); self.dir_stack.push(PathStackEntry::new(entry));
let file = Shell::walk_pxar_archive(&self.accessor, &mut self.dir_stack).await?; let file = Shell::walk_pxar_archive(self.accessor, &mut self.dir_stack).await?;
self.extract_file(file).await?; self.extract_file(file).await?;
self.dir_stack.pop(); self.dir_stack.pop();
} }
@ -1153,7 +1152,7 @@ impl<'a> ExtractorState<'a> {
| (true, DirEntryAttribute::Hardlink) => { | (true, DirEntryAttribute::Hardlink) => {
let attr = entry.attr.clone(); let attr = entry.attr.clone();
self.dir_stack.push(PathStackEntry::new(entry)); self.dir_stack.push(PathStackEntry::new(entry));
let file = Shell::walk_pxar_archive(&self.accessor, &mut self.dir_stack).await?; let file = Shell::walk_pxar_archive(self.accessor, &mut self.dir_stack).await?;
self.extract_special(file, attr).await?; self.extract_special(file, attr).await?;
self.dir_stack.pop(); self.dir_stack.pop();
} }
@ -1172,13 +1171,9 @@ impl<'a> ExtractorState<'a> {
pxar::EntryKind::File { size, .. } => { pxar::EntryKind::File { size, .. } => {
let file_name = CString::new(entry.file_name().as_bytes())?; let file_name = CString::new(entry.file_name().as_bytes())?;
let mut contents = entry.contents().await?; let mut contents = entry.contents().await?;
self.extractor.async_extract_file( self.extractor
&file_name, .async_extract_file(&file_name, entry.metadata(), *size, &mut contents)
entry.metadata(), .await
*size,
&mut contents,
)
.await
} }
_ => { _ => {
bail!( bail!(
@ -1197,11 +1192,13 @@ impl<'a> ExtractorState<'a> {
let file_name = CString::new(entry.file_name().as_bytes())?; let file_name = CString::new(entry.file_name().as_bytes())?;
match (catalog_attr, entry.kind()) { match (catalog_attr, entry.kind()) {
(DirEntryAttribute::Symlink, pxar::EntryKind::Symlink(symlink)) => { (DirEntryAttribute::Symlink, pxar::EntryKind::Symlink(symlink)) => {
block_in_place(|| self.extractor.extract_symlink( block_in_place(|| {
&file_name, self.extractor.extract_symlink(
entry.metadata(), &file_name,
symlink.as_os_str(), entry.metadata(),
)) symlink.as_os_str(),
)
})
} }
(DirEntryAttribute::Symlink, _) => { (DirEntryAttribute::Symlink, _) => {
bail!( bail!(
@ -1211,7 +1208,10 @@ impl<'a> ExtractorState<'a> {
} }
(DirEntryAttribute::Hardlink, pxar::EntryKind::Hardlink(hardlink)) => { (DirEntryAttribute::Hardlink, pxar::EntryKind::Hardlink(hardlink)) => {
block_in_place(|| self.extractor.extract_hardlink(&file_name, hardlink.as_os_str())) block_in_place(|| {
self.extractor
.extract_hardlink(&file_name, hardlink.as_os_str())
})
} }
(DirEntryAttribute::Hardlink, _) => { (DirEntryAttribute::Hardlink, _) => {
bail!( bail!(
@ -1224,16 +1224,18 @@ impl<'a> ExtractorState<'a> {
self.extract_device(attr.clone(), &file_name, device, entry.metadata()) self.extract_device(attr.clone(), &file_name, device, entry.metadata())
} }
(DirEntryAttribute::Fifo, pxar::EntryKind::Fifo) => { (DirEntryAttribute::Fifo, pxar::EntryKind::Fifo) => block_in_place(|| {
block_in_place(|| self.extractor.extract_special(&file_name, entry.metadata(), 0)) self.extractor
} .extract_special(&file_name, entry.metadata(), 0)
}),
(DirEntryAttribute::Fifo, _) => { (DirEntryAttribute::Fifo, _) => {
bail!("catalog fifo {:?} not a fifo in the archive", self.path()); bail!("catalog fifo {:?} not a fifo in the archive", self.path());
} }
(DirEntryAttribute::Socket, pxar::EntryKind::Socket) => { (DirEntryAttribute::Socket, pxar::EntryKind::Socket) => block_in_place(|| {
block_in_place(|| self.extractor.extract_special(&file_name, entry.metadata(), 0)) self.extractor
} .extract_special(&file_name, entry.metadata(), 0)
}),
(DirEntryAttribute::Socket, _) => { (DirEntryAttribute::Socket, _) => {
bail!( bail!(
"catalog socket {:?} not a socket in the archive", "catalog socket {:?} not a socket in the archive",
@ -1277,6 +1279,9 @@ impl<'a> ExtractorState<'a> {
); );
} }
} }
block_in_place(|| self.extractor.extract_special(file_name, metadata, device.to_dev_t())) block_in_place(|| {
self.extractor
.extract_special(file_name, metadata, device.to_dev_t())
})
} }
} }

View File

@ -1,8 +1,8 @@
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use anyhow::Error;
use bytes::BytesMut; use bytes::BytesMut;
use anyhow::{Error};
use futures::ready; use futures::ready;
use futures::stream::{Stream, TryStream}; use futures::stream::{Stream, TryStream};
@ -18,7 +18,12 @@ pub struct ChunkStream<S: Unpin> {
impl<S: Unpin> ChunkStream<S> { impl<S: Unpin> ChunkStream<S> {
pub fn new(input: S, chunk_size: Option<usize>) -> Self { pub fn new(input: S, chunk_size: Option<usize>) -> Self {
Self { input, chunker: Chunker::new(chunk_size.unwrap_or(4*1024*1024)), buffer: BytesMut::new(), scan_pos: 0} Self {
input,
chunker: Chunker::new(chunk_size.unwrap_or(4 * 1024 * 1024)),
buffer: BytesMut::new(),
scan_pos: 0,
}
} }
} }
@ -30,7 +35,6 @@ where
S::Ok: AsRef<[u8]>, S::Ok: AsRef<[u8]>,
S::Error: Into<Error>, S::Error: Into<Error>,
{ {
type Item = Result<BytesMut, Error>; type Item = Result<BytesMut, 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>> {
@ -82,7 +86,11 @@ pub struct FixedChunkStream<S: Unpin> {
impl<S: Unpin> FixedChunkStream<S> { impl<S: Unpin> FixedChunkStream<S> {
pub fn new(input: S, chunk_size: usize) -> Self { pub fn new(input: S, chunk_size: usize) -> Self {
Self { input, chunk_size, buffer: BytesMut::new() } Self {
input,
chunk_size,
buffer: BytesMut::new(),
}
} }
} }
@ -95,7 +103,10 @@ where
{ {
type Item = Result<BytesMut, S::Error>; type Item = Result<BytesMut, S::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Result<BytesMut, S::Error>>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Option<Result<BytesMut, S::Error>>> {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {
if this.buffer.len() >= this.chunk_size { if this.buffer.len() >= this.chunk_size {

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