]>
Commit | Line | Data |
---|---|---|
803e7110 | 1 | use anyhow::{Error}; |
319e4255 DM |
2 | |
3 | use std::collections::HashMap; | |
2a16daaf | 4 | use std::pin::Pin; |
319e4255 | 5 | use std::sync::Arc; |
3a1a7cbd | 6 | use std::task::{Context, Poll}; |
319e4255 DM |
7 | |
8 | use futures::*; | |
9 | use hyper::{Body, Request, Response, StatusCode}; | |
10 | ||
6b5dc96c WB |
11 | use proxmox::api::{ApiResponseFuture, HttpError, Router, RpcEnvironment}; |
12 | use proxmox::http_err; | |
4da0705c | 13 | |
85ec987a DM |
14 | use crate::{normalize_uri_path, WorkerTask}; |
15 | use crate::formatter::*; | |
dc28aa1a | 16 | |
319e4255 DM |
17 | /// Hyper Service implementation to handle stateful H2 connections. |
18 | /// | |
19 | /// We use this kind of service to handle backup protocol | |
20 | /// connections. State is stored inside the generic ``rpcenv``. Logs | |
21 | /// goes into the ``WorkerTask`` log. | |
22 | pub struct H2Service<E> { | |
23 | router: &'static Router, | |
24 | rpcenv: E, | |
25 | worker: Arc<WorkerTask>, | |
26 | debug: bool, | |
27 | } | |
28 | ||
29 | impl <E: RpcEnvironment + Clone> H2Service<E> { | |
30 | ||
31 | pub fn new(rpcenv: E, worker: Arc<WorkerTask>, router: &'static Router, debug: bool) -> Self { | |
32 | Self { rpcenv, worker, router, debug } | |
33 | } | |
34 | ||
35 | pub fn debug<S: AsRef<str>>(&self, msg: S) { | |
020c8e69 | 36 | if self.debug { self.worker.log_message(msg); } |
319e4255 DM |
37 | } |
38 | ||
3e2c8347 | 39 | fn handle_request(&self, req: Request<Body>) -> ApiResponseFuture { |
319e4255 DM |
40 | |
41 | let (parts, body) = req.into_parts(); | |
42 | ||
43 | let method = parts.method.clone(); | |
44 | ||
cc674416 | 45 | let (path, components) = match normalize_uri_path(parts.uri.path()) { |
319e4255 | 46 | Ok((p,c)) => (p, c), |
df9109d4 | 47 | Err(err) => return future::err(http_err!(BAD_REQUEST, "{}", err)).boxed(), |
319e4255 DM |
48 | }; |
49 | ||
50 | self.debug(format!("{} {}", method, path)); | |
51 | ||
52 | let mut uri_param = HashMap::new(); | |
53 | ||
962553d2 | 54 | let formatter = JSON_FORMATTER; |
319e4255 DM |
55 | |
56 | match self.router.find_method(&components, method, &mut uri_param) { | |
3de9361d | 57 | None => { |
df9109d4 | 58 | let err = http_err!(NOT_FOUND, "Path '{}' not found.", path); |
962553d2 | 59 | future::ok(formatter.format_error(err)).boxed() |
319e4255 | 60 | } |
3de9361d | 61 | Some(api_method) => { |
85ec987a | 62 | crate::rest::handle_api_request( |
764bdf54 | 63 | self.rpcenv.clone(), api_method, formatter, parts, body, uri_param).boxed() |
319e4255 DM |
64 | } |
65 | } | |
66 | } | |
67 | ||
68 | fn log_response(worker: Arc<WorkerTask>, method: hyper::Method, path: &str, resp: &Response<Body>) { | |
69 | ||
70 | let status = resp.status(); | |
71 | ||
72 | if !status.is_success() { | |
73 | let reason = status.canonical_reason().unwrap_or("unknown reason"); | |
74 | ||
75 | let mut message = "request failed"; | |
76 | if let Some(data) = resp.extensions().get::<ErrorMessageExtension>() { | |
77 | message = &data.0; | |
78 | } | |
79 | ||
020c8e69 DM |
80 | worker.log_message(format!( |
81 | "{} {}: {} {}: {}", | |
82 | method.as_str(), | |
83 | path, | |
84 | status.as_str(), | |
85 | reason, | |
86 | message | |
87 | )); | |
319e4255 DM |
88 | } |
89 | } | |
90 | } | |
91 | ||
3a1a7cbd WB |
92 | impl <E: RpcEnvironment + Clone> tower_service::Service<Request<Body>> for H2Service<E> { |
93 | type Response = Response<Body>; | |
319e4255 | 94 | type Error = Error; |
2a16daaf FG |
95 | #[allow(clippy::type_complexity)] |
96 | type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; | |
319e4255 | 97 | |
3a1a7cbd WB |
98 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
99 | Poll::Ready(Ok(())) | |
100 | } | |
101 | ||
102 | fn call(&mut self, req: Request<Body>) -> Self::Future { | |
319e4255 DM |
103 | let path = req.uri().path().to_owned(); |
104 | let method = req.method().clone(); | |
105 | let worker = self.worker.clone(); | |
106 | ||
28f3b0df | 107 | self.handle_request(req) |
3a1a7cbd | 108 | .map(move |result| match result { |
319e4255 DM |
109 | Ok(res) => { |
110 | Self::log_response(worker, method, &path, &res); | |
111 | Ok::<_, Error>(res) | |
112 | } | |
113 | Err(err) => { | |
114 | if let Some(apierr) = err.downcast_ref::<HttpError>() { | |
115 | let mut resp = Response::new(Body::from(apierr.message.clone())); | |
116 | resp.extensions_mut().insert(ErrorMessageExtension(apierr.message.clone())); | |
117 | *resp.status_mut() = apierr.code; | |
118 | Self::log_response(worker, method, &path, &resp); | |
119 | Ok(resp) | |
120 | } else { | |
121 | let mut resp = Response::new(Body::from(err.to_string())); | |
122 | resp.extensions_mut().insert(ErrorMessageExtension(err.to_string())); | |
123 | *resp.status_mut() = StatusCode::BAD_REQUEST; | |
124 | Self::log_response(worker, method, &path, &resp); | |
125 | Ok(resp) | |
126 | } | |
127 | } | |
3a1a7cbd WB |
128 | }) |
129 | .boxed() | |
319e4255 DM |
130 | } |
131 | } |