]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-client.rs: define and use BackupRepository
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
1 extern crate proxmox_backup;
2
3 use failure::*;
4 //use std::os::unix::io::AsRawFd;
5
6 use proxmox_backup::tools;
7 use proxmox_backup::cli::command::*;
8 use proxmox_backup::api::schema::*;
9 use proxmox_backup::api::router::*;
10 use proxmox_backup::client::http_client::*;
11 use proxmox_backup::client::catar_backup_stream::*;
12 //use proxmox_backup::backup::chunk_store::*;
13 //use proxmox_backup::backup::image_index::*;
14 //use proxmox_backup::config::datastore;
15 //use proxmox_backup::catar::encoder::*;
16 //use proxmox_backup::backup::datastore::*;
17
18 use serde_json::{Value};
19 use hyper::Body;
20 use std::sync::Arc;
21 use lazy_static::lazy_static;
22 use regex::Regex;
23
24 lazy_static! {
25 // user@host:datastore
26 pub static ref BACKUP_REPO_URL_REGEX: Regex = Regex::new(r"^(?:(?:([\w@]+)@)?(\w+):)?(\w+)$").unwrap();
27
28 pub static ref BACKUP_REPO_URL: Arc<ApiStringFormat> =
29 ApiStringFormat::Pattern(&BACKUP_REPO_URL_REGEX).into();
30 }
31
32 #[derive(Debug)]
33 pub struct BackupRepository {
34 pub user: String,
35 pub host: String,
36 pub store: String,
37 }
38
39 impl BackupRepository {
40
41 pub fn parse(url: &str) -> Result<Self, Error> {
42
43 let cap = BACKUP_REPO_URL_REGEX.captures(url)
44 .ok_or_else(|| format_err!("unable to parse reepository url '{}'", url))?;
45
46 Ok(BackupRepository {
47 user: cap.get(1).map_or("root@pam", |m| m.as_str()).to_owned(),
48 host: cap.get(2).map_or("localhost", |m| m.as_str()).to_owned(),
49 store: cap[3].to_owned(),
50 })
51 }
52 }
53
54 fn backup_directory(repo: &BackupRepository, body: Body, archive_name: &str) -> Result<(), Error> {
55
56 let client = HttpClient::new(&repo.host);
57
58 let epoch = std::time::SystemTime::now().duration_since(
59 std::time::SystemTime::UNIX_EPOCH)?.as_secs();
60
61 let query = url::form_urlencoded::Serializer::new(String::new())
62 .append_pair("archive_name", archive_name)
63 .append_pair("type", "host")
64 .append_pair("id", &tools::nodename())
65 .append_pair("time", &epoch.to_string())
66 .finish();
67
68 let path = format!("api2/json/admin/datastore/{}/catar?{}", repo.store, query);
69
70 client.upload("application/x-proxmox-backup-catar", body, &path)?;
71
72 Ok(())
73 }
74
75 /****
76 fn backup_image(datastore: &DataStore, file: &std::fs::File, size: usize, target: &str, chunk_size: usize) -> Result<(), Error> {
77
78 let mut target = PathBuf::from(target);
79
80 if let Some(ext) = target.extension() {
81 if ext != "fidx" {
82 bail!("got wrong file extension - expected '.fidx'");
83 }
84 } else {
85 target.set_extension("fidx");
86 }
87
88 let mut index = datastore.create_image_writer(&target, size, chunk_size)?;
89
90 tools::file_chunker(file, chunk_size, |pos, chunk| {
91 index.add_chunk(pos, chunk)?;
92 Ok(true)
93 })?;
94
95 index.close()?; // commit changes
96
97 Ok(())
98 }
99 */
100
101 fn list_backups(
102 param: Value,
103 _info: &ApiMethod,
104 _rpcenv: &mut RpcEnvironment,
105 ) -> Result<Value, Error> {
106
107 let repo_url = tools::required_string_param(&param, "repository")?;
108 let repo = BackupRepository::parse(repo_url)?;
109
110 let client = HttpClient::new(&repo.host);
111
112 let path = format!("api2/json/admin/datastore/{}/backups", repo.store);
113
114 let result = client.get(&path)?;
115
116 Ok(result)
117 }
118
119
120 fn create_backup(
121 param: Value,
122 _info: &ApiMethod,
123 _rpcenv: &mut RpcEnvironment,
124 ) -> Result<Value, Error> {
125
126 let filename = tools::required_string_param(&param, "filename")?;
127 let repo_url = tools::required_string_param(&param, "repository")?;
128 let target = tools::required_string_param(&param, "target")?;
129
130 let repo = BackupRepository::parse(repo_url)?;
131
132 let mut _chunk_size = 4*1024*1024;
133
134 if let Some(size) = param["chunk-size"].as_u64() {
135 static SIZES: [u64; 7] = [64, 128, 256, 512, 1024, 2048, 4096];
136
137 if SIZES.contains(&size) {
138 _chunk_size = (size as usize) * 1024;
139 } else {
140 bail!("Got unsupported chunk size '{}'", size);
141 }
142 }
143
144 let stat = match nix::sys::stat::stat(filename) {
145 Ok(s) => s,
146 Err(err) => bail!("unable to access '{}' - {}", filename, err),
147 };
148
149 if (stat.st_mode & libc::S_IFDIR) != 0 {
150 println!("Backup directory '{}' to '{:?}'", filename, repo);
151
152 let stream = CaTarBackupStream::open(filename)?;
153
154 let body = Body::wrap_stream(stream);
155
156 backup_directory(&repo, body, target)?;
157
158 } else if (stat.st_mode & (libc::S_IFREG|libc::S_IFBLK)) != 0 {
159 println!("Backup image '{}' to '{:?}'", filename, repo);
160
161 if stat.st_size <= 0 { bail!("got strange file size '{}'", stat.st_size); }
162 let _size = stat.st_size as usize;
163
164 panic!("implement me");
165
166 //backup_image(&datastore, &file, size, &target, chunk_size)?;
167
168 // let idx = datastore.open_image_reader(target)?;
169 // idx.print_info();
170
171 } else {
172 bail!("unsupported file type (expected a directory, file or block device)");
173 }
174
175 //datastore.garbage_collection()?;
176
177 Ok(Value::Null)
178 }
179
180 fn main() {
181
182 let repo_url_schema: Arc<Schema> = Arc::new(
183 StringSchema::new("Repository URL.")
184 .format(BACKUP_REPO_URL.clone())
185 .max_length(256)
186 .into()
187 );
188
189 let create_cmd_def = CliCommand::new(
190 ApiMethod::new(
191 create_backup,
192 ObjectSchema::new("Create backup.")
193 .required("repository", repo_url_schema.clone())
194 .required("filename", StringSchema::new("Source name (file or directory name)"))
195 .required("target", StringSchema::new("Target name."))
196 .optional(
197 "chunk-size",
198 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
199 .minimum(64)
200 .maximum(4096)
201 .default(4096)
202 )
203 ))
204 .arg_param(vec!["repository", "filename", "target"])
205 .completion_cb("filename", tools::complete_file_name);
206
207 let list_cmd_def = CliCommand::new(
208 ApiMethod::new(
209 list_backups,
210 ObjectSchema::new("List backups.")
211 .required("repository", repo_url_schema.clone())
212 ))
213 .arg_param(vec!["repository"]);
214
215 let cmd_def = CliCommandMap::new()
216 .insert("create".to_owned(), create_cmd_def.into())
217 .insert("list".to_owned(), list_cmd_def.into());
218
219 if let Err(err) = run_cli_command(&cmd_def.into()) {
220 eprintln!("Error: {}", err);
221 if err.downcast::<UsageError>().is_ok() {
222 print_cli_usage();
223 }
224 std::process::exit(-1);
225 }
226
227 }