]> git.proxmox.com Git - proxmox-backup.git/blob - src/bin/proxmox-backup-client.rs
src/client/http_client.rs: implement post
[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 use chrono::{Local, TimeZone};
6
7 use proxmox_backup::tools;
8 use proxmox_backup::cli::command::*;
9 use proxmox_backup::api_schema::*;
10 use proxmox_backup::api_schema::router::*;
11 use proxmox_backup::client::*;
12 use proxmox_backup::backup::*;
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
22 fn backup_directory(
23 repo: &BackupRepository,
24 body: Body,
25 archive_name: &str,
26 chunk_size: Option<u64>,
27 ) -> Result<(), Error> {
28
29 let client = HttpClient::new(&repo.host, &repo.user);
30
31 let epoch = std::time::SystemTime::now().duration_since(
32 std::time::SystemTime::UNIX_EPOCH)?.as_secs();
33
34 let mut query = url::form_urlencoded::Serializer::new(String::new());
35
36 query
37 .append_pair("archive_name", archive_name)
38 .append_pair("type", "host")
39 .append_pair("id", &tools::nodename())
40 .append_pair("time", &epoch.to_string());
41
42 if let Some(size) = chunk_size {
43 query.append_pair("chunk-size", &size.to_string());
44 }
45
46 let query = query.finish();
47
48 let path = format!("api2/json/admin/datastore/{}/catar?{}", repo.store, query);
49
50 client.upload("application/x-proxmox-backup-catar", body, &path)?;
51
52 Ok(())
53 }
54
55 /****
56 fn backup_image(datastore: &DataStore, file: &std::fs::File, size: usize, target: &str, chunk_size: usize) -> Result<(), Error> {
57
58 let mut target = PathBuf::from(target);
59
60 if let Some(ext) = target.extension() {
61 if ext != "fidx" {
62 bail!("got wrong file extension - expected '.fidx'");
63 }
64 } else {
65 target.set_extension("fidx");
66 }
67
68 let mut index = datastore.create_image_writer(&target, size, chunk_size)?;
69
70 tools::file_chunker(file, chunk_size, |pos, chunk| {
71 index.add_chunk(pos, chunk)?;
72 Ok(true)
73 })?;
74
75 index.close()?; // commit changes
76
77 Ok(())
78 }
79 */
80
81 fn list_backups(
82 param: Value,
83 _info: &ApiMethod,
84 _rpcenv: &mut RpcEnvironment,
85 ) -> Result<Value, Error> {
86
87 let repo_url = tools::required_string_param(&param, "repository")?;
88 let repo = BackupRepository::parse(repo_url)?;
89
90 let client = HttpClient::new(&repo.host, &repo.user);
91
92 let path = format!("api2/json/admin/datastore/{}/backups", repo.store);
93
94 let result = client.get(&path)?;
95
96 // fixme: implement and use output formatter instead ..
97 let list = result["data"].as_array().unwrap();
98
99 for item in list {
100
101 let id = item["backup_id"].as_str(). unwrap();
102 let btype = item["backup_type"].as_str(). unwrap();
103 let epoch = item["backup_time"].as_i64(). unwrap();
104
105 let time_str = Local.timestamp(epoch, 0).format("%c");
106
107 let files = item["files"].as_array().unwrap();
108
109 for file in files {
110 let filename = file.as_str().unwrap();
111 println!("| {} | {} | {} | {}", btype, id, time_str, filename);
112 }
113 }
114
115 //Ok(result)
116 Ok(Value::Null)
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 chunk_size_opt = param["chunk-size"].as_u64().map(|v| v*1024);
133
134 if let Some(size) = chunk_size_opt {
135 verify_chunk_size(size)?;
136 }
137
138 let stat = match nix::sys::stat::stat(filename) {
139 Ok(s) => s,
140 Err(err) => bail!("unable to access '{}' - {}", filename, err),
141 };
142
143 if (stat.st_mode & libc::S_IFDIR) != 0 {
144 println!("Backup directory '{}' to '{:?}'", filename, repo);
145
146 let stream = CaTarBackupStream::open(filename)?;
147
148 let body = Body::wrap_stream(stream);
149
150 backup_directory(&repo, body, target, chunk_size_opt)?;
151
152 } else if (stat.st_mode & (libc::S_IFREG|libc::S_IFBLK)) != 0 {
153 println!("Backup image '{}' to '{:?}'", filename, repo);
154
155 if stat.st_size <= 0 { bail!("got strange file size '{}'", stat.st_size); }
156 let _size = stat.st_size as usize;
157
158 panic!("implement me");
159
160 //backup_image(&datastore, &file, size, &target, chunk_size)?;
161
162 // let idx = datastore.open_image_reader(target)?;
163 // idx.print_info();
164
165 } else {
166 bail!("unsupported file type (expected a directory, file or block device)");
167 }
168
169 //datastore.garbage_collection()?;
170
171 Ok(Value::Null)
172 }
173
174 fn main() {
175
176 let repo_url_schema: Arc<Schema> = Arc::new(
177 StringSchema::new("Repository URL.")
178 .format(BACKUP_REPO_URL.clone())
179 .max_length(256)
180 .into()
181 );
182
183 let create_cmd_def = CliCommand::new(
184 ApiMethod::new(
185 create_backup,
186 ObjectSchema::new("Create backup.")
187 .required("repository", repo_url_schema.clone())
188 .required("filename", StringSchema::new("Source name (file or directory name)"))
189 .required("target", StringSchema::new("Target name."))
190 .optional(
191 "chunk-size",
192 IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
193 .minimum(64)
194 .maximum(4096)
195 .default(4096)
196 )
197 ))
198 .arg_param(vec!["repository", "filename", "target"])
199 .completion_cb("filename", tools::complete_file_name);
200
201 let list_cmd_def = CliCommand::new(
202 ApiMethod::new(
203 list_backups,
204 ObjectSchema::new("List backups.")
205 .required("repository", repo_url_schema.clone())
206 ))
207 .arg_param(vec!["repository"]);
208
209 let cmd_def = CliCommandMap::new()
210 .insert("create".to_owned(), create_cmd_def.into())
211 .insert("list".to_owned(), list_cmd_def.into());
212
213 if let Err(err) = run_cli_command(&cmd_def.into()) {
214 eprintln!("Error: {}", err);
215 if err.downcast::<UsageError>().is_ok() {
216 print_cli_usage();
217 }
218 std::process::exit(-1);
219 }
220
221 }