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}
158
159/// A simple language for describing assertions about a label's existence and value.
160///
161/// Used by [`LabelSelector`].
162#[derive(Clone, Debug)]
163pub enum LabelSelectionLogic {
164    /// The label exists and its value equals the given value.
165    /// Equivalent to `InSet { values: vec![value] }`
166    Eq { value: String },
167    /// Either the label does not exist, or it exists
168    /// but its value does not equal the given value.
169    /// Equivalent to `NotInSet { values: vec![value] }`
170    NotEq { value: String },
171    /// The label exists.
172    Exists,
173    /// The label does not exist.
174    NotExists,
175    /// The label exists and its value is one of the given values.
176    InSet { values: Vec<String> },
177    /// Either the label does not exist, or it exists
178    /// but its value is not one of the given values.
179    NotInSet { values: Vec<String> },
180}
181
182/// A simple language for describing whether a label
183/// exists and whether the value corresponding to it is in some set.
184/// Intended to correspond to the capabilities offered by Kubernetes label selectors,
185/// but without directly exposing Kubernetes API code to consumers of this module.
186#[derive(Clone, Debug)]
187pub struct LabelSelector {
188    /// The name of the label
189    pub label_name: String,
190    /// An assertion about the existence and value of a label
191    /// named `label_name`
192    pub logic: LabelSelectionLogic,
193}
194
195/// Describes the desired state of a service.
196#[derive(Derivative)]
197#[derivative(Debug)]
198pub struct ServiceConfig {
199    /// Static application name (usually present in labels)
200    pub app_name: String,
201    /// An opaque identifier for the executable or container image to run.
202    ///
203    /// Often names a container on Docker Hub or a path on the local machine.
204    pub image: String,
205    /// For the Kubernetes orchestrator, this is an init container to
206    /// configure for the pod running the service.
207    pub init_container_image: Option<String>,
208    /// A function that generates the arguments for each process of the service
209    /// given the assigned listen addresses for each named port.
210    #[derivative(Debug = "ignore")]
211    pub args: Box<dyn Fn(ServiceAssignments) -> Vec<String> + Send + Sync>,
212    /// Ports to expose.
213    pub ports: Vec<ServicePort>,
214    /// An optional limit on the memory that the service can use.
215    pub memory_limit: Option<MemoryLimit>,
216    /// An optional request on the memory that the service can use. If unspecified,
217    /// use the same value as `memory_limit`.
218    pub memory_request: Option<MemoryLimit>,
219    /// An optional limit on the CPU that the service can use.
220    pub cpu_limit: Option<CpuLimit>,
221    /// An optional request on the CPU that the service can use.
222    pub cpu_request: Option<CpuLimit>,
223    /// The number of copies of this service to run.
224    pub scale: NonZero<u16>,
225    /// Arbitrary key–value pairs to attach to the service in the orchestrator
226    /// backend.
227    ///
228    /// The orchestrator backend may apply a prefix to the key if appropriate.
229    pub labels: BTreeMap<String, String>,
230    /// Arbitrary key–value pairs to attach to the service as annotations in the
231    /// orchestrator backend.
232    ///
233    /// The orchestrator backend may apply a prefix to the key if appropriate.
234    pub annotations: BTreeMap<String, String>,
235    /// The availability zones the service can be run in. If no availability
236    /// zones are specified, the orchestrator is free to choose one.
237    pub availability_zones: Option<Vec<String>>,
238    /// A set of label selectors selecting all _other_ services that are replicas of this one.
239    ///
240    /// This may be used to implement anti-affinity. If _all_ such selectors
241    /// match for a given service, this service should not be co-scheduled on
242    /// a machine with that service.
243    ///
244    /// The orchestrator backend may or may not actually implement anti-affinity functionality.
245    pub other_replicas_selector: Vec<LabelSelector>,
246    /// A set of label selectors selecting all services that are replicas of this one,
247    /// including itself.
248    ///
249    /// This may be used to implement placement spread.
250    ///
251    /// The orchestrator backend may or may not actually implement placement spread functionality.
252    pub replicas_selector: Vec<LabelSelector>,
253
254    /// The maximum amount of scratch disk space that the service is allowed to consume.
255    pub disk_limit: Option<DiskLimit>,
256    /// Node selector for this service.
257    pub node_selector: BTreeMap<String, String>,
258}
259
260/// Get the recommended Kubernetes labels (app.kubernetes.io/*)
261/// WARNING: this is duplicated in src/orchestratord/src/k8s.rs and src/cloud-resources/src/crd.rs
262pub fn recommended_k8s_labels(app_name: String) -> BTreeMap<String, String> {
263    BTreeMap::from_iter([
264        (
265            "app.kubernetes.io/managed-by".to_owned(),
266            "materialize-operator".to_owned(),
267        ),
268        (
269            "app.kubernetes.io/part-of".to_owned(),
270            "materialize".to_owned(),
271        ),
272        ("app.kubernetes.io/name".to_owned(), app_name.to_owned()),
273        // legacy label
274        ("app".to_owned(), app_name.to_owned()),
275    ])
276}
277
278/// A named port associated with a service.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct ServicePort {
281    /// A descriptive name for the port.
282    ///
283    /// Note that not all orchestrator backends make use of port names.
284    pub name: String,
285    /// The desired port number.
286    ///
287    /// Not all orchestrator backends will make use of the hint.
288    pub port_hint: u16,
289}
290
291/// Assignments that the orchestrator has made for a process in a service.
292#[derive(Clone, Debug)]
293pub struct ServiceAssignments<'a> {
294    /// For each specified [`ServicePort`] name, a listen address.
295    pub listen_addrs: &'a BTreeMap<String, String>,
296    /// The listen addresses of each peer in the service.
297    ///
298    /// The order of peers is significant. Each peer is uniquely identified by its position in the
299    /// list.
300    pub peer_addrs: &'a [BTreeMap<String, String>],
301}
302
303impl ServiceAssignments<'_> {
304    /// Return the peer addresses for the specified [`ServicePort`] name.
305    pub fn peer_addresses(&self, name: &str) -> Vec<String> {
306        self.peer_addrs.iter().map(|a| a[name].clone()).collect()
307    }
308}
309
310/// Describes a limit on memory.
311#[derive(Copy, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
312pub struct MemoryLimit(pub ByteSize);
313
314impl MemoryLimit {
315    pub const MAX: Self = Self(ByteSize(u64::MAX));
316}
317
318impl<'de> Deserialize<'de> for MemoryLimit {
319    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
320    where
321        D: Deserializer<'de>,
322    {
323        <String as Deserialize>::deserialize(deserializer)
324            .and_then(|s| {
325                ByteSize::from_str(&s).map_err(|_e| {
326                    use serde::de::Error;
327                    D::Error::invalid_value(serde::de::Unexpected::Str(&s), &"valid size in bytes")
328                })
329            })
330            .map(MemoryLimit)
331    }
332}
333
334impl Serialize for MemoryLimit {
335    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336    where
337        S: serde::Serializer,
338    {
339        <String as Serialize>::serialize(&self.0.to_string(), serializer)
340    }
341}
342
343/// Describes a limit on CPU resources.
344#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
345pub struct CpuLimit {
346    millicpus: usize,
347}
348
349impl CpuLimit {
350    pub const MAX: Self = Self::from_millicpus(usize::MAX / 1_000_000);
351
352    /// Constructs a new CPU limit from a number of millicpus.
353    pub const fn from_millicpus(millicpus: usize) -> CpuLimit {
354        CpuLimit { millicpus }
355    }
356
357    /// Returns the CPU limit in millicpus.
358    pub fn as_millicpus(&self) -> usize {
359        self.millicpus
360    }
361
362    /// Returns the CPU limit in nanocpus.
363    pub fn as_nanocpus(&self) -> u64 {
364        // The largest possible value of a u64 is
365        // 18_446_744_073_709_551_615,
366        // so we won't overflow this
367        // unless we have an instance with
368        // ~18.45 billion cores.
369        //
370        // Such an instance seems unrealistic,
371        // at least until we raise another few rounds
372        // of funding ...
373
374        u64::cast_from(self.millicpus)
375            .checked_mul(1_000_000)
376            .expect("Nano-CPUs must be representable")
377    }
378}
379
380impl<'de> Deserialize<'de> for CpuLimit {
381    // TODO(benesch): remove this once this function no longer makes use of
382    // potentially dangerous `as` conversions.
383    #[allow(clippy::as_conversions)]
384    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
385    where
386        D: serde::Deserializer<'de>,
387    {
388        // Note -- we just round off any precision beyond 0.001 here.
389        let float = f64::deserialize(deserializer)?;
390        let millicpus = (float * 1000.).round();
391        if millicpus < 0. || millicpus > (std::usize::MAX as f64) {
392            use serde::de::Error;
393            Err(D::Error::invalid_value(
394                Unexpected::Float(float),
395                &"a float representing a plausible number of CPUs",
396            ))
397        } else {
398            Ok(Self {
399                millicpus: millicpus as usize,
400            })
401        }
402    }
403}
404
405impl Serialize for CpuLimit {
406    // TODO(benesch): remove this once this function no longer makes use of
407    // potentially dangerous `as` conversions.
408    #[allow(clippy::as_conversions)]
409    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
410    where
411        S: serde::Serializer,
412    {
413        <f64 as Serialize>::serialize(&(self.millicpus as f64 / 1000.0), serializer)
414    }
415}
416
417/// Describes a limit on disk usage.
418#[derive(Copy, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
419pub struct DiskLimit(pub ByteSize);
420
421impl DiskLimit {
422    pub const ZERO: Self = Self(ByteSize(0));
423    pub const MAX: Self = Self(ByteSize(u64::MAX));
424    pub const ARBITRARY: Self = Self(ByteSize::gib(1));
425}
426
427impl<'de> Deserialize<'de> for DiskLimit {
428    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
429    where
430        D: Deserializer<'de>,
431    {
432        <String as Deserialize>::deserialize(deserializer)
433            .and_then(|s| {
434                ByteSize::from_str(&s).map_err(|_e| {
435                    use serde::de::Error;
436                    D::Error::invalid_value(serde::de::Unexpected::Str(&s), &"valid size in bytes")
437                })
438            })
439            .map(DiskLimit)
440    }
441}
442
443impl Serialize for DiskLimit {
444    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
445    where
446        S: serde::Serializer,
447    {
448        <String as Serialize>::serialize(&self.0.to_string(), serializer)
449    }
450}
451
452/// Configuration for how services are scheduled. These may be ignored by orchestrator
453/// implementations.
454pub mod scheduling_config {
455    #[derive(Debug, Clone)]
456    pub struct ServiceTopologySpreadConfig {
457        /// If `true`, enable spread for replicated services.
458        ///
459        /// Defaults to `true`.
460        pub enabled: bool,
461        /// If `true`, ignore services with `scale` > 1 when expressing
462        /// spread constraints.
463        ///
464        /// Default to `true`.
465        pub ignore_non_singular_scale: bool,
466        /// The `maxSkew` for spread constraints.
467        /// See
468        /// <https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/>
469        /// for more details.
470        ///
471        /// Defaults to `1`.
472        pub max_skew: i32,
473        /// The `minDomains` for spread constraints.
474        /// See
475        /// <https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/>
476        /// for more details.
477        ///
478        /// Defaults to None.
479        pub min_domains: Option<i32>,
480        /// If `true`, make the spread constraints into a preference.
481        ///
482        /// Defaults to `false`.
483        pub soft: bool,
484    }
485
486    #[derive(Debug, Clone)]
487    pub struct ServiceSchedulingConfig {
488        /// If `Some`, add a affinity preference with the given
489        /// weight for services that horizontally scale.
490        ///
491        /// Defaults to `Some(100)`.
492        pub multi_pod_az_affinity_weight: Option<i32>,
493        /// If `true`, make the node-scope anti-affinity between
494        /// replicated services a preference over a constraint.
495        ///
496        /// Defaults to `false`.
497        pub soften_replication_anti_affinity: bool,
498        /// The weight for `soften_replication_anti_affinity.
499        ///
500        /// Defaults to `100`.
501        pub soften_replication_anti_affinity_weight: i32,
502        /// Configuration for `TopologySpreadConstraint`'s
503        pub topology_spread: ServiceTopologySpreadConfig,
504        /// If `true`, make the az-scope node affinity soft.
505        ///
506        /// Defaults to `false`.
507        pub soften_az_affinity: bool,
508        /// The weight for `soften_replication_anti_affinity.
509        ///
510        /// Defaults to `100`.
511        pub soften_az_affinity_weight: i32,
512        // Whether to enable security context for the service.
513        pub security_context_enabled: bool,
514    }
515
516    pub const DEFAULT_POD_AZ_AFFINITY_WEIGHT: Option<i32> = Some(100);
517    pub const DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY: bool = false;
518    pub const DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT: i32 = 100;
519
520    pub const DEFAULT_TOPOLOGY_SPREAD_ENABLED: bool = true;
521    pub const DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE: bool = true;
522    pub const DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW: i32 = 1;
523    pub const DEFAULT_TOPOLOGY_SPREAD_MIN_DOMAIN: Option<i32> = None;
524    pub const DEFAULT_TOPOLOGY_SPREAD_SOFT: bool = false;
525
526    pub const DEFAULT_SOFTEN_AZ_AFFINITY: bool = false;
527    pub const DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT: i32 = 100;
528    pub const DEFAULT_SECURITY_CONTEXT_ENABLED: bool = true;
529
530    impl Default for ServiceSchedulingConfig {
531        fn default() -> Self {
532            ServiceSchedulingConfig {
533                multi_pod_az_affinity_weight: DEFAULT_POD_AZ_AFFINITY_WEIGHT,
534                soften_replication_anti_affinity: DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY,
535                soften_replication_anti_affinity_weight:
536                    DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT,
537                topology_spread: ServiceTopologySpreadConfig {
538                    enabled: DEFAULT_TOPOLOGY_SPREAD_ENABLED,
539                    ignore_non_singular_scale: DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE,
540                    max_skew: DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW,
541                    min_domains: DEFAULT_TOPOLOGY_SPREAD_MIN_DOMAIN,
542                    soft: DEFAULT_TOPOLOGY_SPREAD_SOFT,
543                },
544                soften_az_affinity: DEFAULT_SOFTEN_AZ_AFFINITY,
545                soften_az_affinity_weight: DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT,
546                security_context_enabled: DEFAULT_SECURITY_CONTEXT_ENABLED,
547            }
548        }
549    }
550}