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}
;
9 use proxmox
::api
::{api, list_subdirs_api_method}
;
10 use proxmox
::api
::{ApiFuture, ApiHandler, ApiMethod, Router, RpcEnvironment}
;
11 use proxmox
::api
::router
::SubdirMap
;
12 use proxmox
::api
::schema
::*;
15 use crate::tools
::wrapped_reader_stream
::*;
16 use crate::server
::{WorkerTask, H2Service}
;
18 use crate::api2
::types
::*;
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, &StringSchema
::new("Datastore name.").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()),
44 fn upgrade_to_backup_protocol(
49 rpcenv
: Box
<dyn RpcEnvironment
>,
53 let debug
= param
["debug"].as_bool().unwrap_or(false);
55 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
56 let datastore
= DataStore
::lookup_datastore(&store
)?
;
58 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
59 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
60 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
65 .ok_or_else(|| format_err
!("missing Upgrade header"))?
68 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
69 bail
!("invalid protocol name");
72 if parts
.version
>= http
::version
::Version
::HTTP_2
{
73 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
76 let worker_id
= format
!("{}_{}_{}", store
, backup_type
, backup_id
);
78 let username
= rpcenv
.get_user().unwrap();
79 let env_type
= rpcenv
.env_type();
81 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
82 let last_backup
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
).unwrap_or(None
);
83 let backup_dir
= BackupDir
::new_with_group(backup_group
, backup_time
);
85 if let Some(last
) = &last_backup
{
86 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
87 bail
!("backup timestamp is older than last backup.");
91 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
92 if !is_new { bail!("backup directorty already exists."); }
94 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
95 let mut env
= BackupEnvironment
::new(
96 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
99 env
.last_backup
= last_backup
;
101 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
103 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
105 let abort_future
= worker
.abort_future();
107 let env2
= env
.clone();
108 let env3
= env
.clone();
110 let req_fut
= req_body
112 .map_err(Error
::from
)
113 .and_then(move |conn
| {
114 env3
.debug("protocol upgrade done");
116 let mut http
= hyper
::server
::conn
::Http
::new();
117 http
.http2_only(true);
118 // increase window size: todo - find optiomal size
119 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
120 http
.http2_initial_stream_window_size(window_size
);
121 http
.http2_initial_connection_window_size(window_size
);
123 http
.serve_connection(conn
, service
)
124 .map_err(Error
::from
)
126 let abort_future
= abort_future
127 .map(|_
| Err(format_err
!("task aborted")));
129 use futures
::future
::Either
;
130 future
::select(req_fut
, abort_future
)
131 .map(|res
| match res
{
132 Either
::Left((Ok(res
), _
)) => Ok(res
),
133 Either
::Left((Err(err
), _
)) => Err(err
),
134 Either
::Right((Ok(res
), _
)) => Ok(res
),
135 Either
::Right((Err(err
), _
)) => Err(err
),
137 .and_then(move |_result
| async
move {
138 env
.ensure_finished()?
;
139 env
.log("backup finished sucessfully");
142 .then(move |result
| async
move {
143 if let Err(err
) = result
{
144 match env2
.ensure_finished() {
145 Ok(()) => {}
, // ignore error after finish
147 env2
.log(format
!("backup failed: {}", err
));
148 env2
.log("removing failed backup");
149 env2
.remove_backup()?
;
158 let response
= Response
::builder()
159 .status(StatusCode
::SWITCHING_PROTOCOLS
)
160 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
161 .body(Body
::empty())?
;
167 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
169 "blob", &Router
::new()
170 .upload(&API_METHOD_UPLOAD_BLOB
)
173 "dynamic_chunk", &Router
::new()
174 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
177 "dynamic_close", &Router
::new()
178 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
181 "dynamic_index", &Router
::new()
182 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
183 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
184 .put(&API_METHOD_DYNAMIC_APPEND
)
187 "finish", &Router
::new()
190 &ApiHandler
::Sync(&finish_backup
),
191 &ObjectSchema
::new("Mark backup as finished.", &[])
196 "fixed_chunk", &Router
::new()
197 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
200 "fixed_close", &Router
::new()
201 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
204 "fixed_index", &Router
::new()
205 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
206 .post(&API_METHOD_CREATE_FIXED_INDEX
)
207 .put(&API_METHOD_FIXED_APPEND
)
210 "speedtest", &Router
::new()
211 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
215 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
216 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
217 .subdirs(BACKUP_API_SUBDIRS
);
223 schema
: crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
,
228 /// Create dynamic chunk index file.
229 fn create_dynamic_index(
231 rpcenv
: &mut dyn RpcEnvironment
,
232 ) -> Result
<Value
, Error
> {
234 let env
: &BackupEnvironment
= rpcenv
.as_ref();
236 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
238 let archive_name
= name
.clone();
239 if !archive_name
.ends_with(".didx") {
240 bail
!("wrong archive extension: '{}'", archive_name
);
243 let mut path
= env
.backup_dir
.relative_path();
244 path
.push(archive_name
);
246 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
247 let wid
= env
.register_dynamic_writer(index
, name
)?
;
249 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
255 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
256 &ApiHandler
::Sync(&create_fixed_index
),
258 "Create fixed chunk index file.",
260 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
261 ("size", false, &IntegerSchema
::new("File size.")
269 fn create_fixed_index(
272 rpcenv
: &mut dyn RpcEnvironment
,
273 ) -> Result
<Value
, Error
> {
275 let env
: &BackupEnvironment
= rpcenv
.as_ref();
277 println
!("PARAM: {:?}", param
);
279 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
280 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
282 let archive_name
= name
.clone();
283 if !archive_name
.ends_with(".fidx") {
284 bail
!("wrong archive extension: '{}'", archive_name
);
287 let mut path
= env
.backup_dir
.relative_path();
288 path
.push(archive_name
);
290 let chunk_size
= 4096*1024; // todo: ??
292 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
293 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
295 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
301 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
302 &ApiHandler
::Sync(&dynamic_append
),
304 "Append chunk to dynamic index writer.",
309 &IntegerSchema
::new("Dynamic writer ID.")
317 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
323 "Chunk offset list.",
324 &IntegerSchema
::new("Corresponding chunk offsets.")
336 rpcenv
: &mut dyn RpcEnvironment
,
337 ) -> Result
<Value
, Error
> {
339 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
340 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
341 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
343 if offset_list
.len() != digest_list
.len() {
344 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
347 let env
: &BackupEnvironment
= rpcenv
.as_ref();
349 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
351 for (i
, item
) in digest_list
.iter().enumerate() {
352 let digest_str
= item
.as_str().unwrap();
353 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
354 let offset
= offset_list
[i
].as_u64().unwrap();
355 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
357 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
359 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
366 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
367 &ApiHandler
::Sync(&fixed_append
),
369 "Append chunk to fixed index writer.",
374 &IntegerSchema
::new("Fixed writer ID.")
382 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
388 "Chunk offset list.",
389 &IntegerSchema
::new("Corresponding chunk offsets.")
401 rpcenv
: &mut dyn RpcEnvironment
,
402 ) -> Result
<Value
, Error
> {
404 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
405 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
406 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
408 if offset_list
.len() != digest_list
.len() {
409 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
412 let env
: &BackupEnvironment
= rpcenv
.as_ref();
414 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
416 for (i
, item
) in digest_list
.iter().enumerate() {
417 let digest_str
= item
.as_str().unwrap();
418 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
419 let offset
= offset_list
[i
].as_u64().unwrap();
420 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
422 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
424 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
431 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
432 &ApiHandler
::Sync(&close_dynamic_index
),
434 "Close dynamic index writer.",
439 &IntegerSchema
::new("Dynamic writer ID.")
447 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
454 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
458 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
463 fn close_dynamic_index (
466 rpcenv
: &mut dyn RpcEnvironment
,
467 ) -> Result
<Value
, Error
> {
469 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
470 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
471 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
472 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
473 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
475 let env
: &BackupEnvironment
= rpcenv
.as_ref();
477 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
479 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
485 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
486 &ApiHandler
::Sync(&close_fixed_index
),
488 "Close fixed index writer.",
493 &IntegerSchema
::new("Fixed writer ID.")
501 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
508 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
512 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
517 fn close_fixed_index (
520 rpcenv
: &mut dyn RpcEnvironment
,
521 ) -> Result
<Value
, Error
> {
523 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
524 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
525 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
526 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
527 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
529 let env
: &BackupEnvironment
= rpcenv
.as_ref();
531 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
533 env
.log(format
!("sucessfully closed fixed index {}", wid
));
541 rpcenv
: &mut dyn RpcEnvironment
,
542 ) -> Result
<Value
, Error
> {
544 let env
: &BackupEnvironment
= rpcenv
.as_ref();
546 env
.finish_backup()?
;
547 env
.log("sucessfully finished backup");
553 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
554 &ApiHandler
::AsyncHttp(&dynamic_chunk_index
),
557 Download the dynamic chunk index from the previous backup.
558 Simply returns an empty list if this is the first backup.
561 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
566 fn dynamic_chunk_index(
571 rpcenv
: Box
<dyn RpcEnvironment
>,
575 let env
: &BackupEnvironment
= rpcenv
.as_ref();
577 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
579 if !archive_name
.ends_with(".didx") {
580 bail
!("wrong archive extension: '{}'", archive_name
);
583 let empty_response
= {
585 .status(StatusCode
::OK
)
586 .body(Body
::empty())?
589 let last_backup
= match &env
.last_backup
{
591 None
=> return Ok(empty_response
),
594 let mut path
= last_backup
.backup_dir
.relative_path();
595 path
.push(&archive_name
);
597 let index
= match env
.datastore
.open_dynamic_reader(path
) {
600 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
601 return Ok(empty_response
);
605 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
607 let count
= index
.index_count();
608 for pos
in 0..count
{
609 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
610 let size
= (end
- start
) as u32;
611 env
.register_chunk(digest
, size
)?
;
614 let reader
= DigestListEncoder
::new(Box
::new(index
));
616 let stream
= WrappedReaderStream
::new(reader
);
618 // fixme: set size, content type?
619 let response
= http
::Response
::builder()
621 .body(Body
::wrap_stream(stream
))?
;
628 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
629 &ApiHandler
::AsyncHttp(&fixed_chunk_index
),
632 Download the fixed chunk index from the previous backup.
633 Simply returns an empty list if this is the first backup.
636 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
641 fn fixed_chunk_index(
646 rpcenv
: Box
<dyn RpcEnvironment
>,
650 let env
: &BackupEnvironment
= rpcenv
.as_ref();
652 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
654 if !archive_name
.ends_with(".fidx") {
655 bail
!("wrong archive extension: '{}'", archive_name
);
658 let empty_response
= {
660 .status(StatusCode
::OK
)
661 .body(Body
::empty())?
664 let last_backup
= match &env
.last_backup
{
666 None
=> return Ok(empty_response
),
669 let mut path
= last_backup
.backup_dir
.relative_path();
670 path
.push(&archive_name
);
672 let index
= match env
.datastore
.open_fixed_reader(path
) {
675 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
676 return Ok(empty_response
);
680 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
682 let count
= index
.index_count();
683 let image_size
= index
.index_bytes();
684 for pos
in 0..count
{
685 let digest
= index
.index_digest(pos
).unwrap();
686 // Note: last chunk can be smaller
687 let start
= (pos
*index
.chunk_size
) as u64;
688 let mut end
= start
+ index
.chunk_size
as u64;
689 if end
> image_size { end = image_size; }
690 let size
= (end
- start
) as u32;
691 env
.register_chunk(*digest
, size
)?
;
694 let reader
= DigestListEncoder
::new(Box
::new(index
));
696 let stream
= WrappedReaderStream
::new(reader
);
698 // fixme: set size, content type?
699 let response
= http
::Response
::builder()
701 .body(Body
::wrap_stream(stream
))?
;