mz_orchestrator/
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::fmt;
12use std::str::FromStr;
13use std::sync::Arc;
14
15use async_trait::async_trait;
16use bytesize::ByteSize;
17use chrono::{DateTime, Utc};
18use derivative::Derivative;
19use futures_core::stream::BoxStream;
20use mz_ore::cast::CastFrom;
21use serde::de::Unexpected;
22use serde::{Deserialize, Deserializer, Serialize};
23
24/// An orchestrator manages services.
25///
26/// A service is a set of one or more processes running the same image. See
27/// [`ServiceConfig`] for details.
28///
29/// All services live within a namespace. A namespace allows multiple users to
30/// share an orchestrator without conflicting: each user can only create,
31/// delete, and list the services within their namespace. Namespaces are not
32/// isolated at the network level, however: services in one namespace can
33/// communicate with services in another namespace with no restrictions.
34///
35/// Services **must** be tolerant of running as part of a distributed system. In
36/// particular, services **must** be prepared for the possibility that there are
37/// two live processes with the same identity. This can happen, for example,
38/// when the machine hosting a process *appears* to fail, from the perspective
39/// of the orchestrator, and so the orchestrator restarts the process on another
40/// machine, but in fact the original machine is still alive, just on the
41/// opposite side of a network partition. Be sure to design any communication
42/// with other services (e.g., an external database) to correctly handle
43/// competing communication from another incarnation of the service.
44///
45/// The intent is that you can implement `Orchestrator` with pods in Kubernetes,
46/// containers in Docker, or processes on your local machine.
47pub trait Orchestrator: fmt::Debug + Send + Sync {
48    /// Enter a namespace in the orchestrator.
49    fn namespace(&self, namespace: &str) -> Arc<dyn NamespacedOrchestrator>;
50}
51
52/// An orchestrator restricted to a single namespace.
53#[async_trait]
54pub trait NamespacedOrchestrator: fmt::Debug + Send + Sync {
55    /// Ensures that a service with the given configuration is running.
56    ///
57    /// If a service with the same ID already exists, its configuration is
58    /// updated to match `config`. This may or may not involve restarting the
59    /// service, depending on whether the existing service matches `config`.
60    fn ensure_service(
61        &self,
62        id: &str,
63        config: ServiceConfig,
64    ) -> Result<Box<dyn Service>, anyhow::Error>;
65
66    /// Drops the identified service, if it exists.
67    fn drop_service(&self, id: &str) -> Result<(), anyhow::Error>;
68
69    /// Lists the identifiers of all known services.
70    async fn list_services(&self) -> Result<Vec<String>, anyhow::Error>;
71
72    /// Watch for status changes of all known services.
73    fn watch_services(&self) -> BoxStream<'static, Result<ServiceEvent, anyhow::Error>>;
74
75    /// Gets resource usage metrics for all processes associated with a service.
76    ///
77    /// Returns `Err` if the entire process failed. Returns `Ok(v)` otherwise,
78    /// with one element in `v` for each process of the service,
79    /// even in not all metrics could be collected for all processes.
80    /// In such a case, the corresponding fields of `ServiceProcessMetrics` will be `None`.
81    async fn fetch_service_metrics(
82        &self,
83        id: &str,
84    ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error>;
85
86    fn update_scheduling_config(&self, config: scheduling_config::ServiceSchedulingConfig);
87}
88
89/// An event describing a status change of an orchestrated service.
90#[derive(Debug, Clone, Serialize)]
91pub struct ServiceEvent {
92    pub service_id: String,
93    pub process_id: u64,
94    pub status: ServiceStatus,
95    pub time: DateTime<Utc>,
96}
97
98/// Why the service is not ready, if known
99#[derive(Debug, Clone, Copy, Serialize, Eq, PartialEq)]
100pub enum OfflineReason {
101    OomKilled,
102    Initializing,
103}
104
105impl fmt::Display for OfflineReason {
106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107        match self {
108            OfflineReason::OomKilled => f.write_str("oom-killed"),
109            OfflineReason::Initializing => f.write_str("initializing"),
110        }
111    }
112}
113
114/// Describes the status of an orchestrated service.
115#[derive(Debug, Clone, Copy, Serialize, Eq, PartialEq)]
116pub enum ServiceStatus {
117    /// Service is ready to accept requests.
118    Online,
119    /// Service is not ready to accept requests.
120    /// The inner element is `None` if the reason
121    /// is unknown
122    Offline(Option<OfflineReason>),
123}
124
125impl ServiceStatus {
126    /// Returns the service status as a kebab-case string.
127    pub fn as_kebab_case_str(&self) -> &'static str {
128        match self {
129            ServiceStatus::Online => "online",
130            ServiceStatus::Offline(_) => "offline",
131        }
132    }
133}
134
135/// Describes a running service managed by an `Orchestrator`.
136pub trait Service: fmt::Debug + Send + Sync {
137    /// Given the name of a port, returns the addresses for each of the
138    /// service's processes, in order.
139    ///
140    /// Panics if `port` does not name a valid port.
141    fn addresses(&self, port: &str) -> Vec<String>;
142}
143
144#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
145pub struct ServiceProcessMetrics {
146    pub cpu_nano_cores: Option<u64>,
147    pub memory_bytes: Option<u64>,
148    pub disk_usage_bytes: Option<u64>,
149}
150
151/// A simple language for describing assertions about a label's existence and value.
152///
153/// Used by [`LabelSelector`].
154#[derive(Clone, Debug)]
155pub enum LabelSelectionLogic {
156    /// The label exists and its value equals the given value.
157    /// Equivalent to `InSet { values: vec![value] }`
158    Eq { value: String },
159    /// Either the label does not exist, or it exists
160    /// but its value does not equal the given value.
161    /// Equivalent to `NotInSet { values: vec![value] }`
162    NotEq { value: String },
163    /// The label exists.
164    Exists,
165    /// The label does not exist.
166    NotExists,
167    /// The label exists and its value is one of the given values.
168    InSet { values: Vec<String> },
169    /// Either the label does not exist, or it exists
170    /// but its value is not one of the given values.
171    NotInSet { values: Vec<String> },
172}
173
174/// A simple language for describing whether a label
175/// exists and whether the value corresponding to it is in some set.
176/// Intended to correspond to the capabilities offered by Kubernetes label selectors,
177/// but without directly exposing Kubernetes API code to consumers of this module.
178#[derive(Clone, Debug)]
179pub struct LabelSelector {
180    /// The name of the label
181    pub label_name: String,
182    /// An assertion about the existence and value of a label
183    /// named `label_name`
184    pub logic: LabelSelectionLogic,
185}
186
187/// Describes the desired state of a service.
188#[derive(Derivative)]
189#[derivative(Debug)]
190pub struct ServiceConfig {
191    /// An opaque identifier for the executable or container image to run.
192    ///
193    /// Often names a container on Docker Hub or a path on the local machine.
194    pub image: String,
195    /// For the Kubernetes orchestrator, this is an init container to
196    /// configure for the pod running the service.
197    pub init_container_image: Option<String>,
198    /// A function that generates the arguments for each process of the service
199    /// given the assigned listen addresses for each named port.
200    #[derivative(Debug = "ignore")]
201    pub args: Box<dyn Fn(&BTreeMap<String, String>) -> Vec<String> + Send + Sync>,
202    /// Ports to expose.
203    pub ports: Vec<ServicePort>,
204    /// An optional limit on the memory that the service can use.
205    pub memory_limit: Option<MemoryLimit>,
206    /// An optional limit on the CPU that the service can use.
207    pub cpu_limit: Option<CpuLimit>,
208    /// The number of copies of this service to run.
209    pub scale: u16,
210    /// Arbitrary key–value pairs to attach to the service in the orchestrator
211    /// backend.
212    ///
213    /// The orchestrator backend may apply a prefix to the key if appropriate.
214    pub labels: BTreeMap<String, String>,
215    /// The availability zones the service can be run in. If no availability
216    /// zones are specified, the orchestrator is free to choose one.
217    pub availability_zones: Option<Vec<String>>,
218    /// A set of label selectors selecting all _other_ services that are replicas of this one.
219    ///
220    /// This may be used to implement anti-affinity. If _all_ such selectors
221    /// match for a given service, this service should not be co-scheduled on
222    /// a machine with that service.
223    ///
224    /// The orchestrator backend may or may not actually implement anti-affinity functionality.
225    pub other_replicas_selector: Vec<LabelSelector>,
226    /// A set of label selectors selecting all services that are replicas of this one,
227    /// including itself.
228    ///
229    /// This may be used to implement placement spread.
230    ///
231    /// The orchestrator backend may or may not actually implement placement spread functionality.
232    pub replicas_selector: Vec<LabelSelector>,
233
234    /// Whether scratch disk space should be allocated for the service.
235    pub disk: bool,
236    /// The maximum amount of scratch disk space that the service is allowed to consume.
237    pub disk_limit: Option<DiskLimit>,
238    /// Node selector for this service.
239    pub node_selector: BTreeMap<String, String>,
240}
241
242/// A named port associated with a service.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct ServicePort {
245    /// A descriptive name for the port.
246    ///
247    /// Note that not all orchestrator backends make use of port names.
248    pub name: String,
249    /// The desired port number.
250    ///
251    /// Not all orchestrator backends will make use of the hint.
252    pub port_hint: u16,
253}
254
255/// Describes a limit on memory.
256#[derive(Copy, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
257pub struct MemoryLimit(pub ByteSize);
258
259impl MemoryLimit {
260    pub const MAX: Self = Self(ByteSize(u64::MAX));
261}
262
263impl<'de> Deserialize<'de> for MemoryLimit {
264    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
265    where
266        D: Deserializer<'de>,
267    {
268        <String as Deserialize>::deserialize(deserializer)
269            .and_then(|s| {
270                ByteSize::from_str(&s).map_err(|_e| {
271                    use serde::de::Error;
272                    D::Error::invalid_value(serde::de::Unexpected::Str(&s), &"valid size in bytes")
273                })
274            })
275            .map(MemoryLimit)
276    }
277}
278
279impl Serialize for MemoryLimit {
280    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
281    where
282        S: serde::Serializer,
283    {
284        <String as Serialize>::serialize(&self.0.to_string(), serializer)
285    }
286}
287
288/// Describes a limit on CPU resources.
289#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
290pub struct CpuLimit {
291    millicpus: usize,
292}
293
294impl CpuLimit {
295    pub const MAX: Self = Self::from_millicpus(usize::MAX / 1_000_000);
296
297    /// Constructs a new CPU limit from a number of millicpus.
298    pub const fn from_millicpus(millicpus: usize) -> CpuLimit {
299        CpuLimit { millicpus }
300    }
301
302    /// Returns the CPU limit in millicpus.
303    pub fn as_millicpus(&self) -> usize {
304        self.millicpus
305    }
306
307    /// Returns the CPU limit in nanocpus.
308    pub fn as_nanocpus(&self) -> u64 {
309        // The largest possible value of a u64 is
310        // 18_446_744_073_709_551_615,
311        // so we won't overflow this
312        // unless we have an instance with
313        // ~18.45 billion cores.
314        //
315        // Such an instance seems unrealistic,
316        // at least until we raise another few rounds
317        // of funding ...
318
319        u64::cast_from(self.millicpus)
320            .checked_mul(1_000_000)
321            .expect("Nano-CPUs must be representable")
322    }
323}
324
325impl<'de> Deserialize<'de> for CpuLimit {
326    // TODO(benesch): remove this once this function no longer makes use of
327    // potentially dangerous `as` conversions.
328    #[allow(clippy::as_conversions)]
329    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
330    where
331        D: serde::Deserializer<'de>,
332    {
333        // Note -- we just round off any precision beyond 0.001 here.
334        let float = f64::deserialize(deserializer)?;
335        let millicpus = (float * 1000.).round();
336        if millicpus < 0. || millicpus > (std::usize::MAX as f64) {
337            use serde::de::Error;
338            Err(D::Error::invalid_value(
339                Unexpected::Float(float),
340                &"a float representing a plausible number of CPUs",
341            ))
342        } else {
343            Ok(Self {
344                millicpus: millicpus as usize,
345            })
346        }
347    }
348}
349
350impl Serialize for CpuLimit {
351    // TODO(benesch): remove this once this function no longer makes use of
352    // potentially dangerous `as` conversions.
353    #[allow(clippy::as_conversions)]
354    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
355    where
356        S: serde::Serializer,
357    {
358        <f64 as Serialize>::serialize(&(self.millicpus as f64 / 1000.0), serializer)
359    }
360}
361
362/// Describes a limit on disk usage.
363#[derive(Copy, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
364pub struct DiskLimit(pub ByteSize);
365
366impl DiskLimit {
367    pub const ZERO: Self = Self(ByteSize(0));
368    pub const MAX: Self = Self(ByteSize(u64::MAX));
369    pub const ARBITRARY: Self = Self(ByteSize::gib(1));
370}
371
372impl<'de> Deserialize<'de> for DiskLimit {
373    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
374    where
375        D: Deserializer<'de>,
376    {
377        <String as Deserialize>::deserialize(deserializer)
378            .and_then(|s| {
379                ByteSize::from_str(&s).map_err(|_e| {
380                    use serde::de::Error;
381                    D::Error::invalid_value(serde::de::Unexpected::Str(&s), &"valid size in bytes")
382                })
383            })
384            .map(DiskLimit)
385    }
386}
387
388impl Serialize for DiskLimit {
389    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
390    where
391        S: serde::Serializer,
392    {
393        <String as Serialize>::serialize(&self.0.to_string(), serializer)
394    }
395}
396
397/// Configuration for how services are scheduled. These may be ignored by orchestrator
398/// implementations.
399pub mod scheduling_config {
400    #[derive(Debug, Clone)]
401    pub struct ServiceTopologySpreadConfig {
402        /// If `true`, enable spread for replicated services.
403        ///
404        /// Defaults to `true`.
405        pub enabled: bool,
406        /// If `true`, ignore services with `scale` > 1 when expressing
407        /// spread constraints.
408        ///
409        /// Default to `true`.
410        pub ignore_non_singular_scale: bool,
411        /// The `maxSkew` for spread constraints.
412        /// See
413        /// <https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/>
414        /// for more details.
415        ///
416        /// Defaults to `1`.
417        pub max_skew: i32,
418        /// If `true`, make the spread constraints into a preference.
419        ///
420        /// Defaults to `false`.
421        pub soft: bool,
422    }
423
424    #[derive(Debug, Clone)]
425    pub struct ServiceSchedulingConfig {
426        /// If `Some`, add a affinity preference with the given
427        /// weight for services that horizontally scale.
428        ///
429        /// Defaults to `Some(100)`.
430        pub multi_pod_az_affinity_weight: Option<i32>,
431        /// If `true`, make the node-scope anti-affinity between
432        /// replicated services a preference over a constraint.
433        ///
434        /// Defaults to `false`.
435        pub soften_replication_anti_affinity: bool,
436        /// The weight for `soften_replication_anti_affinity.
437        ///
438        /// Defaults to `100`.
439        pub soften_replication_anti_affinity_weight: i32,
440        /// Configuration for `TopologySpreadConstraint`'s
441        pub topology_spread: ServiceTopologySpreadConfig,
442        /// If `true`, make the az-scope node affinity soft.
443        ///
444        /// Defaults to `false`.
445        pub soften_az_affinity: bool,
446        /// The weight for `soften_replication_anti_affinity.
447        ///
448        /// Defaults to `100`.
449        pub soften_az_affinity_weight: i32,
450        /// Whether to always provision a replica with disk,
451        /// regardless of `DISK` DDL option.
452        ///
453        /// Defaults to `false`.
454        pub always_use_disk: bool,
455        // Whether to enable security context for the service.
456        pub security_context_enabled: bool,
457    }
458
459    pub const DEFAULT_POD_AZ_AFFINITY_WEIGHT: Option<i32> = Some(100);
460    pub const DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY: bool = false;
461    pub const DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT: i32 = 100;
462
463    pub const DEFAULT_TOPOLOGY_SPREAD_ENABLED: bool = true;
464    pub const DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE: bool = true;
465    pub const DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW: i32 = 1;
466    pub const DEFAULT_TOPOLOGY_SPREAD_SOFT: bool = false;
467
468    pub const DEFAULT_SOFTEN_AZ_AFFINITY: bool = false;
469    pub const DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT: i32 = 100;
470    pub const DEFAULT_ALWAYS_USE_DISK: bool = false;
471    pub const DEFAULT_SECURITY_CONTEXT_ENABLED: bool = true;
472
473    impl Default for ServiceSchedulingConfig {
474        fn default() -> Self {
475            ServiceSchedulingConfig {
476                multi_pod_az_affinity_weight: DEFAULT_POD_AZ_AFFINITY_WEIGHT,
477                soften_replication_anti_affinity: DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY,
478                soften_replication_anti_affinity_weight:
479                    DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT,
480                topology_spread: ServiceTopologySpreadConfig {
481                    enabled: DEFAULT_TOPOLOGY_SPREAD_ENABLED,
482                    ignore_non_singular_scale: DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE,
483                    max_skew: DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW,
484                    soft: DEFAULT_TOPOLOGY_SPREAD_SOFT,
485                },
486                soften_az_affinity: DEFAULT_SOFTEN_AZ_AFFINITY,
487                soften_az_affinity_weight: DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT,
488                always_use_disk: DEFAULT_ALWAYS_USE_DISK,
489                security_context_enabled: DEFAULT_SECURITY_CONTEXT_ENABLED,
490            }
491        }
492    }
493}