1 use std
::collections
::{HashSet, HashMap}
;
2 use std
::io
::{self, Write, Seek, SeekFrom}
;
3 use std
::path
::{Path, PathBuf}
;
5 use std
::sync
::{Arc, Mutex}
;
6 use std
::task
::Context
;
8 use anyhow
::{bail, format_err, Error}
;
9 use chrono
::{Local, DateTime, Utc, TimeZone}
;
10 use futures
::future
::FutureExt
;
11 use futures
::stream
::{StreamExt, TryStreamExt}
;
12 use serde_json
::{json, Value}
;
13 use tokio
::sync
::mpsc
;
14 use xdg
::BaseDirectories
;
16 use pathpatterns
::{MatchEntry, MatchType, PatternFlag}
;
17 use proxmox
::tools
::fs
::{file_get_contents, file_get_json, replace_file, CreateOptions, image_size}
;
18 use proxmox
::api
::{ApiHandler, ApiMethod, RpcEnvironment}
;
19 use proxmox
::api
::schema
::*;
20 use proxmox
::api
::cli
::*;
21 use proxmox
::api
::api
;
22 use pxar
::accessor
::{MaybeReady, ReadAt, ReadAtOperation}
;
24 use proxmox_backup
::tools
;
25 use proxmox_backup
::api2
::types
::*;
26 use proxmox_backup
::client
::*;
27 use proxmox_backup
::pxar
::catalog
::*;
28 use proxmox_backup
::backup
::{
37 BufferedDynamicReader
,
53 mod proxmox_backup_client
;
54 use proxmox_backup_client
::*;
56 const ENV_VAR_PBS_FINGERPRINT
: &str = "PBS_FINGERPRINT";
57 const ENV_VAR_PBS_PASSWORD
: &str = "PBS_PASSWORD";
60 pub const REPO_URL_SCHEMA
: Schema
= StringSchema
::new("Repository URL.")
61 .format(&BACKUP_REPO_URL
)
65 pub const KEYFILE_SCHEMA
: Schema
= StringSchema
::new(
66 "Path to encryption key. All data will be encrypted using this key.")
69 pub const ENCRYPTION_SCHEMA
: Schema
= BooleanSchema
::new(
70 "Explicitly enable or disable encryption. \
71 (Allows disabling encryption when a default key file is present.)")
74 const CHUNK_SIZE_SCHEMA
: Schema
= IntegerSchema
::new(
75 "Chunk size in KB. Must be a power of 2.")
81 fn get_default_repository() -> Option
<String
> {
82 std
::env
::var("PBS_REPOSITORY").ok()
85 pub fn extract_repository_from_value(
87 ) -> Result
<BackupRepository
, Error
> {
89 let repo_url
= param
["repository"]
92 .or_else(get_default_repository
)
93 .ok_or_else(|| format_err
!("unable to get (default) repository"))?
;
95 let repo
: BackupRepository
= repo_url
.parse()?
;
100 fn extract_repository_from_map(
101 param
: &HashMap
<String
, String
>,
102 ) -> Option
<BackupRepository
> {
104 param
.get("repository")
106 .or_else(get_default_repository
)
107 .and_then(|repo_url
| repo_url
.parse
::<BackupRepository
>().ok())
110 fn record_repository(repo
: &BackupRepository
) {
112 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
117 // usually $HOME/.cache/proxmox-backup/repo-list
118 let path
= match base
.place_cache_file("repo-list") {
123 let mut data
= file_get_json(&path
, None
).unwrap_or_else(|_
| json
!({}
));
125 let repo
= repo
.to_string();
127 data
[&repo
] = json
!{ data[&repo].as_i64().unwrap_or(0) + 1 }
;
129 let mut map
= serde_json
::map
::Map
::new();
132 let mut max_used
= 0;
133 let mut max_repo
= None
;
134 for (repo
, count
) in data
.as_object().unwrap() {
135 if map
.contains_key(repo
) { continue; }
136 if let Some(count
) = count
.as_i64() {
137 if count
> max_used
{
139 max_repo
= Some(repo
);
143 if let Some(repo
) = max_repo
{
144 map
.insert(repo
.to_owned(), json
!(max_used
));
148 if map
.len() > 10 { // store max. 10 repos
153 let new_data
= json
!(map
);
155 let _
= replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new());
158 pub fn complete_repository(_arg
: &str, _param
: &HashMap
<String
, String
>) -> Vec
<String
> {
160 let mut result
= vec
![];
162 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
167 // usually $HOME/.cache/proxmox-backup/repo-list
168 let path
= match base
.place_cache_file("repo-list") {
173 let data
= file_get_json(&path
, None
).unwrap_or_else(|_
| json
!({}
));
175 if let Some(map
) = data
.as_object() {
176 for (repo
, _count
) in map
{
177 result
.push(repo
.to_owned());
184 fn connect(server
: &str, userid
: &str) -> Result
<HttpClient
, Error
> {
186 let fingerprint
= std
::env
::var(ENV_VAR_PBS_FINGERPRINT
).ok();
188 use std
::env
::VarError
::*;
189 let password
= match std
::env
::var(ENV_VAR_PBS_PASSWORD
) {
191 Err(NotUnicode(_
)) => bail
!(format
!("{} contains bad characters", ENV_VAR_PBS_PASSWORD
)),
192 Err(NotPresent
) => None
,
195 let options
= HttpClientOptions
::new()
196 .prefix(Some("proxmox-backup".to_string()))
199 .fingerprint(fingerprint
)
200 .fingerprint_cache(true)
203 HttpClient
::new(server
, userid
, options
)
206 async
fn view_task_result(
210 ) -> Result
<(), Error
> {
211 let data
= &result
["data"];
212 if output_format
== "text" {
213 if let Some(upid
) = data
.as_str() {
214 display_task_log(client
, upid
, true).await?
;
217 format_and_print_result(&data
, &output_format
);
223 async
fn api_datastore_list_snapshots(
226 group
: Option
<BackupGroup
>,
227 ) -> Result
<Value
, Error
> {
229 let path
= format
!("api2/json/admin/datastore/{}/snapshots", store
);
231 let mut args
= json
!({}
);
232 if let Some(group
) = group
{
233 args
["backup-type"] = group
.backup_type().into();
234 args
["backup-id"] = group
.backup_id().into();
237 let mut result
= client
.get(&path
, Some(args
)).await?
;
239 Ok(result
["data"].take())
242 pub async
fn api_datastore_latest_snapshot(
246 ) -> Result
<(String
, String
, DateTime
<Utc
>), Error
> {
248 let list
= api_datastore_list_snapshots(client
, store
, Some(group
.clone())).await?
;
249 let mut list
: Vec
<SnapshotListItem
> = serde_json
::from_value(list
)?
;
252 bail
!("backup group {:?} does not contain any snapshots.", group
.group_path());
255 list
.sort_unstable_by(|a
, b
| b
.backup_time
.cmp(&a
.backup_time
));
257 let backup_time
= Utc
.timestamp(list
[0].backup_time
, 0);
259 Ok((group
.backup_type().to_owned(), group
.backup_id().to_owned(), backup_time
))
262 async
fn backup_directory
<P
: AsRef
<Path
>>(
263 client
: &BackupWriter
,
264 previous_manifest
: Option
<Arc
<BackupManifest
>>,
267 chunk_size
: Option
<usize>,
268 device_set
: Option
<HashSet
<u64>>,
270 skip_lost_and_found
: bool
,
271 catalog
: Arc
<Mutex
<CatalogWriter
<crate::tools
::StdChannelWriter
>>>,
272 exclude_pattern
: Vec
<MatchEntry
>,
274 ) -> Result
<BackupStats
, Error
> {
276 let pxar_stream
= PxarBackupStream
::open(
285 let mut chunk_stream
= ChunkStream
::new(pxar_stream
, chunk_size
);
287 let (mut tx
, rx
) = mpsc
::channel(10); // allow to buffer 10 chunks
290 .map_err(Error
::from
);
292 // spawn chunker inside a separate task so that it can run parallel
293 tokio
::spawn(async
move {
294 while let Some(v
) = chunk_stream
.next().await
{
295 let _
= tx
.send(v
).await
;
300 .upload_stream(previous_manifest
, archive_name
, stream
, "dynamic", None
)
306 async
fn backup_image
<P
: AsRef
<Path
>>(
307 client
: &BackupWriter
,
308 previous_manifest
: Option
<Arc
<BackupManifest
>>,
312 chunk_size
: Option
<usize>,
314 ) -> Result
<BackupStats
, Error
> {
316 let path
= image_path
.as_ref().to_owned();
318 let file
= tokio
::fs
::File
::open(path
).await?
;
320 let stream
= tokio_util
::codec
::FramedRead
::new(file
, tokio_util
::codec
::BytesCodec
::new())
321 .map_err(Error
::from
);
323 let stream
= FixedChunkStream
::new(stream
, chunk_size
.unwrap_or(4*1024*1024));
326 .upload_stream(previous_manifest
, archive_name
, stream
, "fixed", Some(image_size
))
336 schema
: REPO_URL_SCHEMA
,
340 schema
: OUTPUT_FORMAT
,
346 /// List backup groups.
347 async
fn list_backup_groups(param
: Value
) -> Result
<Value
, Error
> {
349 let output_format
= get_output_format(¶m
);
351 let repo
= extract_repository_from_value(¶m
)?
;
353 let client
= connect(repo
.host(), repo
.user())?
;
355 let path
= format
!("api2/json/admin/datastore/{}/groups", repo
.store());
357 let mut result
= client
.get(&path
, None
).await?
;
359 record_repository(&repo
);
361 let render_group_path
= |_v
: &Value
, record
: &Value
| -> Result
<String
, Error
> {
362 let item
: GroupListItem
= serde_json
::from_value(record
.to_owned())?
;
363 let group
= BackupGroup
::new(item
.backup_type
, item
.backup_id
);
364 Ok(group
.group_path().to_str().unwrap().to_owned())
367 let render_last_backup
= |_v
: &Value
, record
: &Value
| -> Result
<String
, Error
> {
368 let item
: GroupListItem
= serde_json
::from_value(record
.to_owned())?
;
369 let snapshot
= BackupDir
::new(item
.backup_type
, item
.backup_id
, item
.last_backup
);
370 Ok(snapshot
.relative_path().to_str().unwrap().to_owned())
373 let render_files
= |_v
: &Value
, record
: &Value
| -> Result
<String
, Error
> {
374 let item
: GroupListItem
= serde_json
::from_value(record
.to_owned())?
;
375 Ok(tools
::format
::render_backup_file_list(&item
.files
))
378 let options
= default_table_format_options()
379 .sortby("backup-type", false)
380 .sortby("backup-id", false)
381 .column(ColumnConfig
::new("backup-id").renderer(render_group_path
).header("group"))
383 ColumnConfig
::new("last-backup")
384 .renderer(render_last_backup
)
385 .header("last snapshot")
388 .column(ColumnConfig
::new("backup-count"))
389 .column(ColumnConfig
::new("files").renderer(render_files
));
391 let mut data
: Value
= result
["data"].take();
393 let info
= &proxmox_backup
::api2
::admin
::datastore
::API_RETURN_SCHEMA_LIST_GROUPS
;
395 format_and_print_result_full(&mut data
, info
, &output_format
, &options
);
404 schema
: REPO_URL_SCHEMA
,
409 description
: "Backup group.",
413 schema
: OUTPUT_FORMAT
,
419 /// List backup snapshots.
420 async
fn list_snapshots(param
: Value
) -> Result
<Value
, Error
> {
422 let repo
= extract_repository_from_value(¶m
)?
;
424 let output_format
= get_output_format(¶m
);
426 let client
= connect(repo
.host(), repo
.user())?
;
428 let group
: Option
<BackupGroup
> = if let Some(path
) = param
["group"].as_str() {
434 let mut data
= api_datastore_list_snapshots(&client
, repo
.store(), group
).await?
;
436 record_repository(&repo
);
438 let render_snapshot_path
= |_v
: &Value
, record
: &Value
| -> Result
<String
, Error
> {
439 let item
: SnapshotListItem
= serde_json
::from_value(record
.to_owned())?
;
440 let snapshot
= BackupDir
::new(item
.backup_type
, item
.backup_id
, item
.backup_time
);
441 Ok(snapshot
.relative_path().to_str().unwrap().to_owned())
444 let render_files
= |_v
: &Value
, record
: &Value
| -> Result
<String
, Error
> {
445 let item
: SnapshotListItem
= serde_json
::from_value(record
.to_owned())?
;
446 let mut filenames
= Vec
::new();
447 for file
in &item
.files
{
448 filenames
.push(file
.filename
.to_string());
450 Ok(tools
::format
::render_backup_file_list(&filenames
[..]))
453 let options
= default_table_format_options()
454 .sortby("backup-type", false)
455 .sortby("backup-id", false)
456 .sortby("backup-time", false)
457 .column(ColumnConfig
::new("backup-id").renderer(render_snapshot_path
).header("snapshot"))
458 .column(ColumnConfig
::new("size"))
459 .column(ColumnConfig
::new("files").renderer(render_files
))
462 let info
= &proxmox_backup
::api2
::admin
::datastore
::API_RETURN_SCHEMA_LIST_SNAPSHOTS
;
464 format_and_print_result_full(&mut data
, info
, &output_format
, &options
);
473 schema
: REPO_URL_SCHEMA
,
478 description
: "Snapshot path.",
483 /// Forget (remove) backup snapshots.
484 async
fn forget_snapshots(param
: Value
) -> Result
<Value
, Error
> {
486 let repo
= extract_repository_from_value(¶m
)?
;
488 let path
= tools
::required_string_param(¶m
, "snapshot")?
;
489 let snapshot
: BackupDir
= path
.parse()?
;
491 let mut client
= connect(repo
.host(), repo
.user())?
;
493 let path
= format
!("api2/json/admin/datastore/{}/snapshots", repo
.store());
495 let result
= client
.delete(&path
, Some(json
!({
496 "backup-type": snapshot
.group().backup_type(),
497 "backup-id": snapshot
.group().backup_id(),
498 "backup-time": snapshot
.backup_time().timestamp(),
501 record_repository(&repo
);
510 schema
: REPO_URL_SCHEMA
,
516 /// Try to login. If successful, store ticket.
517 async
fn api_login(param
: Value
) -> Result
<Value
, Error
> {
519 let repo
= extract_repository_from_value(¶m
)?
;
521 let client
= connect(repo
.host(), repo
.user())?
;
522 client
.login().await?
;
524 record_repository(&repo
);
533 schema
: REPO_URL_SCHEMA
,
539 /// Logout (delete stored ticket).
540 fn api_logout(param
: Value
) -> Result
<Value
, Error
> {
542 let repo
= extract_repository_from_value(¶m
)?
;
544 delete_ticket_info("proxmox-backup", repo
.host(), repo
.user())?
;
554 schema
: REPO_URL_SCHEMA
,
559 description
: "Snapshot path.",
562 schema
: OUTPUT_FORMAT
,
568 /// List snapshot files.
569 async
fn list_snapshot_files(param
: Value
) -> Result
<Value
, Error
> {
571 let repo
= extract_repository_from_value(¶m
)?
;
573 let path
= tools
::required_string_param(¶m
, "snapshot")?
;
574 let snapshot
: BackupDir
= path
.parse()?
;
576 let output_format
= get_output_format(¶m
);
578 let client
= connect(repo
.host(), repo
.user())?
;
580 let path
= format
!("api2/json/admin/datastore/{}/files", repo
.store());
582 let mut result
= client
.get(&path
, Some(json
!({
583 "backup-type": snapshot
.group().backup_type(),
584 "backup-id": snapshot
.group().backup_id(),
585 "backup-time": snapshot
.backup_time().timestamp(),
588 record_repository(&repo
);
590 let info
= &proxmox_backup
::api2
::admin
::datastore
::API_RETURN_SCHEMA_LIST_SNAPSHOT_FILES
;
592 let mut data
: Value
= result
["data"].take();
594 let options
= default_table_format_options();
596 format_and_print_result_full(&mut data
, info
, &output_format
, &options
);
605 schema
: REPO_URL_SCHEMA
,
609 schema
: OUTPUT_FORMAT
,
615 /// Start garbage collection for a specific repository.
616 async
fn start_garbage_collection(param
: Value
) -> Result
<Value
, Error
> {
618 let repo
= extract_repository_from_value(¶m
)?
;
620 let output_format
= get_output_format(¶m
);
622 let mut client
= connect(repo
.host(), repo
.user())?
;
624 let path
= format
!("api2/json/admin/datastore/{}/gc", repo
.store());
626 let result
= client
.post(&path
, None
).await?
;
628 record_repository(&repo
);
630 view_task_result(client
, result
, &output_format
).await?
;
635 fn spawn_catalog_upload(
636 client
: Arc
<BackupWriter
>
639 Arc
<Mutex
<CatalogWriter
<crate::tools
::StdChannelWriter
>>>,
640 tokio
::sync
::oneshot
::Receiver
<Result
<BackupStats
, Error
>>
643 let (catalog_tx
, catalog_rx
) = std
::sync
::mpsc
::sync_channel(10); // allow to buffer 10 writes
644 let catalog_stream
= crate::tools
::StdChannelStream(catalog_rx
);
645 let catalog_chunk_size
= 512*1024;
646 let catalog_chunk_stream
= ChunkStream
::new(catalog_stream
, Some(catalog_chunk_size
));
648 let catalog
= Arc
::new(Mutex
::new(CatalogWriter
::new(crate::tools
::StdChannelWriter
::new(catalog_tx
))?
));
650 let (catalog_result_tx
, catalog_result_rx
) = tokio
::sync
::oneshot
::channel();
652 tokio
::spawn(async
move {
653 let catalog_upload_result
= client
654 .upload_stream(None
, CATALOG_NAME
, catalog_chunk_stream
, "dynamic", None
)
657 if let Err(ref err
) = catalog_upload_result
{
658 eprintln
!("catalog upload error - {}", err
);
662 let _
= catalog_result_tx
.send(catalog_upload_result
);
665 Ok((catalog
, catalog_result_rx
))
668 fn keyfile_parameters(param
: &Value
) -> Result
<(Option
<PathBuf
>, CryptMode
), Error
> {
669 let keyfile
= match param
.get("keyfile") {
670 Some(Value
::String(keyfile
)) => Some(keyfile
),
671 Some(_
) => bail
!("bad --keyfile parameter type"),
675 let crypt_mode
: Option
<CryptMode
> = match param
.get("crypt-mode") {
676 Some(mode
) => Some(serde_json
::from_value(mode
.clone())?
),
680 Ok(match (keyfile
, crypt_mode
) {
682 (None
, None
) => (key
::optional_default_key_path()?
, CryptMode
::Encrypt
),
684 // just --crypt-mode=none
685 (None
, Some(CryptMode
::None
)) => (None
, CryptMode
::None
),
687 // just --crypt-mode other than none
688 (None
, Some(crypt_mode
)) => match key
::optional_default_key_path()?
{
689 None
=> bail
!("--crypt-mode without --keyfile and no default key file available"),
690 Some(path
) => (Some(path
), crypt_mode
),
694 (Some(keyfile
), None
) => (Some(PathBuf
::from(keyfile
)), CryptMode
::Encrypt
),
696 // --keyfile and --crypt-mode=none
697 (Some(_
), Some(CryptMode
::None
)) => {
698 bail
!("--keyfile and --crypt-mode=none are mutually exclusive");
701 // --keyfile and --crypt-mode other than none
702 (Some(keyfile
), Some(crypt_mode
)) => (Some(PathBuf
::from(keyfile
)), crypt_mode
),
711 description
: "List of backup source specifications ([<label.ext>:<path>] ...)",
713 schema
: BACKUP_SOURCE_SCHEMA
,
717 schema
: REPO_URL_SCHEMA
,
721 description
: "Include mountpoints with same st_dev number (see ``man fstat``) as specified files.",
725 description
: "Path to file.",
729 schema
: KEYFILE_SCHEMA
,
733 schema
: ENCRYPTION_SCHEMA
,
736 "skip-lost-and-found": {
738 description
: "Skip lost+found directory.",
742 schema
: BACKUP_TYPE_SCHEMA
,
746 schema
: BACKUP_ID_SCHEMA
,
750 schema
: BACKUP_TIME_SCHEMA
,
754 schema
: CHUNK_SIZE_SCHEMA
,
759 description
: "List of paths or patterns for matching files to exclude.",
763 description
: "Path or match pattern.",
768 description
: "Max number of entries to hold in memory.",
770 default: proxmox_backup
::pxar
::ENCODER_MAX_ENTRIES
as isize,
774 description
: "Verbose output.",
780 /// Create (host) backup.
781 async
fn create_backup(
784 _rpcenv
: &mut dyn RpcEnvironment
,
785 ) -> Result
<Value
, Error
> {
787 let repo
= extract_repository_from_value(¶m
)?
;
789 let backupspec_list
= tools
::required_array_param(¶m
, "backupspec")?
;
791 let all_file_systems
= param
["all-file-systems"].as_bool().unwrap_or(false);
793 let skip_lost_and_found
= param
["skip-lost-and-found"].as_bool().unwrap_or(false);
795 let verbose
= param
["verbose"].as_bool().unwrap_or(false);
797 let backup_time_opt
= param
["backup-time"].as_i64();
799 let chunk_size_opt
= param
["chunk-size"].as_u64().map(|v
| (v
*1024) as usize);
801 if let Some(size
) = chunk_size_opt
{
802 verify_chunk_size(size
)?
;
805 let (keyfile
, crypt_mode
) = keyfile_parameters(¶m
)?
;
807 let backup_id
= param
["backup-id"].as_str().unwrap_or(&proxmox
::tools
::nodename());
809 let backup_type
= param
["backup-type"].as_str().unwrap_or("host");
811 let include_dev
= param
["include-dev"].as_array();
813 let entries_max
= param
["entries-max"].as_u64()
814 .unwrap_or(proxmox_backup
::pxar
::ENCODER_MAX_ENTRIES
as u64);
816 let empty
= Vec
::new();
817 let exclude_args
= param
["exclude"].as_array().unwrap_or(&empty
);
819 let mut pattern_list
= Vec
::with_capacity(exclude_args
.len());
820 for entry
in exclude_args
{
821 let entry
= entry
.as_str().ok_or_else(|| format_err
!("Invalid pattern string slice"))?
;
823 MatchEntry
::parse_pattern(entry
, PatternFlag
::PATH_NAME
, MatchType
::Exclude
)
824 .map_err(|err
| format_err
!("invalid exclude pattern entry: {}", err
))?
828 let mut devices
= if all_file_systems { None }
else { Some(HashSet::new()) }
;
830 if let Some(include_dev
) = include_dev
{
831 if all_file_systems
{
832 bail
!("option 'all-file-systems' conflicts with option 'include-dev'");
835 let mut set
= HashSet
::new();
836 for path
in include_dev
{
837 let path
= path
.as_str().unwrap();
838 let stat
= nix
::sys
::stat
::stat(path
)
839 .map_err(|err
| format_err
!("fstat {:?} failed - {}", path
, err
))?
;
840 set
.insert(stat
.st_dev
);
845 let mut upload_list
= vec
![];
847 for backupspec
in backupspec_list
{
848 let spec
= parse_backup_specification(backupspec
.as_str().unwrap())?
;
849 let filename
= &spec
.config_string
;
850 let target
= &spec
.archive_name
;
852 use std
::os
::unix
::fs
::FileTypeExt
;
854 let metadata
= std
::fs
::metadata(filename
)
855 .map_err(|err
| format_err
!("unable to access '{}' - {}", filename
, err
))?
;
856 let file_type
= metadata
.file_type();
858 match spec
.spec_type
{
859 BackupSpecificationType
::PXAR
=> {
860 if !file_type
.is_dir() {
861 bail
!("got unexpected file type (expected directory)");
863 upload_list
.push((BackupSpecificationType
::PXAR
, filename
.to_owned(), format
!("{}.didx", target
), 0));
865 BackupSpecificationType
::IMAGE
=> {
866 if !(file_type
.is_file() || file_type
.is_block_device()) {
867 bail
!("got unexpected file type (expected file or block device)");
870 let size
= image_size(&PathBuf
::from(filename
))?
;
872 if size
== 0 { bail!("got zero-sized file '{}'
", filename); }
874 upload_list.push((BackupSpecificationType::IMAGE, filename.to_owned(), format!("{}
.fidx
", target), size));
876 BackupSpecificationType::CONFIG => {
877 if !file_type.is_file() {
878 bail!("got unexpected file
type (expected regular file
)");
880 upload_list.push((BackupSpecificationType::CONFIG, filename.to_owned(), format!("{}
.blob
", target), metadata.len()));
882 BackupSpecificationType::LOGFILE => {
883 if !file_type.is_file() {
884 bail!("got unexpected file
type (expected regular file
)");
886 upload_list.push((BackupSpecificationType::LOGFILE, filename.to_owned(), format!("{}
.blob
", target), metadata.len()));
891 let backup_time = Utc.timestamp(backup_time_opt.unwrap_or_else(|| Utc::now().timestamp()), 0);
893 let client = connect(repo.host(), repo.user())?;
894 record_repository(&repo);
896 println!("Starting backup
: {}
/{}
/{}
", backup_type, backup_id, BackupDir::backup_time_to_string(backup_time));
898 println!("Client name
: {}
", proxmox::tools::nodename());
900 let start_time = Local::now();
902 println!("Starting protocol
: {}
", start_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
904 let (crypt_config, rsa_encrypted_key) = match keyfile {
905 None => (None, None),
907 let (key, created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
909 let crypt_config = CryptConfig::new(key)?;
911 let path = master_pubkey_path()?;
913 let pem_data = file_get_contents(&path)?;
914 let rsa = openssl::rsa::Rsa::public_key_from_pem(&pem_data)?;
915 let enc_key = crypt_config.generate_rsa_encoded_key(rsa, created)?;
916 (Some(Arc::new(crypt_config)), Some(enc_key))
918 (Some(Arc::new(crypt_config)), None)
923 let client = BackupWriter::start(
925 crypt_config.clone(),
933 let previous_manifest = if let Ok(previous_manifest) = client.download_previous_manifest().await {
934 Some(Arc::new(previous_manifest))
939 let snapshot = BackupDir::new(backup_type, backup_id, backup_time.timestamp());
940 let mut manifest = BackupManifest::new(snapshot);
942 let mut catalog = None;
943 let mut catalog_result_tx = None;
945 for (backup_type, filename, target, size) in upload_list {
947 BackupSpecificationType::CONFIG => {
948 println!("Upload config file '{}' to '{:?}'
as {}
", filename, repo, target);
950 .upload_blob_from_file(&filename, &target, true, crypt_mode)
952 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
954 BackupSpecificationType::LOGFILE => { // fixme: remove - not needed anymore ?
955 println!("Upload log file '{}' to '{:?}'
as {}
", filename, repo, target);
957 .upload_blob_from_file(&filename, &target, true, crypt_mode)
959 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
961 BackupSpecificationType::PXAR => {
962 // start catalog upload on first use
963 if catalog.is_none() {
964 let (cat, res) = spawn_catalog_upload(client.clone())?;
966 catalog_result_tx = Some(res);
968 let catalog = catalog.as_ref().unwrap();
970 println!("Upload directory '{}' to '{:?}'
as {}
", filename, repo, target);
971 catalog.lock().unwrap().start_directory(std::ffi::CString::new(target.as_str())?.as_c_str())?;
972 let stats = backup_directory(
974 previous_manifest.clone(),
982 pattern_list.clone(),
983 entries_max as usize,
985 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
986 catalog.lock().unwrap().end_directory()?;
988 BackupSpecificationType::IMAGE => {
989 println!("Upload image '{}' to '{:?}'
as {}
", filename, repo, target);
990 let stats = backup_image(
992 previous_manifest.clone(),
999 manifest.add_file(target, stats.size, stats.csum, crypt_mode)?;
1004 // finalize and upload catalog
1005 if let Some(catalog) = catalog {
1006 let mutex = Arc::try_unwrap(catalog)
1007 .map_err(|_| format_err!("unable to get
catalog (still used
)"))?;
1008 let mut catalog = mutex.into_inner().unwrap();
1012 drop(catalog); // close upload stream
1014 if let Some(catalog_result_rx) = catalog_result_tx {
1015 let stats = catalog_result_rx.await??;
1016 manifest.add_file(CATALOG_NAME.to_owned(), stats.size, stats.csum, crypt_mode)?;
1020 if let Some(rsa_encrypted_key) = rsa_encrypted_key {
1021 let target = "rsa
-encrypted
.key
";
1022 println!("Upload RSA encoded key to '{:?}'
as {}
", repo, target);
1024 .upload_blob_from_data(rsa_encrypted_key, target, false, CryptMode::None)
1026 manifest.add_file(format!("{}
.blob
", target), stats.size, stats.csum, crypt_mode)?;
1028 // openssl rsautl -decrypt -inkey master-private.pem -in rsa-encrypted.key -out t
1030 let mut buffer2 = vec![0u8; rsa.size() as usize];
1031 let pem_data = file_get_contents("master
-private
.pem
")?;
1032 let rsa = openssl::rsa::Rsa::private_key_from_pem(&pem_data)?;
1033 let len = rsa.private_decrypt(&buffer, &mut buffer2, openssl::rsa::Padding::PKCS1)?;
1034 println!("TEST {} {:?}
", len, buffer2);
1038 // create manifest (index.json)
1039 let manifest = manifest.into_json();
1041 println!("Upload index
.json to '{:?}'
", repo);
1042 let manifest = serde_json::to_string_pretty(&manifest)?.into();
1043 // manifests are never encrypted
1044 let manifest_crypt_mode = match crypt_mode {
1045 CryptMode::None => CryptMode::None,
1046 _ => CryptMode::SignOnly,
1049 .upload_blob_from_data(manifest, MANIFEST_BLOB_NAME, true, manifest_crypt_mode)
1052 client.finish().await?;
1054 let end_time = Local::now();
1055 let elapsed = end_time.signed_duration_since(start_time);
1056 println!("Duration
: {}
", elapsed);
1058 println!("End Time
: {}
", end_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
1063 fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1065 let mut result = vec![];
1067 let data: Vec<&str> = arg.splitn(2, ':').collect();
1069 if data.len() != 2 {
1070 result.push(String::from("root
.pxar
:/"));
1071 result.push(String::from("etc
.pxar
:/etc
"));
1075 let files = tools::complete_file_name(data[1], param);
1078 result.push(format!("{}
:{}
", data[0], file));
1084 async fn dump_image<W: Write>(
1085 client: Arc<BackupReader>,
1086 crypt_config: Option<Arc<CryptConfig>>,
1087 index: FixedIndexReader,
1090 ) -> Result<(), Error> {
1092 let most_used = index.find_most_used_chunks(8);
1094 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1096 // Note: we avoid using BufferedFixedReader, because that add an additional buffer/copy
1097 // and thus slows down reading. Instead, directly use RemoteChunkReader
1100 let start_time = std::time::Instant::now();
1102 for pos in 0..index.index_count() {
1103 let digest = index.index_digest(pos).unwrap();
1104 let raw_data = chunk_reader.read_chunk(&digest).await?;
1105 writer.write_all(&raw_data)?;
1106 bytes += raw_data.len();
1108 let next_per = ((pos+1)*100)/index.index_count();
1109 if per != next_per {
1110 eprintln!("progress {}
% (read {} bytes
, duration {} sec
)",
1111 next_per, bytes, start_time.elapsed().as_secs());
1117 let end_time = std::time::Instant::now();
1118 let elapsed = end_time.duration_since(start_time);
1119 eprintln!("restore image
complete (bytes
={}
, duration
={:.2}s
, speed
={:.2}MB
/s
)",
1121 elapsed.as_secs_f64(),
1122 bytes as f64/(1024.0*1024.0*elapsed.as_secs_f64())
1129 fn parse_archive_type(name: &str) -> (String, ArchiveType) {
1130 if name.ends_with(".didx
") || name.ends_with(".fidx
") || name.ends_with(".blob
") {
1131 (name.into(), archive_type(name).unwrap())
1132 } else if name.ends_with(".pxar
") {
1133 (format!("{}
.didx
", name), ArchiveType::DynamicIndex)
1134 } else if name.ends_with(".img
") {
1135 (format!("{}
.fidx
", name), ArchiveType::FixedIndex)
1137 (format!("{}
.blob
", name), ArchiveType::Blob)
1145 schema: REPO_URL_SCHEMA,
1150 description: "Group
/Snapshot path
.",
1153 description: "Backup archive name
.",
1158 description: r###"Target directory path
. Use '
-' to write to standard output
.
1160 We
do not extraxt '
.pxar' archives when writing to standard output
.
1164 "allow
-existing
-dirs
": {
1166 description: "Do not fail
if directories already exists
.",
1170 schema: KEYFILE_SCHEMA,
1174 schema: ENCRYPTION_SCHEMA,
1180 /// Restore backup repository.
1181 async fn restore(param: Value) -> Result<Value, Error> {
1182 let repo = extract_repository_from_value(¶m)?;
1184 let verbose = param["verbose
"].as_bool().unwrap_or(false);
1186 let allow_existing_dirs = param["allow
-existing
-dirs
"].as_bool().unwrap_or(false);
1188 let archive_name = tools::required_string_param(¶m, "archive
-name
")?;
1190 let client = connect(repo.host(), repo.user())?;
1192 record_repository(&repo);
1194 let path = tools::required_string_param(¶m, "snapshot
")?;
1196 let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 {
1197 let group: BackupGroup = path.parse()?;
1198 api_datastore_latest_snapshot(&client, repo.store(), group).await?
1200 let snapshot: BackupDir = path.parse()?;
1201 (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time())
1204 let target = tools::required_string_param(¶m, "target
")?;
1205 let target = if target == "-" { None } else { Some(target) };
1207 let (keyfile, _crypt_mode) = keyfile_parameters(¶m)?;
1209 let crypt_config = match keyfile {
1212 let (key, _) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
1213 Some(Arc::new(CryptConfig::new(key)?))
1217 let client = BackupReader::start(
1219 crypt_config.clone(),
1227 let manifest = client.download_manifest().await?;
1229 let (archive_name, archive_type) = parse_archive_type(archive_name);
1231 if archive_name == MANIFEST_BLOB_NAME {
1232 let backup_index_data = manifest.into_json().to_string();
1233 if let Some(target) = target {
1234 replace_file(target, backup_index_data.as_bytes(), CreateOptions::new())?;
1236 let stdout = std::io::stdout();
1237 let mut writer = stdout.lock();
1238 writer.write_all(backup_index_data.as_bytes())
1239 .map_err(|err| format_err!("unable to pipe data
- {}
", err))?;
1242 } else if archive_type == ArchiveType::Blob {
1244 let mut reader = client.download_blob(&manifest, &archive_name).await?;
1246 if let Some(target) = target {
1247 let mut writer = std::fs::OpenOptions::new()
1252 .map_err(|err| format_err!("unable to create target file {:?}
- {}
", target, err))?;
1253 std::io::copy(&mut reader, &mut writer)?;
1255 let stdout = std::io::stdout();
1256 let mut writer = stdout.lock();
1257 std::io::copy(&mut reader, &mut writer)
1258 .map_err(|err| format_err!("unable to pipe data
- {}
", err))?;
1261 } else if archive_type == ArchiveType::DynamicIndex {
1263 let index = client.download_dynamic_index(&manifest, &archive_name).await?;
1265 let most_used = index.find_most_used_chunks(8);
1267 let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, most_used);
1269 let mut reader = BufferedDynamicReader::new(index, chunk_reader);
1271 if let Some(target) = target {
1272 proxmox_backup::pxar::extract_archive(
1273 pxar::decoder::Decoder::from_std(reader)?,
1276 proxmox_backup::pxar::Flags::DEFAULT,
1277 allow_existing_dirs,
1280 println!("{:?}
", path);
1284 .map_err(|err| format_err!("error extracting archive
- {}
", err))?;
1286 let mut writer = std::fs::OpenOptions::new()
1288 .open("/dev
/stdout
")
1289 .map_err(|err| format_err!("unable to open
/dev
/stdout
- {}
", err))?;
1291 std::io::copy(&mut reader, &mut writer)
1292 .map_err(|err| format_err!("unable to pipe data
- {}
", err))?;
1294 } else if archive_type == ArchiveType::FixedIndex {
1296 let index = client.download_fixed_index(&manifest, &archive_name).await?;
1298 let mut writer = if let Some(target) = target {
1299 std::fs::OpenOptions::new()
1304 .map_err(|err| format_err!("unable to create target file {:?}
- {}
", target, err))?
1306 std::fs::OpenOptions::new()
1308 .open("/dev
/stdout
")
1309 .map_err(|err| format_err!("unable to open
/dev
/stdout
- {}
", err))?
1312 dump_image(client.clone(), crypt_config.clone(), index, &mut writer, verbose).await?;
1322 schema: REPO_URL_SCHEMA,
1327 description: "Group
/Snapshot path
.",
1331 description: "The path to the log file you want to upload
.",
1334 schema: KEYFILE_SCHEMA,
1338 schema: ENCRYPTION_SCHEMA,
1344 /// Upload backup log file.
1345 async fn upload_log(param: Value) -> Result<Value, Error> {
1347 let logfile = tools::required_string_param(¶m, "logfile
")?;
1348 let repo = extract_repository_from_value(¶m)?;
1350 let snapshot = tools::required_string_param(¶m, "snapshot
")?;
1351 let snapshot: BackupDir = snapshot.parse()?;
1353 let mut client = connect(repo.host(), repo.user())?;
1355 let (keyfile, crypt_mode) = keyfile_parameters(¶m)?;
1357 let crypt_config = match keyfile {
1360 let (key, _created) = load_and_decrypt_key(&path, &key::get_encryption_key_password)?;
1361 let crypt_config = CryptConfig::new(key)?;
1362 Some(Arc::new(crypt_config))
1366 let data = file_get_contents(logfile)?;
1368 let blob = match crypt_mode {
1369 CryptMode::None => DataBlob::encode(&data, None, true)?,
1370 CryptMode::Encrypt => {
1371 DataBlob::encode(&data, crypt_config.as_ref().map(Arc::as_ref), true)?
1373 CryptMode::SignOnly => DataBlob::create_signed(
1376 .ok_or_else(|| format_err!("cannot sign without crypt config
"))?
1382 let raw_data = blob.into_inner();
1384 let path = format!("api2
/json
/admin
/datastore
/{}
/upload
-backup
-log
", repo.store());
1387 "backup
-type": snapshot.group().backup_type(),
1388 "backup
-id
": snapshot.group().backup_id(),
1389 "backup
-time
": snapshot.backup_time().timestamp(),
1392 let body = hyper::Body::from(raw_data);
1394 client.upload("application
/octet
-stream
", body, &path, Some(args)).await
1397 const API_METHOD_PRUNE: ApiMethod = ApiMethod::new(
1398 &ApiHandler::Async(&prune),
1400 "Prune a backup repository
.",
1401 &proxmox_backup::add_common_prune_prameters!([
1402 ("dry
-run
", true, &BooleanSchema::new(
1403 "Just show what prune would
do, but
do not delete anything
.")
1405 ("group
", false, &StringSchema::new("Backup group
.").schema()),
1407 ("output
-format
", true, &OUTPUT_FORMAT),
1411 &BooleanSchema::new("Minimal output
- only show removals
.")
1414 ("repository
", true, &REPO_URL_SCHEMA),
1422 _rpcenv: &'a mut dyn RpcEnvironment,
1423 ) -> proxmox::api::ApiFuture<'a> {
1425 prune_async(param).await
1429 async fn prune_async(mut param: Value) -> Result<Value, Error> {
1430 let repo = extract_repository_from_value(¶m)?;
1432 let mut client = connect(repo.host(), repo.user())?;
1434 let path = format!("api2
/json
/admin
/datastore
/{}
/prune
", repo.store());
1436 let group = tools::required_string_param(¶m, "group
")?;
1437 let group: BackupGroup = group.parse()?;
1439 let output_format = get_output_format(¶m);
1441 let quiet = param["quiet
"].as_bool().unwrap_or(false);
1443 param.as_object_mut().unwrap().remove("repository
");
1444 param.as_object_mut().unwrap().remove("group
");
1445 param.as_object_mut().unwrap().remove("output
-format
");
1446 param.as_object_mut().unwrap().remove("quiet
");
1448 param["backup
-type"] = group.backup_type().into();
1449 param["backup
-id
"] = group.backup_id().into();
1451 let mut result = client.post(&path, Some(param)).await?;
1453 record_repository(&repo);
1455 let render_snapshot_path = |_v: &Value, record: &Value| -> Result<String, Error> {
1456 let item: PruneListItem = serde_json::from_value(record.to_owned())?;
1457 let snapshot = BackupDir::new(item.backup_type, item.backup_id, item.backup_time);
1458 Ok(snapshot.relative_path().to_str().unwrap().to_owned())
1461 let render_prune_action = |v: &Value, _record: &Value| -> Result<String, Error> {
1462 Ok(match v.as_bool() {
1463 Some(true) => "keep
",
1464 Some(false) => "remove
",
1469 let options = default_table_format_options()
1470 .sortby("backup
-type", false)
1471 .sortby("backup
-id
", false)
1472 .sortby("backup
-time
", false)
1473 .column(ColumnConfig::new("backup
-id
").renderer(render_snapshot_path).header("snapshot
"))
1474 .column(ColumnConfig::new("backup
-time
").renderer(tools::format::render_epoch).header("date
"))
1475 .column(ColumnConfig::new("keep
").renderer(render_prune_action).header("action
"))
1478 let info = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_PRUNE;
1480 let mut data = result["data
"].take();
1483 let list: Vec<Value> = data.as_array().unwrap().iter().filter(|item| {
1484 item["keep
"].as_bool() == Some(false)
1485 }).map(|v| v.clone()).collect();
1489 format_and_print_result_full(&mut data, info, &output_format, &options);
1498 schema: REPO_URL_SCHEMA,
1502 schema: OUTPUT_FORMAT,
1508 /// Get repository status.
1509 async fn status(param: Value) -> Result<Value, Error> {
1511 let repo = extract_repository_from_value(¶m)?;
1513 let output_format = get_output_format(¶m);
1515 let client = connect(repo.host(), repo.user())?;
1517 let path = format!("api2
/json
/admin
/datastore
/{}
/status
", repo.store());
1519 let mut result = client.get(&path, None).await?;
1520 let mut data = result["data
"].take();
1522 record_repository(&repo);
1524 let render_total_percentage = |v: &Value, record: &Value| -> Result<String, Error> {
1525 let v = v.as_u64().unwrap();
1526 let total = record["total
"].as_u64().unwrap();
1527 let roundup = total/200;
1528 let per = ((v+roundup)*100)/total;
1529 let info = format!(" ({}
%)", per);
1530 Ok(format!("{} {:>8}
", v, info))
1533 let options = default_table_format_options()
1535 .column(ColumnConfig::new("total
").renderer(render_total_percentage))
1536 .column(ColumnConfig::new("used
").renderer(render_total_percentage))
1537 .column(ColumnConfig::new("avail
").renderer(render_total_percentage));
1539 let schema = &proxmox_backup::api2::admin::datastore::API_RETURN_SCHEMA_STATUS;
1541 format_and_print_result_full(&mut data, schema, &output_format, &options);
1546 // like get, but simply ignore errors and return Null instead
1547 async fn try_get(repo: &BackupRepository, url: &str) -> Value {
1549 let fingerprint = std::env::var(ENV_VAR_PBS_FINGERPRINT).ok();
1550 let password = std::env::var(ENV_VAR_PBS_PASSWORD).ok();
1552 let options = HttpClientOptions::new()
1553 .prefix(Some("proxmox
-backup
".to_string()))
1556 .fingerprint(fingerprint)
1557 .fingerprint_cache(true)
1558 .ticket_cache(true);
1560 let client = match HttpClient::new(repo.host(), repo.user(), options) {
1562 _ => return Value::Null,
1565 let mut resp = match client.get(url, None).await {
1567 _ => return Value::Null,
1570 if let Some(map) = resp.as_object_mut() {
1571 if let Some(data) = map.remove("data
") {
1578 fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1579 proxmox_backup::tools::runtime::main(async { complete_backup_group_do(param).await })
1582 async fn complete_backup_group_do(param: &HashMap<String, String>) -> Vec<String> {
1584 let mut result = vec![];
1586 let repo = match extract_repository_from_map(param) {
1591 let path = format!("api2
/json
/admin
/datastore
/{}
/groups
", repo.store());
1593 let data = try_get(&repo, &path).await;
1595 if let Some(list) = data.as_array() {
1597 if let (Some(backup_id), Some(backup_type)) =
1598 (item["backup
-id
"].as_str(), item["backup
-type"].as_str())
1600 result.push(format!("{}
/{}
", backup_type, backup_id));
1608 pub fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1609 proxmox_backup::tools::runtime::main(async { complete_group_or_snapshot_do(arg, param).await })
1612 async fn complete_group_or_snapshot_do(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1614 if arg.matches('/').count() < 2 {
1615 let groups = complete_backup_group_do(param).await;
1616 let mut result = vec![];
1617 for group in groups {
1618 result.push(group.to_string());
1619 result.push(format!("{}
/", group));
1624 complete_backup_snapshot_do(param).await
1627 fn complete_backup_snapshot(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1628 proxmox_backup::tools::runtime::main(async { complete_backup_snapshot_do(param).await })
1631 async fn complete_backup_snapshot_do(param: &HashMap<String, String>) -> Vec<String> {
1633 let mut result = vec![];
1635 let repo = match extract_repository_from_map(param) {
1640 let path = format!("api2
/json
/admin
/datastore
/{}
/snapshots
", repo.store());
1642 let data = try_get(&repo, &path).await;
1644 if let Some(list) = data.as_array() {
1646 if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
1647 (item["backup
-id
"].as_str(), item["backup
-type"].as_str(), item["backup
-time
"].as_i64())
1649 let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
1650 result.push(snapshot.relative_path().to_str().unwrap().to_owned());
1658 fn complete_server_file_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1659 proxmox_backup::tools::runtime::main(async { complete_server_file_name_do(param).await })
1662 async fn complete_server_file_name_do(param: &HashMap<String, String>) -> Vec<String> {
1664 let mut result = vec![];
1666 let repo = match extract_repository_from_map(param) {
1671 let snapshot: BackupDir = match param.get("snapshot
") {
1673 match path.parse() {
1681 let query = tools::json_object_to_query(json!({
1682 "backup
-type": snapshot.group().backup_type(),
1683 "backup
-id
": snapshot.group().backup_id(),
1684 "backup
-time
": snapshot.backup_time().timestamp(),
1687 let path = format!("api2
/json
/admin
/datastore
/{}
/files?{}
", repo.store(), query);
1689 let data = try_get(&repo, &path).await;
1691 if let Some(list) = data.as_array() {
1693 if let Some(filename) = item["filename
"].as_str() {
1694 result.push(filename.to_owned());
1702 fn complete_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1703 complete_server_file_name(arg, param)
1705 .map(|v| tools::format::strip_server_file_expenstion(&v))
1709 pub fn complete_pxar_archive_name(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
1710 complete_server_file_name(arg, param)
1713 let name = tools::format::strip_server_file_expenstion(&v);
1714 if name.ends_with(".pxar
") {
1723 fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
1725 let mut result = vec![];
1729 result.push(size.to_string());
1731 if size > 4096 { break; }
1737 fn master_pubkey_path() -> Result<PathBuf, Error> {
1738 let base = BaseDirectories::with_prefix("proxmox
-backup
")?;
1740 // usually $HOME/.config/proxmox-backup/master-public.pem
1741 let path = base.place_config_file("master
-public
.pem
")?;
1746 use proxmox_backup::client::RemoteChunkReader;
1747 /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
1750 /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
1751 /// so that we can properly access it from multiple threads simultaneously while not issuing
1752 /// duplicate simultaneous reads over http.
1753 pub struct BufferedDynamicReadAt {
1754 inner: Mutex<BufferedDynamicReader<RemoteChunkReader>>,
1757 impl BufferedDynamicReadAt {
1758 fn new(inner: BufferedDynamicReader<RemoteChunkReader>) -> Self {
1760 inner: Mutex::new(inner),
1765 impl ReadAt for BufferedDynamicReadAt {
1766 fn start_read_at<'a>(
1767 self: Pin<&'a Self>,
1771 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1773 MaybeReady::Ready(tokio::task::block_in_place(move || {
1774 let mut reader = self.inner.lock().unwrap();
1775 reader.seek(SeekFrom::Start(offset))?;
1776 Ok(reader.read(buf)?)
1780 fn poll_complete<'a>(
1781 self: Pin<&'a Self>,
1782 _op: ReadAtOperation<'a>,
1783 ) -> MaybeReady<io::Result<usize>, ReadAtOperation<'a>> {
1784 panic!("LocalDynamicReadAt
::start_read_at returned Pending
");
1790 let backup_cmd_def = CliCommand::new(&API_METHOD_CREATE_BACKUP)
1791 .arg_param(&["backupspec
"])
1792 .completion_cb("repository
", complete_repository)
1793 .completion_cb("backupspec
", complete_backup_source)
1794 .completion_cb("keyfile
", tools::complete_file_name)
1795 .completion_cb("chunk
-size
", complete_chunk_size);
1797 let benchmark_cmd_def = CliCommand::new(&API_METHOD_BENCHMARK)
1798 .completion_cb("repository
", complete_repository)
1799 .completion_cb("keyfile
", tools::complete_file_name);
1801 let upload_log_cmd_def = CliCommand::new(&API_METHOD_UPLOAD_LOG)
1802 .arg_param(&["snapshot
", "logfile
"])
1803 .completion_cb("snapshot
", complete_backup_snapshot)
1804 .completion_cb("logfile
", tools::complete_file_name)
1805 .completion_cb("keyfile
", tools::complete_file_name)
1806 .completion_cb("repository
", complete_repository);
1808 let list_cmd_def = CliCommand::new(&API_METHOD_LIST_BACKUP_GROUPS)
1809 .completion_cb("repository
", complete_repository);
1811 let snapshots_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOTS)
1812 .arg_param(&["group
"])
1813 .completion_cb("group
", complete_backup_group)
1814 .completion_cb("repository
", complete_repository);
1816 let forget_cmd_def = CliCommand::new(&API_METHOD_FORGET_SNAPSHOTS)
1817 .arg_param(&["snapshot
"])
1818 .completion_cb("repository
", complete_repository)
1819 .completion_cb("snapshot
", complete_backup_snapshot);
1821 let garbage_collect_cmd_def = CliCommand::new(&API_METHOD_START_GARBAGE_COLLECTION)
1822 .completion_cb("repository
", complete_repository);
1824 let restore_cmd_def = CliCommand::new(&API_METHOD_RESTORE)
1825 .arg_param(&["snapshot
", "archive
-name
", "target
"])
1826 .completion_cb("repository
", complete_repository)
1827 .completion_cb("snapshot
", complete_group_or_snapshot)
1828 .completion_cb("archive
-name
", complete_archive_name)
1829 .completion_cb("target
", tools::complete_file_name);
1831 let files_cmd_def = CliCommand::new(&API_METHOD_LIST_SNAPSHOT_FILES)
1832 .arg_param(&["snapshot
"])
1833 .completion_cb("repository
", complete_repository)
1834 .completion_cb("snapshot
", complete_backup_snapshot);
1836 let prune_cmd_def = CliCommand::new(&API_METHOD_PRUNE)
1837 .arg_param(&["group
"])
1838 .completion_cb("group
", complete_backup_group)
1839 .completion_cb("repository
", complete_repository);
1841 let status_cmd_def = CliCommand::new(&API_METHOD_STATUS)
1842 .completion_cb("repository
", complete_repository);
1844 let login_cmd_def = CliCommand::new(&API_METHOD_API_LOGIN)
1845 .completion_cb("repository
", complete_repository);
1847 let logout_cmd_def = CliCommand::new(&API_METHOD_API_LOGOUT)
1848 .completion_cb("repository
", complete_repository);
1850 let cmd_def = CliCommandMap::new()
1851 .insert("backup
", backup_cmd_def)
1852 .insert("upload
-log
", upload_log_cmd_def)
1853 .insert("forget
", forget_cmd_def)
1854 .insert("garbage
-collect
", garbage_collect_cmd_def)
1855 .insert("list
", list_cmd_def)
1856 .insert("login
", login_cmd_def)
1857 .insert("logout
", logout_cmd_def)
1858 .insert("prune
", prune_cmd_def)
1859 .insert("restore
", restore_cmd_def)
1860 .insert("snapshots
", snapshots_cmd_def)
1861 .insert("files
", files_cmd_def)
1862 .insert("status
", status_cmd_def)
1863 .insert("key
", key::cli())
1864 .insert("mount
", mount_cmd_def())
1865 .insert("catalog
", catalog_mgmt_cli())
1866 .insert("task
", task_mgmt_cli())
1867 .insert("benchmark
", benchmark_cmd_def);
1869 let rpcenv = CliEnvironment::new();
1870 run_cli_command(cmd_def, rpcenv, Some(|future| {
1871 proxmox_backup::tools::runtime::main(future)