1use 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
21const APPLICATIONS: &str = "/api/v1/applications";
23const INSTALLATIONS: &str = "/api/v1/installations";
25const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
27
28const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum ApplicationAction {
44 Withdraw,
47 Approve,
49 Disable,
53}
54
55impl ApplicationAction {
56 fn segment(self) -> &'static str {
58 match self {
59 Self::Withdraw => "withdraw",
60 Self::Approve => "approve",
61 Self::Disable => "disable",
62 }
63 }
64
65 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 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 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 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 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 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 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
288fn 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}