Skip to main content

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 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/// 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                        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
420/// Commands sent from a [`NamespacedProcessOrchestrator`] to its
421/// [`OrchestratorWorker`].
422///
423/// Commands for which the caller expects a result include a `result_tx` on which the
424/// [`OrchestratorWorker`] will deliver the result.
425enum 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
442/// Describes the desired state of a process.
443struct EnsureServiceConfig {
444    /// An opaque identifier for the executable or container image to run.
445    ///
446    /// Often names a container on Docker Hub or a path on the local machine.
447    pub image: String,
448    /// A function that generates the arguments for each process of the service
449    /// given the assigned listen addresses for each named port.
450    pub args: Box<dyn Fn(ServiceAssignments) -> Vec<String> + Send + Sync>,
451    /// Ports to expose.
452    pub ports: Vec<ServicePort>,
453    /// An optional limit on the memory that the service can use.
454    pub memory_limit: Option<MemoryLimit>,
455    /// An optional limit on the CPU that the service can use.
456    pub cpu_limit: Option<CpuLimit>,
457    /// The number of copies of this service to run.
458    pub scale: NonZero<u16>,
459    /// Arbitrary key–value pairs to attach to the service in the orchestrator
460    /// backend.
461    ///
462    /// The orchestrator backend may apply a prefix to the key if appropriate.
463    pub labels: BTreeMap<String, String>,
464    /// Whether scratch disk space should be allocated for the service.
465    pub disk: bool,
466}
467
468/// A task executing blocking work for a [`NamespacedProcessOrchestrator`] in the background.
469///
470/// This type exists to enable making [`NamespacedProcessOrchestrator::ensure_service`] and
471/// [`NamespacedProcessOrchestrator::drop_service`] non-blocking, allowing invocation of these
472/// methods in latency-sensitive contexts.
473///
474/// Note that, apart from `ensure_service` and `drop_service`, this worker also handles blocking
475/// orchestrator calls that query service state (such as `list_services`). These need to be
476/// sequenced through the worker loop to ensure they linearize as expected. For example, we want to
477/// ensure that a `list_services` result contains exactly those services that were previously
478/// created with `ensure_service` and not yet dropped with `drop_service`.
479struct 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                            // Justification for `unwrap`:
538                            //
539                            // `u64::try_cast_from(f: f64)`
540                            // will always succeed if 0 <= f < 2^64.
541                            // Since the max value of `process.cpu_usage()` is
542                            // 100.0 * num_of_cores, this will be true whenever there
543                            // are less than 2^64 / 10^9 logical cores, or about
544                            // 18 billion.
545                            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                // Process orchestrator does not support the remaining fields right now.
559                disk_bytes: None,
560                heap_bytes: None,
561                heap_limit: None,
562                swap_bytes: None,
563            });
564        }
565        Ok(metrics)
566    }
567
568    async fn ensure_service(
569        &self,
570        id: String,
571        EnsureServiceConfig {
572            image,
573            args,
574            ports: ports_in,
575            memory_limit,
576            cpu_limit,
577            scale,
578            labels,
579            disk,
580        }: EnsureServiceConfig,
581    ) -> Result<(), anyhow::Error> {
582        let full_id = self.config.full_id(&id);
583
584        let run_dir = self.config.service_run_dir(&id);
585        fs::create_dir_all(&run_dir)
586            .await
587            .context("creating run directory")?;
588        let scratch_dir = if disk {
589            let scratch_dir = self.config.service_scratch_dir(&id);
590            fs::create_dir_all(&scratch_dir)
591                .await
592                .context("creating scratch directory")?;
593            Some(fs::canonicalize(&scratch_dir).await?)
594        } else {
595            None
596        };
597
598        // The service might already exist. If it has the same config as requested (currently we
599        // check only the scale), we have nothing to do. Otherwise we need to drop and recreate it.
600        let old_scale = {
601            let services = self.services.lock().expect("poisoned");
602            services.get(&id).map(|states| states.len())
603        };
604        match old_scale {
605            Some(old) if old == usize::cast_from(scale) => return Ok(()),
606            Some(_) => self.drop_service(&id).await?,
607            None => (),
608        }
609
610        // Create sockets for all processes in the service.
611        let mut peer_addrs = Vec::new();
612        for i in 0..scale.into() {
613            let addresses = ports_in
614                .iter()
615                .map(|port| {
616                    let addr = socket_path(&run_dir, &port.name, i);
617                    (port.name.clone(), addr)
618                })
619                .collect();
620            peer_addrs.push(addresses);
621        }
622
623        {
624            let mut services = self.services.lock().expect("lock poisoned");
625
626            // Create the state for new processes.
627            let mut process_states = vec![];
628            for i in 0..usize::cast_from(scale) {
629                let listen_addrs = &peer_addrs[i];
630
631                // Fill out placeholders in the command wrapper for this process.
632                let mut command_wrapper = self.config.command_wrapper.clone();
633                if let Some(parts) = command_wrapper.get_mut(1..) {
634                    for part in parts {
635                        *part = interpolate_command(&part[..], &full_id, listen_addrs);
636                    }
637                }
638
639                // Allocate listeners for each TCP proxy, if requested.
640                let mut ports = vec![];
641                let mut tcp_proxy_addrs = BTreeMap::new();
642                for port in &ports_in {
643                    let tcp_proxy_listener = match &self.config.tcp_proxy {
644                        None => None,
645                        Some(tcp_proxy) => {
646                            let listener = StdTcpListener::bind((tcp_proxy.listen_addr, 0))
647                                .with_context(|| format!("binding to {}", tcp_proxy.listen_addr))?;
648                            listener.set_nonblocking(true)?;
649                            let listener = TcpListener::from_std(listener)?;
650                            let local_addr = listener.local_addr()?;
651                            tcp_proxy_addrs.insert(port.name.clone(), local_addr);
652                            Some(AddressedTcpListener {
653                                listener,
654                                local_addr,
655                            })
656                        }
657                    };
658                    ports.push(ServiceProcessPort {
659                        name: port.name.clone(),
660                        listen_addr: listen_addrs[&port.name].clone(),
661                        tcp_proxy_listener,
662                    });
663                }
664
665                let mut args = args(ServiceAssignments {
666                    listen_addrs,
667                    peer_addrs: &peer_addrs,
668                });
669                args.push(format!("--process={i}"));
670                if disk {
671                    if let Some(scratch) = &scratch_dir {
672                        args.push(format!("--scratch-directory={}", scratch.display()));
673                    } else {
674                        panic!(
675                            "internal error: service requested disk but no scratch directory was configured"
676                        );
677                    }
678                }
679
680                // Launch supervisor process.
681                let handle = mz_ore::task::spawn(
682                    || format!("process-orchestrator:{full_id}-{i}"),
683                    self.supervise_service_process(ServiceProcessConfig {
684                        id: id.to_string(),
685                        run_dir: run_dir.clone(),
686                        i,
687                        image: image.clone(),
688                        args,
689                        command_wrapper,
690                        ports,
691                        memory_limit,
692                        cpu_limit,
693                        launch_spec: self.config.launch_spec,
694                    }),
695                );
696
697                process_states.push(ProcessState {
698                    _handle: handle.abort_on_drop(),
699                    status: ProcessStatus::NotReady,
700                    status_time: Utc::now(),
701                    restart_count: 0,
702                    labels: labels.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
703                    tcp_proxy_addrs,
704                });
705            }
706
707            // Update the in-memory process state. We do this after we've created
708            // all process states to avoid partially updating our in-memory state.
709            services.insert(id, process_states);
710        }
711
712        self.maybe_write_prometheus_service_discovery_file().await;
713
714        Ok(())
715    }
716
717    async fn drop_service(&self, id: &str) -> Result<(), anyhow::Error> {
718        let full_id = self.config.full_id(id);
719        let run_dir = self.config.service_run_dir(id);
720        let scratch_dir = self.config.service_scratch_dir(id);
721
722        // Drop the supervisor for the service, if it exists. If this service
723        // was under supervision, this will kill all processes associated with
724        // it.
725        {
726            let mut supervisors = self.services.lock().expect("lock poisoned");
727            supervisors.remove(id);
728        }
729
730        // If the service was orphaned by a prior incarnation of the
731        // orchestrator, it won't have been under supervision and therefore will
732        // still be running. So kill any process that we have state for in the
733        // run directory.
734        if let Ok(mut entries) = fs::read_dir(&run_dir).await {
735            while let Some(entry) = entries.next_entry().await? {
736                let path = entry.path();
737                if path.extension() == Some(OsStr::new("pid")) {
738                    let mut system = System::new();
739                    let Some(process) = find_process_from_pid_file(&mut system, &path).await else {
740                        continue;
741                    };
742                    let pid = process.pid();
743                    info!("terminating orphaned process for {full_id} with PID {pid}");
744                    process.kill();
745                }
746            }
747        }
748
749        // Clean up the on-disk state of the service.
750        if let Err(e) = remove_dir_all(run_dir).await {
751            if e.kind() != io::ErrorKind::NotFound {
752                warn!(
753                    "error cleaning up run directory for {full_id}: {}",
754                    e.display_with_causes()
755                );
756            }
757        }
758        if let Err(e) = remove_dir_all(scratch_dir).await {
759            if e.kind() != io::ErrorKind::NotFound {
760                warn!(
761                    "error cleaning up scratch directory for {full_id}: {}",
762                    e.display_with_causes()
763                );
764            }
765        }
766
767        self.maybe_write_prometheus_service_discovery_file().await;
768        Ok(())
769    }
770
771    async fn list_services(&self) -> Result<Vec<String>, anyhow::Error> {
772        let mut services = vec![];
773        let namespace_prefix = format!("{}-", self.config.namespace);
774        let mut entries = fs::read_dir(&self.config.metadata_dir).await?;
775        while let Some(entry) = entries.next_entry().await? {
776            let filename = entry
777                .file_name()
778                .into_string()
779                .map_err(|_| anyhow!("unable to convert filename to string"))?;
780            if let Some(id) = filename.strip_prefix(&namespace_prefix) {
781                services.push(id.to_string());
782            }
783        }
784        Ok(services)
785    }
786
787    fn supervise_service_process(
788        &self,
789        ServiceProcessConfig {
790            id,
791            run_dir,
792            i,
793            image,
794            args,
795            command_wrapper,
796            ports,
797            memory_limit,
798            cpu_limit,
799            launch_spec,
800        }: ServiceProcessConfig,
801    ) -> impl Future<Output = ()> + use<> {
802        let suppress_output = self.config.suppress_output;
803        let propagate_crashes = self.config.propagate_crashes;
804        let image = self.config.image_dir.join(image);
805        let pid_file = run_dir.join(format!("{i}.pid"));
806        let full_id = self.config.full_id(&id);
807
808        let state_updater = ProcessStateUpdater {
809            namespace: self.config.namespace.clone(),
810            id,
811            i,
812            services: Arc::clone(&self.services),
813            service_event_tx: self.service_event_tx.clone(),
814        };
815
816        async move {
817            // Holds AbortOnDropHandles to keep proxy tasks alive.
818            #[allow(clippy::collection_is_never_read)]
819            let mut proxy_handles = vec![];
820            for port in ports {
821                if let Some(tcp_listener) = port.tcp_proxy_listener {
822                    info!(
823                        "{full_id}-{i}: {} tcp proxy listening on {}",
824                        port.name, tcp_listener.local_addr,
825                    );
826                    let uds_path = port.listen_addr;
827                    let handle = mz_ore::task::spawn(
828                        || format!("{full_id}-{i}-proxy-{}", port.name),
829                        tcp_proxy(TcpProxyConfig {
830                            name: format!("{full_id}-{i}-{}", port.name),
831                            tcp_listener,
832                            uds_path: uds_path.clone(),
833                        }),
834                    );
835                    proxy_handles.push(handle.abort_on_drop());
836                }
837            }
838
839            supervise_existing_process(&state_updater, &pid_file).await;
840
841            loop {
842                let mut cmd = launch_spec.refine_command(
843                    &image,
844                    &args,
845                    &command_wrapper,
846                    memory_limit.as_ref(),
847                    cpu_limit.as_ref(),
848                );
849                info!(
850                    "launching {full_id}-{i} via {} {}...",
851                    cmd.as_std().get_program().to_string_lossy(),
852                    cmd.as_std()
853                        .get_args()
854                        .map(|arg| arg.to_string_lossy())
855                        .join(" ")
856                );
857                if suppress_output {
858                    cmd.stdout(Stdio::null());
859                    cmd.stderr(Stdio::null());
860                }
861                match spawn_process(&state_updater, cmd, &pid_file, !command_wrapper.is_empty())
862                    .await
863                {
864                    Ok(status) => {
865                        assert!(
866                            !(propagate_crashes && did_process_crash(status)),
867                            "{full_id}-{i} crashed; aborting because propagate_crashes is enabled"
868                        );
869                        error!("{full_id}-{i} exited: {:?}; relaunching in 5s", status);
870                    }
871                    Err(e) => {
872                        error!("{full_id}-{i} failed to spawn: {}; relaunching in 5s", e);
873                    }
874                };
875                state_updater.update_state(ProcessStatus::NotReady);
876                time::sleep(Duration::from_secs(5)).await;
877            }
878        }
879    }
880
881    async fn maybe_write_prometheus_service_discovery_file(&self) {
882        #[derive(Serialize)]
883        struct StaticConfig {
884            labels: BTreeMap<String, String>,
885            targets: Vec<String>,
886        }
887
888        let Some(tcp_proxy) = &self.config.tcp_proxy else {
889            return;
890        };
891        let Some(dir) = &tcp_proxy.prometheus_service_discovery_dir else {
892            return;
893        };
894
895        let mut static_configs = vec![];
896        {
897            let services = self.services.lock().expect("lock poisoned");
898            for (id, states) in &*services {
899                for (i, state) in states.iter().enumerate() {
900                    for (name, addr) in &state.tcp_proxy_addrs {
901                        let mut labels = btreemap! {
902                            "mz_orchestrator_namespace".into() => self.config.namespace.clone(),
903                            "mz_orchestrator_service_id".into() => id.clone(),
904                            "mz_orchestrator_port".into() => name.clone(),
905                            "mz_orchestrator_ordinal".into() => i.to_string(),
906                        };
907                        for (k, v) in &state.labels {
908                            let k = format!("mz_orchestrator_{}", k.replace('-', "_"));
909                            labels.insert(k, v.clone());
910                        }
911                        static_configs.push(StaticConfig {
912                            labels,
913                            targets: vec![addr.to_string()],
914                        })
915                    }
916                }
917            }
918        }
919
920        let path = dir.join(Path::new(&self.config.namespace).with_extension("json"));
921        let contents = serde_json::to_vec_pretty(&static_configs).expect("valid json");
922        if let Err(e) = fs::write(&path, &contents).await {
923            warn!(
924                "{}: failed to write prometheus service discovery file: {}",
925                self.config.namespace,
926                e.display_with_causes()
927            );
928        }
929    }
930}
931
932struct ServiceProcessConfig {
933    id: String,
934    run_dir: PathBuf,
935    i: usize,
936    image: String,
937    args: Vec<String>,
938    command_wrapper: Vec<String>,
939    ports: Vec<ServiceProcessPort>,
940    memory_limit: Option<MemoryLimit>,
941    cpu_limit: Option<CpuLimit>,
942    launch_spec: LaunchSpec,
943}
944
945struct ServiceProcessPort {
946    name: String,
947    listen_addr: String,
948    tcp_proxy_listener: Option<AddressedTcpListener>,
949}
950
951/// Supervises an existing process, if it exists.
952async fn supervise_existing_process(state_updater: &ProcessStateUpdater, pid_file: &Path) {
953    let name = format!(
954        "{}-{}-{}",
955        state_updater.namespace, state_updater.id, state_updater.i
956    );
957
958    let mut system = System::new();
959    let Some(process) = find_process_from_pid_file(&mut system, pid_file).await else {
960        return;
961    };
962    let pid = process.pid();
963    let start_time = process.start_time();
964
965    info!(%pid, "discovered existing process for {name}");
966    state_updater.update_state(ProcessStatus::Ready { pid });
967
968    // Kill the process if the future is dropped.
969    let need_kill = AtomicBool::new(true);
970    defer! {
971        state_updater.update_state(ProcessStatus::NotReady);
972        if need_kill.load(Ordering::SeqCst) {
973            info!(%pid, "terminating existing process for {name}");
974            process.kill();
975        }
976    }
977
978    // Periodically check if the process has terminated. Verify start_time
979    // on each iteration to detect PID reuse.
980    let mut system = System::new();
981    loop {
982        if !system.refresh_process_specifics(pid, ProcessRefreshKind::new()) {
983            break;
984        }
985        match system.process(pid) {
986            Some(p) if p.start_time() == start_time => {}
987            _ => break,
988        }
989        time::sleep(Duration::from_secs(5)).await;
990    }
991
992    // The process has crashed. Exit the function without attempting to
993    // kill it.
994    warn!(%pid, "process for {name} has crashed; will reboot");
995    need_kill.store(false, Ordering::SeqCst)
996}
997
998fn interpolate_command(
999    command_part: &str,
1000    full_id: &str,
1001    ports: &BTreeMap<String, String>,
1002) -> String {
1003    let mut command_part = command_part.replace("%N", full_id);
1004    for (endpoint, port) in ports {
1005        command_part = command_part.replace(&format!("%P:{endpoint}"), port);
1006    }
1007    command_part
1008}
1009
1010async fn spawn_process(
1011    state_updater: &ProcessStateUpdater,
1012    mut cmd: Command,
1013    pid_file: &Path,
1014    send_sigterm: bool,
1015) -> Result<ExitStatus, anyhow::Error> {
1016    struct KillOnDropChild(Child, bool);
1017
1018    impl Drop for KillOnDropChild {
1019        fn drop(&mut self) {
1020            if let (Some(pid), true) = (self.0.id().and_then(|id| i32::try_from(id).ok()), self.1) {
1021                let _ = nix::sys::signal::kill(
1022                    nix::unistd::Pid::from_raw(pid),
1023                    nix::sys::signal::Signal::SIGTERM,
1024                );
1025                // Give the process a bit of time to react to the signal
1026                tokio::task::block_in_place(|| std::thread::sleep(Duration::from_millis(500)));
1027            }
1028            let _ = self.0.start_kill();
1029        }
1030    }
1031
1032    let mut child = KillOnDropChild(cmd.spawn()?, send_sigterm);
1033
1034    // Immediately write out a file containing the PID of the child process and
1035    // its start time. We'll use this state to rediscover our children if we
1036    // crash and restart. There's a very small window where we can crash after
1037    // having spawned the child but before writing this file, in which case we
1038    // might orphan the process. We accept this risk, though. It's hard to do
1039    // anything more robust given the Unix APIs available to us, and the
1040    // solution here is good enough given that the process orchestrator is only
1041    // used in development/testing.
1042    let pid = Pid::from_u32(child.0.id().unwrap());
1043    write_pid_file(pid_file, pid).await?;
1044    state_updater.update_state(ProcessStatus::Ready { pid });
1045    Ok(child.0.wait().await?)
1046}
1047
1048fn did_process_crash(status: ExitStatus) -> bool {
1049    // Likely not exhaustive. Feel free to add additional tests for other
1050    // indications of a crashed child process, as those conditions are
1051    // discovered.
1052    status.signal().is_some_and(|s| {
1053        matches!(
1054            Signal::try_from(s),
1055            Ok(Signal::SIGABRT
1056                | Signal::SIGBUS
1057                | Signal::SIGSEGV
1058                | Signal::SIGTRAP
1059                | Signal::SIGILL)
1060        )
1061    })
1062}
1063
1064async fn write_pid_file(pid_file: &Path, pid: Pid) -> Result<(), anyhow::Error> {
1065    let mut system = System::new();
1066    system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1067    let start_time = system.process(pid).map_or(0, |p| p.start_time());
1068    fs::write(pid_file, format!("{pid}\n{start_time}\n")).await?;
1069    Ok(())
1070}
1071
1072async fn find_process_from_pid_file<'a>(
1073    system: &'a mut System,
1074    pid_file: &Path,
1075) -> Option<&'a Process> {
1076    let Ok(contents) = fs::read_to_string(pid_file).await else {
1077        return None;
1078    };
1079    let lines = contents.trim().split('\n').collect::<Vec<_>>();
1080    let [pid, start_time] = lines.as_slice() else {
1081        return None;
1082    };
1083    let Ok(pid) = Pid::from_str(pid) else {
1084        return None;
1085    };
1086    let Ok(start_time) = u64::from_str(start_time) else {
1087        return None;
1088    };
1089    system.refresh_process_specifics(pid, ProcessRefreshKind::new());
1090    let process = system.process(pid)?;
1091    // Checking the start time protects against killing an unrelated process due
1092    // to PID reuse.
1093    if process.start_time() != start_time {
1094        return None;
1095    }
1096    Some(process)
1097}
1098
1099struct TcpProxyConfig {
1100    name: String,
1101    tcp_listener: AddressedTcpListener,
1102    uds_path: String,
1103}
1104
1105async fn tcp_proxy(
1106    TcpProxyConfig {
1107        name,
1108        tcp_listener,
1109        uds_path,
1110    }: TcpProxyConfig,
1111) {
1112    let mut conns = FuturesUnordered::new();
1113    loop {
1114        select! {
1115            res = tcp_listener.listener.accept() => {
1116                debug!("{name}: accepting tcp proxy connection");
1117                let uds_path = uds_path.clone();
1118                conns.push(Box::pin(async move {
1119                    let (mut tcp_conn, _) = res.context("accepting tcp connection")?;
1120                    let mut uds_conn = UnixStream::connect(uds_path)
1121                        .await
1122                        .context("making uds connection")?;
1123                    io::copy_bidirectional(&mut tcp_conn, &mut uds_conn)
1124                        .await
1125                        .context("proxying")
1126                }));
1127            }
1128            Some(result) = conns.next() => if let Err(e) = result {
1129                warn!("{name}: tcp proxy connection failed: {}", e.display_with_causes());
1130            }
1131        }
1132    }
1133}
1134
1135struct ProcessStateUpdater {
1136    namespace: String,
1137    id: String,
1138    i: usize,
1139    services: Arc<Mutex<BTreeMap<String, Vec<ProcessState>>>>,
1140    service_event_tx: broadcast::Sender<ServiceEvent>,
1141}
1142
1143impl ProcessStateUpdater {
1144    fn update_state(&self, status: ProcessStatus) {
1145        let mut services = self.services.lock().expect("lock poisoned");
1146        let Some(process_states) = services.get_mut(&self.id) else {
1147            return;
1148        };
1149        let Some(process_state) = process_states.get_mut(self.i) else {
1150            return;
1151        };
1152        let status_time = Utc::now();
1153        // Count each transition to NotReady as a restart. The process
1154        // orchestrator always relaunches a process that exits, so a death is a
1155        // restart. This is monotonic for a given `ProcessState` and changes on
1156        // every restart, which is what the 0dt caught-up check needs. It only
1157        // resets to zero if the whole service is dropped and recreated.
1158        if matches!(status, ProcessStatus::NotReady) {
1159            process_state.restart_count += 1;
1160        }
1161        process_state.status = status;
1162        process_state.status_time = status_time;
1163        let _ = self.service_event_tx.send(ServiceEvent {
1164            service_id: self.id.to_string(),
1165            process_id: u64::cast_from(self.i),
1166            status: status.into(),
1167            restart_count: process_state.restart_count,
1168            time: status_time,
1169        });
1170    }
1171}
1172
1173#[derive(Debug)]
1174struct ProcessState {
1175    _handle: AbortOnDropHandle<()>,
1176    status: ProcessStatus,
1177    status_time: DateTime<Utc>,
1178    /// Number of times this process has died and been relaunched. Monotonic for
1179    /// the lifetime of this `ProcessState`. See [`ProcessStateUpdater::update_state`].
1180    restart_count: u64,
1181    labels: BTreeMap<String, String>,
1182    tcp_proxy_addrs: BTreeMap<String, SocketAddr>,
1183}
1184
1185impl ProcessState {
1186    fn pid(&self) -> Option<Pid> {
1187        match &self.status {
1188            ProcessStatus::NotReady => None,
1189            ProcessStatus::Ready { pid } => Some(*pid),
1190        }
1191    }
1192}
1193
1194#[derive(Debug, Clone, Copy)]
1195enum ProcessStatus {
1196    NotReady,
1197    Ready { pid: Pid },
1198}
1199
1200impl From<ProcessStatus> for ServiceStatus {
1201    fn from(status: ProcessStatus) -> ServiceStatus {
1202        match status {
1203            ProcessStatus::NotReady => ServiceStatus::Offline(None),
1204            ProcessStatus::Ready { .. } => ServiceStatus::Online,
1205        }
1206    }
1207}
1208
1209fn socket_path(run_dir: &Path, port: &str, process: u16) -> String {
1210    let desired = run_dir
1211        .join(format!("{port}-{process}"))
1212        .to_string_lossy()
1213        .into_owned();
1214    if UnixSocketAddr::from_pathname(&desired).is_err() {
1215        // Unix socket addresses have a very low maximum length of around 100
1216        // bytes on most platforms.
1217        env::temp_dir()
1218            .join(hex::encode(Sha1::digest(desired)))
1219            .display()
1220            .to_string()
1221    } else {
1222        desired
1223    }
1224}
1225
1226struct AddressedTcpListener {
1227    listener: TcpListener,
1228    local_addr: SocketAddr,
1229}
1230
1231#[derive(Debug)]
1232struct ProcessService {
1233    run_dir: PathBuf,
1234    scale: NonZero<u16>,
1235}
1236
1237impl Service for ProcessService {
1238    fn addresses(&self, port: &str) -> Vec<String> {
1239        (0..self.scale.get())
1240            .map(|i| socket_path(&self.run_dir, port, i))
1241            .collect()
1242    }
1243}