]> git.proxmox.com Git - proxmox-backup.git/blame - src/api2/backup.rs
api: add world accessible ping dummy endpoint
[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
4ebda996 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
b428af97 185 let env3 = env2.clone();
d9bd06ea 186 http.serve_connection(conn, service)
b428af97
DM
187 .map(move |result| {
188 match result {
189 Err(err) => {
190 // Avoid Transport endpoint is not connected (os error 107)
191 // fixme: find a better way to test for that error
192 if err.to_string().starts_with("connection error") && env3.finished() {
193 Ok(())
194 } else {
195 Err(Error::from(err))
196 }
197 }
198 Ok(()) => Ok(()),
199 }
200 })
59b2baa0 201 });
6650a242 202 let mut abort_future = abort_future
59b2baa0
WB
203 .map(|_| Err(format_err!("task aborted")));
204
6650a242 205 async move {
95bda2f2
SR
206 // keep flock until task ends
207 let _group_guard = _group_guard;
0698f78d 208 let snap_guard = snap_guard;
81f29351 209 let _last_guard = _last_guard;
95bda2f2 210
6650a242
DC
211 let res = select!{
212 req = req_fut => req,
213 abrt = abort_future => abrt,
214 };
61d7b501
HL
215 if benchmark {
216 env.log("benchmark finished successfully");
9070d11f 217 tools::runtime::block_in_place(|| env.remove_backup())?;
61d7b501
HL
218 return Ok(());
219 }
0698f78d
SR
220
221 let verify = |env: BackupEnvironment| {
222 if let Err(err) = env.verify_after_complete(snap_guard) {
223 env.log(format!(
224 "backup finished, but starting the requested verify task failed: {}",
225 err
226 ));
227 }
228 };
229
6650a242
DC
230 match (res, env.ensure_finished()) {
231 (Ok(_), Ok(())) => {
add5861e 232 env.log("backup finished successfully");
0698f78d 233 verify(env);
6650a242
DC
234 Ok(())
235 },
236 (Err(err), Ok(())) => {
237 // ignore errors after finish
238 env.log(format!("backup had errors but finished: {}", err));
0698f78d 239 verify(env);
6650a242
DC
240 Ok(())
241 },
242 (Ok(_), Err(err)) => {
243 env.log(format!("backup ended and finish failed: {}", err));
244 env.log("removing unfinished backup");
455f2ad2 245 tools::runtime::block_in_place(|| env.remove_backup())?;
6650a242
DC
246 Err(err)
247 },
248 (Err(err), Err(_)) => {
249 env.log(format!("backup failed: {}", err));
250 env.log("removing failed backup");
9070d11f 251 tools::runtime::block_in_place(|| env.remove_backup())?;
6650a242
DC
252 Err(err)
253 },
254 }
255 }
090ac9f7
DM
256 })?;
257
258 let response = Response::builder()
259 .status(StatusCode::SWITCHING_PROTOCOLS)
986bef16 260 .header(UPGRADE, HeaderValue::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1!()))
090ac9f7
DM
261 .body(Body::empty())?;
262
ad51d02a
DM
263 Ok(response)
264 }.boxed()
152764ec 265}
92ac375a 266
255f378a
DM
267pub const BACKUP_API_SUBDIRS: SubdirMap = &[
268 (
269 "blob", &Router::new()
270 .upload(&API_METHOD_UPLOAD_BLOB)
271 ),
272 (
273 "dynamic_chunk", &Router::new()
274 .upload(&API_METHOD_UPLOAD_DYNAMIC_CHUNK)
275 ),
276 (
277 "dynamic_close", &Router::new()
278 .post(&API_METHOD_CLOSE_DYNAMIC_INDEX)
279 ),
280 (
281 "dynamic_index", &Router::new()
255f378a
DM
282 .post(&API_METHOD_CREATE_DYNAMIC_INDEX)
283 .put(&API_METHOD_DYNAMIC_APPEND)
284 ),
285 (
286 "finish", &Router::new()
287 .post(
288 &ApiMethod::new(
289 &ApiHandler::Sync(&finish_backup),
290 &ObjectSchema::new("Mark backup as finished.", &[])
372724af 291 )
255f378a
DM
292 )
293 ),
294 (
295 "fixed_chunk", &Router::new()
296 .upload(&API_METHOD_UPLOAD_FIXED_CHUNK)
297 ),
298 (
299 "fixed_close", &Router::new()
300 .post(&API_METHOD_CLOSE_FIXED_INDEX)
301 ),
302 (
303 "fixed_index", &Router::new()
255f378a
DM
304 .post(&API_METHOD_CREATE_FIXED_INDEX)
305 .put(&API_METHOD_FIXED_APPEND)
306 ),
b957aa81
DM
307 (
308 "previous", &Router::new()
309 .download(&API_METHOD_DOWNLOAD_PREVIOUS)
310 ),
255f378a
DM
311 (
312 "speedtest", &Router::new()
313 .upload(&API_METHOD_UPLOAD_SPEEDTEST)
314 ),
315];
316
317pub const BACKUP_API_ROUTER: Router = Router::new()
318 .get(&list_subdirs_api_method!(BACKUP_API_SUBDIRS))
319 .subdirs(BACKUP_API_SUBDIRS);
320
3d229a4a
DM
321#[sortable]
322pub const API_METHOD_CREATE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
323 &ApiHandler::Sync(&create_dynamic_index),
324 &ObjectSchema::new(
325 "Create dynamic chunk index file.",
326 &sorted!([
327 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
328 ]),
329 )
330);
331
f9578f3c
DM
332fn create_dynamic_index(
333 param: Value,
3d229a4a 334 _info: &ApiMethod,
dd5495d6 335 rpcenv: &mut dyn RpcEnvironment,
f9578f3c
DM
336) -> Result<Value, Error> {
337
338 let env: &BackupEnvironment = rpcenv.as_ref();
f9578f3c 339
8bea85b4 340 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
f9578f3c 341
4af0ee05 342 let archive_name = name.clone();
0997967d 343 if !archive_name.ends_with(".didx") {
a42fa400 344 bail!("wrong archive extension: '{}'", archive_name);
f9578f3c
DM
345 }
346
6b95c7df 347 let mut path = env.backup_dir.relative_path();
f9578f3c
DM
348 path.push(archive_name);
349
976595e1 350 let index = env.datastore.create_dynamic_writer(&path)?;
8bea85b4 351 let wid = env.register_dynamic_writer(index, name)?;
f9578f3c 352
bb105f9d 353 env.log(format!("created new dynamic index {} ({:?})", wid, path));
f9578f3c 354
bb105f9d 355 Ok(json!(wid))
f9578f3c
DM
356}
357
552c2259 358#[sortable]
255f378a
DM
359pub const API_METHOD_CREATE_FIXED_INDEX: ApiMethod = ApiMethod::new(
360 &ApiHandler::Sync(&create_fixed_index),
361 &ObjectSchema::new(
362 "Create fixed chunk index file.",
552c2259 363 &sorted!([
255f378a
DM
364 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA),
365 ("size", false, &IntegerSchema::new("File size.")
366 .minimum(1)
367 .schema()
368 ),
facd9801
SR
369 ("reuse-csum", true, &StringSchema::new("If set, compare last backup's \
370 csum and reuse index for incremental backup if it matches.").schema()),
552c2259 371 ]),
a42fa400 372 )
255f378a 373);
a42fa400
DM
374
375fn create_fixed_index(
376 param: Value,
377 _info: &ApiMethod,
dd5495d6 378 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
379) -> Result<Value, Error> {
380
381 let env: &BackupEnvironment = rpcenv.as_ref();
382
a42fa400
DM
383 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
384 let size = tools::required_integer_param(&param, "size")? as usize;
facd9801 385 let reuse_csum = param["reuse-csum"].as_str();
a42fa400 386
4af0ee05 387 let archive_name = name.clone();
0997967d 388 if !archive_name.ends_with(".fidx") {
a42fa400 389 bail!("wrong archive extension: '{}'", archive_name);
a42fa400
DM
390 }
391
392 let mut path = env.backup_dir.relative_path();
facd9801 393 path.push(&archive_name);
a42fa400
DM
394
395 let chunk_size = 4096*1024; // todo: ??
396
facd9801
SR
397 // do incremental backup if csum is set
398 let mut reader = None;
399 let mut incremental = false;
400 if let Some(csum) = reuse_csum {
401 incremental = true;
402 let last_backup = match &env.last_backup {
403 Some(info) => info,
404 None => {
0af2da04 405 bail!("cannot reuse index - no valid previous backup exists");
facd9801
SR
406 }
407 };
408
409 let mut last_path = last_backup.backup_dir.relative_path();
410 last_path.push(&archive_name);
411
412 let index = match env.datastore.open_fixed_reader(last_path) {
413 Ok(index) => index,
414 Err(_) => {
415 bail!("cannot reuse index - no previous backup exists for archive");
416 }
417 };
418
419 let (old_csum, _) = index.compute_csum();
420 let old_csum = proxmox::tools::digest_to_hex(&old_csum);
421 if old_csum != csum {
422 bail!("expected csum ({}) doesn't match last backup's ({}), cannot do incremental backup",
423 csum, old_csum);
424 }
425
426 reader = Some(index);
427 }
428
429 let mut writer = env.datastore.create_fixed_writer(&path, size, chunk_size)?;
430
431 if let Some(reader) = reader {
432 writer.clone_data_from(&reader)?;
433 }
434
435 let wid = env.register_fixed_writer(writer, name, size, chunk_size as u32, incremental)?;
a42fa400
DM
436
437 env.log(format!("created new fixed index {} ({:?})", wid, path));
438
439 Ok(json!(wid))
440}
441
552c2259 442#[sortable]
255f378a
DM
443pub const API_METHOD_DYNAMIC_APPEND: ApiMethod = ApiMethod::new(
444 &ApiHandler::Sync(&dynamic_append),
445 &ObjectSchema::new(
446 "Append chunk to dynamic index writer.",
552c2259 447 &sorted!([
255f378a
DM
448 (
449 "wid",
450 false,
451 &IntegerSchema::new("Dynamic writer ID.")
452 .minimum(1)
453 .maximum(256)
454 .schema()
455 ),
456 (
457 "digest-list",
458 false,
459 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
460 ),
461 (
462 "offset-list",
463 false,
464 &ArraySchema::new(
465 "Chunk offset list.",
466 &IntegerSchema::new("Corresponding chunk offsets.")
467 .minimum(0)
468 .schema()
469 ).schema()
470 ),
552c2259 471 ]),
82ab7230 472 )
255f378a 473);
82ab7230
DM
474
475fn dynamic_append (
476 param: Value,
477 _info: &ApiMethod,
dd5495d6 478 rpcenv: &mut dyn RpcEnvironment,
82ab7230
DM
479) -> Result<Value, Error> {
480
481 let wid = tools::required_integer_param(&param, "wid")? as usize;
aa1b2e04 482 let digest_list = tools::required_array_param(&param, "digest-list")?;
417cb073 483 let offset_list = tools::required_array_param(&param, "offset-list")?;
aa1b2e04 484
417cb073
DM
485 if offset_list.len() != digest_list.len() {
486 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
487 }
488
82ab7230
DM
489 let env: &BackupEnvironment = rpcenv.as_ref();
490
39e60bd6
DM
491 env.debug(format!("dynamic_append {} chunks", digest_list.len()));
492
417cb073 493 for (i, item) in digest_list.iter().enumerate() {
aa1b2e04 494 let digest_str = item.as_str().unwrap();
bffd40d6 495 let digest = proxmox::tools::hex_to_digest(digest_str)?;
417cb073 496 let offset = offset_list[i].as_u64().unwrap();
aa1b2e04 497 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 498
417cb073 499 env.dynamic_writer_append_chunk(wid, offset, size, &digest)?;
82ab7230 500
add5861e 501 env.debug(format!("successfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str, wid, offset, size));
aa1b2e04 502 }
82ab7230
DM
503
504 Ok(Value::Null)
505}
506
552c2259 507#[sortable]
255f378a
DM
508pub const API_METHOD_FIXED_APPEND: ApiMethod = ApiMethod::new(
509 &ApiHandler::Sync(&fixed_append),
510 &ObjectSchema::new(
511 "Append chunk to fixed index writer.",
552c2259 512 &sorted!([
255f378a
DM
513 (
514 "wid",
515 false,
516 &IntegerSchema::new("Fixed writer ID.")
517 .minimum(1)
518 .maximum(256)
519 .schema()
520 ),
521 (
522 "digest-list",
523 false,
524 &ArraySchema::new("Chunk digest list.", &CHUNK_DIGEST_SCHEMA).schema()
525 ),
526 (
527 "offset-list",
528 false,
529 &ArraySchema::new(
530 "Chunk offset list.",
531 &IntegerSchema::new("Corresponding chunk offsets.")
532 .minimum(0)
533 .schema()
534 ).schema()
a42fa400 535 )
552c2259 536 ]),
a42fa400 537 )
255f378a 538);
a42fa400
DM
539
540fn fixed_append (
541 param: Value,
542 _info: &ApiMethod,
dd5495d6 543 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
544) -> Result<Value, Error> {
545
546 let wid = tools::required_integer_param(&param, "wid")? as usize;
547 let digest_list = tools::required_array_param(&param, "digest-list")?;
548 let offset_list = tools::required_array_param(&param, "offset-list")?;
549
a42fa400
DM
550 if offset_list.len() != digest_list.len() {
551 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
552 }
553
554 let env: &BackupEnvironment = rpcenv.as_ref();
555
39e60bd6
DM
556 env.debug(format!("fixed_append {} chunks", digest_list.len()));
557
a42fa400
DM
558 for (i, item) in digest_list.iter().enumerate() {
559 let digest_str = item.as_str().unwrap();
bffd40d6 560 let digest = proxmox::tools::hex_to_digest(digest_str)?;
a42fa400
DM
561 let offset = offset_list[i].as_u64().unwrap();
562 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
39e60bd6 563
a42fa400
DM
564 env.fixed_writer_append_chunk(wid, offset, size, &digest)?;
565
add5861e 566 env.debug(format!("successfully added chunk {} to fixed index {} (offset {}, size {})", digest_str, wid, offset, size));
a42fa400
DM
567 }
568
569 Ok(Value::Null)
570}
571
552c2259 572#[sortable]
255f378a
DM
573pub const API_METHOD_CLOSE_DYNAMIC_INDEX: ApiMethod = ApiMethod::new(
574 &ApiHandler::Sync(&close_dynamic_index),
575 &ObjectSchema::new(
576 "Close dynamic index writer.",
552c2259 577 &sorted!([
255f378a
DM
578 (
579 "wid",
580 false,
581 &IntegerSchema::new("Dynamic writer ID.")
582 .minimum(1)
583 .maximum(256)
584 .schema()
585 ),
586 (
587 "chunk-count",
588 false,
589 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
590 .minimum(1)
591 .schema()
592 ),
593 (
594 "size",
595 false,
596 &IntegerSchema::new("File size. This is used to verify that the server got all data.")
597 .minimum(1)
598 .schema()
599 ),
600 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 601 ]),
a2077252 602 )
255f378a 603);
a2077252
DM
604
605fn close_dynamic_index (
606 param: Value,
607 _info: &ApiMethod,
dd5495d6 608 rpcenv: &mut dyn RpcEnvironment,
a2077252
DM
609) -> Result<Value, Error> {
610
611 let wid = tools::required_integer_param(&param, "wid")? as usize;
8bea85b4
DM
612 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
613 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
614 let csum_str = tools::required_string_param(&param, "csum")?;
615 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a2077252
DM
616
617 let env: &BackupEnvironment = rpcenv.as_ref();
618
fb6026b6 619 env.dynamic_writer_close(wid, chunk_count, size, csum)?;
a2077252 620
add5861e 621 env.log(format!("successfully closed dynamic index {}", wid));
bb105f9d 622
a2077252
DM
623 Ok(Value::Null)
624}
625
552c2259 626#[sortable]
255f378a
DM
627pub const API_METHOD_CLOSE_FIXED_INDEX: ApiMethod = ApiMethod::new(
628 &ApiHandler::Sync(&close_fixed_index),
629 &ObjectSchema::new(
630 "Close fixed index writer.",
552c2259 631 &sorted!([
255f378a
DM
632 (
633 "wid",
634 false,
635 &IntegerSchema::new("Fixed writer ID.")
636 .minimum(1)
637 .maximum(256)
638 .schema()
639 ),
640 (
641 "chunk-count",
642 false,
facd9801
SR
643 &IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks. Ignored for incremental backups.")
644 .minimum(0)
255f378a
DM
645 .schema()
646 ),
647 (
648 "size",
649 false,
facd9801
SR
650 &IntegerSchema::new("File size. This is used to verify that the server got all data. Ignored for incremental backups.")
651 .minimum(0)
255f378a
DM
652 .schema()
653 ),
654 ("csum", false, &StringSchema::new("Digest list checksum.").schema()),
552c2259 655 ]),
a42fa400 656 )
255f378a 657);
a42fa400
DM
658
659fn close_fixed_index (
660 param: Value,
661 _info: &ApiMethod,
dd5495d6 662 rpcenv: &mut dyn RpcEnvironment,
a42fa400
DM
663) -> Result<Value, Error> {
664
665 let wid = tools::required_integer_param(&param, "wid")? as usize;
666 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
667 let size = tools::required_integer_param(&param, "size")? as u64;
fb6026b6
DM
668 let csum_str = tools::required_string_param(&param, "csum")?;
669 let csum = proxmox::tools::hex_to_digest(csum_str)?;
a42fa400
DM
670
671 let env: &BackupEnvironment = rpcenv.as_ref();
672
fb6026b6 673 env.fixed_writer_close(wid, chunk_count, size, csum)?;
a42fa400 674
add5861e 675 env.log(format!("successfully closed fixed index {}", wid));
a42fa400
DM
676
677 Ok(Value::Null)
678}
a2077252 679
372724af
DM
680fn finish_backup (
681 _param: Value,
682 _info: &ApiMethod,
dd5495d6 683 rpcenv: &mut dyn RpcEnvironment,
372724af
DM
684) -> Result<Value, Error> {
685
686 let env: &BackupEnvironment = rpcenv.as_ref();
687
688 env.finish_backup()?;
add5861e 689 env.log("successfully finished backup");
372724af
DM
690
691 Ok(Value::Null)
692}
a2077252 693
552c2259 694#[sortable]
b957aa81
DM
695pub const API_METHOD_DOWNLOAD_PREVIOUS: ApiMethod = ApiMethod::new(
696 &ApiHandler::AsyncHttp(&download_previous),
255f378a 697 &ObjectSchema::new(
b957aa81 698 "Download archive from previous backup.",
552c2259
DM
699 &sorted!([
700 ("archive-name", false, &crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA)
701 ]),
a42fa400 702 )
255f378a 703);
a42fa400 704
b957aa81 705fn download_previous(
d3611366
DM
706 _parts: Parts,
707 _req_body: Body,
708 param: Value,
255f378a 709 _info: &ApiMethod,
dd5495d6 710 rpcenv: Box<dyn RpcEnvironment>,
bb084b9c 711) -> ApiResponseFuture {
d3611366 712
ad51d02a
DM
713 async move {
714 let env: &BackupEnvironment = rpcenv.as_ref();
d3611366 715
ad51d02a 716 let archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
d3611366 717
ad51d02a
DM
718 let last_backup = match &env.last_backup {
719 Some(info) => info,
0af2da04 720 None => bail!("no valid previous backup"),
ad51d02a
DM
721 };
722
b957aa81 723 let mut path = env.datastore.snapshot_path(&last_backup.backup_dir);
ad51d02a
DM
724 path.push(&archive_name);
725
fe3e65c3
DM
726 {
727 let index: Option<Box<dyn IndexFile>> = match archive_type(&archive_name)? {
728 ArchiveType::FixedIndex => {
729 let index = env.datastore.open_fixed_reader(&path)?;
730 Some(Box::new(index))
731 }
732 ArchiveType::DynamicIndex => {
733 let index = env.datastore.open_dynamic_reader(&path)?;
734 Some(Box::new(index))
735 }
736 _ => { None }
737 };
738 if let Some(index) = index {
739 env.log(format!("register chunks in '{}' from previous backup.", archive_name));
740
741 for pos in 0..index.index_count() {
742 let info = index.chunk_info(pos).unwrap();
743 let size = info.range.end - info.range.start;
744 env.register_chunk(info.digest, size as u32)?;
745 }
746 }
747 }
748
749 env.log(format!("download '{}' from previous backup.", archive_name));
b957aa81 750 crate::api2::helpers::create_download_response(path).await
ad51d02a 751 }.boxed()
a42fa400 752}