3 use hyper
::header
::{HeaderValue, UPGRADE}
;
4 use hyper
::http
::request
::Parts
;
5 use hyper
::{Body, Response, StatusCode}
;
6 use serde_json
::{json, Value}
;
8 use proxmox
::{sortable, identity}
;
9 use proxmox
::api
::list_subdirs_api_method
;
10 use proxmox
::api
::{ApiFuture, ApiHandler, ApiMethod, Router, RpcEnvironment}
;
11 use proxmox
::api
::router
::SubdirMap
;
12 use proxmox
::api
::schema
::*;
15 use crate::tools
::wrapped_reader_stream
::*;
16 use crate::server
::{WorkerTask, H2Service}
;
18 use crate::api2
::types
::*;
26 pub const ROUTER
: Router
= Router
::new()
27 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
30 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
31 &ApiHandler
::Async(&upgrade_to_backup_protocol
),
33 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
35 ("store", false, &StringSchema
::new("Datastore name.").schema()),
36 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
37 ("backup-id", false, &BACKUP_ID_SCHEMA
),
38 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
39 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
44 fn upgrade_to_backup_protocol(
49 rpcenv
: Box
<dyn RpcEnvironment
>,
50 ) -> Result
<ApiFuture
, 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_API_ROUTER
, debug
);
104 let abort_future
= worker
.abort_future();
106 let env2
= env
.clone();
107 let env3
= env
.clone();
109 let req_fut
= req_body
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 let abort_future
= abort_future
126 .map(|_
| Err(format_err
!("task aborted")));
128 use futures
::future
::Either
;
129 future
::select(req_fut
, abort_future
)
130 .map(|res
| match res
{
131 Either
::Left((Ok(res
), _
)) => Ok(res
),
132 Either
::Left((Err(err
), _
)) => Err(err
),
133 Either
::Right((Ok(res
), _
)) => Ok(res
),
134 Either
::Right((Err(err
), _
)) => Err(err
),
136 .and_then(move |_result
| async
move {
137 env
.ensure_finished()?
;
138 env
.log("backup finished sucessfully");
141 .then(move |result
| async
move {
142 if let Err(err
) = result
{
143 match env2
.ensure_finished() {
144 Ok(()) => {}
, // ignore error after finish
146 env2
.log(format
!("backup failed: {}", err
));
147 env2
.log("removing failed backup");
148 env2
.remove_backup()?
;
157 let response
= Response
::builder()
158 .status(StatusCode
::SWITCHING_PROTOCOLS
)
159 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
160 .body(Body
::empty())?
;
162 Ok(Box
::new(futures
::future
::ok(response
)))
165 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
167 "blob", &Router
::new()
168 .upload(&API_METHOD_UPLOAD_BLOB
)
171 "dynamic_chunk", &Router
::new()
172 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
175 "dynamic_close", &Router
::new()
176 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
179 "dynamic_index", &Router
::new()
180 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
181 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
182 .put(&API_METHOD_DYNAMIC_APPEND
)
185 "finish", &Router
::new()
188 &ApiHandler
::Sync(&finish_backup
),
189 &ObjectSchema
::new("Mark backup as finished.", &[])
194 "fixed_chunk", &Router
::new()
195 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
198 "fixed_close", &Router
::new()
199 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
202 "fixed_index", &Router
::new()
203 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
204 .post(&API_METHOD_CREATE_FIXED_INDEX
)
205 .put(&API_METHOD_FIXED_APPEND
)
208 "speedtest", &Router
::new()
209 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
213 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
214 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
215 .subdirs(BACKUP_API_SUBDIRS
);
218 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
219 &ApiHandler
::Sync(&create_dynamic_index
),
221 "Create dynamic chunk index file.",
223 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
228 fn create_dynamic_index(
231 rpcenv
: &mut dyn RpcEnvironment
,
232 ) -> Result
<Value
, Error
> {
234 let env
: &BackupEnvironment
= rpcenv
.as_ref();
236 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
238 let archive_name
= name
.clone();
239 if !archive_name
.ends_with(".didx") {
240 bail
!("wrong archive extension: '{}'", archive_name
);
243 let mut path
= env
.backup_dir
.relative_path();
244 path
.push(archive_name
);
246 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
247 let wid
= env
.register_dynamic_writer(index
, name
)?
;
249 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
255 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
256 &ApiHandler
::Sync(&create_fixed_index
),
258 "Create fixed chunk index file.",
260 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
261 ("size", false, &IntegerSchema
::new("File size.")
269 fn create_fixed_index(
272 rpcenv
: &mut dyn RpcEnvironment
,
273 ) -> Result
<Value
, Error
> {
275 let env
: &BackupEnvironment
= rpcenv
.as_ref();
277 println
!("PARAM: {:?}", param
);
279 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
280 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
282 let archive_name
= name
.clone();
283 if !archive_name
.ends_with(".fidx") {
284 bail
!("wrong archive extension: '{}'", archive_name
);
287 let mut path
= env
.backup_dir
.relative_path();
288 path
.push(archive_name
);
290 let chunk_size
= 4096*1024; // todo: ??
292 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
293 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
295 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
301 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
302 &ApiHandler
::Sync(&dynamic_append
),
304 "Append chunk to dynamic index writer.",
309 &IntegerSchema
::new("Dynamic writer ID.")
317 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
323 "Chunk offset list.",
324 &IntegerSchema
::new("Corresponding chunk offsets.")
336 rpcenv
: &mut dyn RpcEnvironment
,
337 ) -> Result
<Value
, Error
> {
339 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
340 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
341 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
343 if offset_list
.len() != digest_list
.len() {
344 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
347 let env
: &BackupEnvironment
= rpcenv
.as_ref();
349 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
351 for (i
, item
) in digest_list
.iter().enumerate() {
352 let digest_str
= item
.as_str().unwrap();
353 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
354 let offset
= offset_list
[i
].as_u64().unwrap();
355 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
357 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
359 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
366 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
367 &ApiHandler
::Sync(&fixed_append
),
369 "Append chunk to fixed index writer.",
374 &IntegerSchema
::new("Fixed writer ID.")
382 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
388 "Chunk offset list.",
389 &IntegerSchema
::new("Corresponding chunk offsets.")
401 rpcenv
: &mut dyn RpcEnvironment
,
402 ) -> Result
<Value
, Error
> {
404 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
405 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
406 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
408 if offset_list
.len() != digest_list
.len() {
409 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
412 let env
: &BackupEnvironment
= rpcenv
.as_ref();
414 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
416 for (i
, item
) in digest_list
.iter().enumerate() {
417 let digest_str
= item
.as_str().unwrap();
418 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
419 let offset
= offset_list
[i
].as_u64().unwrap();
420 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
422 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
424 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
431 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
432 &ApiHandler
::Sync(&close_dynamic_index
),
434 "Close dynamic index writer.",
439 &IntegerSchema
::new("Dynamic writer ID.")
447 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
454 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
458 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
463 fn close_dynamic_index (
466 rpcenv
: &mut dyn RpcEnvironment
,
467 ) -> Result
<Value
, Error
> {
469 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
470 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
471 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
472 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
473 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
475 let env
: &BackupEnvironment
= rpcenv
.as_ref();
477 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
479 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
485 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
486 &ApiHandler
::Sync(&close_fixed_index
),
488 "Close fixed index writer.",
493 &IntegerSchema
::new("Fixed writer ID.")
501 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
508 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
512 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
517 fn close_fixed_index (
520 rpcenv
: &mut dyn RpcEnvironment
,
521 ) -> Result
<Value
, Error
> {
523 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
524 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
525 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
526 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
527 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
529 let env
: &BackupEnvironment
= rpcenv
.as_ref();
531 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
533 env
.log(format
!("sucessfully closed fixed index {}", wid
));
541 rpcenv
: &mut dyn RpcEnvironment
,
542 ) -> Result
<Value
, Error
> {
544 let env
: &BackupEnvironment
= rpcenv
.as_ref();
546 env
.finish_backup()?
;
547 env
.log("sucessfully finished backup");
553 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
554 &ApiHandler
::Async(&dynamic_chunk_index
),
557 Download the dynamic chunk index from the previous backup.
558 Simply returns an empty list if this is the first backup.
561 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
566 fn dynamic_chunk_index(
571 rpcenv
: Box
<dyn RpcEnvironment
>,
572 ) -> Result
<ApiFuture
, Error
> {
574 let env
: &BackupEnvironment
= rpcenv
.as_ref();
576 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
578 if !archive_name
.ends_with(".didx") {
579 bail
!("wrong archive extension: '{}'", archive_name
);
582 let empty_response
= {
584 .status(StatusCode
::OK
)
585 .body(Body
::empty())?
588 let last_backup
= match &env
.last_backup
{
590 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
593 let mut path
= last_backup
.backup_dir
.relative_path();
594 path
.push(&archive_name
);
596 let index
= match env
.datastore
.open_dynamic_reader(path
) {
599 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
600 return Ok(Box
::new(future
::ok(empty_response
)));
604 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
606 let count
= index
.index_count();
607 for pos
in 0..count
{
608 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
609 let size
= (end
- start
) as u32;
610 env
.register_chunk(digest
, size
)?
;
613 let reader
= DigestListEncoder
::new(Box
::new(index
));
615 let stream
= WrappedReaderStream
::new(reader
);
617 // fixme: set size, content type?
618 let response
= http
::Response
::builder()
620 .body(Body
::wrap_stream(stream
))?
;
622 Ok(Box
::new(future
::ok(response
)))
626 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
627 &ApiHandler
::Async(&fixed_chunk_index
),
630 Download the fixed chunk index from the previous backup.
631 Simply returns an empty list if this is the first backup.
634 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
639 fn fixed_chunk_index(
644 rpcenv
: Box
<dyn RpcEnvironment
>,
645 ) -> Result
<ApiFuture
, Error
> {
647 let env
: &BackupEnvironment
= rpcenv
.as_ref();
649 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
651 if !archive_name
.ends_with(".fidx") {
652 bail
!("wrong archive extension: '{}'", archive_name
);
655 let empty_response
= {
657 .status(StatusCode
::OK
)
658 .body(Body
::empty())?
661 let last_backup
= match &env
.last_backup
{
663 None
=> return Ok(Box
::new(future
::ok(empty_response
))),
666 let mut path
= last_backup
.backup_dir
.relative_path();
667 path
.push(&archive_name
);
669 let index
= match env
.datastore
.open_fixed_reader(path
) {
672 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
673 return Ok(Box
::new(future
::ok(empty_response
)));
677 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
679 let count
= index
.index_count();
680 let image_size
= index
.index_bytes();
681 for pos
in 0..count
{
682 let digest
= index
.index_digest(pos
).unwrap();
683 // Note: last chunk can be smaller
684 let start
= (pos
*index
.chunk_size
) as u64;
685 let mut end
= start
+ index
.chunk_size
as u64;
686 if end
> image_size { end = image_size; }
687 let size
= (end
- start
) as u32;
688 env
.register_chunk(*digest
, size
)?
;
691 let reader
= DigestListEncoder
::new(Box
::new(index
));
693 let stream
= WrappedReaderStream
::new(reader
);
695 // fixme: set size, content type?
696 let response
= http
::Response
::builder()
698 .body(Body
::wrap_stream(stream
))?
;
700 Ok(Box
::new(future
::ok(response
)))