1use std::collections::BTreeMap;
11use std::env;
12use std::ffi::OsStr;
13use std::fmt::Debug;
14use std::fs::Permissions;
15use std::future::Future;
16use std::net::{IpAddr, SocketAddr, TcpListener as StdTcpListener};
17use std::num::NonZero;
18use std::os::unix::fs::PermissionsExt;
19use std::os::unix::process::ExitStatusExt;
20use std::path::{Path, PathBuf};
21use std::process::{ExitStatus, Stdio};
22use std::str::FromStr;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Mutex};
25
26use anyhow::{Context, anyhow, bail};
27use async_stream::stream;
28use async_trait::async_trait;
29use chrono::{DateTime, Utc};
30use futures::StreamExt;
31use futures::stream::{BoxStream, FuturesUnordered};
32use itertools::Itertools;
33use maplit::btreemap;
34use mz_orchestrator::scheduling_config::ServiceSchedulingConfig;
35use mz_orchestrator::{
36 CpuLimit, DiskLimit, MemoryLimit, NamespacedOrchestrator, Orchestrator, Service,
37 ServiceAssignments, ServiceConfig, ServiceEvent, ServicePort, ServiceProcessMetrics,
38 ServiceStatus,
39};
40use mz_ore::cast::{CastFrom, TryCastFrom};
41use mz_ore::error::ErrorExt;
42use mz_ore::netio::UnixSocketAddr;
43use mz_ore::result::ResultExt;
44use mz_ore::task::AbortOnDropHandle;
45use nix::sys::signal::Signal;
46use scopeguard::defer;
47use serde::Serialize;
48use sha1::{Digest, Sha1};
49use sysinfo::{Pid, PidExt, Process, ProcessExt, ProcessRefreshKind, System, SystemExt};
50use tokio::fs::remove_dir_all;
51use tokio::net::{TcpListener, UnixStream};
52use tokio::process::{Child, Command};
53use tokio::sync::{broadcast, mpsc, oneshot};
54use tokio::time::{self, Duration};
55use tokio::{fs, io, select};
56use tracing::{debug, error, info, warn};
57
58pub mod secrets;
59
60#[derive(Debug, Clone)]
62pub struct ProcessOrchestratorConfig {
63 pub image_dir: PathBuf,
66 pub suppress_output: bool,
68 pub environment_id: String,
70 pub secrets_dir: PathBuf,
72 pub command_wrapper: Vec<String>,
74 pub propagate_crashes: bool,
76 pub tcp_proxy: Option<ProcessOrchestratorTcpProxyConfig>,
87 pub scratch_directory: PathBuf,
89}
90
91#[derive(Debug, Clone)]
95pub struct ProcessOrchestratorTcpProxyConfig {
96 pub listen_addr: IpAddr,
98 pub prometheus_service_discovery_dir: Option<PathBuf>,
108}
109
110#[derive(Debug)]
116pub struct ProcessOrchestrator {
117 image_dir: PathBuf,
118 suppress_output: bool,
119 namespaces: Mutex<BTreeMap<String, Arc<dyn NamespacedOrchestrator>>>,
120 metadata_dir: PathBuf,
121 secrets_dir: PathBuf,
122 command_wrapper: Vec<String>,
123 propagate_crashes: bool,
124 tcp_proxy: Option<ProcessOrchestratorTcpProxyConfig>,
125 scratch_directory: PathBuf,
126 launch_spec: LaunchSpec,
127}
128
129#[derive(Debug, Clone, Copy)]
130enum LaunchSpec {
131 Direct,
133 Systemd,
135}
136
137impl LaunchSpec {
138 fn determine_implementation() -> Result<Self, anyhow::Error> {
139 match Path::new("/run/systemd/system/").try_exists()? {
143 true => Ok(Self::Systemd),
144 false => Ok(Self::Direct),
145 }
146 }
147
148 fn refine_command(
149 &self,
150 image: impl AsRef<OsStr>,
151 args: &[impl AsRef<OsStr>],
152 wrapper: &[String],
153 memory_limit: Option<&MemoryLimit>,
154 cpu_limit: Option<&CpuLimit>,
155 ) -> Command {
156 let mut cmd = match self {
157 Self::Direct => {
158 if let Some((program, wrapper_args)) = wrapper.split_first() {
159 let mut cmd = Command::new(program);
160 cmd.args(wrapper_args);
161 cmd.arg(image);
162 cmd
163 } else {
164 Command::new(image)
165 }
166 }
167 Self::Systemd => {
168 let mut cmd = Command::new("systemd-run");
169 cmd.args(["--user", "--scope", "--quiet"]);
170 if let Some(memory_limit) = memory_limit {
171 let memory_limit = memory_limit.0.as_u64();
172 cmd.args(["-p", &format!("MemoryMax={memory_limit}")]);
173 }
175 if let Some(cpu_limit) = cpu_limit {
176 let cpu_limit = (cpu_limit.as_millicpus() + 9) / 10;
177 cmd.args(["-p", &format!("CPUQuota={cpu_limit}%")]);
178 }
179
180 cmd.args(wrapper);
181 cmd.arg(image);
182 cmd
183 }
184 };
185 cmd.args(args);
186 cmd
187 }
188}
189
190impl ProcessOrchestrator {
191 pub async fn new(
193 ProcessOrchestratorConfig {
194 image_dir,
195 suppress_output,
196 environment_id,
197 secrets_dir,
198 command_wrapper,
199 propagate_crashes,
200 tcp_proxy,
201 scratch_directory,
202 }: ProcessOrchestratorConfig,
203 ) -> Result<ProcessOrchestrator, anyhow::Error> {
204 let metadata_dir = env::temp_dir().join(format!("environmentd-{environment_id}"));
205 fs::create_dir_all(&metadata_dir)
206 .await
207 .context("creating metadata directory")?;
208 fs::create_dir_all(&secrets_dir)
209 .await
210 .context("creating secrets directory")?;
211 fs::set_permissions(&secrets_dir, Permissions::from_mode(0o700))
212 .await
213 .context("setting secrets directory permissions")?;
214 if let Some(prometheus_dir) = tcp_proxy
215 .as_ref()
216 .and_then(|p| p.prometheus_service_discovery_dir.as_ref())
217 {
218 fs::create_dir_all(&prometheus_dir)
219 .await
220 .context("creating prometheus directory")?;
221 }
222
223 let launch_spec = LaunchSpec::determine_implementation()?;
224 info!(driver = ?launch_spec, "Process orchestrator launch spec");
225
226 Ok(ProcessOrchestrator {
227 image_dir: fs::canonicalize(image_dir).await?,
228 suppress_output,
229 namespaces: Mutex::new(BTreeMap::new()),
230 metadata_dir: fs::canonicalize(metadata_dir).await?,
231 secrets_dir: fs::canonicalize(secrets_dir).await?,
232 command_wrapper,
233 propagate_crashes,
234 tcp_proxy,
235 scratch_directory,
236 launch_spec,
237 })
238 }
239}
240
241impl Orchestrator for ProcessOrchestrator {
242 fn namespace(&self, namespace: &str) -> Arc<dyn NamespacedOrchestrator> {
243 let mut namespaces = self.namespaces.lock().expect("lock poisoned");
244 Arc::clone(namespaces.entry(namespace.into()).or_insert_with(|| {
245 let config = Arc::new(NamespacedProcessOrchestratorConfig {
246 namespace: namespace.into(),
247 image_dir: self.image_dir.clone(),
248 suppress_output: self.suppress_output,
249 metadata_dir: self.metadata_dir.clone(),
250 command_wrapper: self.command_wrapper.clone(),
251 propagate_crashes: self.propagate_crashes,
252 tcp_proxy: self.tcp_proxy.clone(),
253 scratch_directory: self.scratch_directory.clone(),
254 launch_spec: self.launch_spec,
255 });
256
257 let services = Arc::new(Mutex::new(BTreeMap::new()));
258 let (service_event_tx, service_event_rx) = broadcast::channel(16384);
259 let (command_tx, command_rx) = mpsc::unbounded_channel();
260
261 let worker = OrchestratorWorker {
262 config: Arc::clone(&config),
263 services: Arc::clone(&services),
264 service_event_tx,
265 system: System::new(),
266 command_rx,
267 }
268 .spawn();
269
270 Arc::new(NamespacedProcessOrchestrator {
271 config,
272 services,
273 service_event_rx,
274 command_tx,
275 scheduling_config: Default::default(),
276 _worker: worker,
277 })
278 }))
279 }
280}
281
282#[derive(Debug)]
284struct NamespacedProcessOrchestratorConfig {
285 namespace: String,
286 image_dir: PathBuf,
287 suppress_output: bool,
288 metadata_dir: PathBuf,
289 command_wrapper: Vec<String>,
290 propagate_crashes: bool,
291 tcp_proxy: Option<ProcessOrchestratorTcpProxyConfig>,
292 scratch_directory: PathBuf,
293 launch_spec: LaunchSpec,
294}
295
296impl NamespacedProcessOrchestratorConfig {
297 fn full_id(&self, id: &str) -> String {
298 format!("{}-{}", self.namespace, id)
299 }
300
301 fn service_run_dir(&self, id: &str) -> PathBuf {
302 self.metadata_dir.join(&self.full_id(id))
303 }
304
305 fn service_scratch_dir(&self, id: &str) -> PathBuf {
306 self.scratch_directory.join(&self.full_id(id))
307 }
308}
309
310#[derive(Debug)]
311struct NamespacedProcessOrchestrator {
312 config: Arc<NamespacedProcessOrchestratorConfig>,
313 services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
314 service_event_rx: broadcast::Receiver<ServiceEvent>,
315 command_tx: mpsc::UnboundedSender<WorkerCommand>,
316 scheduling_config: std::sync::RwLock<ServiceSchedulingConfig>,
317 _worker: AbortOnDropHandle<()>,
318}
319
320impl NamespacedProcessOrchestrator {
321 fn send_command(&self, cmd: WorkerCommand) {
322 self.command_tx.send(cmd).expect("worker task not dropped");
323 }
324}
325
326#[async_trait]
327impl NamespacedOrchestrator for NamespacedProcessOrchestrator {
328 fn ensure_service(
329 &self,
330 id: &str,
331 config: ServiceConfig,
332 ) -> Result<Box<dyn Service>, anyhow::Error> {
333 let service = ProcessService {
334 run_dir: self.config.service_run_dir(id),
335 scale: config.scale,
336 };
337
338 let disk = config.disk_limit != Some(DiskLimit::ZERO);
340
341 let config = EnsureServiceConfig {
342 image: config.image,
343 args: config.args,
344 ports: config.ports,
345 memory_limit: config.memory_limit,
346 cpu_limit: config.cpu_limit,
347 scale: config.scale,
348 labels: config.labels,
349 disk,
350 };
351
352 self.send_command(WorkerCommand::EnsureService {
353 id: id.to_string(),
354 config,
355 });
356
357 Ok(Box::new(service))
358 }
359
360 fn drop_service(&self, id: &str) -> Result<(), anyhow::Error> {
361 self.send_command(WorkerCommand::DropService { id: id.to_string() });
362 Ok(())
363 }
364
365 async fn list_services(&self) -> Result<Vec<String>, anyhow::Error> {
366 let (result_tx, result_rx) = oneshot::channel();
367 self.send_command(WorkerCommand::ListServices { result_tx });
368
369 result_rx.await.expect("worker task not dropped")
370 }
371
372 fn watch_services(&self) -> BoxStream<'static, Result<ServiceEvent, anyhow::Error>> {
373 let mut initial_events = vec![];
374 let mut service_event_rx = {
375 let services = self.services.lock().expect("lock poisoned");
376 for (service_id, process_states) in &*services {
377 for (process_id, process_state) in process_states.iter().enumerate() {
378 initial_events.push(ServiceEvent {
379 service_id: service_id.clone(),
380 process_id: u64::cast_from(process_id),
381 status: process_state.status.into(),
382 restart_count: process_state.restart_count,
383 time: process_state.status_time,
384 });
385 }
386 }
387 self.service_event_rx.resubscribe()
388 };
389 Box::pin(stream! {
390 for event in initial_events {
391 yield Ok(event);
392 }
393 loop {
394 yield service_event_rx.recv().await.err_into();
395 }
396 })
397 }
398
399 async fn fetch_service_metrics(
400 &self,
401 id: &str,
402 ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error> {
403 let (result_tx, result_rx) = oneshot::channel();
404 self.send_command(WorkerCommand::FetchServiceMetrics {
405 id: id.to_string(),
406 result_tx,
407 });
408
409 result_rx.await.expect("worker task not dropped")
410 }
411
412 fn update_scheduling_config(
413 &self,
414 config: mz_orchestrator::scheduling_config::ServiceSchedulingConfig,
415 ) {
416 *self.scheduling_config.write().expect("poisoned") = config;
417 }
418}
419
420enum WorkerCommand {
426 EnsureService {
427 id: String,
428 config: EnsureServiceConfig,
429 },
430 DropService {
431 id: String,
432 },
433 ListServices {
434 result_tx: oneshot::Sender<Result<Vec<String>, anyhow::Error>>,
435 },
436 FetchServiceMetrics {
437 id: String,
438 result_tx: oneshot::Sender<Result<Vec<ServiceProcessMetrics>, anyhow::Error>>,
439 },
440}
441
442struct EnsureServiceConfig {
444 pub image: String,
448 pub args: Box<dyn Fn(ServiceAssignments) -> Vec<String> + Send + Sync>,
451 pub ports: Vec<ServicePort>,
453 pub memory_limit: Option<MemoryLimit>,
455 pub cpu_limit: Option<CpuLimit>,
457 pub scale: NonZero<u16>,
459 pub labels: BTreeMap<String, String>,
464 pub disk: bool,
466}
467
468struct OrchestratorWorker {
480 config: Arc<NamespacedProcessOrchestratorConfig>,
481 services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
482 service_event_tx: broadcast::Sender<ServiceEvent>,
483 system: System,
484 command_rx: mpsc::UnboundedReceiver<WorkerCommand>,
485}
486
487impl OrchestratorWorker {
488 fn spawn(self) -> AbortOnDropHandle<()> {
489 let name = format!("process-orchestrator:{}", self.config.namespace);
490 mz_ore::task::spawn(|| name, self.run()).abort_on_drop()
491 }
492
493 async fn run(mut self) {
494 while let Some(cmd) = self.command_rx.recv().await {
495 use WorkerCommand::*;
496 let result = match cmd {
497 EnsureService { id, config } => self.ensure_service(id, config).await,
498 DropService { id } => self.drop_service(&id).await,
499 ListServices { result_tx } => {
500 let _ = result_tx.send(self.list_services().await);
501 Ok(())
502 }
503 FetchServiceMetrics { id, result_tx } => {
504 let _ = result_tx.send(self.fetch_service_metrics(&id));
505 Ok(())
506 }
507 };
508
509 if let Err(error) = result {
510 panic!("process orchestrator worker failed: {error}");
511 }
512 }
513 }
514
515 fn fetch_service_metrics(
516 &mut self,
517 id: &str,
518 ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error> {
519 let pids: Vec<_> = {
520 let services = self.services.lock().expect("lock poisoned");
521 let Some(service) = services.get(id) else {
522 bail!("unknown service {id}")
523 };
524 service.iter().map(|p| p.pid()).collect()
525 };
526
527 let mut metrics = vec![];
528 for pid in pids {
529 let (cpu_nano_cores, memory_bytes) = match pid {
530 None => (None, None),
531 Some(pid) => {
532 self.system
533 .refresh_process_specifics(pid, ProcessRefreshKind::new().with_cpu());
534 match self.system.process(pid) {
535 None => (None, None),
536 Some(process) => {
537 let cpu = u64::try_cast_from(
546 (f64::from(process.cpu_usage()) * 10_000_000.0).trunc(),
547 )
548 .expect("sane value of process.cpu_usage()");
549 let memory = process.memory();
550 (Some(cpu), Some(memory))
551 }
552 }
553 }
554 };
555 metrics.push(ServiceProcessMetrics {
556 cpu_nano_cores,
557 memory_bytes,
558 disk_bytes: None,
560 heap_bytes: None,
561 heap_limit: None,
562 });
563 }
564 Ok(metrics)
565 }
566
567 async fn ensure_service(
568 &self,
569 id: String,
570 EnsureServiceConfig {
571 image,
572 args,
573 ports: ports_in,
574 memory_limit,
575 cpu_limit,
576 scale,
577 labels,
578 disk,
579 }: EnsureServiceConfig,
580 ) -> Result<(), anyhow::Error> {
581 let full_id = self.config.full_id(&id);
582
583 let run_dir = self.config.service_run_dir(&id);
584 fs::create_dir_all(&run_dir)
585 .await
586 .context("creating run directory")?;
587 let scratch_dir = if disk {
588 let scratch_dir = self.config.service_scratch_dir(&id);
589 fs::create_dir_all(&scratch_dir)
590 .await
591 .context("creating scratch directory")?;
592 Some(fs::canonicalize(&scratch_dir).await?)
593 } else {
594 None
595 };
596
597 let old_scale = {
600 let services = self.services.lock().expect("poisoned");
601 services.get(&id).map(|states| states.len())
602 };
603 match old_scale {
604 Some(old) if old == usize::cast_from(scale) => return Ok(()),
605 Some(_) => self.drop_service(&id).await?,
606 None => (),
607 }
608
609 let mut peer_addrs = Vec::new();
611 for i in 0..scale.into() {
612 let addresses = ports_in
613 .iter()
614 .map(|port| {
615 let addr = socket_path(&run_dir, &port.name, i);
616 (port.name.clone(), addr)
617 })
618 .collect();
619 peer_addrs.push(addresses);
620 }
621
622 {
623 let mut services = self.services.lock().expect("lock poisoned");
624
625 let mut process_states = vec![];
627 for i in 0..usize::cast_from(scale) {
628 let listen_addrs = &peer_addrs[i];
629
630 let mut command_wrapper = self.config.command_wrapper.clone();
632 if let Some(parts) = command_wrapper.get_mut(1..) {
633 for part in parts {
634 *part = interpolate_command(&part[..], &full_id, listen_addrs);
635 }
636 }
637
638 let mut ports = vec![];
640 let mut tcp_proxy_addrs = BTreeMap::new();
641 for port in &ports_in {
642 let tcp_proxy_listener = match &self.config.tcp_proxy {
643 None => None,
644 Some(tcp_proxy) => {
645 let listener = StdTcpListener::bind((tcp_proxy.listen_addr, 0))
646 .with_context(|| format!("binding to {}", tcp_proxy.listen_addr))?;
647 listener.set_nonblocking(true)?;
648 let listener = TcpListener::from_std(listener)?;
649 let local_addr = listener.local_addr()?;
650 tcp_proxy_addrs.insert(port.name.clone(), local_addr);
651 Some(AddressedTcpListener {
652 listener,
653 local_addr,
654 })
655 }
656 };
657 ports.push(ServiceProcessPort {
658 name: port.name.clone(),
659 listen_addr: listen_addrs[&port.name].clone(),
660 tcp_proxy_listener,
661 });
662 }
663
664 let mut args = args(ServiceAssignments {
665 listen_addrs,
666 peer_addrs: &peer_addrs,
667 });
668 args.push(format!("--process={i}"));
669 if disk {
670 if let Some(scratch) = &scratch_dir {
671 args.push(format!("--scratch-directory={}", scratch.display()));
672 } else {
673 panic!(
674 "internal error: service requested disk but no scratch directory was configured"
675 );
676 }
677 }
678
679 let handle = mz_ore::task::spawn(
681 || format!("process-orchestrator:{full_id}-{i}"),
682 self.supervise_service_process(ServiceProcessConfig {
683 id: id.to_string(),
684 run_dir: run_dir.clone(),
685 i,
686 image: image.clone(),
687 args,
688 command_wrapper,
689 ports,
690 memory_limit,
691 cpu_limit,
692 launch_spec: self.config.launch_spec,
693 }),
694 );
695
696 process_states.push(ProcessState {
697 _handle: handle.abort_on_drop(),
698 status: ProcessStatus::NotReady,
699 status_time: Utc::now(),
700 restart_count: 0,
701 labels: labels.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
702 tcp_proxy_addrs,
703 });
704 }
705
706 services.insert(id, process_states);
709 }
710
711 self.maybe_write_prometheus_service_discovery_file().await;
712
713 Ok(())
714 }
715
716 async fn drop_service(&self, id: &str) -> Result<(), anyhow::Error> {
717 let full_id = self.config.full_id(id);
718 let run_dir = self.config.service_run_dir(id);
719 let scratch_dir = self.config.service_scratch_dir(id);
720
721 {
725 let mut supervisors = self.services.lock().expect("lock poisoned");
726 supervisors.remove(id);
727 }
728
729 if let Ok(mut entries) = fs::read_dir(&run_dir).await {
734 while let Some(entry) = entries.next_entry().await? {
735 let path = entry.path();
736 if path.extension() == Some(OsStr::new("pid")) {
737 let mut system = System::new();
738 let Some(process) = find_process_from_pid_file(&mut system, &path).await else {
739 continue;
740 };
741 let pid = process.pid();
742 info!("terminating orphaned process for {full_id} with PID {pid}");
743 process.kill();
744 }
745 }
746 }
747
748 if let Err(e) = remove_dir_all(run_dir).await {
750 if e.kind() != io::ErrorKind::NotFound {
751 warn!(
752 "error cleaning up run directory for {full_id}: {}",
753 e.display_with_causes()
754 );
755 }
756 }
757 if let Err(e) = remove_dir_all(scratch_dir).await {
758 if e.kind() != io::ErrorKind::NotFound {
759 warn!(
760 "error cleaning up scratch directory for {full_id}: {}",
761 e.display_with_causes()
762 );
763 }
764 }
765
766 self.maybe_write_prometheus_service_discovery_file().await;
767 Ok(())
768 }
769
770 async fn list_services(&self) -> Result<Vec<String>, anyhow::Error> {
771 let mut services = vec![];
772 let namespace_prefix = format!("{}-", self.config.namespace);
773 let mut entries = fs::read_dir(&self.config.metadata_dir).await?;
774 while let Some(entry) = entries.next_entry().await? {
775 let filename = entry
776 .file_name()
777 .into_string()
778 .map_err(|_| anyhow!("unable to convert filename to string"))?;
779 if let Some(id) = filename.strip_prefix(&namespace_prefix) {
780 services.push(id.to_string());
781 }
782 }
783 Ok(services)
784 }
785
786 fn supervise_service_process(
787 &self,
788 ServiceProcessConfig {
789 id,
790 run_dir,
791 i,
792 image,
793 args,
794 command_wrapper,
795 ports,
796 memory_limit,
797 cpu_limit,
798 launch_spec,
799 }: ServiceProcessConfig,
800 ) -> impl Future<Output = ()> + use<> {
801 let suppress_output = self.config.suppress_output;
802 let propagate_crashes = self.config.propagate_crashes;
803 let image = self.config.image_dir.join(image);
804 let pid_file = run_dir.join(format!("{i}.pid"));
805 let full_id = self.config.full_id(&id);
806
807 let state_updater = ProcessStateUpdater {
808 namespace: self.config.namespace.clone(),
809 id,
810 i,
811 services: Arc::clone(&self.services),
812 service_event_tx: self.service_event_tx.clone(),
813 };
814
815 async move {
816 #[allow(clippy::collection_is_never_read)]
818 let mut proxy_handles = vec![];
819 for port in ports {
820 if let Some(tcp_listener) = port.tcp_proxy_listener {
821 info!(
822 "{full_id}-{i}: {} tcp proxy listening on {}",
823 port.name, tcp_listener.local_addr,
824 );
825 let uds_path = port.listen_addr;
826 let handle = mz_ore::task::spawn(
827 || format!("{full_id}-{i}-proxy-{}", port.name),
828 tcp_proxy(TcpProxyConfig {
829 name: format!("{full_id}-{i}-{}", port.name),
830 tcp_listener,
831 uds_path: uds_path.clone(),
832 }),
833 );
834 proxy_handles.push(handle.abort_on_drop());
835 }
836 }
837
838 supervise_existing_process(&state_updater, &pid_file).await;
839
840 loop {
841 let mut cmd = launch_spec.refine_command(
842 &image,
843 &args,
844 &command_wrapper,
845 memory_limit.as_ref(),
846 cpu_limit.as_ref(),
847 );
848 info!(
849 "launching {full_id}-{i} via {} {}...",
850 cmd.as_std().get_program().to_string_lossy(),
851 cmd.as_std()
852 .get_args()
853 .map(|arg| arg.to_string_lossy())
854 .join(" ")
855 );
856 if suppress_output {
857 cmd.stdout(Stdio::null());
858 cmd.stderr(Stdio::null());
859 }
860 match spawn_process(&state_updater, cmd, &pid_file, !command_wrapper.is_empty())
861 .await
862 {
863 Ok(status) => {
864 assert!(
865 !(propagate_crashes && did_process_crash(status)),
866 "{full_id}-{i} crashed; aborting because propagate_crashes is enabled"
867 );
868 error!("{full_id}-{i} exited: {:?}; relaunching in 5s", status);
869 }
870 Err(e) => {
871 error!("{full_id}-{i} failed to spawn: {}; relaunching in 5s", e);
872 }
873 };
874 state_updater.update_state(ProcessStatus::NotReady);
875 time::sleep(Duration::from_secs(5)).await;
876 }
877 }
878 }
879
880 async fn maybe_write_prometheus_service_discovery_file(&self) {
881 #[derive(Serialize)]
882 struct StaticConfig {
883 labels: BTreeMap<String, String>,
884 targets: Vec<String>,
885 }
886
887 let Some(tcp_proxy) = &self.config.tcp_proxy else {
888 return;
889 };
890 let Some(dir) = &tcp_proxy.prometheus_service_discovery_dir else {
891 return;
892 };
893
894 let mut static_configs = vec![];
895 {
896 let services = self.services.lock().expect("lock poisoned");
897 for (id, states) in &*services {
898 for (i, state) in states.iter().enumerate() {
899 for (name, addr) in &state.tcp_proxy_addrs {
900 let mut labels = btreemap! {
901 "mz_orchestrator_namespace".into() => self.config.namespace.clone(),
902 "mz_orchestrator_service_id".into() => id.clone(),
903 "mz_orchestrator_port".into() => name.clone(),
904 "mz_orchestrator_ordinal".into() => i.to_string(),
905 };
906 for (k, v) in &state.labels {
907 let k = format!("mz_orchestrator_{}", k.replace('-', "_"));
908 labels.insert(k, v.clone());
909 }
910 static_configs.push(StaticConfig {
911 labels,
912 targets: vec![addr.to_string()],
913 })
914 }
915 }
916 }
917 }
918
919 let path = dir.join(Path::new(&self.config.namespace).with_extension("json"));
920 let contents = serde_json::to_vec_pretty(&static_configs).expect("valid json");
921 if let Err(e) = fs::write(&path, &contents).await {
922 warn!(
923 "{}: failed to write prometheus service discovery file: {}",
924 self.config.namespace,
925 e.display_with_causes()
926 );
927 }
928 }
929}
930
931struct ServiceProcessConfig {
932 id: String,
933 run_dir: PathBuf,
934 i: usize,
935 image: String,
936 args: Vec<String>,
937 command_wrapper: Vec<String>,
938 ports: Vec<ServiceProcessPort>,
939 memory_limit: Option<MemoryLimit>,
940 cpu_limit: Option<CpuLimit>,
941 launch_spec: LaunchSpec,
942}
943
944struct ServiceProcessPort {
945 name: String,
946 listen_addr: String,
947 tcp_proxy_listener: Option<AddressedTcpListener>,
948}
949
950async fn supervise_existing_process(state_updater: &ProcessStateUpdater, pid_file: &Path) {
952 let name = format!(
953 "{}-{}-{}",
954 state_updater.namespace, state_updater.id, state_updater.i
955 );
956
957 let mut system = System::new();
958 let Some(process) = find_process_from_pid_file(&mut system, pid_file).await else {
959 return;
960 };
961 let pid = process.pid();
962 let start_time = process.start_time();
963
964 info!(%pid, "discovered existing process for {name}");
965 state_updater.update_state(ProcessStatus::Ready { pid });
966
967 let need_kill = AtomicBool::new(true);
969 defer! {
970 state_updater.update_state(ProcessStatus::NotReady);
971 if need_kill.load(Ordering::SeqCst) {
972 info!(%pid, "terminating existing process for {name}");
973 process.kill();
974 }
975 }
976
977 let mut system = System::new();
980 loop {
981 if !system.refresh_process_specifics(pid, ProcessRefreshKind::new()) {
982 break;
983 }
984 match system.process(pid) {
985 Some(p) if p.start_time() == start_time => {}
986 _ => break,
987 }
988 time::sleep(Duration::from_secs(5)).await;
989 }
990
991 warn!(%pid, "process for {name} has crashed; will reboot");
994 need_kill.store(false, Ordering::SeqCst)
995}
996
997fn interpolate_command(
998 command_part: &str,
999 full_id: &str,
1000 ports: &BTreeMap<String, String>,
1001) -> String {
1002 let mut command_part = command_part.replace("%N", full_id);
1003 for (endpoint, port) in ports {
1004 command_part = command_part.replace(&format!("%P:{endpoint}"), port);
1005 }
1006 command_part
1007}
1008
1009async fn spawn_process(
1010 state_updater: &ProcessStateUpdater,
1011 mut cmd: Command,
1012 pid_file: &Path,
1013 send_sigterm: bool,
1014) -> Result<ExitStatus, anyhow::Error> {
1015 struct KillOnDropChild(Child, bool);
1016
1017 impl Drop for KillOnDropChild {
1018 fn drop(&mut self) {
1019 if let (Some(pid), true) = (self.0.id().and_then(|id| i32::try_from(id).ok()), self.1) {
1020 let _ = nix::sys::signal::kill(
1021 nix::unistd::Pid::from_raw(pid),
1022 nix::sys::signal::Signal::SIGTERM,
1023 );
1024 tokio::task::block_in_place(|| std::thread::sleep(Duration::from_millis(500)));
1026 }
1027 let _ = self.0.start_kill();
1028 }
1029 }
1030
1031 let mut child = KillOnDropChild(cmd.spawn()?, send_sigterm);
1032
1033 let pid = Pid::from_u32(child.0.id().unwrap());
1042 write_pid_file(pid_file, pid).await?;
1043 state_updater.update_state(ProcessStatus::Ready { pid });
1044 Ok(child.0.wait().await?)
1045}
1046
1047fn did_process_crash(status: ExitStatus) -> bool {
1048 status.signal().is_some_and(|s| {
1052 matches!(
1053 Signal::try_from(s),
1054 Ok(Signal::SIGABRT
1055 | Signal::SIGBUS
1056 | Signal::SIGSEGV
1057 | Signal::SIGTRAP
1058 | Signal::SIGILL)
1059 )
1060 })
1061}
1062
1063async fn write_pid_file(pid_file: &Path, pid: Pid) -> Result<(), anyhow::Error> {
1064 let mut system = System::new();
1065 system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1066 let start_time = system.process(pid).map_or(0, |p| p.start_time());
1067 fs::write(pid_file, format!("{pid}\n{start_time}\n")).await?;
1068 Ok(())
1069}
1070
1071async fn find_process_from_pid_file<'a>(
1072 system: &'a mut System,
1073 pid_file: &Path,
1074) -> Option<&'a Process> {
1075 let Ok(contents) = fs::read_to_string(pid_file).await else {
1076 return None;
1077 };
1078 let lines = contents.trim().split('\n').collect::<Vec<_>>();
1079 let [pid, start_time] = lines.as_slice() else {
1080 return None;
1081 };
1082 let Ok(pid) = Pid::from_str(pid) else {
1083 return None;
1084 };
1085 let Ok(start_time) = u64::from_str(start_time) else {
1086 return None;
1087 };
1088 system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1089 let process = system.process(pid)?;
1090 if process.start_time() != start_time {
1093 return None;
1094 }
1095 Some(process)
1096}
1097
1098struct TcpProxyConfig {
1099 name: String,
1100 tcp_listener: AddressedTcpListener,
1101 uds_path: String,
1102}
1103
1104async fn tcp_proxy(
1105 TcpProxyConfig {
1106 name,
1107 tcp_listener,
1108 uds_path,
1109 }: TcpProxyConfig,
1110) {
1111 let mut conns = FuturesUnordered::new();
1112 loop {
1113 select! {
1114 res = tcp_listener.listener.accept() => {
1115 debug!("{name}: accepting tcp proxy connection");
1116 let uds_path = uds_path.clone();
1117 conns.push(Box::pin(async move {
1118 let (mut tcp_conn, _) = res.context("accepting tcp connection")?;
1119 let mut uds_conn = UnixStream::connect(uds_path)
1120 .await
1121 .context("making uds connection")?;
1122 io::copy_bidirectional(&mut tcp_conn, &mut uds_conn)
1123 .await
1124 .context("proxying")
1125 }));
1126 }
1127 Some(result) = conns.next() => if let Err(e) = result {
1128 warn!("{name}: tcp proxy connection failed: {}", e.display_with_causes());
1129 }
1130 }
1131 }
1132}
1133
1134struct ProcessStateUpdater {
1135 namespace: String,
1136 id: String,
1137 i: usize,
1138 services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
1139 service_event_tx: broadcast::Sender<ServiceEvent>,
1140}
1141
1142impl ProcessStateUpdater {
1143 fn update_state(&self, status: ProcessStatus) {
1144 let mut services = self.services.lock().expect("lock poisoned");
1145 let Some(process_states) = services.get_mut(&self.id) else {
1146 return;
1147 };
1148 let Some(process_state) = process_states.get_mut(self.i) else {
1149 return;
1150 };
1151 let status_time = Utc::now();
1152 if matches!(status, ProcessStatus::NotReady) {
1158 process_state.restart_count += 1;
1159 }
1160 process_state.status = status;
1161 process_state.status_time = status_time;
1162 let _ = self.service_event_tx.send(ServiceEvent {
1163 service_id: self.id.to_string(),
1164 process_id: u64::cast_from(self.i),
1165 status: status.into(),
1166 restart_count: process_state.restart_count,
1167 time: status_time,
1168 });
1169 }
1170}
1171
1172#[derive(Debug)]
1173struct ProcessState {
1174 _handle: AbortOnDropHandle<()>,
1175 status: ProcessStatus,
1176 status_time: DateTime<Utc>,
1177 restart_count: u64,
1180 labels: BTreeMap<String, String>,
1181 tcp_proxy_addrs: BTreeMap<String, SocketAddr>,
1182}
1183
1184impl ProcessState {
1185 fn pid(&self) -> Option<Pid> {
1186 match &self.status {
1187 ProcessStatus::NotReady => None,
1188 ProcessStatus::Ready { pid } => Some(*pid),
1189 }
1190 }
1191}
1192
1193#[derive(Debug, Clone, Copy)]
1194enum ProcessStatus {
1195 NotReady,
1196 Ready { pid: Pid },
1197}
1198
1199impl From<ProcessStatus> for ServiceStatus {
1200 fn from(status: ProcessStatus) -> ServiceStatus {
1201 match status {
1202 ProcessStatus::NotReady => ServiceStatus::Offline(None),
1203 ProcessStatus::Ready { .. } => ServiceStatus::Online,
1204 }
1205 }
1206}
1207
1208fn socket_path(run_dir: &Path, port: &str, process: u16) -> String {
1209 let desired = run_dir
1210 .join(format!("{port}-{process}"))
1211 .to_string_lossy()
1212 .into_owned();
1213 if UnixSocketAddr::from_pathname(&desired).is_err() {
1214 env::temp_dir()
1217 .join(hex::encode(Sha1::digest(desired)))
1218 .display()
1219 .to_string()
1220 } else {
1221 desired
1222 }
1223}
1224
1225struct AddressedTcpListener {
1226 listener: TcpListener,
1227 local_addr: SocketAddr,
1228}
1229
1230#[derive(Debug)]
1231struct ProcessService {
1232 run_dir: PathBuf,
1233 scale: NonZero<u16>,
1234}
1235
1236impl Service for ProcessService {
1237 fn addresses(&self, port: &str) -> Vec<String> {
1238 (0..self.scale.get())
1239 .map(|i| socket_path(&self.run_dir, port, i))
1240 .collect()
1241 }
1242}