mz_orchestrator_process/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use 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 libc::{SIGABRT, SIGBUS, SIGILL, SIGSEGV, SIGTRAP};
34use maplit::btreemap;
35use mz_orchestrator::scheduling_config::ServiceSchedulingConfig;
36use mz_orchestrator::{
37    CpuLimit, DiskLimit, MemoryLimit, NamespacedOrchestrator, Orchestrator, Service,
38    ServiceAssignments, ServiceConfig, ServiceEvent, ServicePort, ServiceProcessMetrics,
39    ServiceStatus,
40};
41use mz_ore::cast::{CastFrom, TryCastFrom};
42use mz_ore::error::ErrorExt;
43use mz_ore::netio::UnixSocketAddr;
44use mz_ore::result::ResultExt;
45use mz_ore::task::AbortOnDropHandle;
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/// Configures a [`ProcessOrchestrator`].
61#[derive(Debug, Clone)]
62pub struct ProcessOrchestratorConfig {
63    /// The directory in which the orchestrator should look for executable
64    /// images.
65    pub image_dir: PathBuf,
66    /// Whether to supress output from spawned subprocesses.
67    pub suppress_output: bool,
68    /// The ID of the environment under orchestration.
69    pub environment_id: String,
70    /// The directory in which to store secrets.
71    pub secrets_dir: PathBuf,
72    /// A command to wrap the child command invocation
73    pub command_wrapper: Vec<String>,
74    /// Whether to crash this process if a child process crashes.
75    pub propagate_crashes: bool,
76    /// TCP proxy configuration.
77    ///
78    /// When enabled, for each named port of each created service, the process
79    /// orchestrator will bind a TCP listener that proxies incoming connections
80    /// to the underlying Unix domain socket. Each bound TCP address will be
81    /// emitted as a tracing event.
82    ///
83    /// The primary use is live debugging the running child services via tools
84    /// that do not support Unix domain sockets (e.g., Prometheus, web
85    /// browsers).
86    pub tcp_proxy: Option<ProcessOrchestratorTcpProxyConfig>,
87    /// A scratch directory that orchestrated processes can use for ephemeral storage.
88    pub scratch_directory: PathBuf,
89}
90
91/// Configures the TCP proxy for a [`ProcessOrchestrator`].
92///
93/// See [`ProcessOrchestratorConfig::tcp_proxy`].
94#[derive(Debug, Clone)]
95pub struct ProcessOrchestratorTcpProxyConfig {
96    /// The IP address on which to bind TCP listeners.
97    pub listen_addr: IpAddr,
98    /// A directory in which to write Prometheus scrape targets, for use with
99    /// Prometheus's file-based service discovery.
100    ///
101    /// Each [`NamespacedOrchestrator`] will maintain a single JSON file into
102    /// the directory named `NAMESPACE.json` containing the scrape targets for
103    /// all extant services. The scrape targets will use the TCP proxy address,
104    /// as Prometheus does not support scraping over Unix domain sockets.
105    ///
106    /// See also: <https://prometheus.io/docs/guides/file-sd/>
107    pub prometheus_service_discovery_dir: Option<PathBuf>,
108}
109
110/// An orchestrator backed by processes on the local machine.
111///
112/// **This orchestrator is for development only.** Due to limitations in the
113/// Unix process API, it does not exactly conform to the documented semantics
114/// of `Orchestrator`.
115#[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    /// Directly execute the provided binary
132    Direct,
133    /// Use Systemd to start the binary
134    Systemd,
135}
136
137impl LaunchSpec {
138    fn determine_implementation() -> Result<Self, anyhow::Error> {
139        // According to https://www.freedesktop.org/software/systemd/man/latest/sd_booted.html
140        // checking for `/run/systemd/system/` is the canonical way to determine if the system
141        // was booted up with systemd.
142        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                    // TODO: We could set `-p MemorySwapMax=0` here to disable regular swap.
174                }
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    /// Creates a new process orchestrator from the provided configuration.
192    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/// Configuration for a [`NamespacedProcessOrchestrator`].
283#[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        // Enable disk if the size does not disable it.
339        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                        time: process_state.status_time,
383                    });
384                }
385            }
386            self.service_event_rx.resubscribe()
387        };
388        Box::pin(stream! {
389            for event in initial_events {
390                yield Ok(event);
391            }
392            loop {
393                yield service_event_rx.recv().await.err_into();
394            }
395        })
396    }
397
398    async fn fetch_service_metrics(
399        &self,
400        id: &str,
401    ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error> {
402        let (result_tx, result_rx) = oneshot::channel();
403        self.send_command(WorkerCommand::FetchServiceMetrics {
404            id: id.to_string(),
405            result_tx,
406        });
407
408        result_rx.await.expect("worker task not dropped")
409    }
410
411    fn update_scheduling_config(
412        &self,
413        config: mz_orchestrator::scheduling_config::ServiceSchedulingConfig,
414    ) {
415        *self.scheduling_config.write().expect("poisoned") = config;
416    }
417}
418
419/// Commands sent from a [`NamespacedProcessOrchestrator`] to its
420/// [`OrchestratorWorker`].
421///
422/// Commands for which the caller expects a result include a `result_tx` on which the
423/// [`OrchestratorWorker`] will deliver the result.
424enum WorkerCommand {
425    EnsureService {
426        id: String,
427        config: EnsureServiceConfig,
428    },
429    DropService {
430        id: String,
431    },
432    ListServices {
433        result_tx: oneshot::Sender<Result<Vec<String>, anyhow::Error>>,
434    },
435    FetchServiceMetrics {
436        id: String,
437        result_tx: oneshot::Sender<Result<Vec<ServiceProcessMetrics>, anyhow::Error>>,
438    },
439}
440
441/// Describes the desired state of a process.
442struct EnsureServiceConfig {
443    /// An opaque identifier for the executable or container image to run.
444    ///
445    /// Often names a container on Docker Hub or a path on the local machine.
446    pub image: String,
447    /// A function that generates the arguments for each process of the service
448    /// given the assigned listen addresses for each named port.
449    pub args: Box<dyn Fn(ServiceAssignments) -> Vec<String> + Send + Sync>,
450    /// Ports to expose.
451    pub ports: Vec<ServicePort>,
452    /// An optional limit on the memory that the service can use.
453    pub memory_limit: Option<MemoryLimit>,
454    /// An optional limit on the CPU that the service can use.
455    pub cpu_limit: Option<CpuLimit>,
456    /// The number of copies of this service to run.
457    pub scale: NonZero<u16>,
458    /// Arbitrary key–value pairs to attach to the service in the orchestrator
459    /// backend.
460    ///
461    /// The orchestrator backend may apply a prefix to the key if appropriate.
462    pub labels: BTreeMap<String, String>,
463    /// Whether scratch disk space should be allocated for the service.
464    pub disk: bool,
465}
466
467/// A task executing blocking work for a [`NamespacedProcessOrchestrator`] in the background.
468///
469/// This type exists to enable making [`NamespacedProcessOrchestrator::ensure_service`] and
470/// [`NamespacedProcessOrchestrator::drop_service`] non-blocking, allowing invocation of these
471/// methods in latency-sensitive contexts.
472///
473/// Note that, apart from `ensure_service` and `drop_service`, this worker also handles blocking
474/// orchestrator calls that query service state (such as `list_services`). These need to be
475/// sequenced through the worker loop to ensure they linearize as expected. For example, we want to
476/// ensure that a `list_services` result contains exactly those services that were previously
477/// created with `ensure_service` and not yet dropped with `drop_service`.
478struct OrchestratorWorker {
479    config: Arc<NamespacedProcessOrchestratorConfig>,
480    services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
481    service_event_tx: broadcast::Sender<ServiceEvent>,
482    system: System,
483    command_rx: mpsc::UnboundedReceiver<WorkerCommand>,
484}
485
486impl OrchestratorWorker {
487    fn spawn(self) -> AbortOnDropHandle<()> {
488        let name = format!("process-orchestrator:{}", self.config.namespace);
489        mz_ore::task::spawn(|| name, self.run()).abort_on_drop()
490    }
491
492    async fn run(mut self) {
493        while let Some(cmd) = self.command_rx.recv().await {
494            use WorkerCommand::*;
495            let result = match cmd {
496                EnsureService { id, config } => self.ensure_service(id, config).await,
497                DropService { id } => self.drop_service(&id).await,
498                ListServices { result_tx } => {
499                    let _ = result_tx.send(self.list_services().await);
500                    Ok(())
501                }
502                FetchServiceMetrics { id, result_tx } => {
503                    let _ = result_tx.send(self.fetch_service_metrics(&id));
504                    Ok(())
505                }
506            };
507
508            if let Err(error) = result {
509                panic!("process orchestrator worker failed: {error}");
510            }
511        }
512    }
513
514    fn fetch_service_metrics(
515        &mut self,
516        id: &str,
517    ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error> {
518        let pids: Vec<_> = {
519            let services = self.services.lock().expect("lock poisoned");
520            let Some(service) = services.get(id) else {
521                bail!("unknown service {id}")
522            };
523            service.iter().map(|p| p.pid()).collect()
524        };
525
526        let mut metrics = vec![];
527        for pid in pids {
528            let (cpu_nano_cores, memory_bytes) = match pid {
529                None => (None, None),
530                Some(pid) => {
531                    self.system
532                        .refresh_process_specifics(pid, ProcessRefreshKind::new().with_cpu());
533                    match self.system.process(pid) {
534                        None => (None, None),
535                        Some(process) => {
536                            // Justification for `unwrap`:
537                            //
538                            // `u64::try_cast_from(f: f64)`
539                            // will always succeed if 0 <= f < 2^64.
540                            // Since the max value of `process.cpu_usage()` is
541                            // 100.0 * num_of_cores, this will be true whenever there
542                            // are less than 2^64 / 10^9 logical cores, or about
543                            // 18 billion.
544                            let cpu = u64::try_cast_from(
545                                (f64::from(process.cpu_usage()) * 10_000_000.0).trunc(),
546                            )
547                            .expect("sane value of process.cpu_usage()");
548                            let memory = process.memory();
549                            (Some(cpu), Some(memory))
550                        }
551                    }
552                }
553            };
554            metrics.push(ServiceProcessMetrics {
555                cpu_nano_cores,
556                memory_bytes,
557                // Process orchestrator does not support the remaining fields right now.
558                disk_bytes: None,
559                heap_bytes: None,
560                heap_limit: None,
561            });
562        }
563        Ok(metrics)
564    }
565
566    async fn ensure_service(
567        &self,
568        id: String,
569        EnsureServiceConfig {
570            image,
571            args,
572            ports: ports_in,
573            memory_limit,
574            cpu_limit,
575            scale,
576            labels,
577            disk,
578        }: EnsureServiceConfig,
579    ) -> Result<(), anyhow::Error> {
580        let full_id = self.config.full_id(&id);
581
582        let run_dir = self.config.service_run_dir(&id);
583        fs::create_dir_all(&run_dir)
584            .await
585            .context("creating run directory")?;
586        let scratch_dir = if disk {
587            let scratch_dir = self.config.service_scratch_dir(&id);
588            fs::create_dir_all(&scratch_dir)
589                .await
590                .context("creating scratch directory")?;
591            Some(fs::canonicalize(&scratch_dir).await?)
592        } else {
593            None
594        };
595
596        // The service might already exist. If it has the same config as requested (currently we
597        // check only the scale), we have nothing to do. Otherwise we need to drop and recreate it.
598        let old_scale = {
599            let services = self.services.lock().expect("poisoned");
600            services.get(&id).map(|states| states.len())
601        };
602        match old_scale {
603            Some(old) if old == usize::cast_from(scale) => return Ok(()),
604            Some(_) => self.drop_service(&id).await?,
605            None => (),
606        }
607
608        // Create sockets for all processes in the service.
609        let mut peer_addrs = Vec::new();
610        for i in 0..scale.into() {
611            let addresses = ports_in
612                .iter()
613                .map(|port| {
614                    let addr = socket_path(&run_dir, &port.name, i);
615                    (port.name.clone(), addr)
616                })
617                .collect();
618            peer_addrs.push(addresses);
619        }
620
621        {
622            let mut services = self.services.lock().expect("lock poisoned");
623
624            // Create the state for new processes.
625            let mut process_states = vec![];
626            for i in 0..usize::cast_from(scale) {
627                let listen_addrs = &peer_addrs[i];
628
629                // Fill out placeholders in the command wrapper for this process.
630                let mut command_wrapper = self.config.command_wrapper.clone();
631                if let Some(parts) = command_wrapper.get_mut(1..) {
632                    for part in parts {
633                        *part = interpolate_command(&part[..], &full_id, listen_addrs);
634                    }
635                }
636
637                // Allocate listeners for each TCP proxy, if requested.
638                let mut ports = vec![];
639                let mut tcp_proxy_addrs = BTreeMap::new();
640                for port in &ports_in {
641                    let tcp_proxy_listener = match &self.config.tcp_proxy {
642                        None => None,
643                        Some(tcp_proxy) => {
644                            let listener = StdTcpListener::bind((tcp_proxy.listen_addr, 0))
645                                .with_context(|| format!("binding to {}", tcp_proxy.listen_addr))?;
646                            listener.set_nonblocking(true)?;
647                            let listener = TcpListener::from_std(listener)?;
648                            let local_addr = listener.local_addr()?;
649                            tcp_proxy_addrs.insert(port.name.clone(), local_addr);
650                            Some(AddressedTcpListener {
651                                listener,
652                                local_addr,
653                            })
654                        }
655                    };
656                    ports.push(ServiceProcessPort {
657                        name: port.name.clone(),
658                        listen_addr: listen_addrs[&port.name].clone(),
659                        tcp_proxy_listener,
660                    });
661                }
662
663                let mut args = args(ServiceAssignments {
664                    listen_addrs,
665                    peer_addrs: &peer_addrs,
666                });
667                args.push(format!("--process={i}"));
668                if disk {
669                    if let Some(scratch) = &scratch_dir {
670                        args.push(format!("--scratch-directory={}", scratch.display()));
671                    } else {
672                        panic!(
673                            "internal error: service requested disk but no scratch directory was configured"
674                        );
675                    }
676                }
677
678                // Launch supervisor process.
679                let handle = mz_ore::task::spawn(
680                    || format!("process-orchestrator:{full_id}-{i}"),
681                    self.supervise_service_process(ServiceProcessConfig {
682                        id: id.to_string(),
683                        run_dir: run_dir.clone(),
684                        i,
685                        image: image.clone(),
686                        args,
687                        command_wrapper,
688                        ports,
689                        memory_limit,
690                        cpu_limit,
691                        launch_spec: self.config.launch_spec,
692                    }),
693                );
694
695                process_states.push(ProcessState {
696                    _handle: handle.abort_on_drop(),
697                    status: ProcessStatus::NotReady,
698                    status_time: Utc::now(),
699                    labels: labels.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
700                    tcp_proxy_addrs,
701                });
702            }
703
704            // Update the in-memory process state. We do this after we've created
705            // all process states to avoid partially updating our in-memory state.
706            services.insert(id, process_states);
707        }
708
709        self.maybe_write_prometheus_service_discovery_file().await;
710
711        Ok(())
712    }
713
714    async fn drop_service(&self, id: &str) -> Result<(), anyhow::Error> {
715        let full_id = self.config.full_id(id);
716        let run_dir = self.config.service_run_dir(id);
717        let scratch_dir = self.config.service_scratch_dir(id);
718
719        // Drop the supervisor for the service, if it exists. If this service
720        // was under supervision, this will kill all processes associated with
721        // it.
722        {
723            let mut supervisors = self.services.lock().expect("lock poisoned");
724            supervisors.remove(id);
725        }
726
727        // If the service was orphaned by a prior incarnation of the
728        // orchestrator, it won't have been under supervision and therefore will
729        // still be running. So kill any process that we have state for in the
730        // run directory.
731        if let Ok(mut entries) = fs::read_dir(&run_dir).await {
732            while let Some(entry) = entries.next_entry().await? {
733                let path = entry.path();
734                if path.extension() == Some(OsStr::new("pid")) {
735                    let mut system = System::new();
736                    let Some(process) = find_process_from_pid_file(&mut system, &path).await else {
737                        continue;
738                    };
739                    let pid = process.pid();
740                    info!("terminating orphaned process for {full_id} with PID {pid}");
741                    process.kill();
742                }
743            }
744        }
745
746        // Clean up the on-disk state of the service.
747        if let Err(e) = remove_dir_all(run_dir).await {
748            if e.kind() != io::ErrorKind::NotFound {
749                warn!(
750                    "error cleaning up run directory for {full_id}: {}",
751                    e.display_with_causes()
752                );
753            }
754        }
755        if let Err(e) = remove_dir_all(scratch_dir).await {
756            if e.kind() != io::ErrorKind::NotFound {
757                warn!(
758                    "error cleaning up scratch directory for {full_id}: {}",
759                    e.display_with_causes()
760                );
761            }
762        }
763
764        self.maybe_write_prometheus_service_discovery_file().await;
765        Ok(())
766    }
767
768    async fn list_services(&self) -> Result<Vec<String>, anyhow::Error> {
769        let mut services = vec![];
770        let namespace_prefix = format!("{}-", self.config.namespace);
771        let mut entries = fs::read_dir(&self.config.metadata_dir).await?;
772        while let Some(entry) = entries.next_entry().await? {
773            let filename = entry
774                .file_name()
775                .into_string()
776                .map_err(|_| anyhow!("unable to convert filename to string"))?;
777            if let Some(id) = filename.strip_prefix(&namespace_prefix) {
778                services.push(id.to_string());
779            }
780        }
781        Ok(services)
782    }
783
784    fn supervise_service_process(
785        &self,
786        ServiceProcessConfig {
787            id,
788            run_dir,
789            i,
790            image,
791            args,
792            command_wrapper,
793            ports,
794            memory_limit,
795            cpu_limit,
796            launch_spec,
797        }: ServiceProcessConfig,
798    ) -> impl Future<Output = ()> + use<> {
799        let suppress_output = self.config.suppress_output;
800        let propagate_crashes = self.config.propagate_crashes;
801        let image = self.config.image_dir.join(image);
802        let pid_file = run_dir.join(format!("{i}.pid"));
803        let full_id = self.config.full_id(&id);
804
805        let state_updater = ProcessStateUpdater {
806            namespace: self.config.namespace.clone(),
807            id,
808            i,
809            services: Arc::clone(&self.services),
810            service_event_tx: self.service_event_tx.clone(),
811        };
812
813        async move {
814            let mut proxy_handles = vec![];
815            for port in ports {
816                if let Some(tcp_listener) = port.tcp_proxy_listener {
817                    info!(
818                        "{full_id}-{i}: {} tcp proxy listening on {}",
819                        port.name, tcp_listener.local_addr,
820                    );
821                    let uds_path = port.listen_addr;
822                    let handle = mz_ore::task::spawn(
823                        || format!("{full_id}-{i}-proxy-{}", port.name),
824                        tcp_proxy(TcpProxyConfig {
825                            name: format!("{full_id}-{i}-{}", port.name),
826                            tcp_listener,
827                            uds_path: uds_path.clone(),
828                        }),
829                    );
830                    proxy_handles.push(handle.abort_on_drop());
831                }
832            }
833
834            supervise_existing_process(&state_updater, &pid_file).await;
835
836            loop {
837                let mut cmd = launch_spec.refine_command(
838                    &image,
839                    &args,
840                    &command_wrapper,
841                    memory_limit.as_ref(),
842                    cpu_limit.as_ref(),
843                );
844                info!(
845                    "launching {full_id}-{i} via {} {}...",
846                    cmd.as_std().get_program().to_string_lossy(),
847                    cmd.as_std()
848                        .get_args()
849                        .map(|arg| arg.to_string_lossy())
850                        .join(" ")
851                );
852                if suppress_output {
853                    cmd.stdout(Stdio::null());
854                    cmd.stderr(Stdio::null());
855                }
856                match spawn_process(&state_updater, cmd, &pid_file, !command_wrapper.is_empty())
857                    .await
858                {
859                    Ok(status) => {
860                        if propagate_crashes && did_process_crash(status) {
861                            panic!(
862                                "{full_id}-{i} crashed; aborting because propagate_crashes is enabled"
863                            );
864                        }
865                        error!("{full_id}-{i} exited: {:?}; relaunching in 5s", status);
866                    }
867                    Err(e) => {
868                        error!("{full_id}-{i} failed to spawn: {}; relaunching in 5s", e);
869                    }
870                };
871                state_updater.update_state(ProcessStatus::NotReady);
872                time::sleep(Duration::from_secs(5)).await;
873            }
874        }
875    }
876
877    async fn maybe_write_prometheus_service_discovery_file(&self) {
878        #[derive(Serialize)]
879        struct StaticConfig {
880            labels: BTreeMap<String, String>,
881            targets: Vec<String>,
882        }
883
884        let Some(tcp_proxy) = &self.config.tcp_proxy else {
885            return;
886        };
887        let Some(dir) = &tcp_proxy.prometheus_service_discovery_dir else {
888            return;
889        };
890
891        let mut static_configs = vec![];
892        {
893            let services = self.services.lock().expect("lock poisoned");
894            for (id, states) in &*services {
895                for (i, state) in states.iter().enumerate() {
896                    for (name, addr) in &state.tcp_proxy_addrs {
897                        let mut labels = btreemap! {
898                            "mz_orchestrator_namespace".into() => self.config.namespace.clone(),
899                            "mz_orchestrator_service_id".into() => id.clone(),
900                            "mz_orchestrator_port".into() => name.clone(),
901                            "mz_orchestrator_ordinal".into() => i.to_string(),
902                        };
903                        for (k, v) in &state.labels {
904                            let k = format!("mz_orchestrator_{}", k.replace('-', "_"));
905                            labels.insert(k, v.clone());
906                        }
907                        static_configs.push(StaticConfig {
908                            labels,
909                            targets: vec![addr.to_string()],
910                        })
911                    }
912                }
913            }
914        }
915
916        let path = dir.join(Path::new(&self.config.namespace).with_extension("json"));
917        let contents = serde_json::to_vec_pretty(&static_configs).expect("valid json");
918        if let Err(e) = fs::write(&path, &contents).await {
919            warn!(
920                "{}: failed to write prometheus service discovery file: {}",
921                self.config.namespace,
922                e.display_with_causes()
923            );
924        }
925    }
926}
927
928struct ServiceProcessConfig {
929    id: String,
930    run_dir: PathBuf,
931    i: usize,
932    image: String,
933    args: Vec<String>,
934    command_wrapper: Vec<String>,
935    ports: Vec<ServiceProcessPort>,
936    memory_limit: Option<MemoryLimit>,
937    cpu_limit: Option<CpuLimit>,
938    launch_spec: LaunchSpec,
939}
940
941struct ServiceProcessPort {
942    name: String,
943    listen_addr: String,
944    tcp_proxy_listener: Option<AddressedTcpListener>,
945}
946
947/// Supervises an existing process, if it exists.
948async fn supervise_existing_process(state_updater: &ProcessStateUpdater, pid_file: &Path) {
949    let name = format!(
950        "{}-{}-{}",
951        state_updater.namespace, state_updater.id, state_updater.i
952    );
953
954    let mut system = System::new();
955    let Some(process) = find_process_from_pid_file(&mut system, pid_file).await else {
956        return;
957    };
958    let pid = process.pid();
959
960    info!(%pid, "discovered existing process for {name}");
961    state_updater.update_state(ProcessStatus::Ready { pid });
962
963    // Kill the process if the future is dropped.
964    let need_kill = AtomicBool::new(true);
965    defer! {
966        state_updater.update_state(ProcessStatus::NotReady);
967        if need_kill.load(Ordering::SeqCst) {
968            info!(%pid, "terminating existing process for {name}");
969            process.kill();
970        }
971    }
972
973    // Periodically check if the process has terminated.
974    let mut system = System::new();
975    while system.refresh_process_specifics(pid, ProcessRefreshKind::new()) {
976        time::sleep(Duration::from_secs(5)).await;
977    }
978
979    // The process has crashed. Exit the function without attempting to
980    // kill it.
981    warn!(%pid, "process for {name} has crashed; will reboot");
982    need_kill.store(false, Ordering::SeqCst)
983}
984
985fn interpolate_command(
986    command_part: &str,
987    full_id: &str,
988    ports: &BTreeMap<String, String>,
989) -> String {
990    let mut command_part = command_part.replace("%N", full_id);
991    for (endpoint, port) in ports {
992        command_part = command_part.replace(&format!("%P:{endpoint}"), port);
993    }
994    command_part
995}
996
997async fn spawn_process(
998    state_updater: &ProcessStateUpdater,
999    mut cmd: Command,
1000    pid_file: &Path,
1001    send_sigterm: bool,
1002) -> Result<ExitStatus, anyhow::Error> {
1003    struct KillOnDropChild(Child, bool);
1004
1005    impl Drop for KillOnDropChild {
1006        fn drop(&mut self) {
1007            if let (Some(pid), true) = (self.0.id().and_then(|id| i32::try_from(id).ok()), self.1) {
1008                let _ = nix::sys::signal::kill(
1009                    nix::unistd::Pid::from_raw(pid),
1010                    nix::sys::signal::Signal::SIGTERM,
1011                );
1012                // Give the process a bit of time to react to the signal
1013                tokio::task::block_in_place(|| std::thread::sleep(Duration::from_millis(500)));
1014            }
1015            let _ = self.0.start_kill();
1016        }
1017    }
1018
1019    let mut child = KillOnDropChild(cmd.spawn()?, send_sigterm);
1020
1021    // Immediately write out a file containing the PID of the child process and
1022    // its start time. We'll use this state to rediscover our children if we
1023    // crash and restart. There's a very small window where we can crash after
1024    // having spawned the child but before writing this file, in which case we
1025    // might orphan the process. We accept this risk, though. It's hard to do
1026    // anything more robust given the Unix APIs available to us, and the
1027    // solution here is good enough given that the process orchestrator is only
1028    // used in development/testing.
1029    let pid = Pid::from_u32(child.0.id().unwrap());
1030    write_pid_file(pid_file, pid).await?;
1031    state_updater.update_state(ProcessStatus::Ready { pid });
1032    Ok(child.0.wait().await?)
1033}
1034
1035fn did_process_crash(status: ExitStatus) -> bool {
1036    // Likely not exhaustive. Feel free to add additional tests for other
1037    // indications of a crashed child process, as those conditions are
1038    // discovered.
1039    matches!(
1040        status.signal(),
1041        Some(SIGABRT | SIGBUS | SIGSEGV | SIGTRAP | SIGILL)
1042    )
1043}
1044
1045async fn write_pid_file(pid_file: &Path, pid: Pid) -> Result<(), anyhow::Error> {
1046    let mut system = System::new();
1047    system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1048    let start_time = system.process(pid).map_or(0, |p| p.start_time());
1049    fs::write(pid_file, format!("{pid}\n{start_time}\n")).await?;
1050    Ok(())
1051}
1052
1053async fn find_process_from_pid_file<'a>(
1054    system: &'a mut System,
1055    pid_file: &Path,
1056) -> Option<&'a Process> {
1057    let Ok(contents) = fs::read_to_string(pid_file).await else {
1058        return None;
1059    };
1060    let lines = contents.trim().split('\n').collect::<Vec<_>>();
1061    let [pid, start_time] = lines.as_slice() else {
1062        return None;
1063    };
1064    let Ok(pid) = Pid::from_str(pid) else {
1065        return None;
1066    };
1067    let Ok(start_time) = u64::from_str(start_time) else {
1068        return None;
1069    };
1070    system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1071    let process = system.process(pid)?;
1072    // Checking the start time protects against killing an unrelated process due
1073    // to PID reuse.
1074    if process.start_time() != start_time {
1075        return None;
1076    }
1077    Some(process)
1078}
1079
1080struct TcpProxyConfig {
1081    name: String,
1082    tcp_listener: AddressedTcpListener,
1083    uds_path: String,
1084}
1085
1086async fn tcp_proxy(
1087    TcpProxyConfig {
1088        name,
1089        tcp_listener,
1090        uds_path,
1091    }: TcpProxyConfig,
1092) {
1093    let mut conns = FuturesUnordered::new();
1094    loop {
1095        select! {
1096            res = tcp_listener.listener.accept() => {
1097                debug!("{name}: accepting tcp proxy connection");
1098                let uds_path = uds_path.clone();
1099                conns.push(Box::pin(async move {
1100                    let (mut tcp_conn, _) = res.context("accepting tcp connection")?;
1101                    let mut uds_conn = UnixStream::connect(uds_path)
1102                        .await
1103                        .context("making uds connection")?;
1104                    io::copy_bidirectional(&mut tcp_conn, &mut uds_conn)
1105                        .await
1106                        .context("proxying")
1107                }));
1108            }
1109            Some(Err(e)) = conns.next() => {
1110                warn!("{name}: tcp proxy connection failed: {}", e.display_with_causes());
1111            }
1112        }
1113    }
1114}
1115
1116struct ProcessStateUpdater {
1117    namespace: String,
1118    id: String,
1119    i: usize,
1120    services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
1121    service_event_tx: broadcast::Sender<ServiceEvent>,
1122}
1123
1124impl ProcessStateUpdater {
1125    fn update_state(&self, status: ProcessStatus) {
1126        let mut services = self.services.lock().expect("lock poisoned");
1127        let Some(process_states) = services.get_mut(&self.id) else {
1128            return;
1129        };
1130        let Some(process_state) = process_states.get_mut(self.i) else {
1131            return;
1132        };
1133        let status_time = Utc::now();
1134        process_state.status = status;
1135        process_state.status_time = status_time;
1136        let _ = self.service_event_tx.send(ServiceEvent {
1137            service_id: self.id.to_string(),
1138            process_id: u64::cast_from(self.i),
1139            status: status.into(),
1140            time: status_time,
1141        });
1142    }
1143}
1144
1145#[derive(Debug)]
1146struct ProcessState {
1147    _handle: AbortOnDropHandle<()>,
1148    status: ProcessStatus,
1149    status_time: DateTime<Utc>,
1150    labels: BTreeMap<String, String>,
1151    tcp_proxy_addrs: BTreeMap<String, SocketAddr>,
1152}
1153
1154impl ProcessState {
1155    fn pid(&self) -> Option<Pid> {
1156        match &self.status {
1157            ProcessStatus::NotReady => None,
1158            ProcessStatus::Ready { pid } => Some(*pid),
1159        }
1160    }
1161}
1162
1163#[derive(Debug, Clone, Copy)]
1164enum ProcessStatus {
1165    NotReady,
1166    Ready { pid: Pid },
1167}
1168
1169impl From<ProcessStatus> for ServiceStatus {
1170    fn from(status: ProcessStatus) -> ServiceStatus {
1171        match status {
1172            ProcessStatus::NotReady => ServiceStatus::Offline(None),
1173            ProcessStatus::Ready { .. } => ServiceStatus::Online,
1174        }
1175    }
1176}
1177
1178fn socket_path(run_dir: &Path, port: &str, process: u16) -> String {
1179    let desired = run_dir
1180        .join(format!("{port}-{process}"))
1181        .to_string_lossy()
1182        .into_owned();
1183    if UnixSocketAddr::from_pathname(&desired).is_err() {
1184        // Unix socket addresses have a very low maximum length of around 100
1185        // bytes on most platforms.
1186        env::temp_dir()
1187            .join(hex::encode(Sha1::digest(desired)))
1188            .display()
1189            .to_string()
1190    } else {
1191        desired
1192    }
1193}
1194
1195struct AddressedTcpListener {
1196    listener: TcpListener,
1197    local_addr: SocketAddr,
1198}
1199
1200#[derive(Debug, Clone)]
1201struct ProcessService {
1202    run_dir: PathBuf,
1203    scale: NonZero<u16>,
1204}
1205
1206impl Service for ProcessService {
1207    fn addresses(&self, port: &str) -> Vec<String> {
1208        (0..self.scale.get())
1209            .map(|i| socket_path(&self.run_dir, port, i))
1210            .collect()
1211    }
1212}