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