1use std::future::Future;
4use std::net::SocketAddr;
5use std::process::ExitCode;
6use std::sync::Arc;
7use std::time::Duration;
8
9use tokio::task::JoinHandle;
10use tokio_util::sync::CancellationToken;
11
12use redup_bootstrap_grpc::{Binder, PlatformServices, bind_platform};
13
14use crate::apoptosis::Apoptosis;
15use crate::bootstrap_config::BootstrapConfig;
16use crate::builder::Assembled;
17use crate::dependency::Dependencies;
18use crate::error::Error;
19use crate::grpc_server::{self, providers};
20use crate::halt::{Halt, Stop};
21use crate::info_source::InfoSource;
22use crate::listener::{Listener, Routes};
23use crate::memory;
24use crate::panic_error::Panic;
25use crate::signals;
26use crate::stopper::Stopper;
27use crate::telemetry::Telemetry;
28use crate::telemetry::journal::{Logging, fatal};
29
30const INFLATION_STEP: u64 = 256 * 1024 * 1024;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum State {
36 Built,
38 Starting,
40 Running,
42 Stopping,
44 Stopped,
46 Failed,
48}
49
50pub struct Instance {
55 info: Arc<InfoSource>,
56 dependencies: Vec<Dependencies>,
57 config: BootstrapConfig,
58 telemetry: Arc<Telemetry>,
59 token: CancellationToken,
60 halt: Halt,
61 listener: Option<Listener>,
62 grpc_listener: Option<Listener>,
63 grpc: Binder,
64 instance_id: String,
65}
66
67async fn isolated<T, F>(point: F) -> Result<T, Panic>
69where
70 F: Future<Output = T> + Send + 'static,
71 T: Send + 'static,
72{
73 match tokio::spawn(point).await {
74 Ok(value) => Ok(value),
75 Err(join) if join.is_panic() => Err(Panic::from_payload(join.try_into_panic().ok())),
76 Err(_) => Err(Panic(None)),
77 }
78}
79
80impl Instance {
81 pub(crate) fn new(assembled: Assembled) -> Self {
82 let Assembled {
83 entries,
84 dependencies,
85 configs,
86 telemetry,
87 config,
88 service,
89 token,
90 halt,
91 instance_id,
92 grpc,
93 } = assembled;
94 let handles = dependencies.iter().map(Dependencies::handles).collect();
95 let info = Arc::new(InfoSource::new(
96 service,
97 entries,
98 handles,
99 configs,
100 telemetry.load(),
101 ));
102 Self {
103 info,
104 dependencies,
105 config,
106 telemetry: Arc::new(telemetry),
107 token,
108 halt,
109 listener: None,
110 grpc_listener: None,
111 grpc,
112 instance_id,
113 }
114 }
115
116 pub fn state(&self) -> State {
118 self.info.state()
119 }
120
121 pub fn snapshot(&self) -> crate::snapshot::Snapshot {
123 self.info.snapshot()
124 }
125
126 pub fn address(&self) -> Option<SocketAddr> {
128 self.listener.as_ref().map(Listener::address)
129 }
130
131 pub fn grpc_address(&self) -> Option<SocketAddr> {
133 self.grpc_listener.as_ref().map(Listener::address)
134 }
135
136 pub fn stopper(&self) -> Stopper {
138 Stopper::new(self.halt.clone())
139 }
140
141 pub fn apoptosis(&self) -> Apoptosis {
143 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone())
144 }
145
146 pub fn logging(&self) -> Logging {
148 self.telemetry.logging()
149 }
150
151 pub async fn start(&mut self) -> Result<(), Error> {
154 if self.state() != State::Built {
155 return Err(Error::State {
156 action: "be started",
157 });
158 }
159 self.info.set_state(State::Starting);
160 self.info.mark_started();
161 self.start_load_average();
162 if let Some(rest) = self.config.rest() {
163 let routes = Routes {
164 snapshot: self.snapshot_source(),
165 telemetry: Arc::clone(&self.telemetry),
166 info: Arc::clone(&self.info),
167 };
168 let listener = Listener::bind(
169 rest.host(),
170 rest.port(),
171 crate::routes::router(routes),
172 "REST",
173 )
174 .await
175 .map_err(|source| Error::Bind {
176 address: format!("{}:{}", rest.host(), rest.port()),
177 source,
178 });
179 match listener {
180 Ok(listener) => self.listener = Some(listener),
181 Err(error) => {
182 tracing::error!(error = %error, "the instance failed to start");
183 self.release().await;
184 self.info.set_state(State::Failed);
185 return Err(error);
186 }
187 }
188 }
189 if let Some(grpc) = self.config.grpc().cloned()
190 && let Err(error) = self.start_grpc(&grpc).await
191 {
192 tracing::error!(error = %error, "the instance failed to start");
193 self.release().await;
194 self.info.set_state(State::Failed);
195 return Err(error);
196 }
197 let entries: Vec<(std::sync::Arc<dyn crate::runtime::Runtime>, &'static str)> = self
198 .info
199 .modules()
200 .iter()
201 .map(|entry| (Arc::clone(&entry.module), entry.name))
202 .collect();
203 for (module, name) in entries {
204 match isolated(module.start()).await {
205 Ok(Ok(())) => {
206 tracing::info!(module = name, "module started");
207 }
208 Ok(Err(source)) => {
209 tracing::error!(module = name, error = %source, "module failed to start");
210 self.release().await;
211 self.info.set_state(State::Failed);
212 return Err(Error::Start {
213 module: name,
214 source,
215 });
216 }
217 Err(panic) => {
218 tracing::warn!(
220 module = name,
221 error = %panic,
222 "module failed to start after a panic recorded above"
223 );
224 self.release().await;
225 self.info.set_state(State::Failed);
226 return Err(Error::Start {
227 module: name,
228 source: Box::new(panic),
229 });
230 }
231 }
232 }
233 self.info.set_state(State::Running);
234 tracing::info!(
235 service = self.info.service().name(),
236 version = self.info.service().version(),
237 modules = self.info.modules().len(),
238 "the instance is running"
239 );
240 Ok(())
241 }
242
243 pub async fn stop(&mut self) {
247 if matches!(self.state(), State::Stopping | State::Stopped) {
248 return;
249 }
250 let running = self.state() == State::Running;
251 self.info.set_state(State::Stopping);
252 if running {
253 self.drain().await;
254 }
255 self.finish().await;
256 }
257
258 async fn stop_fatal(&mut self) {
261 self.stop_without_drain().await;
262 }
263
264 async fn stop_without_drain(&mut self) {
266 if matches!(self.state(), State::Stopping | State::Stopped) {
267 return;
268 }
269 self.info.set_state(State::Stopping);
270 self.finish().await;
271 }
272
273 async fn finish(&mut self) {
275 self.release().await;
276 self.info.set_state(State::Stopped);
277 tracing::info!("the instance is stopped");
278 #[cfg(feature = "otlp")]
279 self.telemetry.finish();
280 }
281
282 pub async fn run(mut self) -> ExitCode {
286 if let Err(error) = self.start().await {
287 tracing::error!(error = %error, "the instance failed to start");
288 return ExitCode::from(1);
289 }
290 self.listen_to_signals();
291 match self.halt.wait().await {
292 Stop::Fatal(reason) => {
293 fatal!(
294 reason = reason.as_str(),
295 "the service stops on a fatal report: continuing may corrupt data"
296 );
297 self.stop_fatal().await;
298 ExitCode::from(1)
299 }
300 Stop::Apoptosis(reason) => self.apoptose(reason).await,
301 Stop::Signal | Stop::Request(_) => {
302 self.stop().await;
303 ExitCode::SUCCESS
304 }
305 Stop::RequestFast(_) => {
306 tracing::info!("the instance stops on request without draining");
307 self.stop_without_drain().await;
308 ExitCode::SUCCESS
309 }
310 }
311 }
312
313 fn listen_to_signals(&self) {
314 let halt = self.halt.clone();
315 tokio::spawn(async move {
316 if let Err(error) = signals::terminate().await {
317 tracing::error!(
318 error = %error,
319 "termination signals are not being listened to; the instance can be stopped \
320 only by a request"
321 );
322 return;
323 }
324 if halt.stop(Stop::Signal) {
325 tracing::info!(
326 "termination signal received: the instance is stopping. A repeated signal \
327 exits the process immediately"
328 );
329 let _ = signals::terminate().await;
330 }
331 std::process::exit(130);
332 });
333 }
334
335 async fn start_grpc(&mut self, config: &crate::grpc_config::GrpcConfig) -> Result<(), Error> {
338 let mut names: Vec<String> = self
339 .grpc
340 .services()
341 .iter()
342 .map(|service| service.name().to_owned())
343 .collect();
344 for name in [
345 "grpc.health.v1.Health",
346 "redup.bootstrap.v1.Info",
347 "redup.bootstrap.v1.Metrics",
348 "redup.bootstrap.v1.Control",
349 "grpc.reflection.v1.ServerReflection",
350 "grpc.reflection.v1alpha.ServerReflection",
351 ] {
352 names.push(name.to_owned());
353 }
354 let services = PlatformServices {
355 health: Arc::new(providers::HealthState::new(Arc::clone(&self.info), names)),
356 info: Arc::new(providers::InfoState::new(
357 Arc::clone(&self.info),
358 self.grpc.services(),
359 )),
360 metrics: Arc::new(providers::MetricsState::new(
361 Arc::clone(&self.info),
362 Arc::clone(&self.telemetry),
363 )),
364 control: Arc::new(providers::ControlState::new(
365 Stopper::new(self.halt.clone()),
366 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone()),
367 self.telemetry.logging(),
368 self.token.child_token(),
369 )),
370 };
371 bind_platform(&self.grpc, services).map_err(|source| Error::Grpc {
372 source: Box::new(source),
373 })?;
374 self.start_health_watch();
375 let state = grpc_server::State {
376 binder: self.grpc.clone(),
377 telemetry: Arc::clone(&self.telemetry),
378 service_name: self.info.service().name().to_owned(),
379 instance_id: self.instance_id.clone(),
380 exposure: config.errors().exposure(),
381 debug_info: config.errors().debug_info(),
382 token: self.token.child_token(),
383 };
384 let router = grpc_server::router(self.grpc.take_routes(), state);
385 let listener = Listener::bind(config.host(), config.port(), router, "gRPC")
386 .await
387 .map_err(|source| Error::Bind {
388 address: format!("{}:{}", config.host(), config.port()),
389 source,
390 })?;
391 self.grpc_listener = Some(listener);
392 Ok(())
393 }
394
395 fn start_health_watch(&self) {
397 for entry in self.info.modules() {
398 let Some(health) = entry.health.clone() else {
399 continue;
400 };
401 let mut changes = health.subscribe();
402 let info = Arc::clone(&self.info);
403 let token = self.token.child_token();
404 tokio::spawn(async move {
405 loop {
406 tokio::select! {
407 _ = token.cancelled() => return,
408 changed = changes.changed() => {
409 if changed.is_err() {
410 return;
411 }
412 info.notify();
413 }
414 }
415 }
416 });
417 }
418 }
419
420 fn start_load_average(&self) {
422 let token = self.token.child_token();
423 let averages = self.telemetry.clone();
424 tokio::spawn(async move {
425 averages.run(token).await;
426 });
427 }
428
429 fn snapshot_source(&self) -> crate::listener::SnapshotSource {
431 let info = Arc::clone(&self.info);
432 Arc::new(move || info.snapshot())
433 }
434
435 async fn drain(&self) {
438 let timeout = self.config.control().drain_timeout();
439 let mut tasks: Vec<(&'static str, JoinHandle<()>)> = Vec::new();
440 for entry in self.info.modules() {
441 let module = Arc::clone(&entry.module);
442 let name = entry.name;
443 tasks.push((
444 name,
445 tokio::spawn(async move {
446 match tokio::time::timeout(timeout, module.drain()).await {
447 Ok(Ok(())) => {}
448 Ok(Err(source)) => {
449 tracing::warn!(module = name, error = %source, "module failed to drain")
450 }
451 Err(_) => tracing::warn!(
452 module = name,
453 timeout = ?timeout,
454 "module did not finish draining within the drain timeout"
455 ),
456 }
457 }),
458 ));
459 }
460 for (name, task) in tasks {
461 if task.await.is_err() {
462 tracing::warn!(module = name, "module panicked while draining");
463 }
464 }
465 }
466
467 async fn stop_modules(&self, timeout: Option<Duration>) {
470 let stopping = async {
471 for entry in self.info.modules().iter().rev() {
472 let module = Arc::clone(&entry.module);
473 let name = entry.name;
474 match isolated(module.stop()).await {
475 Ok(Ok(())) => {}
476 Ok(Err(source)) => {
477 tracing::error!(module = name, error = %source, "module failed to stop")
478 }
479 Err(panic) => {
480 tracing::warn!(
481 module = name,
482 error = %panic,
483 "module failed to stop after a panic recorded above"
484 );
485 }
486 }
487 }
488 };
489 match timeout {
490 None => stopping.await,
491 Some(limit) => {
492 if tokio::time::timeout(limit, stopping).await.is_err() {
493 tracing::warn!(
494 limit = ?limit,
495 "modules did not stop within the timeout; proceeding without them"
496 );
497 }
498 }
499 }
500 }
501
502 async fn release(&mut self) {
505 self.token.cancel();
506 self.stop_modules(None).await;
507 for dependencies in &mut self.dependencies {
508 dependencies.shutdown().await;
509 }
510 if let Some(listener) = self.listener.take() {
511 listener.shutdown().await;
512 }
513 if let Some(listener) = self.grpc_listener.take() {
514 listener.shutdown().await;
515 }
516 }
517
518 async fn apoptose(&mut self, reason: String) -> ExitCode {
521 fatal!(
522 reason,
523 memory = memory::resident_bytes(),
524 limit = memory::container_limit(),
525 "apoptosis: the service cannot recover from the memory shortage and will be unloaded"
526 );
527 self.info.set_state(State::Stopping);
528 let timeout = self
529 .config
530 .control()
531 .oom()
532 .map(|oom| oom.modules_shutdown_timeout());
533 self.token.cancel();
534 self.stop_modules(timeout).await;
535 for dependencies in &mut self.dependencies {
536 dependencies.shutdown().await;
537 }
538 let Some(limit) = memory::container_limit() else {
539 tracing::error!("the container has no memory limit; the process exits with code 137");
540 return ExitCode::from(137);
541 };
542 let mut target = limit;
543 loop {
544 match memory::inflate(target).await {
545 Ok(()) => target = target.saturating_add(INFLATION_STEP),
546 Err(error) => {
547 tracing::error!(
548 %error,
549 "memory inflation stopped before the limit; the process exits with code 137"
550 );
551 return ExitCode::from(137);
552 }
553 }
554 }
555 }
556}