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};
const APPLICATIONS: &str = "/api/v1/applications";
const INSTALLATIONS: &str = "/api/v1/installations";
const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
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,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApplicationAction {
Withdraw,
Approve,
Disable,
}
impl ApplicationAction {
fn segment(self) -> &'static str {
match self {
Self::Withdraw => "withdraw",
Self::Approve => "approve",
Self::Disable => "disable",
}
}
fn expected(self) -> ApplicationState {
match self {
Self::Withdraw => ApplicationState::Withdrawn,
Self::Approve => ApplicationState::Approved,
Self::Disable => ApplicationState::Disabled,
}
}
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 {
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)
}
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)
}
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)
}
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)
}
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)"
))
}
}
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)
}