use std::{
collections::BTreeMap,
fs::{self, File},
io::{self, Write},
num::NonZeroU16,
path::Path,
process,
sync::atomic::{AtomicUsize, Ordering},
};
use troll_core::{AppRequest, Permanent, Refused, Registry, SystemClock, parse_component_spec};
use crate::{
cli::{AppAllocationArgs, AppCommand},
error::CliError,
output::{
self, AppAllocationOutput, AppEntries, AppListOutput, AppOutput, EditOutput, EnvOutput,
EnvWriteReport, SCHEMA, TaggedPermanent, format_port,
},
};
use super::{
Context,
edit::{self, EditChanges},
inspect::allocation_snapshot_proto,
registry::holder,
};
pub(crate) fn build_app_reserve(
context: &Context,
args: AppAllocationArgs,
) -> Result<AppAllocationOutput, CliError> {
build_allocation(context, args, true)
}
pub(crate) fn build_app_add(
context: &Context,
args: AppAllocationArgs,
) -> Result<AppAllocationOutput, CliError> {
build_allocation(context, args, false)
}
fn build_allocation(
context: &Context,
args: AppAllocationArgs,
reserve: bool,
) -> Result<AppAllocationOutput, CliError> {
let mut components = args
.components
.iter()
.map(|spec| parse_component_spec(spec))
.collect::<Result<Vec<_>, _>>()?;
for pin in &args.pins {
let (name, port) = pin
.split_once('=')
.and_then(|(name, port)| {
port.parse::<NonZeroU16>()
.ok()
.map(|port| (name, port.get()))
})
.ok_or_else(|| {
CliError::invalid_request(format!(
"invalid port pin {pin:?}, expected COMPONENT=PORT"
))
})?;
let component = components
.iter_mut()
.find(|component| component.name == name)
.ok_or_else(|| {
CliError::invalid_request(format!("port pin {pin:?} names an unlisted component"))
})?;
if component.pinned_port.replace(port).is_some() {
return Err(CliError::invalid_request(format!(
"component {name:?} has more than one port pin"
)));
}
}
context.require_ephemeral_range()?;
let probe = context.probe()?;
context.ensure_registry_home()?;
let request = AppRequest {
app: args.app.clone(),
claimed_by: holder(),
bind: args.bind,
components,
};
let allocate = if reserve {
troll_core::reserve_app_proto
} else {
troll_core::add_components_proto
};
let result = allocate(
&context.store,
&context.config.policy,
&|proto| allocation_snapshot_proto(probe, proto),
&SystemClock,
request,
)?;
Ok(AppAllocationOutput {
schema: SCHEMA,
app: app_entries(args.app, result.entries, false),
contiguous: result.contiguous,
})
}
pub(crate) fn build_app_list(context: &Context) -> Result<AppListOutput, CliError> {
let registry = context.store.load()?;
let apps = registry
.apps()
.into_iter()
.map(|(app, entries)| app_entries(app, entries.into_iter().cloned(), true))
.collect();
Ok(AppListOutput {
schema: SCHEMA,
apps,
})
}
pub(crate) fn build_app_show(context: &Context, app: &str) -> Result<AppOutput, CliError> {
let registry = context.store.load()?;
let entries = registry.app(app).ok_or_else(|| app_not_found(app))?;
Ok(AppOutput {
schema: SCHEMA,
app: app_entries(app, entries.into_iter().cloned(), true),
})
}
pub(crate) fn build_app_remove(
context: &Context,
app: &str,
component: &str,
force_shared: bool,
expected_tag: Option<&str>,
) -> Result<AppOutput, CliError> {
context.ensure_registry_home()?;
let entry =
troll_core::remove_component(&context.store, app, component, force_shared, expected_tag)?;
Ok(AppOutput {
schema: SCHEMA,
app: app_entries(app, [entry], false),
})
}
pub(crate) fn build_app_edit(
context: &Context,
app: &str,
component: &str,
expected_tag: Option<&str>,
changes: EditChanges,
) -> Result<EditOutput, CliError> {
let registry = context.store.load()?;
let entries = registry.app(app).ok_or_else(|| app_not_found(app))?;
let entry = entries
.into_iter()
.find(|entry| entry.component.as_deref() == Some(component))
.ok_or_else(|| Refused::ComponentNotFound {
app: app.into(),
component: component.into(),
})?;
edit::edit_snapshot(context, entry, expected_tag, changes)
}
pub(crate) fn build_app_release(
context: &Context,
app: &str,
confirm: &str,
expected_tag: Option<&str>,
) -> Result<AppOutput, CliError> {
context.ensure_registry_home()?;
let entries = troll_core::release_app(&context.store, app, confirm, expected_tag)?;
Ok(AppOutput {
schema: SCHEMA,
app: app_entries(app, entries, false),
})
}
pub(crate) fn build_env(context: &Context, app: &str) -> Result<EnvOutput, CliError> {
let registry = context.store.load()?;
let env = registry.app_env(app).ok_or_else(|| app_not_found(app))?;
Ok(EnvOutput {
schema: SCHEMA,
variables: env.variables,
written: None,
unlabeled: env.unlabeled.iter().map(|entry| entry.port).collect(),
})
}
fn app_not_found(app: &str) -> Refused {
Refused::AppNotFound { app: app.into() }
}
fn app_entries(
app: impl Into<String>,
entries: impl IntoIterator<Item = Permanent>,
include_tag: bool,
) -> AppEntries {
let entries: Vec<TaggedPermanent> = entries.into_iter().map(Into::into).collect();
let tag =
include_tag.then(|| Registry::app_tag(entries.iter().map(|claim| claim.tag.as_str())));
AppEntries {
app: app.into(),
tag,
entries,
}
}
pub(super) fn run(context: &Context, action: AppCommand, json: bool) -> Result<(), CliError> {
match action {
AppCommand::Reserve(args) => print_allocation(build_app_reserve(context, args)?, json),
AppCommand::Add(args) => print_allocation(build_app_add(context, args)?, json),
AppCommand::List => {
let result = build_app_list(context)?;
output::write(json, &result, |out| {
if result.apps.is_empty() {
writeln!(out, "No apps.")?;
}
for app in &result.apps {
print_app(out, app)?;
}
Ok(())
})
}
AppCommand::Show { app } => print_result(build_app_show(context, &app)?, "", json),
AppCommand::Remove {
app,
component,
force_shared,
if_tag,
} => print_result(
build_app_remove(context, &app, &component, force_shared, if_tag.as_deref())?,
"Removed from ",
json,
),
AppCommand::Edit {
app,
component,
mut changes,
} => {
let tag = changes.tag.take();
edit::print_edit(
build_app_edit(
context,
&app,
&component,
tag.as_deref(),
changes.try_into()?,
)?,
json,
)
}
AppCommand::Release {
app,
confirm,
if_tag,
} => print_result(
build_app_release(context, &app, &confirm, if_tag.as_deref())?,
"Released ",
json,
),
}
}
pub(super) fn env(
context: &Context,
app: &str,
write: Option<&Path>,
json: bool,
) -> Result<(), CliError> {
let mut result = build_env(context, app)?;
for port in &result.unlabeled {
writeln!(
io::stderr().lock(),
"App {app:?} port {port} has no component label."
)?;
}
if let Some(path) = write {
result.written = Some(write_env_file(path, &result.variables)?);
}
output::write(json, &result, |out| {
if let Some(report) = &result.written {
writeln!(
out,
"Updated {}: {} added, {} updated, {} unchanged.",
report.path,
report.added.len(),
report.updated.len(),
report.unchanged.len()
)?;
} else {
for (name, port) in &result.variables {
writeln!(out, "{name}={port}")?;
}
}
Ok(())
})
}
pub(crate) fn write_env_file(
path: &Path,
variables: &[(String, u16)],
) -> Result<EnvWriteReport, CliError> {
static ENV_TMP_SEQ: AtomicUsize = AtomicUsize::new(0);
let (existing_text, existing_perms) = match fs::symlink_metadata(path) {
Ok(meta) => {
if !meta.is_file() {
return Err(CliError::invalid_request(format!(
"refusing to write env file '{}': target must be a regular file, not a symlink or directory",
path.display()
)));
}
let text = fs::read_to_string(path).map_err(|e| {
CliError::invalid_request(format!("could not read '{}': {e}", path.display()))
})?;
(Some(text), Some(meta.permissions()))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => (None, None),
Err(err) => {
return Err(CliError::invalid_request(format!(
"could not inspect '{}': {err}",
path.display()
)));
}
};
let desired: BTreeMap<&str, u16> = variables
.iter()
.map(|(name, port)| (name.as_str(), *port))
.collect();
let mut seen: BTreeMap<&str, bool> = BTreeMap::new();
let mut updated = Vec::new();
let mut unchanged = Vec::new();
let mut added = Vec::new();
let mut newline = "\n";
let mut out_lines: Vec<String> = Vec::new();
if let Some(text) = &existing_text {
if text.contains("\r\n") {
newline = "\r\n";
}
for raw_line in text.split('\n') {
let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
if let Some((prefix, name, current_val)) = parse_env_assignment(line)
&& let Some(&port) = desired.get(name)
{
let port_str = port.to_string();
seen.insert(name, true);
if current_val.trim() == port_str {
unchanged.push(name.to_owned());
out_lines.push(line.to_owned());
} else {
updated.push(name.to_owned());
out_lines.push(format!("{prefix}{name}={port_str}"));
}
continue;
}
out_lines.push(line.to_owned());
}
if text.ends_with('\n') && out_lines.last().is_some_and(String::is_empty) {
out_lines.pop();
}
}
for (name, port) in variables {
if !seen.contains_key(name.as_str()) {
added.push(name.clone());
out_lines.push(format!("{name}={port}"));
}
}
let mut content = out_lines.join(newline);
if !content.is_empty() {
content.push_str(newline);
}
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let (staged_path, mut file) = loop {
let seq = ENV_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
let candidate = parent.join(format!(".troll-env-{}-{seq}.tmp", process::id()));
match File::create_new(&candidate) {
Ok(file) => break (candidate, file),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(err) => {
return Err(CliError::invalid_request(format!(
"could not create staging file in '{}': {err}",
parent.display()
)));
}
}
};
let write_res = (|| -> io::Result<()> {
if let Some(perms) = existing_perms {
file.set_permissions(perms)?;
}
file.write_all(content.as_bytes())?;
file.sync_all()?;
drop(file);
fs::rename(&staged_path, path)?;
Ok(())
})();
if let Err(err) = write_res {
let _ = fs::remove_file(&staged_path);
return Err(CliError::invalid_request(format!(
"could not write '{}': {err}",
path.display()
)));
}
Ok(EnvWriteReport {
path: path.display().to_string(),
added,
updated,
unchanged,
})
}
fn parse_env_assignment(line: &str) -> Option<(&str, &str, &str)> {
let trimmed_start_len = line.len() - line.trim_start_matches([' ', '\t']).len();
let rest = &line[trimmed_start_len..];
if rest.is_empty() || rest.starts_with('#') {
return None;
}
let (prefix_end, after_export) = if let Some(after) = rest.strip_prefix("export")
&& after.starts_with([' ', '\t'])
{
let ws = after.len() - after.trim_start_matches([' ', '\t']).len();
(trimmed_start_len + "export".len() + ws, &after[ws..])
} else {
(trimmed_start_len, rest)
};
let (name, value) = after_export.split_once('=')?;
let name = name.trim_end_matches([' ', '\t']);
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return None;
}
Some((&line[..prefix_end], name, value))
}
fn print_allocation(result: AppAllocationOutput, json: bool) -> Result<(), CliError> {
output::write(json, &result, |out| {
print_app(out, &result.app)?;
let layout = if result.contiguous {
"contiguous"
} else {
"non-contiguous"
};
writeln!(out, "Automatically allocated ports: {layout}.")?;
Ok(())
})
}
fn print_result(result: AppOutput, prefix: &str, json: bool) -> Result<(), CliError> {
output::write(json, &result, |out| {
write!(out, "{prefix}")?;
print_app(out, &result.app)
})
}
fn print_app(out: &mut dyn Write, app: &AppEntries) -> Result<(), CliError> {
write!(out, "App {}", app.app)?;
if let Some(tag) = &app.tag {
write!(out, " (tag {tag})")?;
}
writeln!(out)?;
for claim in &app.entries {
let entry = &claim.entry;
let component = entry.component.as_deref().unwrap_or("(unlabeled)");
let role = match entry.role {
troll_core::Role::App => "app",
troll_core::Role::Service => "service",
};
write!(
out,
" {} {component} {role} {} {} tag {}",
format_port(entry.port, entry.protocol),
entry.bind,
entry.service,
claim.tag
)?;
if let Some(link) = &claim.link {
write!(out, " {link}")?;
}
writeln!(out)?;
}
Ok(())
}