2 use lazy_static
::lazy_static
;
7 use hyper
::header
::{HeaderValue, UPGRADE}
;
8 use hyper
::{Body, Response, StatusCode}
;
9 use hyper
::http
::request
::Parts
;
10 use chrono
::{Local, TimeZone}
;
12 use serde_json
::{json, Value}
;
15 use crate::tools
::wrapped_reader_stream
::*;
16 use crate::api_schema
::router
::*;
17 use crate::api_schema
::*;
18 use crate::server
::{WorkerTask, H2Service}
;
20 use crate::api2
::types
::*;
28 pub fn router() -> Router
{
30 .upgrade(api_method_upgrade_backup())
33 pub fn api_method_upgrade_backup() -> ApiAsyncMethod
{
35 upgrade_to_backup_protocol
,
36 ObjectSchema
::new(concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."))
37 .required("store", StringSchema
::new("Datastore name."))
38 .required("backup-type", StringSchema
::new("Backup type.")
39 .format(Arc
::new(ApiStringFormat
::Enum(&["vm", "ct", "host"]))))
40 .required("backup-id", StringSchema
::new("Backup ID."))
41 .optional("debug", BooleanSchema
::new("Enable verbose debug logging."))
45 fn upgrade_to_backup_protocol(
49 _info
: &ApiAsyncMethod
,
50 rpcenv
: Box
<dyn RpcEnvironment
>,
51 ) -> Result
<BoxFut
, Error
> {
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
= Local
.timestamp(Local
::now().timestamp(), 0);
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
.timestamp());
85 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
86 if !is_new { bail!("backup directorty already exists."); }
88 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
89 let mut env
= BackupEnvironment
::new(
90 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
93 env
.last_backup
= last_backup
;
95 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
97 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_ROUTER
, debug
);
99 let abort_future
= worker
.abort_future();
101 let env2
= env
.clone();
102 let env3
= env
.clone();
106 .map_err(Error
::from
)
107 .and_then(move |conn
| {
108 env3
.debug("protocol upgrade done");
110 let mut http
= hyper
::server
::conn
::Http
::new();
111 http
.http2_only(true);
112 // increase window size: todo - find optiomal size
113 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
114 http
.http2_initial_stream_window_size(window_size
);
115 http
.http2_initial_connection_window_size(window_size
);
117 http
.serve_connection(conn
, service
)
118 .map_err(Error
::from
)
120 .select(abort_future
.map_err(|_
| {}
).then(move |_
| { bail!("task aborted"); }
))
121 .map_err(|(err
, _
)| err
)
122 .and_then(move |(_result
, _
)| {
123 env
.ensure_finished()?
;
124 env
.log("backup finished sucessfully");
127 .then(move |result
| {
128 if let Err(err
) = result
{
129 match env2
.ensure_finished() {
130 Ok(()) => {}
, // ignore error after finish
132 env2
.log(format
!("backup failed: {}", err
));
133 env2
.log("removing failed backup");
134 env2
.remove_backup()?
;
143 let response
= Response
::builder()
144 .status(StatusCode
::SWITCHING_PROTOCOLS
)
145 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
146 .body(Body
::empty())?
;
148 Ok(Box
::new(futures
::future
::ok(response
)))
152 static ref BACKUP_ROUTER
: Router
= backup_api();
155 pub fn backup_api() -> Router
{
157 let router
= Router
::new()
159 "blob", Router
::new()
160 .upload(api_method_upload_blob())
163 "dynamic_chunk", Router
::new()
164 .upload(api_method_upload_dynamic_chunk())
167 "dynamic_index", Router
::new()
168 .download(api_method_dynamic_chunk_index())
169 .post(api_method_create_dynamic_index())
170 .put(api_method_dynamic_append())
173 "dynamic_close", Router
::new()
174 .post(api_method_close_dynamic_index())
177 "fixed_chunk", Router
::new()
178 .upload(api_method_upload_fixed_chunk())
181 "fixed_index", Router
::new()
182 .download(api_method_fixed_chunk_index())
183 .post(api_method_create_fixed_index())
184 .put(api_method_fixed_append())
187 "fixed_close", Router
::new()
188 .post(api_method_close_fixed_index())
191 "finish", Router
::new()
195 ObjectSchema
::new("Mark backup as finished.")
200 "speedtest", Router
::new()
201 .upload(api_method_upload_speedtest())
208 pub fn api_method_create_dynamic_index() -> ApiMethod
{
210 create_dynamic_index
,
211 ObjectSchema
::new("Create dynamic chunk index file.")
212 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
216 fn create_dynamic_index(
219 rpcenv
: &mut dyn RpcEnvironment
,
220 ) -> Result
<Value
, Error
> {
222 let env
: &BackupEnvironment
= rpcenv
.as_ref();
224 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
226 let mut archive_name
= name
.clone();
227 if !archive_name
.ends_with(".pxar") {
228 bail
!("wrong archive extension: '{}'", archive_name
);
230 archive_name
.push_str(".didx");
233 let mut path
= env
.backup_dir
.relative_path();
234 path
.push(archive_name
);
236 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
237 let wid
= env
.register_dynamic_writer(index
, name
)?
;
239 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
244 pub fn api_method_create_fixed_index() -> ApiMethod
{
247 ObjectSchema
::new("Create fixed chunk index file.")
248 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
249 .required("size", IntegerSchema
::new("File size.")
255 fn create_fixed_index(
258 rpcenv
: &mut dyn RpcEnvironment
,
259 ) -> Result
<Value
, Error
> {
261 let env
: &BackupEnvironment
= rpcenv
.as_ref();
263 println
!("PARAM: {:?}", param
);
265 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
266 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
268 let mut archive_name
= name
.clone();
269 if !archive_name
.ends_with(".img") {
270 bail
!("wrong archive extension: '{}'", archive_name
);
272 archive_name
.push_str(".fidx");
275 let mut path
= env
.backup_dir
.relative_path();
276 path
.push(archive_name
);
278 let chunk_size
= 4096*1024; // todo: ??
280 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
281 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
283 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
288 pub fn api_method_dynamic_append() -> ApiMethod
{
291 ObjectSchema
::new("Append chunk to dynamic index writer.")
292 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
296 .required("digest-list", ArraySchema
::new(
297 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
299 .required("offset-list", ArraySchema
::new(
300 "Chunk offset list.",
301 IntegerSchema
::new("Corresponding chunk offsets.")
311 rpcenv
: &mut dyn RpcEnvironment
,
312 ) -> Result
<Value
, Error
> {
314 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
315 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
316 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
318 if offset_list
.len() != digest_list
.len() {
319 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
322 let env
: &BackupEnvironment
= rpcenv
.as_ref();
324 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
326 for (i
, item
) in digest_list
.iter().enumerate() {
327 let digest_str
= item
.as_str().unwrap();
328 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
329 let offset
= offset_list
[i
].as_u64().unwrap();
330 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
332 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
334 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
340 pub fn api_method_fixed_append() -> ApiMethod
{
343 ObjectSchema
::new("Append chunk to fixed index writer.")
344 .required("wid", IntegerSchema
::new("Fixed writer ID.")
348 .required("digest-list", ArraySchema
::new(
349 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
351 .required("offset-list", ArraySchema
::new(
352 "Chunk offset list.",
353 IntegerSchema
::new("Corresponding chunk offsets.")
363 rpcenv
: &mut dyn RpcEnvironment
,
364 ) -> Result
<Value
, Error
> {
366 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
367 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
368 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
370 if offset_list
.len() != digest_list
.len() {
371 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
374 let env
: &BackupEnvironment
= rpcenv
.as_ref();
376 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
378 for (i
, item
) in digest_list
.iter().enumerate() {
379 let digest_str
= item
.as_str().unwrap();
380 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
381 let offset
= offset_list
[i
].as_u64().unwrap();
382 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
384 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
386 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
392 pub fn api_method_close_dynamic_index() -> ApiMethod
{
395 ObjectSchema
::new("Close dynamic index writer.")
396 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
400 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
403 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
409 fn close_dynamic_index (
412 rpcenv
: &mut dyn RpcEnvironment
,
413 ) -> Result
<Value
, Error
> {
415 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
416 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
417 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
419 let env
: &BackupEnvironment
= rpcenv
.as_ref();
421 env
.dynamic_writer_close(wid
, chunk_count
, size
)?
;
423 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
428 pub fn api_method_close_fixed_index() -> ApiMethod
{
431 ObjectSchema
::new("Close fixed index writer.")
432 .required("wid", IntegerSchema
::new("Fixed writer ID.")
436 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
439 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
445 fn close_fixed_index (
448 rpcenv
: &mut dyn RpcEnvironment
,
449 ) -> Result
<Value
, Error
> {
451 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
452 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
453 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
455 let env
: &BackupEnvironment
= rpcenv
.as_ref();
457 env
.fixed_writer_close(wid
, chunk_count
, size
)?
;
459 env
.log(format
!("sucessfully closed fixed index {}", wid
));
467 rpcenv
: &mut dyn RpcEnvironment
,
468 ) -> Result
<Value
, Error
> {
470 let env
: &BackupEnvironment
= rpcenv
.as_ref();
472 env
.finish_backup()?
;
473 env
.log("sucessfully finished backup");
478 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod
{
481 ObjectSchema
::new(r
###"
482 Download the dynamic chunk index from the previous backup.
483 Simply returns an empty list if this is the first backup.
486 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
490 fn dynamic_chunk_index(
494 _info
: &ApiAsyncMethod
,
495 rpcenv
: Box
<dyn RpcEnvironment
>,
496 ) -> Result
<BoxFut
, Error
> {
498 let env
: &BackupEnvironment
= rpcenv
.as_ref();
500 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
502 if !archive_name
.ends_with(".pxar") {
503 bail
!("wrong archive extension: '{}'", archive_name
);
505 archive_name
.push_str(".didx");
508 let empty_response
= {
510 .status(StatusCode
::OK
)
511 .body(Body
::empty())?
514 let last_backup
= match &env
.last_backup
{
516 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
519 let mut path
= last_backup
.backup_dir
.relative_path();
520 path
.push(&archive_name
);
522 let index
= match env
.datastore
.open_dynamic_reader(path
) {
525 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
526 return Ok(Box
::new(future
::ok(empty_response
)));
530 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
532 let count
= index
.index_count();
533 for pos
in 0..count
{
534 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
535 let size
= (end
- start
) as u32;
536 env
.register_chunk(digest
, size
)?
;
539 let reader
= DigestListEncoder
::new(Box
::new(index
));
541 let stream
= WrappedReaderStream
::new(reader
);
543 // fixme: set size, content type?
544 let response
= http
::Response
::builder()
546 .body(Body
::wrap_stream(stream
))?
;
548 Ok(Box
::new(future
::ok(response
)))
551 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod
{
554 ObjectSchema
::new(r
###"
555 Download the fixed chunk index from the previous backup.
556 Simply returns an empty list if this is the first backup.
559 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
563 fn fixed_chunk_index(
567 _info
: &ApiAsyncMethod
,
568 rpcenv
: Box
<dyn RpcEnvironment
>,
569 ) -> Result
<BoxFut
, Error
> {
571 let env
: &BackupEnvironment
= rpcenv
.as_ref();
573 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
575 if !archive_name
.ends_with(".img") {
576 bail
!("wrong archive extension: '{}'", archive_name
);
578 archive_name
.push_str(".fidx");
581 let empty_response
= {
583 .status(StatusCode
::OK
)
584 .body(Body
::empty())?
587 let last_backup
= match &env
.last_backup
{
589 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
592 let mut path
= last_backup
.backup_dir
.relative_path();
593 path
.push(&archive_name
);
595 let index
= match env
.datastore
.open_fixed_reader(path
) {
598 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
599 return Ok(Box
::new(future
::ok(empty_response
)));
603 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
605 let count
= index
.index_count();
606 let image_size
= index
.index_bytes();
607 for pos
in 0..count
{
608 let digest
= index
.index_digest(pos
).unwrap();
609 // Note: last chunk can be smaller
610 let start
= (pos
*index
.chunk_size
) as u64;
611 let mut end
= start
+ index
.chunk_size
as u64;
612 if end
> image_size { end = image_size; }
613 let size
= (end
- start
) as u32;
614 env
.register_chunk(*digest
, size
)?
;
617 let reader
= DigestListEncoder
::new(Box
::new(index
));
619 let stream
= WrappedReaderStream
::new(reader
);
621 // fixme: set size, content type?
622 let response
= http
::Response
::builder()
624 .body(Body
::wrap_stream(stream
))?
;
626 Ok(Box
::new(future
::ok(response
)))