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