worker.rs 9.17 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Ryan Olson's avatar
Ryan Olson committed
15
16
17
18
19
20

//! The [Worker] class is a convenience wrapper around the construction of the [Runtime]
//! and execution of the users application.
//!
//! In the future, the [Worker] should probably be moved to a procedural macro similar
//! to the `#[tokio::main]` attribute, where we might annotate an async main function with
Neelay Shah's avatar
Neelay Shah committed
21
//! `#[dynamo::main]` or similar.
Ryan Olson's avatar
Ryan Olson committed
22
23
24
25
26
27
//!
//! The [Worker::execute] method is designed to be called once from main and will block
//! the calling thread until the application completes or is canceled. The method initialized
//! the signal handler used to trap `SIGINT` and `SIGTERM` signals and trigger a graceful shutdown.
//!
//! On termination, the user application is given a graceful shutdown period of controlled by
28
//! the [DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT] environment variable. If the application does not
Ryan Olson's avatar
Ryan Olson committed
29
30
//! shutdown in time, the worker will terminate the application with an exit code of 911.
//!
31
//! The default values of [DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT] differ between the development
Ryan Olson's avatar
Ryan Olson committed
32
33
34
//! and release builds. In development, the default is [DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_DEBUG] and
//! in release, the default is [DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_RELEASE].

35
use super::{error, CancellationToken, Result, Runtime, RuntimeConfig};
Ryan Olson's avatar
Ryan Olson committed
36
37
38
39
40
41
42

use futures::Future;
use once_cell::sync::OnceCell;
use std::{sync::Mutex, time::Duration};
use tokio::{signal, task::JoinHandle};

static RT: OnceCell<tokio::runtime::Runtime> = OnceCell::new();
43
static RTHANDLE: OnceCell<tokio::runtime::Handle> = OnceCell::new();
Ryan Olson's avatar
Ryan Olson committed
44
45
46
47
48
static INIT: OnceCell<Mutex<Option<tokio::task::JoinHandle<Result<()>>>>> = OnceCell::new();

const SHUTDOWN_MESSAGE: &str =
    "Application received shutdown signal; attempting to gracefully shutdown";
const SHUTDOWN_TIMEOUT_MESSAGE: &str =
49
    "Use DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT to control the graceful shutdown timeout";
Ryan Olson's avatar
Ryan Olson committed
50
51

/// Environment variable to control the graceful shutdown timeout
52
pub const DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT: &str = "DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT";
Ryan Olson's avatar
Ryan Olson committed
53
54
55
56
57
58
59

/// Default graceful shutdown timeout in seconds in debug mode
pub const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_DEBUG: u64 = 5;

/// Default graceful shutdown timeout in seconds in release mode
pub const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_RELEASE: u64 = 30;

60
#[derive(Debug, Clone)]
Ryan Olson's avatar
Ryan Olson committed
61
62
pub struct Worker {
    runtime: Runtime,
63
    config: RuntimeConfig,
Ryan Olson's avatar
Ryan Olson committed
64
65
66
67
68
69
70
71
72
73
74
75
}

impl Worker {
    /// Create a new [`Worker`] instance from [`RuntimeConfig`] settings which is sourced from the environment
    pub fn from_settings() -> Result<Worker> {
        let config = RuntimeConfig::from_settings()?;
        Worker::from_config(config)
    }

    /// Create a new [`Worker`] instance from a provided [`RuntimeConfig`]
    pub fn from_config(config: RuntimeConfig) -> Result<Worker> {
        // if the runtime is already initialized, return an error
76
        if RT.get().is_some() || RTHANDLE.get().is_some() {
Ryan Olson's avatar
Ryan Olson committed
77
78
79
80
81
82
83
84
85
86
87
            return Err(error!("Worker already initialized"));
        }

        // create a new runtime and insert it into the OnceCell
        // there is still a potential race-condition here, two threads cou have passed the first check
        // but only one will succeed in inserting the runtime
        let rt = RT.try_insert(config.create_runtime()?).map_err(|_| {
            error!("Failed to create worker; Only a single Worker should ever be created")
        })?;

        let runtime = Runtime::from_handle(rt.handle().clone())?;
88
        Ok(Worker { runtime, config })
Ryan Olson's avatar
Ryan Olson committed
89
90
    }

Ryan Olson's avatar
Ryan Olson committed
91
92
93
94
95
96
97
98
99
100
    pub fn runtime_from_existing() -> Result<Runtime> {
        if let Some(rt) = RT.get() {
            Ok(Runtime::from_handle(rt.handle().clone())?)
        } else if let Some(rt) = RTHANDLE.get() {
            Ok(Runtime::from_handle(rt.clone())?)
        } else {
            Runtime::from_settings()
        }
    }

Ryan Olson's avatar
Ryan Olson committed
101
102
103
104
105
106
107
108
    pub fn tokio_runtime(&self) -> Result<&'static tokio::runtime::Runtime> {
        RT.get().ok_or_else(|| error!("Worker not initialized"))
    }

    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    pub fn execute<F, Fut>(self, f: F) -> Result<()>
    where
        F: FnOnce(Runtime) -> Fut + Send + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let runtime = self.runtime.clone();
        runtime.secondary().block_on(self.execute_internal(f))??;
        runtime.shutdown();
        Ok(())
    }

    pub async fn execute_async<F, Fut>(self, f: F) -> Result<()>
    where
        F: FnOnce(Runtime) -> Fut + Send + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let runtime = self.runtime.clone();
        let task = self.execute_internal(f);
        task.await??;
        runtime.shutdown();
        Ok(())
    }

Ryan Olson's avatar
Ryan Olson committed
132
133
    /// Executes the provided application/closure on the [`Runtime`].
    /// This is designed to be called once from main and will block the calling thread until the application completes.
134
    fn execute_internal<F, Fut>(self, f: F) -> JoinHandle<Result<()>>
Ryan Olson's avatar
Ryan Olson committed
135
136
137
138
    where
        F: FnOnce(Runtime) -> Fut + Send + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
139
        let runtime = self.runtime.clone();
Ryan Olson's avatar
Ryan Olson committed
140
        let primary = runtime.primary();
141
        let secondary = runtime.secondary();
Ryan Olson's avatar
Ryan Olson committed
142

143
        let timeout = std::env::var(DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT)
Ryan Olson's avatar
Ryan Olson committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or({
                if cfg!(debug_assertions) {
                    DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_DEBUG
                } else {
                    DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_RELEASE
                }
            });

        INIT.set(Mutex::new(Some(secondary.spawn(async move {
            // start signal handler
            tokio::spawn(signal_handler(runtime.cancellation_token.clone()));

            let cancel_token = runtime.child_token();
            let (mut app_tx, app_rx) = tokio::sync::oneshot::channel::<()>();

            // spawn a task to run the application
            let task: JoinHandle<Result<()>> = primary.spawn(async move {
                let _rx = app_rx;
                f(runtime).await
            });

            tokio::select! {
                _ = cancel_token.cancelled() => {
169
170
                    tracing::debug!("{}", SHUTDOWN_MESSAGE);
                    tracing::debug!("{} {} seconds", SHUTDOWN_TIMEOUT_MESSAGE, timeout);
Ryan Olson's avatar
Ryan Olson committed
171
172
173
174
175
176
177
178
179
180
181
182
                }

                _ = app_tx.closed() => {
                }
            };

            let result = tokio::select! {
                result = task => {
                    result
                }

                _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout)) => {
183
                    tracing::debug!("Application did not shutdown in time; terminating");
Ryan Olson's avatar
Ryan Olson committed
184
185
186
187
188
189
                    std::process::exit(911);
                }
            }?;

            match &result {
                Ok(_) => {
190
                    tracing::debug!("Application shutdown successfully");
Ryan Olson's avatar
Ryan Olson committed
191
192
                }
                Err(e) => {
193
                    tracing::error!("Application shutdown with error: {:?}", e);
Ryan Olson's avatar
Ryan Olson committed
194
195
196
197
198
                }
            }

            result
        }))))
199
        .expect("Failed to spawn application task");
Ryan Olson's avatar
Ryan Olson committed
200
201
202
203
204
205
206
207

        let task = INIT
            .get()
            .expect("Application task not initialized")
            .lock()
            .unwrap()
            .take()
            .expect("Application initialized; but another thread is awaiting it; Worker.execute() can only be called once");
208
209
        task
    }
Ryan Olson's avatar
Ryan Olson committed
210

211
212
213
214
215
    pub fn from_current() -> Result<Worker> {
        if RT.get().is_some() || RTHANDLE.get().is_some() {
            return Err(error!("Worker already initialized"));
        }
        let runtime = Runtime::from_current()?;
216
217
        let config = RuntimeConfig::from_settings()?;
        Ok(Worker { runtime, config })
Ryan Olson's avatar
Ryan Olson committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
    }
}

/// Catch signals and trigger a shutdown
async fn signal_handler(cancel_token: CancellationToken) -> Result<()> {
    let ctrl_c = async {
        signal::ctrl_c().await?;
        anyhow::Ok(())
    };

    let sigterm = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())?
            .recv()
            .await;
        anyhow::Ok(())
    };

    tokio::select! {
        _ = ctrl_c => {
            tracing::info!("Ctrl+C received, starting graceful shutdown");
        },
        _ = sigterm => {
            tracing::info!("SIGTERM received, starting graceful shutdown");
        },
        _ = cancel_token.cancelled() => {
243
            tracing::debug!("CancellationToken triggered; shutting down");
Ryan Olson's avatar
Ryan Olson committed
244
245
246
247
248
249
250
251
        },
    }

    // trigger a shutdown
    cancel_token.cancel();

    Ok(())
}