1 //use chrono::{Local, TimeZone};
4 use hyper
::header
::{self, HeaderValue, UPGRADE}
;
5 use hyper
::http
::request
::Parts
;
6 use hyper
::{Body, Response, StatusCode}
;
9 use proxmox
::{sortable, identity}
;
10 use proxmox
::api
::http_err
;
11 use proxmox
::api
::{ApiFuture, ApiHandler, ApiMethod, Router, RpcEnvironment}
;
12 use proxmox
::api
::schema
::*;
14 use crate::api2
::types
::*;
16 use crate::server
::{WorkerTask, H2Service}
;
22 pub const ROUTER
: Router
= Router
::new()
23 .upgrade(&API_METHOD_UPGRADE_BACKUP
);
26 pub const API_METHOD_UPGRADE_BACKUP
: ApiMethod
= ApiMethod
::new(
27 &ApiHandler
::AsyncHttp(&upgrade_to_backup_reader_protocol
),
29 concat
!("Upgraded to backup protocol ('", PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!(), "')."),
31 ("store", false, &DATASTORE_SCHEMA
),
32 ("backup-type", false, &StringSchema
::new("Backup type.")
33 .format(&ApiStringFormat
::Enum(&["vm", "ct", "host"]))
36 ("backup-id", false, &StringSchema
::new("Backup ID.").schema()),
37 ("backup-time", false, &IntegerSchema
::new("Backup time (Unix epoch.)")
38 .minimum(1_547_797_308)
41 ("debug", true, &BooleanSchema
::new("Enable verbose debug logging.").schema()),
46 fn upgrade_to_backup_reader_protocol(
51 rpcenv
: Box
<dyn RpcEnvironment
>,
55 let debug
= param
["debug"].as_bool().unwrap_or(false);
57 let store
= tools
::required_string_param(¶m
, "store")?
.to_owned();
58 let datastore
= DataStore
::lookup_datastore(&store
)?
;
60 let backup_type
= tools
::required_string_param(¶m
, "backup-type")?
;
61 let backup_id
= tools
::required_string_param(¶m
, "backup-id")?
;
62 let backup_time
= tools
::required_integer_param(¶m
, "backup-time")?
;
67 .ok_or_else(|| format_err
!("missing Upgrade header"))?
70 if protocols
!= PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!() {
71 bail
!("invalid protocol name");
74 if parts
.version
>= http
::version
::Version
::HTTP_2
{
75 bail
!("unexpected http version '{:?}' (expected version < 2)", parts
.version
);
78 let username
= rpcenv
.get_user().unwrap();
79 let env_type
= rpcenv
.env_type();
81 let backup_dir
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
82 let path
= datastore
.base_path();
84 //let files = BackupInfo::list_files(&path, &backup_dir)?;
86 let worker_id
= format
!("{}_{}_{}_{:08X}", store
, backup_type
, backup_id
, backup_dir
.backup_time().timestamp());
88 WorkerTask
::spawn("reader", Some(worker_id
), &username
.clone(), true, move |worker
| {
89 let mut env
= ReaderEnvironment
::new(
90 env_type
, username
.clone(), worker
.clone(), datastore
, backup_dir
);
94 env
.log(format
!("starting new backup reader datastore '{}': {:?}", store
, path
));
96 let service
= H2Service
::new(env
.clone(), worker
.clone(), &READER_API_ROUTER
, debug
);
98 let abort_future
= worker
.abort_future();
100 let req_fut
= req_body
102 .map_err(Error
::from
)
104 let env
= env
.clone();
106 env
.debug("protocol upgrade done");
108 let mut http
= hyper
::server
::conn
::Http
::new();
109 http
.http2_only(true);
110 // increase window size: todo - find optiomal size
111 let window_size
= 32*1024*1024; // max = (1 << 31) - 2
112 http
.http2_initial_stream_window_size(window_size
);
113 http
.http2_initial_connection_window_size(window_size
);
115 http
.serve_connection(conn
, service
)
116 .map_err(Error
::from
)
119 let abort_future
= abort_future
120 .map(|_
| Err(format_err
!("task aborted")));
122 use futures
::future
::Either
;
123 futures
::future
::select(req_fut
, abort_future
)
124 .map(|res
| match res
{
125 Either
::Left((Ok(res
), _
)) => Ok(res
),
126 Either
::Left((Err(err
), _
)) => Err(err
),
127 Either
::Right((Ok(res
), _
)) => Ok(res
),
128 Either
::Right((Err(err
), _
)) => Err(err
),
130 .map_ok(move |_
| env
.log("reader finished sucessfully"))
133 let response
= Response
::builder()
134 .status(StatusCode
::SWITCHING_PROTOCOLS
)
135 .header(UPGRADE
, HeaderValue
::from_static(PROXMOX_BACKUP_READER_PROTOCOL_ID_V1
!()))
136 .body(Body
::empty())?
;
142 pub const READER_API_ROUTER
: Router
= Router
::new()
145 "chunk", &Router
::new()
146 .download(&API_METHOD_DOWNLOAD_CHUNK
)
149 "download", &Router
::new()
150 .download(&API_METHOD_DOWNLOAD_FILE
)
153 "speedtest", &Router
::new()
154 .download(&API_METHOD_SPEEDTEST
)
159 pub const API_METHOD_DOWNLOAD_FILE
: ApiMethod
= ApiMethod
::new(
160 &ApiHandler
::AsyncHttp(&download_file
),
162 "Download specified file.",
164 ("file-name", false, &crate::api2
::types
::BACKUP_ARCHIVE_NAME_SCHEMA
),
174 rpcenv
: Box
<dyn RpcEnvironment
>,
178 let env
: &ReaderEnvironment
= rpcenv
.as_ref();
180 let file_name
= tools
::required_string_param(¶m
, "file-name")?
.to_owned();
182 let mut path
= env
.datastore
.base_path();
183 path
.push(env
.backup_dir
.relative_path());
184 path
.push(&file_name
);
186 let path2
= path
.clone();
187 let path3
= path
.clone();
189 let file
= tokio
::fs
::File
::open(path
)
190 .map_err(move |err
| http_err
!(BAD_REQUEST
, format
!("open file {:?} failed: {}", path2
, err
)))
193 env
.log(format
!("download {:?}", path3
));
195 let payload
= tokio_util
::codec
::FramedRead
::new(file
, tokio_util
::codec
::BytesCodec
::new())
196 .map_ok(|bytes
| hyper
::body
::Bytes
::from(bytes
.freeze()));
198 let body
= Body
::wrap_stream(payload
);
200 // fixme: set other headers ?
201 Ok(Response
::builder()
202 .status(StatusCode
::OK
)
203 .header(header
::CONTENT_TYPE
, "application/octet-stream")
210 pub const API_METHOD_DOWNLOAD_CHUNK
: ApiMethod
= ApiMethod
::new(
211 &ApiHandler
::AsyncHttp(&download_chunk
),
213 "Download specified chunk.",
215 ("digest", false, &CHUNK_DIGEST_SCHEMA
),
225 rpcenv
: Box
<dyn RpcEnvironment
>,
229 let env
: &ReaderEnvironment
= rpcenv
.as_ref();
231 let digest_str
= tools
::required_string_param(¶m
, "digest")?
;
232 let digest
= proxmox
::tools
::hex_to_digest(digest_str
)?
;
234 let (path
, _
) = env
.datastore
.chunk_path(&digest
);
235 let path2
= path
.clone();
237 env
.debug(format
!("download chunk {:?}", path
));
239 let data
= tokio
::fs
::read(path
)
240 .map_err(move |err
| http_err
!(BAD_REQUEST
, format
!("reading file {:?} failed: {}", path2
, err
)))
243 let body
= Body
::from(data
);
245 // fixme: set other headers ?
246 Ok(Response
::builder()
247 .status(StatusCode
::OK
)
248 .header(header
::CONTENT_TYPE
, "application/octet-stream")
255 fn download_chunk_old(
260 rpcenv: Box<dyn RpcEnvironment>,
261 ) -> Result<ApiFuture, Error> {
263 let env: &ReaderEnvironment = rpcenv.as_ref();
264 let env2 = env.clone();
266 let digest_str = tools::required_string_param(¶m, "digest")?;
267 let digest = proxmox::tools::hex_to_digest(digest_str)?;
269 let (path, _) = env.datastore.chunk_path(&digest);
271 let path2 = path.clone();
272 let path3 = path.clone();
274 let response_future = tokio::fs::File::open(path)
275 .map_err(move |err| http_err!(BAD_REQUEST, format!("open file {:?} failed: {}", path2, err)))
276 .and_then(move |file| {
277 env2.debug(format!("download chunk {:?}", path3));
278 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
279 .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()));
281 let body = Body::wrap_stream(payload);
283 // fixme: set other headers ?
284 futures::future::ok(Response::builder()
285 .status(StatusCode::OK)
286 .header(header::CONTENT_TYPE, "application/octet-stream")
291 Ok(Box::new(response_future))
295 pub const API_METHOD_SPEEDTEST
: ApiMethod
= ApiMethod
::new(
296 &ApiHandler
::AsyncHttp(&speedtest
),
297 &ObjectSchema
::new("Test 4M block download speed.", &[])
305 _rpcenv
: Box
<dyn RpcEnvironment
>,
308 let buffer
= vec
![65u8; 1024*1024]; // nonsense [A,A,A...]
310 let body
= Body
::from(buffer
);
312 let response
= Response
::builder()
313 .status(StatusCode
::OK
)
314 .header(header
::CONTENT_TYPE
, "application/octet-stream")
318 future
::ok(response
).boxed()