use std::{
io::{self, Write},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
use serde::{Serialize, Serializer};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use troll_core::{
DriftCounts, Lease, LeaseState, Permanent, SilentEntry, Zone, ZoneConflict, ZoneResult,
};
use troll_probe::{
Classification, Kind, Listener, OwnerDetails, ServiceCategory, ServiceInfo, identify_service,
inspect_owner_details,
};
use crate::error::CliError;
pub const SCHEMA: u32 = 1;
#[derive(Serialize)]
pub struct ClaimOutput {
pub schema: u32,
#[serde(flatten)]
pub entry: Permanent,
pub tag: String,
}
#[derive(Serialize)]
pub(crate) struct LeaseOutput {
pub schema: u32,
#[serde(flatten)]
pub lease: TaggedLease,
}
#[derive(Serialize)]
pub struct ReleaseOutput {
pub schema: u32,
#[serde(flatten)]
pub entry: ReleasedEntry,
}
#[derive(Serialize)]
pub(crate) struct LeaseGroupOutput {
pub schema: u32,
pub group: String,
pub group_tag: String,
pub contiguous: bool,
pub leases: Vec<TaggedLease>,
}
#[derive(Serialize)]
pub(crate) struct LeaseGroupChangeOutput<T> {
pub schema: u32,
pub group: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub group_tag: Option<String>,
pub leases: Vec<T>,
}
#[derive(Serialize)]
pub(crate) struct EditOutput {
pub schema: u32,
#[serde(flatten)]
pub claim: TaggedPermanent,
}
#[derive(Serialize)]
pub(crate) struct LeaseEditOutput {
pub schema: u32,
#[serde(flatten)]
pub lease: TaggedLease,
}
#[derive(Serialize)]
pub(crate) struct ZoneOutput {
pub schema: u32,
#[serde(flatten, serialize_with = "serialize_zone_result")]
pub result: ZoneResult,
}
#[derive(Serialize)]
pub(crate) struct ZoneListOutput {
pub schema: u32,
#[serde(serialize_with = "serialize_zones")]
pub zones: Vec<Zone>,
pub conflicts: Vec<ZoneConflict>,
pub conflict_count: usize,
}
#[derive(Serialize)]
struct TaggedZone<'a> {
#[serde(flatten)]
zone: &'a Zone,
tag: String,
}
impl<'a> From<&'a Zone> for TaggedZone<'a> {
fn from(zone: &'a Zone) -> Self {
Self {
zone,
tag: zone.entry_tag(),
}
}
}
fn serialize_zone_result<S: Serializer>(
result: &ZoneResult,
serializer: S,
) -> Result<S::Ok, S::Error> {
#[derive(Serialize)]
struct TaggedZoneResult<'a> {
zone: TaggedZone<'a>,
conflicts: &'a [ZoneConflict],
}
TaggedZoneResult {
zone: (&result.zone).into(),
conflicts: &result.conflicts,
}
.serialize(serializer)
}
fn serialize_zones<S: Serializer>(zones: &[Zone], serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(zones.iter().map(TaggedZone::from))
}
#[derive(Serialize)]
pub(crate) struct AppOutput {
pub schema: u32,
#[serde(flatten)]
pub app: AppEntries,
}
#[derive(Serialize)]
pub(crate) struct AppListOutput {
pub schema: u32,
pub apps: Vec<AppEntries>,
}
#[derive(Serialize)]
pub(crate) struct AppEntries {
pub app: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
pub entries: Vec<TaggedPermanent>,
}
#[derive(Serialize)]
pub(crate) struct AppAllocationOutput {
pub schema: u32,
#[serde(flatten)]
pub app: AppEntries,
pub contiguous: bool,
}
#[derive(Serialize)]
pub(crate) struct EnvOutput {
pub schema: u32,
pub variables: Vec<(String, u16)>,
#[serde(skip)]
pub unlabeled: Vec<u16>,
}
#[derive(Serialize)]
#[serde(tag = "tier", rename_all = "lowercase")]
pub enum ReleasedEntry {
Permanent(Permanent),
Lease(Lease),
}
#[derive(Serialize)]
pub struct CheckOutput<P = Permanent, L = Lease> {
pub schema: u32,
pub port: u16,
pub verdict: &'static str,
pub permanent: Vec<P>,
pub lease: Vec<L>,
pub listeners: Vec<ListenerOutput>,
}
#[derive(Serialize)]
pub struct ListOutput {
pub schema: u32,
pub complete: bool,
pub skipped_rows: usize,
pub services: Vec<PermanentRow>,
pub apps: Vec<PermanentRow>,
pub leases: Vec<LeaseRow>,
pub unregistered: Vec<ListenerOutput>,
}
#[derive(Serialize)]
pub struct PermanentRow {
#[serde(flatten)]
pub claim: TaggedPermanent,
pub status: &'static str,
pub listeners: Vec<ListenerOutput>,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_info: Option<ServiceInfoOutput>,
}
#[derive(Serialize)]
pub struct LeaseRow {
#[serde(flatten)]
pub lease: TaggedLease,
#[serde(skip_serializing_if = "Option::is_none")]
pub group_tag: Option<String>,
pub status: &'static str,
pub state: &'static str,
pub listeners: Vec<ListenerOutput>,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_info: Option<ServiceInfoOutput>,
}
#[derive(Serialize)]
pub(crate) struct TaggedPermanent {
#[serde(flatten)]
pub entry: Permanent,
pub tag: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
}
impl From<Permanent> for TaggedPermanent {
fn from(entry: Permanent) -> Self {
let tag = entry.entry_tag();
let link = web_link(&entry);
Self { entry, tag, link }
}
}
fn web_link(entry: &Permanent) -> Option<String> {
let web = entry.web.as_ref()?;
let host = match entry.bind {
IpAddr::V4(Ipv4Addr::LOCALHOST | Ipv4Addr::UNSPECIFIED) => "127.0.0.1",
IpAddr::V6(Ipv6Addr::LOCALHOST | Ipv6Addr::UNSPECIFIED) => "[::1]",
_ => return None,
};
Some(format!(
"{}://{host}:{}{}",
web.scheme, entry.port, web.path
))
}
#[derive(Serialize)]
pub(crate) struct TaggedLease {
#[serde(flatten)]
pub entry: Lease,
pub tag: String,
}
impl From<Lease> for TaggedLease {
fn from(entry: Lease) -> Self {
let tag = entry.entry_tag();
Self { entry, tag }
}
}
#[derive(Serialize)]
pub(crate) struct DriftOutput {
pub schema: u32,
pub complete: bool,
pub skipped_rows: usize,
pub listening_unclaimed: Vec<ListenerOutput>,
pub claimed_silent: Vec<TaggedSilentEntry>,
pub leases_expiring: Vec<TaggedLease>,
pub zone_conflicts: Vec<ZoneConflict>,
pub counts: DriftCounts,
}
#[derive(Serialize)]
#[serde(tag = "tier", rename_all = "lowercase")]
pub(crate) enum TaggedSilentEntry {
Permanent(TaggedPermanent),
Lease(TaggedLease),
}
impl From<SilentEntry> for TaggedSilentEntry {
fn from(entry: SilentEntry) -> Self {
match entry {
SilentEntry::Permanent(entry) => Self::Permanent(entry.into()),
SilentEntry::Lease(entry) => Self::Lease(entry.into()),
}
}
}
#[derive(Clone, Serialize)]
pub struct ServiceInfoOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub category: &'static str,
pub is_web: bool,
pub detected_by: &'static str,
}
impl ServiceInfoOutput {
pub fn from_info(info: ServiceInfo) -> Option<Self> {
if info.category == ServiceCategory::Unknown && info.name.is_none() && !info.is_web {
return None;
}
Some(Self {
name: info.name,
category: info.category.as_str(),
is_web: info.is_web,
detected_by: info.detected_by,
})
}
}
#[derive(Clone, Serialize)]
pub struct ProjectFileOutput {
pub name: String,
pub path: String,
pub kind: &'static str,
}
#[derive(Clone, Serialize)]
pub struct ListenerOutput {
pub id: String,
pub port: u16,
pub bind: IpAddr,
pub project: Option<String>,
#[serde(serialize_with = "serialize_kind")]
pub kind: Kind,
pub owners: Vec<OwnerOutput>,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_info: Option<ServiceInfoOutput>,
}
impl ListenerOutput {
pub fn new(listener: Listener, classification: Classification) -> Self {
let details: Vec<OwnerDetails> =
listener.owners.iter().map(inspect_owner_details).collect();
let service_info = ServiceInfoOutput::from_info(identify_service(
listener.port,
&listener.owners,
&details,
None,
None,
None,
false,
));
let owners = listener
.owners
.into_iter()
.zip(details)
.map(|(owner, detail)| OwnerOutput {
pid: owner.pid,
name: owner.name,
exe: owner.exe.map(|p| p.to_string_lossy().into_owned()),
cwd: owner.cwd.map(|p| p.to_string_lossy().into_owned()),
uid: owner.uid,
project_root: detail
.project_root
.map(|p| p.to_string_lossy().into_owned()),
unit: detail.unit,
package_name: detail.package_name,
files: detail
.files
.into_iter()
.map(|file| ProjectFileOutput {
name: file.name,
path: file.path.to_string_lossy().into_owned(),
kind: file.kind,
})
.collect(),
})
.collect();
Self {
id: listener.inode.to_string(),
port: listener.port,
bind: listener.addr,
project: classification.project,
kind: classification.kind,
owners,
service_info,
}
}
}
#[derive(Clone, Serialize)]
pub struct OwnerOutput {
pub pid: u32,
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exe: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub uid: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub project_root: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub package_name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub files: Vec<ProjectFileOutput>,
}
#[derive(Serialize)]
pub struct SweepOutput {
pub schema: u32,
pub dry_run: bool,
pub removed: Vec<Lease>,
pub kept_overdue: Vec<Lease>,
pub kept_unknown: Vec<Lease>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kept: Option<Vec<LeaseIdentity>>,
}
#[derive(Serialize)]
pub struct LeaseIdentity {
pub port: u16,
pub bind: IpAddr,
#[serde(serialize_with = "serialize_lease_start")]
pub leased_at: OffsetDateTime,
}
fn serialize_lease_start<S: Serializer>(
value: &OffsetDateTime,
serializer: S,
) -> Result<S::Ok, S::Error> {
let text = timestamp(*value).map_err(serde::ser::Error::custom)?;
serializer.serialize_str(&text)
}
pub fn write<T: Serialize>(
json: bool,
value: &T,
human: impl FnOnce(&mut dyn Write) -> Result<(), CliError>,
) -> Result<(), CliError> {
let mut out = io::stdout().lock();
if json {
let line = serde_json::to_vec(value).map_err(CliError::Json)?;
out.write_all(&line)?;
writeln!(out)?;
} else {
human(&mut out)?;
}
out.flush()?;
Ok(())
}
pub fn write_listener_scan_warning(out: &mut dyn Write, skipped_rows: usize) -> io::Result<()> {
if skipped_rows != 0 {
writeln!(
out,
"Warning: listener scan skipped {skipped_rows} malformed rows. Results are incomplete."
)?;
}
Ok(())
}
pub fn stderr_json(value: &impl Serialize) {
if let Ok(mut line) = serde_json::to_vec(value) {
line.push(b'\n');
let _ = io::stderr().lock().write_all(&line);
}
}
pub fn timestamp(time: OffsetDateTime) -> Result<String, CliError> {
Ok(time.format(&Rfc3339)?)
}
pub fn lease_state_name(state: LeaseState) -> &'static str {
match state {
LeaseState::Active => "active",
LeaseState::Overdue => "overdue",
LeaseState::Reclaimable => "reclaimable",
LeaseState::Unknown => "unknown",
}
}
pub fn kind_name(kind: Kind) -> &'static str {
match kind {
Kind::Ours => "ours",
Kind::System => "system",
Kind::ThirdParty => "third-party",
Kind::Unknown => "unknown",
}
}
fn serialize_kind<S: Serializer>(kind: &Kind, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(kind_name(*kind))
}