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 mut archive_name
= name
.clone();
232 if !archive_name
.ends_with(".pxar") {
233 bail
!("wrong archive extension: '{}'", archive_name
);
235 archive_name
.push_str(".didx");
238 let mut path
= env
.backup_dir
.relative_path();
239 path
.push(archive_name
);
241 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
242 let wid
= env
.register_dynamic_writer(index
, name
)?
;
244 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
249 pub fn api_method_create_fixed_index() -> ApiMethod
{
252 ObjectSchema
::new("Create fixed chunk index file.")
253 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
254 .required("size", IntegerSchema
::new("File size.")
260 fn create_fixed_index(
263 rpcenv
: &mut dyn RpcEnvironment
,
264 ) -> Result
<Value
, Error
> {
266 let env
: &BackupEnvironment
= rpcenv
.as_ref();
268 println
!("PARAM: {:?}", param
);
270 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
271 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
273 let mut archive_name
= name
.clone();
274 if !archive_name
.ends_with(".img") {
275 bail
!("wrong archive extension: '{}'", archive_name
);
277 archive_name
.push_str(".fidx");
280 let mut path
= env
.backup_dir
.relative_path();
281 path
.push(archive_name
);
283 let chunk_size
= 4096*1024; // todo: ??
285 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
286 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
288 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
293 pub fn api_method_dynamic_append() -> ApiMethod
{
296 ObjectSchema
::new("Append chunk to dynamic index writer.")
297 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
301 .required("digest-list", ArraySchema
::new(
302 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
304 .required("offset-list", ArraySchema
::new(
305 "Chunk offset list.",
306 IntegerSchema
::new("Corresponding chunk offsets.")
316 rpcenv
: &mut dyn RpcEnvironment
,
317 ) -> Result
<Value
, Error
> {
319 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
320 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
321 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
323 if offset_list
.len() != digest_list
.len() {
324 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
327 let env
: &BackupEnvironment
= rpcenv
.as_ref();
329 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
331 for (i
, item
) in digest_list
.iter().enumerate() {
332 let digest_str
= item
.as_str().unwrap();
333 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
334 let offset
= offset_list
[i
].as_u64().unwrap();
335 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
337 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
339 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
345 pub fn api_method_fixed_append() -> ApiMethod
{
348 ObjectSchema
::new("Append chunk to fixed index writer.")
349 .required("wid", IntegerSchema
::new("Fixed writer ID.")
353 .required("digest-list", ArraySchema
::new(
354 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
356 .required("offset-list", ArraySchema
::new(
357 "Chunk offset list.",
358 IntegerSchema
::new("Corresponding chunk offsets.")
368 rpcenv
: &mut dyn RpcEnvironment
,
369 ) -> Result
<Value
, Error
> {
371 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
372 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
373 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
375 if offset_list
.len() != digest_list
.len() {
376 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
379 let env
: &BackupEnvironment
= rpcenv
.as_ref();
381 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
383 for (i
, item
) in digest_list
.iter().enumerate() {
384 let digest_str
= item
.as_str().unwrap();
385 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
386 let offset
= offset_list
[i
].as_u64().unwrap();
387 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
389 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
391 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
397 pub fn api_method_close_dynamic_index() -> ApiMethod
{
400 ObjectSchema
::new("Close dynamic index writer.")
401 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
405 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
408 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
414 fn close_dynamic_index (
417 rpcenv
: &mut dyn RpcEnvironment
,
418 ) -> Result
<Value
, Error
> {
420 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
421 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
422 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
424 let env
: &BackupEnvironment
= rpcenv
.as_ref();
426 env
.dynamic_writer_close(wid
, chunk_count
, size
)?
;
428 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
433 pub fn api_method_close_fixed_index() -> ApiMethod
{
436 ObjectSchema
::new("Close fixed index writer.")
437 .required("wid", IntegerSchema
::new("Fixed writer ID.")
441 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
444 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
450 fn close_fixed_index (
453 rpcenv
: &mut dyn RpcEnvironment
,
454 ) -> Result
<Value
, Error
> {
456 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
457 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
458 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
460 let env
: &BackupEnvironment
= rpcenv
.as_ref();
462 env
.fixed_writer_close(wid
, chunk_count
, size
)?
;
464 env
.log(format
!("sucessfully closed fixed index {}", wid
));
472 rpcenv
: &mut dyn RpcEnvironment
,
473 ) -> Result
<Value
, Error
> {
475 let env
: &BackupEnvironment
= rpcenv
.as_ref();
477 env
.finish_backup()?
;
478 env
.log("sucessfully finished backup");
483 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod
{
486 ObjectSchema
::new(r
###"
487 Download the dynamic chunk index from the previous backup.
488 Simply returns an empty list if this is the first backup.
491 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
495 fn dynamic_chunk_index(
499 _info
: &ApiAsyncMethod
,
500 rpcenv
: Box
<dyn RpcEnvironment
>,
501 ) -> Result
<BoxFut
, Error
> {
503 let env
: &BackupEnvironment
= rpcenv
.as_ref();
505 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
507 if !archive_name
.ends_with(".pxar") {
508 bail
!("wrong archive extension: '{}'", archive_name
);
510 archive_name
.push_str(".didx");
513 let empty_response
= {
515 .status(StatusCode
::OK
)
516 .body(Body
::empty())?
519 let last_backup
= match &env
.last_backup
{
521 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
524 let mut path
= last_backup
.backup_dir
.relative_path();
525 path
.push(&archive_name
);
527 let index
= match env
.datastore
.open_dynamic_reader(path
) {
530 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
531 return Ok(Box
::new(future
::ok(empty_response
)));
535 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
537 let count
= index
.index_count();
538 for pos
in 0..count
{
539 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
540 let size
= (end
- start
) as u32;
541 env
.register_chunk(digest
, size
)?
;
544 let reader
= DigestListEncoder
::new(Box
::new(index
));
546 let stream
= WrappedReaderStream
::new(reader
);
548 // fixme: set size, content type?
549 let response
= http
::Response
::builder()
551 .body(Body
::wrap_stream(stream
))?
;
553 Ok(Box
::new(future
::ok(response
)))
556 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod
{
559 ObjectSchema
::new(r
###"
560 Download the fixed chunk index from the previous backup.
561 Simply returns an empty list if this is the first backup.
564 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
568 fn fixed_chunk_index(
572 _info
: &ApiAsyncMethod
,
573 rpcenv
: Box
<dyn RpcEnvironment
>,
574 ) -> Result
<BoxFut
, Error
> {
576 let env
: &BackupEnvironment
= rpcenv
.as_ref();
578 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
580 if !archive_name
.ends_with(".img") {
581 bail
!("wrong archive extension: '{}'", archive_name
);
583 archive_name
.push_str(".fidx");
586 let empty_response
= {
588 .status(StatusCode
::OK
)
589 .body(Body
::empty())?
592 let last_backup
= match &env
.last_backup
{
594 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
597 let mut path
= last_backup
.backup_dir
.relative_path();
598 path
.push(&archive_name
);
600 let index
= match env
.datastore
.open_fixed_reader(path
) {
603 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
604 return Ok(Box
::new(future
::ok(empty_response
)));
608 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
610 let count
= index
.index_count();
611 let image_size
= index
.index_bytes();
612 for pos
in 0..count
{
613 let digest
= index
.index_digest(pos
).unwrap();
614 // Note: last chunk can be smaller
615 let start
= (pos
*index
.chunk_size
) as u64;
616 let mut end
= start
+ index
.chunk_size
as u64;
617 if end
> image_size { end = image_size; }
618 let size
= (end
- start
) as u32;
619 env
.register_chunk(*digest
, size
)?
;
622 let reader
= DigestListEncoder
::new(Box
::new(index
));
624 let stream
= WrappedReaderStream
::new(reader
);
626 // fixme: set size, content type?
627 let response
= http
::Response
::builder()
629 .body(Body
::wrap_stream(stream
))?
;
631 Ok(Box
::new(future
::ok(response
)))