1 use anyhow
::{bail, format_err, Error}
;
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, list_subdirs_api_method}
;
9 use proxmox
::api
::{ApiResponseFuture, ApiHandler, ApiMethod, Router, RpcEnvironment, Permission}
;
10 use proxmox
::api
::router
::SubdirMap
;
11 use proxmox
::api
::schema
::*;
13 use crate::tools
::{self, WrappedReaderStream}
;
14 use crate::server
::{WorkerTask, H2Service}
;
16 use crate::api2
::types
::*;
17 use crate::config
::acl
::PRIV_DATASTORE_ALLOCATE_SPACE
;
25 pub const ROUTER
: Router
= Router
::new()
26 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
29 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
30 &ApiHandler
::AsyncHttp(&upgrade_to_backup_protocol
),
32 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1
!(), "')."),
34 ("store", false, &DATASTORE_SCHEMA
),
35 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
36 ("backup-id", false, &BACKUP_ID_SCHEMA
),
37 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
38 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
41 ).access(None
, &Permission
::Privilege(&["datastore", "{store}"], PRIV_DATASTORE_ALLOCATE_SPACE
, false));
43 fn upgrade_to_backup_protocol(
48 rpcenv
: Box
<dyn RpcEnvironment
>,
49 ) -> ApiResponseFuture
{
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.");
88 // fixme: abort if last backup is still running - howto test?
89 // Idea: write upid into a file inside snapshot dir. then test if
90 // it is still running here.
93 let (path
, is_new
) = datastore
.create_backup_dir(&backup_dir
)?
;
94 if !is_new { bail!("backup directorty already exists."); }
96 WorkerTask
::spawn("backup", Some(worker_id
), &username
.clone(), true, move |worker
| {
97 let mut env
= BackupEnvironment
::new(
98 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
101 env
.last_backup
= last_backup
;
103 env
.log(format
!("starting new backup on datastore '{}': {:?}", store
, path
));
105 let service
= H2Service
::new(env
.clone(), worker
.clone(), &BACKUP_API_ROUTER
, debug
);
107 let abort_future
= worker
.abort_future();
109 let env2
= env
.clone();
111 let mut req_fut
= req_body
113 .map_err(Error
::from
)
114 .and_then(move |conn
| {
115 env2
.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 let mut abort_future
= abort_future
128 .map(|_
| Err(format_err
!("task aborted")));
132 req
= req_fut
=> req
,
133 abrt
= abort_future
=> abrt
,
136 match (res
, env
.ensure_finished()) {
138 env
.log("backup finished sucessfully");
141 (Err(err
), Ok(())) => {
142 // ignore errors after finish
143 env
.log(format
!("backup had errors but finished: {}", err
));
146 (Ok(_
), Err(err
)) => {
147 env
.log(format
!("backup ended and finish failed: {}", err
));
148 env
.log("removing unfinished backup");
149 env
.remove_backup()?
;
152 (Err(err
), Err(_
)) => {
153 env
.log(format
!("backup failed: {}", err
));
154 env
.log("removing failed backup");
155 env
.remove_backup()?
;
162 let response
= Response
::builder()
163 .status(StatusCode
::SWITCHING_PROTOCOLS
)
164 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
165 .body(Body
::empty())?
;
171 pub const BACKUP_API_SUBDIRS
: SubdirMap
= &[
173 "blob", &Router
::new()
174 .upload(&API_METHOD_UPLOAD_BLOB
)
177 "dynamic_chunk", &Router
::new()
178 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK
)
181 "dynamic_close", &Router
::new()
182 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX
)
185 "dynamic_index", &Router
::new()
186 .download(&API_METHOD_DYNAMIC_CHUNK_INDEX
)
187 .post(&API_METHOD_CREATE_DYNAMIC_INDEX
)
188 .put(&API_METHOD_DYNAMIC_APPEND
)
191 "finish", &Router
::new()
194 &ApiHandler
::Sync(&finish_backup
),
195 &ObjectSchema
::new("Mark backup as finished.", &[])
200 "fixed_chunk", &Router
::new()
201 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK
)
204 "fixed_close", &Router
::new()
205 .post(&API_METHOD_CLOSE_FIXED_INDEX
)
208 "fixed_index", &Router
::new()
209 .download(&API_METHOD_FIXED_CHUNK_INDEX
)
210 .post(&API_METHOD_CREATE_FIXED_INDEX
)
211 .put(&API_METHOD_FIXED_APPEND
)
214 "speedtest", &Router
::new()
215 .upload(&API_METHOD_UPLOAD_SPEEDTEST
)
219 pub const BACKUP_API_ROUTER
: Router
= Router
::new()
220 .get(&list_subdirs_api_method
!(BACKUP_API_SUBDIRS
))
221 .subdirs(BACKUP_API_SUBDIRS
);
224 pub const API_METHOD_CREATE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
225 &ApiHandler
::Sync(&create_dynamic_index
),
227 "Create dynamic chunk index file.",
229 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
234 fn create_dynamic_index(
237 rpcenv
: &mut dyn RpcEnvironment
,
238 ) -> Result
<Value
, Error
> {
240 let env
: &BackupEnvironment
= rpcenv
.as_ref();
242 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
244 let archive_name
= name
.clone();
245 if !archive_name
.ends_with(".didx") {
246 bail
!("wrong archive extension: '{}'", archive_name
);
249 let mut path
= env
.backup_dir
.relative_path();
250 path
.push(archive_name
);
252 let index
= env
.datastore
.create_dynamic_writer(&path
)?
;
253 let wid
= env
.register_dynamic_writer(index
, name
)?
;
255 env
.log(format
!("created new dynamic index {} ({:?})", wid
, path
));
261 pub const API_METHOD_CREATE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
262 &ApiHandler
::Sync(&create_fixed_index
),
264 "Create fixed chunk index file.",
266 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
267 ("size", false, &IntegerSchema
::new("File size.")
275 fn create_fixed_index(
278 rpcenv
: &mut dyn RpcEnvironment
,
279 ) -> Result
<Value
, Error
> {
281 let env
: &BackupEnvironment
= rpcenv
.as_ref();
283 println
!("PARAM: {:?}", param
);
285 let name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
286 let size
= tools
::required_integer_param(¶m
, "size")?
as usize;
288 let archive_name
= name
.clone();
289 if !archive_name
.ends_with(".fidx") {
290 bail
!("wrong archive extension: '{}'", archive_name
);
293 let mut path
= env
.backup_dir
.relative_path();
294 path
.push(archive_name
);
296 let chunk_size
= 4096*1024; // todo: ??
298 let index
= env
.datastore
.create_fixed_writer(&path
, size
, chunk_size
)?
;
299 let wid
= env
.register_fixed_writer(index
, name
, size
, chunk_size
as u32)?
;
301 env
.log(format
!("created new fixed index {} ({:?})", wid
, path
));
307 pub const API_METHOD_DYNAMIC_APPEND
: ApiMethod
= ApiMethod
::new(
308 &ApiHandler
::Sync(&dynamic_append
),
310 "Append chunk to dynamic index writer.",
315 &IntegerSchema
::new("Dynamic writer ID.")
323 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
329 "Chunk offset list.",
330 &IntegerSchema
::new("Corresponding chunk offsets.")
342 rpcenv
: &mut dyn RpcEnvironment
,
343 ) -> Result
<Value
, Error
> {
345 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
346 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
347 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
349 if offset_list
.len() != digest_list
.len() {
350 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
353 let env
: &BackupEnvironment
= rpcenv
.as_ref();
355 env
.debug(format
!("dynamic_append {} chunks", digest_list
.len()));
357 for (i
, item
) in digest_list
.iter().enumerate() {
358 let digest_str
= item
.as_str().unwrap();
359 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
360 let offset
= offset_list
[i
].as_u64().unwrap();
361 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
363 env
.dynamic_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
365 env
.debug(format
!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
372 pub const API_METHOD_FIXED_APPEND
: ApiMethod
= ApiMethod
::new(
373 &ApiHandler
::Sync(&fixed_append
),
375 "Append chunk to fixed index writer.",
380 &IntegerSchema
::new("Fixed writer ID.")
388 &ArraySchema
::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA
).schema()
394 "Chunk offset list.",
395 &IntegerSchema
::new("Corresponding chunk offsets.")
407 rpcenv
: &mut dyn RpcEnvironment
,
408 ) -> Result
<Value
, Error
> {
410 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
411 let digest_list
= tools
::required_array_param(¶m
, "digest-list")?
;
412 let offset_list
= tools
::required_array_param(¶m
, "offset-list")?
;
414 if offset_list
.len() != digest_list
.len() {
415 bail
!("offset list has wrong length ({} != {})", offset_list
.len(), digest_list
.len());
418 let env
: &BackupEnvironment
= rpcenv
.as_ref();
420 env
.debug(format
!("fixed_append {} chunks", digest_list
.len()));
422 for (i
, item
) in digest_list
.iter().enumerate() {
423 let digest_str
= item
.as_str().unwrap();
424 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
425 let offset
= offset_list
[i
].as_u64().unwrap();
426 let size
= env
.lookup_chunk(&digest
).ok_or_else(|| format_err
!("no such chunk {}", digest_str
))?
;
428 env
.fixed_writer_append_chunk(wid
, offset
, size
, &digest
)?
;
430 env
.debug(format
!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str
, wid
, offset
, size
));
437 pub const API_METHOD_CLOSE_DYNAMIC_INDEX
: ApiMethod
= ApiMethod
::new(
438 &ApiHandler
::Sync(&close_dynamic_index
),
440 "Close dynamic index writer.",
445 &IntegerSchema
::new("Dynamic writer ID.")
453 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
460 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
464 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
469 fn close_dynamic_index (
472 rpcenv
: &mut dyn RpcEnvironment
,
473 ) -> Result
<Value
, Error
> {
475 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
476 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
477 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
478 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
479 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
481 let env
: &BackupEnvironment
= rpcenv
.as_ref();
483 env
.dynamic_writer_close(wid
, chunk_count
, size
, csum
)?
;
485 env
.log(format
!("sucessfully closed dynamic index {}", wid
));
491 pub const API_METHOD_CLOSE_FIXED_INDEX
: ApiMethod
= ApiMethod
::new(
492 &ApiHandler
::Sync(&close_fixed_index
),
494 "Close fixed index writer.",
499 &IntegerSchema
::new("Fixed writer ID.")
507 &IntegerSchema
::new("Chunk count. This is used to verify that the server got all chunks.")
514 &IntegerSchema
::new("File size. This is used to verify that the server got all data.")
518 ("csum", false, &StringSchema
::new("Digest list checksum.").schema()),
523 fn close_fixed_index (
526 rpcenv
: &mut dyn RpcEnvironment
,
527 ) -> Result
<Value
, Error
> {
529 let wid
= tools
::required_integer_param(¶m
, "wid")?
as usize;
530 let chunk_count
= tools
::required_integer_param(¶m
, "chunk-count")?
as u64;
531 let size
= tools
::required_integer_param(¶m
, "size")?
as u64;
532 let csum_str
= tools
::required_string_param(¶m
, "csum")?
;
533 let csum
= proxmox
::tools
::hex_to_digest(csum_str
)?
;
535 let env
: &BackupEnvironment
= rpcenv
.as_ref();
537 env
.fixed_writer_close(wid
, chunk_count
, size
, csum
)?
;
539 env
.log(format
!("sucessfully closed fixed index {}", wid
));
547 rpcenv
: &mut dyn RpcEnvironment
,
548 ) -> Result
<Value
, Error
> {
550 let env
: &BackupEnvironment
= rpcenv
.as_ref();
552 env
.finish_backup()?
;
553 env
.log("sucessfully finished backup");
559 pub const API_METHOD_DYNAMIC_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
560 &ApiHandler
::AsyncHttp(&dynamic_chunk_index
),
563 Download the dynamic chunk index from the previous backup.
564 Simply returns an empty list if this is the first backup.
567 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
572 fn dynamic_chunk_index(
577 rpcenv
: Box
<dyn RpcEnvironment
>,
578 ) -> ApiResponseFuture
{
581 let env
: &BackupEnvironment
= rpcenv
.as_ref();
583 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
585 if !archive_name
.ends_with(".didx") {
586 bail
!("wrong archive extension: '{}'", archive_name
);
589 let empty_response
= {
591 .status(StatusCode
::OK
)
592 .body(Body
::empty())?
595 let last_backup
= match &env
.last_backup
{
597 None
=> return Ok(empty_response
),
600 let mut path
= last_backup
.backup_dir
.relative_path();
601 path
.push(&archive_name
);
603 let index
= match env
.datastore
.open_dynamic_reader(path
) {
606 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
607 return Ok(empty_response
);
611 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
613 let count
= index
.index_count();
614 for pos
in 0..count
{
615 let (start
, end
, digest
) = index
.chunk_info(pos
)?
;
616 let size
= (end
- start
) as u32;
617 env
.register_chunk(digest
, size
)?
;
620 let reader
= DigestListEncoder
::new(Box
::new(index
));
622 let stream
= WrappedReaderStream
::new(reader
);
624 // fixme: set size, content type?
625 let response
= http
::Response
::builder()
627 .body(Body
::wrap_stream(stream
))?
;
634 pub const API_METHOD_FIXED_CHUNK_INDEX
: ApiMethod
= ApiMethod
::new(
635 &ApiHandler
::AsyncHttp(&fixed_chunk_index
),
638 Download the fixed chunk index from the previous backup.
639 Simply returns an empty list if this is the first backup.
642 ("archive-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
)
647 fn fixed_chunk_index(
652 rpcenv
: Box
<dyn RpcEnvironment
>,
653 ) -> ApiResponseFuture
{
656 let env
: &BackupEnvironment
= rpcenv
.as_ref();
658 let archive_name
= tools
::required_string_param(¶m
, "archive-name")?
.to_owned();
660 if !archive_name
.ends_with(".fidx") {
661 bail
!("wrong archive extension: '{}'", archive_name
);
664 let empty_response
= {
666 .status(StatusCode
::OK
)
667 .body(Body
::empty())?
670 let last_backup
= match &env
.last_backup
{
672 None
=> return Ok(empty_response
),
675 let mut path
= last_backup
.backup_dir
.relative_path();
676 path
.push(&archive_name
);
678 let index
= match env
.datastore
.open_fixed_reader(path
) {
681 env
.log(format
!("there is no last backup for archive '{}'", archive_name
));
682 return Ok(empty_response
);
686 env
.log(format
!("download last backup index for archive '{}'", archive_name
));
688 let count
= index
.index_count();
689 let image_size
= index
.index_bytes();
690 for pos
in 0..count
{
691 let digest
= index
.index_digest(pos
).unwrap();
692 // Note: last chunk can be smaller
693 let start
= (pos
*index
.chunk_size
) as u64;
694 let mut end
= start
+ index
.chunk_size
as u64;
695 if end
> image_size { end = image_size; }
696 let size
= (end
- start
) as u32;
697 env
.register_chunk(*digest
, size
)?
;
700 let reader
= DigestListEncoder
::new(Box
::new(index
));
702 let stream
= WrappedReaderStream
::new(reader
);
704 // fixme: set size, content type?
705 let response
= http
::Response
::builder()
707 .body(Body
::wrap_stream(stream
))?
;