Skip to main content

isothrum_machine/cloud/
gcp.rs

1//! Google Cloud, through the Google Cloud CLI (`gcloud`): the account it is signed in as, whether
2//! its own sign-in and the application-default one (what Terraform's Google provider reads) still
3//! hold, the billing accounts and organizations the account can see, and its projects: what state
4//! one is in, and making one ready for deployments (created, linked to a billing account, an API
5//! enabled) or deleting it.
6
7use std::time::Duration;
8
9use isothrum_runner::ProcessSpec;
10use serde_json::Value;
11
12use super::{ask, json_list, line, run, says};
13use crate::context::Context;
14use crate::failure::{Failure, Refusal};
15
16/// The Google Cloud CLI.
17pub const CLI: &str = "gcloud";
18
19/// How gcloud refused, read from what it said: a sign-in run out or missing (the runner's reading,
20/// a `gcloud auth` hint, credentials), what was asked about not found (the API's `NOT_FOUND`, a
21/// word of its own), a permission denied, an API not enabled, a quota used up (a billing account
22/// with no free project slot is refused as `FAILED_PRECONDITION`).
23#[must_use]
24pub fn refusal(said: &str) -> Refusal {
25    if isothrum_runner::sign_in_expired(said) || says(said, &["gcloud auth", "credentials"]) {
26        Refusal::CredentialsExpired
27    } else if names_status(said, "NOT_FOUND") {
28        Refusal::NotFound
29    } else if names_status(said, "SERVICE_DISABLED") || says(said, &["has not been used in project", "it is disabled"]) {
30        // Before a denial: an API turned off is refused as `PERMISSION_DENIED`.
31        Refusal::NotEnabled
32    } else if says(said, &["does not have permission", "PERMISSION_DENIED", "Permission denied", "was not found"]) {
33        Refusal::Denied
34    } else if says(said, &["quota", "FAILED_PRECONDITION", "Precondition"]) {
35        Refusal::QuotaExceeded
36    } else {
37        Refusal::Other
38    }
39}
40
41/// Whether `said` names the API status `status`, which gcloud writes in capitals as a word of its
42/// own (`ERROR: (gcloud.projects.describe) NOT_FOUND: …`).
43fn names_status(said: &str, status: &str) -> bool {
44    said.split(|c: char| !(c.is_ascii_uppercase() || c == '_')).any(|word| word == status)
45}
46
47/// The account gcloud is signed in as (`gcloud auth list`, its active one): None when none is.
48/// An account whose sign-in ran out still shows as active here: [`access_token`] and
49/// [`signed_in`] tell whether it holds.
50///
51/// # Errors
52///
53/// [`Failure`]: the CLI isn't installed, or failed.
54pub async fn active_account(cx: &Context) -> Result<Option<String>, Failure> {
55    let out = ask(cx, CLI, &["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"], refusal).await?;
56    Ok(Some(line(&out)).filter(|a| !a.is_empty()))
57}
58
59/// Whether gcloud's own sign-in still gives a token (`gcloud auth print-access-token`, the token
60/// not kept).
61///
62/// # Errors
63///
64/// [`Failure`]: the CLI isn't installed, or Google refused ([`Refusal::CredentialsExpired`]).
65pub async fn access_token(cx: &Context) -> Result<(), Failure> {
66    ask(cx, CLI, &["auth", "print-access-token", "--quiet"], refusal).await.map(drop)
67}
68
69/// Whether the application-default sign-in, the one Terraform's Google provider signs in with,
70/// still gives a token (`gcloud auth application-default print-access-token`, the token not
71/// kept): the sign-in a deployment on Google Cloud needs.
72///
73/// # Errors
74///
75/// [`Failure`]: the CLI isn't installed, or Google refused ([`Refusal::CredentialsExpired`]).
76pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
77    ask(cx, CLI, &["auth", "application-default", "print-access-token"], refusal).await.map(drop)
78}
79
80/// A billing account the signed-in account can see.
81#[derive(Debug, Clone, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct BillingAccount {
84    /// Its id (`billingAccounts/` left out).
85    pub id: String,
86    /// Its display name.
87    pub name: String,
88    /// Whether it is open, so it can pay for a project.
89    pub open: bool,
90}
91
92/// The billing accounts the signed-in account can see (`gcloud billing accounts list`).
93///
94/// # Errors
95///
96/// [`Failure`]: the CLI isn't installed, Google refused (the Cloud Billing API off, a permission
97/// denied), or its answer isn't the list.
98pub async fn billing_accounts(cx: &Context) -> Result<Vec<BillingAccount>, Failure> {
99    let out = ask(cx, CLI, &["billing", "accounts", "list", "--format", "json"], refusal).await?;
100    Ok(read_billing_accounts(&json_list(CLI, &out)?))
101}
102
103/// Billing accounts as gcloud lists them: an entry without an id is left out, a field of the
104/// wrong type read as empty.
105fn read_billing_accounts(list: &[Value]) -> Vec<BillingAccount> {
106    list.iter()
107        .map(|v| BillingAccount {
108            id: id(v, "billingAccounts/"),
109            name: v["displayName"].as_str().unwrap_or_default().to_owned(),
110            open: v["open"].as_bool().unwrap_or(false),
111        })
112        .filter(|b| !b.id.is_empty())
113        .collect()
114}
115
116/// An entry's `name` without its `prefix`.
117fn id(v: &Value, prefix: &str) -> String {
118    v["name"].as_str().unwrap_or_default().trim_start_matches(prefix).to_owned()
119}
120
121/// Billing account `id`'s display name (`gcloud billing accounts describe`): gcloud is signed in
122/// and can see it.
123///
124/// # Errors
125///
126/// [`Failure`]: the CLI isn't installed, or Google refused ([`Refusal::CredentialsExpired`]: not
127/// signed in; [`Refusal::Denied`] or [`Refusal::NotFound`]: not this account's to see).
128pub async fn billing_account_name(cx: &Context, id: &str) -> Result<String, Failure> {
129    ask(cx, CLI, &["billing", "accounts", "describe", id, "--format", "value(displayName)"], refusal)
130        .await
131        .map(|out| line(&out))
132}
133
134/// An organization the signed-in account belongs to.
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
136#[non_exhaustive]
137pub struct Organization {
138    /// Its numeric id (`organizations/` left out).
139    pub id: String,
140    /// Its display name.
141    pub name: String,
142}
143
144/// The organizations the signed-in account belongs to (`gcloud organizations list`): none for a
145/// personal account.
146///
147/// # Errors
148///
149/// [`Failure`]: the CLI isn't installed, Google refused, or its answer isn't the list (gcloud
150/// prints `Listed 0 items.` for none, which isn't one).
151pub async fn organizations(cx: &Context) -> Result<Vec<Organization>, Failure> {
152    let out = ask(cx, CLI, &["organizations", "list", "--format", "json"], refusal).await?;
153    Ok(read_organizations(&json_list(CLI, &out)?))
154}
155
156/// Organizations as gcloud lists them: an entry without an id is left out.
157fn read_organizations(list: &[Value]) -> Vec<Organization> {
158    list.iter()
159        .map(|v| Organization {
160            id: id(v, "organizations/"),
161            name: v["displayName"].as_str().unwrap_or_default().to_owned(),
162        })
163        .filter(|o| !o.id.is_empty())
164        .collect()
165}
166
167/// How long creating a project, linking it to billing, enabling an API on it or deleting it may
168/// take.
169pub const PROJECT_TIMEOUT: Duration = Duration::from_secs(5 * 60);
170
171/// What state a project is in, as Google has it.
172#[derive(Debug, Clone, PartialEq, Eq)]
173#[non_exhaustive]
174pub enum ProjectState {
175    /// It can be used.
176    Active,
177    /// It doesn't exist (`NOT_FOUND`), or is being deleted: it can't be used again.
178    Gone,
179    /// Another state Google names (`SUSPENDED`...).
180    Other(String),
181}
182
183/// Project `id`'s state (`gcloud projects describe`). Gone only when Google says so plainly: the
184/// project is being deleted, or `NOT_FOUND`. "No permission (or it may not exist)", what another
185/// signed-in account gets, is a [`Refusal::Denied`], never gone.
186///
187/// # Errors
188///
189/// [`Failure`]: the CLI isn't installed, Google refused (signed out, no permission), or no answer.
190pub async fn project_state(cx: &Context, id: &str) -> Result<ProjectState, Failure> {
191    match ask(cx, CLI, &["projects", "describe", id, "--format", "value(lifecycleState)"], refusal).await {
192        Ok(state) => Ok(match state.trim() {
193            "ACTIVE" => ProjectState::Active,
194            "DELETE_REQUESTED" | "DELETE_IN_PROGRESS" => ProjectState::Gone,
195            other => ProjectState::Other(other.to_owned()),
196        }),
197        Err(Failure::Refused {
198            refusal: Refusal::NotFound, ..
199        }) => Ok(ProjectState::Gone),
200        Err(other) => Err(other),
201    }
202}
203
204/// `gcloud args` within [`PROJECT_TIMEOUT`].
205async fn change(cx: &Context, args: &[&str]) -> Result<(), Failure> {
206    run(cx, PROJECT_TIMEOUT, &ProcessSpec::new(CLI, args.iter().copied()), refusal).await.map(drop)
207}
208
209/// The arguments of `gcloud projects create` for project `id` named `name`, under `organization`
210/// (its numeric id) when given.
211#[must_use]
212pub fn create_args(id: &str, name: &str, organization: Option<&str>) -> Vec<String> {
213    let mut args: Vec<String> = ["projects", "create", id, "--name", name].map(str::to_owned).to_vec();
214    args.extend(organization.map(|o| format!("--organization={o}")));
215    args
216}
217
218/// Creates project `id` named `name`, under `organization` when given.
219///
220/// # Errors
221///
222/// [`Failure`]: the CLI isn't installed, or Google refused (the id taken, a quota of projects).
223pub async fn create_project(cx: &Context, id: &str, name: &str, organization: Option<&str>) -> Result<(), Failure> {
224    let args = create_args(id, name, organization);
225    change(cx, &args.iter().map(String::as_str).collect::<Vec<_>>()).await
226}
227
228/// Links project `id` to billing account `billing`, which then pays for it.
229///
230/// # Errors
231///
232/// [`Failure`]: the CLI isn't installed, or Google refused ([`Refusal::QuotaExceeded`]: the billing
233/// account has no free project slot).
234pub async fn link_billing(cx: &Context, id: &str, billing: &str) -> Result<(), Failure> {
235    change(cx, &["billing", "projects", "link", id, "--billing-account", billing]).await
236}
237
238/// Enables the API `service` (`compute.googleapis.com`) on project `id`.
239///
240/// # Errors
241///
242/// [`Failure`]: the CLI isn't installed, or Google refused.
243pub async fn enable_service(cx: &Context, id: &str, service: &str) -> Result<(), Failure> {
244    change(cx, &["services", "enable", service, "--project", id]).await
245}
246
247/// Deletes project `id` (Google keeps it 30 days, deleted, before it is gone for good), which frees
248/// its billing account's slot.
249///
250/// # Errors
251///
252/// [`Failure`]: the CLI isn't installed, or Google refused.
253pub async fn delete_project(cx: &Context, id: &str) -> Result<(), Failure> {
254    change(cx, &["projects", "delete", id, "--quiet"]).await
255}
256
257#[cfg(test)]
258mod tests;