5 use hyper
::client
::Client
;
6 use xdg
::BaseDirectories
;
7 use chrono
::{DateTime, Utc}
;
8 use std
::collections
::HashSet
;
9 use std
::sync
::{Arc, Mutex}
;
12 use http
::{Request, Response}
;
13 use http
::header
::HeaderValue
;
16 use futures
::stream
::Stream
;
17 use std
::sync
::atomic
::{AtomicUsize, Ordering}
;
18 use tokio
::sync
::mpsc
;
19 use openssl
::ssl
::{SslConnector, SslMethod}
;
21 use serde_json
::{json, Value}
;
22 use url
::percent_encoding
::{percent_encode, DEFAULT_ENCODE_SET}
;
26 fs
::{file_get_json, file_set_contents}
,
29 use crate::tools
::{self, BroadcastFuture, tty}
;
30 use crate::tools
::futures
::{cancellable, Canceller}
;
31 use super::pipe_to_stream
::*;
32 use super::merge_known_chunks
::*;
43 /// HTTP(S) API client
44 pub struct HttpClient
{
45 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
47 auth
: BroadcastFuture
<AuthInfo
>,
50 fn store_ticket_info(server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
52 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
54 // usually /run/user/<uid>/...
55 let path
= base
.place_runtime_file("tickets")?
;
57 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
59 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
61 let now
= Utc
::now().timestamp();
63 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
65 let mut new_data
= json
!({}
);
67 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
69 let empty
= serde_json
::map
::Map
::new();
70 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
71 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
72 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
73 let age
= now
- timestamp
;
74 if age
< ticket_lifetime
{
75 new_data
[server
][username
] = uinfo
.clone();
81 file_set_contents(path
, new_data
.to_string().as_bytes(), Some(mode
))?
;
86 fn load_ticket_info(server
: &str, username
: &str) -> Option
<(String
, String
)> {
87 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
92 // usually /run/user/<uid>/...
93 let path
= match base
.place_runtime_file("tickets") {
98 let data
= match file_get_json(&path
, None
) {
103 let now
= Utc
::now().timestamp();
105 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
107 if let Some(uinfo
) = data
[server
][username
].as_object() {
108 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
109 let age
= now
- timestamp
;
110 if age
< ticket_lifetime
{
111 let ticket
= match uinfo
["ticket"].as_str() {
115 let token
= match uinfo
["token"].as_str() {
119 return Some((ticket
.to_owned(), token
.to_owned()));
129 pub fn new(server
: &str, username
: &str) -> Result
<Self, Error
> {
130 let client
= Self::build_client();
132 let password
= if let Some((ticket
, _token
)) = load_ticket_info(server
, username
) {
135 Self::get_password(&username
)?
138 let login
= Self::credentials(client
.clone(), server
.to_owned(), username
.to_owned(), password
);
142 server
: String
::from(server
),
143 auth
: BroadcastFuture
::new(login
),
147 fn get_password(_username
: &str) -> Result
<String
, Error
> {
148 use std
::env
::VarError
::*;
149 match std
::env
::var("PBS_PASSWORD") {
150 Ok(p
) => return Ok(p
),
151 Err(NotUnicode(_
)) => bail
!("PBS_PASSWORD contains bad characters"),
153 // Try another method
157 // If we're on a TTY, query the user for a password
158 if tty
::stdin_isatty() {
159 return Ok(String
::from_utf8(tty
::read_password("Password: ")?
)?
);
162 bail
!("no password input mechanism available");
165 fn build_client() -> Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>> {
167 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
169 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
); // fixme!
171 let mut httpc
= hyper
::client
::HttpConnector
::new(1);
172 httpc
.set_nodelay(true); // important for h2 download performance!
173 httpc
.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance!
174 httpc
.enforce_http(false); // we want https...
176 let https
= hyper_openssl
::HttpsConnector
::with_connector(httpc
, ssl_connector_builder
).unwrap();
179 //.http2_initial_stream_window_size( (1 << 31) - 2)
180 //.http2_initial_connection_window_size( (1 << 31) - 2)
181 .build
::<_
, Body
>(https
)
184 pub fn request(&self, mut req
: Request
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
186 let login
= self.auth
.listen();
188 let client
= self.client
.clone();
190 login
.and_then(move |auth
| {
192 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
193 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
194 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
196 let request
= Self::api_request(client
, req
);
202 pub fn get(&self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
204 let req
= Self::request_builder(&self.server
, "GET", path
, data
).unwrap();
208 pub fn delete(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
210 let req
= Self::request_builder(&self.server
, "DELETE", path
, data
).unwrap();
214 pub fn post(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
216 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
220 pub fn download
<W
: Write
>(&mut self, path
: &str, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
222 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
224 let login
= self.auth
.listen();
226 let client
= self.client
.clone();
228 login
.and_then(move |auth
| {
230 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
231 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
234 .map_err(Error
::from
)
236 let status
= resp
.status();
237 if !status
.is_success() {
239 HttpClient
::api_response(resp
)
240 .and_then(|_
| { bail!("unknown error"); }
)
245 .map_err(Error
::from
)
246 .fold(output
, move |mut acc
, chunk
| {
247 acc
.write_all(&chunk
)?
;
262 ) -> impl Future
<Item
=Value
, Error
=Error
> {
264 let path
= path
.trim_matches('
/'
);
265 let mut url
= format
!("https://{}:8007/{}", &self.server
, path
);
267 if let Some(data
) = data
{
268 let query
= tools
::json_object_to_query(data
).unwrap();
270 url
.push_str(&query
);
273 let url
: Uri
= url
.parse().unwrap();
275 let req
= Request
::builder()
278 .header("User-Agent", "proxmox-backup-client/1.0")
279 .header("Content-Type", content_type
)
280 .body(body
).unwrap();
290 backup_time
: DateTime
<Utc
>,
292 ) -> impl Future
<Item
=Arc
<BackupClient
>, Error
=Error
> {
295 "backup-type": backup_type
,
296 "backup-id": backup_id
,
297 "backup-time": backup_time
.timestamp(),
302 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/backup", Some(param
)).unwrap();
304 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
305 .map(|(h2
, canceller
)| BackupClient
::new(h2
, canceller
))
308 pub fn start_backup_reader(
313 backup_time
: DateTime
<Utc
>,
315 ) -> impl Future
<Item
=Arc
<BackupReader
>, Error
=Error
> {
318 "backup-type": backup_type
,
319 "backup-id": backup_id
,
320 "backup-time": backup_time
.timestamp(),
324 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/reader", Some(param
)).unwrap();
326 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!()))
327 .map(|(h2
, canceller
)| BackupReader
::new(h2
, canceller
))
330 pub fn start_h2_connection(
332 mut req
: Request
<Body
>,
333 protocol_name
: String
,
334 ) -> impl Future
<Item
=(H2Client
, Canceller
), Error
=Error
> {
336 let login
= self.auth
.listen();
337 let client
= self.client
.clone();
339 login
.and_then(move |auth
| {
341 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
342 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
343 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
346 .map_err(Error
::from
)
349 let status
= resp
.status();
350 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
351 future
::Either
::A(Self::api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
353 future
::Either
::B(resp
.into_body().on_upgrade().map_err(Error
::from
))
356 .and_then(|upgraded
| {
357 let max_window_size
= (1 << 31) - 2;
359 h2
::client
::Builder
::new()
360 .initial_connection_window_size(max_window_size
)
361 .initial_window_size(max_window_size
)
362 .max_frame_size(4*1024*1024)
364 .map_err(Error
::from
)
366 .and_then(|(h2
, connection
)| {
367 let connection
= connection
368 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
370 let (connection
, canceller
) = cancellable(connection
)?
;
371 // A cancellable future returns an Option which is None when cancelled and
372 // Some when it finished instead, since we don't care about the return type we
373 // need to map it away:
374 let connection
= connection
.map(|_
| ());
376 // Spawn a new task to drive the connection state
377 hyper
::rt
::spawn(connection
);
379 // Wait until the `SendRequest` handle has available capacity.
381 .map(move |c
| (H2Client
::new(c
), canceller
))
382 .map_err(Error
::from
))
389 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
393 ) -> Box
<dyn Future
<Item
=AuthInfo
, Error
=Error
> + Send
> {
395 let server2
= server
.clone();
397 let create_request
= futures
::future
::lazy(move || {
398 let data
= json
!({ "username": username, "password": password }
);
399 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
400 Self::api_request(client
, req
)
403 let login_future
= create_request
404 .and_then(move |cred
| {
405 let auth
= AuthInfo
{
406 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
407 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
408 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
411 let _
= store_ticket_info(&server2
, &auth
.username
, &auth
.ticket
, &auth
.token
);
416 Box
::new(login_future
)
419 fn api_response(response
: Response
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
421 let status
= response
.status();
426 .map_err(Error
::from
)
427 .and_then(move |data
| {
429 let text
= String
::from_utf8(data
.to_vec()).unwrap();
430 if status
.is_success() {
432 let value
: Value
= serde_json
::from_str(&text
)?
;
438 bail
!("HTTP Error {}: {}", status
, text
);
444 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
446 ) -> impl Future
<Item
=Value
, Error
=Error
> {
449 .map_err(Error
::from
)
450 .and_then(Self::api_response
)
453 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
454 let path
= path
.trim_matches('
/'
);
455 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
457 if let Some(data
) = data
{
458 if method
== "POST" {
459 let request
= Request
::builder()
462 .header("User-Agent", "proxmox-backup-client/1.0")
463 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
464 .body(Body
::from(data
.to_string()))?
;
467 let query
= tools
::json_object_to_query(data
)?
;
468 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
469 let request
= Request
::builder()
472 .header("User-Agent", "proxmox-backup-client/1.0")
473 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
474 .body(Body
::empty())?
;
479 let request
= Request
::builder()
482 .header("User-Agent", "proxmox-backup-client/1.0")
483 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
484 .body(Body
::empty())?
;
491 pub struct BackupReader
{
493 canceller
: Canceller
,
496 impl Drop
for BackupReader
{
499 self.canceller
.cancel();
505 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
506 Arc
::new(Self { h2, canceller: canceller }
)
509 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
510 self.h2
.get(path
, param
)
513 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
514 self.h2
.put(path
, param
)
517 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
518 self.h2
.post(path
, param
)
521 pub fn download
<W
: Write
>(
525 ) -> impl Future
<Item
=W
, Error
=Error
> {
526 let path
= "download";
527 let param
= json
!({ "file-name": file_name }
);
528 self.h2
.download(path
, Some(param
), output
)
531 pub fn speedtest
<W
: Write
>(
534 ) -> impl Future
<Item
=W
, Error
=Error
> {
535 self.h2
.download("speedtest", None
, output
)
538 pub fn download_chunk
<W
: Write
>(
542 ) -> impl Future
<Item
=W
, Error
=Error
> {
544 let param
= json
!({ "digest": digest_to_hex(digest) }
);
545 self.h2
.download(path
, Some(param
), output
)
548 pub fn force_close(self) {
549 self.canceller
.cancel();
553 pub struct BackupClient
{
555 canceller
: Canceller
,
558 impl Drop
for BackupClient
{
561 self.canceller
.cancel();
565 pub struct BackupStats
{
572 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
573 Arc
::new(Self { h2, canceller }
)
576 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
577 self.h2
.get(path
, param
)
580 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
581 self.h2
.put(path
, param
)
584 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
585 self.h2
.post(path
, param
)
588 pub fn finish(self: Arc
<Self>) -> impl Future
<Item
=(), Error
=Error
> {
590 .post("finish", None
)
592 self.canceller
.cancel();
596 pub fn force_close(self) {
597 self.canceller
.cancel();
600 pub fn upload_blob_from_data(
604 crypt_config
: Option
<Arc
<CryptConfig
>>,
607 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
609 let h2
= self.h2
.clone();
610 let file_name
= file_name
.to_owned();
611 let size
= data
.len() as u64;
613 futures
::future
::ok(())
615 let blob
= if let Some(ref crypt_config
) = crypt_config
{
617 DataBlob
::create_signed(&data
, crypt_config
, compress
)?
619 DataBlob
::encode(&data
, Some(crypt_config
), compress
)?
622 DataBlob
::encode(&data
, None
, compress
)?
625 let raw_data
= blob
.into_inner();
628 .and_then(move |raw_data
| {
629 let csum
= openssl
::sha
::sha256(&raw_data
);
630 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
631 h2
.upload("blob", Some(param
), raw_data
)
633 BackupStats { size, csum }
638 pub fn upload_blob_from_file
<P
: AsRef
<std
::path
::Path
>>(
642 crypt_config
: Option
<Arc
<CryptConfig
>>,
644 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
646 let h2
= self.h2
.clone();
647 let file_name
= file_name
.to_owned();
648 let src_path
= src_path
.as_ref().to_owned();
650 let task
= tokio
::fs
::File
::open(src_path
.clone())
651 .map_err(move |err
| format_err
!("unable to open file {:?} - {}", src_path
, err
))
652 .and_then(move |file
| {
653 let contents
= vec
![];
654 tokio
::io
::read_to_end(file
, contents
)
655 .map_err(Error
::from
)
656 .and_then(move |(_
, contents
)| {
657 let blob
= if let Some(ref crypt_config
) = crypt_config
{
658 DataBlob
::encode(&contents
, Some(crypt_config
), compress
)?
660 DataBlob
::encode(&contents
, None
, compress
)?
662 let raw_data
= blob
.into_inner();
663 Ok((raw_data
, contents
.len() as u64))
665 .and_then(move |(raw_data
, size
)| {
666 let csum
= openssl
::sha
::sha256(&raw_data
);
667 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
668 h2
.upload("blob", Some(param
), raw_data
)
670 BackupStats { size, csum }
678 pub fn upload_stream(
681 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
683 fixed_size
: Option
<u64>,
684 crypt_config
: Option
<Arc
<CryptConfig
>>,
685 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
687 let known_chunks
= Arc
::new(Mutex
::new(HashSet
::new()));
689 let h2
= self.h2
.clone();
690 let h2_2
= self.h2
.clone();
691 let h2_3
= self.h2
.clone();
692 let h2_4
= self.h2
.clone();
694 let mut param
= json
!({ "archive-name": archive_name }
);
695 if let Some(size
) = fixed_size
{
696 param
["size"] = size
.into();
699 let index_path
= format
!("{}_index", prefix
);
700 let close_path
= format
!("{}_close", prefix
);
702 let prefix
= prefix
.to_owned();
704 Self::download_chunk_list(h2
, &index_path
, archive_name
, known_chunks
.clone())
706 h2_2
.post(&index_path
, Some(param
))
708 .and_then(move |res
| {
709 let wid
= res
.as_u64().unwrap();
710 Self::upload_chunk_info_stream(h2_3
, wid
, stream
, &prefix
, known_chunks
.clone(), crypt_config
)
711 .and_then(move |(chunk_count
, size
, _speed
)| {
714 "chunk-count": chunk_count
,
717 h2_4
.post(&close_path
, Some(param
))
719 BackupStats { size: size as u64, csum: [0u8; 32] }
725 fn response_queue() -> (
726 mpsc
::Sender
<h2
::client
::ResponseFuture
>,
727 sync
::oneshot
::Receiver
<Result
<(), Error
>>
729 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(100);
730 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
734 .map_err(Error
::from
)
735 .for_each(|response
: h2
::client
::ResponseFuture
| {
737 .map_err(Error
::from
)
738 .and_then(H2Client
::h2api_response
)
740 println
!("RESPONSE: {:?}", result
);
743 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
746 verify_result_tx
.send(result
)
748 .map_err(|_
| { /* ignore closed channel */ }
)
751 (verify_queue_tx
, verify_result_rx
)
754 fn append_chunk_queue(h2
: H2Client
, wid
: u64, path
: String
) -> (
755 mpsc
::Sender
<(MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)>,
756 sync
::oneshot
::Receiver
<Result
<(), Error
>>
758 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(64);
759 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
761 let h2_2
= h2
.clone();
765 .map_err(Error
::from
)
766 .and_then(move |(merged_chunk_info
, response
): (MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)| {
767 match (response
, merged_chunk_info
) {
768 (Some(response
), MergedChunkInfo
::Known(list
)) => {
771 .map_err(Error
::from
)
772 .and_then(H2Client
::h2api_response
)
773 .and_then(move |_result
| {
774 Ok(MergedChunkInfo
::Known(list
))
778 (None
, MergedChunkInfo
::Known(list
)) => {
779 future
::Either
::B(future
::ok(MergedChunkInfo
::Known(list
)))
784 .merge_known_chunks()
785 .and_then(move |merged_chunk_info
| {
786 match merged_chunk_info
{
787 MergedChunkInfo
::Known(chunk_list
) => {
788 let mut digest_list
= vec
![];
789 let mut offset_list
= vec
![];
790 for (offset
, digest
) in chunk_list
{
791 //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset);
792 digest_list
.push(digest_to_hex(&digest
));
793 offset_list
.push(offset
);
795 println
!("append chunks list len ({})", digest_list
.len());
796 let param
= json
!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }
);
797 let mut request
= H2Client
::request_builder("localhost", "PUT", &path
, None
).unwrap();
798 request
.headers_mut().insert(hyper
::header
::CONTENT_TYPE
, HeaderValue
::from_static("application/json"));
799 let param_data
= bytes
::Bytes
::from(param
.to_string().as_bytes());
800 let upload_data
= Some(param_data
);
801 h2_2
.send_request(request
, upload_data
)
802 .and_then(move |response
| {
804 .map_err(Error
::from
)
805 .and_then(H2Client
::h2api_response
)
806 .and_then(|_
| Ok(()))
808 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
813 .for_each(|_
| Ok(()))
815 verify_result_tx
.send(result
)
817 .map_err(|_
| { /* ignore closed channel */ }
)
820 (verify_queue_tx
, verify_result_rx
)
823 fn download_chunk_list(
827 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
828 ) -> impl Future
<Item
=(), Error
=Error
> {
830 let param
= json
!({ "archive-name": archive_name }
);
831 let request
= H2Client
::request_builder("localhost", "GET", path
, Some(param
)).unwrap();
833 h2
.send_request(request
, None
)
834 .and_then(move |response
| {
836 .map_err(Error
::from
)
837 .and_then(move |resp
| {
838 let status
= resp
.status();
840 if !status
.is_success() {
841 future
::Either
::A(H2Client
::h2api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
843 future
::Either
::B(future
::ok(resp
.into_body()))
846 .and_then(move |mut body
| {
848 let mut release_capacity
= body
.release_capacity().clone();
850 DigestListDecoder
::new(body
.map_err(Error
::from
))
851 .for_each(move |chunk
| {
852 let _
= release_capacity
.release_capacity(chunk
.len());
853 println
!("GOT DOWNLOAD {}", digest_to_hex(&chunk
));
854 known_chunks
.lock().unwrap().insert(chunk
);
861 fn upload_chunk_info_stream(
864 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
866 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
867 crypt_config
: Option
<Arc
<CryptConfig
>>,
868 ) -> impl Future
<Item
=(usize, usize, usize), Error
=Error
> {
870 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
871 let repeat2
= repeat
.clone();
873 let stream_len
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
874 let stream_len2
= stream_len
.clone();
876 let append_chunk_path
= format
!("{}_index", prefix
);
877 let upload_chunk_path
= format
!("{}_chunk", prefix
);
879 let (upload_queue
, upload_result
) = Self::append_chunk_queue(h2
.clone(), wid
, append_chunk_path
.to_owned());
881 let start_time
= std
::time
::Instant
::now();
884 .and_then(move |data
| {
886 let chunk_len
= data
.len();
888 repeat
.fetch_add(1, Ordering
::SeqCst
);
889 let offset
= stream_len
.fetch_add(chunk_len
, Ordering
::SeqCst
) as u64;
891 let mut chunk_builder
= DataChunkBuilder
::new(data
.as_ref())
894 if let Some(ref crypt_config
) = crypt_config
{
895 chunk_builder
= chunk_builder
.crypt_config(crypt_config
);
898 let mut known_chunks
= known_chunks
.lock().unwrap();
899 let digest
= chunk_builder
.digest();
900 let chunk_is_known
= known_chunks
.contains(digest
);
902 Ok(MergedChunkInfo
::Known(vec
![(offset
, *digest
)]))
904 known_chunks
.insert(*digest
);
905 let chunk
= chunk_builder
.build()?
;
906 Ok(MergedChunkInfo
::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset }
))
909 .merge_known_chunks()
910 .for_each(move |merged_chunk_info
| {
912 if let MergedChunkInfo
::New(chunk_info
) = merged_chunk_info
{
913 let offset
= chunk_info
.offset
;
914 let digest
= *chunk_info
.chunk
.digest();
915 let digest_str
= digest_to_hex(&digest
);
916 let upload_queue
= upload_queue
.clone();
918 println
!("upload new chunk {} ({} bytes, offset {})", digest_str
,
919 chunk_info
.chunk_len
, offset
);
921 let chunk_data
= chunk_info
.chunk
.raw_data();
924 "digest": digest_str
,
925 "size": chunk_info
.chunk_len
,
926 "encoded-size": chunk_data
.len(),
929 let request
= H2Client
::request_builder("localhost", "POST", &upload_chunk_path
, Some(param
)).unwrap();
930 let upload_data
= Some(bytes
::Bytes
::from(chunk_data
));
932 let new_info
= MergedChunkInfo
::Known(vec
![(offset
, digest
)]);
935 h2
.send_request(request
, upload_data
)
936 .and_then(move |response
| {
937 upload_queue
.clone().send((new_info
, Some(response
)))
938 .map(|_
| ()).map_err(Error
::from
)
944 upload_queue
.clone().send((merged_chunk_info
, None
))
945 .map(|_
| ()).map_err(Error
::from
)
949 .then(move |result
| {
950 //println!("RESULT {:?}", result);
951 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
952 Ok(upload1_result
.and(result
))
957 let repeat
= repeat2
.load(Ordering
::SeqCst
);
958 let stream_len
= stream_len2
.load(Ordering
::SeqCst
);
959 let speed
= ((stream_len
*1000000)/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
960 println
!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat
, start_time
.elapsed().as_secs(), speed
);
962 println
!("Average chunk size was {} bytes.", stream_len
/repeat
);
963 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
965 Ok((repeat
, stream_len
, speed
))
969 pub fn upload_speedtest(&self) -> impl Future
<Item
=usize, Error
=Error
> {
971 let mut data
= vec
![];
972 // generate pseudo random byte sequence
973 for i
in 0..1024*1024 {
975 let byte
= ((i
>> (j
<<3))&0xff) as u8;
980 let item_len
= data
.len();
982 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
983 let repeat2
= repeat
.clone();
985 let (upload_queue
, upload_result
) = Self::response_queue();
987 let start_time
= std
::time
::Instant
::now();
989 let h2
= self.h2
.clone();
991 futures
::stream
::repeat(data
)
992 .take_while(move |_
| {
993 repeat
.fetch_add(1, Ordering
::SeqCst
);
994 Ok(start_time
.elapsed().as_secs() < 5)
996 .for_each(move |data
| {
999 let upload_queue
= upload_queue
.clone();
1001 println
!("send test data ({} bytes)", data
.len());
1002 let request
= H2Client
::request_builder("localhost", "POST", "speedtest", None
).unwrap();
1003 h2
.send_request(request
, Some(bytes
::Bytes
::from(data
)))
1004 .and_then(move |response
| {
1005 upload_queue
.send(response
)
1006 .map(|_
| ()).map_err(Error
::from
)
1009 .then(move |result
| {
1010 println
!("RESULT {:?}", result
);
1011 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
1012 Ok(upload1_result
.and(result
))
1016 .and_then(move |_
| {
1017 let repeat
= repeat2
.load(Ordering
::SeqCst
);
1018 println
!("Uploaded {} chunks in {} seconds.", repeat
, start_time
.elapsed().as_secs());
1019 let speed
= ((item_len
*1000000*(repeat
as usize))/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
1021 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
1029 pub struct H2Client
{
1030 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
1035 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
1039 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1040 let req
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1044 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1045 let req
= Self::request_builder("localhost", "PUT", path
, param
).unwrap();
1049 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1050 let req
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1054 pub fn download
<W
: Write
>(&self, path
: &str, param
: Option
<Value
>, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
1055 let request
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1057 self.send_request(request
, None
)
1058 .and_then(move |response
| {
1060 .map_err(Error
::from
)
1061 .and_then(move |resp
| {
1062 let status
= resp
.status();
1063 if !status
.is_success() {
1065 H2Client
::h2api_response(resp
)
1066 .and_then(|_
| { bail!("unknown error"); }
)
1069 let mut body
= resp
.into_body();
1070 let mut release_capacity
= body
.release_capacity().clone();
1074 .map_err(Error
::from
)
1075 .fold(output
, move |mut acc
, chunk
| {
1076 let _
= release_capacity
.release_capacity(chunk
.len());
1077 acc
.write_all(&chunk
)?
;
1086 pub fn upload(&self, path
: &str, param
: Option
<Value
>, data
: Vec
<u8>) -> impl Future
<Item
=Value
, Error
=Error
> {
1087 let request
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1091 .map_err(Error
::from
)
1092 .and_then(move |mut send_request
| {
1093 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1094 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
)
1097 .map_err(Error
::from
)
1098 .and_then(Self::h2api_response
)
1105 request
: Request
<()>,
1106 ) -> impl Future
<Item
=Value
, Error
=Error
> {
1108 self.send_request(request
, None
)
1109 .and_then(move |response
| {
1111 .map_err(Error
::from
)
1112 .and_then(Self::h2api_response
)
1118 request
: Request
<()>,
1119 data
: Option
<bytes
::Bytes
>,
1120 ) -> impl Future
<Item
=h2
::client
::ResponseFuture
, Error
=Error
> {
1124 .map_err(Error
::from
)
1125 .and_then(move |mut send_request
| {
1126 if let Some(data
) = data
{
1127 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1128 future
::Either
::A(PipeToSendStream
::new(data
, stream
)
1129 .and_then(move |_
| {
1130 future
::ok(response
)
1133 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
1134 future
::Either
::B(future
::ok(response
))
1139 fn h2api_response(response
: Response
<h2
::RecvStream
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1141 let status
= response
.status();
1143 let (_head
, mut body
) = response
.into_parts();
1145 // The `release_capacity` handle allows the caller to manage
1148 // Whenever data is received, the caller is responsible for
1149 // releasing capacity back to the server once it has freed
1150 // the data from memory.
1151 let mut release_capacity
= body
.release_capacity().clone();
1155 // Let the server send more data.
1156 let _
= release_capacity
.release_capacity(chunk
.len());
1160 .map_err(Error
::from
)
1161 .and_then(move |data
| {
1162 let text
= String
::from_utf8(data
.to_vec()).unwrap();
1163 if status
.is_success() {
1165 let mut value
: Value
= serde_json
::from_str(&text
)?
;
1166 if let Some(map
) = value
.as_object_mut() {
1167 if let Some(data
) = map
.remove("data") {
1171 bail
!("got result without data property");
1176 bail
!("HTTP Error {}: {}", status
, text
);
1181 // Note: We always encode parameters with the url
1182 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<()>, Error
> {
1183 let path
= path
.trim_matches('
/'
);
1185 if let Some(data
) = data
{
1186 let query
= tools
::json_object_to_query(data
)?
;
1187 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
1188 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
1189 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
1190 let request
= Request
::builder()
1193 .header("User-Agent", "proxmox-backup-client/1.0")
1194 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
1198 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
1199 let request
= Request
::builder()
1202 .header("User-Agent", "proxmox-backup-client/1.0")
1203 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")