Skip to main content

isothrum_machine/cloud/
azure.rs

1//! Azure, through the Azure CLI (`az`): whether its sign-in holds, the subscriptions it can see,
2//! and what a subscription may create in a region: the VM sizes Azure lists for it there (each
3//! with the reason Azure refuses it to that subscription, if it does) and its core quotas.
4//!
5//! `az vm list-skus` is slow (a minute is common) and filters by location only: a caller that
6//! asks it more than once keeps the answer.
7
8use serde_json::Value;
9
10use super::{ask, json_list, line, says};
11use crate::context::Context;
12use crate::failure::{Failure, Refusal};
13
14/// The Azure CLI.
15pub const CLI: &str = "az";
16
17/// How the Azure CLI refused, read from what it said: a sign-in run out or missing (the runner's
18/// reading, `az login`, an `AADSTS` error), or a subscription it can't find.
19#[must_use]
20pub fn refusal(said: &str) -> Refusal {
21    if isothrum_runner::sign_in_expired(said) || says(said, &["az login", "not logged in", "AADSTS"]) {
22        Refusal::CredentialsExpired
23    } else if says(said, &["was not found"]) {
24        Refusal::NotFound
25    } else {
26        Refusal::Other
27    }
28}
29
30/// Whether the CLI's sign-in still gives a token (`az account get-access-token`, the token not
31/// printed).
32///
33/// # Errors
34///
35/// [`Failure`]: the CLI isn't installed, or Azure refused ([`Refusal::CredentialsExpired`]).
36pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
37    ask(cx, CLI, &["account", "get-access-token", "--output", "none"], refusal).await.map(drop)
38}
39
40/// A subscription the signed-in account can see.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Subscription {
44    /// Its display name.
45    pub name: String,
46    /// Its id.
47    pub id: String,
48    /// Whether the CLI has it as its default.
49    pub is_default: bool,
50}
51
52/// The subscriptions the signed-in account can see (`az account list`).
53///
54/// # Errors
55///
56/// [`Failure`]: the CLI isn't installed, Azure refused, or its answer isn't the list.
57pub async fn subscriptions(cx: &Context) -> Result<Vec<Subscription>, Failure> {
58    let out = ask(
59        cx,
60        CLI,
61        &["account", "list", "--query", "[].{name:name,id:id,isDefault:isDefault}", "--output", "json"],
62        refusal,
63    )
64    .await?;
65    read_subscriptions(&out)
66}
67
68/// `az account list`'s answer (the query above) as subscriptions: entries without a name or an
69/// id read as empty ones.
70fn read_subscriptions(out: &str) -> Result<Vec<Subscription>, Failure> {
71    let list = json_list(CLI, out)?;
72    if list.iter().any(|v| !v.is_object()) {
73        return Err(super::unreadable(CLI, "an entry of its list isn't a subscription"));
74    }
75    Ok(list
76        .iter()
77        .map(|v| Subscription {
78            name: v["name"].as_str().unwrap_or_default().to_owned(),
79            id: v["id"].as_str().unwrap_or_default().to_owned(),
80            is_default: v["isDefault"].as_bool().unwrap_or(false),
81        })
82        .collect())
83}
84
85/// Subscription `id`'s display name (`az account show`): it is signed in and can reach it.
86///
87/// # Errors
88///
89/// [`Failure`]: the CLI isn't installed, or Azure refused ([`Refusal::CredentialsExpired`]: not
90/// signed in; [`Refusal::NotFound`]: no such subscription for this account).
91pub async fn subscription_name(cx: &Context, id: &str) -> Result<String, Failure> {
92    ask(
93        cx,
94        CLI,
95        &["account", "show", "--subscription", id, "--query", "name", "--output", "tsv"],
96        refusal,
97    )
98    .await
99    .map(|out| line(&out))
100}
101
102/// A VM size in one location, as `az vm list-skus --all` lists it.
103#[derive(Debug, Clone, PartialEq)]
104#[non_exhaustive]
105pub struct Size {
106    /// Its name (`Standard_D2als_v6`).
107    pub name: String,
108    /// Its quota family, lowercase, as [`quotas`] names it.
109    pub family: String,
110    /// The location this entry is about, lowercase.
111    pub location: String,
112    /// Why Azure won't create it for this subscription in `location` (its reason code:
113    /// `NotAvailableForSubscription`, `QuotaId`), if it won't.
114    pub restricted: Option<String>,
115    /// Its vCPUs, when listed.
116    pub vcpus: Option<u32>,
117    /// Its memory in GB, when listed.
118    pub memory_gb: Option<f64>,
119}
120
121impl Size {
122    /// Whether it is the size named `name` (in any case).
123    #[must_use]
124    pub fn is(&self, name: &str) -> bool {
125        self.name.eq_ignore_ascii_case(name)
126    }
127}
128
129/// The VM sizes Azure lists for `subscription` (`az vm list-skus --all`, so those refused to it
130/// are listed too, with why), in `region` or (None) every region, only `size` when given.
131///
132/// # Errors
133///
134/// [`Failure`]: the CLI isn't installed, Azure refused (signed out, throttled, a bad region), or
135/// its answer isn't the list: never an empty list for an answer that isn't one.
136pub async fn sizes(cx: &Context, subscription: &str, region: Option<&str>, size: Option<&str>) -> Result<Vec<Size>, Failure> {
137    let mut args = vec![
138        "vm",
139        "list-skus",
140        "--subscription",
141        subscription,
142        "--resource-type",
143        "virtualMachines",
144        "--all",
145        "-o",
146        "json",
147    ];
148    if let Some(region) = region {
149        args.extend(["-l", region]);
150    }
151    if let Some(size) = size {
152        args.extend(["--size", size]);
153    }
154    let out = ask(cx, CLI, &args, refusal).await?;
155    Ok(json_list(CLI, &out)?.iter().filter_map(read_size).collect())
156}
157
158/// One entry of `az vm list-skus --all`: the location it is about, and whether a `Location`
159/// restriction keeps the subscription from it there (a `Zone` one only closes some zones). None
160/// for an entry without a name.
161fn read_size(v: &Value) -> Option<Size> {
162    let lower = |text: &Value| text.as_str().map(str::to_lowercase);
163    let location = v["locations"]
164        .get(0)
165        .and_then(lower)
166        .or_else(|| v["locationInfo"].get(0).and_then(|l| lower(&l["location"])))
167        .unwrap_or_default();
168    let restricted = v["restrictions"].as_array().into_iter().flatten().find_map(|r| {
169        let places = r
170            .pointer("/restrictionInfo/locations")
171            .and_then(Value::as_array)
172            .or_else(|| r.get("values").and_then(Value::as_array));
173        let here = places.is_none_or(|p| p.iter().any(|l| lower(l).as_deref() == Some(location.as_str())));
174        (r["type"].as_str() == Some("Location") && here).then(|| r["reasonCode"].as_str().unwrap_or("restricted").to_owned())
175    });
176    let capability = |name: &str| v["capabilities"].as_array()?.iter().find(|c| c["name"].as_str() == Some(name))?["value"].as_str();
177    Some(Size {
178        name: v["name"].as_str()?.to_owned(),
179        family: v["family"].as_str().unwrap_or_default().to_lowercase(),
180        location,
181        restricted,
182        vcpus: capability("vCPUs").and_then(|n| n.parse().ok()),
183        memory_gb: capability("MemoryGB").and_then(|n| n.parse().ok()),
184    })
185}
186
187/// Where a size stands in a region's list ([`in_region`]).
188#[derive(Debug, Clone, PartialEq, Eq)]
189#[non_exhaustive]
190pub enum InRegion {
191    /// The subscription may create it there: its quota family.
192    Usable(String),
193    /// The region doesn't offer it.
194    NotOffered,
195    /// The region offers it, but not to this subscription: Azure's reason code.
196    Restricted(String),
197}
198
199/// Where `size` stands in `region_sizes` (a region's [`sizes`]).
200#[must_use]
201pub fn in_region(region_sizes: &[Size], size: &str) -> InRegion {
202    match region_sizes.iter().find(|s| s.is(size)) {
203        None => InRegion::NotOffered,
204        Some(Size { restricted: Some(why), .. }) => InRegion::Restricted(why.clone()),
205        Some(s) => InRegion::Usable(s.family.clone()),
206    }
207}
208
209/// Of `everywhere` (a size's [`sizes`] across every region), the regions other than `region`
210/// where the subscription may create `size`, sorted, and how many refuse it to the subscription.
211#[must_use]
212pub fn elsewhere<'a>(everywhere: &'a [Size], size: &str, region: &str) -> (Vec<&'a str>, usize) {
213    let mut usable: Vec<&str> = everywhere
214        .iter()
215        .filter(|s| s.is(size) && s.restricted.is_none() && s.location != region)
216        .map(|s| s.location.as_str())
217        .collect();
218    usable.sort_unstable();
219    usable.dedup();
220    let refused = everywhere.iter().filter(|s| s.is(size) && s.restricted.is_some()).count();
221    (usable, refused)
222}
223
224/// At most `n` sizes of `region_sizes` the subscription may create that are like `size`: as many
225/// vCPUs or more, at least its memory, the smallest first (then by name). What `size` is comes
226/// from either list; unknown, it is taken as 2 vCPUs.
227#[must_use]
228pub fn alike<'a>(size: &str, everywhere: Option<&[Size]>, region_sizes: &'a [Size], n: usize) -> Vec<&'a Size> {
229    let model = region_sizes.iter().chain(everywhere.into_iter().flatten()).find(|s| s.is(size));
230    let (vcpus, memory) = (model.and_then(|m| m.vcpus).unwrap_or(2), model.and_then(|m| m.memory_gb).unwrap_or(0.0));
231    let mut usable: Vec<&Size> = region_sizes
232        .iter()
233        .filter(|s| !s.is(size) && s.restricted.is_none() && s.vcpus.is_some_and(|c| c >= vcpus) && s.memory_gb.unwrap_or(0.0) >= memory)
234        .collect();
235    usable.sort_by(|a, b| {
236        (a.vcpus, a.memory_gb.unwrap_or(0.0))
237            .partial_cmp(&(b.vcpus, b.memory_gb.unwrap_or(0.0)))
238            .unwrap_or(std::cmp::Ordering::Equal)
239            .then_with(|| a.name.cmp(&b.name))
240    });
241    usable.truncate(n);
242    usable
243}
244
245/// A core quota of a subscription in a region, as `az vm list-usage` lists it.
246#[derive(Debug, Clone, PartialEq, Eq)]
247#[non_exhaustive]
248pub struct Quota {
249    /// The VM family it counts (lowercase), as [`Size::family`] names it.
250    pub family: String,
251    /// Cores allowed.
252    pub limit: i64,
253    /// Cores in use.
254    pub used: i64,
255}
256
257impl Quota {
258    /// Cores still free.
259    #[must_use]
260    pub fn free(&self) -> i64 {
261        self.limit - self.used
262    }
263}
264
265/// `subscription`'s core quotas in `region` (`az vm list-usage`).
266///
267/// # Errors
268///
269/// [`Failure`]: the CLI isn't installed, Azure refused, or its answer isn't the list.
270pub async fn quotas(cx: &Context, subscription: &str, region: &str) -> Result<Vec<Quota>, Failure> {
271    let out = ask(
272        cx,
273        CLI,
274        &["vm", "list-usage", "--subscription", subscription, "-l", region, "-o", "json"],
275        refusal,
276    )
277    .await?;
278    Ok(read_quotas(&json_list(CLI, &out)?))
279}
280
281/// `az vm list-usage`'s entries as quotas: its numbers come as strings or numbers, one that
282/// can't be read counts as 0; an entry without a name is left out.
283fn read_quotas(list: &[Value]) -> Vec<Quota> {
284    let n = |v: &Value| v.as_str().and_then(|s| s.parse::<i64>().ok()).or_else(|| v.as_i64()).unwrap_or(0);
285    list.iter()
286        .filter_map(|x| {
287            Some(Quota {
288                family: x.pointer("/name/value").and_then(Value::as_str)?.to_lowercase(),
289                limit: n(&x["limit"]),
290                used: n(&x["currentValue"]),
291            })
292        })
293        .collect()
294}
295
296/// The cores free in `family`'s quota (`family` lowercase), when `quotas` has it.
297#[must_use]
298pub fn free_cores(quotas: &[Quota], family: &str) -> Option<i64> {
299    quotas.iter().find(|q| q.family == family).map(Quota::free)
300}
301
302#[cfg(test)]
303mod tests;