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