]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/backup.rs
api: always use complete file names (including add exctensions)
[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 archive_name = name.clone();
232 if !archive_name.ends_with(".pxar.didx") {
233 bail!("wrong archive extension: '{}'", archive_name);
234 }
235
236 let mut path = env.backup_dir.relative_path();
237 path.push(archive_name);
238
239 let index = env.datastore.create_dynamic_writer(&path)?;
240 let wid = env.register_dynamic_writer(index, name)?;
241
242 env.log(format!("created new dynamic index {} ({:?})", wid, path));
243
244 Ok(json!(wid))
245 }
246
247 pub fn api_method_create_fixed_index() -> ApiMethod {
248 ApiMethod::new(
249 create_fixed_index,
250 ObjectSchema::new("Create fixed chunk index file.")
251 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
252 .required("size", IntegerSchema::new("File size.")
253 .minimum(1)
254 )
255 )
256 }
257
258 fn create_fixed_index(
259 param: Value,
260 _info: &ApiMethod,
261 rpcenv: &mut dyn RpcEnvironment,
262 ) -> Result<Value, Error> {
263
264 let env: &BackupEnvironment = rpcenv.as_ref();
265
266 println!("PARAM: {:?}", param);
267
268 let name = tools::required_string_param(&param, "archive-name")?.to_owned();
269 let size = tools::required_integer_param(&param, "size")? as usize;
270
271 let archive_name = name.clone();
272 if !archive_name.ends_with(".img.fidx") {
273 bail!("wrong archive extension: '{}'", archive_name);
274 }
275
276 let mut path = env.backup_dir.relative_path();
277 path.push(archive_name);
278
279 let chunk_size = 4096*1024; // todo: ??
280
281 let index = env.datastore.create_fixed_writer(&path, size, chunk_size)?;
282 let wid = env.register_fixed_writer(index, name, size, chunk_size as u32)?;
283
284 env.log(format!("created new fixed index {} ({:?})", wid, path));
285
286 Ok(json!(wid))
287 }
288
289 pub fn api_method_dynamic_append() -> ApiMethod {
290 ApiMethod::new(
291 dynamic_append,
292 ObjectSchema::new("Append chunk to dynamic index writer.")
293 .required("wid", IntegerSchema::new("Dynamic writer ID.")
294 .minimum(1)
295 .maximum(256)
296 )
297 .required("digest-list", ArraySchema::new(
298 "Chunk digest list.", CHUNK_DIGEST_SCHEMA.clone())
299 )
300 .required("offset-list", ArraySchema::new(
301 "Chunk offset list.",
302 IntegerSchema::new("Corresponding chunk offsets.")
303 .minimum(0)
304 .into())
305 )
306 )
307 }
308
309 fn dynamic_append (
310 param: Value,
311 _info: &ApiMethod,
312 rpcenv: &mut dyn RpcEnvironment,
313 ) -> Result<Value, Error> {
314
315 let wid = tools::required_integer_param(&param, "wid")? as usize;
316 let digest_list = tools::required_array_param(&param, "digest-list")?;
317 let offset_list = tools::required_array_param(&param, "offset-list")?;
318
319 if offset_list.len() != digest_list.len() {
320 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
321 }
322
323 let env: &BackupEnvironment = rpcenv.as_ref();
324
325 env.debug(format!("dynamic_append {} chunks", digest_list.len()));
326
327 for (i, item) in digest_list.iter().enumerate() {
328 let digest_str = item.as_str().unwrap();
329 let digest = proxmox::tools::hex_to_digest(digest_str)?;
330 let offset = offset_list[i].as_u64().unwrap();
331 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
332
333 env.dynamic_writer_append_chunk(wid, offset, size, &digest)?;
334
335 env.debug(format!("sucessfully added chunk {} to dynamic index {} (offset {}, size {})", digest_str, wid, offset, size));
336 }
337
338 Ok(Value::Null)
339 }
340
341 pub fn api_method_fixed_append() -> ApiMethod {
342 ApiMethod::new(
343 fixed_append,
344 ObjectSchema::new("Append chunk to fixed index writer.")
345 .required("wid", IntegerSchema::new("Fixed writer ID.")
346 .minimum(1)
347 .maximum(256)
348 )
349 .required("digest-list", ArraySchema::new(
350 "Chunk digest list.", CHUNK_DIGEST_SCHEMA.clone())
351 )
352 .required("offset-list", ArraySchema::new(
353 "Chunk offset list.",
354 IntegerSchema::new("Corresponding chunk offsets.")
355 .minimum(0)
356 .into())
357 )
358 )
359 }
360
361 fn fixed_append (
362 param: Value,
363 _info: &ApiMethod,
364 rpcenv: &mut dyn RpcEnvironment,
365 ) -> Result<Value, Error> {
366
367 let wid = tools::required_integer_param(&param, "wid")? as usize;
368 let digest_list = tools::required_array_param(&param, "digest-list")?;
369 let offset_list = tools::required_array_param(&param, "offset-list")?;
370
371 if offset_list.len() != digest_list.len() {
372 bail!("offset list has wrong length ({} != {})", offset_list.len(), digest_list.len());
373 }
374
375 let env: &BackupEnvironment = rpcenv.as_ref();
376
377 env.debug(format!("fixed_append {} chunks", digest_list.len()));
378
379 for (i, item) in digest_list.iter().enumerate() {
380 let digest_str = item.as_str().unwrap();
381 let digest = proxmox::tools::hex_to_digest(digest_str)?;
382 let offset = offset_list[i].as_u64().unwrap();
383 let size = env.lookup_chunk(&digest).ok_or_else(|| format_err!("no such chunk {}", digest_str))?;
384
385 env.fixed_writer_append_chunk(wid, offset, size, &digest)?;
386
387 env.debug(format!("sucessfully added chunk {} to fixed index {} (offset {}, size {})", digest_str, wid, offset, size));
388 }
389
390 Ok(Value::Null)
391 }
392
393 pub fn api_method_close_dynamic_index() -> ApiMethod {
394 ApiMethod::new(
395 close_dynamic_index,
396 ObjectSchema::new("Close dynamic index writer.")
397 .required("wid", IntegerSchema::new("Dynamic writer ID.")
398 .minimum(1)
399 .maximum(256)
400 )
401 .required("chunk-count", IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
402 .minimum(1)
403 )
404 .required("size", IntegerSchema::new("File size. This is used to verify that the server got all data.")
405 .minimum(1)
406 )
407 )
408 }
409
410 fn close_dynamic_index (
411 param: Value,
412 _info: &ApiMethod,
413 rpcenv: &mut dyn RpcEnvironment,
414 ) -> Result<Value, Error> {
415
416 let wid = tools::required_integer_param(&param, "wid")? as usize;
417 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
418 let size = tools::required_integer_param(&param, "size")? as u64;
419
420 let env: &BackupEnvironment = rpcenv.as_ref();
421
422 env.dynamic_writer_close(wid, chunk_count, size)?;
423
424 env.log(format!("sucessfully closed dynamic index {}", wid));
425
426 Ok(Value::Null)
427 }
428
429 pub fn api_method_close_fixed_index() -> ApiMethod {
430 ApiMethod::new(
431 close_fixed_index,
432 ObjectSchema::new("Close fixed index writer.")
433 .required("wid", IntegerSchema::new("Fixed writer ID.")
434 .minimum(1)
435 .maximum(256)
436 )
437 .required("chunk-count", IntegerSchema::new("Chunk count. This is used to verify that the server got all chunks.")
438 .minimum(1)
439 )
440 .required("size", IntegerSchema::new("File size. This is used to verify that the server got all data.")
441 .minimum(1)
442 )
443 )
444 }
445
446 fn close_fixed_index (
447 param: Value,
448 _info: &ApiMethod,
449 rpcenv: &mut dyn RpcEnvironment,
450 ) -> Result<Value, Error> {
451
452 let wid = tools::required_integer_param(&param, "wid")? as usize;
453 let chunk_count = tools::required_integer_param(&param, "chunk-count")? as u64;
454 let size = tools::required_integer_param(&param, "size")? as u64;
455
456 let env: &BackupEnvironment = rpcenv.as_ref();
457
458 env.fixed_writer_close(wid, chunk_count, size)?;
459
460 env.log(format!("sucessfully closed fixed index {}", wid));
461
462 Ok(Value::Null)
463 }
464
465 fn finish_backup (
466 _param: Value,
467 _info: &ApiMethod,
468 rpcenv: &mut dyn RpcEnvironment,
469 ) -> Result<Value, Error> {
470
471 let env: &BackupEnvironment = rpcenv.as_ref();
472
473 env.finish_backup()?;
474 env.log("sucessfully finished backup");
475
476 Ok(Value::Null)
477 }
478
479 pub fn api_method_dynamic_chunk_index() -> ApiAsyncMethod {
480 ApiAsyncMethod::new(
481 dynamic_chunk_index,
482 ObjectSchema::new(r###"
483 Download the dynamic chunk index from the previous backup.
484 Simply returns an empty list if this is the first backup.
485 "###
486 )
487 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
488 )
489 }
490
491 fn dynamic_chunk_index(
492 _parts: Parts,
493 _req_body: Body,
494 param: Value,
495 _info: &ApiAsyncMethod,
496 rpcenv: Box<dyn RpcEnvironment>,
497 ) -> Result<BoxFut, Error> {
498
499 let env: &BackupEnvironment = rpcenv.as_ref();
500
501 let archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
502
503 if !archive_name.ends_with(".pxar.didx") {
504 bail!("wrong archive extension: '{}'", archive_name);
505 }
506
507 let empty_response = {
508 Response::builder()
509 .status(StatusCode::OK)
510 .body(Body::empty())?
511 };
512
513 let last_backup = match &env.last_backup {
514 Some(info) => info,
515 None => return Ok(Box::new(future::ok(empty_response))),
516 };
517
518 let mut path = last_backup.backup_dir.relative_path();
519 path.push(&archive_name);
520
521 let index = match env.datastore.open_dynamic_reader(path) {
522 Ok(index) => index,
523 Err(_) => {
524 env.log(format!("there is no last backup for archive '{}'", archive_name));
525 return Ok(Box::new(future::ok(empty_response)));
526 }
527 };
528
529 env.log(format!("download last backup index for archive '{}'", archive_name));
530
531 let count = index.index_count();
532 for pos in 0..count {
533 let (start, end, digest) = index.chunk_info(pos)?;
534 let size = (end - start) as u32;
535 env.register_chunk(digest, size)?;
536 }
537
538 let reader = DigestListEncoder::new(Box::new(index));
539
540 let stream = WrappedReaderStream::new(reader);
541
542 // fixme: set size, content type?
543 let response = http::Response::builder()
544 .status(200)
545 .body(Body::wrap_stream(stream))?;
546
547 Ok(Box::new(future::ok(response)))
548 }
549
550 pub fn api_method_fixed_chunk_index() -> ApiAsyncMethod {
551 ApiAsyncMethod::new(
552 fixed_chunk_index,
553 ObjectSchema::new(r###"
554 Download the fixed chunk index from the previous backup.
555 Simply returns an empty list if this is the first backup.
556 "###
557 )
558 .required("archive-name", crate::api2::types::BACKUP_ARCHIVE_NAME_SCHEMA.clone())
559 )
560 }
561
562 fn fixed_chunk_index(
563 _parts: Parts,
564 _req_body: Body,
565 param: Value,
566 _info: &ApiAsyncMethod,
567 rpcenv: Box<dyn RpcEnvironment>,
568 ) -> Result<BoxFut, Error> {
569
570 let env: &BackupEnvironment = rpcenv.as_ref();
571
572 let archive_name = tools::required_string_param(&param, "archive-name")?.to_owned();
573
574 if !archive_name.ends_with(".img.fidx") {
575 bail!("wrong archive extension: '{}'", archive_name);
576 }
577
578 let empty_response = {
579 Response::builder()
580 .status(StatusCode::OK)
581 .body(Body::empty())?
582 };
583
584 let last_backup = match &env.last_backup {
585 Some(info) => info,
586 None => return Ok(Box::new(future::ok(empty_response))),
587 };
588
589 let mut path = last_backup.backup_dir.relative_path();
590 path.push(&archive_name);
591
592 let index = match env.datastore.open_fixed_reader(path) {
593 Ok(index) => index,
594 Err(_) => {
595 env.log(format!("there is no last backup for archive '{}'", archive_name));
596 return Ok(Box::new(future::ok(empty_response)));
597 }
598 };
599
600 env.log(format!("download last backup index for archive '{}'", archive_name));
601
602 let count = index.index_count();
603 let image_size = index.index_bytes();
604 for pos in 0..count {
605 let digest = index.index_digest(pos).unwrap();
606 // Note: last chunk can be smaller
607 let start = (pos*index.chunk_size) as u64;
608 let mut end = start + index.chunk_size as u64;
609 if end > image_size { end = image_size; }
610 let size = (end - start) as u32;
611 env.register_chunk(*digest, size)?;
612 }
613
614 let reader = DigestListEncoder::new(Box::new(index));
615
616 let stream = WrappedReaderStream::new(reader);
617
618 // fixme: set size, content type?
619 let response = http::Response::builder()
620 .status(200)
621 .body(Body::wrap_stream(stream))?;
622
623 Ok(Box::new(future::ok(response)))
624 }