Skip to main content

feldera_types/
deployment.rs

1//! What exists for a pipeline deployment: desired versus current resources per host, and the
2//! state of each transition. State names follow the Kubernetes kstatus library.
3
4use crate::config::ResourceConfig;
5use crate::size::ConfigSize;
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use utoipa::ToSchema;
9
10/// Spec and observed status of a pipeline deployment.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
12pub struct PipelineDeployment {
13    pub spec: DeploymentSpec,
14    /// Absent when the runner does not observe its resources.
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub status: Option<DeploymentStatus>,
17}
18
19/// What the deployment asks for, from the pipeline's `deployment_config`.
20#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
21pub struct DeploymentSpec {
22    pub resources: DeploymentSpecResources,
23}
24
25/// Each `*_min` is a Kubernetes request and each `*_max` a limit.
26#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
27pub struct DeploymentSpecResources {
28    pub cpu_cores_min: Option<f64>,
29    pub cpu_cores_max: Option<f64>,
30    #[schema(value_type = Option<String>)]
31    pub memory_min: Option<ConfigSize>,
32    #[schema(value_type = Option<String>)]
33    pub memory_max: Option<ConfigSize>,
34    #[schema(value_type = Option<String>)]
35    pub storage_min: Option<ConfigSize>,
36    #[schema(value_type = Option<String>)]
37    pub storage_max: Option<ConfigSize>,
38}
39
40impl From<&ResourceConfig> for DeploymentSpecResources {
41    fn from(r: &ResourceConfig) -> Self {
42        Self {
43            cpu_cores_min: r.cpu_cores_min,
44            cpu_cores_max: r.cpu_cores_max,
45            memory_min: r.memory_min,
46            memory_max: r.memory_max,
47            storage_min: r.storage_min,
48            storage_max: r.storage_max,
49        }
50    }
51}
52
53/// Status of an object or of the whole deployment, from
54/// [kstatus](https://github.com/kubernetes-sigs/cli-utils/blob/master/pkg/kstatus/status/status.go).
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
56pub enum DeploymentState {
57    /// Matches its desired state.
58    Current,
59    /// On its way to the desired state.
60    InProgress,
61    /// Will not reach the desired state without a change.
62    Failed,
63    /// Being deleted.
64    Terminating,
65    /// Does not exist.
66    NotFound,
67    /// Cannot be determined. Clients read a state they do not know as this one.
68    #[serde(other)]
69    Unknown,
70}
71
72/// Who sets the desired value.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
74pub enum ResourceManager {
75    /// The pipeline's configuration.
76    User,
77    /// The runner's autoscaler, within the configured bounds.
78    Autoscaler,
79}
80
81/// State of one Kubernetes object, with its cause.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
83pub struct Transition {
84    pub state: DeploymentState,
85    /// Machine-readable cause, passed through from the runner's platform.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub reason: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub message: Option<String>,
90    /// When the platform last changed the condition behind `state` (Kubernetes
91    /// `lastTransitionTime`, or `deletionTimestamp` for `Terminating`). If only `reason` changes,
92    /// for example from `ContainerCreating` to `CrashLoopBackOff`, the time stays.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub last_transition_time: Option<DateTime<Utc>>,
95}
96
97impl Transition {
98    pub fn new(state: DeploymentState) -> Self {
99        Self {
100            state,
101            reason: None,
102            message: None,
103            last_transition_time: None,
104        }
105    }
106
107    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
108        self.reason = Some(reason.into());
109        self
110    }
111
112    pub fn with_message(mut self, message: impl Into<String>) -> Self {
113        self.message = Some(message.into());
114        self
115    }
116
117    pub fn with_last_transition_time(mut self, since: Option<DateTime<Utc>>) -> Self {
118        self.last_transition_time = since;
119        self
120    }
121}
122
123#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
124pub struct ComputeResources {
125    pub cpu_cores_min: Option<f64>,
126    pub cpu_cores_max: Option<f64>,
127    pub memory_mb_min: Option<u64>,
128    pub memory_mb_max: Option<u64>,
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
132pub struct StorageResources {
133    pub storage_mb: Option<u64>,
134}
135
136/// CPU and memory of one host.
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
138pub struct HostCompute {
139    #[serde(flatten)]
140    pub transition: Transition,
141    pub manager: ResourceManager,
142    /// Absent when the pipeline's `resources` are invalid.
143    pub desired: Option<ComputeResources>,
144    /// Absent when there is no pod, it cannot be read, or the kubelet has not reported its
145    /// resources.
146    pub current: Option<ComputeResources>,
147}
148
149/// Storage volume of one host.
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
151pub struct HostStorage {
152    #[serde(flatten)]
153    pub transition: Transition,
154    pub manager: ResourceManager,
155    /// Absent when the pipeline's `resources` are invalid.
156    pub desired: Option<StorageResources>,
157    /// Absent when there is no volume, it cannot be read, or it is not bound yet.
158    pub current: Option<StorageResources>,
159}
160
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
162pub struct HostStatus {
163    /// Host index, from 0 to `hosts - 1`. Kubernetes names the pod `<statefulset>-<ordinal>`.
164    pub ordinal: usize,
165    pub compute: HostCompute,
166    /// Absent when the pipeline has no storage.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub storage: Option<HostStorage>,
169}
170
171/// Observed status of the deployment. `state`, `reason` and `message` summarize `hosts`.
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
173pub struct DeploymentStatus {
174    pub state: DeploymentState,
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub reason: Option<String>,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub message: Option<String>,
179    pub hosts: Vec<HostStatus>,
180}
181
182impl DeploymentStatus {
183    /// Summarizes `hosts` like kstatus `AggregateStatus`: `Failed` if any object failed, else
184    /// `Unknown` if any is unknown, else the desired state if every object reached the state it
185    /// is expected to (compute `compute_expected`, storage `storage_expected`), else
186    /// `InProgress`. The desired state is `NotFound` when nothing is expected to exist, else
187    /// `Current`. Reason and message come from the first object that decides the result.
188    /// <https://github.com/kubernetes-sigs/cli-utils/blob/master/pkg/kstatus/polling/aggregator/aggregator.go>
189    pub fn aggregate(
190        hosts: Vec<HostStatus>,
191        compute_expected: DeploymentState,
192        storage_expected: DeploymentState,
193    ) -> Self {
194        let objects: Vec<(&Transition, DeploymentState)> = hosts
195            .iter()
196            .flat_map(|host| {
197                std::iter::once((&host.compute.transition, compute_expected)).chain(
198                    host.storage
199                        .as_ref()
200                        .map(|storage| (&storage.transition, storage_expected)),
201                )
202            })
203            .collect();
204        let desired = if compute_expected == DeploymentState::NotFound
205            && objects
206                .iter()
207                .all(|(_, expected)| *expected == DeploymentState::NotFound)
208        {
209            DeploymentState::NotFound
210        } else {
211            DeploymentState::Current
212        };
213        let first = |matches: &dyn Fn(&Transition, DeploymentState) -> bool| {
214            objects
215                .iter()
216                .find(|(transition, expected)| matches(transition, *expected))
217                .map(|(transition, _)| *transition)
218        };
219        let (state, decider) = if let Some(t) = first(&|t, _| t.state == DeploymentState::Failed) {
220            (DeploymentState::Failed, Some(t))
221        } else if let Some(t) = first(&|t, _| t.state == DeploymentState::Unknown) {
222            (DeploymentState::Unknown, Some(t))
223        } else if let Some(t) = first(&|t, expected| t.state != expected) {
224            (DeploymentState::InProgress, Some(t))
225        } else {
226            (desired, None)
227        };
228        Self {
229            state,
230            reason: decider.and_then(|t| t.reason.clone()),
231            message: decider.and_then(|t| t.message.clone()),
232            hosts,
233        }
234    }
235}
236
237#[cfg(test)]
238mod test {
239    use super::*;
240    use DeploymentState::*;
241
242    fn host(compute: Transition, storage: Option<Transition>) -> HostStatus {
243        HostStatus {
244            ordinal: 0,
245            compute: HostCompute {
246                transition: compute,
247                manager: ResourceManager::User,
248                desired: None,
249                current: None,
250            },
251            storage: storage.map(|transition| HostStorage {
252                transition,
253                manager: ResourceManager::User,
254                desired: None,
255                current: None,
256            }),
257        }
258    }
259
260    fn summary(status: &DeploymentStatus) -> (DeploymentState, Option<&str>) {
261        (status.state, status.reason.as_deref())
262    }
263
264    #[test]
265    fn all_objects_as_expected_is_current() {
266        let running = DeploymentStatus::aggregate(
267            vec![host(
268                Transition::new(Current),
269                Some(Transition::new(Current)),
270            )],
271            Current,
272            Current,
273        );
274        assert_eq!(summary(&running), (Current, None));
275
276        // A stopped pipeline keeps its storage and has no pod.
277        let stopped = DeploymentStatus::aggregate(
278            vec![host(
279                Transition::new(NotFound),
280                Some(Transition::new(Current)),
281            )],
282            NotFound,
283            Current,
284        );
285        assert_eq!(summary(&stopped), (Current, None));
286    }
287
288    #[test]
289    fn object_not_as_expected_is_in_progress() {
290        // Stopping: the pod is still there.
291        let stopping = DeploymentStatus::aggregate(
292            vec![host(
293                Transition::new(Terminating).with_reason("Deleting"),
294                None,
295            )],
296            NotFound,
297            Current,
298        );
299        assert_eq!(summary(&stopping), (InProgress, Some("Deleting")));
300
301        // Starting: the pod is not there yet.
302        let starting = DeploymentStatus::aggregate(
303            vec![host(Transition::new(NotFound), None)],
304            Current,
305            Current,
306        );
307        assert_eq!(summary(&starting), (InProgress, None));
308    }
309
310    #[test]
311    fn failed_wins_over_unknown_and_in_progress() {
312        let status = DeploymentStatus::aggregate(
313            vec![
314                host(
315                    Transition::new(InProgress).with_reason("Deferred"),
316                    Some(Transition::new(Unknown).with_reason("ListFailed")),
317                ),
318                host(
319                    Transition::new(Current),
320                    Some(
321                        Transition::new(Failed)
322                            .with_reason("ControllerResizeInfeasible")
323                            .with_message("too big"),
324                    ),
325                ),
326            ],
327            Current,
328            Current,
329        );
330        assert_eq!(
331            summary(&status),
332            (Failed, Some("ControllerResizeInfeasible"))
333        );
334        assert_eq!(status.message.as_deref(), Some("too big"));
335    }
336
337    #[test]
338    fn unknown_wins_over_in_progress() {
339        let status = DeploymentStatus::aggregate(
340            vec![
341                host(Transition::new(InProgress).with_reason("Deferred"), None),
342                host(Transition::new(Unknown).with_reason("GetFailed"), None),
343            ],
344            Current,
345            Current,
346        );
347        assert_eq!(summary(&status), (Unknown, Some("GetFailed")));
348    }
349
350    #[test]
351    fn first_deciding_object_gives_the_reason() {
352        let status = DeploymentStatus::aggregate(
353            vec![
354                host(Transition::new(Current), None),
355                host(
356                    Transition::new(InProgress).with_reason("Deferred"),
357                    Some(Transition::new(InProgress).with_reason("NodeResizePending")),
358                ),
359            ],
360            Current,
361            Current,
362        );
363        assert_eq!(summary(&status), (InProgress, Some("Deferred")));
364    }
365
366    #[test]
367    fn no_hosts_is_the_desired_state() {
368        let status = DeploymentStatus::aggregate(vec![], Current, Current);
369        assert_eq!(summary(&status), (Current, None));
370        let status = DeploymentStatus::aggregate(vec![], NotFound, NotFound);
371        assert_eq!(summary(&status), (NotFound, None));
372    }
373
374    /// Stopped and cleared: kstatus reports `NotFound` when that is the desired state.
375    #[test]
376    fn nothing_expected_to_exist_is_not_found() {
377        let cleared = DeploymentStatus::aggregate(
378            vec![host(
379                Transition::new(NotFound),
380                Some(Transition::new(NotFound)),
381            )],
382            NotFound,
383            NotFound,
384        );
385        assert_eq!(summary(&cleared), (NotFound, None));
386
387        // Without storage, the pod alone decides.
388        let stopped = DeploymentStatus::aggregate(
389            vec![host(Transition::new(NotFound), None)],
390            NotFound,
391            Current,
392        );
393        assert_eq!(summary(&stopped), (NotFound, None));
394    }
395
396    #[test]
397    fn unknown_state_reads_as_unknown() {
398        let state: DeploymentState = serde_json::from_str("\"Suspended\"").unwrap();
399        assert_eq!(state, Unknown);
400    }
401
402    #[test]
403    fn serializes_flat() {
404        let status = DeploymentStatus::aggregate(
405            vec![host(
406                Transition::new(InProgress).with_reason("InProgress"),
407                None,
408            )],
409            Current,
410            Current,
411        );
412        assert_eq!(
413            serde_json::to_value(&status).unwrap(),
414            serde_json::json!({
415                "state": "InProgress",
416                "reason": "InProgress",
417                "hosts": [{
418                    "ordinal": 0,
419                    "compute": {
420                        "state": "InProgress",
421                        "reason": "InProgress",
422                        "manager": "User",
423                        "desired": null,
424                        "current": null
425                    }
426                }]
427            })
428        );
429    }
430}