]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/backup.rs
src/api2/backup.rs: cleanup schema definitions
[proxmox-backup.git] / src / api2 / backup.rs
1 use failure::*;
2 use lazy_static::lazy_static;
3
4 //use std::sync::Arc;
5
6 use futures::*;
7 use hyper::header::{HeaderValue, UPGRADE};
8 use hyper::{Body, Response, StatusCode};
9 use hyper::http::request::Parts;
10
11 use serde_json::{json, Value};
12
13 use crate::tools;
14 use crate::tools::wrapped_reader_stream::*;
15 use crate::api_schema::router::*;
16 use crate::api_schema::*;
17 use crate::server::{WorkerTask, H2Service};
18 use crate::backup::*;
19 use crate::api2::types::*;
20
21 mod environment;
22 use environment::*;
23
24 mod upload_chunk;
25 use upload_chunk::*;
26
27 pub fn router() -> Router {
28 Router::new()
29 .upgrade(api_method_upgrade_backup())
30 }
31
32 pub fn api_method_upgrade_backup() -> ApiAsyncMethod {
33 ApiAsyncMethod::new(
34 upgrade_to_backup_protocol,
35 ObjectSchema::new(concat!("Upgraded to backup protocol ('", PROXMOX_BACKUP_PROTOCOL_ID_V1!(), "')."))
36 .required("store", StringSchema::new("Datastore name."))
37 .required("backup-type", BACKUP_TYPE_SCHEMA.clone())
38 .required("backup-id", BACKUP_ID_SCHEMA.clone())
39 .required("backup-time", BACKUP_TIME_SCHEMA.clone())
40 .optional("debug", BooleanSchema::new("Enable verbose debug logging."))
41 )
42 }
43
44 fn upgrade_to_backup_protocol(
45 parts: Parts,
46 req_body: Body,
47 param: Value,
48 _info: &ApiAsyncMethod,
49 rpcenv: Box<dyn RpcEnvironment>,
50 ) -> Result<BoxFut, Error> {
51
52 let debug = param["debug"].as_bool().unwrap_or(false);
53
54 let store = tools::required_string_param(&param, "store")?.to_owned();
55 let datastore = DataStore::lookup_datastore(&store)?;
56
57 let backup_type = tools::required_string_param(&param, "backup-type")?;
58 let backup_id = tools::required_string_param(&param, "backup-id")?;
59 let backup_time = tools::required_integer_param(&param, "backup-time")?;
60
61 let protocols = parts
62 .headers
63 .get("UPGRADE")
64 .ok_or_else(|| format_err!("missing Upgrade header"))?
65 .to_str()?;
66
67 if protocols != PROXMOX_BACKUP_PROTOCOL_ID_V1!() {
68 bail!("invalid protocol name");
69 }
70
71 if parts.version >= http::version::Version::HTTP_2 {
72 bail!("unexpected http version '{:?}' (expected version < 2)", parts.version);
73 }
74
75 let worker_id = format!("{}_{}_{}", store, backup_type, backup_id);
76
77 let username = rpcenv.get_user().unwrap();
78 let env_type = rpcenv.env_type();
79
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);
83
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.");
87 }
88 }
89
90 let (path, is_new) = datastore.create_backup_dir(&backup_dir)?;
91 if !is_new { bail!("backup directorty already exists."); }
92
93 WorkerTask::spawn("backup", Some(worker_id), &username.clone(), true, move |worker| {
94 let mut env = BackupEnvironment::new(
95 env_type, username.clone(), worker.clone(), datastore, backup_dir);
96
97 env.debug = debug;
98 env.last_backup = last_backup;
99
100 env.log(format!("starting new backup on datastore '{}': {:?}", store, path));
101
102 let service = H2Service::new(env.clone(), worker.clone(), &BACKUP_ROUTER, debug);
103
104 let abort_future = worker.abort_future();
105
106 let env2 = env.clone();
107 let env3 = env.clone();
108
109 req_body
110 .on_upgrade()
111 .map_err(Error::from)
112 .and_then(move |conn| {
113 env3.debug("protocol upgrade done");
114
115 let mut http = hyper::server::conn::Http::new();
116 http.http2_only(true);
117 // increase window size: todo - find optiomal size
118 let window_size = 32*1024*1024; // max = (1 << 31) - 2
119 http.http2_initial_stream_window_size(window_size);
120 http.http2_initial_connection_window_size(window_size);
121
122 http.serve_connection(conn, service)
123 .map_err(Error::from)
124 })
125 .select(abort_future.map_err(|_| {}).then(move |_| { bail!("task aborted"); }))
126 .map_err(|(err, _)| err)
127 .and_then(move |(_result, _)| {
128 env.ensure_finished()?;
129 env.log("backup finished sucessfully");
130 Ok(())
131 })
132 .then(move |result| {
133 if let Err(err) = result {
134 match env2.ensure_finished() {
135 Ok(()) => {}, // ignore error after finish
136 _ => {
137 env2.log(format!("backup failed: {}", err));
138 env2.log("removing failed backup");
139 env2.remove_backup()?;
140 return Err(err);
141 }
142 }
143 }
144 Ok(())
145 })
146 })?;
147
148 let response = Response::builder()
149 .status(StatusCode::SWITCHING_PROTOCOLS)
150 .header(UPGRADE, HeaderValue::from_static(PROXMOX_BACKUP_PROTOCOL_ID_V1!()))
151 .body(Body::empty())?;
152
153 Ok(Box::new(futures::future::ok(response)))
154 }
155
156 lazy_static!{
157 static ref BACKUP_ROUTER: Router = backup_api();
158 }
159
160 pub fn backup_api() -> Router {
161
162 let router = Router::new()
163 .subdir(
164 "blob", Router::new()
165 .upload(api_method_upload_blob())
166 )
167 .subdir(
168 "dynamic_chunk", Router::new()
169 .upload(api_method_upload_dynamic_chunk())
170 )
171 .subdir(
172 "dynamic_index", Router::new()
173 .download(api_method_dynamic_chunk_index())
174 .post(api_method_create_dynamic_index())
175 .put(api_method_dynamic_append())
176 )
177 .subdir(
178 "dynamic_close", Router::new()
179 .post(api_method_close_dynamic_index())
180 )
181 .subdir(
182 "fixed_chunk", Router::new()
183 .upload(api_method_upload_fixed_chunk())
184 )
185 .subdir(
186 "fixed_index", Router::new()
187 .download(api_method_fixed_chunk_index())
188 .post(api_method_create_fixed_index())
189 .put(api_method_fixed_append())
190 )
191 .subdir(
192 "fixed_close", Router::new()
193 .post(api_method_close_fixed_index())
194 )
195 .subdir(
196 "finish", Router::new()
197 .post(
198 ApiMethod::new(
199 finish_backup,
200 ObjectSchema::new("Mark backup as finished.")
201 )
202 )
203 )
204 .subdir(
205 "speedtest", Router::new()
206 .upload(api_method_upload_speedtest())
207 )
208 .list_subdirs();
209
210 router
211 }
212
213 pub fn api_method_create_dynamic_index() -> ApiMethod {
214 ApiMethod::new(
215 create_dynamic_index,
216 ObjectSchema::new("Create dynamic chunk index file.")
217 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
218 )
219 }
220
221 fn create_dynamic_index(
222 param: Value,
223 _info: &ApiMethod,
224 rpcenv: &mut dyn RpcEnvironment,
225 ) -> Result<Value, Error> {
226
227 let env: &BackupEnvironment = rpcenv.as_ref();
228
229 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
230
231 let mut archive_name = name.clone();
232 if !archive_name.ends_with(".pxar") {
233 bail!("wrong archive extension: '{}'", archive_name);
234 } else {
235 archive_name.push_str(".didx");
236 }
237
238 let mut path = env.backup_dir.relative_path();
239 path.push(archive_name);
240
241 let index = env.datastore.create_dynamic_writer(&path)?;
242 let wid = env.register_dynamic_writer(index, name)?;
243
244 env.log(format!("created new dynamic index {} ({:?})", wid, path));
245
246 Ok(json!(wid))
247 }
248
249 pub fn api_method_create_fixed_index() -> ApiMethod {
250 ApiMethod::new(
251 create_fixed_index,
252 ObjectSchema::new("Create fixed chunk index file.")
253 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
254 .required("size", IntegerSchema::new("File size.")
255 .minimum(1)
256 )
257 )
258 }
259
260 fn create_fixed_index(
261 param: Value,
262 _info: &ApiMethod,
263 rpcenv: &mut dyn RpcEnvironment,
264 ) -> Result<Value, Error> {
265
266 let env: &BackupEnvironment = rpcenv.as_ref();
267
268 println!("PARAM: {:?}", param);
269
270 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
271 let size = tools::required_integer_param(&param, "size")? as usize;
272
273 let mut archive_name = name.clone();
274 if !archive_name.ends_with(".img") {
275 bail!("wrong archive extension: '{}'", archive_name);
276 } else {
277 archive_name.push_str(".fidx");
278 }
279
280 let mut path = env.backup_dir.relative_path();
281 path.push(archive_name);
282
283 let chunk_size = 4096*1024; // todo: ??
284
285 let index = env.datastore.create_fixed_writer(&path, size, chunk_size)?;
286 let wid = env.register_fixed_writer(index, name, size, chunk_size as u32)?;
287
288 env.log(format!("created new fixed index {} ({:?})", wid, path));
289
290 Ok(json!(wid))
291 }
292
293 pub fn api_method_dynamic_append() -> ApiMethod {
294 ApiMethod::new(
295 dynamic_append,
296 ObjectSchema::new("Append chunk to dynamic index writer.")
297 .required("wid", IntegerSchema::new("Dynamic writer ID.")
298 .minimum(1)
299 .maximum(256)
300 )
301 .required("digest-list", ArraySchema::new(
302 "Chunk digest list.", CHUNK_DIGEST_SCHEMA.clone())
303 )
304 .required("offset-list", ArraySchema::new(
305 "Chunk offset list.",
306 IntegerSchema::new("Corresponding chunk offsets.")
307 .minimum(0)
308 .into())
309 )
310 )
311 }
312
313 fn dynamic_append (
314 param: Value,
315 _info: &ApiMethod,
316 rpcenv: &mut dyn RpcEnvironment,
317 ) -> Result<Value, Error> {
318
319 let wid = tools::required_integer_param(&param, "wid")? as usize;
320 let digest_list = tools::required_array_param(&param, "digest-list")?;
321 let offset_list = tools::required_array_param(&param, "offset-list")?;
322
323 if offset_list.len() != digest_list.len() {
324 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
325 }
326
327 let env: &BackupEnvironment = rpcenv.as_ref();
328
329 env.debug(format!("dynamic_append {} chunks", digest_list.len()));
330
331 for (i, item) in digest_list.iter().enumerate() {
332 let digest_str = item.as_str().unwrap();
333 let digest = proxmox::tools::hex_to_digest(digest_str)?;
334 let offset = offset_list[i].as_u64().unwrap();
335 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
336
337 env.dynamic_writer_append_chunk(wid, offset, size, &digest)?;
338
339 env.debug(format!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str, wid, offset, size));
340 }
341
342 Ok(Value::Null)
343 }
344
345 pub fn api_method_fixed_append() -> ApiMethod {
346 ApiMethod::new(
347 fixed_append,
348 ObjectSchema::new("Append chunk to fixed index writer.")
349 .required("wid", IntegerSchema::new("Fixed writer ID.")
350 .minimum(1)
351 .maximum(256)
352 )
353 .required("digest-list", ArraySchema::new(
354 "Chunk digest list.", CHUNK_DIGEST_SCHEMA.clone())
355 )
356 .required("offset-list", ArraySchema::new(
357 "Chunk offset list.",
358 IntegerSchema::new("Corresponding chunk offsets.")
359 .minimum(0)
360 .into())
361 )
362 )
363 }
364
365 fn fixed_append (
366 param: Value,
367 _info: &ApiMethod,
368 rpcenv: &mut dyn RpcEnvironment,
369 ) -> Result<Value, Error> {
370
371 let wid = tools::required_integer_param(&param, "wid")? as usize;
372 let digest_list = tools::required_array_param(&param, "digest-list")?;
373 let offset_list = tools::required_array_param(&param, "offset-list")?;
374
375 if offset_list.len() != digest_list.len() {
376 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
377 }
378
379 let env: &BackupEnvironment = rpcenv.as_ref();
380
381 env.debug(format!("fixed_append {} chunks", digest_list.len()));
382
383 for (i, item) in digest_list.iter().enumerate() {
384 let digest_str = item.as_str().unwrap();
385 let digest = proxmox::tools::hex_to_digest(digest_str)?;
386 let offset = offset_list[i].as_u64().unwrap();
387 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
388
389 env.fixed_writer_append_chunk(wid, offset, size, &digest)?;
390
391 env.debug(format!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str, wid, offset, size));
392 }
393
394 Ok(Value::Null)
395 }
396
397 pub fn api_method_close_dynamic_index() -> ApiMethod {
398 ApiMethod::new(
399 close_dynamic_index,
400 ObjectSchema::new("Close dynamic index writer.")
401 .required("wid", IntegerSchema::new("Dynamic writer ID.")
402 .minimum(1)
403 .maximum(256)
404 )
405 .required("chunk-count", IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
406 .minimum(1)
407 )
408 .required("size", IntegerSchema::new("File size. This is used to verify that the server got all data.")
409 .minimum(1)
410 )
411 )
412 }
413
414 fn close_dynamic_index (
415 param: Value,
416 _info: &ApiMethod,
417 rpcenv: &mut dyn RpcEnvironment,
418 ) -> Result<Value, Error> {
419
420 let wid = tools::required_integer_param(&param, "wid")? as usize;
421 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
422 let size = tools::required_integer_param(&param, "size")? as u64;
423
424 let env: &BackupEnvironment = rpcenv.as_ref();
425
426 env.dynamic_writer_close(wid, chunk_count, size)?;
427
428 env.log(format!("sucessfully closed dynamic index {}", wid));
429
430 Ok(Value::Null)
431 }
432
433 pub fn api_method_close_fixed_index() -> ApiMethod {
434 ApiMethod::new(
435 close_fixed_index,
436 ObjectSchema::new("Close fixed index writer.")
437 .required("wid", IntegerSchema::new("Fixed writer ID.")
438 .minimum(1)
439 .maximum(256)
440 )
441 .required("chunk-count", IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
442 .minimum(1)
443 )
444 .required("size", IntegerSchema::new("File size. This is used to verify that the server got all data.")
445 .minimum(1)
446 )
447 )
448 }
449
450 fn close_fixed_index (
451 param: Value,
452 _info: &ApiMethod,
453 rpcenv: &mut dyn RpcEnvironment,
454 ) -> Result<Value, Error> {
455
456 let wid = tools::required_integer_param(&param, "wid")? as usize;
457 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
458 let size = tools::required_integer_param(&param, "size")? as u64;
459
460 let env: &BackupEnvironment = rpcenv.as_ref();
461
462 env.fixed_writer_close(wid, chunk_count, size)?;
463
464 env.log(format!("sucessfully closed fixed index {}", wid));
465
466 Ok(Value::Null)
467 }
468
469 fn finish_backup (
470 _param: Value,
471 _info: &ApiMethod,
472 rpcenv: &mut dyn RpcEnvironment,
473 ) -> Result<Value, Error> {
474
475 let env: &BackupEnvironment = rpcenv.as_ref();
476
477 env.finish_backup()?;
478 env.log("sucessfully finished backup");
479
480 Ok(Value::Null)
481 }
482
483 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod {
484 ApiAsyncMethod::new(
485 dynamic_chunk_index,
486 ObjectSchema::new(r###"
487 Download the dynamic chunk index from the previous backup.
488 Simply returns an empty list if this is the first backup.
489 "###
490 )
491 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
492 )
493 }
494
495 fn dynamic_chunk_index(
496 _parts: Parts,
497 _req_body: Body,
498 param: Value,
499 _info: &ApiAsyncMethod,
500 rpcenv: Box<dyn RpcEnvironment>,
501 ) -> Result<BoxFut, Error> {
502
503 let env: &BackupEnvironment = rpcenv.as_ref();
504
505 let mut archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
506
507 if !archive_name.ends_with(".pxar") {
508 bail!("wrong archive extension: '{}'", archive_name);
509 } else {
510 archive_name.push_str(".didx");
511 }
512
513 let empty_response = {
514 Response::builder()
515 .status(StatusCode::OK)
516 .body(Body::empty())?
517 };
518
519 let last_backup = match &env.last_backup {
520 Some(info) => info,
521 None => return Ok(Box::new(future::ok(empty_response))),
522 };
523
524 let mut path = last_backup.backup_dir.relative_path();
525 path.push(&archive_name);
526
527 let index = match env.datastore.open_dynamic_reader(path) {
528 Ok(index) => index,
529 Err(_) => {
530 env.log(format!("there is no last backup for archive '{}'", archive_name));
531 return Ok(Box::new(future::ok(empty_response)));
532 }
533 };
534
535 env.log(format!("download last backup index for archive '{}'", archive_name));
536
537 let count = index.index_count();
538 for pos in 0..count {
539 let (start, end, digest) = index.chunk_info(pos)?;
540 let size = (end - start) as u32;
541 env.register_chunk(digest, size)?;
542 }
543
544 let reader = DigestListEncoder::new(Box::new(index));
545
546 let stream = WrappedReaderStream::new(reader);
547
548 // fixme: set size, content type?
549 let response = http::Response::builder()
550 .status(200)
551 .body(Body::wrap_stream(stream))?;
552
553 Ok(Box::new(future::ok(response)))
554 }
555
556 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod {
557 ApiAsyncMethod::new(
558 fixed_chunk_index,
559 ObjectSchema::new(r###"
560 Download the fixed chunk index from the previous backup.
561 Simply returns an empty list if this is the first backup.
562 "###
563 )
564 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
565 )
566 }
567
568 fn fixed_chunk_index(
569 _parts: Parts,
570 _req_body: Body,
571 param: Value,
572 _info: &ApiAsyncMethod,
573 rpcenv: Box<dyn RpcEnvironment>,
574 ) -> Result<BoxFut, Error> {
575
576 let env: &BackupEnvironment = rpcenv.as_ref();
577
578 let mut archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
579
580 if !archive_name.ends_with(".img") {
581 bail!("wrong archive extension: '{}'", archive_name);
582 } else {
583 archive_name.push_str(".fidx");
584 }
585
586 let empty_response = {
587 Response::builder()
588 .status(StatusCode::OK)
589 .body(Body::empty())?
590 };
591
592 let last_backup = match &env.last_backup {
593 Some(info) => info,
594 None => return Ok(Box::new(future::ok(empty_response))),
595 };
596
597 let mut path = last_backup.backup_dir.relative_path();
598 path.push(&archive_name);
599
600 let index = match env.datastore.open_fixed_reader(path) {
601 Ok(index) => index,
602 Err(_) => {
603 env.log(format!("there is no last backup for archive '{}'", archive_name));
604 return Ok(Box::new(future::ok(empty_response)));
605 }
606 };
607
608 env.log(format!("download last backup index for archive '{}'", archive_name));
609
610 let count = index.index_count();
611 let image_size = index.index_bytes();
612 for pos in 0..count {
613 let digest = index.index_digest(pos).unwrap();
614 // Note: last chunk can be smaller
615 let start = (pos*index.chunk_size) as u64;
616 let mut end = start + index.chunk_size as u64;
617 if end > image_size { end = image_size; }
618 let size = (end - start) as u32;
619 env.register_chunk(*digest, size)?;
620 }
621
622 let reader = DigestListEncoder::new(Box::new(index));
623
624 let stream = WrappedReaderStream::new(reader);
625
626 // fixme: set size, content type?
627 let response = http::Response::builder()
628 .status(200)
629 .body(Body::wrap_stream(stream))?;
630
631 Ok(Box::new(future::ok(response)))
632 }