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 /// Delete stored ticket data (logout)
51 pub fn delete_ticket_info(server
: &str, username
: &str) -> Result
<(), Error
> {
53 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
55 // usually /run/user/<uid>/...
56 let path
= base
.place_runtime_file("tickets")?
;
58 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
60 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
62 if let Some(map
) = data
[server
].as_object_mut() {
66 file_set_contents(path
, data
.to_string().as_bytes(), Some(mode
))?
;
71 fn store_ticket_info(server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
73 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
75 // usually /run/user/<uid>/...
76 let path
= base
.place_runtime_file("tickets")?
;
78 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
80 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
82 let now
= Utc
::now().timestamp();
84 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
86 let mut new_data
= json
!({}
);
88 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
90 let empty
= serde_json
::map
::Map
::new();
91 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
92 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
93 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
94 let age
= now
- timestamp
;
95 if age
< ticket_lifetime
{
96 new_data
[server
][username
] = uinfo
.clone();
102 file_set_contents(path
, new_data
.to_string().as_bytes(), Some(mode
))?
;
107 fn load_ticket_info(server
: &str, username
: &str) -> Option
<(String
, String
)> {
108 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
113 // usually /run/user/<uid>/...
114 let path
= match base
.place_runtime_file("tickets") {
119 let data
= match file_get_json(&path
, None
) {
124 let now
= Utc
::now().timestamp();
126 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
128 if let Some(uinfo
) = data
[server
][username
].as_object() {
129 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
130 let age
= now
- timestamp
;
131 if age
< ticket_lifetime
{
132 let ticket
= match uinfo
["ticket"].as_str() {
136 let token
= match uinfo
["token"].as_str() {
140 return Some((ticket
.to_owned(), token
.to_owned()));
150 pub fn new(server
: &str, username
: &str) -> Result
<Self, Error
> {
151 let client
= Self::build_client();
153 let password
= if let Some((ticket
, _token
)) = load_ticket_info(server
, username
) {
156 Self::get_password(&username
)?
159 let login
= Self::credentials(client
.clone(), server
.to_owned(), username
.to_owned(), password
);
163 server
: String
::from(server
),
164 auth
: BroadcastFuture
::new(login
),
170 /// Login is done on demand, so this is onyl required if you need
171 /// access to authentication data in 'AuthInfo'.
172 pub fn login(&self) -> impl Future
<Item
=AuthInfo
, Error
=Error
> {
176 fn get_password(_username
: &str) -> Result
<String
, Error
> {
177 use std
::env
::VarError
::*;
178 match std
::env
::var("PBS_PASSWORD") {
179 Ok(p
) => return Ok(p
),
180 Err(NotUnicode(_
)) => bail
!("PBS_PASSWORD contains bad characters"),
182 // Try another method
186 // If we're on a TTY, query the user for a password
187 if tty
::stdin_isatty() {
188 return Ok(String
::from_utf8(tty
::read_password("Password: ")?
)?
);
191 bail
!("no password input mechanism available");
194 fn build_client() -> Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>> {
196 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
198 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
); // fixme!
200 let mut httpc
= hyper
::client
::HttpConnector
::new(1);
201 httpc
.set_nodelay(true); // important for h2 download performance!
202 httpc
.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance!
203 httpc
.enforce_http(false); // we want https...
205 let https
= hyper_openssl
::HttpsConnector
::with_connector(httpc
, ssl_connector_builder
).unwrap();
208 //.http2_initial_stream_window_size( (1 << 31) - 2)
209 //.http2_initial_connection_window_size( (1 << 31) - 2)
210 .build
::<_
, Body
>(https
)
213 pub fn request(&self, mut req
: Request
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
215 let login
= self.auth
.listen();
217 let client
= self.client
.clone();
219 login
.and_then(move |auth
| {
221 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
222 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
223 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
225 let request
= Self::api_request(client
, req
);
231 pub fn get(&self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
233 let req
= Self::request_builder(&self.server
, "GET", path
, data
).unwrap();
237 pub fn delete(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
239 let req
= Self::request_builder(&self.server
, "DELETE", path
, data
).unwrap();
243 pub fn post(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
245 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
249 pub fn download
<W
: Write
>(&mut self, path
: &str, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
251 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
253 let login
= self.auth
.listen();
255 let client
= self.client
.clone();
257 login
.and_then(move |auth
| {
259 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
260 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
263 .map_err(Error
::from
)
265 let status
= resp
.status();
266 if !status
.is_success() {
268 HttpClient
::api_response(resp
)
269 .and_then(|_
| { bail!("unknown error"); }
)
274 .map_err(Error
::from
)
275 .fold(output
, move |mut acc
, chunk
| {
276 acc
.write_all(&chunk
)?
;
291 ) -> impl Future
<Item
=Value
, Error
=Error
> {
293 let path
= path
.trim_matches('
/'
);
294 let mut url
= format
!("https://{}:8007/{}", &self.server
, path
);
296 if let Some(data
) = data
{
297 let query
= tools
::json_object_to_query(data
).unwrap();
299 url
.push_str(&query
);
302 let url
: Uri
= url
.parse().unwrap();
304 let req
= Request
::builder()
307 .header("User-Agent", "proxmox-backup-client/1.0")
308 .header("Content-Type", content_type
)
309 .body(body
).unwrap();
319 backup_time
: DateTime
<Utc
>,
321 ) -> impl Future
<Item
=Arc
<BackupClient
>, Error
=Error
> {
324 "backup-type": backup_type
,
325 "backup-id": backup_id
,
326 "backup-time": backup_time
.timestamp(),
331 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/backup", Some(param
)).unwrap();
333 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
334 .map(|(h2
, canceller
)| BackupClient
::new(h2
, canceller
))
337 pub fn start_backup_reader(
342 backup_time
: DateTime
<Utc
>,
344 ) -> impl Future
<Item
=Arc
<BackupReader
>, Error
=Error
> {
347 "backup-type": backup_type
,
348 "backup-id": backup_id
,
349 "backup-time": backup_time
.timestamp(),
353 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/reader", Some(param
)).unwrap();
355 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!()))
356 .map(|(h2
, canceller
)| BackupReader
::new(h2
, canceller
))
359 pub fn start_h2_connection(
361 mut req
: Request
<Body
>,
362 protocol_name
: String
,
363 ) -> impl Future
<Item
=(H2Client
, Canceller
), Error
=Error
> {
365 let login
= self.auth
.listen();
366 let client
= self.client
.clone();
368 login
.and_then(move |auth
| {
370 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
371 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
372 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
375 .map_err(Error
::from
)
378 let status
= resp
.status();
379 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
380 future
::Either
::A(Self::api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
382 future
::Either
::B(resp
.into_body().on_upgrade().map_err(Error
::from
))
385 .and_then(|upgraded
| {
386 let max_window_size
= (1 << 31) - 2;
388 h2
::client
::Builder
::new()
389 .initial_connection_window_size(max_window_size
)
390 .initial_window_size(max_window_size
)
391 .max_frame_size(4*1024*1024)
393 .map_err(Error
::from
)
395 .and_then(|(h2
, connection
)| {
396 let connection
= connection
397 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
399 let (connection
, canceller
) = cancellable(connection
)?
;
400 // A cancellable future returns an Option which is None when cancelled and
401 // Some when it finished instead, since we don't care about the return type we
402 // need to map it away:
403 let connection
= connection
.map(|_
| ());
405 // Spawn a new task to drive the connection state
406 hyper
::rt
::spawn(connection
);
408 // Wait until the `SendRequest` handle has available capacity.
410 .map(move |c
| (H2Client
::new(c
), canceller
))
411 .map_err(Error
::from
))
418 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
422 ) -> Box
<dyn Future
<Item
=AuthInfo
, Error
=Error
> + Send
> {
424 let server2
= server
.clone();
426 let create_request
= futures
::future
::lazy(move || {
427 let data
= json
!({ "username": username, "password": password }
);
428 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
429 Self::api_request(client
, req
)
432 let login_future
= create_request
433 .and_then(move |cred
| {
434 let auth
= AuthInfo
{
435 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
436 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
437 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
440 let _
= store_ticket_info(&server2
, &auth
.username
, &auth
.ticket
, &auth
.token
);
445 Box
::new(login_future
)
448 fn api_response(response
: Response
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
450 let status
= response
.status();
455 .map_err(Error
::from
)
456 .and_then(move |data
| {
458 let text
= String
::from_utf8(data
.to_vec()).unwrap();
459 if status
.is_success() {
461 let value
: Value
= serde_json
::from_str(&text
)?
;
467 bail
!("HTTP Error {}: {}", status
, text
);
473 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
475 ) -> impl Future
<Item
=Value
, Error
=Error
> {
478 .map_err(Error
::from
)
479 .and_then(Self::api_response
)
482 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
483 let path
= path
.trim_matches('
/'
);
484 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
486 if let Some(data
) = data
{
487 if method
== "POST" {
488 let request
= Request
::builder()
491 .header("User-Agent", "proxmox-backup-client/1.0")
492 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
493 .body(Body
::from(data
.to_string()))?
;
496 let query
= tools
::json_object_to_query(data
)?
;
497 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
498 let request
= Request
::builder()
501 .header("User-Agent", "proxmox-backup-client/1.0")
502 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
503 .body(Body
::empty())?
;
508 let request
= Request
::builder()
511 .header("User-Agent", "proxmox-backup-client/1.0")
512 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
513 .body(Body
::empty())?
;
520 pub struct BackupReader
{
522 canceller
: Canceller
,
525 impl Drop
for BackupReader
{
528 self.canceller
.cancel();
534 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
535 Arc
::new(Self { h2, canceller: canceller }
)
538 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
539 self.h2
.get(path
, param
)
542 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
543 self.h2
.put(path
, param
)
546 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
547 self.h2
.post(path
, param
)
550 pub fn download
<W
: Write
>(
554 ) -> impl Future
<Item
=W
, Error
=Error
> {
555 let path
= "download";
556 let param
= json
!({ "file-name": file_name }
);
557 self.h2
.download(path
, Some(param
), output
)
560 pub fn speedtest
<W
: Write
>(
563 ) -> impl Future
<Item
=W
, Error
=Error
> {
564 self.h2
.download("speedtest", None
, output
)
567 pub fn download_chunk
<W
: Write
>(
571 ) -> impl Future
<Item
=W
, Error
=Error
> {
573 let param
= json
!({ "digest": digest_to_hex(digest) }
);
574 self.h2
.download(path
, Some(param
), output
)
577 pub fn force_close(self) {
578 self.canceller
.cancel();
582 pub struct BackupClient
{
584 canceller
: Canceller
,
587 impl Drop
for BackupClient
{
590 self.canceller
.cancel();
594 pub struct BackupStats
{
601 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
602 Arc
::new(Self { h2, canceller }
)
605 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
606 self.h2
.get(path
, param
)
609 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
610 self.h2
.put(path
, param
)
613 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
614 self.h2
.post(path
, param
)
617 pub fn finish(self: Arc
<Self>) -> impl Future
<Item
=(), Error
=Error
> {
619 .post("finish", None
)
621 self.canceller
.cancel();
625 pub fn force_close(self) {
626 self.canceller
.cancel();
629 pub fn upload_blob_from_data(
633 crypt_config
: Option
<Arc
<CryptConfig
>>,
636 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
638 let h2
= self.h2
.clone();
639 let file_name
= file_name
.to_owned();
640 let size
= data
.len() as u64;
642 futures
::future
::ok(())
644 let blob
= if let Some(ref crypt_config
) = crypt_config
{
646 DataBlob
::create_signed(&data
, crypt_config
, compress
)?
648 DataBlob
::encode(&data
, Some(crypt_config
), compress
)?
651 DataBlob
::encode(&data
, None
, compress
)?
654 let raw_data
= blob
.into_inner();
657 .and_then(move |raw_data
| {
658 let csum
= openssl
::sha
::sha256(&raw_data
);
659 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
660 h2
.upload("blob", Some(param
), raw_data
)
662 BackupStats { size, csum }
667 pub fn upload_blob_from_file
<P
: AsRef
<std
::path
::Path
>>(
671 crypt_config
: Option
<Arc
<CryptConfig
>>,
673 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
675 let h2
= self.h2
.clone();
676 let file_name
= file_name
.to_owned();
677 let src_path
= src_path
.as_ref().to_owned();
679 let task
= tokio
::fs
::File
::open(src_path
.clone())
680 .map_err(move |err
| format_err
!("unable to open file {:?} - {}", src_path
, err
))
681 .and_then(move |file
| {
682 let contents
= vec
![];
683 tokio
::io
::read_to_end(file
, contents
)
684 .map_err(Error
::from
)
685 .and_then(move |(_
, contents
)| {
686 let blob
= if let Some(ref crypt_config
) = crypt_config
{
687 DataBlob
::encode(&contents
, Some(crypt_config
), compress
)?
689 DataBlob
::encode(&contents
, None
, compress
)?
691 let raw_data
= blob
.into_inner();
692 Ok((raw_data
, contents
.len() as u64))
694 .and_then(move |(raw_data
, size
)| {
695 let csum
= openssl
::sha
::sha256(&raw_data
);
696 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
697 h2
.upload("blob", Some(param
), raw_data
)
699 BackupStats { size, csum }
707 pub fn upload_stream(
710 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
712 fixed_size
: Option
<u64>,
713 crypt_config
: Option
<Arc
<CryptConfig
>>,
714 ) -> impl Future
<Item
=BackupStats
, Error
=Error
> {
716 let known_chunks
= Arc
::new(Mutex
::new(HashSet
::new()));
718 let h2
= self.h2
.clone();
719 let h2_2
= self.h2
.clone();
720 let h2_3
= self.h2
.clone();
721 let h2_4
= self.h2
.clone();
723 let mut param
= json
!({ "archive-name": archive_name }
);
724 if let Some(size
) = fixed_size
{
725 param
["size"] = size
.into();
728 let index_path
= format
!("{}_index", prefix
);
729 let close_path
= format
!("{}_close", prefix
);
731 let prefix
= prefix
.to_owned();
733 Self::download_chunk_list(h2
, &index_path
, archive_name
, known_chunks
.clone())
735 h2_2
.post(&index_path
, Some(param
))
737 .and_then(move |res
| {
738 let wid
= res
.as_u64().unwrap();
739 Self::upload_chunk_info_stream(h2_3
, wid
, stream
, &prefix
, known_chunks
.clone(), crypt_config
)
740 .and_then(move |(chunk_count
, size
, _speed
, csum
)| {
743 "chunk-count": chunk_count
,
746 h2_4
.post(&close_path
, Some(param
))
748 BackupStats { size: size as u64, csum }
754 fn response_queue() -> (
755 mpsc
::Sender
<h2
::client
::ResponseFuture
>,
756 sync
::oneshot
::Receiver
<Result
<(), Error
>>
758 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(100);
759 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
763 .map_err(Error
::from
)
764 .for_each(|response
: h2
::client
::ResponseFuture
| {
766 .map_err(Error
::from
)
767 .and_then(H2Client
::h2api_response
)
769 println
!("RESPONSE: {:?}", result
);
772 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
775 verify_result_tx
.send(result
)
777 .map_err(|_
| { /* ignore closed channel */ }
)
780 (verify_queue_tx
, verify_result_rx
)
783 fn append_chunk_queue(h2
: H2Client
, wid
: u64, path
: String
) -> (
784 mpsc
::Sender
<(MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)>,
785 sync
::oneshot
::Receiver
<Result
<(), Error
>>
787 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(64);
788 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
790 let h2_2
= h2
.clone();
794 .map_err(Error
::from
)
795 .and_then(move |(merged_chunk_info
, response
): (MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)| {
796 match (response
, merged_chunk_info
) {
797 (Some(response
), MergedChunkInfo
::Known(list
)) => {
800 .map_err(Error
::from
)
801 .and_then(H2Client
::h2api_response
)
802 .and_then(move |_result
| {
803 Ok(MergedChunkInfo
::Known(list
))
807 (None
, MergedChunkInfo
::Known(list
)) => {
808 future
::Either
::B(future
::ok(MergedChunkInfo
::Known(list
)))
813 .merge_known_chunks()
814 .and_then(move |merged_chunk_info
| {
815 match merged_chunk_info
{
816 MergedChunkInfo
::Known(chunk_list
) => {
817 let mut digest_list
= vec
![];
818 let mut offset_list
= vec
![];
819 for (offset
, digest
) in chunk_list
{
820 //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset);
821 digest_list
.push(digest_to_hex(&digest
));
822 offset_list
.push(offset
);
824 println
!("append chunks list len ({})", digest_list
.len());
825 let param
= json
!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }
);
826 let mut request
= H2Client
::request_builder("localhost", "PUT", &path
, None
).unwrap();
827 request
.headers_mut().insert(hyper
::header
::CONTENT_TYPE
, HeaderValue
::from_static("application/json"));
828 let param_data
= bytes
::Bytes
::from(param
.to_string().as_bytes());
829 let upload_data
= Some(param_data
);
830 h2_2
.send_request(request
, upload_data
)
831 .and_then(move |response
| {
833 .map_err(Error
::from
)
834 .and_then(H2Client
::h2api_response
)
835 .and_then(|_
| Ok(()))
837 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
842 .for_each(|_
| Ok(()))
844 verify_result_tx
.send(result
)
846 .map_err(|_
| { /* ignore closed channel */ }
)
849 (verify_queue_tx
, verify_result_rx
)
852 fn download_chunk_list(
856 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
857 ) -> impl Future
<Item
=(), Error
=Error
> {
859 let param
= json
!({ "archive-name": archive_name }
);
860 let request
= H2Client
::request_builder("localhost", "GET", path
, Some(param
)).unwrap();
862 h2
.send_request(request
, None
)
863 .and_then(move |response
| {
865 .map_err(Error
::from
)
866 .and_then(move |resp
| {
867 let status
= resp
.status();
869 if !status
.is_success() {
870 future
::Either
::A(H2Client
::h2api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
872 future
::Either
::B(future
::ok(resp
.into_body()))
875 .and_then(move |mut body
| {
877 let mut release_capacity
= body
.release_capacity().clone();
879 DigestListDecoder
::new(body
.map_err(Error
::from
))
880 .for_each(move |chunk
| {
881 let _
= release_capacity
.release_capacity(chunk
.len());
882 println
!("GOT DOWNLOAD {}", digest_to_hex(&chunk
));
883 known_chunks
.lock().unwrap().insert(chunk
);
890 fn upload_chunk_info_stream(
893 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
895 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
896 crypt_config
: Option
<Arc
<CryptConfig
>>,
897 ) -> impl Future
<Item
=(usize, usize, usize, [u8; 32]), Error
=Error
> {
899 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
900 let repeat2
= repeat
.clone();
902 let stream_len
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
903 let stream_len2
= stream_len
.clone();
905 let append_chunk_path
= format
!("{}_index", prefix
);
906 let upload_chunk_path
= format
!("{}_chunk", prefix
);
908 let (upload_queue
, upload_result
) = Self::append_chunk_queue(h2
.clone(), wid
, append_chunk_path
.to_owned());
910 let start_time
= std
::time
::Instant
::now();
912 let index_csum
= Arc
::new(Mutex
::new(Some(openssl
::sha
::Sha256
::new())));
913 let index_csum_2
= index_csum
.clone();
916 .and_then(move |data
| {
918 let chunk_len
= data
.len();
920 repeat
.fetch_add(1, Ordering
::SeqCst
);
921 let offset
= stream_len
.fetch_add(chunk_len
, Ordering
::SeqCst
) as u64;
923 let mut chunk_builder
= DataChunkBuilder
::new(data
.as_ref())
926 if let Some(ref crypt_config
) = crypt_config
{
927 chunk_builder
= chunk_builder
.crypt_config(crypt_config
);
930 let mut known_chunks
= known_chunks
.lock().unwrap();
931 let digest
= chunk_builder
.digest();
933 let mut guard
= index_csum
.lock().unwrap();
934 let csum
= guard
.as_mut().unwrap();
935 csum
.update(&offset
.to_le_bytes());
938 let chunk_is_known
= known_chunks
.contains(digest
);
940 Ok(MergedChunkInfo
::Known(vec
![(offset
, *digest
)]))
942 known_chunks
.insert(*digest
);
943 let chunk
= chunk_builder
.build()?
;
944 Ok(MergedChunkInfo
::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset }
))
947 .merge_known_chunks()
948 .for_each(move |merged_chunk_info
| {
950 if let MergedChunkInfo
::New(chunk_info
) = merged_chunk_info
{
951 let offset
= chunk_info
.offset
;
952 let digest
= *chunk_info
.chunk
.digest();
953 let digest_str
= digest_to_hex(&digest
);
954 let upload_queue
= upload_queue
.clone();
956 println
!("upload new chunk {} ({} bytes, offset {})", digest_str
,
957 chunk_info
.chunk_len
, offset
);
959 let chunk_data
= chunk_info
.chunk
.raw_data();
962 "digest": digest_str
,
963 "size": chunk_info
.chunk_len
,
964 "encoded-size": chunk_data
.len(),
967 let request
= H2Client
::request_builder("localhost", "POST", &upload_chunk_path
, Some(param
)).unwrap();
968 let upload_data
= Some(bytes
::Bytes
::from(chunk_data
));
970 let new_info
= MergedChunkInfo
::Known(vec
![(offset
, digest
)]);
973 h2
.send_request(request
, upload_data
)
974 .and_then(move |response
| {
975 upload_queue
.clone().send((new_info
, Some(response
)))
976 .map(|_
| ()).map_err(Error
::from
)
982 upload_queue
.clone().send((merged_chunk_info
, None
))
983 .map(|_
| ()).map_err(Error
::from
)
987 .then(move |result
| {
988 //println!("RESULT {:?}", result);
989 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
990 Ok(upload1_result
.and(result
))
995 let repeat
= repeat2
.load(Ordering
::SeqCst
);
996 let stream_len
= stream_len2
.load(Ordering
::SeqCst
);
997 let speed
= ((stream_len
*1000000)/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
998 println
!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat
, start_time
.elapsed().as_secs(), speed
);
1000 println
!("Average chunk size was {} bytes.", stream_len
/repeat
);
1001 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
1004 let mut guard
= index_csum_2
.lock().unwrap();
1005 let csum
= guard
.take().unwrap().finish();
1007 Ok((repeat
, stream_len
, speed
, csum
))
1011 pub fn upload_speedtest(&self) -> impl Future
<Item
=usize, Error
=Error
> {
1013 let mut data
= vec
![];
1014 // generate pseudo random byte sequence
1015 for i
in 0..1024*1024 {
1017 let byte
= ((i
>> (j
<<3))&0xff) as u8;
1022 let item_len
= data
.len();
1024 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
1025 let repeat2
= repeat
.clone();
1027 let (upload_queue
, upload_result
) = Self::response_queue();
1029 let start_time
= std
::time
::Instant
::now();
1031 let h2
= self.h2
.clone();
1033 futures
::stream
::repeat(data
)
1034 .take_while(move |_
| {
1035 repeat
.fetch_add(1, Ordering
::SeqCst
);
1036 Ok(start_time
.elapsed().as_secs() < 5)
1038 .for_each(move |data
| {
1039 let h2
= h2
.clone();
1041 let upload_queue
= upload_queue
.clone();
1043 println
!("send test data ({} bytes)", data
.len());
1044 let request
= H2Client
::request_builder("localhost", "POST", "speedtest", None
).unwrap();
1045 h2
.send_request(request
, Some(bytes
::Bytes
::from(data
)))
1046 .and_then(move |response
| {
1047 upload_queue
.send(response
)
1048 .map(|_
| ()).map_err(Error
::from
)
1051 .then(move |result
| {
1052 println
!("RESULT {:?}", result
);
1053 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
1054 Ok(upload1_result
.and(result
))
1058 .and_then(move |_
| {
1059 let repeat
= repeat2
.load(Ordering
::SeqCst
);
1060 println
!("Uploaded {} chunks in {} seconds.", repeat
, start_time
.elapsed().as_secs());
1061 let speed
= ((item_len
*1000000*(repeat
as usize))/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
1063 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
1071 pub struct H2Client
{
1072 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
1077 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
1081 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1082 let req
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1086 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1087 let req
= Self::request_builder("localhost", "PUT", path
, param
).unwrap();
1091 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1092 let req
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1096 pub fn download
<W
: Write
>(&self, path
: &str, param
: Option
<Value
>, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
1097 let request
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1099 self.send_request(request
, None
)
1100 .and_then(move |response
| {
1102 .map_err(Error
::from
)
1103 .and_then(move |resp
| {
1104 let status
= resp
.status();
1105 if !status
.is_success() {
1107 H2Client
::h2api_response(resp
)
1108 .and_then(|_
| { bail!("unknown error"); }
)
1111 let mut body
= resp
.into_body();
1112 let mut release_capacity
= body
.release_capacity().clone();
1116 .map_err(Error
::from
)
1117 .fold(output
, move |mut acc
, chunk
| {
1118 let _
= release_capacity
.release_capacity(chunk
.len());
1119 acc
.write_all(&chunk
)?
;
1128 pub fn upload(&self, path
: &str, param
: Option
<Value
>, data
: Vec
<u8>) -> impl Future
<Item
=Value
, Error
=Error
> {
1129 let request
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1133 .map_err(Error
::from
)
1134 .and_then(move |mut send_request
| {
1135 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1136 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
)
1139 .map_err(Error
::from
)
1140 .and_then(Self::h2api_response
)
1147 request
: Request
<()>,
1148 ) -> impl Future
<Item
=Value
, Error
=Error
> {
1150 self.send_request(request
, None
)
1151 .and_then(move |response
| {
1153 .map_err(Error
::from
)
1154 .and_then(Self::h2api_response
)
1160 request
: Request
<()>,
1161 data
: Option
<bytes
::Bytes
>,
1162 ) -> impl Future
<Item
=h2
::client
::ResponseFuture
, Error
=Error
> {
1166 .map_err(Error
::from
)
1167 .and_then(move |mut send_request
| {
1168 if let Some(data
) = data
{
1169 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1170 future
::Either
::A(PipeToSendStream
::new(data
, stream
)
1171 .and_then(move |_
| {
1172 future
::ok(response
)
1175 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
1176 future
::Either
::B(future
::ok(response
))
1181 fn h2api_response(response
: Response
<h2
::RecvStream
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1183 let status
= response
.status();
1185 let (_head
, mut body
) = response
.into_parts();
1187 // The `release_capacity` handle allows the caller to manage
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();
1197 // Let the server send more data.
1198 let _
= release_capacity
.release_capacity(chunk
.len());
1202 .map_err(Error
::from
)
1203 .and_then(move |data
| {
1204 let text
= String
::from_utf8(data
.to_vec()).unwrap();
1205 if status
.is_success() {
1207 let mut value
: Value
= serde_json
::from_str(&text
)?
;
1208 if let Some(map
) = value
.as_object_mut() {
1209 if let Some(data
) = map
.remove("data") {
1213 bail
!("got result without data property");
1218 bail
!("HTTP Error {}: {}", status
, text
);
1223 // Note: We always encode parameters with the url
1224 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<()>, Error
> {
1225 let path
= path
.trim_matches('
/'
);
1227 if let Some(data
) = data
{
1228 let query
= tools
::json_object_to_query(data
)?
;
1229 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
1230 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
1231 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
1232 let request
= Request
::builder()
1235 .header("User-Agent", "proxmox-backup-client/1.0")
1236 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
1240 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
1241 let request
= Request
::builder()
1244 .header("User-Agent", "proxmox-backup-client/1.0")
1245 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")