]>
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; |
fa5d6977 | 7 | use chrono::{DateTime, 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! |
99168f43 | 168 | httpc.set_recv_buffer_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 | ||
04512d30 DM |
251 | pub fn upload( |
252 | &mut self, | |
253 | content_type: &str, | |
254 | body: Body, | |
255 | path: &str, | |
256 | data: Option<Value>, | |
257 | ) -> impl Future<Item=Value, Error=Error> { | |
81da38c1 DM |
258 | |
259 | let path = path.trim_matches('/'); | |
04512d30 DM |
260 | let mut url = format!("https://{}:8007/{}", &self.server, path); |
261 | ||
262 | if let Some(data) = data { | |
263 | let query = tools::json_object_to_query(data).unwrap(); | |
264 | url.push('?'); | |
265 | url.push_str(&query); | |
266 | } | |
267 | ||
268 | let url: Uri = url.parse().unwrap(); | |
81da38c1 | 269 | |
5a2df000 | 270 | let req = Request::builder() |
81da38c1 DM |
271 | .method("POST") |
272 | .uri(url) | |
273 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
274 | .header("Content-Type", content_type) |
275 | .body(body).unwrap(); | |
81da38c1 | 276 | |
5a2df000 | 277 | self.request(req) |
1fdb4c6f DM |
278 | } |
279 | ||
6ab34afa DM |
280 | pub fn start_backup( |
281 | &self, | |
282 | datastore: &str, | |
283 | backup_type: &str, | |
284 | backup_id: &str, | |
ca5d0b61 | 285 | backup_time: DateTime<Utc>, |
39e60bd6 | 286 | debug: bool, |
3467cd91 | 287 | ) -> impl Future<Item=Arc<BackupClient>, Error=Error> { |
cf639a47 | 288 | |
ca5d0b61 DM |
289 | let param = json!({ |
290 | "backup-type": backup_type, | |
291 | "backup-id": backup_id, | |
292 | "backup-time": backup_time.timestamp(), | |
293 | "store": datastore, | |
294 | "debug": debug | |
295 | }); | |
296 | ||
fb047083 | 297 | let req = Self::request_builder(&self.server, "GET", "/api2/json/backup", Some(param)).unwrap(); |
cf639a47 | 298 | |
fb047083 DM |
299 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_PROTOCOL_ID_V1!())) |
300 | .map(|(h2, canceller)| BackupClient::new(h2, canceller)) | |
301 | } | |
302 | ||
dd066d28 DM |
303 | pub fn start_backup_reader( |
304 | &self, | |
305 | datastore: &str, | |
306 | backup_type: &str, | |
307 | backup_id: &str, | |
fa5d6977 | 308 | backup_time: DateTime<Utc>, |
dd066d28 | 309 | debug: bool, |
3467cd91 | 310 | ) -> impl Future<Item=Arc<BackupReader>, Error=Error> { |
dd066d28 DM |
311 | |
312 | let param = json!({ | |
313 | "backup-type": backup_type, | |
314 | "backup-id": backup_id, | |
315 | "backup-time": backup_time.timestamp(), | |
316 | "store": datastore, | |
317 | "debug": debug, | |
318 | }); | |
319 | let req = Self::request_builder(&self.server, "GET", "/api2/json/reader", Some(param)).unwrap(); | |
320 | ||
321 | self.start_h2_connection(req, String::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1!())) | |
322 | .map(|(h2, canceller)| BackupReader::new(h2, canceller)) | |
323 | } | |
324 | ||
fb047083 DM |
325 | pub fn start_h2_connection( |
326 | &self, | |
327 | mut req: Request<Body>, | |
328 | protocol_name: String, | |
329 | ) -> impl Future<Item=(H2Client, Canceller), Error=Error> { | |
cf639a47 | 330 | |
fb047083 | 331 | let login = self.auth.listen(); |
cf639a47 DM |
332 | let client = self.client.clone(); |
333 | ||
334 | login.and_then(move |auth| { | |
335 | ||
336 | let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)); | |
337 | req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap()); | |
fb047083 | 338 | req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap()); |
cf639a47 DM |
339 | |
340 | client.request(req) | |
341 | .map_err(Error::from) | |
342 | .and_then(|resp| { | |
343 | ||
344 | let status = resp.status(); | |
345 | if status != http::StatusCode::SWITCHING_PROTOCOLS { | |
9af37c8f DM |
346 | future::Either::A(Self::api_response(resp).and_then(|_| { bail!("unknown error"); })) |
347 | } else { | |
348 | future::Either::B(resp.into_body().on_upgrade().map_err(Error::from)) | |
cf639a47 | 349 | } |
cf639a47 | 350 | }) |
cf639a47 | 351 | .and_then(|upgraded| { |
a2b29b68 | 352 | let max_window_size = (1 << 31) - 2; |
fcf5dea5 DM |
353 | |
354 | h2::client::Builder::new() | |
a2b29b68 DM |
355 | .initial_connection_window_size(max_window_size) |
356 | .initial_window_size(max_window_size) | |
fcf5dea5 | 357 | .max_frame_size(4*1024*1024) |
fcf5dea5 DM |
358 | .handshake(upgraded) |
359 | .map_err(Error::from) | |
cf639a47 DM |
360 | }) |
361 | .and_then(|(h2, connection)| { | |
362 | let connection = connection | |
363 | .map_err(|_| panic!("HTTP/2.0 connection failed")); | |
364 | ||
cb4426b3 WB |
365 | let (connection, canceller) = cancellable(connection)?; |
366 | // A cancellable future returns an Option which is None when cancelled and | |
367 | // Some when it finished instead, since we don't care about the return type we | |
368 | // need to map it away: | |
369 | let connection = connection.map(|_| ()); | |
370 | ||
cf639a47 DM |
371 | // Spawn a new task to drive the connection state |
372 | hyper::rt::spawn(connection); | |
373 | ||
374 | // Wait until the `SendRequest` handle has available capacity. | |
cb4426b3 | 375 | Ok(h2.ready() |
fb047083 DM |
376 | .map(move |c| (H2Client::new(c), canceller)) |
377 | .map_err(Error::from)) | |
cf639a47 | 378 | }) |
cb4426b3 | 379 | .flatten() |
cf639a47 DM |
380 | }) |
381 | } | |
382 | ||
5a2df000 | 383 | fn credentials( |
6d1f61b2 | 384 | client: Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, |
45cdce06 DM |
385 | server: String, |
386 | username: String, | |
387 | password: String, | |
dd5495d6 | 388 | ) -> Box<dyn Future<Item=AuthInfo, Error=Error> + Send> { |
0ffbccce | 389 | |
45cdce06 | 390 | let server2 = server.clone(); |
0ffbccce | 391 | |
5a2df000 | 392 | let create_request = futures::future::lazy(move || { |
45cdce06 | 393 | let data = json!({ "username": username, "password": password }); |
5a2df000 | 394 | let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap(); |
45cdce06 | 395 | Self::api_request(client, req) |
5a2df000 | 396 | }); |
0dffe3f9 | 397 | |
5a2df000 DM |
398 | let login_future = create_request |
399 | .and_then(move |cred| { | |
400 | let auth = AuthInfo { | |
401 | username: cred["data"]["username"].as_str().unwrap().to_owned(), | |
402 | ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(), | |
403 | token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(), | |
404 | }; | |
0dffe3f9 | 405 | |
5a2df000 | 406 | let _ = store_ticket_info(&server2, &auth.username, &auth.ticket, &auth.token); |
0dffe3f9 | 407 | |
5a2df000 DM |
408 | Ok(auth) |
409 | }); | |
0dffe3f9 | 410 | |
5a2df000 | 411 | Box::new(login_future) |
ba3a60b2 DM |
412 | } |
413 | ||
d2c48afc DM |
414 | fn api_response(response: Response<Body>) -> impl Future<Item=Value, Error=Error> { |
415 | ||
416 | let status = response.status(); | |
417 | ||
418 | response | |
419 | .into_body() | |
420 | .concat2() | |
421 | .map_err(Error::from) | |
422 | .and_then(move |data| { | |
423 | ||
424 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
425 | if status.is_success() { | |
426 | if text.len() > 0 { | |
427 | let value: Value = serde_json::from_str(&text)?; | |
428 | Ok(value) | |
429 | } else { | |
430 | Ok(Value::Null) | |
431 | } | |
432 | } else { | |
433 | bail!("HTTP Error {}: {}", status, text); | |
434 | } | |
435 | }) | |
436 | } | |
437 | ||
5a2df000 | 438 | fn api_request( |
6d1f61b2 | 439 | client: Client<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, |
5a2df000 DM |
440 | req: Request<Body> |
441 | ) -> impl Future<Item=Value, Error=Error> { | |
ba3a60b2 | 442 | |
5a2df000 DM |
443 | client.request(req) |
444 | .map_err(Error::from) | |
d2c48afc | 445 | .and_then(Self::api_response) |
0dffe3f9 DM |
446 | } |
447 | ||
5a2df000 | 448 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> { |
591f570b | 449 | let path = path.trim_matches('/'); |
5a2df000 DM |
450 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; |
451 | ||
452 | if let Some(data) = data { | |
453 | if method == "POST" { | |
454 | let request = Request::builder() | |
455 | .method(method) | |
456 | .uri(url) | |
457 | .header("User-Agent", "proxmox-backup-client/1.0") | |
458 | .header(hyper::header::CONTENT_TYPE, "application/json") | |
459 | .body(Body::from(data.to_string()))?; | |
460 | return Ok(request); | |
461 | } else { | |
9e391bb7 DM |
462 | let query = tools::json_object_to_query(data)?; |
463 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; | |
464 | let request = Request::builder() | |
465 | .method(method) | |
466 | .uri(url) | |
467 | .header("User-Agent", "proxmox-backup-client/1.0") | |
468 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
469 | .body(Body::empty())?; | |
470 | return Ok(request); | |
5a2df000 | 471 | } |
5a2df000 | 472 | } |
0dffe3f9 | 473 | |
1fdb4c6f | 474 | let request = Request::builder() |
5a2df000 | 475 | .method(method) |
1fdb4c6f DM |
476 | .uri(url) |
477 | .header("User-Agent", "proxmox-backup-client/1.0") | |
5a2df000 DM |
478 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") |
479 | .body(Body::empty())?; | |
1fdb4c6f | 480 | |
5a2df000 | 481 | Ok(request) |
597641fd DM |
482 | } |
483 | } | |
b57cb264 | 484 | |
dd066d28 DM |
485 | |
486 | pub struct BackupReader { | |
487 | h2: H2Client, | |
3467cd91 | 488 | canceller: Canceller, |
dd066d28 DM |
489 | } |
490 | ||
491 | impl Drop for BackupReader { | |
492 | ||
493 | fn drop(&mut self) { | |
3467cd91 | 494 | self.canceller.cancel(); |
dd066d28 DM |
495 | } |
496 | } | |
497 | ||
498 | impl BackupReader { | |
499 | ||
3467cd91 DM |
500 | pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> { |
501 | Arc::new(Self { h2, canceller: canceller }) | |
dd066d28 DM |
502 | } |
503 | ||
504 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
505 | self.h2.get(path, param) | |
506 | } | |
507 | ||
508 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
509 | self.h2.put(path, param) | |
510 | } | |
511 | ||
512 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
513 | self.h2.post(path, param) | |
514 | } | |
515 | ||
516 | pub fn download<W: Write>( | |
517 | &self, | |
518 | file_name: &str, | |
519 | output: W, | |
520 | ) -> impl Future<Item=W, Error=Error> { | |
521 | let path = "download"; | |
522 | let param = json!({ "file-name": file_name }); | |
523 | self.h2.download(path, Some(param), output) | |
524 | } | |
525 | ||
17243003 DM |
526 | pub fn speedtest<W: Write>( |
527 | &self, | |
528 | output: W, | |
529 | ) -> impl Future<Item=W, Error=Error> { | |
530 | self.h2.download("speedtest", None, output) | |
531 | } | |
532 | ||
fcf5dea5 DM |
533 | pub fn download_chunk<W: Write>( |
534 | &self, | |
535 | digest: &[u8; 32], | |
536 | output: W, | |
537 | ) -> impl Future<Item=W, Error=Error> { | |
538 | let path = "chunk"; | |
539 | let param = json!({ "digest": proxmox::tools::digest_to_hex(digest) }); | |
540 | self.h2.download(path, Some(param), output) | |
541 | } | |
542 | ||
4f6aaf54 | 543 | pub fn force_close(self) { |
3467cd91 | 544 | self.canceller.cancel(); |
dd066d28 DM |
545 | } |
546 | } | |
547 | ||
6ab34afa | 548 | pub struct BackupClient { |
9af37c8f | 549 | h2: H2Client, |
3467cd91 | 550 | canceller: Canceller, |
b57cb264 DM |
551 | } |
552 | ||
dd066d28 DM |
553 | impl Drop for BackupClient { |
554 | ||
555 | fn drop(&mut self) { | |
3467cd91 | 556 | self.canceller.cancel(); |
dd066d28 DM |
557 | } |
558 | } | |
91320f08 | 559 | |
2c3891d1 DM |
560 | pub struct BackupStats { |
561 | pub size: u64, | |
562 | } | |
563 | ||
6ab34afa | 564 | impl BackupClient { |
b57cb264 | 565 | |
3467cd91 DM |
566 | pub fn new(h2: H2Client, canceller: Canceller) -> Arc<Self> { |
567 | Arc::new(Self { h2, canceller }) | |
cb4426b3 WB |
568 | } |
569 | ||
b57cb264 | 570 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 571 | self.h2.get(path, param) |
b57cb264 DM |
572 | } |
573 | ||
82ab7230 | 574 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 575 | self.h2.put(path, param) |
82ab7230 DM |
576 | } |
577 | ||
b57cb264 | 578 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { |
9af37c8f | 579 | self.h2.post(path, param) |
97f22ce5 DM |
580 | } |
581 | ||
3467cd91 | 582 | pub fn finish(self: Arc<Self>) -> impl Future<Item=(), Error=Error> { |
9cc88a7c DM |
583 | self.h2.clone() |
584 | .post("finish", None) | |
585 | .map(move |_| { | |
586 | self.canceller.cancel(); | |
587 | }) | |
4247fccb DM |
588 | } |
589 | ||
3467cd91 DM |
590 | pub fn force_close(self) { |
591 | self.canceller.cancel(); | |
d6f204ed DM |
592 | } |
593 | ||
9f46c7de DM |
594 | pub fn upload_blob_from_data( |
595 | &self, | |
596 | data: Vec<u8>, | |
597 | file_name: &str, | |
598 | crypt_config: Option<Arc<CryptConfig>>, | |
599 | compress: bool, | |
2c3891d1 | 600 | ) -> impl Future<Item=BackupStats, Error=Error> { |
9f46c7de DM |
601 | |
602 | let h2 = self.h2.clone(); | |
603 | let file_name = file_name.to_owned(); | |
2c3891d1 | 604 | let size = data.len() as u64; |
9f46c7de DM |
605 | |
606 | futures::future::ok(()) | |
607 | .and_then(move |_| { | |
608 | let blob = if let Some(ref crypt_config) = crypt_config { | |
609 | DataBlob::encode(&data, Some(crypt_config), compress)? | |
610 | } else { | |
611 | DataBlob::encode(&data, None, compress)? | |
612 | }; | |
613 | ||
614 | let raw_data = blob.into_inner(); | |
615 | Ok(raw_data) | |
616 | }) | |
617 | .and_then(move |raw_data| { | |
618 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
619 | h2.upload("blob", Some(param), raw_data) | |
2c3891d1 DM |
620 | .map(move |_| { |
621 | BackupStats { size: size } | |
622 | }) | |
9f46c7de DM |
623 | }) |
624 | } | |
625 | ||
626 | pub fn upload_blob_from_file<P: AsRef<std::path::Path>>( | |
39d6846e | 627 | &self, |
ec8a9bb9 | 628 | src_path: P, |
39d6846e | 629 | file_name: &str, |
cb08ac3e DM |
630 | crypt_config: Option<Arc<CryptConfig>>, |
631 | compress: bool, | |
2c3891d1 | 632 | ) -> impl Future<Item=BackupStats, Error=Error> { |
39d6846e DM |
633 | |
634 | let h2 = self.h2.clone(); | |
635 | let file_name = file_name.to_owned(); | |
ec8a9bb9 | 636 | let src_path = src_path.as_ref().to_owned(); |
39d6846e | 637 | |
ef39bf95 DM |
638 | let task = tokio::fs::File::open(src_path.clone()) |
639 | .map_err(move |err| format_err!("unable to open file {:?} - {}", src_path, err)) | |
cb08ac3e | 640 | .and_then(move |file| { |
39d6846e DM |
641 | let contents = vec![]; |
642 | tokio::io::read_to_end(file, contents) | |
643 | .map_err(Error::from) | |
644 | .and_then(move |(_, contents)| { | |
cb08ac3e DM |
645 | let blob = if let Some(ref crypt_config) = crypt_config { |
646 | DataBlob::encode(&contents, Some(crypt_config), compress)? | |
647 | } else { | |
648 | DataBlob::encode(&contents, None, compress)? | |
649 | }; | |
650 | let raw_data = blob.into_inner(); | |
2c3891d1 | 651 | Ok((raw_data, contents.len())) |
cb08ac3e | 652 | }) |
2c3891d1 | 653 | .and_then(move |(raw_data, size)| { |
cb08ac3e DM |
654 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); |
655 | h2.upload("blob", Some(param), raw_data) | |
2c3891d1 DM |
656 | .map(move |_| { |
657 | BackupStats { size: size as u64 } | |
658 | }) | |
39d6846e DM |
659 | }) |
660 | }); | |
661 | ||
662 | task | |
663 | } | |
664 | ||
a42fa400 | 665 | pub fn upload_stream( |
d6f204ed DM |
666 | &self, |
667 | archive_name: &str, | |
668 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, | |
a42fa400 DM |
669 | prefix: &str, |
670 | fixed_size: Option<u64>, | |
f98ac774 | 671 | crypt_config: Option<Arc<CryptConfig>>, |
2c3891d1 | 672 | ) -> impl Future<Item=BackupStats, Error=Error> { |
d6f204ed DM |
673 | |
674 | let known_chunks = Arc::new(Mutex::new(HashSet::new())); | |
675 | ||
676 | let h2 = self.h2.clone(); | |
677 | let h2_2 = self.h2.clone(); | |
678 | let h2_3 = self.h2.clone(); | |
679 | let h2_4 = self.h2.clone(); | |
680 | ||
a42fa400 DM |
681 | let mut param = json!({ "archive-name": archive_name }); |
682 | if let Some(size) = fixed_size { | |
683 | param["size"] = size.into(); | |
684 | } | |
685 | ||
686 | let index_path = format!("{}_index", prefix); | |
a42fa400 | 687 | let close_path = format!("{}_close", prefix); |
d6f204ed | 688 | |
642322b4 DM |
689 | let prefix = prefix.to_owned(); |
690 | ||
a42fa400 | 691 | Self::download_chunk_list(h2, &index_path, archive_name, known_chunks.clone()) |
d6f204ed | 692 | .and_then(move |_| { |
a42fa400 | 693 | h2_2.post(&index_path, Some(param)) |
d6f204ed DM |
694 | }) |
695 | .and_then(move |res| { | |
696 | let wid = res.as_u64().unwrap(); | |
f98ac774 | 697 | Self::upload_chunk_info_stream(h2_3, wid, stream, &prefix, known_chunks.clone(), crypt_config) |
2c3891d1 | 698 | .and_then(move |(chunk_count, size, _speed)| { |
8bea85b4 DM |
699 | let param = json!({ |
700 | "wid": wid , | |
701 | "chunk-count": chunk_count, | |
702 | "size": size, | |
703 | }); | |
a42fa400 | 704 | h2_4.post(&close_path, Some(param)) |
2c3891d1 DM |
705 | .map(move |_| { |
706 | BackupStats { size: size as u64 } | |
707 | }) | |
708 | }) | |
d6f204ed DM |
709 | }) |
710 | } | |
711 | ||
6ab34afa | 712 | fn response_queue() -> ( |
82ab7230 DM |
713 | mpsc::Sender<h2::client::ResponseFuture>, |
714 | sync::oneshot::Receiver<Result<(), Error>> | |
715 | ) { | |
716 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100); | |
717 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); | |
adec8ea2 | 718 | |
82ab7230 DM |
719 | hyper::rt::spawn( |
720 | verify_queue_rx | |
721 | .map_err(Error::from) | |
722 | .for_each(|response: h2::client::ResponseFuture| { | |
723 | response | |
724 | .map_err(Error::from) | |
9af37c8f | 725 | .and_then(H2Client::h2api_response) |
82ab7230 DM |
726 | .and_then(|result| { |
727 | println!("RESPONSE: {:?}", result); | |
728 | Ok(()) | |
729 | }) | |
730 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
731 | }) | |
732 | .then(|result| | |
733 | verify_result_tx.send(result) | |
734 | ) | |
735 | .map_err(|_| { /* ignore closed channel */ }) | |
736 | ); | |
adec8ea2 | 737 | |
82ab7230 DM |
738 | (verify_queue_tx, verify_result_rx) |
739 | } | |
740 | ||
642322b4 | 741 | fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> ( |
174ad378 | 742 | mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>, |
05cba08c DM |
743 | sync::oneshot::Receiver<Result<(), Error>> |
744 | ) { | |
771953f9 | 745 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64); |
05cba08c DM |
746 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); |
747 | ||
748 | let h2_2 = h2.clone(); | |
749 | ||
750 | hyper::rt::spawn( | |
751 | verify_queue_rx | |
752 | .map_err(Error::from) | |
174ad378 DM |
753 | .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| { |
754 | match (response, merged_chunk_info) { | |
755 | (Some(response), MergedChunkInfo::Known(list)) => { | |
05cba08c | 756 | future::Either::A( |
174ad378 DM |
757 | response |
758 | .map_err(Error::from) | |
759 | .and_then(H2Client::h2api_response) | |
771953f9 | 760 | .and_then(move |_result| { |
174ad378 | 761 | Ok(MergedChunkInfo::Known(list)) |
05cba08c | 762 | }) |
05cba08c DM |
763 | ) |
764 | } | |
174ad378 | 765 | (None, MergedChunkInfo::Known(list)) => { |
05cba08c DM |
766 | future::Either::B(future::ok(MergedChunkInfo::Known(list))) |
767 | } | |
174ad378 | 768 | _ => unreachable!(), |
05cba08c DM |
769 | } |
770 | }) | |
62436222 | 771 | .merge_known_chunks() |
05cba08c DM |
772 | .and_then(move |merged_chunk_info| { |
773 | match merged_chunk_info { | |
774 | MergedChunkInfo::Known(chunk_list) => { | |
775 | let mut digest_list = vec![]; | |
776 | let mut offset_list = vec![]; | |
777 | for (offset, digest) in chunk_list { | |
bffd40d6 DM |
778 | //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset); |
779 | digest_list.push(proxmox::tools::digest_to_hex(&digest)); | |
05cba08c DM |
780 | offset_list.push(offset); |
781 | } | |
782 | println!("append chunks list len ({})", digest_list.len()); | |
783 | let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }); | |
a42fa400 | 784 | let mut request = H2Client::request_builder("localhost", "PUT", &path, None).unwrap(); |
05cba08c DM |
785 | request.headers_mut().insert(hyper::header::CONTENT_TYPE, HeaderValue::from_static("application/json")); |
786 | let param_data = bytes::Bytes::from(param.to_string().as_bytes()); | |
787 | let upload_data = Some(param_data); | |
788 | h2_2.send_request(request, upload_data) | |
789 | .and_then(move |response| { | |
790 | response | |
791 | .map_err(Error::from) | |
792 | .and_then(H2Client::h2api_response) | |
793 | .and_then(|_| Ok(())) | |
794 | }) | |
795 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
796 | } | |
797 | _ => unreachable!(), | |
798 | } | |
799 | }) | |
800 | .for_each(|_| Ok(())) | |
801 | .then(|result| | |
802 | verify_result_tx.send(result) | |
803 | ) | |
804 | .map_err(|_| { /* ignore closed channel */ }) | |
805 | ); | |
806 | ||
807 | (verify_queue_tx, verify_result_rx) | |
808 | } | |
809 | ||
6ab34afa | 810 | fn download_chunk_list( |
9af37c8f | 811 | h2: H2Client, |
553610b4 DM |
812 | path: &str, |
813 | archive_name: &str, | |
814 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, | |
815 | ) -> impl Future<Item=(), Error=Error> { | |
816 | ||
817 | let param = json!({ "archive-name": archive_name }); | |
9af37c8f | 818 | let request = H2Client::request_builder("localhost", "GET", path, Some(param)).unwrap(); |
553610b4 | 819 | |
9af37c8f | 820 | h2.send_request(request, None) |
553610b4 DM |
821 | .and_then(move |response| { |
822 | response | |
823 | .map_err(Error::from) | |
824 | .and_then(move |resp| { | |
825 | let status = resp.status(); | |
7dd1bcac | 826 | |
553610b4 | 827 | if !status.is_success() { |
7dd1bcac DM |
828 | future::Either::A(H2Client::h2api_response(resp).and_then(|_| { bail!("unknown error"); })) |
829 | } else { | |
830 | future::Either::B(future::ok(resp.into_body())) | |
553610b4 | 831 | } |
553610b4 DM |
832 | }) |
833 | .and_then(move |mut body| { | |
834 | ||
835 | let mut release_capacity = body.release_capacity().clone(); | |
836 | ||
986bef16 | 837 | DigestListDecoder::new(body.map_err(Error::from)) |
553610b4 DM |
838 | .for_each(move |chunk| { |
839 | let _ = release_capacity.release_capacity(chunk.len()); | |
bffd40d6 | 840 | println!("GOT DOWNLOAD {}", proxmox::tools::digest_to_hex(&chunk)); |
553610b4 DM |
841 | known_chunks.lock().unwrap().insert(chunk); |
842 | Ok(()) | |
843 | }) | |
844 | }) | |
845 | }) | |
846 | } | |
847 | ||
a42fa400 | 848 | fn upload_chunk_info_stream( |
9af37c8f | 849 | h2: H2Client, |
82ab7230 | 850 | wid: u64, |
f98ac774 | 851 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, |
642322b4 | 852 | prefix: &str, |
553610b4 | 853 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, |
f98ac774 | 854 | crypt_config: Option<Arc<CryptConfig>>, |
8bea85b4 | 855 | ) -> impl Future<Item=(usize, usize, usize), Error=Error> { |
adec8ea2 | 856 | |
82ab7230 DM |
857 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); |
858 | let repeat2 = repeat.clone(); | |
adec8ea2 | 859 | |
82ab7230 DM |
860 | let stream_len = std::sync::Arc::new(AtomicUsize::new(0)); |
861 | let stream_len2 = stream_len.clone(); | |
9c9ad941 | 862 | |
642322b4 DM |
863 | let append_chunk_path = format!("{}_index", prefix); |
864 | let upload_chunk_path = format!("{}_chunk", prefix); | |
865 | ||
866 | let (upload_queue, upload_result) = Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned()); | |
9c9ad941 | 867 | |
82ab7230 | 868 | let start_time = std::time::Instant::now(); |
9c9ad941 | 869 | |
82ab7230 | 870 | stream |
f98ac774 DM |
871 | .and_then(move |data| { |
872 | ||
873 | let chunk_len = data.len(); | |
874 | ||
82ab7230 | 875 | repeat.fetch_add(1, Ordering::SeqCst); |
f98ac774 DM |
876 | let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64; |
877 | ||
878 | let mut chunk_builder = DataChunkBuilder::new(data.as_ref()) | |
879 | .compress(true); | |
880 | ||
881 | if let Some(ref crypt_config) = crypt_config { | |
882 | chunk_builder = chunk_builder.crypt_config(crypt_config); | |
883 | } | |
62436222 DM |
884 | |
885 | let mut known_chunks = known_chunks.lock().unwrap(); | |
f98ac774 DM |
886 | let digest = chunk_builder.digest(); |
887 | let chunk_is_known = known_chunks.contains(digest); | |
62436222 | 888 | if chunk_is_known { |
f98ac774 | 889 | Ok(MergedChunkInfo::Known(vec![(offset, *digest)])) |
62436222 | 890 | } else { |
f98ac774 DM |
891 | known_chunks.insert(*digest); |
892 | let chunk = chunk_builder.build()?; | |
893 | Ok(MergedChunkInfo::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset })) | |
62436222 | 894 | } |
aa1b2e04 | 895 | }) |
62436222 | 896 | .merge_known_chunks() |
aa1b2e04 | 897 | .for_each(move |merged_chunk_info| { |
174ad378 DM |
898 | |
899 | if let MergedChunkInfo::New(chunk_info) = merged_chunk_info { | |
900 | let offset = chunk_info.offset; | |
f98ac774 | 901 | let digest = *chunk_info.chunk.digest(); |
bffd40d6 | 902 | let digest_str = proxmox::tools::digest_to_hex(&digest); |
174ad378 DM |
903 | let upload_queue = upload_queue.clone(); |
904 | ||
f98ac774 DM |
905 | println!("upload new chunk {} ({} bytes, offset {})", digest_str, |
906 | chunk_info.chunk_len, offset); | |
907 | ||
908 | let chunk_data = chunk_info.chunk.raw_data(); | |
909 | let param = json!({ | |
910 | "wid": wid, | |
911 | "digest": digest_str, | |
912 | "size": chunk_info.chunk_len, | |
913 | "encoded-size": chunk_data.len(), | |
914 | }); | |
174ad378 | 915 | |
642322b4 | 916 | let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param)).unwrap(); |
f98ac774 | 917 | let upload_data = Some(bytes::Bytes::from(chunk_data)); |
174ad378 | 918 | |
8de20e5c | 919 | let new_info = MergedChunkInfo::Known(vec![(offset, digest)]); |
174ad378 DM |
920 | |
921 | future::Either::A( | |
922 | h2.send_request(request, upload_data) | |
923 | .and_then(move |response| { | |
924 | upload_queue.clone().send((new_info, Some(response))) | |
925 | .map(|_| ()).map_err(Error::from) | |
926 | }) | |
927 | ) | |
928 | } else { | |
929 | ||
930 | future::Either::B( | |
931 | upload_queue.clone().send((merged_chunk_info, None)) | |
932 | .map(|_| ()).map_err(Error::from) | |
933 | ) | |
934 | } | |
82ab7230 DM |
935 | }) |
936 | .then(move |result| { | |
684233aa | 937 | //println!("RESULT {:?}", result); |
82ab7230 DM |
938 | upload_result.map_err(Error::from).and_then(|upload1_result| { |
939 | Ok(upload1_result.and(result)) | |
940 | }) | |
941 | }) | |
942 | .flatten() | |
943 | .and_then(move |_| { | |
944 | let repeat = repeat2.load(Ordering::SeqCst); | |
945 | let stream_len = stream_len2.load(Ordering::SeqCst); | |
946 | let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
947 | println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed); | |
948 | if repeat > 0 { | |
949 | println!("Average chunk size was {} bytes.", stream_len/repeat); | |
950 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
951 | } | |
8bea85b4 | 952 | Ok((repeat, stream_len, speed)) |
82ab7230 DM |
953 | }) |
954 | } | |
955 | ||
956 | pub fn upload_speedtest(&self) -> impl Future<Item=usize, Error=Error> { | |
957 | ||
958 | let mut data = vec![]; | |
959 | // generate pseudo random byte sequence | |
960 | for i in 0..1024*1024 { | |
961 | for j in 0..4 { | |
962 | let byte = ((i >> (j<<3))&0xff) as u8; | |
963 | data.push(byte); | |
964 | } | |
965 | } | |
966 | ||
967 | let item_len = data.len(); | |
968 | ||
969 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); | |
970 | let repeat2 = repeat.clone(); | |
971 | ||
6ab34afa | 972 | let (upload_queue, upload_result) = Self::response_queue(); |
82ab7230 DM |
973 | |
974 | let start_time = std::time::Instant::now(); | |
975 | ||
6ab34afa | 976 | let h2 = self.h2.clone(); |
82ab7230 DM |
977 | |
978 | futures::stream::repeat(data) | |
979 | .take_while(move |_| { | |
980 | repeat.fetch_add(1, Ordering::SeqCst); | |
981 | Ok(start_time.elapsed().as_secs() < 5) | |
982 | }) | |
983 | .for_each(move |data| { | |
6ab34afa | 984 | let h2 = h2.clone(); |
82ab7230 DM |
985 | |
986 | let upload_queue = upload_queue.clone(); | |
987 | ||
988 | println!("send test data ({} bytes)", data.len()); | |
9af37c8f DM |
989 | let request = H2Client::request_builder("localhost", "POST", "speedtest", None).unwrap(); |
990 | h2.send_request(request, Some(bytes::Bytes::from(data))) | |
82ab7230 DM |
991 | .and_then(move |response| { |
992 | upload_queue.send(response) | |
993 | .map(|_| ()).map_err(Error::from) | |
adec8ea2 DM |
994 | }) |
995 | }) | |
82ab7230 DM |
996 | .then(move |result| { |
997 | println!("RESULT {:?}", result); | |
998 | upload_result.map_err(Error::from).and_then(|upload1_result| { | |
999 | Ok(upload1_result.and(result)) | |
1000 | }) | |
1001 | }) | |
1002 | .flatten() | |
1003 | .and_then(move |_| { | |
1004 | let repeat = repeat2.load(Ordering::SeqCst); | |
1005 | println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs()); | |
1006 | let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
1007 | if repeat > 0 { | |
1008 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
1009 | } | |
1010 | Ok(speed) | |
1011 | }) | |
adec8ea2 | 1012 | } |
9af37c8f DM |
1013 | } |
1014 | ||
1015 | #[derive(Clone)] | |
1016 | pub struct H2Client { | |
1017 | h2: h2::client::SendRequest<bytes::Bytes>, | |
1018 | } | |
1019 | ||
1020 | impl H2Client { | |
1021 | ||
1022 | pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self { | |
1023 | Self { h2 } | |
1024 | } | |
1025 | ||
1026 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1027 | let req = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1028 | self.request(req) | |
1029 | } | |
1030 | ||
1031 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1032 | let req = Self::request_builder("localhost", "PUT", path, param).unwrap(); | |
1033 | self.request(req) | |
1034 | } | |
1035 | ||
1036 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1037 | let req = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1038 | self.request(req) | |
1039 | } | |
1040 | ||
dd066d28 DM |
1041 | pub fn download<W: Write>(&self, path: &str, param: Option<Value>, output: W) -> impl Future<Item=W, Error=Error> { |
1042 | let request = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1043 | ||
1044 | self.send_request(request, None) | |
1045 | .and_then(move |response| { | |
1046 | response | |
1047 | .map_err(Error::from) | |
1048 | .and_then(move |resp| { | |
1049 | let status = resp.status(); | |
1050 | if !status.is_success() { | |
1051 | future::Either::A( | |
1052 | H2Client::h2api_response(resp) | |
1053 | .and_then(|_| { bail!("unknown error"); }) | |
1054 | ) | |
1055 | } else { | |
984a7c35 DM |
1056 | let mut body = resp.into_body(); |
1057 | let mut release_capacity = body.release_capacity().clone(); | |
1058 | ||
dd066d28 | 1059 | future::Either::B( |
984a7c35 | 1060 | body |
dd066d28 DM |
1061 | .map_err(Error::from) |
1062 | .fold(output, move |mut acc, chunk| { | |
984a7c35 | 1063 | let _ = release_capacity.release_capacity(chunk.len()); |
dd066d28 DM |
1064 | acc.write_all(&chunk)?; |
1065 | Ok::<_, Error>(acc) | |
1066 | }) | |
1067 | ) | |
1068 | } | |
1069 | }) | |
1070 | }) | |
1071 | } | |
1072 | ||
9af37c8f DM |
1073 | pub fn upload(&self, path: &str, param: Option<Value>, data: Vec<u8>) -> impl Future<Item=Value, Error=Error> { |
1074 | let request = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1075 | ||
9af37c8f DM |
1076 | self.h2.clone() |
1077 | .ready() | |
1078 | .map_err(Error::from) | |
1079 | .and_then(move |mut send_request| { | |
1080 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
1081 | PipeToSendStream::new(bytes::Bytes::from(data), stream) | |
1082 | .and_then(|_| { | |
1083 | response | |
1084 | .map_err(Error::from) | |
1085 | .and_then(Self::h2api_response) | |
1086 | }) | |
1087 | }) | |
1088 | } | |
adec8ea2 | 1089 | |
b57cb264 | 1090 | fn request( |
9af37c8f | 1091 | &self, |
b57cb264 DM |
1092 | request: Request<()>, |
1093 | ) -> impl Future<Item=Value, Error=Error> { | |
1094 | ||
9af37c8f | 1095 | self.send_request(request, None) |
82ab7230 DM |
1096 | .and_then(move |response| { |
1097 | response | |
1098 | .map_err(Error::from) | |
1099 | .and_then(Self::h2api_response) | |
1100 | }) | |
1101 | } | |
1102 | ||
1103 | fn send_request( | |
9af37c8f | 1104 | &self, |
82ab7230 DM |
1105 | request: Request<()>, |
1106 | data: Option<bytes::Bytes>, | |
1107 | ) -> impl Future<Item=h2::client::ResponseFuture, Error=Error> { | |
1108 | ||
9af37c8f | 1109 | self.h2.clone() |
10130cf4 DM |
1110 | .ready() |
1111 | .map_err(Error::from) | |
1112 | .and_then(move |mut send_request| { | |
82ab7230 DM |
1113 | if let Some(data) = data { |
1114 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
f98ac774 | 1115 | future::Either::A(PipeToSendStream::new(data, stream) |
82ab7230 DM |
1116 | .and_then(move |_| { |
1117 | future::ok(response) | |
1118 | })) | |
1119 | } else { | |
1120 | let (response, _stream) = send_request.send_request(request, true).unwrap(); | |
1121 | future::Either::B(future::ok(response)) | |
1122 | } | |
b57cb264 DM |
1123 | }) |
1124 | } | |
1125 | ||
1126 | fn h2api_response(response: Response<h2::RecvStream>) -> impl Future<Item=Value, Error=Error> { | |
1127 | ||
1128 | let status = response.status(); | |
1129 | ||
1130 | let (_head, mut body) = response.into_parts(); | |
1131 | ||
1132 | // The `release_capacity` handle allows the caller to manage | |
1133 | // flow control. | |
1134 | // | |
1135 | // Whenever data is received, the caller is responsible for | |
1136 | // releasing capacity back to the server once it has freed | |
1137 | // the data from memory. | |
1138 | let mut release_capacity = body.release_capacity().clone(); | |
1139 | ||
1140 | body | |
1141 | .map(move |chunk| { | |
b57cb264 DM |
1142 | // Let the server send more data. |
1143 | let _ = release_capacity.release_capacity(chunk.len()); | |
1144 | chunk | |
1145 | }) | |
1146 | .concat2() | |
1147 | .map_err(Error::from) | |
1148 | .and_then(move |data| { | |
b57cb264 DM |
1149 | let text = String::from_utf8(data.to_vec()).unwrap(); |
1150 | if status.is_success() { | |
1151 | if text.len() > 0 { | |
1152 | let mut value: Value = serde_json::from_str(&text)?; | |
1153 | if let Some(map) = value.as_object_mut() { | |
1154 | if let Some(data) = map.remove("data") { | |
1155 | return Ok(data); | |
1156 | } | |
1157 | } | |
1158 | bail!("got result without data property"); | |
1159 | } else { | |
1160 | Ok(Value::Null) | |
1161 | } | |
1162 | } else { | |
1163 | bail!("HTTP Error {}: {}", status, text); | |
1164 | } | |
1165 | }) | |
1166 | } | |
1167 | ||
eb2bdd1b | 1168 | // Note: We always encode parameters with the url |
b57cb264 DM |
1169 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> { |
1170 | let path = path.trim_matches('/'); | |
b57cb264 DM |
1171 | |
1172 | if let Some(data) = data { | |
1173 | let query = tools::json_object_to_query(data)?; | |
eb2bdd1b DM |
1174 | // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side |
1175 | if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); } | |
b57cb264 | 1176 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; |
eb2bdd1b | 1177 | let request = Request::builder() |
b57cb264 DM |
1178 | .method(method) |
1179 | .uri(url) | |
1180 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1181 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1182 | .body(())?; | |
1183 | return Ok(request); | |
eb2bdd1b DM |
1184 | } else { |
1185 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; | |
1186 | let request = Request::builder() | |
1187 | .method(method) | |
1188 | .uri(url) | |
1189 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1190 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1191 | .body(())?; | |
b57cb264 | 1192 | |
eb2bdd1b DM |
1193 | Ok(request) |
1194 | } | |
b57cb264 DM |
1195 | } |
1196 | } |