]> git.proxmox.com Git - proxmox-backup.git/blame - src/api2/backup.rs
add benchmark flag to backup creation for proper cleanup when running a benchmark
[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;
81f29351 19use crate::tools::fs::lock_dir_noblock;
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
4dbe1292 116 let last_backup = BackupInfo::last_backup(&datastore.base_path(), &backup_group, true).unwrap_or(None);
95bda2f2 117 let backup_dir = BackupDir::new_with_group(backup_group.clone(), backup_time);
ca5d0b61 118
81f29351 119 let _last_guard = if let Some(last) = &last_backup {
ca5d0b61
DM
120 if backup_dir.backup_time() <= last.backup_dir.backup_time() {
121 bail!("backup timestamp is older than last backup.");
122 }
81f29351
SR
123
124 // lock last snapshot to prevent forgetting/pruning it during backup
125 let full_path = datastore.snapshot_path(&last.backup_dir);
126 Some(lock_dir_noblock(&full_path, "snapshot", "base snapshot is already locked by another operation")?)
127 } else {
128 None
129 };
f9578f3c 130
f23f7543 131 let (path, is_new, _snap_guard) = datastore.create_locked_backup_dir(&backup_dir)?;
add5861e 132 if !is_new { bail!("backup directory already exists."); }
f9578f3c 133
61d7b501
HL
134
135 WorkerTask::spawn(worker_type, Some(worker_id), userid.clone(), true, move |worker| {
bb105f9d 136 let mut env = BackupEnvironment::new(
e7cb4dc5 137 env_type, userid, worker.clone(), datastore, backup_dir);
b02a52e3 138
a42d1f55 139 env.debug = debug;
bb105f9d 140 env.last_backup = last_backup;
b02a52e3 141
61d7b501 142 env.log(format!("starting new {} on datastore '{}': {:?}", worker_type, store, path));
bb105f9d 143
255f378a 144 let service = H2Service::new(env.clone(), worker.clone(), &BACKUP_API_ROUTER, debug);
72375ce6 145
a66ab8ae
DM
146 let abort_future = worker.abort_future();
147
372724af 148 let env2 = env.clone();
bb105f9d 149
6650a242 150 let mut req_fut = req_body
152764ec 151 .on_upgrade()
92ac375a 152 .map_err(Error::from)
152764ec 153 .and_then(move |conn| {
6650a242 154 env2.debug("protocol upgrade done");
92ac375a
DM
155
156 let mut http = hyper::server::conn::Http::new();
157 http.http2_only(true);
adec8ea2 158 // increase window size: todo - find optiomal size
771953f9
DM
159 let window_size = 32*1024*1024; // max = (1 << 31) - 2
160 http.http2_initial_stream_window_size(window_size);
161 http.http2_initial_connection_window_size(window_size);
92ac375a 162
d9bd06ea
DM
163 http.serve_connection(conn, service)
164 .map_err(Error::from)
59b2baa0 165 });
6650a242 166 let mut abort_future = abort_future
59b2baa0
WB
167 .map(|_| Err(format_err!("task aborted")));
168
6650a242 169 async move {
95bda2f2
SR
170 // keep flock until task ends
171 let _group_guard = _group_guard;
f23f7543 172 let _snap_guard = _snap_guard;
81f29351 173 let _last_guard = _last_guard;
95bda2f2 174
6650a242
DC
175 let res = select!{
176 req = req_fut => req,
177 abrt = abort_future => abrt,
178 };
61d7b501
HL
179 if benchmark {
180 env.log("benchmark finished successfully");
181 env.remove_backup()?;
182 return Ok(());
183 }
6650a242
DC
184 match (res, env.ensure_finished()) {
185 (Ok(_), Ok(())) => {
add5861e 186 env.log("backup finished successfully");
6650a242
DC
187 Ok(())
188 },
189 (Err(err), Ok(())) => {
190 // ignore errors after finish
191 env.log(format!("backup had errors but finished: {}", err));
192 Ok(())
193 },
194 (Ok(_), Err(err)) => {
195 env.log(format!("backup ended and finish failed: {}", err));
196 env.log("removing unfinished backup");
197 env.remove_backup()?;
198 Err(err)
199 },
200 (Err(err), Err(_)) => {
201 env.log(format!("backup failed: {}", err));
202 env.log("removing failed backup");
203 env.remove_backup()?;
204 Err(err)
205 },
206 }
207 }
090ac9f7
DM
208 })?;
209
210 let response = Response::builder()
211 .status(StatusCode::SWITCHING_PROTOCOLS)
986bef16 212 .header(UPGRADE, HeaderValue::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1!()))
090ac9f7
DM
213 .body(Body::empty())?;
214
ad51d02a
DM
215 Ok(response)
216 }.boxed()
152764ec 217}
92ac375a 218
255f378a
DM
219pub const BACKUP_API_SUBDIRS: SubdirMap = &[
220 (
221 "blob", &Router::new()
222 .upload(&API_METHOD_UPLOAD_BLOB)
223 ),
224 (
225 "dynamic_chunk", &Router::new()
226 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK)
227 ),
228 (
229 "dynamic_close", &Router::new()
230 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX)
231 ),
232 (
233 "dynamic_index", &Router::new()
255f378a
DM
234 .post(&API_METHOD_CREATE_DYNAMIC_INDEX)
235 .put(&API_METHOD_DYNAMIC_APPEND)
236 ),
237 (
238 "finish", &Router::new()
239 .post(
240 &ApiMethod::new(
241 &ApiHandler::Sync(&finish_backup),
242 &ObjectSchema::new("Mark backup as finished.", &[])
372724af 243 )
255f378a
DM
244 )
245 ),
246 (
247 "fixed_chunk", &Router::new()
248 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK)
249 ),
250 (
251 "fixed_close", &Router::new()
252 .post(&API_METHOD_CLOSE_FIXED_INDEX)
253 ),
254 (
255 "fixed_index", &Router::new()
255f378a
DM
256 .post(&API_METHOD_CREATE_FIXED_INDEX)
257 .put(&API_METHOD_FIXED_APPEND)
258 ),
b957aa81
DM
259 (
260 "previous", &Router::new()
261 .download(&API_METHOD_DOWNLOAD_PREVIOUS)
262 ),
255f378a
DM
263 (
264 "speedtest", &Router::new()
265 .upload(&API_METHOD_UPLOAD_SPEEDTEST)
266 ),
267];
268
269pub const BACKUP_API_ROUTER: Router = Router::new()
270 .get(&list_subdirs_api_method!(BACKUP_API_SUBDIRS))
271 .subdirs(BACKUP_API_SUBDIRS);
272
3d229a4a
DM
273#[sortable]
274pub const API_METHOD_CREATE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
275 &ApiHandler::Sync(&create_dynamic_index),
276 &ObjectSchema::new(
277 "Create dynamic chunk index file.",
278 &sorted!([
279 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
280 ]),
281 )
282);
283
f9578f3c
DM
284fn create_dynamic_index(
285 param: Value,
3d229a4a 286 _info: &ApiMethod,
dd5495d6 287 rpcenv: &mut dyn RpcEnvironment,
f9578f3c
DM
288) -> Result<Value, Error> {
289
290 let env: &BackupEnvironment = rpcenv.as_ref();
f9578f3c 291
8bea85b4 292 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
f9578f3c 293
4af0ee05 294 let archive_name = name.clone();
0997967d 295 if !archive_name.ends_with(".didx") {
a42fa400 296 bail!("wrong archive extension: '{}'", archive_name);
f9578f3c
DM
297 }
298
6b95c7df 299 let mut path = env.backup_dir.relative_path();
f9578f3c
DM
300 path.push(archive_name);
301
976595e1 302 let index = env.datastore.create_dynamic_writer(&path)?;
8bea85b4 303 let wid = env.register_dynamic_writer(index, name)?;
f9578f3c 304
bb105f9d 305 env.log(format!("created new dynamic index {} ({:?})", wid, path));
f9578f3c 306
bb105f9d 307 Ok(json!(wid))
f9578f3c
DM
308}
309
552c2259 310#[sortable]
255f378a
DM
311pub const API_METHOD_CREATE_FIXED_INDEX: ApiMethod = ApiMethod::new(
312 &ApiHandler::Sync(&create_fixed_index),
313 &ObjectSchema::new(
314 "Create fixed chunk index file.",
552c2259 315 &sorted!([
255f378a
DM
316 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
317 ("size", false, &IntegerSchema::new("File size.")
318 .minimum(1)
319 .schema()
320 ),
facd9801
SR
321 ("reuse-csum", true, &StringSchema::new("If set, compare last backup's \
322 csum and reuse index for incremental backup if it matches.").schema()),
552c2259 323 ]),
a42fa400 324 )
255f378a 325);
a42fa400
DM
326
327fn create_fixed_index(
328 param: Value,
329 _info: &ApiMethod,
dd5495d6 330 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
331) -> Result<Value, Error> {
332
333 let env: &BackupEnvironment = rpcenv.as_ref();
334
a42fa400
DM
335 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
336 let size = tools::required_integer_param(&param, "size")? as usize;
facd9801 337 let reuse_csum = param["reuse-csum"].as_str();
a42fa400 338
4af0ee05 339 let archive_name = name.clone();
0997967d 340 if !archive_name.ends_with(".fidx") {
a42fa400 341 bail!("wrong archive extension: '{}'", archive_name);
a42fa400
DM
342 }
343
344 let mut path = env.backup_dir.relative_path();
facd9801 345 path.push(&archive_name);
a42fa400
DM
346
347 let chunk_size = 4096*1024; // todo: ??
348
facd9801
SR
349 // do incremental backup if csum is set
350 let mut reader = None;
351 let mut incremental = false;
352 if let Some(csum) = reuse_csum {
353 incremental = true;
354 let last_backup = match &env.last_backup {
355 Some(info) => info,
356 None => {
357 bail!("cannot reuse index - no previous backup exists");
358 }
359 };
360
361 let mut last_path = last_backup.backup_dir.relative_path();
362 last_path.push(&archive_name);
363
364 let index = match env.datastore.open_fixed_reader(last_path) {
365 Ok(index) => index,
366 Err(_) => {
367 bail!("cannot reuse index - no previous backup exists for archive");
368 }
369 };
370
371 let (old_csum, _) = index.compute_csum();
372 let old_csum = proxmox::tools::digest_to_hex(&old_csum);
373 if old_csum != csum {
374 bail!("expected csum ({}) doesn't match last backup's ({}), cannot do incremental backup",
375 csum, old_csum);
376 }
377
378 reader = Some(index);
379 }
380
381 let mut writer = env.datastore.create_fixed_writer(&path, size, chunk_size)?;
382
383 if let Some(reader) = reader {
384 writer.clone_data_from(&reader)?;
385 }
386
387 let wid = env.register_fixed_writer(writer, name, size, chunk_size as u32, incremental)?;
a42fa400
DM
388
389 env.log(format!("created new fixed index {} ({:?})", wid, path));
390
391 Ok(json!(wid))
392}
393
552c2259 394#[sortable]
255f378a
DM
395pub const API_METHOD_DYNAMIC_APPEND: ApiMethod = ApiMethod::new(
396 &ApiHandler::Sync(&dynamic_append),
397 &ObjectSchema::new(
398 "Append chunk to dynamic index writer.",
552c2259 399 &sorted!([
255f378a
DM
400 (
401 "wid",
402 false,
403 &IntegerSchema::new("Dynamic writer ID.")
404 .minimum(1)
405 .maximum(256)
406 .schema()
407 ),
408 (
409 "digest-list",
410 false,
411 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
412 ),
413 (
414 "offset-list",
415 false,
416 &ArraySchema::new(
417 "Chunk offset list.",
418 &IntegerSchema::new("Corresponding chunk offsets.")
419 .minimum(0)
420 .schema()
421 ).schema()
422 ),
552c2259 423 ]),
82ab7230 424 )
255f378a 425);
82ab7230
DM
426
427fn dynamic_append (
428 param: Value,
429 _info: &ApiMethod,
dd5495d6 430 rpcenv: &mut dyn RpcEnvironment,
82ab7230
DM
431) -> Result<Value, Error> {
432
433 let wid = tools::required_integer_param(&param, "wid")? as usize;
aa1b2e04 434 let digest_list = tools::required_array_param(&param, "digest-list")?;
417cb073 435 let offset_list = tools::required_array_param(&param, "offset-list")?;
aa1b2e04 436
417cb073
DM
437 if offset_list.len() != digest_list.len() {
438 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
439 }
440
82ab7230
DM
441 let env: &BackupEnvironment = rpcenv.as_ref();
442
39e60bd6
DM
443 env.debug(format!("dynamic_append {} chunks", digest_list.len()));
444
417cb073 445 for (i, item) in digest_list.iter().enumerate() {
aa1b2e04 446 let digest_str = item.as_str().unwrap();
bffd40d6 447 let digest = proxmox::tools::hex_to_digest(digest_str)?;
417cb073 448 let offset = offset_list[i].as_u64().unwrap();
aa1b2e04 449 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 450
417cb073 451 env.dynamic_writer_append_chunk(wid, offset, size, &digest)?;
82ab7230 452
add5861e 453 env.debug(format!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str, wid, offset, size));
aa1b2e04 454 }
82ab7230
DM
455
456 Ok(Value::Null)
457}
458
552c2259 459#[sortable]
255f378a
DM
460pub const API_METHOD_FIXED_APPEND: ApiMethod = ApiMethod::new(
461 &ApiHandler::Sync(&fixed_append),
462 &ObjectSchema::new(
463 "Append chunk to fixed index writer.",
552c2259 464 &sorted!([
255f378a
DM
465 (
466 "wid",
467 false,
468 &IntegerSchema::new("Fixed writer ID.")
469 .minimum(1)
470 .maximum(256)
471 .schema()
472 ),
473 (
474 "digest-list",
475 false,
476 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
477 ),
478 (
479 "offset-list",
480 false,
481 &ArraySchema::new(
482 "Chunk offset list.",
483 &IntegerSchema::new("Corresponding chunk offsets.")
484 .minimum(0)
485 .schema()
486 ).schema()
a42fa400 487 )
552c2259 488 ]),
a42fa400 489 )
255f378a 490);
a42fa400
DM
491
492fn fixed_append (
493 param: Value,
494 _info: &ApiMethod,
dd5495d6 495 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
496) -> Result<Value, Error> {
497
498 let wid = tools::required_integer_param(&param, "wid")? as usize;
499 let digest_list = tools::required_array_param(&param, "digest-list")?;
500 let offset_list = tools::required_array_param(&param, "offset-list")?;
501
a42fa400
DM
502 if offset_list.len() != digest_list.len() {
503 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
504 }
505
506 let env: &BackupEnvironment = rpcenv.as_ref();
507
39e60bd6
DM
508 env.debug(format!("fixed_append {} chunks", digest_list.len()));
509
a42fa400
DM
510 for (i, item) in digest_list.iter().enumerate() {
511 let digest_str = item.as_str().unwrap();
bffd40d6 512 let digest = proxmox::tools::hex_to_digest(digest_str)?;
a42fa400
DM
513 let offset = offset_list[i].as_u64().unwrap();
514 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 515
a42fa400
DM
516 env.fixed_writer_append_chunk(wid, offset, size, &digest)?;
517
add5861e 518 env.debug(format!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str, wid, offset, size));
a42fa400
DM
519 }
520
521 Ok(Value::Null)
522}
523
552c2259 524#[sortable]
255f378a
DM
525pub const API_METHOD_CLOSE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
526 &ApiHandler::Sync(&close_dynamic_index),
527 &ObjectSchema::new(
528 "Close dynamic index writer.",
552c2259 529 &sorted!([
255f378a
DM
530 (
531 "wid",
532 false,
533 &IntegerSchema::new("Dynamic writer ID.")
534 .minimum(1)
535 .maximum(256)
536 .schema()
537 ),
538 (
539 "chunk-count",
540 false,
541 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
542 .minimum(1)
543 .schema()
544 ),
545 (
546 "size",
547 false,
548 &IntegerSchema::new("File size. This is used to verify that the server got all data.")
549 .minimum(1)
550 .schema()
551 ),
552 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 553 ]),
a2077252 554 )
255f378a 555);
a2077252
DM
556
557fn close_dynamic_index (
558 param: Value,
559 _info: &ApiMethod,
dd5495d6 560 rpcenv: &mut dyn RpcEnvironment,
a2077252
DM
561) -> Result<Value, Error> {
562
563 let wid = tools::required_integer_param(&param, "wid")? as usize;
8bea85b4
DM
564 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
565 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
566 let csum_str = tools::required_string_param(&param, "csum")?;
567 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a2077252
DM
568
569 let env: &BackupEnvironment = rpcenv.as_ref();
570
fb6026b6 571 env.dynamic_writer_close(wid, chunk_count, size, csum)?;
a2077252 572
add5861e 573 env.log(format!("successfully closed dynamic index {}", wid));
bb105f9d 574
a2077252
DM
575 Ok(Value::Null)
576}
577
552c2259 578#[sortable]
255f378a
DM
579pub const API_METHOD_CLOSE_FIXED_INDEX: ApiMethod = ApiMethod::new(
580 &ApiHandler::Sync(&close_fixed_index),
581 &ObjectSchema::new(
582 "Close fixed index writer.",
552c2259 583 &sorted!([
255f378a
DM
584 (
585 "wid",
586 false,
587 &IntegerSchema::new("Fixed writer ID.")
588 .minimum(1)
589 .maximum(256)
590 .schema()
591 ),
592 (
593 "chunk-count",
594 false,
facd9801
SR
595 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks. Ignored for incremental backups.")
596 .minimum(0)
255f378a
DM
597 .schema()
598 ),
599 (
600 "size",
601 false,
facd9801
SR
602 &IntegerSchema::new("File size. This is used to verify that the server got all data. Ignored for incremental backups.")
603 .minimum(0)
255f378a
DM
604 .schema()
605 ),
606 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 607 ]),
a42fa400 608 )
255f378a 609);
a42fa400
DM
610
611fn close_fixed_index (
612 param: Value,
613 _info: &ApiMethod,
dd5495d6 614 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
615) -> Result<Value, Error> {
616
617 let wid = tools::required_integer_param(&param, "wid")? as usize;
618 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
619 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
620 let csum_str = tools::required_string_param(&param, "csum")?;
621 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a42fa400
DM
622
623 let env: &BackupEnvironment = rpcenv.as_ref();
624
fb6026b6 625 env.fixed_writer_close(wid, chunk_count, size, csum)?;
a42fa400 626
add5861e 627 env.log(format!("successfully closed fixed index {}", wid));
a42fa400
DM
628
629 Ok(Value::Null)
630}
a2077252 631
372724af
DM
632fn finish_backup (
633 _param: Value,
634 _info: &ApiMethod,
dd5495d6 635 rpcenv: &mut dyn RpcEnvironment,
372724af
DM
636) -> Result<Value, Error> {
637
638 let env: &BackupEnvironment = rpcenv.as_ref();
639
640 env.finish_backup()?;
add5861e 641 env.log("successfully finished backup");
372724af
DM
642
643 Ok(Value::Null)
644}
a2077252 645
552c2259 646#[sortable]
b957aa81
DM
647pub const API_METHOD_DOWNLOAD_PREVIOUS: ApiMethod = ApiMethod::new(
648 &ApiHandler::AsyncHttp(&download_previous),
255f378a 649 &ObjectSchema::new(
b957aa81 650 "Download archive from previous backup.",
552c2259
DM
651 &sorted!([
652 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA)
653 ]),
a42fa400 654 )
255f378a 655);
a42fa400 656
b957aa81 657fn download_previous(
d3611366
DM
658 _parts: Parts,
659 _req_body: Body,
660 param: Value,
255f378a 661 _info: &ApiMethod,
dd5495d6 662 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 663) -> ApiResponseFuture {
d3611366 664
ad51d02a
DM
665 async move {
666 let env: &BackupEnvironment = rpcenv.as_ref();
d3611366 667
ad51d02a 668 let archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
d3611366 669
ad51d02a
DM
670 let last_backup = match &env.last_backup {
671 Some(info) => info,
b957aa81 672 None => bail!("no previous backup"),
ad51d02a
DM
673 };
674
b957aa81 675 let mut path = env.datastore.snapshot_path(&last_backup.backup_dir);
ad51d02a
DM
676 path.push(&archive_name);
677
fe3e65c3
DM
678 {
679 let index: Option<Box<dyn IndexFile>> = match archive_type(&archive_name)? {
680 ArchiveType::FixedIndex => {
681 let index = env.datastore.open_fixed_reader(&path)?;
682 Some(Box::new(index))
683 }
684 ArchiveType::DynamicIndex => {
685 let index = env.datastore.open_dynamic_reader(&path)?;
686 Some(Box::new(index))
687 }
688 _ => { None }
689 };
690 if let Some(index) = index {
691 env.log(format!("register chunks in '{}' from previous backup.", archive_name));
692
693 for pos in 0..index.index_count() {
694 let info = index.chunk_info(pos).unwrap();
695 let size = info.range.end - info.range.start;
696 env.register_chunk(info.digest, size as u32)?;
697 }
698 }
699 }
700
701 env.log(format!("download '{}' from previous backup.", archive_name));
b957aa81 702 crate::api2::helpers::create_download_response(path).await
ad51d02a 703 }.boxed()
a42fa400 704}