server/config: add mechanism to update template
instead of exposing handlebars itself, offer a register_template and a render_template ourselves. render_template checks if the template file was modified since the last render and reloads it when necessary Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
This commit is contained in:
parent
27fde64794
commit
2ab5acac5a
|
@ -1,5 +1,5 @@
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::path::Path;
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use anyhow::{bail, format_err, Error};
|
use anyhow::{bail, format_err, Error};
|
||||||
use futures::*;
|
use futures::*;
|
||||||
|
@ -53,6 +53,10 @@ async fn run() -> Result<(), Error> {
|
||||||
config.add_alias("css", "/usr/share/javascript/proxmox-backup/css");
|
config.add_alias("css", "/usr/share/javascript/proxmox-backup/css");
|
||||||
config.add_alias("docs", "/usr/share/doc/proxmox-backup/html");
|
config.add_alias("docs", "/usr/share/doc/proxmox-backup/html");
|
||||||
|
|
||||||
|
let mut indexpath = PathBuf::from(buildcfg::JS_DIR);
|
||||||
|
indexpath.push("index.hbs");
|
||||||
|
config.register_template("index", &indexpath)?;
|
||||||
|
|
||||||
let rest_server = RestServer::new(config);
|
let rest_server = RestServer::new(config);
|
||||||
|
|
||||||
//openssl req -x509 -newkey rsa:4096 -keyout /etc/proxmox-backup/proxy.key -out /etc/proxmox-backup/proxy.pem -nodes
|
//openssl req -x509 -newkey rsa:4096 -keyout /etc/proxmox-backup/proxy.key -out /etc/proxmox-backup/proxy.pem -nodes
|
||||||
|
|
|
@ -1,9 +1,13 @@
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::{PathBuf};
|
use std::path::PathBuf;
|
||||||
use anyhow::Error;
|
use std::time::SystemTime;
|
||||||
|
use std::fs::metadata;
|
||||||
|
use std::sync::RwLock;
|
||||||
|
|
||||||
|
use anyhow::{bail, Error, format_err};
|
||||||
use hyper::Method;
|
use hyper::Method;
|
||||||
use handlebars::Handlebars;
|
use handlebars::Handlebars;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
use proxmox::api::{ApiMethod, Router, RpcEnvironmentType};
|
use proxmox::api::{ApiMethod, Router, RpcEnvironmentType};
|
||||||
|
|
||||||
|
@ -12,21 +16,20 @@ pub struct ApiConfig {
|
||||||
router: &'static Router,
|
router: &'static Router,
|
||||||
aliases: HashMap<String, PathBuf>,
|
aliases: HashMap<String, PathBuf>,
|
||||||
env_type: RpcEnvironmentType,
|
env_type: RpcEnvironmentType,
|
||||||
pub templates: Handlebars<'static>,
|
templates: RwLock<Handlebars<'static>>,
|
||||||
|
template_files: RwLock<HashMap<String, (SystemTime, PathBuf)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApiConfig {
|
impl ApiConfig {
|
||||||
|
|
||||||
pub fn new<B: Into<PathBuf>>(basedir: B, router: &'static Router, env_type: RpcEnvironmentType) -> Result<Self, Error> {
|
pub fn new<B: Into<PathBuf>>(basedir: B, router: &'static Router, env_type: RpcEnvironmentType) -> Result<Self, Error> {
|
||||||
let mut templates = Handlebars::new();
|
|
||||||
let basedir = basedir.into();
|
|
||||||
templates.register_template_file("index", basedir.join("index.hbs"))?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
basedir,
|
basedir: basedir.into(),
|
||||||
router,
|
router,
|
||||||
aliases: HashMap::new(),
|
aliases: HashMap::new(),
|
||||||
env_type,
|
env_type,
|
||||||
templates
|
templates: RwLock::new(Handlebars::new()),
|
||||||
|
template_files: RwLock::new(HashMap::new()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -67,4 +70,52 @@ impl ApiConfig {
|
||||||
pub fn env_type(&self) -> RpcEnvironmentType {
|
pub fn env_type(&self) -> RpcEnvironmentType {
|
||||||
self.env_type
|
self.env_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn register_template<P>(&self, name: &str, path: P) -> Result<(), Error>
|
||||||
|
where
|
||||||
|
P: Into<PathBuf>
|
||||||
|
{
|
||||||
|
if self.template_files.read().unwrap().contains_key(name) {
|
||||||
|
bail!("template already registered");
|
||||||
|
}
|
||||||
|
|
||||||
|
let path: PathBuf = path.into();
|
||||||
|
let metadata = metadata(&path)?;
|
||||||
|
let mtime = metadata.modified()?;
|
||||||
|
|
||||||
|
self.templates.write().unwrap().register_template_file(name, &path)?;
|
||||||
|
self.template_files.write().unwrap().insert(name.to_string(), (mtime, path));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if the template was modified since the last rendering
|
||||||
|
/// if yes, it loads a the new version of the template
|
||||||
|
pub fn render_template<T>(&self, name: &str, data: &T) -> Result<String, Error>
|
||||||
|
where
|
||||||
|
T: Serialize,
|
||||||
|
{
|
||||||
|
let path;
|
||||||
|
let mtime;
|
||||||
|
{
|
||||||
|
let template_files = self.template_files.read().unwrap();
|
||||||
|
let (old_mtime, old_path) = template_files.get(name).ok_or_else(|| format_err!("template not found"))?;
|
||||||
|
|
||||||
|
mtime = metadata(old_path)?.modified()?;
|
||||||
|
if mtime <= *old_mtime {
|
||||||
|
return self.templates.read().unwrap().render(name, data).map_err(|err| format_err!("{}", err));
|
||||||
|
}
|
||||||
|
path = old_path.to_path_buf();
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut template_files = self.template_files.write().unwrap();
|
||||||
|
let mut templates = self.templates.write().unwrap();
|
||||||
|
|
||||||
|
templates.register_template_file(name, &path)?;
|
||||||
|
template_files.insert(name.to_string(), (mtime, path));
|
||||||
|
|
||||||
|
templates.render(name, data).map_err(|err| format_err!("{}", err))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,7 +16,6 @@ use serde_json::{json, Value};
|
||||||
use tokio::fs::File;
|
use tokio::fs::File;
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
use url::form_urlencoded;
|
use url::form_urlencoded;
|
||||||
use handlebars::Handlebars;
|
|
||||||
|
|
||||||
use proxmox::http_err;
|
use proxmox::http_err;
|
||||||
use proxmox::api::{ApiHandler, ApiMethod, HttpError};
|
use proxmox::api::{ApiHandler, ApiMethod, HttpError};
|
||||||
|
@ -312,7 +311,7 @@ pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher +
|
||||||
Ok(resp)
|
Ok(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_index(username: Option<String>, token: Option<String>, template: &Handlebars, parts: Parts) -> Response<Body> {
|
fn get_index(username: Option<String>, token: Option<String>, api: &Arc<ApiConfig>, parts: Parts) -> Response<Body> {
|
||||||
|
|
||||||
let nodename = proxmox::tools::nodename();
|
let nodename = proxmox::tools::nodename();
|
||||||
let username = username.unwrap_or_else(|| String::from(""));
|
let username = username.unwrap_or_else(|| String::from(""));
|
||||||
|
@ -338,11 +337,11 @@ fn get_index(username: Option<String>, token: Option<String>, template: &Handleb
|
||||||
|
|
||||||
let mut ct = "text/html";
|
let mut ct = "text/html";
|
||||||
|
|
||||||
let index = match template.render("index", &data) {
|
let index = match api.render_template("index", &data) {
|
||||||
Ok(index) => index,
|
Ok(index) => index,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
ct = "text/plain";
|
ct = "text/plain";
|
||||||
format!("Error rendering template: {}", err.desc)
|
format!("Error rendering template: {}", err)
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -580,15 +579,15 @@ pub async fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> Result<R
|
||||||
match check_auth(&method, &ticket, &token, &user_info) {
|
match check_auth(&method, &ticket, &token, &user_info) {
|
||||||
Ok(username) => {
|
Ok(username) => {
|
||||||
let new_token = assemble_csrf_prevention_token(csrf_secret(), &username);
|
let new_token = assemble_csrf_prevention_token(csrf_secret(), &username);
|
||||||
return Ok(get_index(Some(username), Some(new_token), &api.templates, parts));
|
return Ok(get_index(Some(username), Some(new_token), &api, parts));
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
|
tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
|
||||||
return Ok(get_index(None, None, &api.templates, parts));
|
return Ok(get_index(None, None, &api, parts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Ok(get_index(None, None, &api.templates, parts));
|
return Ok(get_index(None, None, &api, parts));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let filename = api.find_alias(&components);
|
let filename = api.find_alias(&components);
|
||||||
|
|
Loading…
Reference in New Issue