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