src/api2/admin/datastore/backup/service.rs: move service code into extra file

This commit is contained in:
Dietmar Maurer 2019-05-08 17:36:19 +02:00
parent 0aadd40b4f
commit bd1507c4fa
2 changed files with 121 additions and 107 deletions

View File

@ -1,12 +1,10 @@
use failure::*; use failure::*;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use futures::*; use futures::*;
use hyper::header::{HeaderValue, UPGRADE}; use hyper::header::{HeaderValue, UPGRADE};
use hyper::{Body, Request, Response, StatusCode}; use hyper::{Body, Response, StatusCode};
use hyper::http::request::Parts; use hyper::http::request::Parts;
use chrono::{Local, TimeZone}; use chrono::{Local, TimeZone};
@ -15,12 +13,14 @@ use serde_json::Value;
use crate::tools; use crate::tools;
use crate::api_schema::router::*; use crate::api_schema::router::*;
use crate::api_schema::*; use crate::api_schema::*;
use crate::server::formatter::*;
use crate::server::WorkerTask; use crate::server::WorkerTask;
mod environment; mod environment;
use environment::*; use environment::*;
mod service;
use service::*;
pub fn api_method_upgrade_backup() -> ApiAsyncMethod { pub fn api_method_upgrade_backup() -> ApiAsyncMethod {
ApiAsyncMethod::new( ApiAsyncMethod::new(
upgrade_to_backup_protocol, upgrade_to_backup_protocol,
@ -32,109 +32,6 @@ pub fn api_method_upgrade_backup() -> ApiAsyncMethod {
) )
} }
static PROXMOX_BACKUP_PROTOCOL_ID: &str = "proxmox-backup-protocol-h2";
lazy_static!{
static ref BACKUP_ROUTER: Router = backup_api();
}
pub struct BackupService {
rpcenv: BackupEnvironment,
worker: Arc<WorkerTask>,
}
impl BackupService {
fn new(rpcenv: BackupEnvironment, worker: Arc<WorkerTask>) -> Self {
Self { rpcenv, worker }
}
fn handle_request(&self, req: Request<Body>) -> BoxFut {
let (parts, body) = req.into_parts();
let method = parts.method.clone();
let (path, components) = match tools::normalize_uri_path(parts.uri.path()) {
Ok((p,c)) => (p, c),
Err(err) => return Box::new(future::err(http_err!(BAD_REQUEST, err.to_string()))),
};
let formatter = &JSON_FORMATTER;
self.worker.log(format!("H2 REQUEST {} {}", method, path));
self.worker.log(format!("H2 COMPO {:?}", components));
let mut uri_param = HashMap::new();
match BACKUP_ROUTER.find_method(&components, method, &mut uri_param) {
MethodDefinition::None => {
let err = http_err!(NOT_FOUND, "Path not found.".to_string());
return Box::new(future::ok((formatter.format_error)(err)));
}
MethodDefinition::Simple(api_method) => {
return crate::server::rest::handle_sync_api_request(self.rpcenv.clone(), api_method, formatter, parts, body, uri_param);
}
MethodDefinition::Async(async_method) => {
return crate::server::rest::handle_async_api_request(self.rpcenv.clone(), async_method, formatter, parts, body, uri_param);
}
}
}
fn log_response(worker: Arc<WorkerTask>, method: hyper::Method, path: &str, resp: &Response<Body>) {
let status = resp.status();
if !status.is_success() {
let reason = status.canonical_reason().unwrap_or("unknown reason");
let mut message = "request failed";
if let Some(data) = resp.extensions().get::<ErrorMessageExtension>() {
message = &data.0;
}
worker.log(format!("{} {}: {} {}: {}", method.as_str(), path, status.as_str(), reason, message));
}
}
}
impl hyper::service::Service for BackupService {
type ReqBody = Body;
type ResBody = Body;
type Error = hyper::Error;
type Future = Box<Future<Item = Response<Body>, Error = Self::Error> + Send>;
fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
let path = req.uri().path().to_owned();
let method = req.method().clone();
let worker = self.worker.clone();
Box::new(self.handle_request(req).then(move |result| {
match result {
Ok(res) => {
Self::log_response(worker, method, &path, &res);
Ok::<_, hyper::Error>(res)
}
Err(err) => {
if let Some(apierr) = err.downcast_ref::<HttpError>() {
let mut resp = Response::new(Body::from(apierr.message.clone()));
*resp.status_mut() = apierr.code;
Self::log_response(worker, method, &path, &resp);
Ok(resp)
} else {
let mut resp = Response::new(Body::from(err.to_string()));
*resp.status_mut() = StatusCode::BAD_REQUEST;
Self::log_response(worker, method, &path, &resp);
Ok(resp)
}
}
}
}))
}
}
fn upgrade_to_backup_protocol( fn upgrade_to_backup_protocol(
parts: Parts, parts: Parts,
req_body: Body, req_body: Body,
@ -143,6 +40,8 @@ fn upgrade_to_backup_protocol(
rpcenv: &mut RpcEnvironment, rpcenv: &mut RpcEnvironment,
) -> Result<BoxFut, Error> { ) -> Result<BoxFut, Error> {
static PROXMOX_BACKUP_PROTOCOL_ID: &str = "proxmox-backup-protocol-h2";
let store = tools::required_string_param(&param, "store")?; let store = tools::required_string_param(&param, "store")?;
let backup_type = tools::required_string_param(&param, "backup-type")?; let backup_type = tools::required_string_param(&param, "backup-type")?;
let backup_id = tools::required_string_param(&param, "backup-id")?; let backup_id = tools::required_string_param(&param, "backup-id")?;

View File

@ -0,0 +1,115 @@
use failure::*;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Arc;
use futures::*;
use hyper::{Body, Request, Response, StatusCode};
use crate::tools;
use crate::api_schema::router::*;
use crate::server::formatter::*;
use crate::server::WorkerTask;
use super::environment::*;
lazy_static!{
static ref BACKUP_ROUTER: Router = super::backup_api();
}
pub struct BackupService {
rpcenv: BackupEnvironment,
worker: Arc<WorkerTask>,
}
impl BackupService {
pub fn new(rpcenv: BackupEnvironment, worker: Arc<WorkerTask>) -> Self {
Self { rpcenv, worker }
}
fn handle_request(&self, req: Request<Body>) -> BoxFut {
let (parts, body) = req.into_parts();
let method = parts.method.clone();
let (path, components) = match tools::normalize_uri_path(parts.uri.path()) {
Ok((p,c)) => (p, c),
Err(err) => return Box::new(future::err(http_err!(BAD_REQUEST, err.to_string()))),
};
let formatter = &JSON_FORMATTER;
self.worker.log(format!("H2 REQUEST {} {}", method, path));
self.worker.log(format!("H2 COMPO {:?}", components));
let mut uri_param = HashMap::new();
match BACKUP_ROUTER.find_method(&components, method, &mut uri_param) {
MethodDefinition::None => {
let err = http_err!(NOT_FOUND, "Path not found.".to_string());
return Box::new(future::ok((formatter.format_error)(err)));
}
MethodDefinition::Simple(api_method) => {
return crate::server::rest::handle_sync_api_request(self.rpcenv.clone(), api_method, formatter, parts, body, uri_param);
}
MethodDefinition::Async(async_method) => {
return crate::server::rest::handle_async_api_request(self.rpcenv.clone(), async_method, formatter, parts, body, uri_param);
}
}
}
fn log_response(worker: Arc<WorkerTask>, method: hyper::Method, path: &str, resp: &Response<Body>) {
let status = resp.status();
if !status.is_success() {
let reason = status.canonical_reason().unwrap_or("unknown reason");
let mut message = "request failed";
if let Some(data) = resp.extensions().get::<ErrorMessageExtension>() {
message = &data.0;
}
worker.log(format!("{} {}: {} {}: {}", method.as_str(), path, status.as_str(), reason, message));
}
}
}
impl hyper::service::Service for BackupService {
type ReqBody = Body;
type ResBody = Body;
type Error = hyper::Error;
type Future = Box<Future<Item = Response<Body>, Error = Self::Error> + Send>;
fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
let path = req.uri().path().to_owned();
let method = req.method().clone();
let worker = self.worker.clone();
Box::new(self.handle_request(req).then(move |result| {
match result {
Ok(res) => {
Self::log_response(worker, method, &path, &res);
Ok::<_, hyper::Error>(res)
}
Err(err) => {
if let Some(apierr) = err.downcast_ref::<HttpError>() {
let mut resp = Response::new(Body::from(apierr.message.clone()));
*resp.status_mut() = apierr.code;
Self::log_response(worker, method, &path, &resp);
Ok(resp)
} else {
let mut resp = Response::new(Body::from(err.to_string()));
*resp.status_mut() = StatusCode::BAD_REQUEST;
Self::log_response(worker, method, &path, &resp);
Ok(resp)
}
}
}
}))
}
}