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
::*;
13 use crate::tools
::{self, WrappedReaderStream}
;
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 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
203 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
204 .put(&API_METHOD_DYNAMIC_APPEND
)
207 "finish", &Router
::new()
210 &ApiHandler
::Sync(&finish_backup
),
211 &ObjectSchema
::new("Mark backup as finished.", &[])
216 "fixed_chunk", &Router
::new()
217 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
220 "fixed_close", &Router
::new()
221 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
224 "fixed_index", &Router
::new()
225 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
226 .post(&API_METHOD_CREATE_FIXED_INDEX
)
227 .put(&API_METHOD_FIXED_APPEND
)
230 "speedtest", &Router
::new()
231 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
235 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
236 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
237 .subdirs(BACKUP_API_SUBDIRS
);
240 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
241 &ApiHandler
::Sync(&create_dynamic_index
),
243 "Create dynamic chunk index file.",
245 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
250 fn create_dynamic_index(
253 rpcenv
: &mut dyn RpcEnvironment
,
254 ) -> Result
<Value
, Error
> {
256 let env
: &BackupEnvironment
= rpcenv
.as_ref();
258 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
260 let archive_name
= name
.clone();
261 if !archive_name
.ends_with(".didx") {
262 bail
!("wrong archive extension: '{}'", archive_name
);
265 let mut path
= env
.backup_dir
.relative_path();
266 path
.push(archive_name
);
268 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
269 let wid
= env
.register_dynamic_writer(index
, name
)?
;
271 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
277 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
278 &ApiHandler
::Sync(&create_fixed_index
),
280 "Create fixed chunk index file.",
282 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
283 ("size", false, &IntegerSchema
::new("File size.")
291 fn create_fixed_index(
294 rpcenv
: &mut dyn RpcEnvironment
,
295 ) -> Result
<Value
, Error
> {
297 let env
: &BackupEnvironment
= rpcenv
.as_ref();
299 println
!("PARAM: {:?}", param
);
301 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
302 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
304 let archive_name
= name
.clone();
305 if !archive_name
.ends_with(".fidx") {
306 bail
!("wrong archive extension: '{}'", archive_name
);
309 let mut path
= env
.backup_dir
.relative_path();
310 path
.push(archive_name
);
312 let chunk_size
= 4096*1024; // todo: ??
314 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
315 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
317 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
323 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
324 &ApiHandler
::Sync(&dynamic_append
),
326 "Append chunk to dynamic index writer.",
331 &IntegerSchema
::new("Dynamic writer ID.")
339 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
345 "Chunk offset list.",
346 &IntegerSchema
::new("Corresponding chunk offsets.")
358 rpcenv
: &mut dyn RpcEnvironment
,
359 ) -> Result
<Value
, Error
> {
361 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
362 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
363 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
365 if offset_list
.len() != digest_list
.len() {
366 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
369 let env
: &BackupEnvironment
= rpcenv
.as_ref();
371 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
373 for (i
, item
) in digest_list
.iter().enumerate() {
374 let digest_str
= item
.as_str().unwrap();
375 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
376 let offset
= offset_list
[i
].as_u64().unwrap();
377 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
379 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
381 env
.debug(format
!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
388 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
389 &ApiHandler
::Sync(&fixed_append
),
391 "Append chunk to fixed index writer.",
396 &IntegerSchema
::new("Fixed writer ID.")
404 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
410 "Chunk offset list.",
411 &IntegerSchema
::new("Corresponding chunk offsets.")
423 rpcenv
: &mut dyn RpcEnvironment
,
424 ) -> Result
<Value
, Error
> {
426 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
427 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
428 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
430 if offset_list
.len() != digest_list
.len() {
431 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
434 let env
: &BackupEnvironment
= rpcenv
.as_ref();
436 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
438 for (i
, item
) in digest_list
.iter().enumerate() {
439 let digest_str
= item
.as_str().unwrap();
440 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
441 let offset
= offset_list
[i
].as_u64().unwrap();
442 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
444 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
446 env
.debug(format
!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
453 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
454 &ApiHandler
::Sync(&close_dynamic_index
),
456 "Close dynamic index writer.",
461 &IntegerSchema
::new("Dynamic writer ID.")
469 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
476 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
480 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
485 fn close_dynamic_index (
488 rpcenv
: &mut dyn RpcEnvironment
,
489 ) -> Result
<Value
, Error
> {
491 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
492 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
493 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
494 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
495 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
497 let env
: &BackupEnvironment
= rpcenv
.as_ref();
499 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
501 env
.log(format
!("successfully closed dynamic index {}", wid
));
507 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
508 &ApiHandler
::Sync(&close_fixed_index
),
510 "Close fixed index writer.",
515 &IntegerSchema
::new("Fixed writer ID.")
523 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
530 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
534 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
539 fn close_fixed_index (
542 rpcenv
: &mut dyn RpcEnvironment
,
543 ) -> Result
<Value
, Error
> {
545 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
546 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
547 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
548 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
549 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
551 let env
: &BackupEnvironment
= rpcenv
.as_ref();
553 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
555 env
.log(format
!("successfully closed fixed index {}", wid
));
563 rpcenv
: &mut dyn RpcEnvironment
,
564 ) -> Result
<Value
, Error
> {
566 let env
: &BackupEnvironment
= rpcenv
.as_ref();
568 env
.finish_backup()?
;
569 env
.log("successfully finished backup");
575 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
576 &ApiHandler
::AsyncHttp(&dynamic_chunk_index
),
579 Download the dynamic chunk index from the previous backup.
580 Simply returns an empty list if this is the first backup.
583 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
588 fn dynamic_chunk_index(
593 rpcenv
: Box
<dyn RpcEnvironment
>,
594 ) -> ApiResponseFuture
{
597 let env
: &BackupEnvironment
= rpcenv
.as_ref();
599 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
601 if !archive_name
.ends_with(".didx") {
602 bail
!("wrong archive extension: '{}'", archive_name
);
605 let empty_response
= {
607 .status(StatusCode
::OK
)
608 .body(Body
::empty())?
611 let last_backup
= match &env
.last_backup
{
613 None
=> return Ok(empty_response
),
616 let mut path
= last_backup
.backup_dir
.relative_path();
617 path
.push(&archive_name
);
619 let index
= match env
.datastore
.open_dynamic_reader(path
) {
622 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
623 return Ok(empty_response
);
627 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
629 let count
= index
.index_count();
630 for pos
in 0..count
{
631 let info
= index
.chunk_info(pos
)?
;
632 let size
= info
.size() as u32;
633 env
.register_chunk(info
.digest
, size
)?
;
636 let reader
= DigestListEncoder
::new(Box
::new(index
));
638 let stream
= WrappedReaderStream
::new(reader
);
640 // fixme: set size, content type?
641 let response
= http
::Response
::builder()
643 .body(Body
::wrap_stream(stream
))?
;
650 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
651 &ApiHandler
::AsyncHttp(&fixed_chunk_index
),
654 Download the fixed chunk index from the previous backup.
655 Simply returns an empty list if this is the first backup.
658 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
663 fn fixed_chunk_index(
668 rpcenv
: Box
<dyn RpcEnvironment
>,
669 ) -> ApiResponseFuture
{
672 let env
: &BackupEnvironment
= rpcenv
.as_ref();
674 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
676 if !archive_name
.ends_with(".fidx") {
677 bail
!("wrong archive extension: '{}'", archive_name
);
680 let empty_response
= {
682 .status(StatusCode
::OK
)
683 .body(Body
::empty())?
686 let last_backup
= match &env
.last_backup
{
688 None
=> return Ok(empty_response
),
691 let mut path
= last_backup
.backup_dir
.relative_path();
692 path
.push(&archive_name
);
694 let index
= match env
.datastore
.open_fixed_reader(path
) {
697 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
698 return Ok(empty_response
);
702 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
704 let count
= index
.index_count();
705 let image_size
= index
.index_bytes();
706 for pos
in 0..count
{
707 let digest
= index
.index_digest(pos
).unwrap();
708 // Note: last chunk can be smaller
709 let start
= (pos
*index
.chunk_size
) as u64;
710 let mut end
= start
+ index
.chunk_size
as u64;
711 if end
> image_size { end = image_size; }
712 let size
= (end
- start
) as u32;
713 env
.register_chunk(*digest
, size
)?
;
716 let reader
= DigestListEncoder
::new(Box
::new(index
));
718 let stream
= WrappedReaderStream
::new(reader
);
720 // fixme: set size, content type?
721 let response
= http
::Response
::builder()
723 .body(Body
::wrap_stream(stream
))?
;