use std::time::Duration;
use isothrum_runner::tls::{Refusal, Tls, Trust};
use serde::de::DeserializeOwned;
use self::api::{Iface, Node, NodeStatus, Storage, Ticket};
use super::host_for_url;
pub mod api;
pub mod bootstrap;
pub mod check;
pub mod node;
pub mod placement;
pub const DEFAULT_PORT: u16 = 8006;
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(8);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Server {
pub host: String,
pub port: u16,
}
impl Server {
#[must_use]
pub fn new(host: impl Into<String>, port: u16) -> Server {
Server { host: host.into(), port }
}
#[must_use]
pub fn api_url(&self) -> String {
format!("https://{}:{}/api2/json", host_for_url(&self.host), self.port)
}
#[must_use]
pub fn endpoint(&self) -> String {
format!("https://{}:{}/", host_for_url(&self.host), self.port)
}
}
#[derive(Clone, PartialEq, Eq)]
pub enum Credentials {
Token {
id: String,
secret: String,
},
Password {
user: String,
password: String,
},
}
impl Credentials {
#[must_use]
pub fn from_login(login: &str, secret: &str) -> Credentials {
let login = with_default_realm(login);
if is_token(&login) {
Credentials::Token {
id: login,
secret: secret.to_owned(),
}
} else {
Credentials::Password {
user: login,
password: secret.to_owned(),
}
}
}
#[must_use]
pub fn user(&self) -> &str {
match self {
Credentials::Token { id, .. } => token_user(id),
Credentials::Password { user, .. } => user,
}
}
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Credentials::Token { id, .. } => f.debug_struct("Token").field("id", id).finish_non_exhaustive(),
Credentials::Password { user, .. } => f.debug_struct("Password").field("user", user).finish_non_exhaustive(),
}
}
}
#[must_use]
pub fn with_default_realm(login: &str) -> String {
let (user, token) = login.split_once('!').map_or((login, None), |(u, t)| (u, Some(t)));
let user = if user.is_empty() || user.contains('@') {
user.to_owned()
} else {
format!("{user}@pam")
};
token.map_or_else(|| user.clone(), |t| format!("{user}!{t}"))
}
#[must_use]
pub fn is_token(login: &str) -> bool {
login.split_once('!').is_some_and(|(user, name)| user.contains('@') && !name.is_empty())
}
#[must_use]
pub fn token_user(login: &str) -> &str {
login.split_once('!').map_or(login, |(u, _)| u)
}
#[must_use]
pub fn terraform_token(id: &str, secret: &str) -> String {
format!("{id}={secret}")
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SignInError {
#[error("Proxmox VE refused the credentials")]
Rejected,
#[error("{0}")]
Certificate(Refusal),
#[error("{0}")]
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CallError {
#[error("HTTP {0}")]
Status(u16),
#[error("{0}")]
Certificate(Refusal),
#[error("there is no node \"{asked}\" (found: {})", found.join(", "))]
NoSuchNode {
asked: String,
found: Vec<String>,
},
#[error("this user can't see any node")]
NoNode,
#[error("{0}")]
Other(String),
}
pub struct Session {
http: reqwest::Client,
tls: Tls,
base: String,
auth: (&'static str, String),
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session").field("base", &self.base).finish_non_exhaustive()
}
}
pub async fn sign_in(server: &Server, credentials: &Credentials, trust: Trust) -> Result<Session, SignInError> {
let tls = Tls::new(trust).map_err(|e| SignInError::Failed(e.to_string()))?;
let http = reqwest::Client::builder()
.tls_backend_preconfigured(tls.config().clone())
.connect_timeout(REQUEST_TIMEOUT)
.timeout(REQUEST_TIMEOUT)
.build()
.map_err(|e| SignInError::Failed(format!("no HTTP client: {}", chain(&e))))?;
let base = server.api_url();
match credentials {
Credentials::Token { id, secret } => {
let session = Session {
http,
tls,
base,
auth: ("Authorization", format!("PVEAPIToken={id}={secret}")),
};
match session.get("/version").await {
Ok(_) => Ok(session),
Err(CallError::Status(401)) => Err(SignInError::Rejected),
Err(CallError::Certificate(refusal)) => Err(SignInError::Certificate(refusal)),
Err(e) => Err(SignInError::Failed(e.to_string())),
}
}
Credentials::Password { user, password } => {
let sent = http
.post(format!("{base}/access/ticket"))
.form(&[("username", user.as_str()), ("password", password.as_str())])
.send()
.await;
let res = match sent {
Ok(res) => res,
Err(e) => return Err(tls.refused().map_or_else(|| SignInError::Failed(chain(&e)), SignInError::Certificate)),
};
if res.status().as_u16() == 401 {
return Err(SignInError::Rejected);
}
if !res.status().is_success() {
return Err(SignInError::Failed(format!("the API answered HTTP {}", res.status().as_u16())));
}
let body = res.text().await.map_err(|e| SignInError::Failed(chain(&e)))?;
let ticket = api::data::<Ticket>(&body)
.map_err(|e| SignInError::Failed(format!("the sign-in's answer isn't the API's: {e}")))?
.ticket
.ok_or_else(|| SignInError::Failed("no ticket in the sign-in's answer".into()))?;
Ok(Session {
http,
tls,
base,
auth: ("Cookie", format!("PVEAuthCookie={ticket}")),
})
}
}
}
pub(crate) fn chain(e: &dyn std::error::Error) -> String {
let mut line = e.to_string();
let mut cause = e.source();
while let Some(c) = cause {
line = format!("{line}: {c}");
cause = c.source();
}
line
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capacity {
pub cores: u64,
pub mem_total: u64,
pub mem_free: u64,
}
impl Capacity {
#[must_use]
pub fn of(status: &NodeStatus) -> Option<Capacity> {
let (cpu, memory) = (status.cpuinfo.as_ref()?, status.memory.as_ref()?);
Some(Capacity {
cores: cpu.cpus?,
mem_total: memory.total?,
mem_free: memory.free?,
})
}
}
impl Session {
pub async fn get(&self, path: &str) -> Result<String, CallError> {
let sent = self.http.get(format!("{}{path}", self.base)).header(self.auth.0, &self.auth.1).send().await;
let res = match sent {
Ok(res) => res,
Err(e) => return Err(self.tls.refused().map_or_else(|| CallError::Other(chain(&e)), CallError::Certificate)),
};
if !res.status().is_success() {
return Err(CallError::Status(res.status().as_u16()));
}
res.text().await.map_err(|e| CallError::Other(chain(&e)))
}
pub async fn call<T: DeserializeOwned + Default>(&self, path: &str) -> Result<T, CallError> {
read_data(&self.get(path).await?)
}
pub async fn nodes(&self) -> Result<Vec<Node>, CallError> {
self.call("/nodes").await
}
pub async fn node(&self, asked: Option<&str>) -> Result<String, CallError> {
pick_node(&self.nodes().await?, asked)
}
pub async fn storages(&self, node: &str) -> Result<Vec<Storage>, CallError> {
self.call(&format!("/nodes/{node}/storage")).await
}
pub async fn network(&self, node: &str) -> Result<Vec<Iface>, CallError> {
self.call(&format!("/nodes/{node}/network")).await
}
pub async fn bridges(&self, node: &str) -> Result<Vec<Iface>, CallError> {
self.call(&format!("/nodes/{node}/network?type=any_bridge")).await
}
pub async fn status(&self, node: &str) -> Result<NodeStatus, CallError> {
self.call(&format!("/nodes/{node}/status")).await
}
pub async fn capacity(&self, node: &str) -> Result<Capacity, CallError> {
Capacity::of(&self.status(node).await?).ok_or_else(|| CallError::Other(format!("the node {node} reported no cores or memory figures")))
}
}
fn read_data<T: DeserializeOwned + Default>(body: &str) -> Result<T, CallError> {
api::data(body).map_err(|e| CallError::Other(format!("the answer isn't the Proxmox VE API's: {e}")))
}
fn pick_node(nodes: &[Node], asked: Option<&str>) -> Result<String, CallError> {
let names: Vec<&str> = nodes.iter().filter_map(|n| n.node.as_deref()).collect();
match asked.filter(|n| !n.is_empty()) {
Some(n) if names.contains(&n) => Ok(n.to_owned()),
Some(n) => Err(CallError::NoSuchNode {
asked: n.to_owned(),
found: names.iter().map(|s| (*s).to_owned()).collect(),
}),
None => names.first().map(|s| (*s).to_owned()).ok_or(CallError::NoNode),
}
}
#[cfg(test)]
mod tests;