]>
Commit | Line | Data |
---|---|---|
597641fd DM |
1 | use failure::*; |
2 | ||
3 | use http::Uri; | |
4 | use hyper::Body; | |
5 | use hyper::client::Client; | |
ba3a60b2 | 6 | use xdg::BaseDirectories; |
dd066d28 | 7 | use chrono::{DateTime, Local, Utc}; |
553610b4 DM |
8 | use std::collections::HashSet; |
9 | use std::sync::{Arc, Mutex}; | |
c2b94534 | 10 | use std::io::Write; |
597641fd | 11 | |
b57cb264 | 12 | use http::{Request, Response}; |
5a2df000 DM |
13 | use http::header::HeaderValue; |
14 | ||
82ab7230 | 15 | use futures::*; |
1fdb4c6f | 16 | use futures::stream::Stream; |
82ab7230 DM |
17 | use std::sync::atomic::{AtomicUsize, Ordering}; |
18 | use tokio::sync::mpsc; | |
6d1f61b2 | 19 | use openssl::ssl::{SslConnector, SslMethod}; |
1fdb4c6f | 20 | |
ba3a60b2 | 21 | use serde_json::{json, Value}; |
0dffe3f9 | 22 | use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; |
1fdb4c6f | 23 | |
5a2df000 | 24 | use crate::tools::{self, BroadcastFuture, tty}; |
cb4426b3 | 25 | use crate::tools::futures::{cancellable, Canceller}; |
e3dbd41b | 26 | use super::pipe_to_stream::*; |
aa1b2e04 DM |
27 | use super::merge_known_chunks::*; |
28 | ||
986bef16 DM |
29 | use crate::backup::*; |
30 | ||
5a2df000 DM |
31 | #[derive(Clone)] |
32 | struct AuthInfo { | |
33 | username: String, | |
34 | ticket: String, | |
35 | token: String, | |
36 | } | |
56458d97 | 37 | |
151c6ce2 | 38 | /// HTTP(S) API client |
597641fd | 39 | pub struct HttpClient { |
6d1f61b2 | 40 | client: Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, |
597641fd | 41 | server: String, |
5a2df000 | 42 | auth: BroadcastFuture<AuthInfo>, |
597641fd DM |
43 | } |
44 | ||
ba3a60b2 DM |
45 | fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> { |
46 | ||
47 | let base = BaseDirectories::with_prefix("proxmox-backup")?; | |
48 | ||
49 | // usually /run/user/<uid>/... | |
50 | let path = base.place_runtime_file("tickets")?; | |
51 | ||
52 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600); | |
53 | ||
49cf9f3d | 54 | let mut data = tools::file_get_json(&path, Some(json!({})))?; |
ba3a60b2 DM |
55 | |
56 | let now = Utc::now().timestamp(); | |
57 | ||
58 | data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token}); | |
59 | ||
60 | let mut new_data = json!({}); | |
61 | ||
62 | let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60; | |
63 | ||
64 | let empty = serde_json::map::Map::new(); | |
65 | for (server, info) in data.as_object().unwrap_or(&empty) { | |
66 | for (_user, uinfo) in info.as_object().unwrap_or(&empty) { | |
67 | if let Some(timestamp) = uinfo["timestamp"].as_i64() { | |
68 | let age = now - timestamp; | |
69 | if age < ticket_lifetime { | |
70 | new_data[server][username] = uinfo.clone(); | |
71 | } | |
72 | } | |
73 | } | |
74 | } | |
75 | ||
76 | tools::file_set_contents(path, new_data.to_string().as_bytes(), Some(mode))?; | |
77 | ||
78 | Ok(()) | |
79 | } | |
80 | ||
81 | fn load_ticket_info(server: &str, username: &str) -> Option<(String, String)> { | |
82 | let base = match BaseDirectories::with_prefix("proxmox-backup") { | |
83 | Ok(b) => b, | |
84 | _ => return None, | |
85 | }; | |
86 | ||
87 | // usually /run/user/<uid>/... | |
88 | let path = match base.place_runtime_file("tickets") { | |
89 | Ok(p) => p, | |
90 | _ => return None, | |
91 | }; | |
92 | ||
49cf9f3d DM |
93 | let data = match tools::file_get_json(&path, None) { |
94 | Ok(v) => v, | |
95 | _ => return None, | |
96 | }; | |
ba3a60b2 DM |
97 | |
98 | let now = Utc::now().timestamp(); | |
99 | ||
100 | let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60; | |
101 | ||
102 | if let Some(uinfo) = data[server][username].as_object() { | |
103 | if let Some(timestamp) = uinfo["timestamp"].as_i64() { | |
104 | let age = now - timestamp; | |
105 | if age < ticket_lifetime { | |
106 | let ticket = match uinfo["ticket"].as_str() { | |
107 | Some(t) => t, | |
108 | None => return None, | |
109 | }; | |
110 | let token = match uinfo["token"].as_str() { | |
111 | Some(t) => t, | |
112 | None => return None, | |
21ea0158 | 113 | }; |
ba3a60b2 DM |
114 | return Some((ticket.to_owned(), token.to_owned())); |
115 | } | |
116 | } | |
117 | } | |
118 | ||
119 | None | |
120 | } | |
121 | ||
597641fd DM |
122 | impl HttpClient { |
123 | ||
45cdce06 | 124 | pub fn new(server: &str, username: &str) -> Result<Self, Error> { |
5a2df000 | 125 | let client = Self::build_client(); |
5a2df000 | 126 | |
45cdce06 DM |
127 | let password = if let Some((ticket, _token)) = load_ticket_info(server, username) { |
128 | ticket | |
129 | } else { | |
130 | Self::get_password(&username)? | |
131 | }; | |
132 | ||
133 | let login = Self::credentials(client.clone(), server.to_owned(), username.to_owned(), password); | |
134 | ||
135 | Ok(Self { | |
5a2df000 | 136 | client, |
597641fd | 137 | server: String::from(server), |
5a2df000 | 138 | auth: BroadcastFuture::new(login), |
45cdce06 | 139 | }) |
597641fd DM |
140 | } |
141 | ||
5a2df000 | 142 | fn get_password(_username: &str) -> Result<String, Error> { |
56458d97 WB |
143 | use std::env::VarError::*; |
144 | match std::env::var("PBS_PASSWORD") { | |
145 | Ok(p) => return Ok(p), | |
146 | Err(NotUnicode(_)) => bail!("PBS_PASSWORD contains bad characters"), | |
147 | Err(NotPresent) => { | |
148 | // Try another method | |
149 | } | |
150 | } | |
151 | ||
152 | // If we're on a TTY, query the user for a password | |
153 | if tty::stdin_isatty() { | |
154 | return Ok(String::from_utf8(tty::read_password("Password: ")?)?); | |
155 | } | |
156 | ||
157 | bail!("no password input mechanism available"); | |
158 | } | |
159 | ||
6d1f61b2 DM |
160 | fn build_client() -> Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>> { |
161 | ||
162 | let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap(); | |
163 | ||
164 | ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE); // fixme! | |
165 | ||
4a3f6517 | 166 | let mut httpc = hyper::client::HttpConnector::new(1); |
fcf5dea5 | 167 | httpc.set_nodelay(true); // important for h2 download performance! |
8fad30a4 | 168 | httpc.set_recv_buf_size(Some(1024*1024)); //important for h2 download performance! |
4a3f6517 | 169 | httpc.enforce_http(false); // we want https... |
6d1f61b2 DM |
170 | |
171 | let https = hyper_openssl::HttpsConnector::with_connector(httpc, ssl_connector_builder).unwrap(); | |
172 | ||
adec8ea2 DM |
173 | Client::builder() |
174 | //.http2_initial_stream_window_size( (1 << 31) - 2) | |
175 | //.http2_initial_connection_window_size( (1 << 31) - 2) | |
176 | .build::<_, Body>(https) | |
a6b75513 DM |
177 | } |
178 | ||
5a2df000 | 179 | pub fn request(&self, mut req: Request<Body>) -> impl Future<Item=Value, Error=Error> { |
597641fd | 180 | |
5a2df000 | 181 | let login = self.auth.listen(); |
597641fd | 182 | |
5a2df000 | 183 | let client = self.client.clone(); |
597641fd | 184 | |
5a2df000 | 185 | login.and_then(move |auth| { |
597641fd | 186 | |
5a2df000 DM |
187 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
188 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
189 | req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap()); | |
597641fd | 190 | |
5a2df000 | 191 | let request = Self::api_request(client, req); |
597641fd | 192 | |
5a2df000 DM |
193 | request |
194 | }) | |
1fdb4c6f DM |
195 | } |
196 | ||
9e391bb7 | 197 | pub fn get(&self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
a6b75513 | 198 | |
9e391bb7 | 199 | let req = Self::request_builder(&self.server, "GET", path, data).unwrap(); |
5a2df000 | 200 | self.request(req) |
a6b75513 DM |
201 | } |
202 | ||
9e391bb7 | 203 | pub fn delete(&mut self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
a6b75513 | 204 | |
9e391bb7 | 205 | let req = Self::request_builder(&self.server, "DELETE", path, data).unwrap(); |
5a2df000 | 206 | self.request(req) |
a6b75513 DM |
207 | } |
208 | ||
5a2df000 | 209 | pub fn post(&mut self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
024f11bb | 210 | |
5a2df000 DM |
211 | let req = Self::request_builder(&self.server, "POST", path, data).unwrap(); |
212 | self.request(req) | |
024f11bb DM |
213 | } |
214 | ||
c2b94534 | 215 | pub fn download<W: Write>(&mut self, path: &str, output: W) -> impl Future<Item=W, Error=Error> { |
024f11bb | 216 | |
5a2df000 | 217 | let mut req = Self::request_builder(&self.server, "GET", path, None).unwrap(); |
024f11bb | 218 | |
5a2df000 | 219 | let login = self.auth.listen(); |
024f11bb | 220 | |
5a2df000 | 221 | let client = self.client.clone(); |
1fdb4c6f | 222 | |
5a2df000 | 223 | login.and_then(move |auth| { |
81da38c1 | 224 | |
5a2df000 DM |
225 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); |
226 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
6f62c924 | 227 | |
5a2df000 DM |
228 | client.request(req) |
229 | .map_err(Error::from) | |
230 | .and_then(|resp| { | |
81820b0d DM |
231 | let status = resp.status(); |
232 | if !status.is_success() { | |
233 | future::Either::A( | |
234 | HttpClient::api_response(resp) | |
235 | .and_then(|_| { bail!("unknown error"); }) | |
236 | ) | |
237 | } else { | |
238 | future::Either::B( | |
239 | resp.into_body() | |
240 | .map_err(Error::from) | |
c2b94534 DM |
241 | .fold(output, move |mut acc, chunk| { |
242 | acc.write_all(&chunk)?; | |
243 | Ok::<_, Error>(acc) | |
81820b0d DM |
244 | }) |
245 | ) | |
246 | } | |
5a2df000 DM |
247 | }) |
248 | }) | |
6f62c924 DM |
249 | } |
250 | ||
5a2df000 | 251 | pub fn upload(&mut self, content_type: &str, body: Body, path: &str) -> impl Future<Item=Value, Error=Error> { |
81da38c1 DM |
252 | |
253 | let path = path.trim_matches('/'); | |
5a2df000 | 254 | let url: Uri = format!("https://{}:8007/{}", &self.server, path).parse().unwrap(); |
81da38c1 | 255 | |
5a2df000 | 256 | let req = Request::builder() |
81da38c1 DM |
257 | .method("POST") |
258 | .uri(url) | |
259 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
260 | .header("Content-Type", content_type) |
261 | .body(body).unwrap(); | |
81da38c1 | 262 | |
5a2df000 | 263 | self.request(req) |
1fdb4c6f DM |
264 | } |
265 | ||
6ab34afa DM |
266 | pub fn start_backup( |
267 | &self, | |
268 | datastore: &str, | |
269 | backup_type: &str, | |
270 | backup_id: &str, | |
39e60bd6 | 271 | debug: bool, |
6ab34afa | 272 | ) -> impl Future<Item=BackupClient, Error=Error> { |
cf639a47 | 273 | |
7773ccc1 | 274 | let param = json!({"backup-type": backup_type, "backup-id": backup_id, "store": datastore, "debug": debug}); |
fb047083 | 275 | let req = Self::request_builder(&self.server, "GET", "/api2/json/backup", Some(param)).unwrap(); |
cf639a47 | 276 | |
fb047083 DM |
277 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_PROTOCOL_ID_V1!())) |
278 | .map(|(h2, canceller)| BackupClient::new(h2, canceller)) | |
279 | } | |
280 | ||
dd066d28 DM |
281 | pub fn start_backup_reader( |
282 | &self, | |
283 | datastore: &str, | |
284 | backup_type: &str, | |
285 | backup_id: &str, | |
286 | backup_time: DateTime<Local>, | |
287 | debug: bool, | |
288 | ) -> impl Future<Item=BackupReader, Error=Error> { | |
289 | ||
290 | let param = json!({ | |
291 | "backup-type": backup_type, | |
292 | "backup-id": backup_id, | |
293 | "backup-time": backup_time.timestamp(), | |
294 | "store": datastore, | |
295 | "debug": debug, | |
296 | }); | |
297 | let req = Self::request_builder(&self.server, "GET", "/api2/json/reader", Some(param)).unwrap(); | |
298 | ||
299 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())) | |
300 | .map(|(h2, canceller)| BackupReader::new(h2, canceller)) | |
301 | } | |
302 | ||
fb047083 DM |
303 | pub fn start_h2_connection( |
304 | &self, | |
305 | mut req: Request<Body>, | |
306 | protocol_name: String, | |
307 | ) -> impl Future<Item=(H2Client, Canceller), Error=Error> { | |
cf639a47 | 308 | |
fb047083 | 309 | let login = self.auth.listen(); |
cf639a47 DM |
310 | let client = self.client.clone(); |
311 | ||
312 | login.and_then(move |auth| { | |
313 | ||
314 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); | |
315 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
fb047083 | 316 | req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap()); |
cf639a47 DM |
317 | |
318 | client.request(req) | |
319 | .map_err(Error::from) | |
320 | .and_then(|resp| { | |
321 | ||
322 | let status = resp.status(); | |
323 | if status != http::StatusCode::SWITCHING_PROTOCOLS { | |
9af37c8f DM |
324 | future::Either::A(Self::api_response(resp).and_then(|_| { bail!("unknown error"); })) |
325 | } else { | |
326 | future::Either::B(resp.into_body().on_upgrade().map_err(Error::from)) | |
cf639a47 | 327 | } |
cf639a47 | 328 | }) |
cf639a47 | 329 | .and_then(|upgraded| { |
a2b29b68 | 330 | let max_window_size = (1 << 31) - 2; |
fcf5dea5 DM |
331 | |
332 | h2::client::Builder::new() | |
a2b29b68 DM |
333 | .initial_connection_window_size(max_window_size) |
334 | .initial_window_size(max_window_size) | |
fcf5dea5 | 335 | .max_frame_size(4*1024*1024) |
fcf5dea5 DM |
336 | .handshake(upgraded) |
337 | .map_err(Error::from) | |
cf639a47 DM |
338 | }) |
339 | .and_then(|(h2, connection)| { | |
340 | let connection = connection | |
341 | .map_err(|_| panic!("HTTP/2.0 connection failed")); | |
342 | ||
cb4426b3 WB |
343 | let (connection, canceller) = cancellable(connection)?; |
344 | // A cancellable future returns an Option which is None when cancelled and | |
345 | // Some when it finished instead, since we don't care about the return type we | |
346 | // need to map it away: | |
347 | let connection = connection.map(|_| ()); | |
348 | ||
cf639a47 DM |
349 | // Spawn a new task to drive the connection state |
350 | hyper::rt::spawn(connection); | |
351 | ||
352 | // Wait until the `SendRequest` handle has available capacity. | |
cb4426b3 | 353 | Ok(h2.ready() |
fb047083 DM |
354 | .map(move |c| (H2Client::new(c), canceller)) |
355 | .map_err(Error::from)) | |
cf639a47 | 356 | }) |
cb4426b3 | 357 | .flatten() |
cf639a47 DM |
358 | }) |
359 | } | |
360 | ||
5a2df000 | 361 | fn credentials( |
6d1f61b2 | 362 | client: Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, |
45cdce06 DM |
363 | server: String, |
364 | username: String, | |
365 | password: String, | |
dd5495d6 | 366 | ) -> Box<dyn Future<Item=AuthInfo, Error=Error> + Send> { |
0ffbccce | 367 | |
45cdce06 | 368 | let server2 = server.clone(); |
0ffbccce | 369 | |
5a2df000 | 370 | let create_request = futures::future::lazy(move || { |
45cdce06 | 371 | let data = json!({ "username": username, "password": password }); |
5a2df000 | 372 | let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap(); |
45cdce06 | 373 | Self::api_request(client, req) |
5a2df000 | 374 | }); |
0dffe3f9 | 375 | |
5a2df000 DM |
376 | let login_future = create_request |
377 | .and_then(move |cred| { | |
378 | let auth = AuthInfo { | |
379 | username: cred["data"]["username"].as_str().unwrap().to_owned(), | |
380 | ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(), | |
381 | token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(), | |
382 | }; | |
0dffe3f9 | 383 | |
5a2df000 | 384 | let _ = store_ticket_info(&server2, &auth.username, &auth.ticket, &auth.token); |
0dffe3f9 | 385 | |
5a2df000 DM |
386 | Ok(auth) |
387 | }); | |
0dffe3f9 | 388 | |
5a2df000 | 389 | Box::new(login_future) |
ba3a60b2 DM |
390 | } |
391 | ||
d2c48afc DM |
392 | fn api_response(response: Response<Body>) -> impl Future<Item=Value, Error=Error> { |
393 | ||
394 | let status = response.status(); | |
395 | ||
396 | response | |
397 | .into_body() | |
398 | .concat2() | |
399 | .map_err(Error::from) | |
400 | .and_then(move |data| { | |
401 | ||
402 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
403 | if status.is_success() { | |
404 | if text.len() > 0 { | |
405 | let value: Value = serde_json::from_str(&text)?; | |
406 | Ok(value) | |
407 | } else { | |
408 | Ok(Value::Null) | |
409 | } | |
410 | } else { | |
411 | bail!("HTTP Error {}: {}", status, text); | |
412 | } | |
413 | }) | |
414 | } | |
415 | ||
5a2df000 | 416 | fn api_request( |
6d1f61b2 | 417 | client: Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, |
5a2df000 DM |
418 | req: Request<Body> |
419 | ) -> impl Future<Item=Value, Error=Error> { | |
ba3a60b2 | 420 | |
5a2df000 DM |
421 | client.request(req) |
422 | .map_err(Error::from) | |
d2c48afc | 423 | .and_then(Self::api_response) |
0dffe3f9 DM |
424 | } |
425 | ||
5a2df000 | 426 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> { |
591f570b | 427 | let path = path.trim_matches('/'); |
5a2df000 DM |
428 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; |
429 | ||
430 | if let Some(data) = data { | |
431 | if method == "POST" { | |
432 | let request = Request::builder() | |
433 | .method(method) | |
434 | .uri(url) | |
435 | .header("User-Agent", "proxmox-backup-client/1.0") | |
436 | .header(hyper::header::CONTENT_TYPE, "application/json") | |
437 | .body(Body::from(data.to_string()))?; | |
438 | return Ok(request); | |
439 | } else { | |
9e391bb7 DM |
440 | let query = tools::json_object_to_query(data)?; |
441 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; | |
442 | let request = Request::builder() | |
443 | .method(method) | |
444 | .uri(url) | |
445 | .header("User-Agent", "proxmox-backup-client/1.0") | |
446 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
447 | .body(Body::empty())?; | |
448 | return Ok(request); | |
5a2df000 | 449 | } |
5a2df000 | 450 | } |
0dffe3f9 | 451 | |
1fdb4c6f | 452 | let request = Request::builder() |
5a2df000 | 453 | .method(method) |
1fdb4c6f DM |
454 | .uri(url) |
455 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
456 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") |
457 | .body(Body::empty())?; | |
1fdb4c6f | 458 | |
5a2df000 | 459 | Ok(request) |
597641fd DM |
460 | } |
461 | } | |
b57cb264 | 462 | |
dd066d28 | 463 | |
fcf5dea5 | 464 | #[derive(Clone)] |
dd066d28 DM |
465 | pub struct BackupReader { |
466 | h2: H2Client, | |
467 | canceller: Option<Canceller>, | |
468 | } | |
469 | ||
470 | impl Drop for BackupReader { | |
471 | ||
472 | fn drop(&mut self) { | |
473 | if let Some(canceller) = self.canceller.take() { | |
474 | canceller.cancel(); | |
475 | } | |
476 | } | |
477 | } | |
478 | ||
479 | impl BackupReader { | |
480 | ||
481 | pub fn new(h2: H2Client, canceller: Canceller) -> Self { | |
482 | Self { h2, canceller: Some(canceller) } | |
483 | } | |
484 | ||
485 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
486 | self.h2.get(path, param) | |
487 | } | |
488 | ||
489 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
490 | self.h2.put(path, param) | |
491 | } | |
492 | ||
493 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
494 | self.h2.post(path, param) | |
495 | } | |
496 | ||
497 | pub fn download<W: Write>( | |
498 | &self, | |
499 | file_name: &str, | |
500 | output: W, | |
501 | ) -> impl Future<Item=W, Error=Error> { | |
502 | let path = "download"; | |
503 | let param = json!({ "file-name": file_name }); | |
504 | self.h2.download(path, Some(param), output) | |
505 | } | |
506 | ||
17243003 DM |
507 | pub fn speedtest<W: Write>( |
508 | &self, | |
509 | output: W, | |
510 | ) -> impl Future<Item=W, Error=Error> { | |
511 | self.h2.download("speedtest", None, output) | |
512 | } | |
513 | ||
fcf5dea5 DM |
514 | pub fn download_chunk<W: Write>( |
515 | &self, | |
516 | digest: &[u8; 32], | |
517 | output: W, | |
518 | ) -> impl Future<Item=W, Error=Error> { | |
519 | let path = "chunk"; | |
520 | let param = json!({ "digest": proxmox::tools::digest_to_hex(digest) }); | |
521 | self.h2.download(path, Some(param), output) | |
522 | } | |
523 | ||
dd066d28 DM |
524 | pub fn force_close(mut self) { |
525 | if let Some(canceller) = self.canceller.take() { | |
526 | canceller.cancel(); | |
527 | } | |
528 | } | |
529 | } | |
530 | ||
6ab34afa | 531 | pub struct BackupClient { |
9af37c8f | 532 | h2: H2Client, |
cb4426b3 | 533 | canceller: Option<Canceller>, |
b57cb264 DM |
534 | } |
535 | ||
dd066d28 DM |
536 | impl Drop for BackupClient { |
537 | ||
538 | fn drop(&mut self) { | |
539 | if let Some(canceller) = self.canceller.take() { | |
540 | canceller.cancel(); | |
541 | } | |
542 | } | |
543 | } | |
91320f08 | 544 | |
6ab34afa | 545 | impl BackupClient { |
b57cb264 | 546 | |
fb047083 DM |
547 | pub fn new(h2: H2Client, canceller: Canceller) -> Self { |
548 | Self { h2, canceller: Some(canceller) } | |
cb4426b3 WB |
549 | } |
550 | ||
b57cb264 | 551 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 552 | self.h2.get(path, param) |
b57cb264 DM |
553 | } |
554 | ||
82ab7230 | 555 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 556 | self.h2.put(path, param) |
82ab7230 DM |
557 | } |
558 | ||
b57cb264 | 559 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 560 | self.h2.post(path, param) |
97f22ce5 DM |
561 | } |
562 | ||
4247fccb DM |
563 | pub fn finish(mut self) -> impl Future<Item=(), Error=Error> { |
564 | let canceler = self.canceller.take().unwrap(); | |
565 | self.h2.clone().post("finish", None).map(move |_| { | |
566 | canceler.cancel(); | |
567 | () | |
568 | }) | |
569 | } | |
570 | ||
571 | pub fn force_close(mut self) { | |
dd066d28 DM |
572 | if let Some(canceller) = self.canceller.take() { |
573 | canceller.cancel(); | |
574 | } | |
d6f204ed DM |
575 | } |
576 | ||
9f46c7de DM |
577 | pub fn upload_blob_from_data( |
578 | &self, | |
579 | data: Vec<u8>, | |
580 | file_name: &str, | |
581 | crypt_config: Option<Arc<CryptConfig>>, | |
582 | compress: bool, | |
583 | ) -> impl Future<Item=(), Error=Error> { | |
584 | ||
585 | let h2 = self.h2.clone(); | |
586 | let file_name = file_name.to_owned(); | |
587 | ||
588 | futures::future::ok(()) | |
589 | .and_then(move |_| { | |
590 | let blob = if let Some(ref crypt_config) = crypt_config { | |
591 | DataBlob::encode(&data, Some(crypt_config), compress)? | |
592 | } else { | |
593 | DataBlob::encode(&data, None, compress)? | |
594 | }; | |
595 | ||
596 | let raw_data = blob.into_inner(); | |
597 | Ok(raw_data) | |
598 | }) | |
599 | .and_then(move |raw_data| { | |
600 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
601 | h2.upload("blob", Some(param), raw_data) | |
602 | .map(|_| {}) | |
603 | }) | |
604 | } | |
605 | ||
606 | pub fn upload_blob_from_file<P: AsRef<std::path::Path>>( | |
39d6846e | 607 | &self, |
ec8a9bb9 | 608 | src_path: P, |
39d6846e | 609 | file_name: &str, |
cb08ac3e DM |
610 | crypt_config: Option<Arc<CryptConfig>>, |
611 | compress: bool, | |
ec8a9bb9 | 612 | ) -> impl Future<Item=(), Error=Error> { |
39d6846e DM |
613 | |
614 | let h2 = self.h2.clone(); | |
615 | let file_name = file_name.to_owned(); | |
ec8a9bb9 | 616 | let src_path = src_path.as_ref().to_owned(); |
39d6846e | 617 | |
ef39bf95 DM |
618 | let task = tokio::fs::File::open(src_path.clone()) |
619 | .map_err(move |err| format_err!("unable to open file {:?} - {}", src_path, err)) | |
cb08ac3e | 620 | .and_then(move |file| { |
39d6846e DM |
621 | let contents = vec![]; |
622 | tokio::io::read_to_end(file, contents) | |
623 | .map_err(Error::from) | |
624 | .and_then(move |(_, contents)| { | |
cb08ac3e DM |
625 | let blob = if let Some(ref crypt_config) = crypt_config { |
626 | DataBlob::encode(&contents, Some(crypt_config), compress)? | |
627 | } else { | |
628 | DataBlob::encode(&contents, None, compress)? | |
629 | }; | |
630 | let raw_data = blob.into_inner(); | |
631 | Ok(raw_data) | |
632 | }) | |
633 | .and_then(move |raw_data| { | |
634 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
635 | h2.upload("blob", Some(param), raw_data) | |
39d6846e DM |
636 | .map(|_| {}) |
637 | }) | |
638 | }); | |
639 | ||
640 | task | |
641 | } | |
642 | ||
a42fa400 | 643 | pub fn upload_stream( |
d6f204ed DM |
644 | &self, |
645 | archive_name: &str, | |
646 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, | |
a42fa400 DM |
647 | prefix: &str, |
648 | fixed_size: Option<u64>, | |
f98ac774 | 649 | crypt_config: Option<Arc<CryptConfig>>, |
d6f204ed DM |
650 | ) -> impl Future<Item=(), Error=Error> { |
651 | ||
652 | let known_chunks = Arc::new(Mutex::new(HashSet::new())); | |
653 | ||
654 | let h2 = self.h2.clone(); | |
655 | let h2_2 = self.h2.clone(); | |
656 | let h2_3 = self.h2.clone(); | |
657 | let h2_4 = self.h2.clone(); | |
658 | ||
a42fa400 DM |
659 | let mut param = json!({ "archive-name": archive_name }); |
660 | if let Some(size) = fixed_size { | |
661 | param["size"] = size.into(); | |
662 | } | |
663 | ||
664 | let index_path = format!("{}_index", prefix); | |
a42fa400 | 665 | let close_path = format!("{}_close", prefix); |
d6f204ed | 666 | |
642322b4 DM |
667 | let prefix = prefix.to_owned(); |
668 | ||
a42fa400 | 669 | Self::download_chunk_list(h2, &index_path, archive_name, known_chunks.clone()) |
d6f204ed | 670 | .and_then(move |_| { |
a42fa400 | 671 | h2_2.post(&index_path, Some(param)) |
d6f204ed DM |
672 | }) |
673 | .and_then(move |res| { | |
674 | let wid = res.as_u64().unwrap(); | |
f98ac774 | 675 | Self::upload_chunk_info_stream(h2_3, wid, stream, &prefix, known_chunks.clone(), crypt_config) |
417cb073 | 676 | .and_then(move |(chunk_count, size, _speed)| { |
8bea85b4 DM |
677 | let param = json!({ |
678 | "wid": wid , | |
679 | "chunk-count": chunk_count, | |
680 | "size": size, | |
681 | }); | |
a42fa400 DM |
682 | h2_4.post(&close_path, Some(param)) |
683 | }) | |
d6f204ed DM |
684 | .map(|_| ()) |
685 | }) | |
686 | } | |
687 | ||
6ab34afa | 688 | fn response_queue() -> ( |
82ab7230 DM |
689 | mpsc::Sender<h2::client::ResponseFuture>, |
690 | sync::oneshot::Receiver<Result<(), Error>> | |
691 | ) { | |
692 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100); | |
693 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); | |
adec8ea2 | 694 | |
82ab7230 DM |
695 | hyper::rt::spawn( |
696 | verify_queue_rx | |
697 | .map_err(Error::from) | |
698 | .for_each(|response: h2::client::ResponseFuture| { | |
699 | response | |
700 | .map_err(Error::from) | |
9af37c8f | 701 | .and_then(H2Client::h2api_response) |
82ab7230 DM |
702 | .and_then(|result| { |
703 | println!("RESPONSE: {:?}", result); | |
704 | Ok(()) | |
705 | }) | |
706 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
707 | }) | |
708 | .then(|result| | |
709 | verify_result_tx.send(result) | |
710 | ) | |
711 | .map_err(|_| { /* ignore closed channel */ }) | |
712 | ); | |
adec8ea2 | 713 | |
82ab7230 DM |
714 | (verify_queue_tx, verify_result_rx) |
715 | } | |
716 | ||
642322b4 | 717 | fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> ( |
174ad378 | 718 | mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>, |
05cba08c DM |
719 | sync::oneshot::Receiver<Result<(), Error>> |
720 | ) { | |
771953f9 | 721 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64); |
05cba08c DM |
722 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); |
723 | ||
724 | let h2_2 = h2.clone(); | |
725 | ||
726 | hyper::rt::spawn( | |
727 | verify_queue_rx | |
728 | .map_err(Error::from) | |
174ad378 DM |
729 | .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| { |
730 | match (response, merged_chunk_info) { | |
731 | (Some(response), MergedChunkInfo::Known(list)) => { | |
05cba08c | 732 | future::Either::A( |
174ad378 DM |
733 | response |
734 | .map_err(Error::from) | |
735 | .and_then(H2Client::h2api_response) | |
771953f9 | 736 | .and_then(move |_result| { |
174ad378 | 737 | Ok(MergedChunkInfo::Known(list)) |
05cba08c | 738 | }) |
05cba08c DM |
739 | ) |
740 | } | |
174ad378 | 741 | (None, MergedChunkInfo::Known(list)) => { |
05cba08c DM |
742 | future::Either::B(future::ok(MergedChunkInfo::Known(list))) |
743 | } | |
174ad378 | 744 | _ => unreachable!(), |
05cba08c DM |
745 | } |
746 | }) | |
62436222 | 747 | .merge_known_chunks() |
05cba08c DM |
748 | .and_then(move |merged_chunk_info| { |
749 | match merged_chunk_info { | |
750 | MergedChunkInfo::Known(chunk_list) => { | |
751 | let mut digest_list = vec![]; | |
752 | let mut offset_list = vec![]; | |
753 | for (offset, digest) in chunk_list { | |
bffd40d6 DM |
754 | //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset); |
755 | digest_list.push(proxmox::tools::digest_to_hex(&digest)); | |
05cba08c DM |
756 | offset_list.push(offset); |
757 | } | |
758 | println!("append chunks list len ({})", digest_list.len()); | |
759 | let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }); | |
a42fa400 | 760 | let mut request = H2Client::request_builder("localhost", "PUT", &path, None).unwrap(); |
05cba08c DM |
761 | request.headers_mut().insert(hyper::header::CONTENT_TYPE, HeaderValue::from_static("application/json")); |
762 | let param_data = bytes::Bytes::from(param.to_string().as_bytes()); | |
763 | let upload_data = Some(param_data); | |
764 | h2_2.send_request(request, upload_data) | |
765 | .and_then(move |response| { | |
766 | response | |
767 | .map_err(Error::from) | |
768 | .and_then(H2Client::h2api_response) | |
769 | .and_then(|_| Ok(())) | |
770 | }) | |
771 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
772 | } | |
773 | _ => unreachable!(), | |
774 | } | |
775 | }) | |
776 | .for_each(|_| Ok(())) | |
777 | .then(|result| | |
778 | verify_result_tx.send(result) | |
779 | ) | |
780 | .map_err(|_| { /* ignore closed channel */ }) | |
781 | ); | |
782 | ||
783 | (verify_queue_tx, verify_result_rx) | |
784 | } | |
785 | ||
6ab34afa | 786 | fn download_chunk_list( |
9af37c8f | 787 | h2: H2Client, |
553610b4 DM |
788 | path: &str, |
789 | archive_name: &str, | |
790 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, | |
791 | ) -> impl Future<Item=(), Error=Error> { | |
792 | ||
793 | let param = json!({ "archive-name": archive_name }); | |
9af37c8f | 794 | let request = H2Client::request_builder("localhost", "GET", path, Some(param)).unwrap(); |
553610b4 | 795 | |
9af37c8f | 796 | h2.send_request(request, None) |
553610b4 DM |
797 | .and_then(move |response| { |
798 | response | |
799 | .map_err(Error::from) | |
800 | .and_then(move |resp| { | |
801 | let status = resp.status(); | |
7dd1bcac | 802 | |
553610b4 | 803 | if !status.is_success() { |
7dd1bcac DM |
804 | future::Either::A(H2Client::h2api_response(resp).and_then(|_| { bail!("unknown error"); })) |
805 | } else { | |
806 | future::Either::B(future::ok(resp.into_body())) | |
553610b4 | 807 | } |
553610b4 DM |
808 | }) |
809 | .and_then(move |mut body| { | |
810 | ||
811 | let mut release_capacity = body.release_capacity().clone(); | |
812 | ||
986bef16 | 813 | DigestListDecoder::new(body.map_err(Error::from)) |
553610b4 DM |
814 | .for_each(move |chunk| { |
815 | let _ = release_capacity.release_capacity(chunk.len()); | |
bffd40d6 | 816 | println!("GOT DOWNLOAD {}", proxmox::tools::digest_to_hex(&chunk)); |
553610b4 DM |
817 | known_chunks.lock().unwrap().insert(chunk); |
818 | Ok(()) | |
819 | }) | |
820 | }) | |
821 | }) | |
822 | } | |
823 | ||
a42fa400 | 824 | fn upload_chunk_info_stream( |
9af37c8f | 825 | h2: H2Client, |
82ab7230 | 826 | wid: u64, |
f98ac774 | 827 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, |
642322b4 | 828 | prefix: &str, |
553610b4 | 829 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, |
f98ac774 | 830 | crypt_config: Option<Arc<CryptConfig>>, |
8bea85b4 | 831 | ) -> impl Future<Item=(usize, usize, usize), Error=Error> { |
adec8ea2 | 832 | |
82ab7230 DM |
833 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); |
834 | let repeat2 = repeat.clone(); | |
adec8ea2 | 835 | |
82ab7230 DM |
836 | let stream_len = std::sync::Arc::new(AtomicUsize::new(0)); |
837 | let stream_len2 = stream_len.clone(); | |
9c9ad941 | 838 | |
642322b4 DM |
839 | let append_chunk_path = format!("{}_index", prefix); |
840 | let upload_chunk_path = format!("{}_chunk", prefix); | |
841 | ||
842 | let (upload_queue, upload_result) = Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned()); | |
9c9ad941 | 843 | |
82ab7230 | 844 | let start_time = std::time::Instant::now(); |
9c9ad941 | 845 | |
82ab7230 | 846 | stream |
f98ac774 DM |
847 | .and_then(move |data| { |
848 | ||
849 | let chunk_len = data.len(); | |
850 | ||
82ab7230 | 851 | repeat.fetch_add(1, Ordering::SeqCst); |
f98ac774 DM |
852 | let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64; |
853 | ||
854 | let mut chunk_builder = DataChunkBuilder::new(data.as_ref()) | |
855 | .compress(true); | |
856 | ||
857 | if let Some(ref crypt_config) = crypt_config { | |
858 | chunk_builder = chunk_builder.crypt_config(crypt_config); | |
859 | } | |
62436222 DM |
860 | |
861 | let mut known_chunks = known_chunks.lock().unwrap(); | |
f98ac774 DM |
862 | let digest = chunk_builder.digest(); |
863 | let chunk_is_known = known_chunks.contains(digest); | |
62436222 | 864 | if chunk_is_known { |
f98ac774 | 865 | Ok(MergedChunkInfo::Known(vec![(offset, *digest)])) |
62436222 | 866 | } else { |
f98ac774 DM |
867 | known_chunks.insert(*digest); |
868 | let chunk = chunk_builder.build()?; | |
869 | Ok(MergedChunkInfo::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset })) | |
62436222 | 870 | } |
aa1b2e04 | 871 | }) |
62436222 | 872 | .merge_known_chunks() |
aa1b2e04 | 873 | .for_each(move |merged_chunk_info| { |
174ad378 DM |
874 | |
875 | if let MergedChunkInfo::New(chunk_info) = merged_chunk_info { | |
876 | let offset = chunk_info.offset; | |
f98ac774 | 877 | let digest = *chunk_info.chunk.digest(); |
bffd40d6 | 878 | let digest_str = proxmox::tools::digest_to_hex(&digest); |
174ad378 DM |
879 | let upload_queue = upload_queue.clone(); |
880 | ||
f98ac774 DM |
881 | println!("upload new chunk {} ({} bytes, offset {})", digest_str, |
882 | chunk_info.chunk_len, offset); | |
883 | ||
884 | let chunk_data = chunk_info.chunk.raw_data(); | |
885 | let param = json!({ | |
886 | "wid": wid, | |
887 | "digest": digest_str, | |
888 | "size": chunk_info.chunk_len, | |
889 | "encoded-size": chunk_data.len(), | |
890 | }); | |
174ad378 | 891 | |
642322b4 | 892 | let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param)).unwrap(); |
f98ac774 | 893 | let upload_data = Some(bytes::Bytes::from(chunk_data)); |
174ad378 | 894 | |
8de20e5c | 895 | let new_info = MergedChunkInfo::Known(vec![(offset, digest)]); |
174ad378 DM |
896 | |
897 | future::Either::A( | |
898 | h2.send_request(request, upload_data) | |
899 | .and_then(move |response| { | |
900 | upload_queue.clone().send((new_info, Some(response))) | |
901 | .map(|_| ()).map_err(Error::from) | |
902 | }) | |
903 | ) | |
904 | } else { | |
905 | ||
906 | future::Either::B( | |
907 | upload_queue.clone().send((merged_chunk_info, None)) | |
908 | .map(|_| ()).map_err(Error::from) | |
909 | ) | |
910 | } | |
82ab7230 DM |
911 | }) |
912 | .then(move |result| { | |
913 | println!("RESULT {:?}", result); | |
914 | upload_result.map_err(Error::from).and_then(|upload1_result| { | |
915 | Ok(upload1_result.and(result)) | |
916 | }) | |
917 | }) | |
918 | .flatten() | |
919 | .and_then(move |_| { | |
920 | let repeat = repeat2.load(Ordering::SeqCst); | |
921 | let stream_len = stream_len2.load(Ordering::SeqCst); | |
922 | let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
923 | println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed); | |
924 | if repeat > 0 { | |
925 | println!("Average chunk size was {} bytes.", stream_len/repeat); | |
926 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
927 | } | |
8bea85b4 | 928 | Ok((repeat, stream_len, speed)) |
82ab7230 DM |
929 | }) |
930 | } | |
931 | ||
932 | pub fn upload_speedtest(&self) -> impl Future<Item=usize, Error=Error> { | |
933 | ||
934 | let mut data = vec![]; | |
935 | // generate pseudo random byte sequence | |
936 | for i in 0..1024*1024 { | |
937 | for j in 0..4 { | |
938 | let byte = ((i >> (j<<3))&0xff) as u8; | |
939 | data.push(byte); | |
940 | } | |
941 | } | |
942 | ||
943 | let item_len = data.len(); | |
944 | ||
945 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); | |
946 | let repeat2 = repeat.clone(); | |
947 | ||
6ab34afa | 948 | let (upload_queue, upload_result) = Self::response_queue(); |
82ab7230 DM |
949 | |
950 | let start_time = std::time::Instant::now(); | |
951 | ||
6ab34afa | 952 | let h2 = self.h2.clone(); |
82ab7230 DM |
953 | |
954 | futures::stream::repeat(data) | |
955 | .take_while(move |_| { | |
956 | repeat.fetch_add(1, Ordering::SeqCst); | |
957 | Ok(start_time.elapsed().as_secs() < 5) | |
958 | }) | |
959 | .for_each(move |data| { | |
6ab34afa | 960 | let h2 = h2.clone(); |
82ab7230 DM |
961 | |
962 | let upload_queue = upload_queue.clone(); | |
963 | ||
964 | println!("send test data ({} bytes)", data.len()); | |
9af37c8f DM |
965 | let request = H2Client::request_builder("localhost", "POST", "speedtest", None).unwrap(); |
966 | h2.send_request(request, Some(bytes::Bytes::from(data))) | |
82ab7230 DM |
967 | .and_then(move |response| { |
968 | upload_queue.send(response) | |
969 | .map(|_| ()).map_err(Error::from) | |
adec8ea2 DM |
970 | }) |
971 | }) | |
82ab7230 DM |
972 | .then(move |result| { |
973 | println!("RESULT {:?}", result); | |
974 | upload_result.map_err(Error::from).and_then(|upload1_result| { | |
975 | Ok(upload1_result.and(result)) | |
976 | }) | |
977 | }) | |
978 | .flatten() | |
979 | .and_then(move |_| { | |
980 | let repeat = repeat2.load(Ordering::SeqCst); | |
981 | println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs()); | |
982 | let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
983 | if repeat > 0 { | |
984 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
985 | } | |
986 | Ok(speed) | |
987 | }) | |
adec8ea2 | 988 | } |
9af37c8f DM |
989 | } |
990 | ||
991 | #[derive(Clone)] | |
992 | pub struct H2Client { | |
993 | h2: h2::client::SendRequest<bytes::Bytes>, | |
994 | } | |
995 | ||
996 | impl H2Client { | |
997 | ||
998 | pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self { | |
999 | Self { h2 } | |
1000 | } | |
1001 | ||
1002 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1003 | let req = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1004 | self.request(req) | |
1005 | } | |
1006 | ||
1007 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1008 | let req = Self::request_builder("localhost", "PUT", path, param).unwrap(); | |
1009 | self.request(req) | |
1010 | } | |
1011 | ||
1012 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1013 | let req = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1014 | self.request(req) | |
1015 | } | |
1016 | ||
dd066d28 DM |
1017 | pub fn download<W: Write>(&self, path: &str, param: Option<Value>, output: W) -> impl Future<Item=W, Error=Error> { |
1018 | let request = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1019 | ||
1020 | self.send_request(request, None) | |
1021 | .and_then(move |response| { | |
1022 | response | |
1023 | .map_err(Error::from) | |
1024 | .and_then(move |resp| { | |
1025 | let status = resp.status(); | |
1026 | if !status.is_success() { | |
1027 | future::Either::A( | |
1028 | H2Client::h2api_response(resp) | |
1029 | .and_then(|_| { bail!("unknown error"); }) | |
1030 | ) | |
1031 | } else { | |
984a7c35 DM |
1032 | let mut body = resp.into_body(); |
1033 | let mut release_capacity = body.release_capacity().clone(); | |
1034 | ||
dd066d28 | 1035 | future::Either::B( |
984a7c35 | 1036 | body |
dd066d28 DM |
1037 | .map_err(Error::from) |
1038 | .fold(output, move |mut acc, chunk| { | |
984a7c35 | 1039 | let _ = release_capacity.release_capacity(chunk.len()); |
dd066d28 DM |
1040 | acc.write_all(&chunk)?; |
1041 | Ok::<_, Error>(acc) | |
1042 | }) | |
1043 | ) | |
1044 | } | |
1045 | }) | |
1046 | }) | |
1047 | } | |
1048 | ||
9af37c8f DM |
1049 | pub fn upload(&self, path: &str, param: Option<Value>, data: Vec<u8>) -> impl Future<Item=Value, Error=Error> { |
1050 | let request = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1051 | ||
9af37c8f DM |
1052 | self.h2.clone() |
1053 | .ready() | |
1054 | .map_err(Error::from) | |
1055 | .and_then(move |mut send_request| { | |
1056 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
1057 | PipeToSendStream::new(bytes::Bytes::from(data), stream) | |
1058 | .and_then(|_| { | |
1059 | response | |
1060 | .map_err(Error::from) | |
1061 | .and_then(Self::h2api_response) | |
1062 | }) | |
1063 | }) | |
1064 | } | |
adec8ea2 | 1065 | |
b57cb264 | 1066 | fn request( |
9af37c8f | 1067 | &self, |
b57cb264 DM |
1068 | request: Request<()>, |
1069 | ) -> impl Future<Item=Value, Error=Error> { | |
1070 | ||
9af37c8f | 1071 | self.send_request(request, None) |
82ab7230 DM |
1072 | .and_then(move |response| { |
1073 | response | |
1074 | .map_err(Error::from) | |
1075 | .and_then(Self::h2api_response) | |
1076 | }) | |
1077 | } | |
1078 | ||
1079 | fn send_request( | |
9af37c8f | 1080 | &self, |
82ab7230 DM |
1081 | request: Request<()>, |
1082 | data: Option<bytes::Bytes>, | |
1083 | ) -> impl Future<Item=h2::client::ResponseFuture, Error=Error> { | |
1084 | ||
9af37c8f | 1085 | self.h2.clone() |
10130cf4 DM |
1086 | .ready() |
1087 | .map_err(Error::from) | |
1088 | .and_then(move |mut send_request| { | |
82ab7230 DM |
1089 | if let Some(data) = data { |
1090 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
f98ac774 | 1091 | future::Either::A(PipeToSendStream::new(data, stream) |
82ab7230 DM |
1092 | .and_then(move |_| { |
1093 | future::ok(response) | |
1094 | })) | |
1095 | } else { | |
1096 | let (response, _stream) = send_request.send_request(request, true).unwrap(); | |
1097 | future::Either::B(future::ok(response)) | |
1098 | } | |
b57cb264 DM |
1099 | }) |
1100 | } | |
1101 | ||
1102 | fn h2api_response(response: Response<h2::RecvStream>) -> impl Future<Item=Value, Error=Error> { | |
1103 | ||
1104 | let status = response.status(); | |
1105 | ||
1106 | let (_head, mut body) = response.into_parts(); | |
1107 | ||
1108 | // The `release_capacity` handle allows the caller to manage | |
1109 | // flow control. | |
1110 | // | |
1111 | // Whenever data is received, the caller is responsible for | |
1112 | // releasing capacity back to the server once it has freed | |
1113 | // the data from memory. | |
1114 | let mut release_capacity = body.release_capacity().clone(); | |
1115 | ||
1116 | body | |
1117 | .map(move |chunk| { | |
b57cb264 DM |
1118 | // Let the server send more data. |
1119 | let _ = release_capacity.release_capacity(chunk.len()); | |
1120 | chunk | |
1121 | }) | |
1122 | .concat2() | |
1123 | .map_err(Error::from) | |
1124 | .and_then(move |data| { | |
b57cb264 DM |
1125 | let text = String::from_utf8(data.to_vec()).unwrap(); |
1126 | if status.is_success() { | |
1127 | if text.len() > 0 { | |
1128 | let mut value: Value = serde_json::from_str(&text)?; | |
1129 | if let Some(map) = value.as_object_mut() { | |
1130 | if let Some(data) = map.remove("data") { | |
1131 | return Ok(data); | |
1132 | } | |
1133 | } | |
1134 | bail!("got result without data property"); | |
1135 | } else { | |
1136 | Ok(Value::Null) | |
1137 | } | |
1138 | } else { | |
1139 | bail!("HTTP Error {}: {}", status, text); | |
1140 | } | |
1141 | }) | |
1142 | } | |
1143 | ||
eb2bdd1b | 1144 | // Note: We always encode parameters with the url |
b57cb264 DM |
1145 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> { |
1146 | let path = path.trim_matches('/'); | |
b57cb264 DM |
1147 | |
1148 | if let Some(data) = data { | |
1149 | let query = tools::json_object_to_query(data)?; | |
eb2bdd1b DM |
1150 | // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side |
1151 | if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); } | |
b57cb264 | 1152 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; |
eb2bdd1b | 1153 | let request = Request::builder() |
b57cb264 DM |
1154 | .method(method) |
1155 | .uri(url) | |
1156 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1157 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1158 | .body(())?; | |
1159 | return Ok(request); | |
eb2bdd1b DM |
1160 | } else { |
1161 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; | |
1162 | let request = Request::builder() | |
1163 | .method(method) | |
1164 | .uri(url) | |
1165 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1166 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1167 | .body(())?; | |
b57cb264 | 1168 | |
eb2bdd1b DM |
1169 | Ok(request) |
1170 | } | |
b57cb264 DM |
1171 | } |
1172 | } |