troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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>,
    /// Number of affected allocations, counting overlaps only once per allocation.
    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 {
        // Encode before writing so a serialization error can still return one
        // valid JSON error object.
        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(())
}

// Diagnostics must not interrupt child waiting or lease release if stderr closes.
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))
}