2 use lazy_static
::lazy_static
;
7 use hyper
::header
::{HeaderValue, UPGRADE}
;
8 use hyper
::{Body, Response, StatusCode}
;
9 use hyper
::http
::request
::Parts
;
11 use serde_json
::{json, Value}
;
14 use crate::tools
::wrapped_reader_stream
::*;
15 use crate::api_schema
::router
::*;
16 use crate::api_schema
::*;
17 use crate::server
::{WorkerTask, H2Service}
;
19 use crate::api2
::types
::*;
27 pub fn router() -> Router
{
29 .upgrade(api_method_upgrade_backup())
32 pub fn api_method_upgrade_backup() -> ApiAsyncMethod
{
34 upgrade_to_backup_protocol
,
35 ObjectSchema
::new(concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."))
36 .required("store", StringSchema
::new("Datastore name."))
37 .required("backup-type", BACKUP_TYPE_SCHEMA
.clone())
38 .required("backup-id", BACKUP_ID_SCHEMA
.clone())
39 .required("backup-time", BACKUP_TIME_SCHEMA
.clone())
40 .optional("debug", BooleanSchema
::new("Enable verbose debug logging."))
44 fn upgrade_to_backup_protocol(
48 _info
: &ApiAsyncMethod
,
49 rpcenv
: Box
<dyn RpcEnvironment
>,
50 ) -> Result
<BoxFut
, Error
> {
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.");
90 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
91 if !is_new { bail!("backup directorty already exists."); }
93 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
94 let mut env
= BackupEnvironment
::new(
95 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
98 env
.last_backup
= last_backup
;
100 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
102 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_ROUTER
, debug
);
104 let abort_future
= worker
.abort_future();
106 let env2
= env
.clone();
107 let env3
= env
.clone();
111 .map_err(Error
::from
)
112 .and_then(move |conn
| {
113 env3
.debug("protocol upgrade done");
115 let mut http
= hyper
::server
::conn
::Http
::new();
116 http
.http2_only(true);
117 // increase window size: todo - find optiomal size
118 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
119 http
.http2_initial_stream_window_size(window_size
);
120 http
.http2_initial_connection_window_size(window_size
);
122 http
.serve_connection(conn
, service
)
123 .map_err(Error
::from
)
125 .select(abort_future
.map_err(|_
| {}
).then(move |_
| { bail!("task aborted"); }
))
126 .map_err(|(err
, _
)| err
)
127 .and_then(move |(_result
, _
)| {
128 env
.ensure_finished()?
;
129 env
.log("backup finished sucessfully");
132 .then(move |result
| {
133 if let Err(err
) = result
{
134 match env2
.ensure_finished() {
135 Ok(()) => {}
, // ignore error after finish
137 env2
.log(format
!("backup failed: {}", err
));
138 env2
.log("removing failed backup");
139 env2
.remove_backup()?
;
148 let response
= Response
::builder()
149 .status(StatusCode
::SWITCHING_PROTOCOLS
)
150 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
151 .body(Body
::empty())?
;
153 Ok(Box
::new(futures
::future
::ok(response
)))
157 static ref BACKUP_ROUTER
: Router
= backup_api();
160 pub fn backup_api() -> Router
{
162 let router
= Router
::new()
164 "blob", Router
::new()
165 .upload(api_method_upload_blob())
168 "dynamic_chunk", Router
::new()
169 .upload(api_method_upload_dynamic_chunk())
172 "dynamic_index", Router
::new()
173 .download(api_method_dynamic_chunk_index())
174 .post(api_method_create_dynamic_index())
175 .put(api_method_dynamic_append())
178 "dynamic_close", Router
::new()
179 .post(api_method_close_dynamic_index())
182 "fixed_chunk", Router
::new()
183 .upload(api_method_upload_fixed_chunk())
186 "fixed_index", Router
::new()
187 .download(api_method_fixed_chunk_index())
188 .post(api_method_create_fixed_index())
189 .put(api_method_fixed_append())
192 "fixed_close", Router
::new()
193 .post(api_method_close_fixed_index())
196 "finish", Router
::new()
200 ObjectSchema
::new("Mark backup as finished.")
205 "speedtest", Router
::new()
206 .upload(api_method_upload_speedtest())
213 pub fn api_method_create_dynamic_index() -> ApiMethod
{
215 create_dynamic_index
,
216 ObjectSchema
::new("Create dynamic chunk index file.")
217 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
221 fn create_dynamic_index(
224 rpcenv
: &mut dyn RpcEnvironment
,
225 ) -> Result
<Value
, Error
> {
227 let env
: &BackupEnvironment
= rpcenv
.as_ref();
229 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
231 let archive_name
= name
.clone();
232 if !archive_name
.ends_with(".pxar.didx") {
233 bail
!("wrong archive extension: '{}'", archive_name
);
236 let mut path
= env
.backup_dir
.relative_path();
237 path
.push(archive_name
);
239 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
240 let wid
= env
.register_dynamic_writer(index
, name
)?
;
242 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
247 pub fn api_method_create_fixed_index() -> ApiMethod
{
250 ObjectSchema
::new("Create fixed chunk index file.")
251 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
252 .required("size", IntegerSchema
::new("File size.")
258 fn create_fixed_index(
261 rpcenv
: &mut dyn RpcEnvironment
,
262 ) -> Result
<Value
, Error
> {
264 let env
: &BackupEnvironment
= rpcenv
.as_ref();
266 println
!("PARAM: {:?}", param
);
268 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
269 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
271 let archive_name
= name
.clone();
272 if !archive_name
.ends_with(".img.fidx") {
273 bail
!("wrong archive extension: '{}'", archive_name
);
276 let mut path
= env
.backup_dir
.relative_path();
277 path
.push(archive_name
);
279 let chunk_size
= 4096*1024; // todo: ??
281 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
282 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
284 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
289 pub fn api_method_dynamic_append() -> ApiMethod
{
292 ObjectSchema
::new("Append chunk to dynamic index writer.")
293 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
297 .required("digest-list", ArraySchema
::new(
298 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
300 .required("offset-list", ArraySchema
::new(
301 "Chunk offset list.",
302 IntegerSchema
::new("Corresponding chunk offsets.")
312 rpcenv
: &mut dyn RpcEnvironment
,
313 ) -> Result
<Value
, Error
> {
315 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
316 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
317 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
319 if offset_list
.len() != digest_list
.len() {
320 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
323 let env
: &BackupEnvironment
= rpcenv
.as_ref();
325 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
327 for (i
, item
) in digest_list
.iter().enumerate() {
328 let digest_str
= item
.as_str().unwrap();
329 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
330 let offset
= offset_list
[i
].as_u64().unwrap();
331 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
333 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
335 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
341 pub fn api_method_fixed_append() -> ApiMethod
{
344 ObjectSchema
::new("Append chunk to fixed index writer.")
345 .required("wid", IntegerSchema
::new("Fixed writer ID.")
349 .required("digest-list", ArraySchema
::new(
350 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
352 .required("offset-list", ArraySchema
::new(
353 "Chunk offset list.",
354 IntegerSchema
::new("Corresponding chunk offsets.")
364 rpcenv
: &mut dyn RpcEnvironment
,
365 ) -> Result
<Value
, Error
> {
367 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
368 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
369 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
371 if offset_list
.len() != digest_list
.len() {
372 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
375 let env
: &BackupEnvironment
= rpcenv
.as_ref();
377 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
379 for (i
, item
) in digest_list
.iter().enumerate() {
380 let digest_str
= item
.as_str().unwrap();
381 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
382 let offset
= offset_list
[i
].as_u64().unwrap();
383 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
385 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
387 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
393 pub fn api_method_close_dynamic_index() -> ApiMethod
{
396 ObjectSchema
::new("Close dynamic index writer.")
397 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
401 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
404 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
410 fn close_dynamic_index (
413 rpcenv
: &mut dyn RpcEnvironment
,
414 ) -> Result
<Value
, Error
> {
416 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
417 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
418 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
420 let env
: &BackupEnvironment
= rpcenv
.as_ref();
422 env
.dynamic_writer_close(wid
, chunk_count
, size
)?
;
424 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
429 pub fn api_method_close_fixed_index() -> ApiMethod
{
432 ObjectSchema
::new("Close fixed index writer.")
433 .required("wid", IntegerSchema
::new("Fixed writer ID.")
437 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
440 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
446 fn close_fixed_index (
449 rpcenv
: &mut dyn RpcEnvironment
,
450 ) -> Result
<Value
, Error
> {
452 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
453 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
454 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
456 let env
: &BackupEnvironment
= rpcenv
.as_ref();
458 env
.fixed_writer_close(wid
, chunk_count
, size
)?
;
460 env
.log(format
!("sucessfully closed fixed index {}", wid
));
468 rpcenv
: &mut dyn RpcEnvironment
,
469 ) -> Result
<Value
, Error
> {
471 let env
: &BackupEnvironment
= rpcenv
.as_ref();
473 env
.finish_backup()?
;
474 env
.log("sucessfully finished backup");
479 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod
{
482 ObjectSchema
::new(r
###"
483 Download the dynamic chunk index from the previous backup.
484 Simply returns an empty list if this is the first backup.
487 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
491 fn dynamic_chunk_index(
495 _info
: &ApiAsyncMethod
,
496 rpcenv
: Box
<dyn RpcEnvironment
>,
497 ) -> Result
<BoxFut
, Error
> {
499 let env
: &BackupEnvironment
= rpcenv
.as_ref();
501 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
503 if !archive_name
.ends_with(".pxar.didx") {
504 bail
!("wrong archive extension: '{}'", archive_name
);
507 let empty_response
= {
509 .status(StatusCode
::OK
)
510 .body(Body
::empty())?
513 let last_backup
= match &env
.last_backup
{
515 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
518 let mut path
= last_backup
.backup_dir
.relative_path();
519 path
.push(&archive_name
);
521 let index
= match env
.datastore
.open_dynamic_reader(path
) {
524 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
525 return Ok(Box
::new(future
::ok(empty_response
)));
529 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
531 let count
= index
.index_count();
532 for pos
in 0..count
{
533 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
534 let size
= (end
- start
) as u32;
535 env
.register_chunk(digest
, size
)?
;
538 let reader
= DigestListEncoder
::new(Box
::new(index
));
540 let stream
= WrappedReaderStream
::new(reader
);
542 // fixme: set size, content type?
543 let response
= http
::Response
::builder()
545 .body(Body
::wrap_stream(stream
))?
;
547 Ok(Box
::new(future
::ok(response
)))
550 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod
{
553 ObjectSchema
::new(r
###"
554 Download the fixed chunk index from the previous backup.
555 Simply returns an empty list if this is the first backup.
558 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
562 fn fixed_chunk_index(
566 _info
: &ApiAsyncMethod
,
567 rpcenv
: Box
<dyn RpcEnvironment
>,
568 ) -> Result
<BoxFut
, Error
> {
570 let env
: &BackupEnvironment
= rpcenv
.as_ref();
572 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
574 if !archive_name
.ends_with(".img.fidx") {
575 bail
!("wrong archive extension: '{}'", archive_name
);
578 let empty_response
= {
580 .status(StatusCode
::OK
)
581 .body(Body
::empty())?
584 let last_backup
= match &env
.last_backup
{
586 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
589 let mut path
= last_backup
.backup_dir
.relative_path();
590 path
.push(&archive_name
);
592 let index
= match env
.datastore
.open_fixed_reader(path
) {
595 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
596 return Ok(Box
::new(future
::ok(empty_response
)));
600 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
602 let count
= index
.index_count();
603 let image_size
= index
.index_bytes();
604 for pos
in 0..count
{
605 let digest
= index
.index_digest(pos
).unwrap();
606 // Note: last chunk can be smaller
607 let start
= (pos
*index
.chunk_size
) as u64;
608 let mut end
= start
+ index
.chunk_size
as u64;
609 if end
> image_size { end = image_size; }
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
))?
;
623 Ok(Box
::new(future
::ok(response
)))