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