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}
;
24 use crate::tools
::{self, BroadcastFuture, tty}
;
25 use crate::tools
::futures
::{cancellable, Canceller}
;
26 use super::pipe_to_stream
::*;
27 use super::merge_known_chunks
::*;
38 /// HTTP(S) API client
39 pub struct HttpClient
{
40 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
42 auth
: BroadcastFuture
<AuthInfo
>,
45 fn store_ticket_info(server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
47 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
49 // usually /run/user/<uid>/...
50 let path
= base
.place_runtime_file("tickets")?
;
52 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
54 let mut data
= tools
::file_get_json(&path
, Some(json
!({}
)))?
;
56 let now
= Utc
::now().timestamp();
58 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
60 let mut new_data
= json
!({}
);
62 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
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();
76 tools
::file_set_contents(path
, new_data
.to_string().as_bytes(), Some(mode
))?
;
81 fn load_ticket_info(server
: &str, username
: &str) -> Option
<(String
, String
)> {
82 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
87 // usually /run/user/<uid>/...
88 let path
= match base
.place_runtime_file("tickets") {
93 let data
= match tools
::file_get_json(&path
, None
) {
98 let now
= Utc
::now().timestamp();
100 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
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() {
110 let token
= match uinfo
["token"].as_str() {
114 return Some((ticket
.to_owned(), token
.to_owned()));
124 pub fn new(server
: &str, username
: &str) -> Result
<Self, Error
> {
125 let client
= Self::build_client();
127 let password
= if let Some((ticket
, _token
)) = load_ticket_info(server
, username
) {
130 Self::get_password(&username
)?
133 let login
= Self::credentials(client
.clone(), server
.to_owned(), username
.to_owned(), password
);
137 server
: String
::from(server
),
138 auth
: BroadcastFuture
::new(login
),
142 fn get_password(_username
: &str) -> Result
<String
, Error
> {
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"),
148 // Try another method
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: ")?
)?
);
157 bail
!("no password input mechanism available");
160 fn build_client() -> Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>> {
162 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
164 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
); // fixme!
166 let mut httpc
= hyper
::client
::HttpConnector
::new(1);
167 httpc
.set_nodelay(true); // important for h2 download performance!
168 httpc
.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance!
169 httpc
.enforce_http(false); // we want https...
171 let https
= hyper_openssl
::HttpsConnector
::with_connector(httpc
, ssl_connector_builder
).unwrap();
174 //.http2_initial_stream_window_size( (1 << 31) - 2)
175 //.http2_initial_connection_window_size( (1 << 31) - 2)
176 .build
::<_
, Body
>(https
)
179 pub fn request(&self, mut req
: Request
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
181 let login
= self.auth
.listen();
183 let client
= self.client
.clone();
185 login
.and_then(move |auth
| {
187 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
188 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
189 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
191 let request
= Self::api_request(client
, req
);
197 pub fn get(&self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
199 let req
= Self::request_builder(&self.server
, "GET", path
, data
).unwrap();
203 pub fn delete(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
205 let req
= Self::request_builder(&self.server
, "DELETE", path
, data
).unwrap();
209 pub fn post(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
211 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
215 pub fn download
<W
: Write
>(&mut self, path
: &str, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
217 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
219 let login
= self.auth
.listen();
221 let client
= self.client
.clone();
223 login
.and_then(move |auth
| {
225 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
226 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
229 .map_err(Error
::from
)
231 let status
= resp
.status();
232 if !status
.is_success() {
234 HttpClient
::api_response(resp
)
235 .and_then(|_
| { bail!("unknown error"); }
)
240 .map_err(Error
::from
)
241 .fold(output
, move |mut acc
, chunk
| {
242 acc
.write_all(&chunk
)?
;
257 ) -> impl Future
<Item
=Value
, Error
=Error
> {
259 let path
= path
.trim_matches('
/'
);
260 let mut url
= format
!("https://{}:8007/{}", &self.server
, path
);
262 if let Some(data
) = data
{
263 let query
= tools
::json_object_to_query(data
).unwrap();
265 url
.push_str(&query
);
268 let url
: Uri
= url
.parse().unwrap();
270 let req
= Request
::builder()
273 .header("User-Agent", "proxmox-backup-client/1.0")
274 .header("Content-Type", content_type
)
275 .body(body
).unwrap();
285 backup_time
: DateTime
<Utc
>,
287 ) -> impl Future
<Item
=Arc
<BackupClient
>, Error
=Error
> {
290 "backup-type": backup_type
,
291 "backup-id": backup_id
,
292 "backup-time": backup_time
.timestamp(),
297 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/backup", Some(param
)).unwrap();
299 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_PROTOCOL_ID_V1
!()))
300 .map(|(h2
, canceller
)| BackupClient
::new(h2
, canceller
))
303 pub fn start_backup_reader(
308 backup_time
: DateTime
<Utc
>,
310 ) -> impl Future
<Item
=Arc
<BackupReader
>, Error
=Error
> {
313 "backup-type": backup_type
,
314 "backup-id": backup_id
,
315 "backup-time": backup_time
.timestamp(),
319 let req
= Self::request_builder(&self.server
, "GET", "/api2/json/reader", Some(param
)).unwrap();
321 self.start_h2_connection(req
, String
::from(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!()))
322 .map(|(h2
, canceller
)| BackupReader
::new(h2
, canceller
))
325 pub fn start_h2_connection(
327 mut req
: Request
<Body
>,
328 protocol_name
: String
,
329 ) -> impl Future
<Item
=(H2Client
, Canceller
), Error
=Error
> {
331 let login
= self.auth
.listen();
332 let client
= self.client
.clone();
334 login
.and_then(move |auth
| {
336 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
337 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
338 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
341 .map_err(Error
::from
)
344 let status
= resp
.status();
345 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
346 future
::Either
::A(Self::api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
348 future
::Either
::B(resp
.into_body().on_upgrade().map_err(Error
::from
))
351 .and_then(|upgraded
| {
352 let max_window_size
= (1 << 31) - 2;
354 h2
::client
::Builder
::new()
355 .initial_connection_window_size(max_window_size
)
356 .initial_window_size(max_window_size
)
357 .max_frame_size(4*1024*1024)
359 .map_err(Error
::from
)
361 .and_then(|(h2
, connection
)| {
362 let connection
= connection
363 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
365 let (connection
, canceller
) = cancellable(connection
)?
;
366 // A cancellable future returns an Option which is None when cancelled and
367 // Some when it finished instead, since we don't care about the return type we
368 // need to map it away:
369 let connection
= connection
.map(|_
| ());
371 // Spawn a new task to drive the connection state
372 hyper
::rt
::spawn(connection
);
374 // Wait until the `SendRequest` handle has available capacity.
376 .map(move |c
| (H2Client
::new(c
), canceller
))
377 .map_err(Error
::from
))
384 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
388 ) -> Box
<dyn Future
<Item
=AuthInfo
, Error
=Error
> + Send
> {
390 let server2
= server
.clone();
392 let create_request
= futures
::future
::lazy(move || {
393 let data
= json
!({ "username": username, "password": password }
);
394 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
395 Self::api_request(client
, req
)
398 let login_future
= create_request
399 .and_then(move |cred
| {
400 let auth
= AuthInfo
{
401 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
402 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
403 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
406 let _
= store_ticket_info(&server2
, &auth
.username
, &auth
.ticket
, &auth
.token
);
411 Box
::new(login_future
)
414 fn api_response(response
: Response
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
416 let status
= response
.status();
421 .map_err(Error
::from
)
422 .and_then(move |data
| {
424 let text
= String
::from_utf8(data
.to_vec()).unwrap();
425 if status
.is_success() {
427 let value
: Value
= serde_json
::from_str(&text
)?
;
433 bail
!("HTTP Error {}: {}", status
, text
);
439 client
: Client
<hyper_openssl
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
441 ) -> impl Future
<Item
=Value
, Error
=Error
> {
444 .map_err(Error
::from
)
445 .and_then(Self::api_response
)
448 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
449 let path
= path
.trim_matches('
/'
);
450 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
452 if let Some(data
) = data
{
453 if method
== "POST" {
454 let request
= Request
::builder()
457 .header("User-Agent", "proxmox-backup-client/1.0")
458 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
459 .body(Body
::from(data
.to_string()))?
;
462 let query
= tools
::json_object_to_query(data
)?
;
463 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
464 let request
= Request
::builder()
467 .header("User-Agent", "proxmox-backup-client/1.0")
468 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
469 .body(Body
::empty())?
;
474 let request
= Request
::builder()
477 .header("User-Agent", "proxmox-backup-client/1.0")
478 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
479 .body(Body
::empty())?
;
486 pub struct BackupReader
{
488 canceller
: Canceller
,
491 impl Drop
for BackupReader
{
494 self.canceller
.cancel();
500 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
501 Arc
::new(Self { h2, canceller: canceller }
)
504 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
505 self.h2
.get(path
, param
)
508 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
509 self.h2
.put(path
, param
)
512 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
513 self.h2
.post(path
, param
)
516 pub fn download
<W
: Write
>(
520 ) -> impl Future
<Item
=W
, Error
=Error
> {
521 let path
= "download";
522 let param
= json
!({ "file-name": file_name }
);
523 self.h2
.download(path
, Some(param
), output
)
526 pub fn speedtest
<W
: Write
>(
529 ) -> impl Future
<Item
=W
, Error
=Error
> {
530 self.h2
.download("speedtest", None
, output
)
533 pub fn download_chunk
<W
: Write
>(
537 ) -> impl Future
<Item
=W
, Error
=Error
> {
539 let param
= json
!({ "digest": proxmox::tools::digest_to_hex(digest) }
);
540 self.h2
.download(path
, Some(param
), output
)
543 pub fn force_close(self) {
544 self.canceller
.cancel();
548 pub struct BackupClient
{
550 canceller
: Canceller
,
553 impl Drop
for BackupClient
{
556 self.canceller
.cancel();
562 pub fn new(h2
: H2Client
, canceller
: Canceller
) -> Arc
<Self> {
563 Arc
::new(Self { h2, canceller }
)
566 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
567 self.h2
.get(path
, param
)
570 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
571 self.h2
.put(path
, param
)
574 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
575 self.h2
.post(path
, param
)
578 pub fn finish(self: Arc
<Self>) -> impl Future
<Item
=(), Error
=Error
> {
580 .post("finish", None
)
582 self.canceller
.cancel();
586 pub fn force_close(self) {
587 self.canceller
.cancel();
590 pub fn upload_blob_from_data(
594 crypt_config
: Option
<Arc
<CryptConfig
>>,
596 ) -> impl Future
<Item
=(), Error
=Error
> {
598 let h2
= self.h2
.clone();
599 let file_name
= file_name
.to_owned();
601 futures
::future
::ok(())
603 let blob
= if let Some(ref crypt_config
) = crypt_config
{
604 DataBlob
::encode(&data
, Some(crypt_config
), compress
)?
606 DataBlob
::encode(&data
, None
, compress
)?
609 let raw_data
= blob
.into_inner();
612 .and_then(move |raw_data
| {
613 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
614 h2
.upload("blob", Some(param
), raw_data
)
619 pub fn upload_blob_from_file
<P
: AsRef
<std
::path
::Path
>>(
623 crypt_config
: Option
<Arc
<CryptConfig
>>,
625 ) -> impl Future
<Item
=(), Error
=Error
> {
627 let h2
= self.h2
.clone();
628 let file_name
= file_name
.to_owned();
629 let src_path
= src_path
.as_ref().to_owned();
631 let task
= tokio
::fs
::File
::open(src_path
.clone())
632 .map_err(move |err
| format_err
!("unable to open file {:?} - {}", src_path
, err
))
633 .and_then(move |file
| {
634 let contents
= vec
![];
635 tokio
::io
::read_to_end(file
, contents
)
636 .map_err(Error
::from
)
637 .and_then(move |(_
, contents
)| {
638 let blob
= if let Some(ref crypt_config
) = crypt_config
{
639 DataBlob
::encode(&contents
, Some(crypt_config
), compress
)?
641 DataBlob
::encode(&contents
, None
, compress
)?
643 let raw_data
= blob
.into_inner();
646 .and_then(move |raw_data
| {
647 let param
= json
!({"encoded-size": raw_data.len(), "file-name": file_name }
);
648 h2
.upload("blob", Some(param
), raw_data
)
656 pub fn upload_stream(
659 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
661 fixed_size
: Option
<u64>,
662 crypt_config
: Option
<Arc
<CryptConfig
>>,
663 ) -> impl Future
<Item
=(), Error
=Error
> {
665 let known_chunks
= Arc
::new(Mutex
::new(HashSet
::new()));
667 let h2
= self.h2
.clone();
668 let h2_2
= self.h2
.clone();
669 let h2_3
= self.h2
.clone();
670 let h2_4
= self.h2
.clone();
672 let mut param
= json
!({ "archive-name": archive_name }
);
673 if let Some(size
) = fixed_size
{
674 param
["size"] = size
.into();
677 let index_path
= format
!("{}_index", prefix
);
678 let close_path
= format
!("{}_close", prefix
);
680 let prefix
= prefix
.to_owned();
682 Self::download_chunk_list(h2
, &index_path
, archive_name
, known_chunks
.clone())
684 h2_2
.post(&index_path
, Some(param
))
686 .and_then(move |res
| {
687 let wid
= res
.as_u64().unwrap();
688 Self::upload_chunk_info_stream(h2_3
, wid
, stream
, &prefix
, known_chunks
.clone(), crypt_config
)
689 .and_then(move |(chunk_count
, size
, _speed
)| {
692 "chunk-count": chunk_count
,
695 h2_4
.post(&close_path
, Some(param
))
701 fn response_queue() -> (
702 mpsc
::Sender
<h2
::client
::ResponseFuture
>,
703 sync
::oneshot
::Receiver
<Result
<(), Error
>>
705 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(100);
706 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
710 .map_err(Error
::from
)
711 .for_each(|response
: h2
::client
::ResponseFuture
| {
713 .map_err(Error
::from
)
714 .and_then(H2Client
::h2api_response
)
716 println
!("RESPONSE: {:?}", result
);
719 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
722 verify_result_tx
.send(result
)
724 .map_err(|_
| { /* ignore closed channel */ }
)
727 (verify_queue_tx
, verify_result_rx
)
730 fn append_chunk_queue(h2
: H2Client
, wid
: u64, path
: String
) -> (
731 mpsc
::Sender
<(MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)>,
732 sync
::oneshot
::Receiver
<Result
<(), Error
>>
734 let (verify_queue_tx
, verify_queue_rx
) = mpsc
::channel(64);
735 let (verify_result_tx
, verify_result_rx
) = sync
::oneshot
::channel();
737 let h2_2
= h2
.clone();
741 .map_err(Error
::from
)
742 .and_then(move |(merged_chunk_info
, response
): (MergedChunkInfo
, Option
<h2
::client
::ResponseFuture
>)| {
743 match (response
, merged_chunk_info
) {
744 (Some(response
), MergedChunkInfo
::Known(list
)) => {
747 .map_err(Error
::from
)
748 .and_then(H2Client
::h2api_response
)
749 .and_then(move |_result
| {
750 Ok(MergedChunkInfo
::Known(list
))
754 (None
, MergedChunkInfo
::Known(list
)) => {
755 future
::Either
::B(future
::ok(MergedChunkInfo
::Known(list
)))
760 .merge_known_chunks()
761 .and_then(move |merged_chunk_info
| {
762 match merged_chunk_info
{
763 MergedChunkInfo
::Known(chunk_list
) => {
764 let mut digest_list
= vec
![];
765 let mut offset_list
= vec
![];
766 for (offset
, digest
) in chunk_list
{
767 //println!("append chunk {} (offset {})", proxmox::tools::digest_to_hex(&digest), offset);
768 digest_list
.push(proxmox
::tools
::digest_to_hex(&digest
));
769 offset_list
.push(offset
);
771 println
!("append chunks list len ({})", digest_list
.len());
772 let param
= json
!({ "wid": wid, "digest-list": digest_list, "offset-list": offset_list }
);
773 let mut request
= H2Client
::request_builder("localhost", "PUT", &path
, None
).unwrap();
774 request
.headers_mut().insert(hyper
::header
::CONTENT_TYPE
, HeaderValue
::from_static("application/json"));
775 let param_data
= bytes
::Bytes
::from(param
.to_string().as_bytes());
776 let upload_data
= Some(param_data
);
777 h2_2
.send_request(request
, upload_data
)
778 .and_then(move |response
| {
780 .map_err(Error
::from
)
781 .and_then(H2Client
::h2api_response
)
782 .and_then(|_
| Ok(()))
784 .map_err(|err
| format_err
!("pipelined request failed: {}", err
))
789 .for_each(|_
| Ok(()))
791 verify_result_tx
.send(result
)
793 .map_err(|_
| { /* ignore closed channel */ }
)
796 (verify_queue_tx
, verify_result_rx
)
799 fn download_chunk_list(
803 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
804 ) -> impl Future
<Item
=(), Error
=Error
> {
806 let param
= json
!({ "archive-name": archive_name }
);
807 let request
= H2Client
::request_builder("localhost", "GET", path
, Some(param
)).unwrap();
809 h2
.send_request(request
, None
)
810 .and_then(move |response
| {
812 .map_err(Error
::from
)
813 .and_then(move |resp
| {
814 let status
= resp
.status();
816 if !status
.is_success() {
817 future
::Either
::A(H2Client
::h2api_response(resp
).and_then(|_
| { bail!("unknown error"); }
))
819 future
::Either
::B(future
::ok(resp
.into_body()))
822 .and_then(move |mut body
| {
824 let mut release_capacity
= body
.release_capacity().clone();
826 DigestListDecoder
::new(body
.map_err(Error
::from
))
827 .for_each(move |chunk
| {
828 let _
= release_capacity
.release_capacity(chunk
.len());
829 println
!("GOT DOWNLOAD {}", proxmox
::tools
::digest_to_hex(&chunk
));
830 known_chunks
.lock().unwrap().insert(chunk
);
837 fn upload_chunk_info_stream(
840 stream
: impl Stream
<Item
=bytes
::BytesMut
, Error
=Error
>,
842 known_chunks
: Arc
<Mutex
<HashSet
<[u8;32]>>>,
843 crypt_config
: Option
<Arc
<CryptConfig
>>,
844 ) -> impl Future
<Item
=(usize, usize, usize), Error
=Error
> {
846 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
847 let repeat2
= repeat
.clone();
849 let stream_len
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
850 let stream_len2
= stream_len
.clone();
852 let append_chunk_path
= format
!("{}_index", prefix
);
853 let upload_chunk_path
= format
!("{}_chunk", prefix
);
855 let (upload_queue
, upload_result
) = Self::append_chunk_queue(h2
.clone(), wid
, append_chunk_path
.to_owned());
857 let start_time
= std
::time
::Instant
::now();
860 .and_then(move |data
| {
862 let chunk_len
= data
.len();
864 repeat
.fetch_add(1, Ordering
::SeqCst
);
865 let offset
= stream_len
.fetch_add(chunk_len
, Ordering
::SeqCst
) as u64;
867 let mut chunk_builder
= DataChunkBuilder
::new(data
.as_ref())
870 if let Some(ref crypt_config
) = crypt_config
{
871 chunk_builder
= chunk_builder
.crypt_config(crypt_config
);
874 let mut known_chunks
= known_chunks
.lock().unwrap();
875 let digest
= chunk_builder
.digest();
876 let chunk_is_known
= known_chunks
.contains(digest
);
878 Ok(MergedChunkInfo
::Known(vec
![(offset
, *digest
)]))
880 known_chunks
.insert(*digest
);
881 let chunk
= chunk_builder
.build()?
;
882 Ok(MergedChunkInfo
::New(ChunkInfo { chunk, chunk_len: chunk_len as u64, offset }
))
885 .merge_known_chunks()
886 .for_each(move |merged_chunk_info
| {
888 if let MergedChunkInfo
::New(chunk_info
) = merged_chunk_info
{
889 let offset
= chunk_info
.offset
;
890 let digest
= *chunk_info
.chunk
.digest();
891 let digest_str
= proxmox
::tools
::digest_to_hex(&digest
);
892 let upload_queue
= upload_queue
.clone();
894 println
!("upload new chunk {} ({} bytes, offset {})", digest_str
,
895 chunk_info
.chunk_len
, offset
);
897 let chunk_data
= chunk_info
.chunk
.raw_data();
900 "digest": digest_str
,
901 "size": chunk_info
.chunk_len
,
902 "encoded-size": chunk_data
.len(),
905 let request
= H2Client
::request_builder("localhost", "POST", &upload_chunk_path
, Some(param
)).unwrap();
906 let upload_data
= Some(bytes
::Bytes
::from(chunk_data
));
908 let new_info
= MergedChunkInfo
::Known(vec
![(offset
, digest
)]);
911 h2
.send_request(request
, upload_data
)
912 .and_then(move |response
| {
913 upload_queue
.clone().send((new_info
, Some(response
)))
914 .map(|_
| ()).map_err(Error
::from
)
920 upload_queue
.clone().send((merged_chunk_info
, None
))
921 .map(|_
| ()).map_err(Error
::from
)
925 .then(move |result
| {
926 //println!("RESULT {:?}", result);
927 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
928 Ok(upload1_result
.and(result
))
933 let repeat
= repeat2
.load(Ordering
::SeqCst
);
934 let stream_len
= stream_len2
.load(Ordering
::SeqCst
);
935 let speed
= ((stream_len
*1000000)/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
936 println
!("Uploaded {} chunks in {} seconds ({} MB/s).", repeat
, start_time
.elapsed().as_secs(), speed
);
938 println
!("Average chunk size was {} bytes.", stream_len
/repeat
);
939 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
941 Ok((repeat
, stream_len
, speed
))
945 pub fn upload_speedtest(&self) -> impl Future
<Item
=usize, Error
=Error
> {
947 let mut data
= vec
![];
948 // generate pseudo random byte sequence
949 for i
in 0..1024*1024 {
951 let byte
= ((i
>> (j
<<3))&0xff) as u8;
956 let item_len
= data
.len();
958 let repeat
= std
::sync
::Arc
::new(AtomicUsize
::new(0));
959 let repeat2
= repeat
.clone();
961 let (upload_queue
, upload_result
) = Self::response_queue();
963 let start_time
= std
::time
::Instant
::now();
965 let h2
= self.h2
.clone();
967 futures
::stream
::repeat(data
)
968 .take_while(move |_
| {
969 repeat
.fetch_add(1, Ordering
::SeqCst
);
970 Ok(start_time
.elapsed().as_secs() < 5)
972 .for_each(move |data
| {
975 let upload_queue
= upload_queue
.clone();
977 println
!("send test data ({} bytes)", data
.len());
978 let request
= H2Client
::request_builder("localhost", "POST", "speedtest", None
).unwrap();
979 h2
.send_request(request
, Some(bytes
::Bytes
::from(data
)))
980 .and_then(move |response
| {
981 upload_queue
.send(response
)
982 .map(|_
| ()).map_err(Error
::from
)
985 .then(move |result
| {
986 println
!("RESULT {:?}", result
);
987 upload_result
.map_err(Error
::from
).and_then(|upload1_result
| {
988 Ok(upload1_result
.and(result
))
993 let repeat
= repeat2
.load(Ordering
::SeqCst
);
994 println
!("Uploaded {} chunks in {} seconds.", repeat
, start_time
.elapsed().as_secs());
995 let speed
= ((item_len
*1000000*(repeat
as usize))/(1024*1024))/(start_time
.elapsed().as_micros() as usize);
997 println
!("Time per request: {} microseconds.", (start_time
.elapsed().as_micros())/(repeat
as u128
));
1005 pub struct H2Client
{
1006 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
1011 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
1015 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1016 let req
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1020 pub fn put(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1021 let req
= Self::request_builder("localhost", "PUT", path
, param
).unwrap();
1025 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1026 let req
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1030 pub fn download
<W
: Write
>(&self, path
: &str, param
: Option
<Value
>, output
: W
) -> impl Future
<Item
=W
, Error
=Error
> {
1031 let request
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
1033 self.send_request(request
, None
)
1034 .and_then(move |response
| {
1036 .map_err(Error
::from
)
1037 .and_then(move |resp
| {
1038 let status
= resp
.status();
1039 if !status
.is_success() {
1041 H2Client
::h2api_response(resp
)
1042 .and_then(|_
| { bail!("unknown error"); }
)
1045 let mut body
= resp
.into_body();
1046 let mut release_capacity
= body
.release_capacity().clone();
1050 .map_err(Error
::from
)
1051 .fold(output
, move |mut acc
, chunk
| {
1052 let _
= release_capacity
.release_capacity(chunk
.len());
1053 acc
.write_all(&chunk
)?
;
1062 pub fn upload(&self, path
: &str, param
: Option
<Value
>, data
: Vec
<u8>) -> impl Future
<Item
=Value
, Error
=Error
> {
1063 let request
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
1067 .map_err(Error
::from
)
1068 .and_then(move |mut send_request
| {
1069 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1070 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
)
1073 .map_err(Error
::from
)
1074 .and_then(Self::h2api_response
)
1081 request
: Request
<()>,
1082 ) -> impl Future
<Item
=Value
, Error
=Error
> {
1084 self.send_request(request
, None
)
1085 .and_then(move |response
| {
1087 .map_err(Error
::from
)
1088 .and_then(Self::h2api_response
)
1094 request
: Request
<()>,
1095 data
: Option
<bytes
::Bytes
>,
1096 ) -> impl Future
<Item
=h2
::client
::ResponseFuture
, Error
=Error
> {
1100 .map_err(Error
::from
)
1101 .and_then(move |mut send_request
| {
1102 if let Some(data
) = data
{
1103 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
1104 future
::Either
::A(PipeToSendStream
::new(data
, stream
)
1105 .and_then(move |_
| {
1106 future
::ok(response
)
1109 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
1110 future
::Either
::B(future
::ok(response
))
1115 fn h2api_response(response
: Response
<h2
::RecvStream
>) -> impl Future
<Item
=Value
, Error
=Error
> {
1117 let status
= response
.status();
1119 let (_head
, mut body
) = response
.into_parts();
1121 // The `release_capacity` handle allows the caller to manage
1124 // Whenever data is received, the caller is responsible for
1125 // releasing capacity back to the server once it has freed
1126 // the data from memory.
1127 let mut release_capacity
= body
.release_capacity().clone();
1131 // Let the server send more data.
1132 let _
= release_capacity
.release_capacity(chunk
.len());
1136 .map_err(Error
::from
)
1137 .and_then(move |data
| {
1138 let text
= String
::from_utf8(data
.to_vec()).unwrap();
1139 if status
.is_success() {
1141 let mut value
: Value
= serde_json
::from_str(&text
)?
;
1142 if let Some(map
) = value
.as_object_mut() {
1143 if let Some(data
) = map
.remove("data") {
1147 bail
!("got result without data property");
1152 bail
!("HTTP Error {}: {}", status
, text
);
1157 // Note: We always encode parameters with the url
1158 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<()>, Error
> {
1159 let path
= path
.trim_matches('
/'
);
1161 if let Some(data
) = data
{
1162 let query
= tools
::json_object_to_query(data
)?
;
1163 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
1164 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
1165 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
1166 let request
= Request
::builder()
1169 .header("User-Agent", "proxmox-backup-client/1.0")
1170 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
1174 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
1175 let request
= Request
::builder()
1178 .header("User-Agent", "proxmox-backup-client/1.0")
1179 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")