Skip to content

fix(shutdown): handle SIGTERM at tracker boundary - #2133

Merged
josecelano merged 30 commits into
torrust:developfrom
josecelano:2132-add-sigterm-to-main
Sep 3, 2026
Merged

josecelano merged 30 commits into
torrust:developfrom
josecelano:2132-add-sigterm-to-main

Conversation

@josecelano

@josecelano josecelano commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Add Unix SIGTERM handling at the tracker executable boundary. SIGINT and SIGTERM select the shutdown source, emit distinct observable logs, and execute the existing JobManager cancellation and waiting sequence once.

Details

  • Extract wait_for_shutdown_signal() so platform-specific signal registration and source selection are isolated from the executable lifecycle.
  • Retain Ctrl-C support on non-Unix builds and explicitly fail if Tokio cannot install the Ctrl-C handler rather than treating an error as SIGINT.
  • Explicitly reject an unexpectedly closed SIGTERM signal stream rather than reporting it as SIGTERM.
  • Add Unix-only native executable-boundary coverage that launches the Cargo-built tracker binary, waits for health readiness and signal-handler registration, and sends SIGTERM or SIGINT to its exact child PID.
  • Add a reusable lifecycle fixture with isolated port-zero configuration, child-only environment configuration, concurrent output draining, deadline-bounded health polling, graceful shutdown, and force-kill/reap panic cleanup.
  • Refactor the fixture incrementally into workspace, output-capture, and health-check client collaborators; document the decision not to add a separate ReadinessProbe.
  • Record the implementation retrospective and standardize the repository workflow for conditional issue-local retrospectives.
  • Move the SI-1 specification and verification evidence to docs/issues/open/2132-add-sigterm-to-main/.

Closes #2132

Validation

  • cargo build --release
  • cargo test --test lifecycle-signals
  • cargo test
  • linter all
  • Mandatory pre-commit checks on every signed commit
  • Pre-push checks: nightly format/check/docs and full test suite
  • Manual direct release-binary verification for default SIGTERM, explicit SIGTERM, SIGINT, and SIGKILL control behavior

Known transitional behavior

Legacy periodic jobs retain their existing sequential per-job timeout behavior. The documented aggregate shutdown-result and deadline policy remain owned by SI-20. The native fixture's output assertions intentionally require message presence only; stdout and stderr are drained concurrently into one retained buffer and their cross-stream ordering is not asserted.

@codecov

codecov Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.96774% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.26%. Comparing base (c956a44) to head (b0810e3).

Files with missing lines Patch % Lines
src/main.rs 70.96% 7 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2133      +/-   ##
===========================================
+ Coverage    84.04%   84.26%   +0.21%     
===========================================
  Files          351      351              
  Lines        27988    28008      +20     
  Branches     27988    28008      +20     
===========================================
+ Hits         23523    23601      +78     
+ Misses        4070     4006      -64     
- Partials       395      401       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

src/main.rs currently ignores the Result from tokio::signal::ctrl_c() inside tokio::select!, which can cause an error to be treated as a SIGINT and trigger an unintended shutdown.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds Unix SIGTERM handling at the tracker executable boundary so the existing coordinated shutdown sequence runs for both SIGINT and SIGTERM, with distinct observable logs, and updates the related issue spec/evidence docs accordingly.

Changes:

  • Add Unix-only SIGTERM listener and select SIGINT vs SIGTERM to label shutdown logs in src/main.rs.
  • Update SI-1/#2132 issue spec and verification evidence to reflect completed implementation and manual checks.
  • Update the shutdown EPIC (#1488) to link to the new open issue spec location.
File summaries
File Description
src/main.rs Adds SIGTERM handling (Unix) and shutdown-source logging before running the existing JobManager cancellation/wait sequence.
docs/issues/open/2132-add-sigterm-to-main/verification.md Records post-implementation manual verification evidence and checklist updates.
docs/issues/open/2132-add-sigterm-to-main/ISSUE.md Promotes draft to open issue #2132 and updates acceptance criteria/status narrative.
docs/issues/open/1488-overhaul-tracker-shutdown/ISSUE.md Updates the EPIC table link to reference the new SI-1 issue spec path.
Review details

Suppressed comments (3)

docs/issues/open/2132-add-sigterm-to-main/ISSUE.md:10

  • Frontmatter last-updated-utc is date-only, but the repo template requires UTC timestamp precision (YYYY-MM-DD HH:MM). Update this field to include the time in UTC to match the documented convention.
    docs/issues/open/2132-add-sigterm-to-main/verification.md:161
  • The verification environment captures a personal machine hostname (josecelano-desktop) in the OS line. To avoid leaking identifiable workstation details in repo docs, redact the hostname while keeping kernel/version info.
    docs/issues/open/2132-add-sigterm-to-main/verification.md:156
  • Verification notes say the SIGTERM fix was "uncommitted" and the commit hash line includes a "working tree contains" qualifier, which reduces reproducibility for anyone trying to re-run the evidence later. Prefer re-running verification on a clean working tree and recording the exact commit SHA that contains the change.
  • Files reviewed: 4/4 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/main.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

src/main.rs currently treats sigterm.recv() returning None as a SIGTERM, which can misreport the shutdown source and trigger shutdown unexpectedly if the signal stream closes.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (2)

src/main.rs:59

  • Same as the outer select!: sigterm.recv() yields Option<()>. If it ever returns None, the current arm would still select and report SIGTERM. Handle None explicitly to avoid misreporting the shutdown source.
                _ = sigterm.recv() => "SIGTERM",

docs/issues/open/2132-add-sigterm-to-main/ISSUE.md:10

  • last-updated-utc should include a UTC time (YYYY-MM-DD HH:MM) per the issue spec template; this entry is date-only, which makes updates harder to track consistently.
  • Files reviewed: 12/13 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/main.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new tests/lifecycle/native_tracker.rs introduces const fn methods that mutate or use non-const operations and are likely to break compilation under the project MSRV.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (4)

Previously missed (1) — in code that hasn't changed since the last review.

docs/issues/open/AGENTS.md:114

  • The summary table mixes the legacy standalone EPIC example (1978-configuration-overhaul-epic.md above) with a folder-style EPIC example here, but the table label EPIC spec doesn’t clarify which format it refers to. This can mislead readers into thinking EPIC specs are always folder-based even when documenting legacy single-file EPICs.

tests/lifecycle/native_tracker.rs:349

  • child_ref is declared as const fn but calls runtime-only methods (as_ref() + expect(...)). This is very likely to be rejected by const-eval rules and can break compilation; use a normal fn.
    const fn child_ref(&self) -> &Child {

tests/lifecycle/native_tracker.rs:353

  • child_mut is declared as const fn but uses Option::as_mut() + expect(...), which is unlikely to be const-evaluable and can break compilation. Use a normal fn.
    const fn child_mut(&mut self) -> &mut Child {

tests/lifecycle/native_tracker.rs:357

  • output_ref is declared as const fn but uses Option::as_ref() + expect(...), which is unlikely to be const-evaluable and can break compilation. Use a normal fn.
    const fn output_ref(&self) -> &TrackerOutputCapture {
  • Files reviewed: 29/30 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread tests/lifecycle/native_tracker.rs Resolved
@josecelano
josecelano marked this pull request as ready for review September 3, 2026 15:39
@josecelano
josecelano requested a review from a team as a code owner September 3, 2026 15:39
@josecelano
josecelano requested a lite review from Copilot September 3, 2026 15:40

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

There are a couple of concrete documentation/maintainability issues in changed files (notably a contradictory naming “Summary Table” and an unnecessary const fn) that should be corrected before merging.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

tests/lifecycle/native_tracker.rs:257

  • take_drop_cleanup_observer is declared as a const fn, but it performs normal runtime state mutation (Option::take()) and returns a non-const type. Marking it const doesn't provide a benefit here and can unnecessarily constrain future changes to this helper.
    /// Returns an observer for the signal that terminated the reaped drop-path child.
    pub const fn take_drop_cleanup_observer(&mut self) -> oneshot::Receiver<Result<i32, String>> {
        self.drop_cleanup_observer
            .take()
            .expect("drop cleanup observer must be taken at most once")
    }
  • Files reviewed: 29/30 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread docs/issues/open/AGENTS.md Resolved
@josecelano

Copy link
Copy Markdown
Member Author

ACK b0810e3

@josecelano
josecelano merged commit d54d418 into torrust:develop Sep 3, 2026
17 of 18 checks passed

@da2ce7 da2ce7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a post-merge review of #2133 as it stands at e170b9620 on the default branch.

What still runs: the signal wait this change added to src/main.rs now lives in src/app.rs as wait_for_shutdown_signal (moved by 989edcc with its log target pinned, otherwise unchanged) and is called by run_until_shutdown_signal, which main enters once app::start_with_explicit_config_toml_path has returned. SIGINT and SIGTERM still select the logged shutdown source and run begin_shutdown and wait_for_all once. The executable-boundary tests in tests/lifecycle/signals.rs are live and extended, and the native fixture now lives under tests/common/native_tracker/. Two gaps in the change as merged were closed later and are history: the fixture's shutdown accepted any exit status, so the SIGINT test did not check a graceful exit, until ccc7a2b; and the success line and the exit code ignored the shutdown outcome until 191158c.

[Minor] The handlers are installed only after the whole startup has finished, so SIGTERM is still unhandled while the trackers are already serving. src/main.rs:30 calls run_until_shutdown_signal only after startup returns, and src/app.rs:198-205 registers SIGTERM and then SIGINT at that point; by then start_jobs_with_manager has bound and spawned the UDP and HTTP trackers (src/app.rs:326-327) and goes on to await the REST API and the health check API (src/app.rs:332-333). A SIGTERM from a supervisor in that span, for example a docker stop or a rolling restart that lands just after the start, takes the default action: the process is killed by signal 15 (reported as 143) instead of exiting with 0 or 1, no shutdown line is logged, in-flight HTTP requests are cut, and with persistent completed statistics enabled the events already published to their listener are lost. The same ordering means a failed registration panics (src/app.rs:201, src/app.rs:206) with every listener bound, skipping begin_shutdown. Smallest fix: on Unix, create both streams with tokio::signal::unix::signal(SignalKind::interrupt()) and signal(SignalKind::terminate()) in main before startup, report the io::Error as a startup failure, and pass the streams to run_until_shutdown_signal. Because signal() registers when it is called, the biased select! with its std::future::ready branch and the pinned ctrl_c future (src/app.rs:186-228) are then unnecessary, and the readiness marker can be logged straight after both registrations. A signal that arrives during startup is then held and acted on as soon as startup returns.

[Nit] A second SIGINT or SIGTERM during the drain is discarded without a trace. wait_for_shutdown_signal drops both listeners when it returns (src/app.rs:197-228), but the Tokio signal driver keeps its process-wide handlers for both signals installed for the rest of the process, so nothing restores the default action and nothing listens. With application.shutdown.deadline_in_secs at its maximum of 3600 and a component that does not stop, a second Ctrl-C in a terminal has no visible effect for up to an hour; only SIGQUIT, SIGKILL or the deadline end the process. Smallest fix: keep the streams in run_until_shutdown_signal and race jobs.wait_for_all(...) (src/app.rs:162) against a further signal, logging that shutdown is already in progress and how to force it; whether a second signal should also force an immediate incomplete exit is a separate choice.

[Nit] The fixture's drop path does not reap on the panic path it was written for. The comment at tests/common/native_tracker/mod.rs:403-404 says a panicking test's child is killed and reaped in the active runtime, but #[tokio::test] runs a current-thread runtime that is shut down as soon as the panic leaves block_on, so the cleanup task spawned at tests/common/native_tracker/mod.rs:405 is dropped before it is first polled: the child is killed only by kill_on_drop (tests/common/native_tracker/command.rs:275), the fixture does not wait for it, the drop observer never receives a result, and the temporary workspace can be removed before the child has exited. The test at tests/lifecycle/signals.rs:155 drops the fixture without panicking, so its runtime keeps running and the task completes; the panic path itself is not covered. Smallest fix: call child.start_kill() synchronously in drop before spawning the reaper, and say in the comment that reaping is best-effort while the runtime shuts down, as tests/common/native_tracker/command.rs:273-274 already says for the no-runtime case.

[Nit] The tokio features this change added for the fixture went into the shipped crate's normal dependencies. Cargo.toml:113 enables io-util and process for torrust-tracker, but nothing under src/ uses tokio::io or tokio::process; only tests/common/native_tracker/ does. Every build of the library and the release binary therefore compiles both modules, and so would any dependant of the library crate once it is published. Smallest fix: move io-util and process to the existing tokio entry under [dev-dependencies] at Cargo.toml:132.

Checked and found sound: the biased first poll registers SIGINT after SIGTERM and before the readiness marker is logged, so the fixture's wait on that marker does not race registration; the recv() future dropped between the two select!s loses no signal, because the stream keeps a delivered signal pending; a closed SIGTERM stream or a failed Ctrl-C registration fails loudly instead of being reported as a signal; the tests signal an unreaped child by its own PID, so the PID cannot have been reused; the SIGTERM test's expected job log still matches src/bootstrap/jobs/manager.rs:729; each child gets only a CLI-selected, port-zero configuration on 127.0.0.1 with the inherited configuration variables removed; and the nix dev-dependency is limited to its signal feature.

This branch was previously deployed

1 inactive deployment
coverage — b0810e3f Deployed Sep 3, 2026 by josecelano via Generate Coverage Report #1904
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add SIGTERM handling at tracker signal boundary

3 participants