troll 0.3.2

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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! First-run configuration, with terminal input and activation kept injectable.

mod config;
#[path = "../../vendor/setup-wizard/src/display.rs"]
mod display;
mod ports;
mod prompt;
#[cfg(all(test, target_os = "linux"))]
mod tests;

use std::{
    env, fs,
    io::{self, IsTerminal, Write},
    ops::RangeInclusive,
    path::{Path, PathBuf},
};

use serde::Serialize;
use troll_core::{
    ClaimRequest, Config, ConfigError, Permanent, ProbeError, Registry, Role, SystemClock,
    UpdateError, Zone, ZoneResult,
};
use troll_probe::{ListenerProbe, SystemProbe};

use crate::{
    cli::Color,
    error::CliError,
    output, platform,
    setup::{ServiceResult, Systemctl, SystemctlProcess, Unit},
};

use self::{
    display::WizardTheme,
    ports::{AvailablePort, Ports, RunningService},
    prompt::{Defaults, Prompter, Terminal},
};

type EphemeralRange = Option<RangeInclusive<u16>>;

const WELL_KNOWN_LABEL: &str = "well-known";
const WELL_KNOWN_PORTS: &str = "0-1023";

struct RegistryChanges {
    port: u16,
    zone: Option<ZoneResult>,
}

pub(crate) fn run(yes: bool, service: bool, json: bool, color: Color) -> Result<(), CliError> {
    if !yes && !io::stdin().is_terminal() {
        return Err(CliError::InitRequiresTerminal);
    }

    let init = Init {
        config_home: platform::config_home()?,
        state_home: platform::state_home()?,
        probe: platform::proc_probe(),
        read_range: &platform::setup_ephemeral_range,
        yes,
        service,
    };
    let result = if yes {
        init.run(&mut Defaults, &mut SystemctlProcess)?
    } else {
        let color = platform::use_color(color)
            && (!matches!(color, Color::Auto) || io::stderr().is_terminal());
        let mut prompter = Terminal {
            input: io::stdin().lock(),
            output: io::stderr().lock(),
            theme: WizardTheme::new(color, true),
        };
        init.run(&mut prompter, &mut SystemctlProcess)?
    };

    output::write(json, &result, |out| result.write_human(out))
}

struct Init<'a> {
    config_home: PathBuf,
    state_home: PathBuf,
    probe: SystemProbe,
    read_range: &'a dyn Fn() -> Result<EphemeralRange, ProbeError>,
    yes: bool,
    service: bool,
}

impl Init<'_> {
    fn run(
        &self,
        prompter: &mut dyn Prompter,
        runner: &mut dyn Systemctl,
    ) -> Result<InitResult, CliError> {
        let path = self.config_home.join(config::FILE_NAME);
        let mut result = InitResult::new(&path);
        if self.yes && config::exists(&path)? {
            self.check_kept_config(&path)?;
            result.config.status = "kept";
            if let Some(unit) = self.choose_unit(prompter)? {
                result.service = Some(unit.install(false)?);
            }
            return Ok(result);
        }

        let previous = config::read(&path)?;
        if previous.is_some() {
            result.config.status = "kept";
        }
        let mut config =
            Config::parse_for_init(&self.config_home, previous.as_deref().unwrap_or(""))
                .map_err(|error| CliError::Config(path.clone(), error))?;
        let homes = format!(
            "Configuration: {:?}\nRegistry: {:?}\nState: {:?}\nUse these locations?",
            self.config_home, config.registry_home, self.state_home
        );
        if !prompter.confirm("Registry home", &homes)? {
            return Ok(result.cancelled());
        }

        let ephemeral = self.ephemeral_range()?;
        let initial_range = config.policy.lease_range.clone();
        let app_range_was_explicit = config.app_range_is_explicit();
        if !self.choose_ranges(&mut config, ephemeral.as_ref(), prompter)? {
            return Ok(result.cancelled());
        }

        let registry = platform::open_store(&config.registry_home).load()?;
        let choices = self.service_ports(&config, &registry, ephemeral.as_ref())?;
        let Some(port) = self.choose_service_port(&choices, config.service_port, prompter)? else {
            return Ok(result.cancelled());
        };
        let choices = self.service_ports(&config, &registry, ephemeral.as_ref())?;
        let service_port_action = match choices.check(port)? {
            AvailablePort::Claimed { running: true, .. } => {
                "reuse claim, running service keeps serving this port"
            }
            AvailablePort::Claimed { .. } => "reuse claim",
            AvailablePort::Free => "create permanent claim",
        };
        let service_port = Some(port);
        let zone = Self::choose_well_known_zone(&registry, port, prompter)?;
        if let Some(proposal) = &zone
            && proposal.zone.contains(port)
        {
            return Err(ports::zone_refusal(port, &proposal.zone.label));
        }

        let unit = self.choose_unit(prompter)?;
        let enable = unit.is_some()
            && !self.yes
            && prompter.confirm("Enable the service now", enable_service_prompt())?;

        let updated = if config.policy.lease_range != initial_range
            || config.service_port != service_port
            || config.app_range_is_explicit() != app_range_was_explicit
        {
            Some(config::render(&self.config_home, &config, service_port)?)
        } else {
            None
        };
        if let (Some(before), Some(after)) = (&previous, &updated)
            && !prompter.confirm(
                "Replace existing config.toml",
                &config::replacement_preview(&path, before, after),
            )?
        {
            return Ok(result.cancelled());
        }

        let mut summary = format!(
            "Configuration: {} {:?}\nLease range: {}-{}\nService port: {port} ({service_port_action})\n{}: {}\nEnable the service now: {}\n",
            if updated.is_some() { "write" } else { "keep" },
            path,
            config.policy.lease_range.start(),
            config.policy.lease_range.end(),
            service_summary_label(),
            unit.as_ref()
                .map_or_else(|| "skip".into(), |unit| format!("{:?}", unit.path)),
            if enable { "yes" } else { "no" },
        );
        if let Some(notice) = config.app_range_notice() {
            summary.push_str(&notice);
            summary.push('\n');
        }
        if updated.is_some()
            && let Some(running) = choices.running_port()
        {
            summary.push_str(&format!(
                "The running service on port {running} keeps its startup settings until it is restarted.\n"
            ));
        }
        if let Some(proposal) = &zone {
            summary.push_str(&format!(
                "Red zone: add {} (ports {}).\n",
                proposal.zone.label,
                proposal.zone.ports.join(", ")
            ));
        }
        summary.push_str("Apply these settings?");
        if !prompter.confirm("Summary", &summary)? {
            return Ok(result.cancelled());
        }

        self.commit(
            &path,
            previous.as_deref(),
            updated.as_deref(),
            &config,
            RegistryChanges { port, zone },
            &mut result,
        )?;
        if let Some(unit) = unit {
            let mut service = unit.install(false)?;
            if enable {
                service.activate(runner);
            }
            result.service = Some(service);
        }
        Ok(result)
    }

    fn choose_ranges(
        &self,
        config: &mut Config,
        ephemeral: Option<&RangeInclusive<u16>>,
        prompter: &mut dyn Prompter,
    ) -> Result<bool, CliError> {
        let initial = config.resolve_app_range(ephemeral.cloned());
        let mut lease_detail = String::from("Enter an inclusive range as FIRST-LAST.");
        if let Some(range) = ephemeral {
            lease_detail.push_str(&format!(
                " The kernel uses {}-{} for ephemeral ports.",
                range.start(),
                range.end()
            ));
        }
        if let Err(
            error @ ConfigError::NoImplicitAppRange {
                suggestion: None, ..
            },
        ) = &initial
        {
            lease_detail.push_str(&format!("\n{error}"));
        }
        let lease = &config.policy.lease_range;
        let default = format!("{}-{}", lease.start(), lease.end());
        let Some(range) = prompter.ask_text("Lease range", &lease_detail, &default)? else {
            return Ok(false);
        };
        config.policy.lease_range = ports::parse_range(&range, "lease")?;

        // Use compatibility handling for a saved lease range. A newly
        // introduced overlap still receives the usual input validation.
        if (config.app_range_notice().is_some()
            || matches!(initial, Err(ConfigError::NoImplicitAppRange { .. })))
            && let Err(error) = config.resolve_app_range(ephemeral.cloned())
        {
            match error {
                ConfigError::NoImplicitAppRange {
                    suggestion: Some(ref range),
                    ..
                } if !self.yes => {
                    let detail = format!("{error}. Enter an inclusive range as FIRST-LAST.");
                    let default = format!("{}-{}", range.start(), range.end());
                    let Some(range) = prompter.ask_text("App range", &detail, &default)? else {
                        return Ok(false);
                    };
                    config.set_app_range(ports::parse_range(&range, "app")?);
                }
                error => return Err(CliError::InvalidInit(error.to_string())),
            }
        }
        ports::validate_range(&config.policy, ephemeral)?;
        Ok(true)
    }

    fn check_kept_config(&self, path: &Path) -> Result<(), CliError> {
        let legacy = RunningService::read(&self.state_home, &self.config_home, &self.probe)
            .and_then(|service| service.unknown_identity().map(|error| (service, error)));
        let legacy = match legacy {
            Some((service, error)) if service.owns_listeners(&self.probe.report()?) => {
                Some((service, error))
            }
            _ => None,
        };

        let config = config::read(path).and_then(|text| {
            Config::parse_for_init(&self.config_home, text.as_deref().unwrap_or_default())
                .map_err(|error| CliError::Config(path.to_owned(), error))
        });
        let config = match config {
            Ok(config) => config,
            // Keep unreadable or future config unless we need to identify
            // an older running service before installing a unit.
            Err(_) if legacy.is_none() => return Ok(()),
            Err(error) => return Err(error),
        };
        let store = platform::open_store(config.registry_home);
        if let Some((service, error)) = legacy
            && (config.service_port.is_none_or(|port| port == service.port)
                || service.has_claim(&store.load()?))
        {
            return Err(error);
        }
        if let Some(port) = config.service_port {
            ports::check_zone(&store.load()?, port)?;
        }
        Ok(())
    }

    fn choose_well_known_zone(
        registry: &Registry,
        port: u16,
        prompter: &mut dyn Prompter,
    ) -> Result<Option<ZoneResult>, CliError> {
        if registry
            .zone
            .iter()
            .any(|zone| zone.label == WELL_KNOWN_LABEL)
        {
            return Ok(None);
        }
        let zone = Zone {
            label: WELL_KNOWN_LABEL.into(),
            reason: Some("system ports".into()),
            ports: vec![WELL_KNOWN_PORTS.into()],
            enabled: true,
        };
        let conflicts = zone.conflicts(registry);
        let mut detail = format!(
            "Reserve ports {WELL_KNOWN_PORTS} for system use in the {WELL_KNOWN_LABEL} red zone?"
        );
        if !conflicts.is_empty() {
            detail.push_str(
                "\nThese allocations will stay in the registry and appear in drift reporting:",
            );
            for conflict in &conflicts {
                detail.push_str(&format!("\n  {conflict}"));
            }
        }
        if zone.contains(port) {
            detail.push_str(&format!(
                "\nDecline the zone to use your selected service port {port}."
            ));
        }
        let accepted =
            prompter.confirm_with_default("Well-known ports", &detail, conflicts.is_empty())?;
        Ok(accepted.then_some(ZoneResult { zone, conflicts }))
    }

    fn stage_well_known_zone(
        &self,
        registry: &mut Registry,
        proposal: Option<ZoneResult>,
    ) -> Result<Option<ZoneResult>, CliError> {
        let Some(proposal) = proposal else {
            return Ok(None);
        };
        if registry
            .zone
            .iter()
            .any(|zone| zone.label == proposal.zone.label)
        {
            return Ok(None);
        }
        if proposal.zone.conflicts(registry) != proposal.conflicts {
            if self.yes {
                return Ok(None);
            }
            return Err(CliError::InitZoneConflictsChanged);
        }
        registry.zone.push(proposal.zone.clone());
        Ok(Some(proposal))
    }

    fn ephemeral_range(&self) -> Result<EphemeralRange, CliError> {
        (self.read_range)().map_err(CliError::EphemeralRange)
    }

    fn service_ports<'a>(
        &self,
        config: &'a Config,
        registry: &'a Registry,
        ephemeral: Option<&'a RangeInclusive<u16>>,
    ) -> Result<Ports<'a>, CliError> {
        Ports::scan(registry, config, ephemeral, &self.state_home, &self.probe)
    }

    fn choose_service_port(
        &self,
        choices: &Ports<'_>,
        configured: Option<u16>,
        prompter: &mut dyn Prompter,
    ) -> Result<Option<u16>, CliError> {
        let (default, detail) = match choices.suggest(configured) {
            Ok(port) => (
                port.to_string(),
                "Enter a port for the permanent troll serve claim.",
            ),
            Err(CliError::NoServicePort(_)) if !self.yes => (
                String::new(),
                "No automatic suggestion. Enter a port for the permanent troll serve claim.",
            ),
            Err(error) => return Err(error),
        };
        let mut detail = detail.to_owned();
        if let Some(port) = configured
            && let Some(label) = choices.zone_for(port)
        {
            detail.push_str(&format!(
                " The saved service port is unavailable: {}. Choose a replacement.",
                ports::zone_refusal(port, label)
            ));
        }
        if let Some(port) = choices.other_registry_port() {
            detail.push_str(&format!(" {}.", CliError::OtherRegistryServicePort(port)));
        }
        let Some(answer) = prompter.ask_text("Service port", &detail, &default)? else {
            return Ok(None);
        };
        let port = answer.parse().map_err(|_| {
            CliError::InvalidInit("enter a service port from 1 through 65535".into())
        })?;
        Ok(Some(port))
    }

    fn choose_unit(&self, prompter: &mut dyn Prompter) -> Result<Option<Unit>, CliError> {
        let selected = if self.yes {
            self.service
        } else {
            cfg!(any(
                target_os = "linux",
                target_os = "macos",
                target_os = "windows"
            )) && prompter.confirm("Background service", write_service_prompt())?
        };
        if !selected {
            return Ok(None);
        }
        let unit = Unit::for_homes(&self.config_home, &self.state_home)?;
        unit.check()?;
        Ok(Some(unit))
    }

    fn commit(
        &self,
        path: &Path,
        previous: Option<&str>,
        updated: Option<&str>,
        config: &Config,
        changes: RegistryChanges,
        result: &mut InitResult,
    ) -> Result<(), CliError> {
        let _lock = platform::lock_setup_dir(&self.config_home).map_err(|error| {
            CliError::SetupIo(
                "lock the configuration directory",
                self.config_home.clone(),
                error,
            )
        })?;
        if self.yes && config::exists(path)? {
            // Another init or an editor wrote config after preview. --yes is
            // still a keep operation and must not create a different claim.
            self.check_kept_config(path)?;
            result.config.status = "kept";
            return Ok(());
        }
        config::check_unchanged(path, previous)?;

        let ephemeral = self.ephemeral_range()?;
        ports::validate_range(&config.policy, ephemeral.as_ref())?;
        let home = &config.registry_home;
        fs::create_dir_all(home).map_err(|error| CliError::RegistryHome(home.clone(), error))?;
        let (claim, zone) = platform::open_store(home)
            .update(|registry| -> Result<_, CliError> {
                let zone = self.stage_well_known_zone(registry, changes.zone)?;
                let ports = self.service_ports(config, registry, ephemeral.as_ref())?;
                let port = changes.port;
                let claim = match ports.check(port)? {
                    AvailablePort::Claimed { entry, running } => ClaimResult {
                        status: "reused",
                        entry: entry.clone(),
                        running,
                    },
                    AvailablePort::Free => ClaimResult {
                        status: "created",
                        entry: registry
                            .insert_claim(&SystemClock, service_claim_request(port))
                            .map_err(CliError::Operation)?,
                        running: false,
                    },
                };
                // An editor can save while init is waiting for the registry
                // lock. A closure error discards the staged claim and zone.
                config::check_unchanged(path, previous)?;
                Ok((claim, zone))
            })
            .map_err(|error| match error {
                UpdateError::Store(error) => CliError::from(error),
                UpdateError::Operation(error) => error,
            })?;
        if let Some(text) = updated {
            let publish = config::check_unchanged(path, previous)
                .map_err(|error| io::Error::other(error.to_string()))
                .and_then(|()| {
                    platform::write_setup_file(
                        &self.config_home,
                        config::FILE_NAME,
                        text.as_bytes(),
                        previous.is_some(),
                    )
                });
            publish.map_err(|error| {
                config_publication_error(path, home, &claim, zone.as_ref(), error)
            })?;
            result.config.status = "written";
        }
        result.claim = Some(claim);
        result.zone = zone;
        Ok(())
    }
}

fn config_publication_error(
    path: &Path,
    home: &Path,
    claim: &ClaimResult,
    zone: Option<&ZoneResult>,
    error: io::Error,
) -> CliError {
    let port = claim.entry.port;
    let project = &claim.entry.project;
    let mut message = format!(
        "{error}. In registry {home:?}, init {} the claim for port {port} (project {project:?})",
        claim.status
    );
    let mut undo = Vec::new();
    if claim.status == "created" {
        let tag = claim.entry.entry_tag();
        undo.push(format!("`troll release {port} --if-tag {tag}`"));
    }
    if let Some(zone) = zone {
        let label = &zone.zone.label;
        message.push_str(&format!(
            " and added zone {label:?} (ports {})",
            zone.zone.ports.join(", ")
        ));
        let tag = zone.zone.entry_tag();
        undo.push(format!("`troll zone remove {label} --if-tag {tag}`"));
    }
    message.push('.');
    if !undo.is_empty() {
        message.push_str(&format!(
            " To undo these changes, use a valid configuration that points to this registry and run {}.",
            undo.join(" and ")
        ));
    }
    CliError::SetupIo(
        "write the configuration",
        path.to_owned(),
        io::Error::new(error.kind(), message),
    )
}

fn service_claim_request(port: u16) -> ClaimRequest {
    let claimed_by = env::var("TROLL_HOLDER")
        .ok()
        .filter(|value| !value.is_empty())
        .or_else(|| env::var("USER").ok().filter(|value| !value.is_empty()))
        .or_else(|| env::var("USERNAME").ok().filter(|value| !value.is_empty()))
        .unwrap_or_else(|| "unknown".into());
    ClaimRequest {
        port,
        bind: None,
        project: ports::PROJECT.into(),
        service: ports::SERVICE.into(),
        claimed_by,
        role: Role::Service,
        container: None,
        used_by: None,
        web: None,
        component: None,
    }
}

#[derive(Serialize)]
struct InitResult {
    schema: u32,
    cancelled: bool,
    config: ConfigResult,
    claim: Option<ClaimResult>,
    zone: Option<ZoneResult>,
    service: Option<ServiceResult>,
}

#[derive(Serialize)]
struct ConfigResult {
    path: String,
    status: &'static str,
}

#[derive(Serialize)]
struct ClaimResult {
    status: &'static str,
    entry: Permanent,
    #[serde(skip)]
    running: bool,
}

impl InitResult {
    fn new(path: &Path) -> Self {
        Self {
            schema: output::SCHEMA,
            cancelled: false,
            config: ConfigResult {
                path: path.to_string_lossy().into_owned(),
                status: "skipped",
            },
            claim: None,
            zone: None,
            service: None,
        }
    }

    fn cancelled(mut self) -> Self {
        self.cancelled = true;
        self
    }

    fn write_human(&self, out: &mut dyn Write) -> Result<(), CliError> {
        if self.cancelled {
            writeln!(out, "Setup cancelled.")?;
        }
        writeln!(
            out,
            "Configuration {:?}: {}.",
            self.config.path, self.config.status
        )?;
        if let Some(claim) = &self.claim {
            writeln!(
                out,
                "Service port {}: claim {}.",
                claim.entry.port, claim.status
            )?;
            if claim.running {
                writeln!(
                    out,
                    "The running service keeps serving port {}.",
                    claim.entry.port
                )?;
            }
        }
        if let Some(zone) = &self.zone {
            writeln!(
                out,
                "Red zone {}: added for ports {}.",
                zone.zone.label,
                zone.zone.ports.join(", ")
            )?;
            for conflict in &zone.conflicts {
                writeln!(out, "  {conflict}")?;
            }
        }
        if let Some(service) = &self.service {
            service.write_human(out)?;
        }
        Ok(())
    }
}

fn write_service_prompt() -> &'static str {
    if cfg!(target_os = "macos") {
        "Write a launchd user agent plist for troll serve?"
    } else if cfg!(target_os = "windows") {
        "Write a Windows Task Scheduler definition for troll serve?"
    } else {
        "Write a systemd user unit for troll serve?"
    }
}

fn enable_service_prompt() -> &'static str {
    if cfg!(target_os = "macos") {
        "Bootstrap and start io.troll.serve with launchctl after writing the configuration?"
    } else if cfg!(target_os = "windows") {
        "Register and start the troll-serve scheduled task after writing the configuration?"
    } else {
        "Reload systemd and enable and start troll.service after writing the configuration?"
    }
}

fn service_summary_label() -> &'static str {
    if cfg!(target_os = "macos") {
        "Launchd user agent"
    } else if cfg!(target_os = "windows") {
        "Scheduled task XML"
    } else {
        "Systemd user unit"
    }
}