Skip to main content

stratum_node_cli/
application.rs

1//! `stratum application …` and `stratum installations`: the administrator's
2//! catalogue commands on the loopback API.
3
4use std::fs::File;
5use std::io::Read as _;
6use std::path::Path;
7
8use serde_json::{json, Value as Json};
9use stratum_node_core::{
10    ApplicationActionRequest, ApplicationId, ApplicationList, ApplicationState,
11    ApplicationStateResponse, ApproveApplicationRequest, ApproveApplicationResponse,
12    InstallationList, JobCeilings, MilliCpus, ValidManifest,
13};
14
15use crate::app::summary_line;
16use crate::error::CliError;
17use crate::exit;
18use crate::output::sanitize;
19use crate::session::{operation_id, to_body, Confirmation, Session};
20
21/// The applications route; each application is `APPLICATIONS/<id>`.
22const APPLICATIONS: &str = "/api/v1/applications";
23/// The administrator's installation list.
24const INSTALLATIONS: &str = "/api/v1/installations";
25/// The largest manifest file read.
26const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
27
28/// The highest ceilings any node can be configured with
29/// (`limits.job_max_*` at the top of their ranges). The client checks a
30/// manifest's shape against these, so it never refuses one the node would
31/// accept; the node checks it against its own ceilings.
32const WIDEST_CEILINGS: JobCeilings = JobCeilings {
33    cpus: MilliCpus::new(64_000),
34    memory_bytes: 1024 * 1024 * 1024 * 1024,
35    pids: 65_536,
36    tmp_bytes: 1024 * 1024 * 1024 * 1024,
37    timeout_secs: 43_200,
38};
39
40/// An administrator transition of an application.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum ApplicationAction {
44    /// `approved` → `withdrawn`: no new installations; existing ones keep
45    /// running.
46    Withdraw,
47    /// `withdrawn` → `approved`: installable again; touches no key.
48    Approve,
49    /// `approved` or `withdrawn` → `disabled`, terminal: the emergency
50    /// stop. Every installation's key is disabled and its running jobs are
51    /// stopped.
52    Disable,
53}
54
55impl ApplicationAction {
56    /// The last segment of the route.
57    fn segment(self) -> &'static str {
58        match self {
59            Self::Withdraw => "withdraw",
60            Self::Approve => "approve",
61            Self::Disable => "disable",
62        }
63    }
64
65    /// The state the node must answer with.
66    fn expected(self) -> ApplicationState {
67        match self {
68            Self::Withdraw => ApplicationState::Withdrawn,
69            Self::Approve => ApplicationState::Approved,
70            Self::Disable => ApplicationState::Disabled,
71        }
72    }
73
74    /// The question asked first.
75    fn question(self, application: &ApplicationId) -> String {
76        match self {
77            Self::Withdraw => format!(
78                "withdraw application {application}? No new installations; existing ones keep \
79                 running"
80            ),
81            Self::Approve => format!("approve application {application} again?"),
82            Self::Disable => format!(
83                "DISABLE application {application}? This is final: every installation's key is \
84                 disabled and its running jobs are stopped; a new version is a new application"
85            ),
86        }
87    }
88}
89
90impl Session {
91    /// `stratum application add <manifest.json> [--yes]`: approves an
92    /// application. Asks first. Signed.
93    ///
94    /// The manifest is read (at most 256 KiB), checked for shape locally
95    /// against the widest ceilings any node allows, shown, and sent as
96    /// given. The node validates it against its own ceilings, and refuses
97    /// it unless its runner reports the image ID present on the tenant
98    /// daemon with no volumes declared.
99    ///
100    /// # Errors
101    ///
102    /// [`CliError::FileContents`] for an unreadable or invalid manifest,
103    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
104    /// errors (`invalid` naming the failed rule, `image_absent`,
105    /// `image_has_volumes`).
106    pub fn application_add(
107        &self,
108        manifest_file: &Path,
109        operation_id_arg: Option<&str>,
110        confirmation: Confirmation,
111    ) -> Result<u8, CliError> {
112        let operation = operation_id(operation_id_arg)?;
113        let bytes = read_manifest(manifest_file)?;
114        let valid = ValidManifest::parse(&bytes, &WIDEST_CEILINGS).map_err(|err| {
115            CliError::FileContents {
116                path: manifest_file.to_owned(),
117                message: format!(
118                    "not a valid manifest: {} ({})",
119                    err.field(),
120                    err.rule().as_str()
121                ),
122            }
123        })?;
124        let manifest: Json =
125            serde_json::from_slice(&bytes).map_err(|_| CliError::FileContents {
126                path: manifest_file.to_owned(),
127                message: "not JSON".to_owned(),
128            })?;
129        let key = self.key()?;
130        let client = self.client()?;
131        let shown = valid.manifest();
132        self.output().line(&format!(
133            "application: {} {}",
134            sanitize(&shown.name),
135            sanitize(&shown.version)
136        ))?;
137        self.output().line(&format!("image: {}", shown.image_id))?;
138        for container in &shown.containers {
139            let modes: Vec<&str> = container.modes.iter().map(|m| m.as_str()).collect();
140            self.output()
141                .line(&format!("  {}  {}", container.path, modes.join(", ")))?;
142        }
143        if !self.confirmed(
144            &format!(
145                "approve {} {} for every member to install?",
146                sanitize(&shown.name),
147                sanitize(&shown.version)
148            ),
149            confirmation,
150        )? {
151            return Err(CliError::NotConfirmed);
152        }
153        self.note_admin_operation(&operation)?;
154        let body = to_body(&ApproveApplicationRequest {
155            operation_id: operation.clone(),
156            manifest,
157        })?;
158        let (answer, raw): (ApproveApplicationResponse, Json) =
159            client.post(APPLICATIONS, &body, Some(&key))?.into_json()?;
160        if answer.image_id != shown.image_id {
161            return Err(CliError::Refused(format!(
162                "the node approved image {} for a manifest naming {}",
163                answer.image_id, shown.image_id
164            )));
165        }
166        self.output().json(&json!({
167            "operation_id": operation.as_str(),
168            "result": raw,
169        }))?;
170        self.output().line(&format!(
171            "application {}: {} (image {})",
172            answer.application, answer.state, answer.image_id
173        ))?;
174        Ok(exit::OK)
175    }
176
177    /// `stratum application list`: lists every application with its state,
178    /// manifest name and version, image ID, approval time and installation
179    /// count. Signed.
180    ///
181    /// # Errors
182    ///
183    /// Key, transport, protocol and server errors.
184    pub fn application_list(&self) -> Result<u8, CliError> {
185        let key = self.key()?;
186        let client = self.client()?;
187        let (list, raw): (ApplicationList, Json) =
188            client.get(APPLICATIONS, Some(&key))?.into_json()?;
189        self.output().json(&raw)?;
190        if list.applications.is_empty() {
191            self.output().line("no applications")?;
192        }
193        for view in &list.applications {
194            self.output().line(&format!(
195                "{}  {}  {} {}  image {}  approved at {}  installations {}",
196                view.application,
197                view.state,
198                sanitize(&view.manifest.name),
199                sanitize(&view.manifest.version),
200                view.image_id,
201                view.approved_at,
202                view.installations
203            ))?;
204        }
205        Ok(exit::OK)
206    }
207
208    /// `stratum application withdraw|approve|disable <id> [--yes]`: moves an
209    /// application to another state. Asks first. Signed.
210    ///
211    /// # Errors
212    ///
213    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
214    /// not the state asked for, and key, transport, protocol and server
215    /// errors (`conflict` from a state that cannot make the transition).
216    pub fn application_action(
217        &self,
218        application: &ApplicationId,
219        action: ApplicationAction,
220        operation_id_arg: Option<&str>,
221        confirmation: Confirmation,
222    ) -> Result<u8, CliError> {
223        let operation = operation_id(operation_id_arg)?;
224        let key = self.key()?;
225        let client = self.client()?;
226        if !self.confirmed(&action.question(application), confirmation)? {
227            return Err(CliError::NotConfirmed);
228        }
229        self.note_admin_operation(&operation)?;
230        let body = to_body(&ApplicationActionRequest {
231            operation_id: operation.clone(),
232        })?;
233        let path = format!("{APPLICATIONS}/{application}/{}", action.segment());
234        let (answer, _raw): (ApplicationStateResponse, Json) =
235            client.post(&path, &body, Some(&key))?.into_json()?;
236        if answer.state != action.expected() {
237            return Err(CliError::Refused(format!(
238                "the node reports application {application} as {} after {}",
239                answer.state,
240                action.segment()
241            )));
242        }
243        self.output().json(&json!({
244            "operation_id": operation.as_str(),
245            "application": application,
246            "state": answer.state,
247        }))?;
248        self.output()
249            .line(&format!("application {application}: {}", answer.state))?;
250        Ok(exit::OK)
251    }
252
253    /// `stratum installations`: lists every installation on the node: owner,
254    /// application, state, key-disable reasons, job counts by state and
255    /// grant state. No result bodies. Signed.
256    ///
257    /// # Errors
258    ///
259    /// Key, transport, protocol and server errors.
260    pub fn installations(&self) -> Result<u8, CliError> {
261        let key = self.key()?;
262        let client = self.client()?;
263        let (list, raw): (InstallationList, Json) =
264            client.get(INSTALLATIONS, Some(&key))?.into_json()?;
265        self.output().json(&raw)?;
266        if list.installations.is_empty() {
267            self.output().line("no installations")?;
268        }
269        for view in &list.installations {
270            self.output()
271                .line(&format!("{}  owner {}", summary_line(view), view.owner))?;
272        }
273        Ok(exit::OK)
274    }
275
276    /// Notes an administrator operation ID before its `POST`.
277    fn note_admin_operation(
278        &self,
279        operation: &stratum_node_core::OperationId,
280    ) -> Result<(), CliError> {
281        self.output().note(&format!(
282            "operation id: {operation} (to retry after a lost response, pass --operation-id \
283             {operation}: the retry must send the same request)"
284        ))
285    }
286}
287
288/// Reads a manifest file: a regular file of at most 256 KiB.
289fn read_manifest(path: &Path) -> Result<Vec<u8>, CliError> {
290    let fail = |message: String| CliError::FileContents {
291        path: path.to_owned(),
292        message,
293    };
294    let file = File::open(path).map_err(|err| fail(format!("cannot be opened: {err}")))?;
295    let metadata = file
296        .metadata()
297        .map_err(|err| fail(format!("cannot be read: {err}")))?;
298    if !metadata.is_file() {
299        return Err(fail("is not a regular file".to_owned()));
300    }
301    let mut bytes = Vec::new();
302    file.take(MAX_MANIFEST_BYTES + 1)
303        .read_to_end(&mut bytes)
304        .map_err(|err| fail(format!("cannot be read: {err}")))?;
305    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_MANIFEST_BYTES {
306        return Err(fail(format!("is larger than {MAX_MANIFEST_BYTES} bytes")));
307    }
308    Ok(bytes)
309}