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
;
26 pub const ROUTER
: Router
= Router
::new()
27 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
30 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
31 &ApiHandler
::AsyncHttp(&upgrade_to_backup_protocol
),
33 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
35 ("store", false, &DATASTORE_SCHEMA
),
36 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
37 ("backup-id", false, &BACKUP_ID_SCHEMA
),
38 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
39 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
43 // Note: parameter 'store' is no uri parameter, so we need to test inside function body
44 Some("The user needs Datastore.Backup privilege on /datastore/{store} and needs to own the backup group."),
48 fn upgrade_to_backup_protocol(
53 rpcenv
: Box
<dyn RpcEnvironment
>,
54 ) -> ApiResponseFuture
{
57 let debug
= param
["debug"].as_bool().unwrap_or(false);
59 let username
= rpcenv
.get_user().unwrap();
61 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
63 let user_info
= CachedUserInfo
::new()?
;
64 user_info
.check_privs(&username
, &["datastore", &store
], PRIV_DATASTORE_BACKUP
, false)?
;
66 let datastore
= DataStore
::lookup_datastore(&store
)?
;
68 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
69 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
70 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
75 .ok_or_else(|| format_err
!("missing Upgrade header"))?
78 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
79 bail
!("invalid protocol name");
82 if parts
.version
>= http
::version
::Version
::HTTP_2
{
83 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
86 let worker_id
= format
!("{}_{}_{}", store
, backup_type
, backup_id
);
88 let env_type
= rpcenv
.env_type();
90 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
91 let owner
= datastore
.create_backup_group(&backup_group
, &username
)?
;
93 if owner
!= username
{ // only the owner is allowed to create additional snapshots
94 bail
!("backup owner check failed ({} != {})", username
, owner
);
97 let last_backup
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
).unwrap_or(None
);
98 let backup_dir
= BackupDir
::new_with_group(backup_group
, backup_time
);
100 if let Some(last
) = &last_backup
{
101 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
102 bail
!("backup timestamp is older than last backup.");
104 // fixme: abort if last backup is still running - howto test?
105 // Idea: write upid into a file inside snapshot dir. then test if
106 // it is still running here.
109 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
110 if !is_new { bail!("backup directory already exists."); }
112 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
113 let mut env
= BackupEnvironment
::new(
114 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
117 env
.last_backup
= last_backup
;
119 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
121 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
123 let abort_future
= worker
.abort_future();
125 let env2
= env
.clone();
127 let mut req_fut
= req_body
129 .map_err(Error
::from
)
130 .and_then(move |conn
| {
131 env2
.debug("protocol upgrade done");
133 let mut http
= hyper
::server
::conn
::Http
::new();
134 http
.http2_only(true);
135 // increase window size: todo - find optiomal size
136 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
137 http
.http2_initial_stream_window_size(window_size
);
138 http
.http2_initial_connection_window_size(window_size
);
140 http
.serve_connection(conn
, service
)
141 .map_err(Error
::from
)
143 let mut abort_future
= abort_future
144 .map(|_
| Err(format_err
!("task aborted")));
148 req
= req_fut
=> req
,
149 abrt
= abort_future
=> abrt
,
152 match (res
, env
.ensure_finished()) {
154 env
.log("backup finished successfully");
157 (Err(err
), Ok(())) => {
158 // ignore errors after finish
159 env
.log(format
!("backup had errors but finished: {}", err
));
162 (Ok(_
), Err(err
)) => {
163 env
.log(format
!("backup ended and finish failed: {}", err
));
164 env
.log("removing unfinished backup");
165 env
.remove_backup()?
;
168 (Err(err
), Err(_
)) => {
169 env
.log(format
!("backup failed: {}", err
));
170 env
.log("removing failed backup");
171 env
.remove_backup()?
;
178 let response
= Response
::builder()
179 .status(StatusCode
::SWITCHING_PROTOCOLS
)
180 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
181 .body(Body
::empty())?
;
187 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
189 "blob", &Router
::new()
190 .upload(&API_METHOD_UPLOAD_BLOB
)
193 "dynamic_chunk", &Router
::new()
194 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
197 "dynamic_close", &Router
::new()
198 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
201 "dynamic_index", &Router
::new()
202 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
203 .put(&API_METHOD_DYNAMIC_APPEND
)
206 "finish", &Router
::new()
209 &ApiHandler
::Sync(&finish_backup
),
210 &ObjectSchema
::new("Mark backup as finished.", &[])
215 "fixed_chunk", &Router
::new()
216 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
219 "fixed_close", &Router
::new()
220 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
223 "fixed_index", &Router
::new()
224 .post(&API_METHOD_CREATE_FIXED_INDEX
)
225 .put(&API_METHOD_FIXED_APPEND
)
228 "previous", &Router
::new()
229 .download(&API_METHOD_DOWNLOAD_PREVIOUS
)
232 "speedtest", &Router
::new()
233 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
237 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
238 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
239 .subdirs(BACKUP_API_SUBDIRS
);
242 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
243 &ApiHandler
::Sync(&create_dynamic_index
),
245 "Create dynamic chunk index file.",
247 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
252 fn create_dynamic_index(
255 rpcenv
: &mut dyn RpcEnvironment
,
256 ) -> Result
<Value
, Error
> {
258 let env
: &BackupEnvironment
= rpcenv
.as_ref();
260 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
262 let archive_name
= name
.clone();
263 if !archive_name
.ends_with(".didx") {
264 bail
!("wrong archive extension: '{}'", archive_name
);
267 let mut path
= env
.backup_dir
.relative_path();
268 path
.push(archive_name
);
270 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
271 let wid
= env
.register_dynamic_writer(index
, name
)?
;
273 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
279 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
280 &ApiHandler
::Sync(&create_fixed_index
),
282 "Create fixed chunk index file.",
284 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
285 ("size", false, &IntegerSchema
::new("File size.")
289 ("reuse-csum", true, &StringSchema
::new("If set, compare last backup's \
290 csum and reuse index for incremental backup if it matches.").schema()),
295 fn create_fixed_index(
298 rpcenv
: &mut dyn RpcEnvironment
,
299 ) -> Result
<Value
, Error
> {
301 let env
: &BackupEnvironment
= rpcenv
.as_ref();
303 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
304 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
305 let reuse_csum
= param
["reuse-csum"].as_str();
307 let archive_name
= name
.clone();
308 if !archive_name
.ends_with(".fidx") {
309 bail
!("wrong archive extension: '{}'", archive_name
);
312 let mut path
= env
.backup_dir
.relative_path();
313 path
.push(&archive_name
);
315 let chunk_size
= 4096*1024; // todo: ??
317 // do incremental backup if csum is set
318 let mut reader
= None
;
319 let mut incremental
= false;
320 if let Some(csum
) = reuse_csum
{
322 let last_backup
= match &env
.last_backup
{
325 bail
!("cannot reuse index - no previous backup exists");
329 let mut last_path
= last_backup
.backup_dir
.relative_path();
330 last_path
.push(&archive_name
);
332 let index
= match env
.datastore
.open_fixed_reader(last_path
) {
335 bail
!("cannot reuse index - no previous backup exists for archive");
339 let (old_csum
, _
) = index
.compute_csum();
340 let old_csum
= proxmox
::tools
::digest_to_hex(&old_csum
);
341 if old_csum
!= csum
{
342 bail
!("expected csum ({}) doesn't match last backup's ({}), cannot do incremental backup",
346 reader
= Some(index
);
349 let mut writer
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
351 if let Some(reader
) = reader
{
352 writer
.clone_data_from(&reader
)?
;
355 let wid
= env
.register_fixed_writer(writer
, name
, size
, chunk_size
as u32, incremental
)?
;
357 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
363 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
364 &ApiHandler
::Sync(&dynamic_append
),
366 "Append chunk to dynamic index writer.",
371 &IntegerSchema
::new("Dynamic writer ID.")
379 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
385 "Chunk offset list.",
386 &IntegerSchema
::new("Corresponding chunk offsets.")
398 rpcenv
: &mut dyn RpcEnvironment
,
399 ) -> Result
<Value
, Error
> {
401 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
402 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
403 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
405 if offset_list
.len() != digest_list
.len() {
406 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
409 let env
: &BackupEnvironment
= rpcenv
.as_ref();
411 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
413 for (i
, item
) in digest_list
.iter().enumerate() {
414 let digest_str
= item
.as_str().unwrap();
415 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
416 let offset
= offset_list
[i
].as_u64().unwrap();
417 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
419 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
421 env
.debug(format
!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
428 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
429 &ApiHandler
::Sync(&fixed_append
),
431 "Append chunk to fixed index writer.",
436 &IntegerSchema
::new("Fixed writer ID.")
444 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
450 "Chunk offset list.",
451 &IntegerSchema
::new("Corresponding chunk offsets.")
463 rpcenv
: &mut dyn RpcEnvironment
,
464 ) -> Result
<Value
, Error
> {
466 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
467 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
468 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
470 if offset_list
.len() != digest_list
.len() {
471 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
474 let env
: &BackupEnvironment
= rpcenv
.as_ref();
476 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
478 for (i
, item
) in digest_list
.iter().enumerate() {
479 let digest_str
= item
.as_str().unwrap();
480 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
481 let offset
= offset_list
[i
].as_u64().unwrap();
482 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
484 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
486 env
.debug(format
!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
493 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
494 &ApiHandler
::Sync(&close_dynamic_index
),
496 "Close dynamic index writer.",
501 &IntegerSchema
::new("Dynamic writer ID.")
509 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
516 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
520 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
525 fn close_dynamic_index (
528 rpcenv
: &mut dyn RpcEnvironment
,
529 ) -> Result
<Value
, Error
> {
531 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
532 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
533 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
534 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
535 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
537 let env
: &BackupEnvironment
= rpcenv
.as_ref();
539 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
541 env
.log(format
!("successfully closed dynamic index {}", wid
));
547 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
548 &ApiHandler
::Sync(&close_fixed_index
),
550 "Close fixed index writer.",
555 &IntegerSchema
::new("Fixed writer ID.")
563 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks. Ignored for incremental backups.")
570 &IntegerSchema
::new("File size. This is used to verify that the server got all data. Ignored for incremental backups.")
574 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
579 fn close_fixed_index (
582 rpcenv
: &mut dyn RpcEnvironment
,
583 ) -> Result
<Value
, Error
> {
585 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
586 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
587 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
588 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
589 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
591 let env
: &BackupEnvironment
= rpcenv
.as_ref();
593 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
595 env
.log(format
!("successfully closed fixed index {}", wid
));
603 rpcenv
: &mut dyn RpcEnvironment
,
604 ) -> Result
<Value
, Error
> {
606 let env
: &BackupEnvironment
= rpcenv
.as_ref();
608 env
.finish_backup()?
;
609 env
.log("successfully finished backup");
615 pub const API_METHOD_DOWNLOAD_PREVIOUS
: ApiMethod
= ApiMethod
::new(
616 &ApiHandler
::AsyncHttp(&download_previous
),
618 "Download archive from previous backup.",
620 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
625 fn download_previous(
630 rpcenv
: Box
<dyn RpcEnvironment
>,
631 ) -> ApiResponseFuture
{
634 let env
: &BackupEnvironment
= rpcenv
.as_ref();
636 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
638 let last_backup
= match &env
.last_backup
{
640 None
=> bail
!("no previous backup"),
643 env
.log(format
!("download '{}' from previous backup.", archive_name
));
645 let mut path
= env
.datastore
.snapshot_path(&last_backup
.backup_dir
);
646 path
.push(&archive_name
);
648 crate::api2
::helpers
::create_download_response(path
).await