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
::AsyncHttp(&upgrade_to_backup_protocol
),
33 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
35 ("store", false, &DATASTORE_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
>,
53 let debug
= param
["debug"].as_bool().unwrap_or(false);
55 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
56 let datastore
= DataStore
::lookup_datastore(&store
)?
;
58 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
59 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
60 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
65 .ok_or_else(|| format_err
!("missing Upgrade header"))?
68 if protocols
!= PROXMOX_BACKUP_PROTOCOL_ID_V1
!() {
69 bail
!("invalid protocol name");
72 if parts
.version
>= http
::version
::Version
::HTTP_2
{
73 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
76 let worker_id
= format
!("{}_{}_{}", store
, backup_type
, backup_id
);
78 let username
= rpcenv
.get_user().unwrap();
79 let env_type
= rpcenv
.env_type();
81 let backup_group
= BackupGroup
::new(backup_type
, backup_id
);
82 let last_backup
= BackupInfo
::last_backup(&datastore
.base_path(), &backup_group
).unwrap_or(None
);
83 let backup_dir
= BackupDir
::new_with_group(backup_group
, backup_time
);
85 if let Some(last
) = &last_backup
{
86 if backup_dir
.backup_time() <= last
.backup_dir
.backup_time() {
87 bail
!("backup timestamp is older than last backup.");
89 // fixme: abort if last backup is still running - howto test?
90 // Idea: write upid into a file inside snapshot dir. then test if
91 // it is still running here.
94 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
95 if !is_new { bail!("backup directorty already exists."); }
97 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
98 let mut env
= BackupEnvironment
::new(
99 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
102 env
.last_backup
= last_backup
;
104 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
106 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
108 let abort_future
= worker
.abort_future();
110 let env2
= env
.clone();
111 let env3
= env
.clone();
113 let req_fut
= req_body
115 .map_err(Error
::from
)
116 .and_then(move |conn
| {
117 env3
.debug("protocol upgrade done");
119 let mut http
= hyper
::server
::conn
::Http
::new();
120 http
.http2_only(true);
121 // increase window size: todo - find optiomal size
122 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
123 http
.http2_initial_stream_window_size(window_size
);
124 http
.http2_initial_connection_window_size(window_size
);
126 http
.serve_connection(conn
, service
)
127 .map_err(Error
::from
)
129 let abort_future
= abort_future
130 .map(|_
| Err(format_err
!("task aborted")));
132 use futures
::future
::Either
;
133 future
::select(req_fut
, abort_future
)
134 .map(|res
| match res
{
135 Either
::Left((Ok(res
), _
)) => Ok(res
),
136 Either
::Left((Err(err
), _
)) => Err(err
),
137 Either
::Right((Ok(res
), _
)) => Ok(res
),
138 Either
::Right((Err(err
), _
)) => Err(err
),
140 .and_then(move |_result
| async
move {
141 env
.ensure_finished()?
;
142 env
.log("backup finished sucessfully");
145 .then(move |result
| async
move {
146 if let Err(err
) = result
{
147 match env2
.ensure_finished() {
148 Ok(()) => {}
, // ignore error after finish
150 env2
.log(format
!("backup failed: {}", err
));
151 env2
.log("removing failed backup");
152 env2
.remove_backup()?
;
161 let response
= Response
::builder()
162 .status(StatusCode
::SWITCHING_PROTOCOLS
)
163 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
164 .body(Body
::empty())?
;
170 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
172 "blob", &Router
::new()
173 .upload(&API_METHOD_UPLOAD_BLOB
)
176 "dynamic_chunk", &Router
::new()
177 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
180 "dynamic_close", &Router
::new()
181 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
184 "dynamic_index", &Router
::new()
185 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
186 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
187 .put(&API_METHOD_DYNAMIC_APPEND
)
190 "finish", &Router
::new()
193 &ApiHandler
::Sync(&finish_backup
),
194 &ObjectSchema
::new("Mark backup as finished.", &[])
199 "fixed_chunk", &Router
::new()
200 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
203 "fixed_close", &Router
::new()
204 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
207 "fixed_index", &Router
::new()
208 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
209 .post(&API_METHOD_CREATE_FIXED_INDEX
)
210 .put(&API_METHOD_FIXED_APPEND
)
213 "speedtest", &Router
::new()
214 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
218 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
219 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
220 .subdirs(BACKUP_API_SUBDIRS
);
223 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
224 &ApiHandler
::Sync(&create_dynamic_index
),
226 "Create dynamic chunk index file.",
228 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
233 fn create_dynamic_index(
236 rpcenv
: &mut dyn RpcEnvironment
,
237 ) -> Result
<Value
, Error
> {
239 let env
: &BackupEnvironment
= rpcenv
.as_ref();
241 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
243 let archive_name
= name
.clone();
244 if !archive_name
.ends_with(".didx") {
245 bail
!("wrong archive extension: '{}'", archive_name
);
248 let mut path
= env
.backup_dir
.relative_path();
249 path
.push(archive_name
);
251 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
252 let wid
= env
.register_dynamic_writer(index
, name
)?
;
254 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
260 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
261 &ApiHandler
::Sync(&create_fixed_index
),
263 "Create fixed chunk index file.",
265 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
266 ("size", false, &IntegerSchema
::new("File size.")
274 fn create_fixed_index(
277 rpcenv
: &mut dyn RpcEnvironment
,
278 ) -> Result
<Value
, Error
> {
280 let env
: &BackupEnvironment
= rpcenv
.as_ref();
282 println
!("PARAM: {:?}", param
);
284 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
285 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
287 let archive_name
= name
.clone();
288 if !archive_name
.ends_with(".fidx") {
289 bail
!("wrong archive extension: '{}'", archive_name
);
292 let mut path
= env
.backup_dir
.relative_path();
293 path
.push(archive_name
);
295 let chunk_size
= 4096*1024; // todo: ??
297 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
298 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
300 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
306 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
307 &ApiHandler
::Sync(&dynamic_append
),
309 "Append chunk to dynamic index writer.",
314 &IntegerSchema
::new("Dynamic writer ID.")
322 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
328 "Chunk offset list.",
329 &IntegerSchema
::new("Corresponding chunk offsets.")
341 rpcenv
: &mut dyn RpcEnvironment
,
342 ) -> Result
<Value
, Error
> {
344 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
345 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
346 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
348 if offset_list
.len() != digest_list
.len() {
349 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
352 let env
: &BackupEnvironment
= rpcenv
.as_ref();
354 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
356 for (i
, item
) in digest_list
.iter().enumerate() {
357 let digest_str
= item
.as_str().unwrap();
358 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
359 let offset
= offset_list
[i
].as_u64().unwrap();
360 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
362 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
364 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
371 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
372 &ApiHandler
::Sync(&fixed_append
),
374 "Append chunk to fixed index writer.",
379 &IntegerSchema
::new("Fixed writer ID.")
387 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
393 "Chunk offset list.",
394 &IntegerSchema
::new("Corresponding chunk offsets.")
406 rpcenv
: &mut dyn RpcEnvironment
,
407 ) -> Result
<Value
, Error
> {
409 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
410 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
411 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
413 if offset_list
.len() != digest_list
.len() {
414 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
417 let env
: &BackupEnvironment
= rpcenv
.as_ref();
419 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
421 for (i
, item
) in digest_list
.iter().enumerate() {
422 let digest_str
= item
.as_str().unwrap();
423 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
424 let offset
= offset_list
[i
].as_u64().unwrap();
425 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
427 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
429 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
436 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
437 &ApiHandler
::Sync(&close_dynamic_index
),
439 "Close dynamic index writer.",
444 &IntegerSchema
::new("Dynamic writer ID.")
452 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
459 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
463 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
468 fn close_dynamic_index (
471 rpcenv
: &mut dyn RpcEnvironment
,
472 ) -> Result
<Value
, Error
> {
474 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
475 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
476 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
477 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
478 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
480 let env
: &BackupEnvironment
= rpcenv
.as_ref();
482 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
484 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
490 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
491 &ApiHandler
::Sync(&close_fixed_index
),
493 "Close fixed index writer.",
498 &IntegerSchema
::new("Fixed writer ID.")
506 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
513 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
517 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
522 fn close_fixed_index (
525 rpcenv
: &mut dyn RpcEnvironment
,
526 ) -> Result
<Value
, Error
> {
528 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
529 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
530 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
531 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
532 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
534 let env
: &BackupEnvironment
= rpcenv
.as_ref();
536 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
538 env
.log(format
!("sucessfully closed fixed index {}", wid
));
546 rpcenv
: &mut dyn RpcEnvironment
,
547 ) -> Result
<Value
, Error
> {
549 let env
: &BackupEnvironment
= rpcenv
.as_ref();
551 env
.finish_backup()?
;
552 env
.log("sucessfully finished backup");
558 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
559 &ApiHandler
::AsyncHttp(&dynamic_chunk_index
),
562 Download the dynamic chunk index from the previous backup.
563 Simply returns an empty list if this is the first backup.
566 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
571 fn dynamic_chunk_index(
576 rpcenv
: Box
<dyn RpcEnvironment
>,
580 let env
: &BackupEnvironment
= rpcenv
.as_ref();
582 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
584 if !archive_name
.ends_with(".didx") {
585 bail
!("wrong archive extension: '{}'", archive_name
);
588 let empty_response
= {
590 .status(StatusCode
::OK
)
591 .body(Body
::empty())?
594 let last_backup
= match &env
.last_backup
{
596 None
=> return 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_dynamic_reader(path
) {
605 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
606 return Ok(empty_response
);
610 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
612 let count
= index
.index_count();
613 for pos
in 0..count
{
614 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
615 let size
= (end
- start
) as u32;
616 env
.register_chunk(digest
, size
)?
;
619 let reader
= DigestListEncoder
::new(Box
::new(index
));
621 let stream
= WrappedReaderStream
::new(reader
);
623 // fixme: set size, content type?
624 let response
= http
::Response
::builder()
626 .body(Body
::wrap_stream(stream
))?
;
633 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
634 &ApiHandler
::AsyncHttp(&fixed_chunk_index
),
637 Download the fixed chunk index from the previous backup.
638 Simply returns an empty list if this is the first backup.
641 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
646 fn fixed_chunk_index(
651 rpcenv
: Box
<dyn RpcEnvironment
>,
655 let env
: &BackupEnvironment
= rpcenv
.as_ref();
657 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
659 if !archive_name
.ends_with(".fidx") {
660 bail
!("wrong archive extension: '{}'", archive_name
);
663 let empty_response
= {
665 .status(StatusCode
::OK
)
666 .body(Body
::empty())?
669 let last_backup
= match &env
.last_backup
{
671 None
=> return Ok(empty_response
),
674 let mut path
= last_backup
.backup_dir
.relative_path();
675 path
.push(&archive_name
);
677 let index
= match env
.datastore
.open_fixed_reader(path
) {
680 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
681 return Ok(empty_response
);
685 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
687 let count
= index
.index_count();
688 let image_size
= index
.index_bytes();
689 for pos
in 0..count
{
690 let digest
= index
.index_digest(pos
).unwrap();
691 // Note: last chunk can be smaller
692 let start
= (pos
*index
.chunk_size
) as u64;
693 let mut end
= start
+ index
.chunk_size
as u64;
694 if end
> image_size { end = image_size; }
695 let size
= (end
- start
) as u32;
696 env
.register_chunk(*digest
, size
)?
;
699 let reader
= DigestListEncoder
::new(Box
::new(index
));
701 let stream
= WrappedReaderStream
::new(reader
);
703 // fixme: set size, content type?
704 let response
= http
::Response
::builder()
706 .body(Body
::wrap_stream(stream
))?
;