1use std::future::Future;
4use std::net::SocketAddr;
5use std::process::ExitCode;
6use std::sync::Arc;
7use std::time::Duration;
8
9use axum::response::IntoResponse as _;
10use tokio::task::JoinHandle;
11use tokio_util::sync::CancellationToken;
12
13use redup_bootstrap_grpc::{Binder, OpenApiDocument, PlatformServices, bind_platform};
14use redup_bootstrap_rest::{BuildError, Transcoder, TranscodingConfig};
15
16use crate::apoptosis::Apoptosis;
17use crate::bootstrap_config::BootstrapConfig;
18use crate::builder::Assembled;
19use crate::dependency::Dependencies;
20use crate::error::Error;
21use crate::grpc_server::{self, providers};
22use crate::halt::{Halt, Stop};
23use crate::info_source::InfoSource;
24use crate::listener::{Listener, Routes};
25use crate::memory;
26use crate::panic_error::Panic;
27use crate::signals;
28use crate::stopper::Stopper;
29use crate::telemetry::Telemetry;
30use crate::telemetry::journal::{Logging, fatal};
31
32const INFLATION_STEP: u64 = 256 * 1024 * 1024;
34
35const NATIVE_PATHS: &[&str] = &[
37 "/readyz",
38 "/health",
39 "/healthz",
40 "/readyz/{name}",
41 "/livez",
42 "/livez/{name}",
43 "/metrics",
44 "/info",
45 "/info/{name}",
46 "/config",
47 "/config/{name}",
48 "/openapi/{file}",
49];
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum State {
54 Built,
56 Starting,
58 Running,
60 Stopping,
62 Stopped,
64 Failed,
66}
67
68pub struct Instance {
73 info: Arc<InfoSource>,
74 dependencies: Vec<Dependencies>,
75 config: BootstrapConfig,
76 telemetry: Arc<Telemetry>,
77 token: CancellationToken,
78 halt: Halt,
79 listener: Option<Listener>,
80 grpc_listener: Option<Listener>,
81 transcoding_listener: Option<Listener>,
82 grpc: Binder,
83 instance_id: String,
84}
85
86fn with_openapi(router: axum::Router, documents: Vec<OpenApiDocument>) -> axum::Router {
88 let documents: std::collections::HashMap<&'static str, &'static str> = documents
89 .into_iter()
90 .map(|document| (document.name(), document.json()))
91 .collect();
92 let documents = Arc::new(documents);
93 let handler = move |axum::extract::Path(file): axum::extract::Path<String>| {
94 let documents = Arc::clone(&documents);
95 async move {
96 let Some(name) = file.strip_suffix(".json") else {
97 return (axum::http::StatusCode::NOT_FOUND, "Not found").into_response();
98 };
99 match documents.get(name) {
100 Some(json) => (
101 [(
102 axum::http::header::CONTENT_TYPE,
103 "application/json; charset=utf-8",
104 )],
105 *json,
106 )
107 .into_response(),
108 None => (axum::http::StatusCode::NOT_FOUND, "Not found").into_response(),
109 }
110 }
111 };
112 router.route("/openapi/{file}", axum::routing::get(handler))
113}
114
115fn fallback(
117 transcoder: Arc<Transcoder>,
118) -> impl Fn(
119 axum::extract::Request,
120) -> futures_util::future::BoxFuture<'static, axum::response::Response>
121+ Clone
122+ Send
123+ Sync
124+ 'static {
125 move |request| {
126 let transcoder = Arc::clone(&transcoder);
127 Box::pin(async move { transcoder.handle(request).await })
128 }
129}
130
131async fn isolated<T, F>(point: F) -> Result<T, Panic>
133where
134 F: Future<Output = T> + Send + 'static,
135 T: Send + 'static,
136{
137 match tokio::spawn(point).await {
138 Ok(value) => Ok(value),
139 Err(join) if join.is_panic() => Err(Panic::from_payload(join.try_into_panic().ok())),
140 Err(_) => Err(Panic(None)),
141 }
142}
143
144impl Instance {
145 pub(crate) fn new(assembled: Assembled) -> Self {
146 let Assembled {
147 entries,
148 dependencies,
149 configs,
150 telemetry,
151 config,
152 service,
153 token,
154 halt,
155 instance_id,
156 grpc,
157 } = assembled;
158 let handles = dependencies.iter().map(Dependencies::handles).collect();
159 let info = Arc::new(InfoSource::new(
160 service,
161 entries,
162 handles,
163 configs,
164 telemetry.load(),
165 ));
166 Self {
167 info,
168 dependencies,
169 config,
170 telemetry: Arc::new(telemetry),
171 token,
172 halt,
173 listener: None,
174 grpc_listener: None,
175 transcoding_listener: None,
176 grpc,
177 instance_id,
178 }
179 }
180
181 pub fn state(&self) -> State {
183 self.info.state()
184 }
185
186 pub fn snapshot(&self) -> crate::snapshot::Snapshot {
188 self.info.snapshot()
189 }
190
191 pub fn address(&self) -> Option<SocketAddr> {
193 self.listener.as_ref().map(Listener::address)
194 }
195
196 pub fn grpc_address(&self) -> Option<SocketAddr> {
198 self.grpc_listener.as_ref().map(Listener::address)
199 }
200
201 pub fn stopper(&self) -> Stopper {
203 Stopper::new(self.halt.clone())
204 }
205
206 pub fn apoptosis(&self) -> Apoptosis {
208 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone())
209 }
210
211 pub fn logging(&self) -> Logging {
213 self.telemetry.logging()
214 }
215
216 pub async fn start(&mut self) -> Result<(), Error> {
219 if self.state() != State::Built {
220 return Err(Error::State {
221 action: "be started",
222 });
223 }
224 self.info.set_state(State::Starting);
225 self.info.mark_started();
226 self.start_load_average();
227 let compression = self
228 .config
229 .rest()
230 .map_or(1024, crate::rest_config::RestConfig::compression_threshold);
231 let concurrent_limit = self.config.rest().map_or(
232 128,
233 crate::rest_config::RestConfig::concurrent_requests_limit,
234 );
235 let grpc_config = self.config.grpc().cloned();
236 let grpc_router = match &grpc_config {
237 Some(grpc) => match self.start_grpc(grpc).await {
238 Ok(router) => Some(router),
239 Err(error) => return Err(self.failed(error).await),
240 },
241 None => None,
242 };
243 let transcoding = grpc_config.as_ref().and_then(|grpc| grpc.transcoding());
244 let transcoder = match self.build_transcoder(transcoding, grpc_router.as_ref()) {
245 Ok(transcoder) => transcoder,
246 Err(error) => return Err(self.failed(error).await),
247 };
248 let documents = transcoding
249 .filter(|config| config.enable_open_api())
250 .map(|_| self.grpc.openapi_documents())
251 .filter(|documents| !documents.is_empty());
252 let rest = self.config.rest().cloned();
253 let shared_port = match (&rest, transcoding) {
254 (Some(rest), Some(config)) if transcoder.is_some() && config.port() == rest.port() => {
255 let host = grpc_config
256 .as_ref()
257 .map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
258 if host != rest.host() {
259 let error = Error::Rest {
260 source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
261 "the gRPC host '{host}' and the REST host '{}' must match on a shared port",
262 rest.host()
263 ))),
264 };
265 return Err(self.failed(error).await);
266 }
267 true
268 }
269 _ => false,
270 };
271 if let Some(rest) = &rest {
272 let routes = Routes {
273 snapshot: self.snapshot_source(),
274 telemetry: Arc::clone(&self.telemetry),
275 info: Arc::clone(&self.info),
276 };
277 let mut router = crate::routes::router(routes);
278 if let Some(transcoder) = &transcoder {
279 let conflicts = transcoder.conflicts(NATIVE_PATHS);
280 if conflicts.is_empty() {
281 router = router.fallback(fallback(Arc::clone(transcoder)));
284 if shared_port && let Some(documents) = &documents {
285 router = with_openapi(router, documents.clone());
286 }
287 } else if shared_port {
288 let mut text = String::new();
289 for conflict in &conflicts {
290 text.push_str(&format!(
291 "\n '{}' overlaps the native path '{}'",
292 conflict.route(),
293 conflict.native()
294 ));
295 }
296 let error = Error::Rest {
297 source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
298 "the transcoding routes overlap native REST paths:{text}"
299 ))),
300 };
301 return Err(self.failed(error).await);
302 } else {
303 tracing::warn!(
304 routes = ?conflicts
305 .iter()
306 .map(|conflict| conflict.route())
307 .collect::<Vec<_>>(),
308 "transcoding routes overlap native REST paths: they are served only on \
309 the transcoding port"
310 );
311 }
312 }
313 let router = crate::http::wrap(router, compression, concurrent_limit);
314 match Listener::bind(rest.host(), rest.port(), router, "REST").await {
315 Ok(listener) => self.listener = Some(listener),
316 Err(source) => {
317 let error = Error::Bind {
318 address: format!("{}:{}", rest.host(), rest.port()),
319 source,
320 };
321 return Err(self.failed(error).await);
322 }
323 }
324 }
325 if let Some(transcoder) = transcoder.filter(|_| !shared_port) {
326 let port = transcoding.map_or(8081, redup_bootstrap_rest::TranscodingConfig::port);
327 let host = grpc_config
328 .as_ref()
329 .map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
330 let mut router = axum::Router::new().fallback(fallback(transcoder));
331 if let Some(documents) = &documents {
332 router = with_openapi(router, documents.clone());
333 }
334 let router = crate::http::wrap(router, compression, concurrent_limit);
335 match Listener::bind(host, port, router, "transcoding").await {
336 Ok(listener) => self.transcoding_listener = Some(listener),
337 Err(source) => {
338 let error = Error::Bind {
339 address: format!("{host}:{port}"),
340 source,
341 };
342 return Err(self.failed(error).await);
343 }
344 }
345 }
346 let entries: Vec<(std::sync::Arc<dyn crate::runtime::Runtime>, &'static str)> = self
347 .info
348 .modules()
349 .iter()
350 .map(|entry| (Arc::clone(&entry.module), entry.name))
351 .collect();
352 for (module, name) in entries {
353 match isolated(module.start()).await {
354 Ok(Ok(())) => {
355 tracing::info!(module = name, "module started");
356 }
357 Ok(Err(source)) => {
358 tracing::error!(module = name, error = %source, "module failed to start");
359 self.release().await;
360 self.info.set_state(State::Failed);
361 return Err(Error::Start {
362 module: name,
363 source,
364 });
365 }
366 Err(panic) => {
367 tracing::warn!(
369 module = name,
370 error = %panic,
371 "module failed to start after a panic recorded above"
372 );
373 self.release().await;
374 self.info.set_state(State::Failed);
375 return Err(Error::Start {
376 module: name,
377 source: Box::new(panic),
378 });
379 }
380 }
381 }
382 self.info.set_state(State::Running);
383 tracing::info!(
384 service = self.info.service().name(),
385 version = self.info.service().version(),
386 modules = self.info.modules().len(),
387 "the instance is running"
388 );
389 Ok(())
390 }
391
392 pub async fn stop(&mut self) {
396 if matches!(self.state(), State::Stopping | State::Stopped) {
397 return;
398 }
399 let running = self.state() == State::Running;
400 self.info.set_state(State::Stopping);
401 if running {
402 self.drain().await;
403 }
404 self.finish().await;
405 }
406
407 async fn stop_fatal(&mut self) {
410 self.stop_without_drain().await;
411 }
412
413 async fn stop_without_drain(&mut self) {
415 if matches!(self.state(), State::Stopping | State::Stopped) {
416 return;
417 }
418 self.info.set_state(State::Stopping);
419 self.finish().await;
420 }
421
422 async fn finish(&mut self) {
424 self.release().await;
425 self.info.set_state(State::Stopped);
426 tracing::info!("the instance is stopped");
427 #[cfg(feature = "otlp")]
428 self.telemetry.finish();
429 }
430
431 pub async fn run(mut self) -> ExitCode {
435 if let Err(error) = self.start().await {
436 tracing::error!(error = %error, "the instance failed to start");
437 return ExitCode::from(1);
438 }
439 self.listen_to_signals();
440 match self.halt.wait().await {
441 Stop::Fatal(reason) => {
442 fatal!(
443 reason = reason.as_str(),
444 "the service stops on a fatal report: continuing may corrupt data"
445 );
446 self.stop_fatal().await;
447 ExitCode::from(1)
448 }
449 Stop::Apoptosis(reason) => self.apoptose(reason).await,
450 Stop::Signal | Stop::Request(_) => {
451 self.stop().await;
452 ExitCode::SUCCESS
453 }
454 Stop::RequestFast(_) => {
455 tracing::info!("the instance stops on request without draining");
456 self.stop_without_drain().await;
457 ExitCode::SUCCESS
458 }
459 }
460 }
461
462 fn listen_to_signals(&self) {
463 let halt = self.halt.clone();
464 tokio::spawn(async move {
465 if let Err(error) = signals::terminate().await {
466 tracing::error!(
467 error = %error,
468 "termination signals are not being listened to; the instance can be stopped \
469 only by a request"
470 );
471 return;
472 }
473 if halt.stop(Stop::Signal) {
474 tracing::info!(
475 "termination signal received: the instance is stopping. A repeated signal \
476 exits the process immediately"
477 );
478 let _ = signals::terminate().await;
479 }
480 std::process::exit(130);
481 });
482 }
483
484 fn build_transcoder(
486 &self,
487 config: Option<TranscodingConfig>,
488 grpc: Option<&axum::Router>,
489 ) -> Result<Option<Arc<Transcoder>>, Error> {
490 let Some(config) = config else {
491 return Ok(None);
492 };
493 let routes = self.grpc.http_routes();
494 if routes.is_empty() {
495 return Ok(None);
496 }
497 let Some(grpc) = grpc else {
498 return Err(Error::Rest {
499 source: Box::new(BuildError::new(
500 "transcoding is configured, but the grpc section is absent",
501 )),
502 });
503 };
504 let timeout = self
505 .config
506 .grpc()
507 .map_or(std::time::Duration::from_secs(15), |grpc| {
508 grpc.default_time_out()
509 });
510 let transcoder = Transcoder::build(
511 routes,
512 self.grpc.descriptors(),
513 config,
514 grpc.clone(),
515 timeout,
516 )
517 .map_err(|source| Error::Rest {
518 source: Box::new(source),
519 })?;
520 Ok(Some(Arc::new(transcoder)))
521 }
522
523 async fn failed(&mut self, error: Error) -> Error {
525 tracing::error!(error = %error, "the instance failed to start");
526 self.release().await;
527 self.info.set_state(State::Failed);
528 error
529 }
530
531 async fn start_grpc(
534 &mut self,
535 config: &crate::grpc_config::GrpcConfig,
536 ) -> Result<axum::Router, Error> {
537 let mut names: Vec<String> = self
538 .grpc
539 .services()
540 .iter()
541 .map(|service| service.name().to_owned())
542 .collect();
543 for name in [
544 "grpc.health.v1.Health",
545 "redup.bootstrap.v1.Info",
546 "redup.bootstrap.v1.Metrics",
547 "redup.bootstrap.v1.Control",
548 "grpc.reflection.v1.ServerReflection",
549 "grpc.reflection.v1alpha.ServerReflection",
550 ] {
551 names.push(name.to_owned());
552 }
553 let services = PlatformServices {
554 health: Arc::new(providers::HealthState::new(Arc::clone(&self.info), names)),
555 info: Arc::new(providers::InfoState::new(
556 Arc::clone(&self.info),
557 self.grpc.services(),
558 )),
559 metrics: Arc::new(providers::MetricsState::new(
560 Arc::clone(&self.info),
561 Arc::clone(&self.telemetry),
562 )),
563 control: Arc::new(providers::ControlState::new(
564 Stopper::new(self.halt.clone()),
565 Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone()),
566 self.telemetry.logging(),
567 self.token.child_token(),
568 )),
569 };
570 bind_platform(&self.grpc, services).map_err(|source| Error::Grpc {
571 source: Box::new(source),
572 })?;
573 self.start_health_watch();
574 let state = grpc_server::State {
575 binder: self.grpc.clone(),
576 telemetry: Arc::clone(&self.telemetry),
577 service_name: self.info.service().name().to_owned(),
578 instance_id: self.instance_id.clone(),
579 exposure: config.errors().exposure(),
580 debug_info: config.errors().debug_info(),
581 token: self.token.child_token(),
582 };
583 let router = grpc_server::router(self.grpc.take_routes(), state);
584 let listener = Listener::bind(config.host(), config.port(), router.clone(), "gRPC")
585 .await
586 .map_err(|source| Error::Bind {
587 address: format!("{}:{}", config.host(), config.port()),
588 source,
589 })?;
590 self.grpc_listener = Some(listener);
591 Ok(router)
592 }
593
594 fn start_health_watch(&self) {
596 for entry in self.info.modules() {
597 let Some(health) = entry.health.clone() else {
598 continue;
599 };
600 let mut changes = health.subscribe();
601 let info = Arc::clone(&self.info);
602 let token = self.token.child_token();
603 tokio::spawn(async move {
604 loop {
605 tokio::select! {
606 _ = token.cancelled() => return,
607 changed = changes.changed() => {
608 if changed.is_err() {
609 return;
610 }
611 info.notify();
612 }
613 }
614 }
615 });
616 }
617 }
618
619 fn start_load_average(&self) {
621 let token = self.token.child_token();
622 let averages = self.telemetry.clone();
623 tokio::spawn(async move {
624 averages.run(token).await;
625 });
626 }
627
628 fn snapshot_source(&self) -> crate::listener::SnapshotSource {
630 let info = Arc::clone(&self.info);
631 Arc::new(move || info.snapshot())
632 }
633
634 async fn drain(&self) {
637 let timeout = self.config.control().drain_timeout();
638 let mut tasks: Vec<(&'static str, JoinHandle<()>)> = Vec::new();
639 for entry in self.info.modules() {
640 let module = Arc::clone(&entry.module);
641 let name = entry.name;
642 tasks.push((
643 name,
644 tokio::spawn(async move {
645 match tokio::time::timeout(timeout, module.drain()).await {
646 Ok(Ok(())) => {}
647 Ok(Err(source)) => {
648 tracing::warn!(module = name, error = %source, "module failed to drain")
649 }
650 Err(_) => tracing::warn!(
651 module = name,
652 timeout = ?timeout,
653 "module did not finish draining within the drain timeout"
654 ),
655 }
656 }),
657 ));
658 }
659 for (name, task) in tasks {
660 if task.await.is_err() {
661 tracing::warn!(module = name, "module panicked while draining");
662 }
663 }
664 }
665
666 async fn stop_modules(&self, timeout: Option<Duration>) {
669 let stopping = async {
670 for entry in self.info.modules().iter().rev() {
671 let module = Arc::clone(&entry.module);
672 let name = entry.name;
673 match isolated(module.stop()).await {
674 Ok(Ok(())) => {}
675 Ok(Err(source)) => {
676 tracing::error!(module = name, error = %source, "module failed to stop")
677 }
678 Err(panic) => {
679 tracing::warn!(
680 module = name,
681 error = %panic,
682 "module failed to stop after a panic recorded above"
683 );
684 }
685 }
686 }
687 };
688 match timeout {
689 None => stopping.await,
690 Some(limit) => {
691 if tokio::time::timeout(limit, stopping).await.is_err() {
692 tracing::warn!(
693 limit = ?limit,
694 "modules did not stop within the timeout; proceeding without them"
695 );
696 }
697 }
698 }
699 }
700
701 async fn release(&mut self) {
704 self.token.cancel();
705 self.stop_modules(None).await;
706 for dependencies in &mut self.dependencies {
707 dependencies.shutdown().await;
708 }
709 if let Some(listener) = self.listener.take() {
710 listener.shutdown().await;
711 }
712 if let Some(listener) = self.grpc_listener.take() {
713 listener.shutdown().await;
714 }
715 if let Some(listener) = self.transcoding_listener.take() {
716 listener.shutdown().await;
717 }
718 }
719
720 async fn apoptose(&mut self, reason: String) -> ExitCode {
723 fatal!(
724 reason,
725 memory = memory::resident_bytes(),
726 limit = memory::container_limit(),
727 "apoptosis: the service cannot recover from the memory shortage and will be unloaded"
728 );
729 self.info.set_state(State::Stopping);
730 let timeout = self
731 .config
732 .control()
733 .oom()
734 .map(|oom| oom.modules_shutdown_timeout());
735 self.token.cancel();
736 self.stop_modules(timeout).await;
737 for dependencies in &mut self.dependencies {
738 dependencies.shutdown().await;
739 }
740 let Some(limit) = memory::container_limit() else {
741 tracing::error!("the container has no memory limit; the process exits with code 137");
742 return ExitCode::from(137);
743 };
744 let mut target = limit;
745 loop {
746 match memory::inflate(target).await {
747 Ok(()) => target = target.saturating_add(INFLATION_STEP),
748 Err(error) => {
749 tracing::error!(
750 %error,
751 "memory inflation stopped before the limit; the process exits with code 137"
752 );
753 return ExitCode::from(137);
754 }
755 }
756 }
757 }
758}