Skip to content

Graceful shutdown for event listeners - #1587

Merged
josecelano merged 1 commit into
torrust:developfrom
josecelano:1405-overhaul-stats-implement-a-graceful-shutdown-for-broadcast-channels
Jun 17, 2025
Merged

josecelano merged 1 commit into
torrust:developfrom
josecelano:1405-overhaul-stats-implement-a-graceful-shutdown-for-broadcast-channels

Conversation

@josecelano

Copy link
Copy Markdown
Member

Events listeners listen for the cancellation request instead of directly for the CRTR+c signal. This will allow implementing centralized policies for shutdown and alternative conditions.

In the future, we should implement the same for all tasks, including:

  • HTTP servers using axum: torrust_server_lib::signals::global_shutdown_signal
  • Job to update metrics: torrust_tracker_swarm_coordination_registry::statistics::activity_metrics_updater::start_job
  • Torrent cleanup jonb: torrust_tracker_lib::bootstrap::jobs::torrent_cleanup::start_job

Events listeners listen for the cancelation request instead of directly
for the CRTR+c signal. This will allow implementing centralized
policies for shutdown and alternative conditions.
@josecelano

Copy link
Copy Markdown
Member Author

ACK d2e75e3

@codecov

codecov Bot commented Jun 17, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 80.29197% with 27 lines in your changes missing coverage. Please review.

Project coverage is 84.60%. Comparing base (1ad19e7) to head (d2e75e3).
Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
...dination-registry/src/statistics/event/listener.rs 61.53% 4 Missing and 1 partial ⚠️
...ages/tracker-core/src/statistics/event/listener.rs 44.44% 4 Missing and 1 partial ⚠️
...http-tracker-core/src/statistics/event/listener.rs 72.72% 2 Missing and 1 partial ⚠️
.../udp-tracker-core/src/statistics/event/listener.rs 72.72% 3 Missing ⚠️
...s/udp-tracker-server/src/banning/event/listener.rs 75.00% 3 Missing ⚠️
...dp-tracker-server/src/statistics/event/listener.rs 72.72% 3 Missing ⚠️
src/bootstrap/jobs/manager.rs 70.00% 3 Missing ⚠️
src/main.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1587      +/-   ##
===========================================
+ Coverage    84.59%   84.60%   +0.01%     
===========================================
  Files          287      287              
  Lines        21382    21447      +65     
  Branches     21382    21447      +65     
===========================================
+ Hits         18088    18146      +58     
- Misses        2979     2985       +6     
- Partials       315      316       +1     

☔ View full report in Codecov by Sentry.
📢 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.

@josecelano josecelano self-assigned this Jun 17, 2025
@josecelano josecelano added the Code Cleanup / Refactoring Tidying and Making Neat label Jun 17, 2025
@josecelano

Copy link
Copy Markdown
Member Author

I've opened a new issue to do the same for other jobs not related to events.

@josecelano
josecelano merged commit b254ffd into torrust:develop Jun 17, 2025

@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 #1587 as its change stands at a94c3ced8 on the default branch.

What still runs from it: the statistics and banning event listeners in packages/{tracker-core,swarm-coordination-registry,http-core,udp-core,udp-server} take a CancellationToken and select on it, biased, ahead of their receiver instead of reading Ctrl-C themselves, and the starters in src/bootstrap/jobs/ pass the token through; the process signal is now read once, at src/app.rs:197, and JobManager::cancel fires the tokens. Most of the rest was rebuilt later: every component gets its own reservation token (c4d7c91, 47f7969), producers stop before the listeners of the buses they publish on (59c9ce8), and a cancelled listener drains its queue within event_listener_drain_in_secs (8726ecf and the listener commits after it). Those commits also closed the gaps the change had when it merged: a cancelled listener dropped the events still queued for it; main cancelled the listeners while the HTTP and UDP servers, which still stopped on their own Ctrl-C, could publish; the HTTP and UDP test environments and packages/tracker-core/tests/common/test_env.rs never cancelled the token they created; the profiling binary waited for its jobs without cancelling them (a08c24d); and packages/events/src/shutdown.rs was added empty and undeclared.

[Minor] src/console/profiling.rs:229 still waits with the 10 s deadline that the merged main used, while src/app.rs:162 now uses application.shutdown.deadline_in_secs (25 s by default), and configuration validation only guarantees that the slowest server drain plus event_listener_drain_in_secs fits within that configured deadline. With the default budgets a UDP instance may use its 5 s request drain before its listeners are asked to stop, and the listeners then have 5 s to admit queued events, so a slow shutdown under load, which is what this binary is run for, reaches 10 s and wait_for_all aborts the listeners with their queues partly unread. wait_for_shutdown (src/console/profiling.rs:218) discards the outcomes, and run prints "Torrust successfully shutdown." at src/console/profiling.rs:213 and returns Ok(()) after that aborted shutdown exactly as after a clean one; with a configuration that enables persistent_torrent_completed_stat, the download increments still queued at that moment are lost behind a success message. Smallest fix: keep the container returned at src/console/profiling.rs:202, pass application_config.shutdown.deadline() to wait_for_all, and return an error naming incomplete_components(&outcomes) when shutdown_exit_code(&outcomes) is not EXIT_CODE_GRACEFUL_SHUTDOWN, as run_until_shutdown_signal does.

[Nit] The receive, cancel and drain loop that this change first threaded the token through now exists as seven near-identical copies in six files: packages/http-core/src/statistics/event/listener.rs:71, packages/udp-core/src/statistics/event/listener.rs:68, packages/udp-server/src/statistics/event/listener.rs:69, packages/udp-server/src/banning/event/listener.rs:81, packages/swarm-coordination-registry/src/statistics/event/listener.rs:53, and packages/tracker-core/src/statistics/event/listener.rs:101 and :129. Adding the drain took six commits (6a6710e, 51bf40e, 1abfc39, 59170e0, fadf2df, 4145958), and any later change to the cancellation protocol has to land in every copy, where a missed one is a listener that loses events at shutdown. packages/events/src/drain.rs:82 already holds drain and log_drain_report!; one generic loop beside it, given the receiver, the token, the drain timeout, the event handler and the listener's response to a closed or lagged receiver, would state the protocol once.

Checked and found sound: in each listener an event already taken is handled before the cancel branch is polled, and the cancel branch drains with try_recv and returns Cancelled; every listener is reserved and subscribed before any producer starts (src/app.rs:313); the HTTP and UDP instances and torrent cleanup are declared as producers of every bus they publish on, and the REST API, activity-metrics and ban-cleanup components publish on none of them; UDP request processors are joined or aborted before a UDP instance completes; a failed startup cancels and joins the components it started (src/app.rs:297); and the HTTP, UDP and tracker-core test environments now cancel and join their listeners.

This branch was previously deployed

1 inactive deployment
coverage — d2e75e3f Deployed Jun 17, 2025 by josecelano
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Code Cleanup / Refactoring Tidying and Making Neat

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Overhaul stats: Implement a graceful shutdown for broadcast channels

2 participants