use serde_json::Value;
use super::{ask, json_list, line, says};
use crate::context::Context;
use crate::failure::{Failure, Refusal};
pub const CLI: &str = "az";
#[must_use]
pub fn refusal(said: &str) -> Refusal {
if isothrum_runner::sign_in_expired(said) || says(said, &["az login", "not logged in", "AADSTS"]) {
Refusal::CredentialsExpired
} else if says(said, &["was not found"]) {
Refusal::NotFound
} else {
Refusal::Other
}
}
pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
ask(cx, CLI, &["account", "get-access-token", "--output", "none"], refusal).await.map(drop)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Subscription {
pub name: String,
pub id: String,
pub is_default: bool,
}
pub async fn subscriptions(cx: &Context) -> Result<Vec<Subscription>, Failure> {
let out = ask(
cx,
CLI,
&["account", "list", "--query", "[].{name:name,id:id,isDefault:isDefault}", "--output", "json"],
refusal,
)
.await?;
read_subscriptions(&out)
}
fn read_subscriptions(out: &str) -> Result<Vec<Subscription>, Failure> {
let list = json_list(CLI, out)?;
if list.iter().any(|v| !v.is_object()) {
return Err(super::unreadable(CLI, "an entry of its list isn't a subscription"));
}
Ok(list
.iter()
.map(|v| Subscription {
name: v["name"].as_str().unwrap_or_default().to_owned(),
id: v["id"].as_str().unwrap_or_default().to_owned(),
is_default: v["isDefault"].as_bool().unwrap_or(false),
})
.collect())
}
pub async fn subscription_name(cx: &Context, id: &str) -> Result<String, Failure> {
ask(
cx,
CLI,
&["account", "show", "--subscription", id, "--query", "name", "--output", "tsv"],
refusal,
)
.await
.map(|out| line(&out))
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Size {
pub name: String,
pub family: String,
pub location: String,
pub restricted: Option<String>,
pub vcpus: Option<u32>,
pub memory_gb: Option<f64>,
}
impl Size {
#[must_use]
pub fn is(&self, name: &str) -> bool {
self.name.eq_ignore_ascii_case(name)
}
}
pub async fn sizes(cx: &Context, subscription: &str, region: Option<&str>, size: Option<&str>) -> Result<Vec<Size>, Failure> {
let mut args = vec![
"vm",
"list-skus",
"--subscription",
subscription,
"--resource-type",
"virtualMachines",
"--all",
"-o",
"json",
];
if let Some(region) = region {
args.extend(["-l", region]);
}
if let Some(size) = size {
args.extend(["--size", size]);
}
let out = ask(cx, CLI, &args, refusal).await?;
Ok(json_list(CLI, &out)?.iter().filter_map(read_size).collect())
}
fn read_size(v: &Value) -> Option<Size> {
let lower = |text: &Value| text.as_str().map(str::to_lowercase);
let location = v["locations"]
.get(0)
.and_then(lower)
.or_else(|| v["locationInfo"].get(0).and_then(|l| lower(&l["location"])))
.unwrap_or_default();
let restricted = v["restrictions"].as_array().into_iter().flatten().find_map(|r| {
let places = r
.pointer("/restrictionInfo/locations")
.and_then(Value::as_array)
.or_else(|| r.get("values").and_then(Value::as_array));
let here = places.is_none_or(|p| p.iter().any(|l| lower(l).as_deref() == Some(location.as_str())));
(r["type"].as_str() == Some("Location") && here).then(|| r["reasonCode"].as_str().unwrap_or("restricted").to_owned())
});
let capability = |name: &str| v["capabilities"].as_array()?.iter().find(|c| c["name"].as_str() == Some(name))?["value"].as_str();
Some(Size {
name: v["name"].as_str()?.to_owned(),
family: v["family"].as_str().unwrap_or_default().to_lowercase(),
location,
restricted,
vcpus: capability("vCPUs").and_then(|n| n.parse().ok()),
memory_gb: capability("MemoryGB").and_then(|n| n.parse().ok()),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InRegion {
Usable(String),
NotOffered,
Restricted(String),
}
#[must_use]
pub fn in_region(region_sizes: &[Size], size: &str) -> InRegion {
match region_sizes.iter().find(|s| s.is(size)) {
None => InRegion::NotOffered,
Some(Size { restricted: Some(why), .. }) => InRegion::Restricted(why.clone()),
Some(s) => InRegion::Usable(s.family.clone()),
}
}
#[must_use]
pub fn elsewhere<'a>(everywhere: &'a [Size], size: &str, region: &str) -> (Vec<&'a str>, usize) {
let mut usable: Vec<&str> = everywhere
.iter()
.filter(|s| s.is(size) && s.restricted.is_none() && s.location != region)
.map(|s| s.location.as_str())
.collect();
usable.sort_unstable();
usable.dedup();
let refused = everywhere.iter().filter(|s| s.is(size) && s.restricted.is_some()).count();
(usable, refused)
}
#[must_use]
pub fn alike<'a>(size: &str, everywhere: Option<&[Size]>, region_sizes: &'a [Size], n: usize) -> Vec<&'a Size> {
let model = region_sizes.iter().chain(everywhere.into_iter().flatten()).find(|s| s.is(size));
let (vcpus, memory) = (model.and_then(|m| m.vcpus).unwrap_or(2), model.and_then(|m| m.memory_gb).unwrap_or(0.0));
let mut usable: Vec<&Size> = region_sizes
.iter()
.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)
.collect();
usable.sort_by(|a, b| {
(a.vcpus, a.memory_gb.unwrap_or(0.0))
.partial_cmp(&(b.vcpus, b.memory_gb.unwrap_or(0.0)))
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.name.cmp(&b.name))
});
usable.truncate(n);
usable
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Quota {
pub family: String,
pub limit: i64,
pub used: i64,
}
impl Quota {
#[must_use]
pub fn free(&self) -> i64 {
self.limit - self.used
}
}
pub async fn quotas(cx: &Context, subscription: &str, region: &str) -> Result<Vec<Quota>, Failure> {
let out = ask(
cx,
CLI,
&["vm", "list-usage", "--subscription", subscription, "-l", region, "-o", "json"],
refusal,
)
.await?;
Ok(read_quotas(&json_list(CLI, &out)?))
}
fn read_quotas(list: &[Value]) -> Vec<Quota> {
let n = |v: &Value| v.as_str().and_then(|s| s.parse::<i64>().ok()).or_else(|| v.as_i64()).unwrap_or(0);
list.iter()
.filter_map(|x| {
Some(Quota {
family: x.pointer("/name/value").and_then(Value::as_str)?.to_lowercase(),
limit: n(&x["limit"]),
used: n(&x["currentValue"]),
})
})
.collect()
}
#[must_use]
pub fn free_cores(quotas: &[Quota], family: &str) -> Option<i64> {
quotas.iter().find(|q| q.family == family).map(Quota::free)
}
#[cfg(test)]
mod tests;