1use std::collections::BTreeMap;
4use std::future::Future;
5use std::net::SocketAddr;
6use std::panic::AssertUnwindSafe;
7use std::process::ExitCode;
8use std::sync::Arc;
9use std::time::Duration;
10
11use axum::response::IntoResponse as _;
12use tokio::task::JoinHandle;
13use tokio_util::sync::CancellationToken;
14
15use redup_bootstrap_client::ClientFactory;
16use redup_bootstrap_grpc::diagnostics::{DumpRegistry, MessageTypes};
17use redup_bootstrap_grpc::{Binder, OpenApiDocument, PlatformServices, bind_platform};
18use redup_bootstrap_rest::{Transcoder, TranscodingConfig};
19
20use crate::apoptosis::Apoptosis;
21use crate::bootstrap_config::BootstrapConfig;
22use crate::builder::Assembled;
23use crate::dependency::Dependencies;
24use crate::error::Error;
25use crate::grpc_server::{self, providers};
26use crate::guard::CallGuards;
27use crate::halt::{Halt, Stop};
28use crate::http::{HttpSurfaces, Surface};
29use crate::info_source::InfoSource;
30use crate::listener::{Listener, Routes};
31use crate::memory;
32use crate::panic_error::Panic;
33use crate::signals;
34use crate::stopper::Stopper;
35use crate::telemetry::Telemetry;
36use crate::telemetry::journal::{Logging, fatal};
37
38const INFLATION_STEP: u64 = 256 * 1024 * 1024;
40
41const NATIVE_PATHS: &[&str] = &[
43 "/readyz",
44 "/health",
45 "/healthz",
46 "/readyz/{name}",
47 "/livez",
48 "/livez/{name}",
49 "/metrics",
50 "/info",
51 "/info/{name}",
52 "/config",
53 "/config/{name}",
54 "/openapi/{file}",
55];
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum State {
60 Built,
62 Starting,
64 Running,
66 Stopping,
68 Stopped,
70 Failed,
72}
73
74pub struct Instance {
79 info: Arc<InfoSource>,
80 dependencies: Vec<Dependencies>,
81 config: BootstrapConfig,
82 telemetry: Arc<Telemetry>,
83 token: CancellationToken,
84 halt: Halt,
85 listener: Option<Listener>,
86 grpc_listener: Option<Listener>,
87 transcoding_listener: Option<Listener>,
88 extra_listeners: Vec<Listener>,
89 grpc: Binder,
90 http: HttpSurfaces,
91 in_process: redup_bootstrap_grpc::InProcess,
92 guards: CallGuards,
93 instance_id: String,
94 clients: Arc<ClientFactory>,
95}
96
97fn with_openapi(router: axum::Router, documents: Vec<OpenApiDocument>) -> axum::Router {
99 let documents: std::collections::HashMap<&'static str, &'static str> = documents
100 .into_iter()
101 .map(|document| (document.name(), document.json()))
102 .collect();
103 let documents = Arc::new(documents);
104 let handler = move |axum::extract::Path(file): axum::extract::Path<String>| {
105 let documents = Arc::clone(&documents);
106 async move {
107 let Some(name) = file.strip_suffix(".json") else {
108 return (axum::http::StatusCode::NOT_FOUND, "Not found").into_response();
109 };
110 match documents.get(name) {
111 Some(json) => (
112 [(
113 axum::http::header::CONTENT_TYPE,
114 "application/json; charset=utf-8",
115 )],
116 *json,
117 )
118 .into_response(),
119 None => (axum::http::StatusCode::NOT_FOUND, "Not found").into_response(),
120 }
121 }
122 };
123 router.route("/openapi/{file}", axum::routing::get(handler))
124}
125
126fn fallback(
128 transcoder: Arc<Transcoder>,
129) -> impl Fn(
130 axum::extract::Request,
131) -> futures_util::future::BoxFuture<'static, axum::response::Response>
132+ Clone
133+ Send
134+ Sync
135+ 'static {
136 move |request| {
137 let transcoder = Arc::clone(&transcoder);
138 Box::pin(async move { transcoder.handle(request).await })
139 }
140}
141
142fn take_address(surfaces: &mut Vec<Surface>, host: &str, port: u16) -> Vec<Surface> {
144 let mut matched = Vec::new();
145 let mut rest = Vec::with_capacity(surfaces.len());
146 for surface in std::mem::take(surfaces) {
147 if surface.host == host && surface.port == port {
148 matched.push(surface);
149 } else {
150 rest.push(surface);
151 }
152 }
153 *surfaces = rest;
154 matched
155}
156
157fn host_mismatch(surfaces: &[Surface], host: &str, port: u16) -> Result<(), Error> {
159 let Some(surface) = surfaces
160 .iter()
161 .find(|surface| surface.port == port && surface.host != host)
162 else {
163 return Ok(());
164 };
165 Err(Error::Surface {
166 what: surface.what,
167 reason: format!("its host must match '{host}' on the shared port {port}"),
168 })
169}
170
171fn merge_surfaces(mut router: axum::Router, surfaces: &[Surface]) -> Result<axum::Router, Error> {
173 for surface in surfaces {
174 let merged =
175 std::panic::catch_unwind(AssertUnwindSafe(|| router.merge(surface.router.clone())));
176 router = merged.map_err(|_| Error::Surface {
177 what: surface.what,
178 reason: format!(
179 "its routes overlap another surface on the shared port {}",
180 surface.address()
181 ),
182 })?;
183 }
184 Ok(router)
185}
186
187async fn isolated<T, F>(point: F) -> Result<T, Panic>
189where
190 F: Future<Output = T> + Send + 'static,
191 T: Send + 'static,
192{
193 match tokio::spawn(point).await {
194 Ok(value) => Ok(value),
195 Err(join) if join.is_panic() => Err(Panic::from_payload(join.try_into_panic().ok())),
196 Err(_) => Err(Panic(None)),
197 }
198}
199
200impl Instance {
201 pub(crate) fn new(assembled: Assembled) -> Self {
202 let Assembled {
203 entries,
204 dependencies,
205 configs,
206 telemetry,
207 config,
208 service,
209 token,
210 halt,
211 instance_id,
212 grpc,
213 http,
214 in_process,
215 guards,
216 clients,
217 } = assembled;
218 let handles = dependencies.iter().map(Dependencies::handles).collect();
219 let info = Arc::new(InfoSource::new(
220 service,
221 entries,
222 handles,
223 configs,
224 telemetry.load(),
225 ));
226 Self {
227 info,
228 dependencies,
229 config,
230 telemetry: Arc::new(telemetry),
231 token,
232 halt,
233 listener: None,
234 grpc_listener: None,
235 transcoding_listener: None,
236 extra_listeners: Vec::new(),
237 grpc,
238 http,
239 in_process,
240 guards,
241 instance_id,
242 clients,
243 }
244 }
245
246 pub fn state(&self) -> State {
248 self.info.state()
249 }
250
251 pub fn snapshot(&self) -> crate::snapshot::Snapshot {
253 self.info.snapshot()
254 }
255
256 pub fn address(&self) -> Option<SocketAddr> {
258 self.listener.as_ref().map(Listener::address)
259 }
260
261 pub fn grpc_address(&self) -> Option<SocketAddr> {
263 self.grpc_listener.as_ref().map(Listener::address)
264 }
265
266 pub fn surface_address(&self, what: &str) -> Option<SocketAddr> {
268 self.http.address(what)
269 }
270
271 pub fn stopper(&self) -> Stopper {
273 Stopper::new(self.halt.clone())
274 }
275
276 pub fn apoptosis(&self) -> Apoptosis {
278 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone())
279 }
280
281 pub fn logging(&self) -> Logging {
283 self.telemetry.logging()
284 }
285
286 pub async fn start(&mut self) -> Result<(), Error> {
289 if self.state() != State::Built {
290 return Err(Error::State {
291 action: "be started",
292 });
293 }
294 self.info.set_state(State::Starting);
295 self.info.mark_started();
296 self.start_load_average();
297 let compression = self
298 .config
299 .rest()
300 .map_or(1024, crate::rest_config::RestConfig::compression_threshold);
301 let concurrent_limit = self.config.rest().map_or(
302 128,
303 crate::rest_config::RestConfig::concurrent_requests_limit,
304 );
305 let grpc_config = self.config.grpc().cloned();
306 let mut surfaces = self.http.take();
307 if let Some(grpc) = &grpc_config
308 && let Some(surface) = surfaces.iter().find(|surface| surface.port == grpc.port())
309 {
310 let error = Error::Surface {
311 what: surface.what,
312 reason: format!(
313 "the port {} is the gRPC listener port; choose another port",
314 grpc.port()
315 ),
316 };
317 return Err(self.failed(error).await);
318 }
319 let grpc_router = match self.assemble_grpc(grpc_config.as_ref()).await {
320 Ok(router) => router,
321 Err(error) => return Err(self.failed(error).await),
322 };
323 if let Some(grpc) = &grpc_config {
324 match Listener::bind(grpc.host(), grpc.port(), grpc_router.clone(), "gRPC").await {
325 Ok(listener) => self.grpc_listener = Some(listener),
326 Err(source) => {
327 let error = Error::Bind {
328 address: format!("{}:{}", grpc.host(), grpc.port()),
329 source,
330 };
331 return Err(self.failed(error).await);
332 }
333 }
334 }
335 let transcoding = grpc_config.as_ref().and_then(|grpc| grpc.transcoding());
336 let transcoder = match self.build_transcoder(transcoding, &grpc_router) {
337 Ok(transcoder) => transcoder,
338 Err(error) => return Err(self.failed(error).await),
339 };
340 let documents = transcoding
341 .filter(|config| config.enable_open_api())
342 .map(|_| self.grpc.openapi_documents())
343 .filter(|documents| !documents.is_empty());
344 let rest = self.config.rest().cloned();
345 let shared_port = match (&rest, transcoding) {
346 (Some(rest), Some(config)) if transcoder.is_some() && config.port() == rest.port() => {
347 let host = grpc_config
348 .as_ref()
349 .map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
350 if host != rest.host() {
351 let error = Error::Rest {
352 source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
353 "the gRPC host '{host}' and the REST host '{}' must match on a shared port",
354 rest.host()
355 ))),
356 };
357 return Err(self.failed(error).await);
358 }
359 true
360 }
361 _ => false,
362 };
363 if let Some(rest) = &rest {
364 if let Err(error) = host_mismatch(&surfaces, rest.host(), rest.port()) {
365 return Err(self.failed(error).await);
366 }
367 let routes = Routes {
368 snapshot: self.snapshot_source(),
369 telemetry: Arc::clone(&self.telemetry),
370 info: Arc::clone(&self.info),
371 };
372 let mut router = crate::routes::router(routes);
373 if let Some(transcoder) = &transcoder {
374 let conflicts = transcoder.conflicts(NATIVE_PATHS);
375 if conflicts.is_empty() {
376 router = router.fallback(fallback(Arc::clone(transcoder)));
379 if shared_port && let Some(documents) = &documents {
380 router = with_openapi(router, documents.clone());
381 }
382 } else if shared_port {
383 let mut text = String::new();
384 for conflict in &conflicts {
385 text.push_str(&format!(
386 "\n '{}' overlaps the native path '{}'",
387 conflict.route(),
388 conflict.native()
389 ));
390 }
391 let error = Error::Rest {
392 source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
393 "the transcoding routes overlap native REST paths:{text}"
394 ))),
395 };
396 return Err(self.failed(error).await);
397 } else {
398 tracing::warn!(
399 routes = ?conflicts
400 .iter()
401 .map(|conflict| conflict.route())
402 .collect::<Vec<_>>(),
403 "transcoding routes overlap native REST paths: they are served only on \
404 the transcoding port"
405 );
406 }
407 }
408 let matched = take_address(&mut surfaces, rest.host(), rest.port());
409 let router = match merge_surfaces(router, &matched) {
410 Ok(router) => router,
411 Err(error) => return Err(self.failed(error).await),
412 };
413 let router = crate::http::wrap(router, compression, concurrent_limit);
414 match Listener::bind(rest.host(), rest.port(), router, "REST").await {
415 Ok(listener) => {
416 self.http.set_addresses(&matched, listener.address());
417 self.listener = Some(listener);
418 }
419 Err(source) => {
420 let error = Error::Bind {
421 address: format!("{}:{}", rest.host(), rest.port()),
422 source,
423 };
424 return Err(self.failed(error).await);
425 }
426 }
427 }
428 if let Some(transcoder) = transcoder.filter(|_| !shared_port) {
429 let port = transcoding.map_or(8081, redup_bootstrap_rest::TranscodingConfig::port);
430 let host = grpc_config
431 .as_ref()
432 .map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
433 if let Err(error) = host_mismatch(&surfaces, host, port) {
434 return Err(self.failed(error).await);
435 }
436 let mut router = axum::Router::new().fallback(fallback(transcoder));
437 if let Some(documents) = &documents {
438 router = with_openapi(router, documents.clone());
439 }
440 let matched = take_address(&mut surfaces, host, port);
441 let router = match merge_surfaces(router, &matched) {
442 Ok(router) => router,
443 Err(error) => return Err(self.failed(error).await),
444 };
445 let router = crate::http::wrap(router, compression, concurrent_limit);
446 match Listener::bind(host, port, router, "transcoding").await {
447 Ok(listener) => {
448 self.http.set_addresses(&matched, listener.address());
449 self.transcoding_listener = Some(listener);
450 }
451 Err(source) => {
452 let error = Error::Bind {
453 address: format!("{host}:{port}"),
454 source,
455 };
456 return Err(self.failed(error).await);
457 }
458 }
459 }
460 if let Err(error) = self
461 .start_extra_surfaces(surfaces, compression, concurrent_limit)
462 .await
463 {
464 return Err(self.failed(error).await);
465 }
466 let entries: Vec<(std::sync::Arc<dyn crate::runtime::Runtime>, &'static str)> = self
467 .info
468 .modules()
469 .iter()
470 .map(|entry| (Arc::clone(&entry.module), entry.name))
471 .collect();
472 for (module, name) in entries {
473 match isolated(module.start()).await {
474 Ok(Ok(())) => {
475 tracing::info!(module = name, "module started");
476 }
477 Ok(Err(source)) => {
478 tracing::error!(module = name, error = %source, "module failed to start");
479 self.release().await;
480 self.info.set_state(State::Failed);
481 return Err(Error::Start {
482 module: name,
483 source,
484 });
485 }
486 Err(panic) => {
487 tracing::warn!(
489 module = name,
490 error = %panic,
491 "module failed to start after a panic recorded above"
492 );
493 self.release().await;
494 self.info.set_state(State::Failed);
495 return Err(Error::Start {
496 module: name,
497 source: Box::new(panic),
498 });
499 }
500 }
501 }
502 self.info.set_state(State::Running);
503 tracing::info!(
504 service = self.info.service().name(),
505 version = self.info.service().version(),
506 modules = self.info.modules().len(),
507 "the instance is running"
508 );
509 Ok(())
510 }
511
512 pub async fn stop(&mut self) {
516 if matches!(self.state(), State::Stopping | State::Stopped) {
517 return;
518 }
519 let running = self.state() == State::Running;
520 self.info.set_state(State::Stopping);
521 if running {
522 self.drain().await;
523 }
524 self.finish().await;
525 }
526
527 async fn stop_fatal(&mut self) {
530 self.stop_without_drain().await;
531 }
532
533 async fn stop_without_drain(&mut self) {
535 if matches!(self.state(), State::Stopping | State::Stopped) {
536 return;
537 }
538 self.info.set_state(State::Stopping);
539 self.finish().await;
540 }
541
542 async fn finish(&mut self) {
544 self.release().await;
545 self.info.set_state(State::Stopped);
546 tracing::info!("the instance is stopped");
547 #[cfg(feature = "otlp")]
548 self.telemetry.finish();
549 }
550
551 pub async fn run(mut self) -> ExitCode {
555 if let Err(error) = self.start().await {
556 tracing::error!(error = %error, "the instance failed to start");
557 return ExitCode::from(1);
558 }
559 self.listen_to_signals();
560 match self.halt.wait().await {
561 Stop::Fatal(reason) => {
562 fatal!(
563 reason = reason.as_str(),
564 "the service stops on a fatal report: continuing may corrupt data"
565 );
566 self.stop_fatal().await;
567 ExitCode::from(1)
568 }
569 Stop::Apoptosis(reason) => self.apoptose(reason).await,
570 Stop::Signal | Stop::Request(_) => {
571 self.stop().await;
572 ExitCode::SUCCESS
573 }
574 Stop::RequestFast(_) => {
575 tracing::info!("the instance stops on request without draining");
576 self.stop_without_drain().await;
577 ExitCode::SUCCESS
578 }
579 }
580 }
581
582 fn listen_to_signals(&self) {
583 let halt = self.halt.clone();
584 tokio::spawn(async move {
585 if let Err(error) = signals::terminate().await {
586 tracing::error!(
587 error = %error,
588 "termination signals are not being listened to; the instance can be stopped \
589 only by a request"
590 );
591 return;
592 }
593 if halt.stop(Stop::Signal) {
594 tracing::info!(
595 "termination signal received: the instance is stopping. A repeated signal \
596 exits the process immediately"
597 );
598 let _ = signals::terminate().await;
599 }
600 std::process::exit(130);
601 });
602 }
603
604 fn build_transcoder(
606 &self,
607 config: Option<TranscodingConfig>,
608 grpc: &axum::Router,
609 ) -> Result<Option<Arc<Transcoder>>, Error> {
610 let Some(config) = config else {
611 return Ok(None);
612 };
613 let routes = self.grpc.http_routes();
614 if routes.is_empty() {
615 return Ok(None);
616 }
617 let timeout = self
618 .config
619 .grpc()
620 .map_or(std::time::Duration::from_secs(15), |grpc| {
621 grpc.default_time_out()
622 });
623 let transcoder = Transcoder::build(
624 routes,
625 self.grpc.descriptors(),
626 config,
627 grpc.clone(),
628 timeout,
629 )
630 .map_err(|source| Error::Rest {
631 source: Box::new(source),
632 })?;
633 Ok(Some(Arc::new(transcoder)))
634 }
635
636 async fn failed(&mut self, error: Error) -> Error {
638 tracing::error!(error = %error, "the instance failed to start");
639 self.release().await;
640 self.info.set_state(State::Failed);
641 error
642 }
643
644 async fn assemble_grpc(
647 &mut self,
648 config: Option<&crate::grpc_config::GrpcConfig>,
649 ) -> Result<axum::Router, Error> {
650 let mut names: Vec<String> = self
651 .grpc
652 .services()
653 .iter()
654 .map(|service| service.name().to_owned())
655 .collect();
656 for name in [
657 "grpc.health.v1.Health",
658 "redup.bootstrap.v1.Info",
659 "redup.bootstrap.v1.Metrics",
660 "redup.bootstrap.v1.Control",
661 "grpc.reflection.v1.ServerReflection",
662 "grpc.reflection.v1alpha.ServerReflection",
663 ] {
664 names.push(name.to_owned());
665 }
666 let dumps = Arc::new(DumpRegistry::new());
667 let services = PlatformServices {
668 health: Arc::new(providers::HealthState::new(Arc::clone(&self.info), names)),
669 info: Arc::new(providers::InfoState::new(
670 Arc::clone(&self.info),
671 self.grpc.services(),
672 )),
673 metrics: Arc::new(providers::MetricsState::new(
674 Arc::clone(&self.info),
675 Arc::clone(&self.telemetry),
676 )),
677 control: Arc::new(providers::ControlState::new(
678 Stopper::new(self.halt.clone()),
679 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone()),
680 self.telemetry.logging(),
681 self.token.child_token(),
682 Arc::clone(&dumps),
683 Arc::clone(&self.clients),
684 )),
685 };
686 bind_platform(&self.grpc, services).map_err(|source| Error::Grpc {
687 source: Box::new(source),
688 })?;
689 self.start_health_watch();
690 let types = Arc::new(MessageTypes::from_descriptors(&self.grpc.descriptors()));
691 let state = grpc_server::State {
692 binder: self.grpc.clone(),
693 telemetry: Arc::clone(&self.telemetry),
694 service_name: self.info.service().name().to_owned(),
695 instance_id: self.instance_id.clone(),
696 exposure: config.map_or_else(Default::default, |grpc| grpc.errors().exposure()),
697 debug_info: config.is_none_or(|grpc| grpc.errors().debug_info()),
698 token: self.token.child_token(),
699 guards: self.guards.all(),
700 dumps,
701 types,
702 };
703 let router = grpc_server::router(self.grpc.take_routes(), state);
704 let _ = self.in_process.set(router.clone());
705 Ok(router)
706 }
707
708 async fn start_extra_surfaces(
710 &mut self,
711 surfaces: Vec<Surface>,
712 compression: u64,
713 concurrent_limit: u32,
714 ) -> Result<(), Error> {
715 let mut groups: BTreeMap<(String, u16), Vec<Surface>> = BTreeMap::new();
716 for surface in surfaces {
717 groups
718 .entry((surface.host.clone(), surface.port))
719 .or_default()
720 .push(surface);
721 }
722 for ((host, port), group) in groups {
723 let mut router = axum::Router::new();
724 router = match merge_surfaces(router, &group) {
725 Ok(router) => router,
726 Err(error) => return Err(error),
727 };
728 let router = crate::http::wrap(router, compression, concurrent_limit);
729 let what = group.first().map_or("integration", |surface| surface.what);
730 match Listener::bind(&host, port, router, what).await {
731 Ok(listener) => {
732 self.http.set_addresses(&group, listener.address());
733 self.extra_listeners.push(listener);
734 }
735 Err(source) => {
736 return Err(Error::Bind {
737 address: format!("{host}:{port}"),
738 source,
739 });
740 }
741 }
742 }
743 Ok(())
744 }
745
746 fn start_health_watch(&self) {
748 for entry in self.info.modules() {
749 let Some(health) = entry.health.clone() else {
750 continue;
751 };
752 let mut changes = health.subscribe();
753 let info = Arc::clone(&self.info);
754 let token = self.token.child_token();
755 tokio::spawn(async move {
756 loop {
757 tokio::select! {
758 _ = token.cancelled() => return,
759 changed = changes.changed() => {
760 if changed.is_err() {
761 return;
762 }
763 info.notify();
764 }
765 }
766 }
767 });
768 }
769 }
770
771 fn start_load_average(&self) {
773 let token = self.token.child_token();
774 let averages = self.telemetry.clone();
775 tokio::spawn(async move {
776 averages.run(token).await;
777 });
778 }
779
780 fn snapshot_source(&self) -> crate::listener::SnapshotSource {
782 let info = Arc::clone(&self.info);
783 Arc::new(move || info.snapshot())
784 }
785
786 async fn drain(&self) {
789 let timeout = self.config.control().drain_timeout();
790 let mut tasks: Vec<(&'static str, JoinHandle<()>)> = Vec::new();
791 for entry in self.info.modules() {
792 let module = Arc::clone(&entry.module);
793 let name = entry.name;
794 tasks.push((
795 name,
796 tokio::spawn(async move {
797 match tokio::time::timeout(timeout, module.drain()).await {
798 Ok(Ok(())) => {}
799 Ok(Err(source)) => {
800 tracing::warn!(module = name, error = %source, "module failed to drain")
801 }
802 Err(_) => tracing::warn!(
803 module = name,
804 timeout = ?timeout,
805 "module did not finish draining within the drain timeout"
806 ),
807 }
808 }),
809 ));
810 }
811 for (name, task) in tasks {
812 if task.await.is_err() {
813 tracing::warn!(module = name, "module panicked while draining");
814 }
815 }
816 }
817
818 async fn stop_modules(&self, timeout: Option<Duration>) {
821 let stopping = async {
822 for entry in self.info.modules().iter().rev() {
823 let module = Arc::clone(&entry.module);
824 let name = entry.name;
825 match isolated(module.stop()).await {
826 Ok(Ok(())) => {}
827 Ok(Err(source)) => {
828 tracing::error!(module = name, error = %source, "module failed to stop")
829 }
830 Err(panic) => {
831 tracing::warn!(
832 module = name,
833 error = %panic,
834 "module failed to stop after a panic recorded above"
835 );
836 }
837 }
838 }
839 };
840 match timeout {
841 None => stopping.await,
842 Some(limit) => {
843 if tokio::time::timeout(limit, stopping).await.is_err() {
844 tracing::warn!(
845 limit = ?limit,
846 "modules did not stop within the timeout; proceeding without them"
847 );
848 }
849 }
850 }
851 }
852
853 async fn release(&mut self) {
856 self.token.cancel();
857 self.stop_modules(None).await;
858 for dependencies in &mut self.dependencies {
859 dependencies.shutdown().await;
860 }
861 if let Some(listener) = self.listener.take() {
862 listener.shutdown().await;
863 }
864 if let Some(listener) = self.grpc_listener.take() {
865 listener.shutdown().await;
866 }
867 if let Some(listener) = self.transcoding_listener.take() {
868 listener.shutdown().await;
869 }
870 for listener in std::mem::take(&mut self.extra_listeners) {
871 listener.shutdown().await;
872 }
873 }
874
875 async fn apoptose(&mut self, reason: String) -> ExitCode {
878 fatal!(
879 reason,
880 memory = memory::resident_bytes(),
881 limit = memory::container_limit(),
882 "apoptosis: the service cannot recover from the memory shortage and will be unloaded"
883 );
884 self.info.set_state(State::Stopping);
885 let timeout = self
886 .config
887 .control()
888 .oom()
889 .map(|oom| oom.modules_shutdown_timeout());
890 self.token.cancel();
891 self.stop_modules(timeout).await;
892 for dependencies in &mut self.dependencies {
893 dependencies.shutdown().await;
894 }
895 let Some(limit) = memory::container_limit() else {
896 tracing::error!("the container has no memory limit; the process exits with code 137");
897 return ExitCode::from(137);
898 };
899 let mut target = limit;
900 loop {
901 match memory::inflate(target).await {
902 Ok(()) => target = target.saturating_add(INFLATION_STEP),
903 Err(error) => {
904 tracing::error!(
905 %error,
906 "memory inflation stopped before the limit; the process exits with code 137"
907 );
908 return ExitCode::from(137);
909 }
910 }
911 }
912 }
913}