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", StringSchema
::new("Backup type.")
38 .format(Arc
::new(ApiStringFormat
::Enum(&["vm", "ct", "host"]))))
39 .required("backup-id", StringSchema
::new("Backup ID."))
40 .required("backup-time", IntegerSchema
::new("Backup time (Unix epoch.)")
42 .optional("debug", BooleanSchema
::new("Enable verbose debug logging."))
46 fn upgrade_to_backup_protocol(
50 _info
: &ApiAsyncMethod
,
51 rpcenv
: Box
<dyn RpcEnvironment
>,
52 ) -> Result
<BoxFut
, Error
> {
54 let debug
= param
["debug"].as_bool().unwrap_or(false);
56 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
57 let datastore
= DataStore
::lookup_datastore(&store
)?
;
59 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
60 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
61 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
66 .ok_or_else(|| format_err
!("missing Upgrade header"))?
69 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
70 bail
!("invalid protocol name");
73 if parts
.version
>= http
::version
::Version
::HTTP_2
{
74 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
77 let worker_id
= format
!("{}_{}_{}", store
, backup_type
, backup_id
);
79 let username
= rpcenv
.get_user().unwrap();
80 let env_type
= rpcenv
.env_type();
82 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
83 let last_backup
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
).unwrap_or(None
);
84 let backup_dir
= BackupDir
::new_with_group(backup_group
, backup_time
);
86 if let Some(last
) = &last_backup
{
87 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
88 bail
!("backup timestamp is older than last backup.");
92 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
93 if !is_new { bail!("backup directorty already exists."); }
95 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
96 let mut env
= BackupEnvironment
::new(
97 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
100 env
.last_backup
= last_backup
;
102 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
104 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_ROUTER
, debug
);
106 let abort_future
= worker
.abort_future();
108 let env2
= env
.clone();
109 let env3
= env
.clone();
113 .map_err(Error
::from
)
114 .and_then(move |conn
| {
115 env3
.debug("protocol upgrade done");
117 let mut http
= hyper
::server
::conn
::Http
::new();
118 http
.http2_only(true);
119 // increase window size: todo - find optiomal size
120 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
121 http
.http2_initial_stream_window_size(window_size
);
122 http
.http2_initial_connection_window_size(window_size
);
124 http
.serve_connection(conn
, service
)
125 .map_err(Error
::from
)
127 .select(abort_future
.map_err(|_
| {}
).then(move |_
| { bail!("task aborted"); }
))
128 .map_err(|(err
, _
)| err
)
129 .and_then(move |(_result
, _
)| {
130 env
.ensure_finished()?
;
131 env
.log("backup finished sucessfully");
134 .then(move |result
| {
135 if let Err(err
) = result
{
136 match env2
.ensure_finished() {
137 Ok(()) => {}
, // ignore error after finish
139 env2
.log(format
!("backup failed: {}", err
));
140 env2
.log("removing failed backup");
141 env2
.remove_backup()?
;
150 let response
= Response
::builder()
151 .status(StatusCode
::SWITCHING_PROTOCOLS
)
152 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
153 .body(Body
::empty())?
;
155 Ok(Box
::new(futures
::future
::ok(response
)))
159 static ref BACKUP_ROUTER
: Router
= backup_api();
162 pub fn backup_api() -> Router
{
164 let router
= Router
::new()
166 "blob", Router
::new()
167 .upload(api_method_upload_blob())
170 "dynamic_chunk", Router
::new()
171 .upload(api_method_upload_dynamic_chunk())
174 "dynamic_index", Router
::new()
175 .download(api_method_dynamic_chunk_index())
176 .post(api_method_create_dynamic_index())
177 .put(api_method_dynamic_append())
180 "dynamic_close", Router
::new()
181 .post(api_method_close_dynamic_index())
184 "fixed_chunk", Router
::new()
185 .upload(api_method_upload_fixed_chunk())
188 "fixed_index", Router
::new()
189 .download(api_method_fixed_chunk_index())
190 .post(api_method_create_fixed_index())
191 .put(api_method_fixed_append())
194 "fixed_close", Router
::new()
195 .post(api_method_close_fixed_index())
198 "finish", Router
::new()
202 ObjectSchema
::new("Mark backup as finished.")
207 "speedtest", Router
::new()
208 .upload(api_method_upload_speedtest())
215 pub fn api_method_create_dynamic_index() -> ApiMethod
{
217 create_dynamic_index
,
218 ObjectSchema
::new("Create dynamic chunk index file.")
219 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
223 fn create_dynamic_index(
226 rpcenv
: &mut dyn RpcEnvironment
,
227 ) -> Result
<Value
, Error
> {
229 let env
: &BackupEnvironment
= rpcenv
.as_ref();
231 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
233 let mut archive_name
= name
.clone();
234 if !archive_name
.ends_with(".pxar") {
235 bail
!("wrong archive extension: '{}'", archive_name
);
237 archive_name
.push_str(".didx");
240 let mut path
= env
.backup_dir
.relative_path();
241 path
.push(archive_name
);
243 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
244 let wid
= env
.register_dynamic_writer(index
, name
)?
;
246 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
251 pub fn api_method_create_fixed_index() -> ApiMethod
{
254 ObjectSchema
::new("Create fixed chunk index file.")
255 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
256 .required("size", IntegerSchema
::new("File size.")
262 fn create_fixed_index(
265 rpcenv
: &mut dyn RpcEnvironment
,
266 ) -> Result
<Value
, Error
> {
268 let env
: &BackupEnvironment
= rpcenv
.as_ref();
270 println
!("PARAM: {:?}", param
);
272 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
273 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
275 let mut archive_name
= name
.clone();
276 if !archive_name
.ends_with(".img") {
277 bail
!("wrong archive extension: '{}'", archive_name
);
279 archive_name
.push_str(".fidx");
282 let mut path
= env
.backup_dir
.relative_path();
283 path
.push(archive_name
);
285 let chunk_size
= 4096*1024; // todo: ??
287 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
288 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
290 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
295 pub fn api_method_dynamic_append() -> ApiMethod
{
298 ObjectSchema
::new("Append chunk to dynamic index writer.")
299 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
303 .required("digest-list", ArraySchema
::new(
304 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
306 .required("offset-list", ArraySchema
::new(
307 "Chunk offset list.",
308 IntegerSchema
::new("Corresponding chunk offsets.")
318 rpcenv
: &mut dyn RpcEnvironment
,
319 ) -> Result
<Value
, Error
> {
321 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
322 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
323 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
325 if offset_list
.len() != digest_list
.len() {
326 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
329 let env
: &BackupEnvironment
= rpcenv
.as_ref();
331 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
333 for (i
, item
) in digest_list
.iter().enumerate() {
334 let digest_str
= item
.as_str().unwrap();
335 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
336 let offset
= offset_list
[i
].as_u64().unwrap();
337 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
339 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
341 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
347 pub fn api_method_fixed_append() -> ApiMethod
{
350 ObjectSchema
::new("Append chunk to fixed index writer.")
351 .required("wid", IntegerSchema
::new("Fixed writer ID.")
355 .required("digest-list", ArraySchema
::new(
356 "Chunk digest list.", CHUNK_DIGEST_SCHEMA
.clone())
358 .required("offset-list", ArraySchema
::new(
359 "Chunk offset list.",
360 IntegerSchema
::new("Corresponding chunk offsets.")
370 rpcenv
: &mut dyn RpcEnvironment
,
371 ) -> Result
<Value
, Error
> {
373 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
374 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
375 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
377 if offset_list
.len() != digest_list
.len() {
378 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
381 let env
: &BackupEnvironment
= rpcenv
.as_ref();
383 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
385 for (i
, item
) in digest_list
.iter().enumerate() {
386 let digest_str
= item
.as_str().unwrap();
387 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
388 let offset
= offset_list
[i
].as_u64().unwrap();
389 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
391 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
393 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
399 pub fn api_method_close_dynamic_index() -> ApiMethod
{
402 ObjectSchema
::new("Close dynamic index writer.")
403 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
407 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
410 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
416 fn close_dynamic_index (
419 rpcenv
: &mut dyn RpcEnvironment
,
420 ) -> Result
<Value
, Error
> {
422 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
423 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
424 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
426 let env
: &BackupEnvironment
= rpcenv
.as_ref();
428 env
.dynamic_writer_close(wid
, chunk_count
, size
)?
;
430 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
435 pub fn api_method_close_fixed_index() -> ApiMethod
{
438 ObjectSchema
::new("Close fixed index writer.")
439 .required("wid", IntegerSchema
::new("Fixed writer ID.")
443 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
446 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
452 fn close_fixed_index (
455 rpcenv
: &mut dyn RpcEnvironment
,
456 ) -> Result
<Value
, Error
> {
458 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
459 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
460 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
462 let env
: &BackupEnvironment
= rpcenv
.as_ref();
464 env
.fixed_writer_close(wid
, chunk_count
, size
)?
;
466 env
.log(format
!("sucessfully closed fixed index {}", wid
));
474 rpcenv
: &mut dyn RpcEnvironment
,
475 ) -> Result
<Value
, Error
> {
477 let env
: &BackupEnvironment
= rpcenv
.as_ref();
479 env
.finish_backup()?
;
480 env
.log("sucessfully finished backup");
485 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod
{
488 ObjectSchema
::new(r
###"
489 Download the dynamic chunk index from the previous backup.
490 Simply returns an empty list if this is the first backup.
493 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
497 fn dynamic_chunk_index(
501 _info
: &ApiAsyncMethod
,
502 rpcenv
: Box
<dyn RpcEnvironment
>,
503 ) -> Result
<BoxFut
, Error
> {
505 let env
: &BackupEnvironment
= rpcenv
.as_ref();
507 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
509 if !archive_name
.ends_with(".pxar") {
510 bail
!("wrong archive extension: '{}'", archive_name
);
512 archive_name
.push_str(".didx");
515 let empty_response
= {
517 .status(StatusCode
::OK
)
518 .body(Body
::empty())?
521 let last_backup
= match &env
.last_backup
{
523 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
526 let mut path
= last_backup
.backup_dir
.relative_path();
527 path
.push(&archive_name
);
529 let index
= match env
.datastore
.open_dynamic_reader(path
) {
532 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
533 return Ok(Box
::new(future
::ok(empty_response
)));
537 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
539 let count
= index
.index_count();
540 for pos
in 0..count
{
541 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
542 let size
= (end
- start
) as u32;
543 env
.register_chunk(digest
, size
)?
;
546 let reader
= DigestListEncoder
::new(Box
::new(index
));
548 let stream
= WrappedReaderStream
::new(reader
);
550 // fixme: set size, content type?
551 let response
= http
::Response
::builder()
553 .body(Body
::wrap_stream(stream
))?
;
555 Ok(Box
::new(future
::ok(response
)))
558 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod
{
561 ObjectSchema
::new(r
###"
562 Download the fixed chunk index from the previous backup.
563 Simply returns an empty list if this is the first backup.
566 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
570 fn fixed_chunk_index(
574 _info
: &ApiAsyncMethod
,
575 rpcenv
: Box
<dyn RpcEnvironment
>,
576 ) -> Result
<BoxFut
, Error
> {
578 let env
: &BackupEnvironment
= rpcenv
.as_ref();
580 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
582 if !archive_name
.ends_with(".img") {
583 bail
!("wrong archive extension: '{}'", archive_name
);
585 archive_name
.push_str(".fidx");
588 let empty_response
= {
590 .status(StatusCode
::OK
)
591 .body(Body
::empty())?
594 let last_backup
= match &env
.last_backup
{
596 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
599 let mut path
= last_backup
.backup_dir
.relative_path();
600 path
.push(&archive_name
);
602 let index
= match env
.datastore
.open_fixed_reader(path
) {
605 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
606 return Ok(Box
::new(future
::ok(empty_response
)));
610 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
612 let count
= index
.index_count();
613 let image_size
= index
.index_bytes();
614 for pos
in 0..count
{
615 let digest
= index
.index_digest(pos
).unwrap();
616 // Note: last chunk can be smaller
617 let start
= (pos
*index
.chunk_size
) as u64;
618 let mut end
= start
+ index
.chunk_size
as u64;
619 if end
> image_size { end = image_size; }
620 let size
= (end
- start
) as u32;
621 env
.register_chunk(*digest
, size
)?
;
624 let reader
= DigestListEncoder
::new(Box
::new(index
));
626 let stream
= WrappedReaderStream
::new(reader
);
628 // fixme: set size, content type?
629 let response
= http
::Response
::builder()
631 .body(Body
::wrap_stream(stream
))?
;
633 Ok(Box
::new(future
::ok(response
)))