Skip to main content

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