]>
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 | ||
9d135fe6 DM |
629 | pub fn upload_blob<R: std::io::Read>( |
630 | &self, | |
631 | mut reader: R, | |
632 | file_name: &str, | |
633 | ) -> impl Future<Item=BackupStats, Error=Error> { | |
634 | ||
635 | let h2 = self.h2.clone(); | |
636 | let file_name = file_name.to_owned(); | |
637 | ||
638 | futures::future::ok(()) | |
639 | .and_then(move |_| { | |
640 | let mut raw_data = Vec::new(); | |
641 | // fixme: avoid loading into memory | |
642 | reader.read_to_end(&mut raw_data)?; | |
643 | Ok(raw_data) | |
644 | }) | |
645 | .and_then(move |raw_data| { | |
646 | let csum = openssl::sha::sha256(&raw_data); | |
647 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); | |
648 | let size = raw_data.len() as u64; // fixme: should be decoded size instead?? | |
649 | h2.upload("blob", Some(param), raw_data) | |
650 | .map(move |_| { | |
651 | BackupStats { size, csum } | |
652 | }) | |
653 | }) | |
654 | } | |
655 | ||
9f46c7de DM |
656 | pub fn upload_blob_from_data( |
657 | &self, | |
658 | data: Vec<u8>, | |
659 | file_name: &str, | |
660 | crypt_config: Option<Arc<CryptConfig>>, | |
661 | compress: bool, | |
b335f5b7 | 662 | sign_only: bool, |
2c3891d1 | 663 | ) -> impl Future<Item=BackupStats, Error=Error> { |
9f46c7de DM |
664 | |
665 | let h2 = self.h2.clone(); | |
666 | let file_name = file_name.to_owned(); | |
2c3891d1 | 667 | let size = data.len() as u64; |
9f46c7de DM |
668 | |
669 | futures::future::ok(()) | |
670 | .and_then(move |_| { | |
9025312a | 671 | let blob = if let Some(crypt_config) = crypt_config { |
b335f5b7 DM |
672 | if sign_only { |
673 | DataBlob::create_signed(&data, crypt_config, compress)? | |
674 | } else { | |
9025312a | 675 | DataBlob::encode(&data, Some(crypt_config.clone()), compress)? |
b335f5b7 | 676 | } |
9f46c7de DM |
677 | } else { |
678 | DataBlob::encode(&data, None, compress)? | |
679 | }; | |
680 | ||
681 | let raw_data = blob.into_inner(); | |
682 | Ok(raw_data) | |
683 | }) | |
684 | .and_then(move |raw_data| { | |
c807d231 | 685 | let csum = openssl::sha::sha256(&raw_data); |
9f46c7de DM |
686 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); |
687 | h2.upload("blob", Some(param), raw_data) | |
2c3891d1 | 688 | .map(move |_| { |
c807d231 | 689 | BackupStats { size, csum } |
2c3891d1 | 690 | }) |
9f46c7de DM |
691 | }) |
692 | } | |
693 | ||
694 | pub fn upload_blob_from_file<P: AsRef<std::path::Path>>( | |
39d6846e | 695 | &self, |
ec8a9bb9 | 696 | src_path: P, |
39d6846e | 697 | file_name: &str, |
cb08ac3e DM |
698 | crypt_config: Option<Arc<CryptConfig>>, |
699 | compress: bool, | |
2c3891d1 | 700 | ) -> impl Future<Item=BackupStats, Error=Error> { |
39d6846e DM |
701 | |
702 | let h2 = self.h2.clone(); | |
703 | let file_name = file_name.to_owned(); | |
ec8a9bb9 | 704 | let src_path = src_path.as_ref().to_owned(); |
39d6846e | 705 | |
ef39bf95 DM |
706 | let task = tokio::fs::File::open(src_path.clone()) |
707 | .map_err(move |err| format_err!("unable to open file {:?} - {}", src_path, err)) | |
cb08ac3e | 708 | .and_then(move |file| { |
39d6846e DM |
709 | let contents = vec![]; |
710 | tokio::io::read_to_end(file, contents) | |
711 | .map_err(Error::from) | |
712 | .and_then(move |(_, contents)| { | |
9025312a | 713 | let blob = DataBlob::encode(&contents, crypt_config, compress)?; |
cb08ac3e | 714 | let raw_data = blob.into_inner(); |
bd15e96d | 715 | Ok((raw_data, contents.len() as u64)) |
cb08ac3e | 716 | }) |
2c3891d1 | 717 | .and_then(move |(raw_data, size)| { |
c807d231 | 718 | let csum = openssl::sha::sha256(&raw_data); |
cb08ac3e DM |
719 | let param = json!({"encoded-size": raw_data.len(), "file-name": file_name }); |
720 | h2.upload("blob", Some(param), raw_data) | |
2c3891d1 | 721 | .map(move |_| { |
bd15e96d | 722 | BackupStats { size, csum } |
2c3891d1 | 723 | }) |
39d6846e DM |
724 | }) |
725 | }); | |
726 | ||
727 | task | |
728 | } | |
729 | ||
a42fa400 | 730 | pub fn upload_stream( |
d6f204ed DM |
731 | &self, |
732 | archive_name: &str, | |
733 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, | |
a42fa400 DM |
734 | prefix: &str, |
735 | fixed_size: Option<u64>, | |
f98ac774 | 736 | crypt_config: Option<Arc<CryptConfig>>, |
2c3891d1 | 737 | ) -> impl Future<Item=BackupStats, Error=Error> { |
d6f204ed DM |
738 | |
739 | let known_chunks = Arc::new(Mutex::new(HashSet::new())); | |
740 | ||
741 | let h2 = self.h2.clone(); | |
742 | let h2_2 = self.h2.clone(); | |
743 | let h2_3 = self.h2.clone(); | |
744 | let h2_4 = self.h2.clone(); | |
745 | ||
a42fa400 DM |
746 | let mut param = json!({ "archive-name": archive_name }); |
747 | if let Some(size) = fixed_size { | |
748 | param["size"] = size.into(); | |
749 | } | |
750 | ||
751 | let index_path = format!("{}_index", prefix); | |
a42fa400 | 752 | let close_path = format!("{}_close", prefix); |
d6f204ed | 753 | |
642322b4 DM |
754 | let prefix = prefix.to_owned(); |
755 | ||
a42fa400 | 756 | Self::download_chunk_list(h2, &index_path, archive_name, known_chunks.clone()) |
d6f204ed | 757 | .and_then(move |_| { |
a42fa400 | 758 | h2_2.post(&index_path, Some(param)) |
d6f204ed DM |
759 | }) |
760 | .and_then(move |res| { | |
761 | let wid = res.as_u64().unwrap(); | |
f98ac774 | 762 | Self::upload_chunk_info_stream(h2_3, wid, stream, &prefix, known_chunks.clone(), crypt_config) |
dbed4c8c | 763 | .and_then(move |(chunk_count, size, _speed, csum)| { |
8bea85b4 DM |
764 | let param = json!({ |
765 | "wid": wid , | |
766 | "chunk-count": chunk_count, | |
767 | "size": size, | |
768 | }); | |
a42fa400 | 769 | h2_4.post(&close_path, Some(param)) |
2c3891d1 | 770 | .map(move |_| { |
dbed4c8c | 771 | BackupStats { size: size as u64, csum } |
2c3891d1 DM |
772 | }) |
773 | }) | |
d6f204ed DM |
774 | }) |
775 | } | |
776 | ||
6ab34afa | 777 | fn response_queue() -> ( |
82ab7230 DM |
778 | mpsc::Sender<h2::client::ResponseFuture>, |
779 | sync::oneshot::Receiver<Result<(), Error>> | |
780 | ) { | |
781 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(100); | |
782 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); | |
adec8ea2 | 783 | |
82ab7230 DM |
784 | hyper::rt::spawn( |
785 | verify_queue_rx | |
786 | .map_err(Error::from) | |
787 | .for_each(|response: h2::client::ResponseFuture| { | |
788 | response | |
789 | .map_err(Error::from) | |
9af37c8f | 790 | .and_then(H2Client::h2api_response) |
82ab7230 DM |
791 | .and_then(|result| { |
792 | println!("RESPONSE: {:?}", result); | |
793 | Ok(()) | |
794 | }) | |
795 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
796 | }) | |
797 | .then(|result| | |
798 | verify_result_tx.send(result) | |
799 | ) | |
800 | .map_err(|_| { /* ignore closed channel */ }) | |
801 | ); | |
adec8ea2 | 802 | |
82ab7230 DM |
803 | (verify_queue_tx, verify_result_rx) |
804 | } | |
805 | ||
642322b4 | 806 | fn append_chunk_queue(h2: H2Client, wid: u64, path: String) -> ( |
174ad378 | 807 | mpsc::Sender<(MergedChunkInfo, Option<h2::client::ResponseFuture>)>, |
05cba08c DM |
808 | sync::oneshot::Receiver<Result<(), Error>> |
809 | ) { | |
771953f9 | 810 | let (verify_queue_tx, verify_queue_rx) = mpsc::channel(64); |
05cba08c DM |
811 | let (verify_result_tx, verify_result_rx) = sync::oneshot::channel(); |
812 | ||
813 | let h2_2 = h2.clone(); | |
814 | ||
815 | hyper::rt::spawn( | |
816 | verify_queue_rx | |
817 | .map_err(Error::from) | |
174ad378 DM |
818 | .and_then(move |(merged_chunk_info, response): (MergedChunkInfo, Option<h2::client::ResponseFuture>)| { |
819 | match (response, merged_chunk_info) { | |
820 | (Some(response), MergedChunkInfo::Known(list)) => { | |
05cba08c | 821 | future::Either::A( |
174ad378 DM |
822 | response |
823 | .map_err(Error::from) | |
824 | .and_then(H2Client::h2api_response) | |
771953f9 | 825 | .and_then(move |_result| { |
174ad378 | 826 | Ok(MergedChunkInfo::Known(list)) |
05cba08c | 827 | }) |
05cba08c DM |
828 | ) |
829 | } | |
174ad378 | 830 | (None, MergedChunkInfo::Known(list)) => { |
05cba08c DM |
831 | future::Either::B(future::ok(MergedChunkInfo::Known(list))) |
832 | } | |
174ad378 | 833 | _ => unreachable!(), |
05cba08c DM |
834 | } |
835 | }) | |
62436222 | 836 | .merge_known_chunks() |
05cba08c DM |
837 | .and_then(move |merged_chunk_info| { |
838 | match merged_chunk_info { | |
839 | MergedChunkInfo::Known(chunk_list) => { | |
840 | let mut digest_list = vec![]; | |
841 | let mut offset_list = vec![]; | |
842 | for (offset, digest) in chunk_list { | |
bffd40d6 | 843 | //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset); |
e18a6c9e | 844 | digest_list.push(digest_to_hex(&digest)); |
05cba08c DM |
845 | offset_list.push(offset); |
846 | } | |
847 | println!("append chunks list len ({})", digest_list.len()); | |
848 | let param = json!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }); | |
a42fa400 | 849 | let mut request = H2Client::request_builder("localhost", "PUT", &path, None).unwrap(); |
05cba08c DM |
850 | request.headers_mut().insert(hyper::header::CONTENT_TYPE, HeaderValue::from_static("application/json")); |
851 | let param_data = bytes::Bytes::from(param.to_string().as_bytes()); | |
852 | let upload_data = Some(param_data); | |
853 | h2_2.send_request(request, upload_data) | |
854 | .and_then(move |response| { | |
855 | response | |
856 | .map_err(Error::from) | |
857 | .and_then(H2Client::h2api_response) | |
858 | .and_then(|_| Ok(())) | |
859 | }) | |
860 | .map_err(|err| format_err!("pipelined request failed: {}", err)) | |
861 | } | |
862 | _ => unreachable!(), | |
863 | } | |
864 | }) | |
865 | .for_each(|_| Ok(())) | |
866 | .then(|result| | |
867 | verify_result_tx.send(result) | |
868 | ) | |
869 | .map_err(|_| { /* ignore closed channel */ }) | |
870 | ); | |
871 | ||
872 | (verify_queue_tx, verify_result_rx) | |
873 | } | |
874 | ||
6ab34afa | 875 | fn download_chunk_list( |
9af37c8f | 876 | h2: H2Client, |
553610b4 DM |
877 | path: &str, |
878 | archive_name: &str, | |
879 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, | |
880 | ) -> impl Future<Item=(), Error=Error> { | |
881 | ||
882 | let param = json!({ "archive-name": archive_name }); | |
9af37c8f | 883 | let request = H2Client::request_builder("localhost", "GET", path, Some(param)).unwrap(); |
553610b4 | 884 | |
9af37c8f | 885 | h2.send_request(request, None) |
553610b4 DM |
886 | .and_then(move |response| { |
887 | response | |
888 | .map_err(Error::from) | |
889 | .and_then(move |resp| { | |
890 | let status = resp.status(); | |
7dd1bcac | 891 | |
553610b4 | 892 | if !status.is_success() { |
7dd1bcac DM |
893 | future::Either::A(H2Client::h2api_response(resp).and_then(|_| { bail!("unknown error"); })) |
894 | } else { | |
895 | future::Either::B(future::ok(resp.into_body())) | |
553610b4 | 896 | } |
553610b4 DM |
897 | }) |
898 | .and_then(move |mut body| { | |
899 | ||
900 | let mut release_capacity = body.release_capacity().clone(); | |
901 | ||
986bef16 | 902 | DigestListDecoder::new(body.map_err(Error::from)) |
553610b4 DM |
903 | .for_each(move |chunk| { |
904 | let _ = release_capacity.release_capacity(chunk.len()); | |
e18a6c9e | 905 | println!("GOT DOWNLOAD {}", digest_to_hex(&chunk)); |
553610b4 DM |
906 | known_chunks.lock().unwrap().insert(chunk); |
907 | Ok(()) | |
908 | }) | |
909 | }) | |
910 | }) | |
911 | } | |
912 | ||
a42fa400 | 913 | fn upload_chunk_info_stream( |
9af37c8f | 914 | h2: H2Client, |
82ab7230 | 915 | wid: u64, |
f98ac774 | 916 | stream: impl Stream<Item=bytes::BytesMut, Error=Error>, |
642322b4 | 917 | prefix: &str, |
553610b4 | 918 | known_chunks: Arc<Mutex<HashSet<[u8;32]>>>, |
f98ac774 | 919 | crypt_config: Option<Arc<CryptConfig>>, |
dbed4c8c | 920 | ) -> impl Future<Item=(usize, usize, usize, [u8; 32]), Error=Error> { |
adec8ea2 | 921 | |
82ab7230 DM |
922 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); |
923 | let repeat2 = repeat.clone(); | |
adec8ea2 | 924 | |
82ab7230 DM |
925 | let stream_len = std::sync::Arc::new(AtomicUsize::new(0)); |
926 | let stream_len2 = stream_len.clone(); | |
9c9ad941 | 927 | |
642322b4 DM |
928 | let append_chunk_path = format!("{}_index", prefix); |
929 | let upload_chunk_path = format!("{}_chunk", prefix); | |
930 | ||
931 | let (upload_queue, upload_result) = Self::append_chunk_queue(h2.clone(), wid, append_chunk_path.to_owned()); | |
9c9ad941 | 932 | |
82ab7230 | 933 | let start_time = std::time::Instant::now(); |
9c9ad941 | 934 | |
dbed4c8c DM |
935 | let index_csum = Arc::new(Mutex::new(Some(openssl::sha::Sha256::new()))); |
936 | let index_csum_2 = index_csum.clone(); | |
937 | ||
82ab7230 | 938 | stream |
f98ac774 DM |
939 | .and_then(move |data| { |
940 | ||
941 | let chunk_len = data.len(); | |
942 | ||
82ab7230 | 943 | repeat.fetch_add(1, Ordering::SeqCst); |
f98ac774 DM |
944 | let offset = stream_len.fetch_add(chunk_len, Ordering::SeqCst) as u64; |
945 | ||
946 | let mut chunk_builder = DataChunkBuilder::new(data.as_ref()) | |
947 | .compress(true); | |
948 | ||
949 | if let Some(ref crypt_config) = crypt_config { | |
950 | chunk_builder = chunk_builder.crypt_config(crypt_config); | |
951 | } | |
62436222 DM |
952 | |
953 | let mut known_chunks = known_chunks.lock().unwrap(); | |
f98ac774 | 954 | let digest = chunk_builder.digest(); |
dbed4c8c DM |
955 | |
956 | let mut guard = index_csum.lock().unwrap(); | |
957 | let csum = guard.as_mut().unwrap(); | |
958 | csum.update(&offset.to_le_bytes()); | |
959 | csum.update(digest); | |
960 | ||
f98ac774 | 961 | let chunk_is_known = known_chunks.contains(digest); |
62436222 | 962 | if chunk_is_known { |
f98ac774 | 963 | Ok(MergedChunkInfo::Known(vec![(offset, *digest)])) |
62436222 | 964 | } else { |
f98ac774 DM |
965 | known_chunks.insert(*digest); |
966 | let chunk = chunk_builder.build()?; | |
967 | Ok(MergedChunkInfo::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset })) | |
62436222 | 968 | } |
aa1b2e04 | 969 | }) |
62436222 | 970 | .merge_known_chunks() |
aa1b2e04 | 971 | .for_each(move |merged_chunk_info| { |
174ad378 DM |
972 | |
973 | if let MergedChunkInfo::New(chunk_info) = merged_chunk_info { | |
974 | let offset = chunk_info.offset; | |
f98ac774 | 975 | let digest = *chunk_info.chunk.digest(); |
e18a6c9e | 976 | let digest_str = digest_to_hex(&digest); |
174ad378 DM |
977 | let upload_queue = upload_queue.clone(); |
978 | ||
f98ac774 DM |
979 | println!("upload new chunk {} ({} bytes, offset {})", digest_str, |
980 | chunk_info.chunk_len, offset); | |
981 | ||
982 | let chunk_data = chunk_info.chunk.raw_data(); | |
983 | let param = json!({ | |
984 | "wid": wid, | |
985 | "digest": digest_str, | |
986 | "size": chunk_info.chunk_len, | |
987 | "encoded-size": chunk_data.len(), | |
988 | }); | |
174ad378 | 989 | |
642322b4 | 990 | let request = H2Client::request_builder("localhost", "POST", &upload_chunk_path, Some(param)).unwrap(); |
f98ac774 | 991 | let upload_data = Some(bytes::Bytes::from(chunk_data)); |
174ad378 | 992 | |
8de20e5c | 993 | let new_info = MergedChunkInfo::Known(vec![(offset, digest)]); |
174ad378 DM |
994 | |
995 | future::Either::A( | |
996 | h2.send_request(request, upload_data) | |
997 | .and_then(move |response| { | |
998 | upload_queue.clone().send((new_info, Some(response))) | |
999 | .map(|_| ()).map_err(Error::from) | |
1000 | }) | |
1001 | ) | |
1002 | } else { | |
1003 | ||
1004 | future::Either::B( | |
1005 | upload_queue.clone().send((merged_chunk_info, None)) | |
1006 | .map(|_| ()).map_err(Error::from) | |
1007 | ) | |
1008 | } | |
82ab7230 DM |
1009 | }) |
1010 | .then(move |result| { | |
684233aa | 1011 | //println!("RESULT {:?}", result); |
82ab7230 DM |
1012 | upload_result.map_err(Error::from).and_then(|upload1_result| { |
1013 | Ok(upload1_result.and(result)) | |
1014 | }) | |
1015 | }) | |
1016 | .flatten() | |
1017 | .and_then(move |_| { | |
1018 | let repeat = repeat2.load(Ordering::SeqCst); | |
1019 | let stream_len = stream_len2.load(Ordering::SeqCst); | |
1020 | let speed = ((stream_len*1000000)/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
1021 | println!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat, start_time.elapsed().as_secs(), speed); | |
1022 | if repeat > 0 { | |
1023 | println!("Average chunk size was {} bytes.", stream_len/repeat); | |
1024 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
1025 | } | |
dbed4c8c DM |
1026 | |
1027 | let mut guard = index_csum_2.lock().unwrap(); | |
1028 | let csum = guard.take().unwrap().finish(); | |
1029 | ||
1030 | Ok((repeat, stream_len, speed, csum)) | |
82ab7230 DM |
1031 | }) |
1032 | } | |
1033 | ||
1034 | pub fn upload_speedtest(&self) -> impl Future<Item=usize, Error=Error> { | |
1035 | ||
1036 | let mut data = vec![]; | |
1037 | // generate pseudo random byte sequence | |
1038 | for i in 0..1024*1024 { | |
1039 | for j in 0..4 { | |
1040 | let byte = ((i >> (j<<3))&0xff) as u8; | |
1041 | data.push(byte); | |
1042 | } | |
1043 | } | |
1044 | ||
1045 | let item_len = data.len(); | |
1046 | ||
1047 | let repeat = std::sync::Arc::new(AtomicUsize::new(0)); | |
1048 | let repeat2 = repeat.clone(); | |
1049 | ||
6ab34afa | 1050 | let (upload_queue, upload_result) = Self::response_queue(); |
82ab7230 DM |
1051 | |
1052 | let start_time = std::time::Instant::now(); | |
1053 | ||
6ab34afa | 1054 | let h2 = self.h2.clone(); |
82ab7230 DM |
1055 | |
1056 | futures::stream::repeat(data) | |
1057 | .take_while(move |_| { | |
1058 | repeat.fetch_add(1, Ordering::SeqCst); | |
1059 | Ok(start_time.elapsed().as_secs() < 5) | |
1060 | }) | |
1061 | .for_each(move |data| { | |
6ab34afa | 1062 | let h2 = h2.clone(); |
82ab7230 DM |
1063 | |
1064 | let upload_queue = upload_queue.clone(); | |
1065 | ||
1066 | println!("send test data ({} bytes)", data.len()); | |
9af37c8f DM |
1067 | let request = H2Client::request_builder("localhost", "POST", "speedtest", None).unwrap(); |
1068 | h2.send_request(request, Some(bytes::Bytes::from(data))) | |
82ab7230 DM |
1069 | .and_then(move |response| { |
1070 | upload_queue.send(response) | |
1071 | .map(|_| ()).map_err(Error::from) | |
adec8ea2 DM |
1072 | }) |
1073 | }) | |
82ab7230 DM |
1074 | .then(move |result| { |
1075 | println!("RESULT {:?}", result); | |
1076 | upload_result.map_err(Error::from).and_then(|upload1_result| { | |
1077 | Ok(upload1_result.and(result)) | |
1078 | }) | |
1079 | }) | |
1080 | .flatten() | |
1081 | .and_then(move |_| { | |
1082 | let repeat = repeat2.load(Ordering::SeqCst); | |
1083 | println!("Uploaded {} chunks in {} seconds.", repeat, start_time.elapsed().as_secs()); | |
1084 | let speed = ((item_len*1000000*(repeat as usize))/(1024*1024))/(start_time.elapsed().as_micros() as usize); | |
1085 | if repeat > 0 { | |
1086 | println!("Time per request: {} microseconds.", (start_time.elapsed().as_micros())/(repeat as u128)); | |
1087 | } | |
1088 | Ok(speed) | |
1089 | }) | |
adec8ea2 | 1090 | } |
9af37c8f DM |
1091 | } |
1092 | ||
1093 | #[derive(Clone)] | |
1094 | pub struct H2Client { | |
1095 | h2: h2::client::SendRequest<bytes::Bytes>, | |
1096 | } | |
1097 | ||
1098 | impl H2Client { | |
1099 | ||
1100 | pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self { | |
1101 | Self { h2 } | |
1102 | } | |
1103 | ||
1104 | pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1105 | let req = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1106 | self.request(req) | |
1107 | } | |
1108 | ||
1109 | pub fn put(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1110 | let req = Self::request_builder("localhost", "PUT", path, param).unwrap(); | |
1111 | self.request(req) | |
1112 | } | |
1113 | ||
1114 | pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> { | |
1115 | let req = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1116 | self.request(req) | |
1117 | } | |
1118 | ||
dd066d28 DM |
1119 | pub fn download<W: Write>(&self, path: &str, param: Option<Value>, output: W) -> impl Future<Item=W, Error=Error> { |
1120 | let request = Self::request_builder("localhost", "GET", path, param).unwrap(); | |
1121 | ||
1122 | self.send_request(request, None) | |
1123 | .and_then(move |response| { | |
1124 | response | |
1125 | .map_err(Error::from) | |
1126 | .and_then(move |resp| { | |
1127 | let status = resp.status(); | |
1128 | if !status.is_success() { | |
1129 | future::Either::A( | |
1130 | H2Client::h2api_response(resp) | |
1131 | .and_then(|_| { bail!("unknown error"); }) | |
1132 | ) | |
1133 | } else { | |
984a7c35 DM |
1134 | let mut body = resp.into_body(); |
1135 | let mut release_capacity = body.release_capacity().clone(); | |
1136 | ||
dd066d28 | 1137 | future::Either::B( |
984a7c35 | 1138 | body |
dd066d28 DM |
1139 | .map_err(Error::from) |
1140 | .fold(output, move |mut acc, chunk| { | |
984a7c35 | 1141 | let _ = release_capacity.release_capacity(chunk.len()); |
dd066d28 DM |
1142 | acc.write_all(&chunk)?; |
1143 | Ok::<_, Error>(acc) | |
1144 | }) | |
1145 | ) | |
1146 | } | |
1147 | }) | |
1148 | }) | |
1149 | } | |
1150 | ||
9af37c8f DM |
1151 | pub fn upload(&self, path: &str, param: Option<Value>, data: Vec<u8>) -> impl Future<Item=Value, Error=Error> { |
1152 | let request = Self::request_builder("localhost", "POST", path, param).unwrap(); | |
1153 | ||
9af37c8f DM |
1154 | self.h2.clone() |
1155 | .ready() | |
1156 | .map_err(Error::from) | |
1157 | .and_then(move |mut send_request| { | |
1158 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
1159 | PipeToSendStream::new(bytes::Bytes::from(data), stream) | |
1160 | .and_then(|_| { | |
1161 | response | |
1162 | .map_err(Error::from) | |
1163 | .and_then(Self::h2api_response) | |
1164 | }) | |
1165 | }) | |
1166 | } | |
adec8ea2 | 1167 | |
b57cb264 | 1168 | fn request( |
9af37c8f | 1169 | &self, |
b57cb264 DM |
1170 | request: Request<()>, |
1171 | ) -> impl Future<Item=Value, Error=Error> { | |
1172 | ||
9af37c8f | 1173 | self.send_request(request, None) |
82ab7230 DM |
1174 | .and_then(move |response| { |
1175 | response | |
1176 | .map_err(Error::from) | |
1177 | .and_then(Self::h2api_response) | |
1178 | }) | |
1179 | } | |
1180 | ||
1181 | fn send_request( | |
9af37c8f | 1182 | &self, |
82ab7230 DM |
1183 | request: Request<()>, |
1184 | data: Option<bytes::Bytes>, | |
1185 | ) -> impl Future<Item=h2::client::ResponseFuture, Error=Error> { | |
1186 | ||
9af37c8f | 1187 | self.h2.clone() |
10130cf4 DM |
1188 | .ready() |
1189 | .map_err(Error::from) | |
1190 | .and_then(move |mut send_request| { | |
82ab7230 DM |
1191 | if let Some(data) = data { |
1192 | let (response, stream) = send_request.send_request(request, false).unwrap(); | |
f98ac774 | 1193 | future::Either::A(PipeToSendStream::new(data, stream) |
82ab7230 DM |
1194 | .and_then(move |_| { |
1195 | future::ok(response) | |
1196 | })) | |
1197 | } else { | |
1198 | let (response, _stream) = send_request.send_request(request, true).unwrap(); | |
1199 | future::Either::B(future::ok(response)) | |
1200 | } | |
b57cb264 DM |
1201 | }) |
1202 | } | |
1203 | ||
1204 | fn h2api_response(response: Response<h2::RecvStream>) -> impl Future<Item=Value, Error=Error> { | |
1205 | ||
1206 | let status = response.status(); | |
1207 | ||
1208 | let (_head, mut body) = response.into_parts(); | |
1209 | ||
1210 | // The `release_capacity` handle allows the caller to manage | |
1211 | // flow control. | |
1212 | // | |
1213 | // Whenever data is received, the caller is responsible for | |
1214 | // releasing capacity back to the server once it has freed | |
1215 | // the data from memory. | |
1216 | let mut release_capacity = body.release_capacity().clone(); | |
1217 | ||
1218 | body | |
1219 | .map(move |chunk| { | |
b57cb264 DM |
1220 | // Let the server send more data. |
1221 | let _ = release_capacity.release_capacity(chunk.len()); | |
1222 | chunk | |
1223 | }) | |
1224 | .concat2() | |
1225 | .map_err(Error::from) | |
1226 | .and_then(move |data| { | |
b57cb264 DM |
1227 | let text = String::from_utf8(data.to_vec()).unwrap(); |
1228 | if status.is_success() { | |
1229 | if text.len() > 0 { | |
1230 | let mut value: Value = serde_json::from_str(&text)?; | |
1231 | if let Some(map) = value.as_object_mut() { | |
1232 | if let Some(data) = map.remove("data") { | |
1233 | return Ok(data); | |
1234 | } | |
1235 | } | |
1236 | bail!("got result without data property"); | |
1237 | } else { | |
1238 | Ok(Value::Null) | |
1239 | } | |
1240 | } else { | |
1241 | bail!("HTTP Error {}: {}", status, text); | |
1242 | } | |
1243 | }) | |
1244 | } | |
1245 | ||
eb2bdd1b | 1246 | // Note: We always encode parameters with the url |
b57cb264 DM |
1247 | pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> { |
1248 | let path = path.trim_matches('/'); | |
b57cb264 DM |
1249 | |
1250 | if let Some(data) = data { | |
1251 | let query = tools::json_object_to_query(data)?; | |
eb2bdd1b DM |
1252 | // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side |
1253 | if query.len() > 4096 { bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len()); } | |
b57cb264 | 1254 | let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?; |
eb2bdd1b | 1255 | let request = Request::builder() |
b57cb264 DM |
1256 | .method(method) |
1257 | .uri(url) | |
1258 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1259 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1260 | .body(())?; | |
1261 | return Ok(request); | |
eb2bdd1b DM |
1262 | } else { |
1263 | let url: Uri = format!("https://{}:8007/{}", server, path).parse()?; | |
1264 | let request = Request::builder() | |
1265 | .method(method) | |
1266 | .uri(url) | |
1267 | .header("User-Agent", "proxmox-backup-client/1.0") | |
1268 | .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
1269 | .body(())?; | |
b57cb264 | 1270 | |
eb2bdd1b DM |
1271 | Ok(request) |
1272 | } | |
b57cb264 DM |
1273 | } |
1274 | } |