1use serde_json::Value;
9
10use super::{ask, json_list, line, says};
11use crate::context::Context;
12use crate::failure::{Failure, Refusal};
13
14pub const CLI: &str = "az";
16
17#[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
30pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Subscription {
44 pub name: String,
46 pub id: String,
48 pub is_default: bool,
50}
51
52pub 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
68fn 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
85pub 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#[derive(Debug, Clone, PartialEq)]
104#[non_exhaustive]
105pub struct Size {
106 pub name: String,
108 pub family: String,
110 pub location: String,
112 pub restricted: Option<String>,
115 pub vcpus: Option<u32>,
117 pub memory_gb: Option<f64>,
119}
120
121impl Size {
122 #[must_use]
124 pub fn is(&self, name: &str) -> bool {
125 self.name.eq_ignore_ascii_case(name)
126 }
127}
128
129pub 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
158fn 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#[derive(Debug, Clone, PartialEq, Eq)]
189#[non_exhaustive]
190pub enum InRegion {
191 Usable(String),
193 NotOffered,
195 Restricted(String),
197}
198
199#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
247#[non_exhaustive]
248pub struct Quota {
249 pub family: String,
251 pub limit: i64,
253 pub used: i64,
255}
256
257impl Quota {
258 #[must_use]
260 pub fn free(&self) -> i64 {
261 self.limit - self.used
262 }
263}
264
265pub 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
281fn 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#[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;