1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::{process, sync::Arc, thread};
use aws_smithy_http_server::{AddExtensionLayer, Router};
use parking_lot::Mutex;
use pyo3::{prelude::*, types::IntoPyDict};
use signal_hook::{consts::*, iterator::Signals};
use tokio::runtime;
use tower::ServiceBuilder;
use crate::{PyHandler, PyHandlers, PySocket, PyState};
#[pyclass(text_signature = "(router)")]
#[derive(Debug, Clone)]
pub struct PyRouter(pub Router);
#[pyclass(subclass, text_signature = "()")]
#[derive(Debug, Default)]
pub struct PyApp {
pub handlers: PyHandlers,
pub context: Option<Arc<PyObject>>,
pub workers: Mutex<Vec<PyObject>>,
pub router: Option<PyRouter>,
}
impl Clone for PyApp {
fn clone(&self) -> Self {
Self {
handlers: self.handlers.clone(),
context: self.context.clone(),
workers: Mutex::new(vec![]),
router: self.router.clone(),
}
}
}
#[allow(dead_code)]
impl PyApp {
fn graceful_termination(&self, workers: &Mutex<Vec<PyObject>>) -> ! {
let workers = workers.lock();
for (idx, worker) in workers.iter().enumerate() {
let idx = idx + 1;
Python::with_gil(|py| {
let pid: isize = worker
.getattr(py, "pid")
.map(|pid| pid.extract(py).unwrap_or(-1))
.unwrap_or(-1);
tracing::debug!("Terminating worker {idx}, PID: {pid}");
match worker.call_method0(py, "terminate") {
Ok(_) => {}
Err(e) => {
tracing::error!("Error terminating worker {idx}, PID: {pid}: {e}");
worker
.call_method0(py, "kill")
.map_err(|e| {
tracing::error!(
"Unable to kill kill worker {idx}, PID: {pid}: {e}"
);
})
.unwrap();
}
}
});
}
process::exit(0);
}
fn immediate_termination(&self, workers: &Mutex<Vec<PyObject>>) -> ! {
let workers = workers.lock();
for (idx, worker) in workers.iter().enumerate() {
let idx = idx + 1;
Python::with_gil(|py| {
let pid: isize = worker
.getattr(py, "pid")
.map(|pid| pid.extract(py).unwrap_or(-1))
.unwrap_or(-1);
tracing::debug!("Killing worker {idx}, PID: {pid}");
worker
.call_method0(py, "kill")
.map_err(|e| {
tracing::error!("Unable to kill kill worker {idx}, PID: {pid}: {e}");
})
.unwrap();
});
}
process::exit(0);
}
fn block_on_rust_signals(&self) {
let mut signals =
Signals::new(&[SIGINT, SIGHUP, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2, SIGWINCH])
.expect("Unable to register signals");
for sig in signals.forever() {
match sig {
SIGINT => {
tracing::info!(
"Termination signal {sig:?} received, all workers will be immediately terminated"
);
self.immediate_termination(&self.workers);
}
SIGTERM | SIGQUIT => {
tracing::info!(
"Termination signal {sig:?} received, all workers will be gracefully terminated"
);
self.graceful_termination(&self.workers);
}
_ => {
tracing::warn!("Signal {sig:?} is ignored by this application");
}
}
}
}
fn register_python_signals(&self, py: Python, event_loop: PyObject) -> PyResult<()> {
let locals = [("event_loop", event_loop)].into_py_dict(py);
py.run(
r#"
import asyncio
import logging
import functools
import signal
async def shutdown(sig, event_loop):
logging.info(f"Caught signal {sig.name}, cancelling tasks registered on this loop")
tasks = [task for task in asyncio.all_tasks() if task is not
asyncio.current_task()]
list(map(lambda task: task.cancel(), tasks))
results = await asyncio.gather(*tasks, return_exceptions=True)
logging.debug(f"Finished awaiting cancelled tasks, results: {results}")
event_loop.stop()
event_loop.add_signal_handler(signal.SIGTERM,
functools.partial(asyncio.ensure_future, shutdown(signal.SIGTERM, event_loop)))
event_loop.add_signal_handler(signal.SIGINT,
functools.partial(asyncio.ensure_future, shutdown(signal.SIGINT, event_loop)))
"#,
None,
Some(locals),
)?;
Ok(())
}
}
#[pymethods]
impl PyApp {
#[pyo3(text_signature = "($self, context)")]
pub fn context(&mut self, _py: Python, context: PyObject) {
self.context = Some(Arc::new(context));
}
#[pyo3(text_signature = "($self, socket, worker_number)")]
pub fn start_worker(
&mut self,
py: Python,
socket: &PyCell<PySocket>,
worker_number: isize,
) -> PyResult<()> {
let asyncio = py.import("asyncio")?;
let uvloop = py.import("uvloop")?;
uvloop.call_method0("install")?;
tracing::debug!("Setting up uvloop for current process");
let event_loop = asyncio.call_method0("new_event_loop")?;
asyncio.call_method1("set_event_loop", (event_loop,))?;
let context = self.context.clone().unwrap_or_else(|| Arc::new(py.None()));
let state = PyState::new(context);
let router: PyRouter = self.router.as_ref().expect("something").clone();
let borrow = socket.try_borrow_mut()?;
let held_socket: &PySocket = &*borrow;
let raw_socket = held_socket.get_socket()?;
self.register_python_signals(py, event_loop.to_object(py))?;
tracing::debug!("Start the Tokio runtime in a background task");
thread::spawn(move || {
let rt = runtime::Builder::new_multi_thread()
.enable_all()
.thread_name(format!("smithy-rs-tokio[{worker_number}]"))
.build()
.expect("Unable to start a new tokio runtime for this process");
rt.block_on(async move {
tracing::debug!("Add middlewares to Rust Python router");
let app = router
.0
.layer(ServiceBuilder::new().layer(AddExtensionLayer::new(state)));
let server = hyper::Server::from_tcp(
raw_socket
.try_into()
.expect("Unable to convert socket2::Socket into std::net::TcpListener"),
)
.expect("Unable to create hyper server from shared socket")
.serve(app.into_make_service());
tracing::debug!("Started hyper server from shared socket");
if let Err(err) = server.await {
tracing::error!("server error: {}", err);
}
});
});
tracing::debug!("Run and block on the Python event loop until a signal is received");
event_loop.call_method0("run_forever")?;
Ok(())
}
#[pyo3(text_signature = "($self, name, func)")]
pub fn register_operation(&mut self, py: Python, name: &str, func: PyObject) -> PyResult<()> {
let inspect = py.import("inspect")?;
let is_coroutine = inspect
.call_method1("iscoroutinefunction", (&func,))?
.extract::<bool>()?;
let func_args = inspect
.call_method1("getargs", (func.getattr(py, "__code__")?,))?
.getattr("args")?
.extract::<Vec<String>>()?;
let handler = PyHandler {
func,
is_coroutine,
args: func_args.len(),
};
tracing::info!(
"Registering function `{name}`, coroutine: {}, arguments: {}",
handler.is_coroutine,
handler.args,
);
self.handlers
.inner
.insert(String::from(name), Arc::new(handler));
Ok(())
}
#[pyo3(text_signature = "($self, address, port, backlog, workers)")]
pub fn run(
&mut self,
py: Python,
address: Option<String>,
port: Option<i32>,
backlog: Option<i32>,
workers: Option<usize>,
) -> PyResult<()> {
let mp = py.import("multiprocessing")?;
mp.call_method0("allow_connection_pickling")?;
let address = address.unwrap_or_else(|| String::from("127.0.0.1"));
let port = port.unwrap_or(13734);
let socket = PySocket::new(address, port, backlog)?;
let mut active_workers = self.workers.lock();
for idx in 1..workers.unwrap_or_else(num_cpus::get) + 1 {
let sock = socket.try_clone()?;
let process = mp.getattr("Process")?;
let handle = process.call1((
py.None(),
self.clone().into_py(py).getattr(py, "start_worker")?,
format!("smithy-rs-worker[{idx}]"),
(sock.into_py(py), idx),
))?;
handle.call_method0("start")?;
active_workers.push(handle.to_object(py));
}
drop(active_workers);
tracing::info!("Rust Python server started successfully");
self.block_on_rust_signals();
Ok(())
}
}