]> git.proxmox.com Git - proxmox-backup.git/blame - src/api2/backup.rs
fix #2988: allow verification after finishing a snapshot
[proxmox-backup.git] / src / api2 / backup.rs
CommitLineData
f7d4e4b5 1use anyhow::{bail, format_err, Error};
92ac375a 2use futures::*;
152764ec 3use hyper::header::{HeaderValue, UPGRADE};
152764ec 4use hyper::http::request::Parts;
cad540e9 5use hyper::{Body, Response, StatusCode};
f9578f3c 6use serde_json::{json, Value};
152764ec 7
9ea4bce4 8use proxmox::{sortable, identity, list_subdirs_api_method};
9f9f7eef 9use proxmox::api::{ApiResponseFuture, ApiHandler, ApiMethod, Router, RpcEnvironment, Permission};
cad540e9
WB
10use proxmox::api::router::SubdirMap;
11use proxmox::api::schema::*;
552c2259 12
b957aa81 13use crate::tools;
42a87f7b 14use crate::server::{WorkerTask, H2Service};
21ee7912 15use crate::backup::*;
6762db70 16use crate::api2::types::*;
54552dda 17use crate::config::acl::PRIV_DATASTORE_BACKUP;
365f0f72 18use crate::config::cached_user_info::CachedUserInfo;
7d6c4c39 19use crate::tools::fs::lock_dir_noblock_shared;
152764ec 20
d95ced64
DM
21mod environment;
22use environment::*;
23
21ee7912
DM
24mod upload_chunk;
25use upload_chunk::*;
26
255f378a
DM
27pub const ROUTER: Router = Router::new()
28 .upgrade(&API_METHOD_UPGRADE_BACKUP);
29
552c2259 30#[sortable]
255f378a 31pub const API_METHOD_UPGRADE_BACKUP: ApiMethod = ApiMethod::new(
329d40b5 32 &ApiHandler::AsyncHttp(&upgrade_to_backup_protocol),
255f378a
DM
33 &ObjectSchema::new(
34 concat!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1!(), "')."),
552c2259 35 &sorted!([
66c49c21 36 ("store", false, &DATASTORE_SCHEMA),
255f378a
DM
37 ("backup-type", false, &BACKUP_TYPE_SCHEMA),
38 ("backup-id", false, &BACKUP_ID_SCHEMA),
39 ("backup-time", false, &BACKUP_TIME_SCHEMA),
40 ("debug", true, &BooleanSchema::new("Enable verbose debug logging.").schema()),
61d7b501 41 ("benchmark", true, &BooleanSchema::new("Job is a benchmark (do not keep data).").schema()),
552c2259 42 ]),
152764ec 43 )
365f0f72
DM
44).access(
45 // Note: parameter 'store' is no uri parameter, so we need to test inside function body
54552dda 46 Some("The user needs Datastore.Backup privilege on /datastore/{store} and needs to own the backup group."),
365f0f72
DM
47 &Permission::Anybody
48);
152764ec 49
0aadd40b 50fn upgrade_to_backup_protocol(
152764ec
DM
51 parts: Parts,
52 req_body: Body,
0aadd40b 53 param: Value,
255f378a 54 _info: &ApiMethod,
dd5495d6 55 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 56) -> ApiResponseFuture {
0aadd40b 57
54552dda 58async move {
a42d1f55 59 let debug = param["debug"].as_bool().unwrap_or(false);
61d7b501 60 let benchmark = param["benchmark"].as_bool().unwrap_or(false);
a42d1f55 61
e7cb4dc5 62 let userid: Userid = rpcenv.get_user().unwrap().parse()?;
365f0f72 63
bb105f9d 64 let store = tools::required_string_param(&param, "store")?.to_owned();
365f0f72
DM
65
66 let user_info = CachedUserInfo::new()?;
e7cb4dc5 67 user_info.check_privs(&userid, &["datastore", &store], PRIV_DATASTORE_BACKUP, false)?;
365f0f72 68
bb105f9d 69 let datastore = DataStore::lookup_datastore(&store)?;
21ee7912 70
0aadd40b
DM
71 let backup_type = tools::required_string_param(&param, "backup-type")?;
72 let backup_id = tools::required_string_param(&param, "backup-id")?;
ca5d0b61 73 let backup_time = tools::required_integer_param(&param, "backup-time")?;
152764ec
DM
74
75 let protocols = parts
76 .headers
77 .get("UPGRADE")
78 .ok_or_else(|| format_err!("missing Upgrade header"))?
79 .to_str()?;
80
986bef16 81 if protocols != PROXMOX_BACKUP_PROTOCOL_ID_V1!() {
152764ec
DM
82 bail!("invalid protocol name");
83 }
84
96e95fc1
DM
85 if parts.version >= http::version::Version::HTTP_2 {
86 bail!("unexpected http version '{:?}' (expected version < 2)", parts.version);
87 }
88
0aadd40b 89 let worker_id = format!("{}_{}_{}", store, backup_type, backup_id);
d9bd06ea 90
58c8d7d9 91 let env_type = rpcenv.env_type();
92ac375a 92
51a4f63f 93 let backup_group = BackupGroup::new(backup_type, backup_id);
1fc82c41 94
61d7b501
HL
95 let worker_type = if backup_type == "host" && backup_id == "benchmark" {
96 if !benchmark {
97 bail!("unable to run benchmark without --benchmark flags");
98 }
99 "benchmark"
100 } else {
101 if benchmark {
102 bail!("benchmark flags is only allowed on 'host/benchmark'");
103 }
104 "backup"
105 };
106
1fc82c41 107 // lock backup group to only allow one backup per group at a time
e7cb4dc5 108 let (owner, _group_guard) = datastore.create_locked_backup_group(&backup_group, &userid)?;
1fc82c41 109
54552dda 110 // permission check
61d7b501
HL
111 if owner != userid && worker_type != "benchmark" {
112 // only the owner is allowed to create additional snapshots
e7cb4dc5 113 bail!("backup owner check failed ({} != {})", userid, owner);
54552dda
DM
114 }
115
0af2da04
SR
116 let last_backup = {
117 let info = BackupInfo::last_backup(&datastore.base_path(), &backup_group, true).unwrap_or(None);
118 if let Some(info) = info {
119 let (manifest, _) = datastore.load_manifest(&info.backup_dir)?;
120 let verify = manifest.unprotected["verify_state"].clone();
121 match serde_json::from_value::<SnapshotVerifyState>(verify) {
122 Ok(verify) => {
d10332a1
SR
123 match verify.state {
124 VerifyState::Ok => Some(info),
125 VerifyState::Failed => None,
0af2da04
SR
126 }
127 },
128 Err(_) => {
129 // no verify state found, treat as valid
130 Some(info)
131 }
132 }
133 } else {
134 None
135 }
136 };
137
d09db6c2 138 let backup_dir = BackupDir::with_group(backup_group.clone(), backup_time)?;
ca5d0b61 139
81f29351 140 let _last_guard = if let Some(last) = &last_backup {
ca5d0b61
DM
141 if backup_dir.backup_time() <= last.backup_dir.backup_time() {
142 bail!("backup timestamp is older than last backup.");
143 }
81f29351
SR
144
145 // lock last snapshot to prevent forgetting/pruning it during backup
146 let full_path = datastore.snapshot_path(&last.backup_dir);
7d6c4c39 147 Some(lock_dir_noblock_shared(&full_path, "snapshot", "base snapshot is already locked by another operation")?)
81f29351
SR
148 } else {
149 None
150 };
f9578f3c 151
0698f78d 152 let (path, is_new, snap_guard) = datastore.create_locked_backup_dir(&backup_dir)?;
add5861e 153 if !is_new { bail!("backup directory already exists."); }
f9578f3c 154
61d7b501
HL
155
156 WorkerTask::spawn(worker_type, Some(worker_id), userid.clone(), true, move |worker| {
bb105f9d 157 let mut env = BackupEnvironment::new(
e7cb4dc5 158 env_type, userid, worker.clone(), datastore, backup_dir);
b02a52e3 159
a42d1f55 160 env.debug = debug;
bb105f9d 161 env.last_backup = last_backup;
b02a52e3 162
61d7b501 163 env.log(format!("starting new {} on datastore '{}': {:?}", worker_type, store, path));
bb105f9d 164
255f378a 165 let service = H2Service::new(env.clone(), worker.clone(), &BACKUP_API_ROUTER, debug);
72375ce6 166
a66ab8ae
DM
167 let abort_future = worker.abort_future();
168
372724af 169 let env2 = env.clone();
bb105f9d 170
6650a242 171 let mut req_fut = req_body
152764ec 172 .on_upgrade()
92ac375a 173 .map_err(Error::from)
152764ec 174 .and_then(move |conn| {
6650a242 175 env2.debug("protocol upgrade done");
92ac375a
DM
176
177 let mut http = hyper::server::conn::Http::new();
178 http.http2_only(true);
adec8ea2 179 // increase window size: todo - find optiomal size
771953f9
DM
180 let window_size = 32*1024*1024; // max = (1 << 31) - 2
181 http.http2_initial_stream_window_size(window_size);
182 http.http2_initial_connection_window_size(window_size);
cf9ea3c4 183 http.http2_max_frame_size(4*1024*1024);
92ac375a 184
d9bd06ea
DM
185 http.serve_connection(conn, service)
186 .map_err(Error::from)
59b2baa0 187 });
6650a242 188 let mut abort_future = abort_future
59b2baa0
WB
189 .map(|_| Err(format_err!("task aborted")));
190
6650a242 191 async move {
95bda2f2
SR
192 // keep flock until task ends
193 let _group_guard = _group_guard;
0698f78d 194 let snap_guard = snap_guard;
81f29351 195 let _last_guard = _last_guard;
95bda2f2 196
6650a242
DC
197 let res = select!{
198 req = req_fut => req,
199 abrt = abort_future => abrt,
200 };
61d7b501
HL
201 if benchmark {
202 env.log("benchmark finished successfully");
9070d11f 203 tools::runtime::block_in_place(|| env.remove_backup())?;
61d7b501
HL
204 return Ok(());
205 }
0698f78d
SR
206
207 let verify = |env: BackupEnvironment| {
208 if let Err(err) = env.verify_after_complete(snap_guard) {
209 env.log(format!(
210 "backup finished, but starting the requested verify task failed: {}",
211 err
212 ));
213 }
214 };
215
6650a242
DC
216 match (res, env.ensure_finished()) {
217 (Ok(_), Ok(())) => {
add5861e 218 env.log("backup finished successfully");
0698f78d 219 verify(env);
6650a242
DC
220 Ok(())
221 },
222 (Err(err), Ok(())) => {
223 // ignore errors after finish
224 env.log(format!("backup had errors but finished: {}", err));
0698f78d 225 verify(env);
6650a242
DC
226 Ok(())
227 },
228 (Ok(_), Err(err)) => {
229 env.log(format!("backup ended and finish failed: {}", err));
230 env.log("removing unfinished backup");
455f2ad2 231 tools::runtime::block_in_place(|| env.remove_backup())?;
6650a242
DC
232 Err(err)
233 },
234 (Err(err), Err(_)) => {
235 env.log(format!("backup failed: {}", err));
236 env.log("removing failed backup");
9070d11f 237 tools::runtime::block_in_place(|| env.remove_backup())?;
6650a242
DC
238 Err(err)
239 },
240 }
241 }
090ac9f7
DM
242 })?;
243
244 let response = Response::builder()
245 .status(StatusCode::SWITCHING_PROTOCOLS)
986bef16 246 .header(UPGRADE, HeaderValue::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1!()))
090ac9f7
DM
247 .body(Body::empty())?;
248
ad51d02a
DM
249 Ok(response)
250 }.boxed()
152764ec 251}
92ac375a 252
255f378a
DM
253pub const BACKUP_API_SUBDIRS: SubdirMap = &[
254 (
255 "blob", &Router::new()
256 .upload(&API_METHOD_UPLOAD_BLOB)
257 ),
258 (
259 "dynamic_chunk", &Router::new()
260 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK)
261 ),
262 (
263 "dynamic_close", &Router::new()
264 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX)
265 ),
266 (
267 "dynamic_index", &Router::new()
255f378a
DM
268 .post(&API_METHOD_CREATE_DYNAMIC_INDEX)
269 .put(&API_METHOD_DYNAMIC_APPEND)
270 ),
271 (
272 "finish", &Router::new()
273 .post(
274 &ApiMethod::new(
275 &ApiHandler::Sync(&finish_backup),
276 &ObjectSchema::new("Mark backup as finished.", &[])
372724af 277 )
255f378a
DM
278 )
279 ),
280 (
281 "fixed_chunk", &Router::new()
282 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK)
283 ),
284 (
285 "fixed_close", &Router::new()
286 .post(&API_METHOD_CLOSE_FIXED_INDEX)
287 ),
288 (
289 "fixed_index", &Router::new()
255f378a
DM
290 .post(&API_METHOD_CREATE_FIXED_INDEX)
291 .put(&API_METHOD_FIXED_APPEND)
292 ),
b957aa81
DM
293 (
294 "previous", &Router::new()
295 .download(&API_METHOD_DOWNLOAD_PREVIOUS)
296 ),
255f378a
DM
297 (
298 "speedtest", &Router::new()
299 .upload(&API_METHOD_UPLOAD_SPEEDTEST)
300 ),
301];
302
303pub const BACKUP_API_ROUTER: Router = Router::new()
304 .get(&list_subdirs_api_method!(BACKUP_API_SUBDIRS))
305 .subdirs(BACKUP_API_SUBDIRS);
306
3d229a4a
DM
307#[sortable]
308pub const API_METHOD_CREATE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
309 &ApiHandler::Sync(&create_dynamic_index),
310 &ObjectSchema::new(
311 "Create dynamic chunk index file.",
312 &sorted!([
313 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
314 ]),
315 )
316);
317
f9578f3c
DM
318fn create_dynamic_index(
319 param: Value,
3d229a4a 320 _info: &ApiMethod,
dd5495d6 321 rpcenv: &mut dyn RpcEnvironment,
f9578f3c
DM
322) -> Result<Value, Error> {
323
324 let env: &BackupEnvironment = rpcenv.as_ref();
f9578f3c 325
8bea85b4 326 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
f9578f3c 327
4af0ee05 328 let archive_name = name.clone();
0997967d 329 if !archive_name.ends_with(".didx") {
a42fa400 330 bail!("wrong archive extension: '{}'", archive_name);
f9578f3c
DM
331 }
332
6b95c7df 333 let mut path = env.backup_dir.relative_path();
f9578f3c
DM
334 path.push(archive_name);
335
976595e1 336 let index = env.datastore.create_dynamic_writer(&path)?;
8bea85b4 337 let wid = env.register_dynamic_writer(index, name)?;
f9578f3c 338
bb105f9d 339 env.log(format!("created new dynamic index {} ({:?})", wid, path));
f9578f3c 340
bb105f9d 341 Ok(json!(wid))
f9578f3c
DM
342}
343
552c2259 344#[sortable]
255f378a
DM
345pub const API_METHOD_CREATE_FIXED_INDEX: ApiMethod = ApiMethod::new(
346 &ApiHandler::Sync(&create_fixed_index),
347 &ObjectSchema::new(
348 "Create fixed chunk index file.",
552c2259 349 &sorted!([
255f378a
DM
350 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
351 ("size", false, &IntegerSchema::new("File size.")
352 .minimum(1)
353 .schema()
354 ),
facd9801
SR
355 ("reuse-csum", true, &StringSchema::new("If set, compare last backup's \
356 csum and reuse index for incremental backup if it matches.").schema()),
552c2259 357 ]),
a42fa400 358 )
255f378a 359);
a42fa400
DM
360
361fn create_fixed_index(
362 param: Value,
363 _info: &ApiMethod,
dd5495d6 364 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
365) -> Result<Value, Error> {
366
367 let env: &BackupEnvironment = rpcenv.as_ref();
368
a42fa400
DM
369 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
370 let size = tools::required_integer_param(&param, "size")? as usize;
facd9801 371 let reuse_csum = param["reuse-csum"].as_str();
a42fa400 372
4af0ee05 373 let archive_name = name.clone();
0997967d 374 if !archive_name.ends_with(".fidx") {
a42fa400 375 bail!("wrong archive extension: '{}'", archive_name);
a42fa400
DM
376 }
377
378 let mut path = env.backup_dir.relative_path();
facd9801 379 path.push(&archive_name);
a42fa400
DM
380
381 let chunk_size = 4096*1024; // todo: ??
382
facd9801
SR
383 // do incremental backup if csum is set
384 let mut reader = None;
385 let mut incremental = false;
386 if let Some(csum) = reuse_csum {
387 incremental = true;
388 let last_backup = match &env.last_backup {
389 Some(info) => info,
390 None => {
0af2da04 391 bail!("cannot reuse index - no valid previous backup exists");
facd9801
SR
392 }
393 };
394
395 let mut last_path = last_backup.backup_dir.relative_path();
396 last_path.push(&archive_name);
397
398 let index = match env.datastore.open_fixed_reader(last_path) {
399 Ok(index) => index,
400 Err(_) => {
401 bail!("cannot reuse index - no previous backup exists for archive");
402 }
403 };
404
405 let (old_csum, _) = index.compute_csum();
406 let old_csum = proxmox::tools::digest_to_hex(&old_csum);
407 if old_csum != csum {
408 bail!("expected csum ({}) doesn't match last backup's ({}), cannot do incremental backup",
409 csum, old_csum);
410 }
411
412 reader = Some(index);
413 }
414
415 let mut writer = env.datastore.create_fixed_writer(&path, size, chunk_size)?;
416
417 if let Some(reader) = reader {
418 writer.clone_data_from(&reader)?;
419 }
420
421 let wid = env.register_fixed_writer(writer, name, size, chunk_size as u32, incremental)?;
a42fa400
DM
422
423 env.log(format!("created new fixed index {} ({:?})", wid, path));
424
425 Ok(json!(wid))
426}
427
552c2259 428#[sortable]
255f378a
DM
429pub const API_METHOD_DYNAMIC_APPEND: ApiMethod = ApiMethod::new(
430 &ApiHandler::Sync(&dynamic_append),
431 &ObjectSchema::new(
432 "Append chunk to dynamic index writer.",
552c2259 433 &sorted!([
255f378a
DM
434 (
435 "wid",
436 false,
437 &IntegerSchema::new("Dynamic writer ID.")
438 .minimum(1)
439 .maximum(256)
440 .schema()
441 ),
442 (
443 "digest-list",
444 false,
445 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
446 ),
447 (
448 "offset-list",
449 false,
450 &ArraySchema::new(
451 "Chunk offset list.",
452 &IntegerSchema::new("Corresponding chunk offsets.")
453 .minimum(0)
454 .schema()
455 ).schema()
456 ),
552c2259 457 ]),
82ab7230 458 )
255f378a 459);
82ab7230
DM
460
461fn dynamic_append (
462 param: Value,
463 _info: &ApiMethod,
dd5495d6 464 rpcenv: &mut dyn RpcEnvironment,
82ab7230
DM
465) -> Result<Value, Error> {
466
467 let wid = tools::required_integer_param(&param, "wid")? as usize;
aa1b2e04 468 let digest_list = tools::required_array_param(&param, "digest-list")?;
417cb073 469 let offset_list = tools::required_array_param(&param, "offset-list")?;
aa1b2e04 470
417cb073
DM
471 if offset_list.len() != digest_list.len() {
472 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
473 }
474
82ab7230
DM
475 let env: &BackupEnvironment = rpcenv.as_ref();
476
39e60bd6
DM
477 env.debug(format!("dynamic_append {} chunks", digest_list.len()));
478
417cb073 479 for (i, item) in digest_list.iter().enumerate() {
aa1b2e04 480 let digest_str = item.as_str().unwrap();
bffd40d6 481 let digest = proxmox::tools::hex_to_digest(digest_str)?;
417cb073 482 let offset = offset_list[i].as_u64().unwrap();
aa1b2e04 483 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 484
417cb073 485 env.dynamic_writer_append_chunk(wid, offset, size, &digest)?;
82ab7230 486
add5861e 487 env.debug(format!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str, wid, offset, size));
aa1b2e04 488 }
82ab7230
DM
489
490 Ok(Value::Null)
491}
492
552c2259 493#[sortable]
255f378a
DM
494pub const API_METHOD_FIXED_APPEND: ApiMethod = ApiMethod::new(
495 &ApiHandler::Sync(&fixed_append),
496 &ObjectSchema::new(
497 "Append chunk to fixed index writer.",
552c2259 498 &sorted!([
255f378a
DM
499 (
500 "wid",
501 false,
502 &IntegerSchema::new("Fixed writer ID.")
503 .minimum(1)
504 .maximum(256)
505 .schema()
506 ),
507 (
508 "digest-list",
509 false,
510 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
511 ),
512 (
513 "offset-list",
514 false,
515 &ArraySchema::new(
516 "Chunk offset list.",
517 &IntegerSchema::new("Corresponding chunk offsets.")
518 .minimum(0)
519 .schema()
520 ).schema()
a42fa400 521 )
552c2259 522 ]),
a42fa400 523 )
255f378a 524);
a42fa400
DM
525
526fn fixed_append (
527 param: Value,
528 _info: &ApiMethod,
dd5495d6 529 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
530) -> Result<Value, Error> {
531
532 let wid = tools::required_integer_param(&param, "wid")? as usize;
533 let digest_list = tools::required_array_param(&param, "digest-list")?;
534 let offset_list = tools::required_array_param(&param, "offset-list")?;
535
a42fa400
DM
536 if offset_list.len() != digest_list.len() {
537 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
538 }
539
540 let env: &BackupEnvironment = rpcenv.as_ref();
541
39e60bd6
DM
542 env.debug(format!("fixed_append {} chunks", digest_list.len()));
543
a42fa400
DM
544 for (i, item) in digest_list.iter().enumerate() {
545 let digest_str = item.as_str().unwrap();
bffd40d6 546 let digest = proxmox::tools::hex_to_digest(digest_str)?;
a42fa400
DM
547 let offset = offset_list[i].as_u64().unwrap();
548 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 549
a42fa400
DM
550 env.fixed_writer_append_chunk(wid, offset, size, &digest)?;
551
add5861e 552 env.debug(format!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str, wid, offset, size));
a42fa400
DM
553 }
554
555 Ok(Value::Null)
556}
557
552c2259 558#[sortable]
255f378a
DM
559pub const API_METHOD_CLOSE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
560 &ApiHandler::Sync(&close_dynamic_index),
561 &ObjectSchema::new(
562 "Close dynamic index writer.",
552c2259 563 &sorted!([
255f378a
DM
564 (
565 "wid",
566 false,
567 &IntegerSchema::new("Dynamic writer ID.")
568 .minimum(1)
569 .maximum(256)
570 .schema()
571 ),
572 (
573 "chunk-count",
574 false,
575 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
576 .minimum(1)
577 .schema()
578 ),
579 (
580 "size",
581 false,
582 &IntegerSchema::new("File size. This is used to verify that the server got all data.")
583 .minimum(1)
584 .schema()
585 ),
586 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 587 ]),
a2077252 588 )
255f378a 589);
a2077252
DM
590
591fn close_dynamic_index (
592 param: Value,
593 _info: &ApiMethod,
dd5495d6 594 rpcenv: &mut dyn RpcEnvironment,
a2077252
DM
595) -> Result<Value, Error> {
596
597 let wid = tools::required_integer_param(&param, "wid")? as usize;
8bea85b4
DM
598 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
599 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
600 let csum_str = tools::required_string_param(&param, "csum")?;
601 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a2077252
DM
602
603 let env: &BackupEnvironment = rpcenv.as_ref();
604
fb6026b6 605 env.dynamic_writer_close(wid, chunk_count, size, csum)?;
a2077252 606
add5861e 607 env.log(format!("successfully closed dynamic index {}", wid));
bb105f9d 608
a2077252
DM
609 Ok(Value::Null)
610}
611
552c2259 612#[sortable]
255f378a
DM
613pub const API_METHOD_CLOSE_FIXED_INDEX: ApiMethod = ApiMethod::new(
614 &ApiHandler::Sync(&close_fixed_index),
615 &ObjectSchema::new(
616 "Close fixed index writer.",
552c2259 617 &sorted!([
255f378a
DM
618 (
619 "wid",
620 false,
621 &IntegerSchema::new("Fixed writer ID.")
622 .minimum(1)
623 .maximum(256)
624 .schema()
625 ),
626 (
627 "chunk-count",
628 false,
facd9801
SR
629 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks. Ignored for incremental backups.")
630 .minimum(0)
255f378a
DM
631 .schema()
632 ),
633 (
634 "size",
635 false,
facd9801
SR
636 &IntegerSchema::new("File size. This is used to verify that the server got all data. Ignored for incremental backups.")
637 .minimum(0)
255f378a
DM
638 .schema()
639 ),
640 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 641 ]),
a42fa400 642 )
255f378a 643);
a42fa400
DM
644
645fn close_fixed_index (
646 param: Value,
647 _info: &ApiMethod,
dd5495d6 648 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
649) -> Result<Value, Error> {
650
651 let wid = tools::required_integer_param(&param, "wid")? as usize;
652 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
653 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
654 let csum_str = tools::required_string_param(&param, "csum")?;
655 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a42fa400
DM
656
657 let env: &BackupEnvironment = rpcenv.as_ref();
658
fb6026b6 659 env.fixed_writer_close(wid, chunk_count, size, csum)?;
a42fa400 660
add5861e 661 env.log(format!("successfully closed fixed index {}", wid));
a42fa400
DM
662
663 Ok(Value::Null)
664}
a2077252 665
372724af
DM
666fn finish_backup (
667 _param: Value,
668 _info: &ApiMethod,
dd5495d6 669 rpcenv: &mut dyn RpcEnvironment,
372724af
DM
670) -> Result<Value, Error> {
671
672 let env: &BackupEnvironment = rpcenv.as_ref();
673
674 env.finish_backup()?;
add5861e 675 env.log("successfully finished backup");
372724af
DM
676
677 Ok(Value::Null)
678}
a2077252 679
552c2259 680#[sortable]
b957aa81
DM
681pub const API_METHOD_DOWNLOAD_PREVIOUS: ApiMethod = ApiMethod::new(
682 &ApiHandler::AsyncHttp(&download_previous),
255f378a 683 &ObjectSchema::new(
b957aa81 684 "Download archive from previous backup.",
552c2259
DM
685 &sorted!([
686 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA)
687 ]),
a42fa400 688 )
255f378a 689);
a42fa400 690
b957aa81 691fn download_previous(
d3611366
DM
692 _parts: Parts,
693 _req_body: Body,
694 param: Value,
255f378a 695 _info: &ApiMethod,
dd5495d6 696 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 697) -> ApiResponseFuture {
d3611366 698
ad51d02a
DM
699 async move {
700 let env: &BackupEnvironment = rpcenv.as_ref();
d3611366 701
ad51d02a 702 let archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
d3611366 703
ad51d02a
DM
704 let last_backup = match &env.last_backup {
705 Some(info) => info,
0af2da04 706 None => bail!("no valid previous backup"),
ad51d02a
DM
707 };
708
b957aa81 709 let mut path = env.datastore.snapshot_path(&last_backup.backup_dir);
ad51d02a
DM
710 path.push(&archive_name);
711
fe3e65c3
DM
712 {
713 let index: Option<Box<dyn IndexFile>> = match archive_type(&archive_name)? {
714 ArchiveType::FixedIndex => {
715 let index = env.datastore.open_fixed_reader(&path)?;
716 Some(Box::new(index))
717 }
718 ArchiveType::DynamicIndex => {
719 let index = env.datastore.open_dynamic_reader(&path)?;
720 Some(Box::new(index))
721 }
722 _ => { None }
723 };
724 if let Some(index) = index {
725 env.log(format!("register chunks in '{}' from previous backup.", archive_name));
726
727 for pos in 0..index.index_count() {
728 let info = index.chunk_info(pos).unwrap();
729 let size = info.range.end - info.range.start;
730 env.register_chunk(info.digest, size as u32)?;
731 }
732 }
733 }
734
735 env.log(format!("download '{}' from previous backup.", archive_name));
b957aa81 736 crate::api2::helpers::create_download_response(path).await
ad51d02a 737 }.boxed()
a42fa400 738}