1 use anyhow
::{bail, format_err, Error}
;
3 use hyper
::header
::{self, HeaderValue, UPGRADE}
;
4 use hyper
::http
::request
::Parts
;
5 use hyper
::{Body, Response, StatusCode}
;
8 use proxmox
::{sortable, identity}
;
9 use proxmox
::api
::{ApiResponseFuture, ApiHandler, ApiMethod, Router, RpcEnvironment, Permission}
;
10 use proxmox
::api
::schema
::*;
11 use proxmox
::http_err
;
13 use crate::api2
::types
::*;
15 use crate::server
::{WorkerTask, H2Service}
;
17 use crate::config
::acl
::PRIV_DATASTORE_READ
;
18 use crate::config
::cached_user_info
::CachedUserInfo
;
19 use crate::api2
::helpers
;
24 pub const ROUTER
: Router
= Router
::new()
25 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
28 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
29 &ApiHandler
::AsyncHttp(&upgrade_to_backup_reader_protocol
),
31 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!(), "')."),
33 ("store", false, &DATASTORE_SCHEMA
),
34 ("backup-type", false, &BACKUP_TYPE_SCHEMA
),
35 ("backup-id", false, &BACKUP_ID_SCHEMA
),
36 ("backup-time", false, &BACKUP_TIME_SCHEMA
),
37 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
41 // Note: parameter 'store' is no uri parameter, so we need to test inside function body
42 Some("The user needs Datastore.Read privilege on /datastore/{store}."),
46 fn upgrade_to_backup_reader_protocol(
51 rpcenv
: Box
<dyn RpcEnvironment
>,
52 ) -> ApiResponseFuture
{
55 let debug
= param
["debug"].as_bool().unwrap_or(false);
57 let userid
: Userid
= rpcenv
.get_user().unwrap().parse()?
;
58 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
60 let user_info
= CachedUserInfo
::new()?
;
61 user_info
.check_privs(&userid
, &["datastore", &store
], PRIV_DATASTORE_READ
, false)?
;
63 let datastore
= DataStore
::lookup_datastore(&store
)?
;
65 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
66 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
67 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
72 .ok_or_else(|| format_err
!("missing Upgrade header"))?
75 if protocols
!= PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!() {
76 bail
!("invalid protocol name");
79 if parts
.version
>= http
::version
::Version
::HTTP_2
{
80 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
83 let env_type
= rpcenv
.env_type();
85 let backup_dir
= BackupDir
::new(backup_type
, backup_id
, backup_time
)?
;
86 let path
= datastore
.base_path();
88 //let files = BackupInfo::list_files(&path, &backup_dir)?;
90 let worker_id
= format
!("{}_{}_{}_{:08X}", store
, backup_type
, backup_id
, backup_dir
.backup_time());
92 WorkerTask
::spawn("reader", Some(worker_id
), userid
.clone(), true, move |worker
| {
93 let mut env
= ReaderEnvironment
::new(
103 env
.log(format
!("starting new backup reader datastore '{}': {:?}", store
, path
));
105 let service
= H2Service
::new(env
.clone(), worker
.clone(), &READER_API_ROUTER
, debug
);
107 let abort_future
= worker
.abort_future();
109 let req_fut
= req_body
111 .map_err(Error
::from
)
113 let env
= env
.clone();
115 env
.debug("protocol upgrade done");
117 let mut http
= hyper
::server
::conn
::Http
::new();
118 http
.http2_only(true);
119 // increase window size: todo - find optiomal size
120 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
121 http
.http2_initial_stream_window_size(window_size
);
122 http
.http2_initial_connection_window_size(window_size
);
123 http
.http2_max_frame_size(4*1024*1024);
125 http
.serve_connection(conn
, service
)
126 .map_err(Error
::from
)
129 let abort_future
= abort_future
130 .map(|_
| Err(format_err
!("task aborted")));
132 use futures
::future
::Either
;
133 futures
::future
::select(req_fut
, abort_future
)
134 .map(|res
| match res
{
135 Either
::Left((Ok(res
), _
)) => Ok(res
),
136 Either
::Left((Err(err
), _
)) => Err(err
),
137 Either
::Right((Ok(res
), _
)) => Ok(res
),
138 Either
::Right((Err(err
), _
)) => Err(err
),
140 .map_ok(move |_
| env
.log("reader finished successfully"))
143 let response
= Response
::builder()
144 .status(StatusCode
::SWITCHING_PROTOCOLS
)
145 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!()))
146 .body(Body
::empty())?
;
152 pub const READER_API_ROUTER
: Router
= Router
::new()
155 "chunk", &Router
::new()
156 .download(&API_METHOD_DOWNLOAD_CHUNK
)
159 "download", &Router
::new()
160 .download(&API_METHOD_DOWNLOAD_FILE
)
163 "speedtest", &Router
::new()
164 .download(&API_METHOD_SPEEDTEST
)
169 pub const API_METHOD_DOWNLOAD_FILE
: ApiMethod
= ApiMethod
::new(
170 &ApiHandler
::AsyncHttp(&download_file
),
172 "Download specified file.",
174 ("file-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
184 rpcenv
: Box
<dyn RpcEnvironment
>,
185 ) -> ApiResponseFuture
{
188 let env
: &ReaderEnvironment
= rpcenv
.as_ref();
190 let file_name
= tools
::required_string_param(¶m
, "file-name")?
.to_owned();
192 let mut path
= env
.datastore
.base_path();
193 path
.push(env
.backup_dir
.relative_path());
194 path
.push(&file_name
);
196 env
.log(format
!("download {:?}", path
.clone()));
198 helpers
::create_download_response(path
).await
203 pub const API_METHOD_DOWNLOAD_CHUNK
: ApiMethod
= ApiMethod
::new(
204 &ApiHandler
::AsyncHttp(&download_chunk
),
206 "Download specified chunk.",
208 ("digest", false, &CHUNK_DIGEST_SCHEMA
),
218 rpcenv
: Box
<dyn RpcEnvironment
>,
219 ) -> ApiResponseFuture
{
222 let env
: &ReaderEnvironment
= rpcenv
.as_ref();
224 let digest_str
= tools
::required_string_param(¶m
, "digest")?
;
225 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
227 let (path
, _
) = env
.datastore
.chunk_path(&digest
);
228 let path2
= path
.clone();
230 env
.debug(format
!("download chunk {:?}", path
));
232 let data
= tools
::runtime
::block_in_place(|| std
::fs
::read(path
))
233 .map_err(move |err
| http_err
!(BAD_REQUEST
, "reading file {:?} failed: {}", path2
, err
))?
;
235 let body
= Body
::from(data
);
237 // fixme: set other headers ?
238 Ok(Response
::builder()
239 .status(StatusCode
::OK
)
240 .header(header
::CONTENT_TYPE
, "application/octet-stream")
247 fn download_chunk_old(
252 rpcenv: Box<dyn RpcEnvironment>,
253 ) -> Result<ApiResponseFuture, Error> {
255 let env: &ReaderEnvironment = rpcenv.as_ref();
256 let env2 = env.clone();
258 let digest_str = tools::required_string_param(¶m, "digest")?;
259 let digest = proxmox::tools::hex_to_digest(digest_str)?;
261 let (path, _) = env.datastore.chunk_path(&digest);
263 let path2 = path.clone();
264 let path3 = path.clone();
266 let response_future = tokio::fs::File::open(path)
267 .map_err(move |err| http_err!(BAD_REQUEST, "open file {:?} failed: {}", path2, err))
268 .and_then(move |file| {
269 env2.debug(format!("download chunk {:?}", path3));
270 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
271 .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()));
273 let body = Body::wrap_stream(payload);
275 // fixme: set other headers ?
276 futures::future::ok(Response::builder()
277 .status(StatusCode::OK)
278 .header(header::CONTENT_TYPE, "application/octet-stream")
283 Ok(Box::new(response_future))
287 pub const API_METHOD_SPEEDTEST
: ApiMethod
= ApiMethod
::new(
288 &ApiHandler
::AsyncHttp(&speedtest
),
289 &ObjectSchema
::new("Test 4M block download speed.", &[])
297 _rpcenv
: Box
<dyn RpcEnvironment
>,
298 ) -> ApiResponseFuture
{
300 let buffer
= vec
![65u8; 1024*1024]; // nonsense [A,A,A...]
302 let body
= Body
::from(buffer
);
304 let response
= Response
::builder()
305 .status(StatusCode
::OK
)
306 .header(header
::CONTENT_TYPE
, "application/octet-stream")
310 future
::ok(response
).boxed()