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}
;
10 use proxmox
::api
::router
::SubdirMap
;
11 use proxmox
::api
::schema
::*;
14 use crate::tools
::wrapped_reader_stream
::*;
15 use crate::server
::{WorkerTask, H2Service}
;
17 use crate::api2
::types
::*;
25 pub const ROUTER
: Router
= Router
::new()
26 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
29 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
30 &ApiHandler
::AsyncHttp(&upgrade_to_backup_protocol
),
32 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
34 ("store", false, &DATASTORE_SCHEMA
),
35 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
36 ("backup-id", false, &BACKUP_ID_SCHEMA
),
37 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
38 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
43 fn upgrade_to_backup_protocol(
48 rpcenv
: Box
<dyn RpcEnvironment
>,
49 ) -> ApiResponseFuture
{
52 let debug
= param
["debug"].as_bool().unwrap_or(false);
54 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
55 let datastore
= DataStore
::lookup_datastore(&store
)?
;
57 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
58 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
59 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
64 .ok_or_else(|| format_err
!("missing Upgrade header"))?
67 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
68 bail
!("invalid protocol name");
71 if parts
.version
>= http
::version
::Version
::HTTP_2
{
72 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
75 let worker_id
= format
!("{}_{}_{}", store
, backup_type
, backup_id
);
77 let username
= rpcenv
.get_user().unwrap();
78 let env_type
= rpcenv
.env_type();
80 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
81 let last_backup
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
).unwrap_or(None
);
82 let backup_dir
= BackupDir
::new_with_group(backup_group
, backup_time
);
84 if let Some(last
) = &last_backup
{
85 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
86 bail
!("backup timestamp is older than last backup.");
88 // fixme: abort if last backup is still running - howto test?
89 // Idea: write upid into a file inside snapshot dir. then test if
90 // it is still running here.
93 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
94 if !is_new { bail!("backup directorty already exists."); }
96 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
97 let mut env
= BackupEnvironment
::new(
98 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
101 env
.last_backup
= last_backup
;
103 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
105 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
107 let abort_future
= worker
.abort_future();
109 let env2
= env
.clone();
110 let env3
= env
.clone();
112 let req_fut
= req_body
114 .map_err(Error
::from
)
115 .and_then(move |conn
| {
116 env3
.debug("protocol upgrade done");
118 let mut http
= hyper
::server
::conn
::Http
::new();
119 http
.http2_only(true);
120 // increase window size: todo - find optiomal size
121 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
122 http
.http2_initial_stream_window_size(window_size
);
123 http
.http2_initial_connection_window_size(window_size
);
125 http
.serve_connection(conn
, service
)
126 .map_err(Error
::from
)
128 let abort_future
= abort_future
129 .map(|_
| Err(format_err
!("task aborted")));
131 use futures
::future
::Either
;
132 future
::select(req_fut
, abort_future
)
133 .map(|res
| match res
{
134 Either
::Left((Ok(res
), _
)) => Ok(res
),
135 Either
::Left((Err(err
), _
)) => Err(err
),
136 Either
::Right((Ok(res
), _
)) => Ok(res
),
137 Either
::Right((Err(err
), _
)) => Err(err
),
139 .and_then(move |_result
| async
move {
140 env
.ensure_finished()?
;
141 env
.log("backup finished sucessfully");
144 .then(move |result
| async
move {
145 if let Err(err
) = result
{
146 match env2
.ensure_finished() {
147 Ok(()) => {}
, // ignore error after finish
149 env2
.log(format
!("backup failed: {}", err
));
150 env2
.log("removing failed backup");
151 env2
.remove_backup()?
;
160 let response
= Response
::builder()
161 .status(StatusCode
::SWITCHING_PROTOCOLS
)
162 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
163 .body(Body
::empty())?
;
169 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
171 "blob", &Router
::new()
172 .upload(&API_METHOD_UPLOAD_BLOB
)
175 "dynamic_chunk", &Router
::new()
176 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
179 "dynamic_close", &Router
::new()
180 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
183 "dynamic_index", &Router
::new()
184 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
185 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
186 .put(&API_METHOD_DYNAMIC_APPEND
)
189 "finish", &Router
::new()
192 &ApiHandler
::Sync(&finish_backup
),
193 &ObjectSchema
::new("Mark backup as finished.", &[])
198 "fixed_chunk", &Router
::new()
199 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
202 "fixed_close", &Router
::new()
203 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
206 "fixed_index", &Router
::new()
207 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
208 .post(&API_METHOD_CREATE_FIXED_INDEX
)
209 .put(&API_METHOD_FIXED_APPEND
)
212 "speedtest", &Router
::new()
213 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
217 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
218 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
219 .subdirs(BACKUP_API_SUBDIRS
);
222 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
223 &ApiHandler
::Sync(&create_dynamic_index
),
225 "Create dynamic chunk index file.",
227 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
232 fn create_dynamic_index(
235 rpcenv
: &mut dyn RpcEnvironment
,
236 ) -> Result
<Value
, Error
> {
238 let env
: &BackupEnvironment
= rpcenv
.as_ref();
240 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
242 let archive_name
= name
.clone();
243 if !archive_name
.ends_with(".didx") {
244 bail
!("wrong archive extension: '{}'", archive_name
);
247 let mut path
= env
.backup_dir
.relative_path();
248 path
.push(archive_name
);
250 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
251 let wid
= env
.register_dynamic_writer(index
, name
)?
;
253 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
259 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
260 &ApiHandler
::Sync(&create_fixed_index
),
262 "Create fixed chunk index file.",
264 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
265 ("size", false, &IntegerSchema
::new("File size.")
273 fn create_fixed_index(
276 rpcenv
: &mut dyn RpcEnvironment
,
277 ) -> Result
<Value
, Error
> {
279 let env
: &BackupEnvironment
= rpcenv
.as_ref();
281 println
!("PARAM: {:?}", param
);
283 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
284 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
286 let archive_name
= name
.clone();
287 if !archive_name
.ends_with(".fidx") {
288 bail
!("wrong archive extension: '{}'", archive_name
);
291 let mut path
= env
.backup_dir
.relative_path();
292 path
.push(archive_name
);
294 let chunk_size
= 4096*1024; // todo: ??
296 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
297 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
299 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
305 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
306 &ApiHandler
::Sync(&dynamic_append
),
308 "Append chunk to dynamic index writer.",
313 &IntegerSchema
::new("Dynamic writer ID.")
321 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
327 "Chunk offset list.",
328 &IntegerSchema
::new("Corresponding chunk offsets.")
340 rpcenv
: &mut dyn RpcEnvironment
,
341 ) -> Result
<Value
, Error
> {
343 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
344 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
345 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
347 if offset_list
.len() != digest_list
.len() {
348 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
351 let env
: &BackupEnvironment
= rpcenv
.as_ref();
353 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
355 for (i
, item
) in digest_list
.iter().enumerate() {
356 let digest_str
= item
.as_str().unwrap();
357 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
358 let offset
= offset_list
[i
].as_u64().unwrap();
359 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
361 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
363 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
370 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
371 &ApiHandler
::Sync(&fixed_append
),
373 "Append chunk to fixed index writer.",
378 &IntegerSchema
::new("Fixed writer ID.")
386 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
392 "Chunk offset list.",
393 &IntegerSchema
::new("Corresponding chunk offsets.")
405 rpcenv
: &mut dyn RpcEnvironment
,
406 ) -> Result
<Value
, Error
> {
408 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
409 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
410 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
412 if offset_list
.len() != digest_list
.len() {
413 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
416 let env
: &BackupEnvironment
= rpcenv
.as_ref();
418 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
420 for (i
, item
) in digest_list
.iter().enumerate() {
421 let digest_str
= item
.as_str().unwrap();
422 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
423 let offset
= offset_list
[i
].as_u64().unwrap();
424 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
426 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
428 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
435 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
436 &ApiHandler
::Sync(&close_dynamic_index
),
438 "Close dynamic index writer.",
443 &IntegerSchema
::new("Dynamic writer ID.")
451 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
458 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
462 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
467 fn close_dynamic_index (
470 rpcenv
: &mut dyn RpcEnvironment
,
471 ) -> Result
<Value
, Error
> {
473 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
474 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
475 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
476 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
477 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
479 let env
: &BackupEnvironment
= rpcenv
.as_ref();
481 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
483 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
489 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
490 &ApiHandler
::Sync(&close_fixed_index
),
492 "Close fixed index writer.",
497 &IntegerSchema
::new("Fixed writer ID.")
505 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
512 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
516 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
521 fn close_fixed_index (
524 rpcenv
: &mut dyn RpcEnvironment
,
525 ) -> Result
<Value
, Error
> {
527 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
528 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
529 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
530 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
531 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
533 let env
: &BackupEnvironment
= rpcenv
.as_ref();
535 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
537 env
.log(format
!("sucessfully closed fixed index {}", wid
));
545 rpcenv
: &mut dyn RpcEnvironment
,
546 ) -> Result
<Value
, Error
> {
548 let env
: &BackupEnvironment
= rpcenv
.as_ref();
550 env
.finish_backup()?
;
551 env
.log("sucessfully finished backup");
557 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
558 &ApiHandler
::AsyncHttp(&dynamic_chunk_index
),
561 Download the dynamic chunk index from the previous backup.
562 Simply returns an empty list if this is the first backup.
565 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
570 fn dynamic_chunk_index(
575 rpcenv
: Box
<dyn RpcEnvironment
>,
576 ) -> ApiResponseFuture
{
579 let env
: &BackupEnvironment
= rpcenv
.as_ref();
581 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
583 if !archive_name
.ends_with(".didx") {
584 bail
!("wrong archive extension: '{}'", archive_name
);
587 let empty_response
= {
589 .status(StatusCode
::OK
)
590 .body(Body
::empty())?
593 let last_backup
= match &env
.last_backup
{
595 None
=> return Ok(empty_response
),
598 let mut path
= last_backup
.backup_dir
.relative_path();
599 path
.push(&archive_name
);
601 let index
= match env
.datastore
.open_dynamic_reader(path
) {
604 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
605 return Ok(empty_response
);
609 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
611 let count
= index
.index_count();
612 for pos
in 0..count
{
613 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
614 let size
= (end
- start
) as u32;
615 env
.register_chunk(digest
, size
)?
;
618 let reader
= DigestListEncoder
::new(Box
::new(index
));
620 let stream
= WrappedReaderStream
::new(reader
);
622 // fixme: set size, content type?
623 let response
= http
::Response
::builder()
625 .body(Body
::wrap_stream(stream
))?
;
632 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
633 &ApiHandler
::AsyncHttp(&fixed_chunk_index
),
636 Download the fixed chunk index from the previous backup.
637 Simply returns an empty list if this is the first backup.
640 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
645 fn fixed_chunk_index(
650 rpcenv
: Box
<dyn RpcEnvironment
>,
651 ) -> ApiResponseFuture
{
654 let env
: &BackupEnvironment
= rpcenv
.as_ref();
656 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
658 if !archive_name
.ends_with(".fidx") {
659 bail
!("wrong archive extension: '{}'", archive_name
);
662 let empty_response
= {
664 .status(StatusCode
::OK
)
665 .body(Body
::empty())?
668 let last_backup
= match &env
.last_backup
{
670 None
=> return Ok(empty_response
),
673 let mut path
= last_backup
.backup_dir
.relative_path();
674 path
.push(&archive_name
);
676 let index
= match env
.datastore
.open_fixed_reader(path
) {
679 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
680 return Ok(empty_response
);
684 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
686 let count
= index
.index_count();
687 let image_size
= index
.index_bytes();
688 for pos
in 0..count
{
689 let digest
= index
.index_digest(pos
).unwrap();
690 // Note: last chunk can be smaller
691 let start
= (pos
*index
.chunk_size
) as u64;
692 let mut end
= start
+ index
.chunk_size
as u64;
693 if end
> image_size { end = image_size; }
694 let size
= (end
- start
) as u32;
695 env
.register_chunk(*digest
, size
)?
;
698 let reader
= DigestListEncoder
::new(Box
::new(index
));
700 let stream
= WrappedReaderStream
::new(reader
);
702 // fixme: set size, content type?
703 let response
= http
::Response
::builder()
705 .body(Body
::wrap_stream(stream
))?
;