1 use anyhow
::{bail, format_err, Error}
;
3 use hyper
::header
::{HeaderValue, UPGRADE}
;
4 use hyper
::http
::request
::Parts
;
5 use hyper
::{Body, Response, StatusCode}
;
6 use serde_json
::{json, Value}
;
8 use proxmox
::{sortable, identity, list_subdirs_api_method}
;
9 use proxmox
::api
::{ApiResponseFuture, ApiHandler, ApiMethod, Router, RpcEnvironment, Permission}
;
10 use proxmox
::api
::router
::SubdirMap
;
11 use proxmox
::api
::schema
::*;
14 use crate::server
::{WorkerTask, H2Service}
;
16 use crate::api2
::types
::*;
17 use crate::config
::acl
::PRIV_DATASTORE_BACKUP
;
18 use crate::config
::cached_user_info
::CachedUserInfo
;
19 use crate::tools
::fs
::lock_dir_noblock_shared
;
27 pub const ROUTER
: Router
= Router
::new()
28 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
31 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
32 &ApiHandler
::AsyncHttp(&upgrade_to_backup_protocol
),
34 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
36 ("store", false, &DATASTORE_SCHEMA
),
37 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
38 ("backup-id", false, &BACKUP_ID_SCHEMA
),
39 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
40 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
41 ("benchmark", true, &BooleanSchema
::new("Job is a benchmark (do not keep data).").schema()),
45 // Note: parameter 'store' is no uri parameter, so we need to test inside function body
46 Some("The user needs Datastore.Backup privilege on /datastore/{store} and needs to own the backup group."),
50 fn upgrade_to_backup_protocol(
55 rpcenv
: Box
<dyn RpcEnvironment
>,
56 ) -> ApiResponseFuture
{
59 let debug
= param
["debug"].as_bool().unwrap_or(false);
60 let benchmark
= param
["benchmark"].as_bool().unwrap_or(false);
62 let userid
: Userid
= rpcenv
.get_user().unwrap().parse()?
;
64 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
66 let user_info
= CachedUserInfo
::new()?
;
67 user_info
.check_privs(&userid
, &["datastore", &store
], PRIV_DATASTORE_BACKUP
, false)?
;
69 let datastore
= DataStore
::lookup_datastore(&store
)?
;
71 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
72 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
73 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
78 .ok_or_else(|| format_err
!("missing Upgrade header"))?
81 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
82 bail
!("invalid protocol name");
85 if parts
.version
>= http
::version
::Version
::HTTP_2
{
86 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
89 let worker_id
= format
!("{}:{}/{}", store
, backup_type
, backup_id
);
91 let env_type
= rpcenv
.env_type();
93 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
95 let worker_type
= if backup_type
== "host" && backup_id
== "benchmark" {
97 bail
!("unable to run benchmark without --benchmark flags");
102 bail
!("benchmark flags is only allowed on 'host/benchmark'");
107 // lock backup group to only allow one backup per group at a time
108 let (owner
, _group_guard
) = datastore
.create_locked_backup_group(&backup_group
, &userid
)?
;
111 if owner
!= userid
&& worker_type
!= "benchmark" {
112 // only the owner is allowed to create additional snapshots
113 bail
!("backup owner check failed ({} != {})", userid
, owner
);
117 let info
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
, true).unwrap_or(None
);
118 if let Some(info
) = info
{
119 let (manifest
, _
) = datastore
.load_manifest(&info
.backup_dir
)?
;
120 let verify
= manifest
.unprotected
["verify_state"].clone();
121 match serde_json
::from_value
::<SnapshotVerifyState
>(verify
) {
124 VerifyState
::Ok
=> Some(info
),
125 VerifyState
::Failed
=> None
,
129 // no verify state found, treat as valid
138 let backup_dir
= BackupDir
::with_group(backup_group
.clone(), backup_time
)?
;
140 let _last_guard
= if let Some(last
) = &last_backup
{
141 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
142 bail
!("backup timestamp is older than last backup.");
145 // lock last snapshot to prevent forgetting/pruning it during backup
146 let full_path
= datastore
.snapshot_path(&last
.backup_dir
);
147 Some(lock_dir_noblock_shared(&full_path
, "snapshot", "base snapshot is already locked by another operation")?
)
152 let (path
, is_new
, snap_guard
) = datastore
.create_locked_backup_dir(&backup_dir
)?
;
153 if !is_new { bail!("backup directory already exists."); }
156 WorkerTask
::spawn(worker_type
, Some(worker_id
), userid
.clone(), true, move |worker
| {
157 let mut env
= BackupEnvironment
::new(
158 env_type
, userid
, worker
.clone(), datastore
, backup_dir
);
161 env
.last_backup
= last_backup
;
163 env
.log(format
!("starting new {} on datastore '{}': {:?}", worker_type
, store
, path
));
165 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
167 let abort_future
= worker
.abort_future();
169 let env2
= env
.clone();
171 let mut req_fut
= req_body
173 .map_err(Error
::from
)
174 .and_then(move |conn
| {
175 env2
.debug("protocol upgrade done");
177 let mut http
= hyper
::server
::conn
::Http
::new();
178 http
.http2_only(true);
179 // increase window size: todo - find optiomal size
180 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
181 http
.http2_initial_stream_window_size(window_size
);
182 http
.http2_initial_connection_window_size(window_size
);
183 http
.http2_max_frame_size(4*1024*1024);
185 let env3
= env2
.clone();
186 http
.serve_connection(conn
, service
)
190 // Avoid Transport endpoint is not connected (os error 107)
191 // fixme: find a better way to test for that error
192 if err
.to_string().starts_with("connection error") && env3
.finished() {
195 Err(Error
::from(err
))
202 let mut abort_future
= abort_future
203 .map(|_
| Err(format_err
!("task aborted")));
206 // keep flock until task ends
207 let _group_guard
= _group_guard
;
208 let snap_guard
= snap_guard
;
209 let _last_guard
= _last_guard
;
212 req
= req_fut
=> req
,
213 abrt
= abort_future
=> abrt
,
216 env
.log("benchmark finished successfully");
217 tools
::runtime
::block_in_place(|| env
.remove_backup())?
;
221 let verify
= |env
: BackupEnvironment
| {
222 if let Err(err
) = env
.verify_after_complete(snap_guard
) {
224 "backup finished, but starting the requested verify task failed: {}",
230 match (res
, env
.ensure_finished()) {
232 env
.log("backup finished successfully");
236 (Err(err
), Ok(())) => {
237 // ignore errors after finish
238 env
.log(format
!("backup had errors but finished: {}", err
));
242 (Ok(_
), Err(err
)) => {
243 env
.log(format
!("backup ended and finish failed: {}", err
));
244 env
.log("removing unfinished backup");
245 tools
::runtime
::block_in_place(|| env
.remove_backup())?
;
248 (Err(err
), Err(_
)) => {
249 env
.log(format
!("backup failed: {}", err
));
250 env
.log("removing failed backup");
251 tools
::runtime
::block_in_place(|| env
.remove_backup())?
;
258 let response
= Response
::builder()
259 .status(StatusCode
::SWITCHING_PROTOCOLS
)
260 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
261 .body(Body
::empty())?
;
267 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
269 "blob", &Router
::new()
270 .upload(&API_METHOD_UPLOAD_BLOB
)
273 "dynamic_chunk", &Router
::new()
274 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
277 "dynamic_close", &Router
::new()
278 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
281 "dynamic_index", &Router
::new()
282 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
283 .put(&API_METHOD_DYNAMIC_APPEND
)
286 "finish", &Router
::new()
289 &ApiHandler
::Sync(&finish_backup
),
290 &ObjectSchema
::new("Mark backup as finished.", &[])
295 "fixed_chunk", &Router
::new()
296 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
299 "fixed_close", &Router
::new()
300 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
303 "fixed_index", &Router
::new()
304 .post(&API_METHOD_CREATE_FIXED_INDEX
)
305 .put(&API_METHOD_FIXED_APPEND
)
308 "previous", &Router
::new()
309 .download(&API_METHOD_DOWNLOAD_PREVIOUS
)
312 "speedtest", &Router
::new()
313 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
317 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
318 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
319 .subdirs(BACKUP_API_SUBDIRS
);
322 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
323 &ApiHandler
::Sync(&create_dynamic_index
),
325 "Create dynamic chunk index file.",
327 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
332 fn create_dynamic_index(
335 rpcenv
: &mut dyn RpcEnvironment
,
336 ) -> Result
<Value
, Error
> {
338 let env
: &BackupEnvironment
= rpcenv
.as_ref();
340 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
342 let archive_name
= name
.clone();
343 if !archive_name
.ends_with(".didx") {
344 bail
!("wrong archive extension: '{}'", archive_name
);
347 let mut path
= env
.backup_dir
.relative_path();
348 path
.push(archive_name
);
350 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
351 let wid
= env
.register_dynamic_writer(index
, name
)?
;
353 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
359 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
360 &ApiHandler
::Sync(&create_fixed_index
),
362 "Create fixed chunk index file.",
364 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
365 ("size", false, &IntegerSchema
::new("File size.")
369 ("reuse-csum", true, &StringSchema
::new("If set, compare last backup's \
370 csum and reuse index for incremental backup if it matches.").schema()),
375 fn create_fixed_index(
378 rpcenv
: &mut dyn RpcEnvironment
,
379 ) -> Result
<Value
, Error
> {
381 let env
: &BackupEnvironment
= rpcenv
.as_ref();
383 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
384 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
385 let reuse_csum
= param
["reuse-csum"].as_str();
387 let archive_name
= name
.clone();
388 if !archive_name
.ends_with(".fidx") {
389 bail
!("wrong archive extension: '{}'", archive_name
);
392 let mut path
= env
.backup_dir
.relative_path();
393 path
.push(&archive_name
);
395 let chunk_size
= 4096*1024; // todo: ??
397 // do incremental backup if csum is set
398 let mut reader
= None
;
399 let mut incremental
= false;
400 if let Some(csum
) = reuse_csum
{
402 let last_backup
= match &env
.last_backup
{
405 bail
!("cannot reuse index - no valid previous backup exists");
409 let mut last_path
= last_backup
.backup_dir
.relative_path();
410 last_path
.push(&archive_name
);
412 let index
= match env
.datastore
.open_fixed_reader(last_path
) {
415 bail
!("cannot reuse index - no previous backup exists for archive");
419 let (old_csum
, _
) = index
.compute_csum();
420 let old_csum
= proxmox
::tools
::digest_to_hex(&old_csum
);
421 if old_csum
!= csum
{
422 bail
!("expected csum ({}) doesn't match last backup's ({}), cannot do incremental backup",
426 reader
= Some(index
);
429 let mut writer
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
431 if let Some(reader
) = reader
{
432 writer
.clone_data_from(&reader
)?
;
435 let wid
= env
.register_fixed_writer(writer
, name
, size
, chunk_size
as u32, incremental
)?
;
437 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
443 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
444 &ApiHandler
::Sync(&dynamic_append
),
446 "Append chunk to dynamic index writer.",
451 &IntegerSchema
::new("Dynamic writer ID.")
459 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
465 "Chunk offset list.",
466 &IntegerSchema
::new("Corresponding chunk offsets.")
478 rpcenv
: &mut dyn RpcEnvironment
,
479 ) -> Result
<Value
, Error
> {
481 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
482 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
483 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
485 if offset_list
.len() != digest_list
.len() {
486 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
489 let env
: &BackupEnvironment
= rpcenv
.as_ref();
491 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
493 for (i
, item
) in digest_list
.iter().enumerate() {
494 let digest_str
= item
.as_str().unwrap();
495 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
496 let offset
= offset_list
[i
].as_u64().unwrap();
497 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
499 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
501 env
.debug(format
!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
508 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
509 &ApiHandler
::Sync(&fixed_append
),
511 "Append chunk to fixed index writer.",
516 &IntegerSchema
::new("Fixed writer ID.")
524 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
530 "Chunk offset list.",
531 &IntegerSchema
::new("Corresponding chunk offsets.")
543 rpcenv
: &mut dyn RpcEnvironment
,
544 ) -> Result
<Value
, Error
> {
546 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
547 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
548 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
550 if offset_list
.len() != digest_list
.len() {
551 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
554 let env
: &BackupEnvironment
= rpcenv
.as_ref();
556 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
558 for (i
, item
) in digest_list
.iter().enumerate() {
559 let digest_str
= item
.as_str().unwrap();
560 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
561 let offset
= offset_list
[i
].as_u64().unwrap();
562 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
564 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
566 env
.debug(format
!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
573 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
574 &ApiHandler
::Sync(&close_dynamic_index
),
576 "Close dynamic index writer.",
581 &IntegerSchema
::new("Dynamic writer ID.")
589 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
596 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
600 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
605 fn close_dynamic_index (
608 rpcenv
: &mut dyn RpcEnvironment
,
609 ) -> Result
<Value
, Error
> {
611 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
612 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
613 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
614 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
615 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
617 let env
: &BackupEnvironment
= rpcenv
.as_ref();
619 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
621 env
.log(format
!("successfully closed dynamic index {}", wid
));
627 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
628 &ApiHandler
::Sync(&close_fixed_index
),
630 "Close fixed index writer.",
635 &IntegerSchema
::new("Fixed writer ID.")
643 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks. Ignored for incremental backups.")
650 &IntegerSchema
::new("File size. This is used to verify that the server got all data. Ignored for incremental backups.")
654 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
659 fn close_fixed_index (
662 rpcenv
: &mut dyn RpcEnvironment
,
663 ) -> Result
<Value
, Error
> {
665 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
666 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
667 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
668 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
669 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
671 let env
: &BackupEnvironment
= rpcenv
.as_ref();
673 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
675 env
.log(format
!("successfully closed fixed index {}", wid
));
683 rpcenv
: &mut dyn RpcEnvironment
,
684 ) -> Result
<Value
, Error
> {
686 let env
: &BackupEnvironment
= rpcenv
.as_ref();
688 env
.finish_backup()?
;
689 env
.log("successfully finished backup");
695 pub const API_METHOD_DOWNLOAD_PREVIOUS
: ApiMethod
= ApiMethod
::new(
696 &ApiHandler
::AsyncHttp(&download_previous
),
698 "Download archive from previous backup.",
700 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
705 fn download_previous(
710 rpcenv
: Box
<dyn RpcEnvironment
>,
711 ) -> ApiResponseFuture
{
714 let env
: &BackupEnvironment
= rpcenv
.as_ref();
716 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
718 let last_backup
= match &env
.last_backup
{
720 None
=> bail
!("no valid previous backup"),
723 let mut path
= env
.datastore
.snapshot_path(&last_backup
.backup_dir
);
724 path
.push(&archive_name
);
727 let index
: Option
<Box
<dyn IndexFile
>> = match archive_type(&archive_name
)?
{
728 ArchiveType
::FixedIndex
=> {
729 let index
= env
.datastore
.open_fixed_reader(&path
)?
;
730 Some(Box
::new(index
))
732 ArchiveType
::DynamicIndex
=> {
733 let index
= env
.datastore
.open_dynamic_reader(&path
)?
;
734 Some(Box
::new(index
))
738 if let Some(index
) = index
{
739 env
.log(format
!("register chunks in '{}' from previous backup.", archive_name
));
741 for pos
in 0..index
.index_count() {
742 let info
= index
.chunk_info(pos
).unwrap();
743 let size
= info
.range
.end
- info
.range
.start
;
744 env
.register_chunk(info
.digest
, size
as u32)?
;
749 env
.log(format
!("download '{}' from previous backup.", archive_name
));
750 crate::api2
::helpers
::create_download_response(path
).await