Skip to main content

isothrum_machine/place/
proxmox.rs

1//! A Proxmox VE server's API, over HTTPS whose certificate is trusted as the caller says
2//! ([`Trust`]: the system's trust store, or a pinned SHA-256 for a self-signed one): sign in with
3//! an API token or a user's password ([`sign_in`]), then read what a placement needs: the nodes,
4//! each node's storages and bridges ([`placement`]), whether the ones chosen can take machines
5//! ([`check`]), and a node's cores and memory ([`Session::capacity`]).
6//!
7//! A refused certificate ends the request before any credential is sent, and the error names the
8//! certificate the server offered ([`SignInError::Certificate`]): what a caller asks a user to
9//! confirm. Pins are the runner's [`isothrum_runner::tls`] fingerprints, so one saved elsewhere in
10//! that format stays valid.
11
12use 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
26/// The port Proxmox VE's API listens on by default.
27pub const DEFAULT_PORT: u16 = 8006;
28
29/// How long one request may take.
30pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(8);
31
32/// A Proxmox VE server, as its API is reached.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Server {
35    /// Its name or address.
36    pub host: String,
37    /// Its API's port ([`DEFAULT_PORT`] unless changed).
38    pub port: u16,
39}
40
41impl Server {
42    /// The server at `host` on `port`.
43    #[must_use]
44    pub fn new(host: impl Into<String>, port: u16) -> Server {
45        Server { host: host.into(), port }
46    }
47
48    /// The API's base URL, `https://<host>:<port>/api2/json`.
49    #[must_use]
50    pub fn api_url(&self) -> String {
51        format!("https://{}:{}/api2/json", host_for_url(&self.host), self.port)
52    }
53
54    /// The endpoint Proxmox's Terraform providers take, `https://<host>:<port>/`.
55    #[must_use]
56    pub fn endpoint(&self) -> String {
57        format!("https://{}:{}/", host_for_url(&self.host), self.port)
58    }
59}
60
61/// What signs a session in.
62#[derive(Clone, PartialEq, Eq)]
63pub enum Credentials {
64    /// An API token: its id (`user@realm!name`) and its secret.
65    Token {
66        /// `user@realm!name`.
67        id: String,
68        /// The token's secret.
69        secret: String,
70    },
71    /// A user (`user@realm`) and their password, for a ticket.
72    Password {
73        /// `user@realm`.
74        user: String,
75        /// Their password.
76        password: String,
77    },
78}
79
80impl Credentials {
81    /// A login as typed (a user or a token id, its realm `@pam` when it has none:
82    /// [`with_default_realm`]) with its secret: a token when the login is a token id
83    /// ([`is_token`]), else a user and their password.
84    #[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    /// The user they sign in as (a token's own user).
101    #[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/// A login with its realm: `root` is `root@pam`, a token `root!name` is `root@pam!name`; one with
120/// a realm (`admin@pve`, `root@pam!ci`) stays as typed.
121#[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/// Whether `login` is an API token id (`user@realm!name`: a realm before the first `!`, a name
133/// after it) rather than a user.
134#[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/// The user a token belongs to (`root@pam!ci` is `root@pam`); a user is its own.
140#[must_use]
141pub fn token_user(login: &str) -> &str {
142    login.split_once('!').map_or(login, |(u, _)| u)
143}
144
145/// The `api_token` value Proxmox's Terraform providers take, `<id>=<secret>`.
146#[must_use]
147pub fn terraform_token(id: &str, secret: &str) -> String {
148    format!("{id}={secret}")
149}
150
151/// Why signing in failed.
152#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
153#[non_exhaustive]
154pub enum SignInError {
155    /// The server answered and refused the credentials.
156    #[error("Proxmox VE refused the credentials")]
157    Rejected,
158    /// Its certificate isn't the one pinned (or none was pinned yet): nothing was sent to it.
159    #[error("{0}")]
160    Certificate(Refusal),
161    /// The API couldn't be talked to (network, TLS, an answer that isn't the API's): why.
162    #[error("{0}")]
163    Failed(String),
164}
165
166/// Why a call to the API failed.
167#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
168#[non_exhaustive]
169pub enum CallError {
170    /// The API answered with this HTTP status, not a success (403: the user may not).
171    #[error("HTTP {0}")]
172    Status(u16),
173    /// The server's certificate was refused (it changed since it was pinned).
174    #[error("{0}")]
175    Certificate(Refusal),
176    /// There is no node by the name asked: the ones there are.
177    #[error("there is no node \"{asked}\" (found: {})", found.join(", "))]
178    NoSuchNode {
179        /// The node asked for.
180        asked: String,
181        /// The nodes the user can see.
182        found: Vec<String>,
183    },
184    /// The user can see no node at all.
185    #[error("this user can't see any node")]
186    NoNode,
187    /// No answer that could be read (network, not the API's JSON): why.
188    #[error("{0}")]
189    Other(String),
190}
191
192/// A signed-in API client.
193pub struct Session {
194    http: reqwest::Client,
195    tls: Tls,
196    base: String,
197    /// The header that signs each call in: a ticket's cookie, or the token.
198    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
207/// Signs in to `server` with `credentials`, its certificate trusted as `trust` says.
208///
209/// A token is proved by an authenticated call (`/version`); a password is exchanged for a ticket
210/// (`access/ticket`).
211///
212/// # Errors
213///
214/// The credentials were refused, the certificate was ([`SignInError::Certificate`], before any
215/// credential was sent), or the API couldn't be talked to.
216pub 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
271/// An error and its causes, on one line, each after a colon.
272pub(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/// A node's cores and memory, as it reports them.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct Capacity {
285    /// Its logical CPUs.
286    pub cores: u64,
287    /// All its memory, in bytes.
288    pub mem_total: u64,
289    /// Its free memory, in bytes.
290    pub mem_free: u64,
291}
292
293impl Capacity {
294    /// A node's `/status` as its capacity; none when a figure is missing.
295    #[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    /// GET `path` (under `/api2/json`): the answer's body, as the API wrote it.
308    ///
309    /// # Errors
310    ///
311    /// Not a success ([`CallError::Status`]), the certificate refused, or no answer.
312    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    /// GET `path` and read its `data` as `T` ([`api::data`]).
325    ///
326    /// # Errors
327    ///
328    /// As [`Session::get`], or an answer that isn't the API's.
329    pub async fn call<T: DeserializeOwned + Default>(&self, path: &str) -> Result<T, CallError> {
330        read_data(&self.get(path).await?)
331    }
332
333    /// The nodes (`/nodes`).
334    ///
335    /// # Errors
336    ///
337    /// As [`Session::call`].
338    pub async fn nodes(&self) -> Result<Vec<Node>, CallError> {
339        self.call("/nodes").await
340    }
341
342    /// The node `asked` (when it is there), else the first one.
343    ///
344    /// # Errors
345    ///
346    /// As [`Session::call`]; there is no node `asked` ([`CallError::NoSuchNode`]), or none at all.
347    pub async fn node(&self, asked: Option<&str>) -> Result<String, CallError> {
348        pick_node(&self.nodes().await?, asked)
349    }
350
351    /// A node's storages (`/nodes/<node>/storage`).
352    ///
353    /// # Errors
354    ///
355    /// As [`Session::call`].
356    pub async fn storages(&self, node: &str) -> Result<Vec<Storage>, CallError> {
357        self.call(&format!("/nodes/{node}/storage")).await
358    }
359
360    /// A node's network interfaces (`/nodes/<node>/network`).
361    ///
362    /// # Errors
363    ///
364    /// As [`Session::call`].
365    pub async fn network(&self, node: &str) -> Result<Vec<Iface>, CallError> {
366        self.call(&format!("/nodes/{node}/network")).await
367    }
368
369    /// A node's bridges, Linux and Open vSwitch (`/nodes/<node>/network?type=any_bridge`).
370    ///
371    /// # Errors
372    ///
373    /// As [`Session::call`].
374    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    /// A node's status (`/nodes/<node>/status`).
379    ///
380    /// # Errors
381    ///
382    /// As [`Session::call`].
383    pub async fn status(&self, node: &str) -> Result<NodeStatus, CallError> {
384        self.call(&format!("/nodes/{node}/status")).await
385    }
386
387    /// A node's cores and memory.
388    ///
389    /// # Errors
390    ///
391    /// As [`Session::status`]; a figure missing from it is [`CallError::Other`].
392    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
397/// The `data` of an answer's `body`, read as `T`.
398fn 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
402/// The node `asked` among `nodes`, else the first.
403fn 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;