1use std::time::Duration;
13
14use isothrum_runner::tls::{Refusal, Tls, Trust};
15use serde::de::DeserializeOwned;
16
17use self::api::{Iface, Node, NodeStatus, Storage, Ticket};
18use super::host_for_url;
19
20pub mod api;
21pub mod bootstrap;
22pub mod check;
23pub mod node;
24pub mod placement;
25
26pub const DEFAULT_PORT: u16 = 8006;
28
29pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(8);
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Server {
35 pub host: String,
37 pub port: u16,
39}
40
41impl Server {
42 #[must_use]
44 pub fn new(host: impl Into<String>, port: u16) -> Server {
45 Server { host: host.into(), port }
46 }
47
48 #[must_use]
50 pub fn api_url(&self) -> String {
51 format!("https://{}:{}/api2/json", host_for_url(&self.host), self.port)
52 }
53
54 #[must_use]
56 pub fn endpoint(&self) -> String {
57 format!("https://{}:{}/", host_for_url(&self.host), self.port)
58 }
59}
60
61#[derive(Clone, PartialEq, Eq)]
63pub enum Credentials {
64 Token {
66 id: String,
68 secret: String,
70 },
71 Password {
73 user: String,
75 password: String,
77 },
78}
79
80impl Credentials {
81 #[must_use]
85 pub fn from_login(login: &str, secret: &str) -> Credentials {
86 let login = with_default_realm(login);
87 if is_token(&login) {
88 Credentials::Token {
89 id: login,
90 secret: secret.to_owned(),
91 }
92 } else {
93 Credentials::Password {
94 user: login,
95 password: secret.to_owned(),
96 }
97 }
98 }
99
100 #[must_use]
102 pub fn user(&self) -> &str {
103 match self {
104 Credentials::Token { id, .. } => token_user(id),
105 Credentials::Password { user, .. } => user,
106 }
107 }
108}
109
110impl std::fmt::Debug for Credentials {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 match self {
113 Credentials::Token { id, .. } => f.debug_struct("Token").field("id", id).finish_non_exhaustive(),
114 Credentials::Password { user, .. } => f.debug_struct("Password").field("user", user).finish_non_exhaustive(),
115 }
116 }
117}
118
119#[must_use]
122pub fn with_default_realm(login: &str) -> String {
123 let (user, token) = login.split_once('!').map_or((login, None), |(u, t)| (u, Some(t)));
124 let user = if user.is_empty() || user.contains('@') {
125 user.to_owned()
126 } else {
127 format!("{user}@pam")
128 };
129 token.map_or_else(|| user.clone(), |t| format!("{user}!{t}"))
130}
131
132#[must_use]
135pub fn is_token(login: &str) -> bool {
136 login.split_once('!').is_some_and(|(user, name)| user.contains('@') && !name.is_empty())
137}
138
139#[must_use]
141pub fn token_user(login: &str) -> &str {
142 login.split_once('!').map_or(login, |(u, _)| u)
143}
144
145#[must_use]
147pub fn terraform_token(id: &str, secret: &str) -> String {
148 format!("{id}={secret}")
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
153#[non_exhaustive]
154pub enum SignInError {
155 #[error("Proxmox VE refused the credentials")]
157 Rejected,
158 #[error("{0}")]
160 Certificate(Refusal),
161 #[error("{0}")]
163 Failed(String),
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
168#[non_exhaustive]
169pub enum CallError {
170 #[error("HTTP {0}")]
172 Status(u16),
173 #[error("{0}")]
175 Certificate(Refusal),
176 #[error("there is no node \"{asked}\" (found: {})", found.join(", "))]
178 NoSuchNode {
179 asked: String,
181 found: Vec<String>,
183 },
184 #[error("this user can't see any node")]
186 NoNode,
187 #[error("{0}")]
189 Other(String),
190}
191
192pub struct Session {
194 http: reqwest::Client,
195 tls: Tls,
196 base: String,
197 auth: (&'static str, String),
199}
200
201impl std::fmt::Debug for Session {
202 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203 f.debug_struct("Session").field("base", &self.base).finish_non_exhaustive()
204 }
205}
206
207pub async fn sign_in(server: &Server, credentials: &Credentials, trust: Trust) -> Result<Session, SignInError> {
217 let tls = Tls::new(trust).map_err(|e| SignInError::Failed(e.to_string()))?;
218 let http = reqwest::Client::builder()
219 .tls_backend_preconfigured(tls.config().clone())
220 .connect_timeout(REQUEST_TIMEOUT)
221 .timeout(REQUEST_TIMEOUT)
222 .build()
223 .map_err(|e| SignInError::Failed(format!("no HTTP client: {}", chain(&e))))?;
224 let base = server.api_url();
225 match credentials {
226 Credentials::Token { id, secret } => {
227 let session = Session {
228 http,
229 tls,
230 base,
231 auth: ("Authorization", format!("PVEAPIToken={id}={secret}")),
232 };
233 match session.get("/version").await {
234 Ok(_) => Ok(session),
235 Err(CallError::Status(401)) => Err(SignInError::Rejected),
236 Err(CallError::Certificate(refusal)) => Err(SignInError::Certificate(refusal)),
237 Err(e) => Err(SignInError::Failed(e.to_string())),
238 }
239 }
240 Credentials::Password { user, password } => {
241 let sent = http
242 .post(format!("{base}/access/ticket"))
243 .form(&[("username", user.as_str()), ("password", password.as_str())])
244 .send()
245 .await;
246 let res = match sent {
247 Ok(res) => res,
248 Err(e) => return Err(tls.refused().map_or_else(|| SignInError::Failed(chain(&e)), SignInError::Certificate)),
249 };
250 if res.status().as_u16() == 401 {
251 return Err(SignInError::Rejected);
252 }
253 if !res.status().is_success() {
254 return Err(SignInError::Failed(format!("the API answered HTTP {}", res.status().as_u16())));
255 }
256 let body = res.text().await.map_err(|e| SignInError::Failed(chain(&e)))?;
257 let ticket = api::data::<Ticket>(&body)
258 .map_err(|e| SignInError::Failed(format!("the sign-in's answer isn't the API's: {e}")))?
259 .ticket
260 .ok_or_else(|| SignInError::Failed("no ticket in the sign-in's answer".into()))?;
261 Ok(Session {
262 http,
263 tls,
264 base,
265 auth: ("Cookie", format!("PVEAuthCookie={ticket}")),
266 })
267 }
268 }
269}
270
271pub(crate) fn chain(e: &dyn std::error::Error) -> String {
273 let mut line = e.to_string();
274 let mut cause = e.source();
275 while let Some(c) = cause {
276 line = format!("{line}: {c}");
277 cause = c.source();
278 }
279 line
280}
281
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct Capacity {
285 pub cores: u64,
287 pub mem_total: u64,
289 pub mem_free: u64,
291}
292
293impl Capacity {
294 #[must_use]
296 pub fn of(status: &NodeStatus) -> Option<Capacity> {
297 let (cpu, memory) = (status.cpuinfo.as_ref()?, status.memory.as_ref()?);
298 Some(Capacity {
299 cores: cpu.cpus?,
300 mem_total: memory.total?,
301 mem_free: memory.free?,
302 })
303 }
304}
305
306impl Session {
307 pub async fn get(&self, path: &str) -> Result<String, CallError> {
313 let sent = self.http.get(format!("{}{path}", self.base)).header(self.auth.0, &self.auth.1).send().await;
314 let res = match sent {
315 Ok(res) => res,
316 Err(e) => return Err(self.tls.refused().map_or_else(|| CallError::Other(chain(&e)), CallError::Certificate)),
317 };
318 if !res.status().is_success() {
319 return Err(CallError::Status(res.status().as_u16()));
320 }
321 res.text().await.map_err(|e| CallError::Other(chain(&e)))
322 }
323
324 pub async fn call<T: DeserializeOwned + Default>(&self, path: &str) -> Result<T, CallError> {
330 read_data(&self.get(path).await?)
331 }
332
333 pub async fn nodes(&self) -> Result<Vec<Node>, CallError> {
339 self.call("/nodes").await
340 }
341
342 pub async fn node(&self, asked: Option<&str>) -> Result<String, CallError> {
348 pick_node(&self.nodes().await?, asked)
349 }
350
351 pub async fn storages(&self, node: &str) -> Result<Vec<Storage>, CallError> {
357 self.call(&format!("/nodes/{node}/storage")).await
358 }
359
360 pub async fn network(&self, node: &str) -> Result<Vec<Iface>, CallError> {
366 self.call(&format!("/nodes/{node}/network")).await
367 }
368
369 pub async fn bridges(&self, node: &str) -> Result<Vec<Iface>, CallError> {
375 self.call(&format!("/nodes/{node}/network?type=any_bridge")).await
376 }
377
378 pub async fn status(&self, node: &str) -> Result<NodeStatus, CallError> {
384 self.call(&format!("/nodes/{node}/status")).await
385 }
386
387 pub async fn capacity(&self, node: &str) -> Result<Capacity, CallError> {
393 Capacity::of(&self.status(node).await?).ok_or_else(|| CallError::Other(format!("the node {node} reported no cores or memory figures")))
394 }
395}
396
397fn read_data<T: DeserializeOwned + Default>(body: &str) -> Result<T, CallError> {
399 api::data(body).map_err(|e| CallError::Other(format!("the answer isn't the Proxmox VE API's: {e}")))
400}
401
402fn pick_node(nodes: &[Node], asked: Option<&str>) -> Result<String, CallError> {
404 let names: Vec<&str> = nodes.iter().filter_map(|n| n.node.as_deref()).collect();
405 match asked.filter(|n| !n.is_empty()) {
406 Some(n) if names.contains(&n) => Ok(n.to_owned()),
407 Some(n) => Err(CallError::NoSuchNode {
408 asked: n.to_owned(),
409 found: names.iter().map(|s| (*s).to_owned()).collect(),
410 }),
411 None => names.first().map(|s| (*s).to_owned()).ok_or(CallError::NoNode),
412 }
413}
414
415#[cfg(test)]
416mod tests;