LCOV - code coverage report
Current view: top level - pageserver/src - task_mgr.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 65.4 % 260 170
Test Date: 2024-06-25 13:20:00 Functions: 20.4 % 103 21

            Line data    Source code
       1              : //!
       2              : //! This module provides centralized handling of tokio tasks in the Page Server.
       3              : //!
       4              : //! We provide a few basic facilities:
       5              : //! - A global registry of tasks that lists what kind of tasks they are, and
       6              : //!   which tenant or timeline they are working on
       7              : //!
       8              : //! - The ability to request a task to shut down.
       9              : //!
      10              : //!
      11              : //! # How it works?
      12              : //!
      13              : //! There is a global hashmap of all the tasks (`TASKS`). Whenever a new
      14              : //! task is spawned, a PageServerTask entry is added there, and when a
      15              : //! task dies, it removes itself from the hashmap. If you want to kill a
      16              : //! task, you can scan the hashmap to find it.
      17              : //!
      18              : //! # Task shutdown
      19              : //!
      20              : //! To kill a task, we rely on co-operation from the victim. Each task is
      21              : //! expected to periodically call the `is_shutdown_requested()` function, and
      22              : //! if it returns true, exit gracefully. In addition to that, when waiting for
      23              : //! the network or other long-running operation, you can use
      24              : //! `shutdown_watcher()` function to get a Future that will become ready if
      25              : //! the current task has been requested to shut down. You can use that with
      26              : //! Tokio select!().
      27              : //!
      28              : //! TODO: This would be a good place to also handle panics in a somewhat sane way.
      29              : //! Depending on what task panics, we might want to kill the whole server, or
      30              : //! only a single tenant or timeline.
      31              : //!
      32              : 
      33              : use std::collections::HashMap;
      34              : use std::fmt;
      35              : use std::future::Future;
      36              : use std::num::NonZeroUsize;
      37              : use std::panic::AssertUnwindSafe;
      38              : use std::str::FromStr;
      39              : use std::sync::atomic::{AtomicU64, Ordering};
      40              : use std::sync::{Arc, Mutex};
      41              : 
      42              : use futures::FutureExt;
      43              : use pageserver_api::shard::TenantShardId;
      44              : use tokio::task::JoinHandle;
      45              : use tokio::task_local;
      46              : use tokio_util::sync::CancellationToken;
      47              : 
      48              : use tracing::{debug, error, info, warn};
      49              : 
      50              : use once_cell::sync::Lazy;
      51              : 
      52              : use utils::env;
      53              : use utils::id::TimelineId;
      54              : 
      55              : use crate::metrics::set_tokio_runtime_setup;
      56              : 
      57              : //
      58              : // There are four runtimes:
      59              : //
      60              : // Compute request runtime
      61              : //  - used to handle connections from compute nodes. Any tasks related to satisfying
      62              : //    GetPage requests, base backups, import, and other such compute node operations
      63              : //    are handled by the Compute request runtime
      64              : //  - page_service.rs
      65              : //  - this includes layer downloads from remote storage, if a layer is needed to
      66              : //    satisfy a GetPage request
      67              : //
      68              : // Management request runtime
      69              : //  - used to handle HTTP API requests
      70              : //
      71              : // WAL receiver runtime:
      72              : //  - used to handle WAL receiver connections.
      73              : //  - and to receiver updates from storage_broker
      74              : //
      75              : // Background runtime
      76              : //  - layer flushing
      77              : //  - garbage collection
      78              : //  - compaction
      79              : //  - remote storage uploads
      80              : //  - initial tenant loading
      81              : //
      82              : // Everything runs in a tokio task. If you spawn new tasks, spawn it using the correct
      83              : // runtime.
      84              : //
      85              : // There might be situations when one task needs to wait for a task running in another
      86              : // Runtime to finish. For example, if a background operation needs a layer from remote
      87              : // storage, it will start to download it. If a background operation needs a remote layer,
      88              : // and the download was already initiated by a GetPage request, the background task
      89              : // will wait for the download - running in the Page server runtime - to finish.
      90              : // Another example: the initial tenant loading tasks are launched in the background ops
      91              : // runtime. If a GetPage request comes in before the load of a tenant has finished, the
      92              : // GetPage request will wait for the tenant load to finish.
      93              : //
      94              : // The core Timeline code is synchronous, and uses a bunch of std Mutexes and RWLocks to
      95              : // protect data structures. Let's keep it that way. Synchronous code is easier to debug
      96              : // and analyze, and there's a lot of hairy, low-level, performance critical code there.
      97              : //
      98              : // It's nice to have different runtimes, so that you can quickly eyeball how much CPU
      99              : // time each class of operations is taking, with 'top -H' or similar.
     100              : //
     101              : // It's also good to avoid hogging all threads that would be needed to process
     102              : // other operations, if the upload tasks e.g. get blocked on locks. It shouldn't
     103              : // happen, but still.
     104              : //
     105              : 
     106          135 : pub(crate) static TOKIO_WORKER_THREADS: Lazy<NonZeroUsize> = Lazy::new(|| {
     107          135 :     // replicates tokio-1.28.1::loom::sys::num_cpus which is not available publicly
     108          135 :     // tokio would had already panicked for parsing errors or NotUnicode
     109          135 :     //
     110          135 :     // this will be wrong if any of the runtimes gets their worker threads configured to something
     111          135 :     // else, but that has not been needed in a long time.
     112          135 :     NonZeroUsize::new(
     113          135 :         std::env::var("TOKIO_WORKER_THREADS")
     114          135 :             .map(|s| s.parse::<usize>().unwrap())
     115          135 :             .unwrap_or_else(|_e| usize::max(2, num_cpus::get())),
     116          135 :     )
     117          135 :     .expect("the max() ensures that this is not zero")
     118          135 : });
     119              : 
     120              : enum TokioRuntimeMode {
     121              :     SingleThreaded,
     122              :     MultiThreaded { num_workers: NonZeroUsize },
     123              : }
     124              : 
     125              : impl FromStr for TokioRuntimeMode {
     126              :     type Err = String;
     127              : 
     128            0 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
     129            0 :         match s {
     130            0 :             "current_thread" => Ok(TokioRuntimeMode::SingleThreaded),
     131            0 :             s => match s.strip_prefix("multi_thread:") {
     132            0 :                 Some("default") => Ok(TokioRuntimeMode::MultiThreaded {
     133            0 :                     num_workers: *TOKIO_WORKER_THREADS,
     134            0 :                 }),
     135            0 :                 Some(suffix) => {
     136            0 :                     let num_workers = suffix.parse::<NonZeroUsize>().map_err(|e| {
     137            0 :                         format!(
     138            0 :                             "invalid number of multi-threaded runtime workers ({suffix:?}): {e}",
     139            0 :                         )
     140            0 :                     })?;
     141            0 :                     Ok(TokioRuntimeMode::MultiThreaded { num_workers })
     142              :                 }
     143            0 :                 None => Err(format!("invalid runtime config: {s:?}")),
     144              :             },
     145              :         }
     146            0 :     }
     147              : }
     148              : 
     149          135 : static ONE_RUNTIME: Lazy<Option<tokio::runtime::Runtime>> = Lazy::new(|| {
     150          135 :     let thread_name = "pageserver-tokio";
     151          135 :     let Some(mode) = env::var("NEON_PAGESERVER_USE_ONE_RUNTIME") else {
     152              :         // If the env var is not set, leave this static as None.
     153          135 :         set_tokio_runtime_setup(
     154          135 :             "multiple-runtimes",
     155          135 :             NUM_MULTIPLE_RUNTIMES
     156          135 :                 .checked_mul(*TOKIO_WORKER_THREADS)
     157          135 :                 .unwrap(),
     158          135 :         );
     159          135 :         return None;
     160              :     };
     161            0 :     Some(match mode {
     162              :         TokioRuntimeMode::SingleThreaded => {
     163            0 :             set_tokio_runtime_setup("one-runtime-single-threaded", NonZeroUsize::new(1).unwrap());
     164            0 :             tokio::runtime::Builder::new_current_thread()
     165            0 :                 .thread_name(thread_name)
     166            0 :                 .enable_all()
     167            0 :                 .build()
     168            0 :                 .expect("failed to create one single runtime")
     169              :         }
     170            0 :         TokioRuntimeMode::MultiThreaded { num_workers } => {
     171            0 :             set_tokio_runtime_setup("one-runtime-multi-threaded", num_workers);
     172            0 :             tokio::runtime::Builder::new_multi_thread()
     173            0 :                 .thread_name(thread_name)
     174            0 :                 .enable_all()
     175            0 :                 .worker_threads(num_workers.get())
     176            0 :                 .build()
     177            0 :                 .expect("failed to create one multi-threaded runtime")
     178              :         }
     179              :     })
     180          135 : });
     181              : 
     182              : /// Declare a lazy static variable named `$varname` that will resolve
     183              : /// to a tokio runtime handle. If the env var `NEON_PAGESERVER_USE_ONE_RUNTIME`
     184              : /// is set, this will resolve to `ONE_RUNTIME`. Otherwise, the macro invocation
     185              : /// declares a separate runtime and the lazy static variable `$varname`
     186              : /// will resolve to that separate runtime.
     187              : ///
     188              : /// The result is is that `$varname.spawn()` will use `ONE_RUNTIME` if
     189              : /// `NEON_PAGESERVER_USE_ONE_RUNTIME` is set, and will use the separate runtime
     190              : /// otherwise.
     191              : macro_rules! pageserver_runtime {
     192              :     ($varname:ident, $name:literal) => {
     193          145 :         pub static $varname: Lazy<&'static tokio::runtime::Runtime> = Lazy::new(|| {
     194          145 :             if let Some(runtime) = &*ONE_RUNTIME {
     195            0 :                 return runtime;
     196          145 :             }
     197          145 :             static RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
     198          145 :                 tokio::runtime::Builder::new_multi_thread()
     199          145 :                     .thread_name($name)
     200          145 :                     .worker_threads(TOKIO_WORKER_THREADS.get())
     201          145 :                     .enable_all()
     202          145 :                     .build()
     203          145 :                     .expect(std::concat!("Failed to create runtime ", $name))
     204          145 :             });
     205          145 :             &*RUNTIME
     206          145 :         });
     207              :     };
     208              : }
     209              : 
     210              : pageserver_runtime!(COMPUTE_REQUEST_RUNTIME, "compute request worker");
     211              : pageserver_runtime!(MGMT_REQUEST_RUNTIME, "mgmt request worker");
     212              : pageserver_runtime!(WALRECEIVER_RUNTIME, "walreceiver worker");
     213              : pageserver_runtime!(BACKGROUND_RUNTIME, "background op worker");
     214              : // Bump this number when adding a new pageserver_runtime!
     215              : // SAFETY: it's obviously correct
     216              : const NUM_MULTIPLE_RUNTIMES: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(4) };
     217              : 
     218              : #[derive(Debug, Clone, Copy)]
     219              : pub struct PageserverTaskId(u64);
     220              : 
     221              : impl fmt::Display for PageserverTaskId {
     222            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     223            0 :         self.0.fmt(f)
     224            0 :     }
     225              : }
     226              : 
     227              : /// Each task that we track is associated with a "task ID". It's just an
     228              : /// increasing number that we assign. Note that it is different from tokio::task::Id.
     229              : static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
     230              : 
     231              : /// Global registry of tasks
     232              : static TASKS: Lazy<Mutex<HashMap<u64, Arc<PageServerTask>>>> =
     233          141 :     Lazy::new(|| Mutex::new(HashMap::new()));
     234              : 
     235              : task_local! {
     236              :     // This is a cancellation token which will be cancelled when a task needs to shut down. The
     237              :     // root token is kept in the global registry, so that anyone can send the signal to request
     238              :     // task shutdown.
     239              :     static SHUTDOWN_TOKEN: CancellationToken;
     240              : 
     241              :     // Each task holds reference to its own PageServerTask here.
     242              :     static CURRENT_TASK: Arc<PageServerTask>;
     243              : }
     244              : 
     245              : ///
     246              : /// There are many kinds of tasks in the system. Some are associated with a particular
     247              : /// tenant or timeline, while others are global.
     248              : ///
     249              : /// Note that we don't try to limit how many task of a certain kind can be running
     250              : /// at the same time.
     251              : ///
     252              : #[derive(
     253              :     Debug,
     254              :     // NB: enumset::EnumSetType derives PartialEq, Eq, Clone, Copy
     255            0 :     enumset::EnumSetType,
     256              :     enum_map::Enum,
     257              :     serde::Serialize,
     258            0 :     serde::Deserialize,
     259         2426 :     strum_macros::IntoStaticStr,
     260            0 :     strum_macros::EnumString,
     261              : )]
     262              : pub enum TaskKind {
     263              :     // Pageserver startup, i.e., `main`
     264              :     Startup,
     265              : 
     266              :     // libpq listener task. It just accepts connection and spawns a
     267              :     // PageRequestHandler task for each connection.
     268              :     LibpqEndpointListener,
     269              : 
     270              :     // HTTP endpoint listener.
     271              :     HttpEndpointListener,
     272              : 
     273              :     // Task that handles a single connection. A PageRequestHandler task
     274              :     // starts detached from any particular tenant or timeline, but it can be
     275              :     // associated with one later, after receiving a command from the client.
     276              :     PageRequestHandler,
     277              : 
     278              :     /// Manages the WAL receiver connection for one timeline.
     279              :     /// It subscribes to events from storage_broker and decides which safekeeper to connect to.
     280              :     /// Once the decision has been made, it establishes the connection using the `tokio-postgres` library.
     281              :     /// There is at most one connection at any given time.
     282              :     ///
     283              :     /// That `tokio-postgres` library represents a connection as two objects: a `Client` and a `Connection`.
     284              :     /// The `Client` object is what library users use to make requests & get responses.
     285              :     /// Internally, `Client` hands over requests to the `Connection` object.
     286              :     /// The `Connection` object is responsible for speaking the wire protocol.
     287              :     ///
     288              :     /// Walreceiver uses a legacy abstraction called `TaskHandle` to represent the activity of establishing and handling a connection.
     289              :     /// The `WalReceiverManager` task ensures that this `TaskHandle` task does not outlive the `WalReceiverManager` task.
     290              :     /// For the `RequestContext` that we hand to the TaskHandle, we use the [`WalReceiverConnectionHandler`] task kind.
     291              :     ///
     292              :     /// Once the connection is established, the `TaskHandle` task spawns a
     293              :     /// [`WalReceiverConnectionPoller`] task that is responsible for polling
     294              :     /// the `Connection` object.
     295              :     /// A `CancellationToken` created by the `TaskHandle` task ensures
     296              :     /// that the [`WalReceiverConnectionPoller`] task will cancel soon after as the `TaskHandle` is dropped.
     297              :     ///
     298              :     /// [`WalReceiverConnectionHandler`]: Self::WalReceiverConnectionHandler
     299              :     /// [`WalReceiverConnectionPoller`]: Self::WalReceiverConnectionPoller
     300              :     WalReceiverManager,
     301              : 
     302              :     /// The `TaskHandle` task that executes `handle_walreceiver_connection`.
     303              :     /// See the comment on [`WalReceiverManager`].
     304              :     ///
     305              :     /// [`WalReceiverManager`]: Self::WalReceiverManager
     306              :     WalReceiverConnectionHandler,
     307              : 
     308              :     /// The task that polls the `tokio-postgres::Connection` object.
     309              :     /// Spawned by task [`WalReceiverConnectionHandler`](Self::WalReceiverConnectionHandler).
     310              :     /// See the comment on [`WalReceiverManager`](Self::WalReceiverManager).
     311              :     WalReceiverConnectionPoller,
     312              : 
     313              :     // Garbage collection worker. One per tenant
     314              :     GarbageCollector,
     315              : 
     316              :     // Compaction. One per tenant.
     317              :     Compaction,
     318              : 
     319              :     // Eviction. One per timeline.
     320              :     Eviction,
     321              : 
     322              :     // Ingest housekeeping (flushing ephemeral layers on time threshold or disk pressure)
     323              :     IngestHousekeeping,
     324              : 
     325              :     /// See [`crate::disk_usage_eviction_task`].
     326              :     DiskUsageEviction,
     327              : 
     328              :     /// See [`crate::tenant::secondary`].
     329              :     SecondaryDownloads,
     330              : 
     331              :     /// See [`crate::tenant::secondary`].
     332              :     SecondaryUploads,
     333              : 
     334              :     // Initial logical size calculation
     335              :     InitialLogicalSizeCalculation,
     336              : 
     337              :     OndemandLogicalSizeCalculation,
     338              : 
     339              :     // Task that flushes frozen in-memory layers to disk
     340              :     LayerFlushTask,
     341              : 
     342              :     // Task that uploads a file to remote storage
     343              :     RemoteUploadTask,
     344              : 
     345              :     // task that handles the initial downloading of all tenants
     346              :     InitialLoad,
     347              : 
     348              :     // task that handles attaching a tenant
     349              :     Attach,
     350              : 
     351              :     // Used mostly for background deletion from s3
     352              :     TimelineDeletionWorker,
     353              : 
     354              :     // task that handhes metrics collection
     355              :     MetricsCollection,
     356              : 
     357              :     // task that drives downloading layers
     358              :     DownloadAllRemoteLayers,
     359              :     // Task that calculates synthetis size for all active tenants
     360              :     CalculateSyntheticSize,
     361              : 
     362              :     // A request that comes in via the pageserver HTTP API.
     363              :     MgmtRequest,
     364              : 
     365              :     DebugTool,
     366              : 
     367              :     EphemeralFilePreWarmPageCache,
     368              : 
     369              :     LayerDownload,
     370              : 
     371              :     #[cfg(test)]
     372              :     UnitTest,
     373              : 
     374              :     DetachAncestor,
     375              : }
     376              : 
     377              : #[derive(Default)]
     378              : struct MutableTaskState {
     379              :     /// Handle for waiting for the task to exit. It can be None, if the
     380              :     /// the task has already exited.
     381              :     join_handle: Option<JoinHandle<()>>,
     382              : }
     383              : 
     384              : struct PageServerTask {
     385              :     task_id: PageserverTaskId,
     386              : 
     387              :     kind: TaskKind,
     388              : 
     389              :     name: String,
     390              : 
     391              :     // To request task shutdown, just cancel this token.
     392              :     cancel: CancellationToken,
     393              : 
     394              :     /// Tasks may optionally be launched for a particular tenant/timeline, enabling
     395              :     /// later cancelling tasks for that tenant/timeline in [`shutdown_tasks`]
     396              :     tenant_shard_id: Option<TenantShardId>,
     397              :     timeline_id: Option<TimelineId>,
     398              : 
     399              :     mutable: Mutex<MutableTaskState>,
     400              : }
     401              : 
     402              : /// Launch a new task
     403              : /// Note: if shutdown_process_on_error is set to true failure
     404              : ///   of the task will lead to shutdown of entire process
     405         3442 : pub fn spawn<F>(
     406         3442 :     runtime: &tokio::runtime::Handle,
     407         3442 :     kind: TaskKind,
     408         3442 :     tenant_shard_id: Option<TenantShardId>,
     409         3442 :     timeline_id: Option<TimelineId>,
     410         3442 :     name: &str,
     411         3442 :     shutdown_process_on_error: bool,
     412         3442 :     future: F,
     413         3442 : ) -> PageserverTaskId
     414         3442 : where
     415         3442 :     F: Future<Output = anyhow::Result<()>> + Send + 'static,
     416         3442 : {
     417         3442 :     let cancel = CancellationToken::new();
     418         3442 :     let task_id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
     419         3442 :     let task = Arc::new(PageServerTask {
     420         3442 :         task_id: PageserverTaskId(task_id),
     421         3442 :         kind,
     422         3442 :         name: name.to_string(),
     423         3442 :         cancel: cancel.clone(),
     424         3442 :         tenant_shard_id,
     425         3442 :         timeline_id,
     426         3442 :         mutable: Mutex::new(MutableTaskState { join_handle: None }),
     427         3442 :     });
     428         3442 : 
     429         3442 :     TASKS.lock().unwrap().insert(task_id, Arc::clone(&task));
     430         3442 : 
     431         3442 :     let mut task_mut = task.mutable.lock().unwrap();
     432         3442 : 
     433         3442 :     let task_name = name.to_string();
     434         3442 :     let task_cloned = Arc::clone(&task);
     435         3442 :     let join_handle = runtime.spawn(task_wrapper(
     436         3442 :         task_name,
     437         3442 :         task_id,
     438         3442 :         task_cloned,
     439         3442 :         cancel,
     440         3442 :         shutdown_process_on_error,
     441         3442 :         future,
     442         3442 :     ));
     443         3442 :     task_mut.join_handle = Some(join_handle);
     444         3442 :     drop(task_mut);
     445         3442 : 
     446         3442 :     // The task is now running. Nothing more to do here
     447         3442 :     PageserverTaskId(task_id)
     448         3442 : }
     449              : 
     450              : /// This wrapper function runs in a newly-spawned task. It initializes the
     451              : /// task-local variables and calls the payload function.
     452         3442 : async fn task_wrapper<F>(
     453         3442 :     task_name: String,
     454         3442 :     task_id: u64,
     455         3442 :     task: Arc<PageServerTask>,
     456         3442 :     shutdown_token: CancellationToken,
     457         3442 :     shutdown_process_on_error: bool,
     458         3442 :     future: F,
     459         3442 : ) where
     460         3442 :     F: Future<Output = anyhow::Result<()>> + Send + 'static,
     461         3442 : {
     462         3276 :     debug!("Starting task '{}'", task_name);
     463              : 
     464         3276 :     let result = SHUTDOWN_TOKEN
     465         3276 :         .scope(
     466         3276 :             shutdown_token,
     467         3276 :             CURRENT_TASK.scope(task, {
     468         3276 :                 // We use AssertUnwindSafe here so that the payload function
     469         3276 :                 // doesn't need to be UnwindSafe. We don't do anything after the
     470         3276 :                 // unwinding that would expose us to unwind-unsafe behavior.
     471         3276 :                 AssertUnwindSafe(future).catch_unwind()
     472         3276 :             }),
     473         3276 :         )
     474        95808 :         .await;
     475         2845 :     task_finish(result, task_name, task_id, shutdown_process_on_error).await;
     476         2845 : }
     477              : 
     478         2845 : async fn task_finish(
     479         2845 :     result: std::result::Result<
     480         2845 :         anyhow::Result<()>,
     481         2845 :         std::boxed::Box<dyn std::any::Any + std::marker::Send>,
     482         2845 :     >,
     483         2845 :     task_name: String,
     484         2845 :     task_id: u64,
     485         2845 :     shutdown_process_on_error: bool,
     486         2845 : ) {
     487         2845 :     // Remove our entry from the global hashmap.
     488         2845 :     let task = TASKS
     489         2845 :         .lock()
     490         2845 :         .unwrap()
     491         2845 :         .remove(&task_id)
     492         2845 :         .expect("no task in registry");
     493         2845 : 
     494         2845 :     let mut shutdown_process = false;
     495              :     {
     496         2845 :         match result {
     497              :             Ok(Ok(())) => {
     498         2845 :                 debug!("Task '{}' exited normally", task_name);
     499              :             }
     500            0 :             Ok(Err(err)) => {
     501            0 :                 if shutdown_process_on_error {
     502            0 :                     error!(
     503            0 :                         "Shutting down: task '{}' tenant_shard_id: {:?}, timeline_id: {:?} exited with error: {:?}",
     504            0 :                         task_name, task.tenant_shard_id, task.timeline_id, err
     505              :                     );
     506            0 :                     shutdown_process = true;
     507              :                 } else {
     508            0 :                     error!(
     509            0 :                         "Task '{}' tenant_shard_id: {:?}, timeline_id: {:?} exited with error: {:?}",
     510            0 :                         task_name, task.tenant_shard_id, task.timeline_id, err
     511              :                     );
     512              :                 }
     513              :             }
     514            0 :             Err(err) => {
     515            0 :                 if shutdown_process_on_error {
     516            0 :                     error!(
     517            0 :                         "Shutting down: task '{}' tenant_shard_id: {:?}, timeline_id: {:?} panicked: {:?}",
     518            0 :                         task_name, task.tenant_shard_id, task.timeline_id, err
     519              :                     );
     520            0 :                     shutdown_process = true;
     521              :                 } else {
     522            0 :                     error!(
     523            0 :                         "Task '{}' tenant_shard_id: {:?}, timeline_id: {:?} panicked: {:?}",
     524            0 :                         task_name, task.tenant_shard_id, task.timeline_id, err
     525              :                     );
     526              :                 }
     527              :             }
     528              :         }
     529              :     }
     530              : 
     531         2845 :     if shutdown_process {
     532            0 :         std::process::exit(1);
     533         2845 :     }
     534         2845 : }
     535              : 
     536              : /// Signal and wait for tasks to shut down.
     537              : ///
     538              : ///
     539              : /// The arguments are used to select the tasks to kill. Any None arguments are
     540              : /// ignored. For example, to shut down all WalReceiver tasks:
     541              : ///
     542              : ///   shutdown_tasks(Some(TaskKind::WalReceiver), None, None)
     543              : ///
     544              : /// Or to shut down all tasks for given timeline:
     545              : ///
     546              : ///   shutdown_tasks(None, Some(tenant_shard_id), Some(timeline_id))
     547              : ///
     548           22 : pub async fn shutdown_tasks(
     549           22 :     kind: Option<TaskKind>,
     550           22 :     tenant_shard_id: Option<TenantShardId>,
     551           22 :     timeline_id: Option<TimelineId>,
     552           22 : ) {
     553           22 :     let mut victim_tasks = Vec::new();
     554           22 : 
     555           22 :     {
     556           22 :         let tasks = TASKS.lock().unwrap();
     557           22 :         for task in tasks.values() {
     558           20 :             if (kind.is_none() || Some(task.kind) == kind)
     559           12 :                 && (tenant_shard_id.is_none() || task.tenant_shard_id == tenant_shard_id)
     560           12 :                 && (timeline_id.is_none() || task.timeline_id == timeline_id)
     561            6 :             {
     562            6 :                 task.cancel.cancel();
     563            6 :                 victim_tasks.push((
     564            6 :                     Arc::clone(task),
     565            6 :                     task.kind,
     566            6 :                     task.tenant_shard_id,
     567            6 :                     task.timeline_id,
     568            6 :                 ));
     569           14 :             }
     570              :         }
     571              :     }
     572              : 
     573           22 :     let log_all = kind.is_none() && tenant_shard_id.is_none() && timeline_id.is_none();
     574              : 
     575           28 :     for (task, task_kind, tenant_shard_id, timeline_id) in victim_tasks {
     576            6 :         let join_handle = {
     577            6 :             let mut task_mut = task.mutable.lock().unwrap();
     578            6 :             task_mut.join_handle.take()
     579              :         };
     580            6 :         if let Some(mut join_handle) = join_handle {
     581            6 :             if log_all {
     582            0 :                 if tenant_shard_id.is_none() {
     583              :                     // there are quite few of these
     584            0 :                     info!(name = task.name, kind = ?task_kind, "stopping global task");
     585              :                 } else {
     586              :                     // warn to catch these in tests; there shouldn't be any
     587            0 :                     warn!(name = task.name, tenant_shard_id = ?tenant_shard_id, timeline_id = ?timeline_id, kind = ?task_kind, "stopping left-over");
     588              :                 }
     589            6 :             }
     590            6 :             if tokio::time::timeout(std::time::Duration::from_secs(1), &mut join_handle)
     591            6 :                 .await
     592            6 :                 .is_err()
     593              :             {
     594              :                 // allow some time to elapse before logging to cut down the number of log
     595              :                 // lines.
     596            0 :                 info!("waiting for task {} to shut down", task.name);
     597              :                 // we never handled this return value, but:
     598              :                 // - we don't deschedule which would lead to is_cancelled
     599              :                 // - panics are already logged (is_panicked)
     600              :                 // - task errors are already logged in the wrapper
     601            0 :                 let _ = join_handle.await;
     602            0 :                 info!("task {} completed", task.name);
     603            6 :             }
     604            0 :         } else {
     605            0 :             // Possibly one of:
     606            0 :             //  * The task had not even fully started yet.
     607            0 :             //  * It was shut down concurrently and already exited
     608            0 :         }
     609              :     }
     610           22 : }
     611              : 
     612            0 : pub fn current_task_kind() -> Option<TaskKind> {
     613            0 :     CURRENT_TASK.try_with(|ct| ct.kind).ok()
     614            0 : }
     615              : 
     616            0 : pub fn current_task_id() -> Option<PageserverTaskId> {
     617            0 :     CURRENT_TASK.try_with(|ct| ct.task_id).ok()
     618            0 : }
     619              : 
     620              : /// A Future that can be used to check if the current task has been requested to
     621              : /// shut down.
     622            0 : pub async fn shutdown_watcher() {
     623            0 :     let token = SHUTDOWN_TOKEN
     624            0 :         .try_with(|t| t.clone())
     625            0 :         .expect("shutdown_watcher() called in an unexpected task or thread");
     626            0 : 
     627            0 :     token.cancelled().await;
     628            0 : }
     629              : 
     630              : /// Clone the current task's cancellation token, which can be moved across tasks.
     631              : ///
     632              : /// When the task which is currently executing is shutdown, the cancellation token will be
     633              : /// cancelled. It can however be moved to other tasks, such as `tokio::task::spawn_blocking` or
     634              : /// `tokio::task::JoinSet::spawn`.
     635         2901 : pub fn shutdown_token() -> CancellationToken {
     636         2901 :     let res = SHUTDOWN_TOKEN.try_with(|t| t.clone());
     637         2901 : 
     638         2901 :     if cfg!(test) {
     639              :         // in tests this method is called from non-taskmgr spawned tasks, and that is all ok.
     640         2901 :         res.unwrap_or_default()
     641              :     } else {
     642            0 :         res.expect("shutdown_token() called in an unexpected task or thread")
     643              :     }
     644         2901 : }
     645              : 
     646              : /// Has the current task been requested to shut down?
     647            0 : pub fn is_shutdown_requested() -> bool {
     648            0 :     if let Ok(true_or_false) = SHUTDOWN_TOKEN.try_with(|t| t.is_cancelled()) {
     649            0 :         true_or_false
     650              :     } else {
     651            0 :         if !cfg!(test) {
     652            0 :             warn!("is_shutdown_requested() called in an unexpected task or thread");
     653            0 :         }
     654            0 :         false
     655              :     }
     656            0 : }
        

Generated by: LCOV version 2.1-beta