6 use hyper
::header
::{HeaderValue, UPGRADE}
;
7 use hyper
::{Body, Response, StatusCode}
;
8 use hyper
::http
::request
::Parts
;
9 use chrono
::{Local, TimeZone}
;
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
;
29 pub fn router() -> Router
{
31 .upgrade(api_method_upgrade_backup())
34 pub fn api_method_upgrade_backup() -> ApiAsyncMethod
{
36 upgrade_to_backup_protocol
,
37 ObjectSchema
::new(concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."))
38 .required("store", StringSchema
::new("Datastore name."))
39 .required("backup-type", StringSchema
::new("Backup type.")
40 .format(Arc
::new(ApiStringFormat
::Enum(&["vm", "ct", "host"]))))
41 .required("backup-id", StringSchema
::new("Backup ID."))
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
= Local
.timestamp(Local
::now().timestamp(), 0);
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
.timestamp());
86 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
87 if !is_new { bail!("backup directorty already exists."); }
89 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
90 let mut env
= BackupEnvironment
::new(
91 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
94 env
.last_backup
= last_backup
;
96 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
98 let service
= BackupService
::new(env
.clone(), worker
.clone(), debug
);
100 let abort_future
= worker
.abort_future();
102 let env2
= env
.clone();
103 let env3
= env
.clone();
107 .map_err(Error
::from
)
108 .and_then(move |conn
| {
109 env3
.debug("protocol upgrade done");
111 let mut http
= hyper
::server
::conn
::Http
::new();
112 http
.http2_only(true);
113 // increase window size: todo - find optiomal size
114 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
115 http
.http2_initial_stream_window_size(window_size
);
116 http
.http2_initial_connection_window_size(window_size
);
118 http
.serve_connection(conn
, service
)
119 .map_err(Error
::from
)
121 .select(abort_future
.map_err(|_
| {}
).then(move |_
| { bail!("task aborted"); }
))
122 .map_err(|(err
, _
)| err
)
123 .and_then(move |(_result
, _
)| {
124 env
.ensure_finished()?
;
125 env
.log("backup finished sucessfully");
128 .then(move |result
| {
129 if let Err(err
) = result
{
130 match env2
.ensure_finished() {
131 Ok(()) => {}
, // ignore error after finish
133 env2
.log(format
!("backup failed: {}", err
));
134 env2
.log("removing failed backup");
135 env2
.remove_backup()?
;
144 let response
= Response
::builder()
145 .status(StatusCode
::SWITCHING_PROTOCOLS
)
146 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
147 .body(Body
::empty())?
;
149 Ok(Box
::new(futures
::future
::ok(response
)))
152 pub fn backup_api() -> Router
{
154 let router
= Router
::new()
156 "config", Router
::new()
157 .upload(api_method_upload_config())
160 "dynamic_chunk", Router
::new()
161 .upload(api_method_upload_dynamic_chunk())
164 "dynamic_index", Router
::new()
165 .download(api_method_dynamic_chunk_index())
166 .post(api_method_create_dynamic_index())
167 .put(api_method_dynamic_append())
170 "dynamic_close", Router
::new()
171 .post(api_method_close_dynamic_index())
174 "fixed_chunk", Router
::new()
175 .upload(api_method_upload_fixed_chunk())
178 "fixed_index", Router
::new()
179 .download(api_method_fixed_chunk_index())
180 .post(api_method_create_fixed_index())
181 .put(api_method_fixed_append())
184 "fixed_close", Router
::new()
185 .post(api_method_close_fixed_index())
188 "finish", Router
::new()
192 ObjectSchema
::new("Mark backup as finished.")
197 "speedtest", Router
::new()
198 .upload(api_method_upload_speedtest())
205 pub fn api_method_create_dynamic_index() -> ApiMethod
{
207 create_dynamic_index
,
208 ObjectSchema
::new("Create dynamic chunk index file.")
209 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
213 fn create_dynamic_index(
216 rpcenv
: &mut dyn RpcEnvironment
,
217 ) -> Result
<Value
, Error
> {
219 let env
: &BackupEnvironment
= rpcenv
.as_ref();
221 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
223 let mut archive_name
= name
.clone();
224 if !archive_name
.ends_with(".pxar") {
225 bail
!("wrong archive extension: '{}'", archive_name
);
227 archive_name
.push_str(".didx");
230 let mut path
= env
.backup_dir
.relative_path();
231 path
.push(archive_name
);
233 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
234 let wid
= env
.register_dynamic_writer(index
, name
)?
;
236 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
241 pub fn api_method_create_fixed_index() -> ApiMethod
{
244 ObjectSchema
::new("Create fixed chunk index file.")
245 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
246 .required("size", IntegerSchema
::new("File size.")
252 fn create_fixed_index(
255 rpcenv
: &mut dyn RpcEnvironment
,
256 ) -> Result
<Value
, Error
> {
258 let env
: &BackupEnvironment
= rpcenv
.as_ref();
260 println
!("PARAM: {:?}", param
);
262 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
263 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
265 let mut archive_name
= name
.clone();
266 if !archive_name
.ends_with(".img") {
267 bail
!("wrong archive extension: '{}'", archive_name
);
269 archive_name
.push_str(".fidx");
272 let mut path
= env
.backup_dir
.relative_path();
273 path
.push(archive_name
);
275 let chunk_size
= 4096*1024; // todo: ??
277 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
278 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
280 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
285 pub fn api_method_dynamic_append() -> ApiMethod
{
288 ObjectSchema
::new("Append chunk to dynamic index writer.")
289 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
293 .required("digest-list", ArraySchema
::new(
294 "Chunk digest list.",
295 StringSchema
::new("Chunk digest.").into())
297 .required("offset-list", ArraySchema
::new(
298 "Chunk offset list.",
299 IntegerSchema
::new("Corresponding chunk offsets.")
309 rpcenv
: &mut dyn RpcEnvironment
,
310 ) -> Result
<Value
, Error
> {
312 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
313 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
314 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
316 if offset_list
.len() != digest_list
.len() {
317 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
320 let env
: &BackupEnvironment
= rpcenv
.as_ref();
322 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
324 for (i
, item
) in digest_list
.iter().enumerate() {
325 let digest_str
= item
.as_str().unwrap();
326 let digest
= crate::tools
::hex_to_digest(digest_str
)?
;
327 let offset
= offset_list
[i
].as_u64().unwrap();
328 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
330 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
332 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
338 pub fn api_method_fixed_append() -> ApiMethod
{
341 ObjectSchema
::new("Append chunk to fixed index writer.")
342 .required("wid", IntegerSchema
::new("Fixed writer ID.")
346 .required("digest-list", ArraySchema
::new(
347 "Chunk digest list.",
348 StringSchema
::new("Chunk digest.").into())
350 .required("offset-list", ArraySchema
::new(
351 "Chunk offset list.",
352 IntegerSchema
::new("Corresponding chunk offsets.")
362 rpcenv
: &mut dyn RpcEnvironment
,
363 ) -> Result
<Value
, Error
> {
365 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
366 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
367 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
369 if offset_list
.len() != digest_list
.len() {
370 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
373 let env
: &BackupEnvironment
= rpcenv
.as_ref();
375 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
377 for (i
, item
) in digest_list
.iter().enumerate() {
378 let digest_str
= item
.as_str().unwrap();
379 let digest
= crate::tools
::hex_to_digest(digest_str
)?
;
380 let offset
= offset_list
[i
].as_u64().unwrap();
381 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
383 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
385 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
391 pub fn api_method_close_dynamic_index() -> ApiMethod
{
394 ObjectSchema
::new("Close dynamic index writer.")
395 .required("wid", IntegerSchema
::new("Dynamic writer ID.")
399 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
402 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
408 fn close_dynamic_index (
411 rpcenv
: &mut dyn RpcEnvironment
,
412 ) -> Result
<Value
, Error
> {
414 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
415 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
416 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
418 let env
: &BackupEnvironment
= rpcenv
.as_ref();
420 env
.dynamic_writer_close(wid
, chunk_count
, size
)?
;
422 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
427 pub fn api_method_close_fixed_index() -> ApiMethod
{
430 ObjectSchema
::new("Close fixed index writer.")
431 .required("wid", IntegerSchema
::new("Fixed writer ID.")
435 .required("chunk-count", IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
438 .required("size", IntegerSchema
::new("File size. This is used to verify that the server got all data.")
444 fn close_fixed_index (
447 rpcenv
: &mut dyn RpcEnvironment
,
448 ) -> Result
<Value
, Error
> {
450 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
451 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
452 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
454 let env
: &BackupEnvironment
= rpcenv
.as_ref();
456 env
.fixed_writer_close(wid
, chunk_count
, size
)?
;
458 env
.log(format
!("sucessfully closed fixed index {}", wid
));
466 rpcenv
: &mut dyn RpcEnvironment
,
467 ) -> Result
<Value
, Error
> {
469 let env
: &BackupEnvironment
= rpcenv
.as_ref();
471 env
.finish_backup()?
;
472 env
.log("sucessfully finished backup");
477 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod
{
480 ObjectSchema
::new(r
###"
481 Download the dynamic chunk index from the previous backup.
482 Simply returns an empty list if this is the first backup.
485 .required("archive-name", crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
.clone())
489 fn dynamic_chunk_index(
493 _info
: &ApiAsyncMethod
,
494 rpcenv
: Box
<dyn RpcEnvironment
>,
495 ) -> Result
<BoxFut
, Error
> {
497 let env
: &BackupEnvironment
= rpcenv
.as_ref();
499 let mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
501 if !archive_name
.ends_with(".pxar") {
502 bail
!("wrong archive extension: '{}'", archive_name
);
504 archive_name
.push_str(".didx");
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 mut archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
574 if !archive_name
.ends_with(".img") {
575 bail
!("wrong archive extension: '{}'", archive_name
);
577 archive_name
.push_str(".fidx");
580 let empty_response
= {
582 .status(StatusCode
::OK
)
583 .body(Body
::empty())?
586 let last_backup
= match &env
.last_backup
{
588 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
591 let mut path
= last_backup
.backup_dir
.relative_path();
592 path
.push(&archive_name
);
594 let index
= match env
.datastore
.open_fixed_reader(path
) {
597 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
598 return Ok(Box
::new(future
::ok(empty_response
)));
602 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
604 let count
= index
.index_count();
605 for pos
in 0..count
{
606 let digest
= index
.index_digest(pos
).unwrap();
607 let size
= index
.chunk_size
as u32;
608 env
.register_chunk(*digest
, size
)?
;
611 let reader
= DigestListEncoder
::new(Box
::new(index
));
613 let stream
= WrappedReaderStream
::new(reader
);
615 // fixme: set size, content type?
616 let response
= http
::Response
::builder()
618 .body(Body
::wrap_stream(stream
))?
;
620 Ok(Box
::new(future
::ok(response
)))