stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! `stratum application …` and `stratum installations`: the administrator's
//! catalogue commands on the loopback API.

use std::fs::File;
use std::io::Read as _;
use std::path::Path;

use serde_json::{json, Value as Json};
use stratum_node_core::{
    ApplicationActionRequest, ApplicationId, ApplicationList, ApplicationState,
    ApplicationStateResponse, ApproveApplicationRequest, ApproveApplicationResponse,
    InstallationList, JobCeilings, MilliCpus, ValidManifest,
};

use crate::app::summary_line;
use crate::error::CliError;
use crate::exit;
use crate::output::sanitize;
use crate::session::{operation_id, to_body, Confirmation, Session};

/// The applications route; each application is `APPLICATIONS/<id>`.
const APPLICATIONS: &str = "/api/v1/applications";
/// The administrator's installation list.
const INSTALLATIONS: &str = "/api/v1/installations";
/// The largest manifest file read.
const MAX_MANIFEST_BYTES: u64 = 256 * 1024;

/// The highest ceilings any node can be configured with
/// (`limits.job_max_*` at the top of their ranges). The client checks a
/// manifest's shape against these, so it never refuses one the node would
/// accept; the node checks it against its own ceilings.
const WIDEST_CEILINGS: JobCeilings = JobCeilings {
    cpus: MilliCpus::new(64_000),
    memory_bytes: 1024 * 1024 * 1024 * 1024,
    pids: 65_536,
    tmp_bytes: 1024 * 1024 * 1024 * 1024,
    timeout_secs: 43_200,
};

/// An administrator transition of an application.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApplicationAction {
    /// `approved` → `withdrawn`: no new installations; existing ones keep
    /// running.
    Withdraw,
    /// `withdrawn` → `approved`: installable again; touches no key.
    Approve,
    /// `approved` or `withdrawn` → `disabled`, terminal: the emergency
    /// stop. Every installation's key is disabled and its running jobs are
    /// stopped.
    Disable,
}

impl ApplicationAction {
    /// The last segment of the route.
    fn segment(self) -> &'static str {
        match self {
            Self::Withdraw => "withdraw",
            Self::Approve => "approve",
            Self::Disable => "disable",
        }
    }

    /// The state the node must answer with.
    fn expected(self) -> ApplicationState {
        match self {
            Self::Withdraw => ApplicationState::Withdrawn,
            Self::Approve => ApplicationState::Approved,
            Self::Disable => ApplicationState::Disabled,
        }
    }

    /// The question asked first.
    fn question(self, application: &ApplicationId) -> String {
        match self {
            Self::Withdraw => format!(
                "withdraw application {application}? No new installations; existing ones keep \
                 running"
            ),
            Self::Approve => format!("approve application {application} again?"),
            Self::Disable => format!(
                "DISABLE application {application}? This is final: every installation's key is \
                 disabled and its running jobs are stopped; a new version is a new application"
            ),
        }
    }
}

impl Session {
    /// `stratum application add <manifest.json> [--yes]`: approves an
    /// application. Asks first. Signed.
    ///
    /// The manifest is read (at most 256 KiB), checked for shape locally
    /// against the widest ceilings any node allows, shown, and sent as
    /// given. The node validates it against its own ceilings, and refuses
    /// it unless its runner reports the image ID present on the tenant
    /// daemon with no volumes declared.
    ///
    /// # Errors
    ///
    /// [`CliError::FileContents`] for an unreadable or invalid manifest,
    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
    /// errors (`invalid` naming the failed rule, `image_absent`,
    /// `image_has_volumes`).
    pub fn application_add(
        &self,
        manifest_file: &Path,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation = operation_id(operation_id_arg)?;
        let bytes = read_manifest(manifest_file)?;
        let valid = ValidManifest::parse(&bytes, &WIDEST_CEILINGS).map_err(|err| {
            CliError::FileContents {
                path: manifest_file.to_owned(),
                message: format!(
                    "not a valid manifest: {} ({})",
                    err.field(),
                    err.rule().as_str()
                ),
            }
        })?;
        let manifest: Json =
            serde_json::from_slice(&bytes).map_err(|_| CliError::FileContents {
                path: manifest_file.to_owned(),
                message: "not JSON".to_owned(),
            })?;
        let key = self.key()?;
        let client = self.client()?;
        let shown = valid.manifest();
        self.output().line(&format!(
            "application: {} {}",
            sanitize(&shown.name),
            sanitize(&shown.version)
        ))?;
        self.output().line(&format!("image: {}", shown.image_id))?;
        for container in &shown.containers {
            let modes: Vec<&str> = container.modes.iter().map(|m| m.as_str()).collect();
            self.output()
                .line(&format!("  {}  {}", container.path, modes.join(", ")))?;
        }
        if !self.confirmed(
            &format!(
                "approve {} {} for every member to install?",
                sanitize(&shown.name),
                sanitize(&shown.version)
            ),
            confirmation,
        )? {
            return Err(CliError::NotConfirmed);
        }
        self.note_admin_operation(&operation)?;
        let body = to_body(&ApproveApplicationRequest {
            operation_id: operation.clone(),
            manifest,
        })?;
        let (answer, raw): (ApproveApplicationResponse, Json) =
            client.post(APPLICATIONS, &body, Some(&key))?.into_json()?;
        if answer.image_id != shown.image_id {
            return Err(CliError::Refused(format!(
                "the node approved image {} for a manifest naming {}",
                answer.image_id, shown.image_id
            )));
        }
        self.output().json(&json!({
            "operation_id": operation.as_str(),
            "result": raw,
        }))?;
        self.output().line(&format!(
            "application {}: {} (image {})",
            answer.application, answer.state, answer.image_id
        ))?;
        Ok(exit::OK)
    }

    /// `stratum application list`: lists every application with its state,
    /// manifest name and version, image ID, approval time and installation
    /// count. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn application_list(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (list, raw): (ApplicationList, Json) =
            client.get(APPLICATIONS, Some(&key))?.into_json()?;
        self.output().json(&raw)?;
        if list.applications.is_empty() {
            self.output().line("no applications")?;
        }
        for view in &list.applications {
            self.output().line(&format!(
                "{}  {}  {} {}  image {}  approved at {}  installations {}",
                view.application,
                view.state,
                sanitize(&view.manifest.name),
                sanitize(&view.manifest.version),
                view.image_id,
                view.approved_at,
                view.installations
            ))?;
        }
        Ok(exit::OK)
    }

    /// `stratum application withdraw|approve|disable <id> [--yes]`: moves an
    /// application to another state. Asks first. Signed.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
    /// not the state asked for, and key, transport, protocol and server
    /// errors (`conflict` from a state that cannot make the transition).
    pub fn application_action(
        &self,
        application: &ApplicationId,
        action: ApplicationAction,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation = operation_id(operation_id_arg)?;
        let key = self.key()?;
        let client = self.client()?;
        if !self.confirmed(&action.question(application), confirmation)? {
            return Err(CliError::NotConfirmed);
        }
        self.note_admin_operation(&operation)?;
        let body = to_body(&ApplicationActionRequest {
            operation_id: operation.clone(),
        })?;
        let path = format!("{APPLICATIONS}/{application}/{}", action.segment());
        let (answer, _raw): (ApplicationStateResponse, Json) =
            client.post(&path, &body, Some(&key))?.into_json()?;
        if answer.state != action.expected() {
            return Err(CliError::Refused(format!(
                "the node reports application {application} as {} after {}",
                answer.state,
                action.segment()
            )));
        }
        self.output().json(&json!({
            "operation_id": operation.as_str(),
            "application": application,
            "state": answer.state,
        }))?;
        self.output()
            .line(&format!("application {application}: {}", answer.state))?;
        Ok(exit::OK)
    }

    /// `stratum installations`: lists every installation on the node: owner,
    /// application, state, key-disable reasons, job counts by state and
    /// grant state. No result bodies. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn installations(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (list, raw): (InstallationList, Json) =
            client.get(INSTALLATIONS, Some(&key))?.into_json()?;
        self.output().json(&raw)?;
        if list.installations.is_empty() {
            self.output().line("no installations")?;
        }
        for view in &list.installations {
            self.output()
                .line(&format!("{}  owner {}", summary_line(view), view.owner))?;
        }
        Ok(exit::OK)
    }

    /// Notes an administrator operation ID before its `POST`.
    fn note_admin_operation(
        &self,
        operation: &stratum_node_core::OperationId,
    ) -> Result<(), CliError> {
        self.output().note(&format!(
            "operation id: {operation} (to retry after a lost response, pass --operation-id \
             {operation}: the retry must send the same request)"
        ))
    }
}

/// Reads a manifest file: a regular file of at most 256 KiB.
fn read_manifest(path: &Path) -> Result<Vec<u8>, CliError> {
    let fail = |message: String| CliError::FileContents {
        path: path.to_owned(),
        message,
    };
    let file = File::open(path).map_err(|err| fail(format!("cannot be opened: {err}")))?;
    let metadata = file
        .metadata()
        .map_err(|err| fail(format!("cannot be read: {err}")))?;
    if !metadata.is_file() {
        return Err(fail("is not a regular file".to_owned()));
    }
    let mut bytes = Vec::new();
    file.take(MAX_MANIFEST_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|err| fail(format!("cannot be read: {err}")))?;
    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_MANIFEST_BYTES {
        return Err(fail(format!("is larger than {MAX_MANIFEST_BYTES} bytes")));
    }
    Ok(bytes)
}