LCOV - code coverage report
Current view: top level - pageserver/src - task_mgr.rs (source / functions) Coverage Total Hit
Test: 6df3fc19ec669bcfbbf9aba41d1338898d24eaa0.info Lines: 62.8 % 250 157
Test Date: 2025-03-12 18:28:53 Functions: 23.2 % 95 22

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

Generated by: LCOV version 2.1-beta