Skip to main content

engenho_controllers/
pod_scheduling.rs

1//! T2.5 — how a scheduler reads a pod, and the two writes it makes to one.
2//!
3//! ★ THE DEFECTS this module is the fix for, all in engenho-scheduler's tick
4//! as this module was written (the scheduler adopts it in its own change;
5//! until then they stand there):
6//!
7//!   * **The bind was unconditional.** `spec.nodeName` was merged in with no
8//!     precondition, on a pod read at the top of the tick. A pod deleted,
9//!     rebound or re-specified in between was bound anyway, onto a node
10//!     chosen for the pod as it was.
11//!   * **A bind was counted by being proposed.** The report listed a
12//!     binding and the ledger was debited whatever the store answered.
13//!   * **"Pending" was one bit** (`spec.nodeName` empty), so a Terminating
14//!     pod, or one naming another scheduler, was placed like any other.
15//!   * **The Unschedulable condition was rewritten from a stale read**, and
16//!     the rewrite replaced the whole `conditions` list with one entry.
17//!
18//! ★ THE SHAPE.
19//!
20//!   * [`PodSchedulingState::of`] classifies a pod into one of five named
21//!     states. Only [`PodSchedulingState::Schedulable`] carries a
22//!     [`Schedulable`]: the pod's key and the revision it was read at. Its
23//!     fields are private and nothing else builds one.
24//!   * [`bind_cas`] takes a `Schedulable` BY VALUE and writes
25//!     `spec.nodeName` conditioned on its revision. A pod never classified
26//!     schedulable cannot be bound (there is no token to pass), and one
27//!     token binds at most once.
28//!   * [`BindOutcome::of`] maps every `ResourceOp` with no wildcard, so a new
29//!     op does not compile until it is placed.
30//!   * [`Binding`] has private fields and is built only in the `Patched` arm
31//!     of that mapping: a binding in a report is a bind the store confirmed.
32//!   * [`mark_unschedulable_cas`] sets `PodScheduled=False/Unschedulable` by
33//!     type ([`crate::condition::upsert_condition`]) with the one-retry CAS
34//!     edit, and stands down when the re-read pod is no longer schedulable.
35//!
36//! Tier-honest: "binding needs a token" and "a Binding needs a `Patched`
37//! answer" are type-level (no constructor). That the scheduler debits its
38//! ledger only for a [`BindOutcome::Bound`] will be held at its one call
39//! site. `tests/t2_5_condition_cas.rs` drives [`mark_unschedulable_cas`]
40//! under a `WatchDriver`: at most 3 ticks in 2 s for one unschedulable pod.
41
42use engenho_store::{command::ResourceOp, resource::ResourceKey, revision::Revision};
43use serde_json::{Value, json};
44
45use crate::condition::{ConditionStatus, DesiredCondition, upsert_condition};
46use crate::effect::{Effect, Refusal};
47use crate::error::ControllerError;
48use crate::meta::ObjectMeta;
49use crate::status::{CasEnv, StatusEdit, StatusEditOutcome, edit_status_cas, resource_version_of};
50
51/// The scheduler a pod names when it names none: the apiserver defaults
52/// `spec.schedulerName` to this.
53pub const DEFAULT_SCHEDULER: &str = "default-scheduler";
54
55/// The pod condition type a scheduler owns.
56pub const POD_SCHEDULED: &str = "PodScheduled";
57
58/// The `PodScheduled=False` reason for a pod no node admits.
59pub const UNSCHEDULABLE: &str = "Unschedulable";
60
61/// How a pod stands, for a scheduler named `scheduler`.
62///
63/// The states are checked in the order declared: a bound pod is `Bound`
64/// even while Terminating. Every state but `Bound` is an unbound, that is
65/// Pending, pod.
66#[derive(Debug, PartialEq, Eq)]
67pub enum PodSchedulingState {
68    /// `spec.nodeName` names a node. Nothing to schedule.
69    Bound,
70    /// Unbound, and a delete was accepted (`metadata.deletionTimestamp`).
71    /// Placing it would start a pod nobody wants.
72    Terminating,
73    /// Unbound, and `spec.schedulerName` names another scheduler, or holds
74    /// something that is not a name.
75    OtherScheduler,
76    /// Unbound and ours, with no parseable `metadata.resourceVersion`: a
77    /// bind could not be conditioned on the pod as read.
78    NoRevision,
79    /// Unbound, alive, ours, and read at a known revision.
80    Schedulable(Schedulable),
81}
82
83impl PodSchedulingState {
84    /// Classify the pod `pod` stored at `key`.
85    #[must_use]
86    pub fn of(key: &ResourceKey, pod: &Value, scheduler: &str) -> Self {
87        if is_bound(pod) {
88            Self::Bound
89        } else if pod.is_terminating() {
90            Self::Terminating
91        } else if !names_scheduler(pod, scheduler) {
92            Self::OtherScheduler
93        } else {
94            match resource_version_of(pod) {
95                None => Self::NoRevision,
96                Some(revision) => Self::Schedulable(Schedulable {
97                    key: key.clone(),
98                    revision,
99                }),
100            }
101        }
102    }
103
104    /// Whether the pod is unbound (Pending), whatever else stands in the
105    /// way of placing it.
106    #[must_use]
107    pub const fn is_pending(&self) -> bool {
108        !matches!(self, Self::Bound)
109    }
110}
111
112/// `spec.nodeName` is a non-empty string.
113fn is_bound(pod: &Value) -> bool {
114    pod.pointer("/spec/nodeName")
115        .and_then(Value::as_str)
116        .is_some_and(|node| !node.is_empty())
117}
118
119/// `spec.schedulerName` is `scheduler`, or unset (absent, `null` or empty),
120/// which the apiserver defaults to [`DEFAULT_SCHEDULER`].
121fn names_scheduler(pod: &Value, scheduler: &str) -> bool {
122    match pod.pointer("/spec/schedulerName") {
123        None | Some(Value::Null) => scheduler == DEFAULT_SCHEDULER,
124        Some(Value::String(name)) if name.is_empty() => scheduler == DEFAULT_SCHEDULER,
125        Some(Value::String(name)) => name == scheduler,
126        Some(_) => false,
127    }
128}
129
130/// A pod classified [`PodSchedulingState::Schedulable`]: its key and the
131/// revision it was read at.
132///
133/// The fields are private: only [`PodSchedulingState::of`] builds one.
134///
135/// ```
136/// use engenho_controllers::pod_scheduling::{DEFAULT_SCHEDULER, PodSchedulingState};
137/// use engenho_store::{ResourceKey, Revision};
138///
139/// let key = ResourceKey::namespaced("", "v1", "Pod", "ns", "p");
140/// let read = serde_json::json!({"metadata": {"resourceVersion": "7"}});
141/// let PodSchedulingState::Schedulable(pod) =
142///     PodSchedulingState::of(&key, &read, DEFAULT_SCHEDULER)
143/// else {
144///     unreachable!("an unbound pod of ours with a revision");
145/// };
146/// assert_eq!(pod.revision(), Revision(7));
147/// ```
148///
149/// and never assembled by hand:
150///
151/// ```compile_fail,E0451
152/// use engenho_controllers::pod_scheduling::Schedulable;
153/// use engenho_store::{ResourceKey, Revision};
154///
155/// let pod = Schedulable {
156///     key: ResourceKey::namespaced("", "v1", "Pod", "ns", "p"),
157///     revision: Revision(7),
158/// };
159/// ```
160#[derive(Debug, PartialEq, Eq)]
161pub struct Schedulable {
162    key: ResourceKey,
163    revision: Revision,
164}
165
166impl Schedulable {
167    /// The pod's key.
168    #[must_use]
169    pub fn key(&self) -> &ResourceKey {
170        &self.key
171    }
172
173    /// The revision the pod was read at, which a bind is conditioned on.
174    #[must_use]
175    pub const fn revision(&self) -> Revision {
176        self.revision
177    }
178}
179
180/// A bind the store confirmed: `spec.nodeName` of `pod_key` was set to
181/// `node_name`.
182///
183/// The fields are private: only [`BindOutcome::of`] builds one, from a
184/// `Patched` answer.
185///
186/// ```
187/// use engenho_controllers::pod_scheduling::{BindOutcome, DEFAULT_SCHEDULER, PodSchedulingState};
188/// use engenho_store::{ResourceKey, command::ResourceOp};
189///
190/// let key = ResourceKey::namespaced("", "v1", "Pod", "ns", "p");
191/// let read = serde_json::json!({"metadata": {"resourceVersion": "7"}});
192/// let PodSchedulingState::Schedulable(pod) =
193///     PodSchedulingState::of(&key, &read, DEFAULT_SCHEDULER)
194/// else {
195///     unreachable!("an unbound pod of ours with a revision");
196/// };
197/// let BindOutcome::Bound(bound) = BindOutcome::of(ResourceOp::Patched, pod, "n1".to_owned())
198/// else {
199///     unreachable!("Patched is a bind");
200/// };
201/// assert_eq!(bound.node_name(), "n1");
202/// ```
203///
204/// and never assembled by hand:
205///
206/// ```compile_fail,E0451
207/// use engenho_controllers::pod_scheduling::Binding;
208/// use engenho_store::ResourceKey;
209///
210/// let bound = Binding {
211///     pod_key: ResourceKey::namespaced("", "v1", "Pod", "ns", "p"),
212///     node_name: "n1".to_owned(),
213/// };
214/// ```
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct Binding {
217    pod_key: ResourceKey,
218    node_name: String,
219}
220
221impl Binding {
222    /// The pod that was bound.
223    #[must_use]
224    pub fn pod_key(&self) -> &ResourceKey {
225        &self.pod_key
226    }
227
228    /// The node it was bound to.
229    #[must_use]
230    pub fn node_name(&self) -> &str {
231        &self.node_name
232    }
233}
234
235/// What the store did with a bind.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub enum BindOutcome {
238    /// The bind landed.
239    Bound(Binding),
240    /// The store refused it. `Conflict`: the pod moved (or went away) since
241    /// it was read; the write that moved it fires a watch event, and the
242    /// next tick classifies the pod afresh.
243    Refused(Refusal),
244    /// The store accepted the patch and changed nothing.
245    Unchanged,
246    /// The store answered with an op a patch does not produce. Not a bind.
247    Unexpected(ResourceOp),
248}
249
250impl BindOutcome {
251    /// The outcome of binding `pod` to `node_name`, read off the store's
252    /// answer `op`.
253    ///
254    /// Exhaustive with no wildcard: a new [`ResourceOp`] does not compile
255    /// until it is placed here.
256    #[must_use]
257    pub fn of(op: ResourceOp, pod: Schedulable, node_name: String) -> Self {
258        match op {
259            ResourceOp::Patched => Self::Bound(Binding {
260                pod_key: pod.key,
261                node_name,
262            }),
263            ResourceOp::Conflict => Self::Refused(Refusal::Conflict),
264            ResourceOp::PatchRejected => Self::Refused(Refusal::PatchRejected),
265            ResourceOp::ApplyConflict => Self::Refused(Refusal::ApplyConflict),
266            ResourceOp::Unchanged | ResourceOp::NoOp => Self::Unchanged,
267            ResourceOp::Created
268            | ResourceOp::Replaced
269            | ResourceOp::Deleted
270            | ResourceOp::DeletionPending => Self::Unexpected(op),
271        }
272    }
273
274    /// What the bind did, as one [`Effect`], for
275    /// [`crate::ReconcileReport::record`].
276    pub const fn effect(&self) -> Effect {
277        match self {
278            Self::Bound(_) => Effect::of(ResourceOp::Patched),
279            Self::Refused(refusal) => Effect::Rejected(*refusal),
280            Self::Unchanged => Effect::Unchanged,
281            Self::Unexpected(op) => Effect::of(*op),
282        }
283    }
284}
285
286/// Bind `pod` to `node_name`: merge `spec.nodeName`, conditioned on the
287/// revision `pod` was classified at.
288///
289/// Not retried: a conflict means the pod changed, and the node was chosen
290/// for the pod as it was.
291///
292/// # Errors
293///
294/// [`ControllerError::Store`] on a transport failure. A refused bind is a
295/// [`BindOutcome::Refused`], not an error.
296pub async fn bind_cas<E>(
297    env: &E,
298    pod: Schedulable,
299    node_name: String,
300) -> Result<BindOutcome, ControllerError>
301where
302    E: CasEnv + ?Sized,
303{
304    let answer = env
305        .patch_at(
306            &pod.key,
307            json!({ "spec": { "nodeName": node_name } }),
308            pod.revision,
309        )
310        .await?;
311    Ok(BindOutcome::of(answer.op, pod, node_name))
312}
313
314/// The condition a pod no node admits carries, with `message` saying why.
315#[must_use]
316pub fn unschedulable_condition(message: String) -> DesiredCondition {
317    DesiredCondition {
318        condition_type: POD_SCHEDULED,
319        status: ConditionStatus::False,
320        reason: UNSCHEDULABLE,
321        message,
322    }
323}
324
325/// Give `pod` a `PodScheduled=False / reason=Unschedulable` condition
326/// carrying `message`, and `status.phase: Pending` when it has no phase
327/// (engenho's apiserver does not default one). Mirrors upstream
328/// kube-scheduler's failure path; the pod stays unbound.
329///
330/// Through [`edit_status_cas`]: the pod is re-read, the condition set by
331/// type, and the result written at the revision read, retrying once on a
332/// conflict. `Unchanged` when the pod already carries the condition and a
333/// phase, so a scheduler that re-derives the same reason every tick
334/// proposes nothing and does not wake itself. `Superseded` when the re-read
335/// pod is no longer ours to mark: bound, Terminating, or claimed by another
336/// scheduler since it was classified.
337///
338/// Emit the `FailedScheduling` Event only when [`StatusEditOutcome::changed`].
339///
340/// # Errors
341///
342/// As [`edit_status_cas`].
343pub async fn mark_unschedulable_cas<E>(
344    env: &E,
345    pod: &Schedulable,
346    scheduler: &str,
347    message: String,
348    now: &str,
349) -> Result<StatusEditOutcome, ControllerError>
350where
351    E: CasEnv + ?Sized,
352{
353    let desired = unschedulable_condition(message);
354    edit_status_cas(env, &pod.key, |live| {
355        if !matches!(
356            PodSchedulingState::of(&pod.key, live, scheduler),
357            PodSchedulingState::Schedulable(_) | PodSchedulingState::NoRevision
358        ) {
359            return Ok(StatusEdit::Superseded);
360        }
361        let mut fields = upsert_condition(live, &desired, now)?
362            .into_status_fields()
363            .unwrap_or_default();
364        if live.pointer("/status/phase").is_none_or(Value::is_null) {
365            fields.insert("phase".to_owned(), json!("Pending"));
366        }
367        Ok(if fields.is_empty() {
368            StatusEdit::Current
369        } else {
370            StatusEdit::Write(fields)
371        })
372    })
373    .await
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    fn key() -> ResourceKey {
381        ResourceKey::namespaced("", "v1", "Pod", "ns", "p")
382    }
383
384    fn state(pod: &Value) -> PodSchedulingState {
385        PodSchedulingState::of(&key(), pod, DEFAULT_SCHEDULER)
386    }
387
388    fn schedulable(revision: u64) -> Schedulable {
389        Schedulable {
390            key: key(),
391            revision: Revision(revision),
392        }
393    }
394
395    #[test]
396    fn a_pod_with_a_node_is_bound_even_while_terminating() {
397        let pod = json!({"metadata": {"resourceVersion": "3", "deletionTimestamp": "t"},
398                         "spec": {"nodeName": "n1"}});
399        assert_eq!(state(&pod), PodSchedulingState::Bound);
400        assert!(!state(&pod).is_pending());
401    }
402
403    #[test]
404    fn an_empty_node_name_is_unbound() {
405        let pod = json!({"metadata": {"resourceVersion": "3"}, "spec": {"nodeName": ""}});
406        assert_eq!(state(&pod), PodSchedulingState::Schedulable(schedulable(3)));
407    }
408
409    #[test]
410    fn an_unbound_pod_being_deleted_is_terminating() {
411        let pod = json!({"metadata": {"resourceVersion": "3", "deletionTimestamp": "t"}});
412        assert_eq!(state(&pod), PodSchedulingState::Terminating);
413        assert!(state(&pod).is_pending());
414    }
415
416    #[test]
417    fn another_scheduler_s_pod_is_not_ours() {
418        for name in [json!("custom"), json!(7)] {
419            let pod = json!({"metadata": {"resourceVersion": "3"},
420                             "spec": {"schedulerName": name}});
421            assert_eq!(state(&pod), PodSchedulingState::OtherScheduler, "{name}");
422        }
423    }
424
425    #[test]
426    fn an_unset_scheduler_name_is_the_default_scheduler() {
427        for spec in [
428            json!({}),
429            json!({"schedulerName": null}),
430            json!({"schedulerName": ""}),
431            json!({"schedulerName": DEFAULT_SCHEDULER}),
432        ] {
433            let pod = json!({"metadata": {"resourceVersion": "3"}, "spec": spec});
434            assert_eq!(
435                state(&pod),
436                PodSchedulingState::Schedulable(schedulable(3)),
437                "{spec}"
438            );
439            // ...and not a pod a scheduler with another name places.
440            assert_eq!(
441                PodSchedulingState::of(&key(), &pod, "custom"),
442                PodSchedulingState::OtherScheduler,
443                "{spec}"
444            );
445        }
446    }
447
448    #[test]
449    fn a_pod_with_no_revision_cannot_be_scheduled() {
450        assert_eq!(state(&json!({"spec": {}})), PodSchedulingState::NoRevision);
451        assert_eq!(
452            state(&json!({"metadata": {"resourceVersion": "x"}})),
453            PodSchedulingState::NoRevision
454        );
455    }
456
457    #[test]
458    fn a_schedulable_pod_carries_its_key_and_revision() {
459        let PodSchedulingState::Schedulable(pod) =
460            state(&json!({"metadata": {"resourceVersion": "42"}}))
461        else {
462            panic!("expected Schedulable");
463        };
464        assert_eq!(pod.key(), &key());
465        assert_eq!(pod.revision(), Revision(42));
466    }
467
468    /// Every op, and what it means for a bind. Only `Patched` binds.
469    #[test]
470    fn only_a_patched_answer_is_a_binding() {
471        let expected = [
472            (
473                ResourceOp::Created,
474                BindOutcome::Unexpected(ResourceOp::Created),
475            ),
476            (
477                ResourceOp::Replaced,
478                BindOutcome::Unexpected(ResourceOp::Replaced),
479            ),
480            (
481                ResourceOp::Patched,
482                BindOutcome::Bound(Binding {
483                    pod_key: key(),
484                    node_name: "n1".to_owned(),
485                }),
486            ),
487            (
488                ResourceOp::Deleted,
489                BindOutcome::Unexpected(ResourceOp::Deleted),
490            ),
491            (
492                ResourceOp::DeletionPending,
493                BindOutcome::Unexpected(ResourceOp::DeletionPending),
494            ),
495            (ResourceOp::NoOp, BindOutcome::Unchanged),
496            (ResourceOp::Unchanged, BindOutcome::Unchanged),
497            (
498                ResourceOp::Conflict,
499                BindOutcome::Refused(Refusal::Conflict),
500            ),
501            (
502                ResourceOp::PatchRejected,
503                BindOutcome::Refused(Refusal::PatchRejected),
504            ),
505            (
506                ResourceOp::ApplyConflict,
507                BindOutcome::Refused(Refusal::ApplyConflict),
508            ),
509        ];
510        for (op, outcome) in expected {
511            assert_eq!(
512                BindOutcome::of(op, schedulable(1), "n1".to_owned()),
513                outcome,
514                "{op:?}"
515            );
516            assert_eq!(
517                outcome.effect(),
518                Effect::of(op),
519                "{op:?}: a bind counts as what the store did"
520            );
521        }
522    }
523
524    #[test]
525    fn a_binding_names_the_pod_and_the_node() {
526        let BindOutcome::Bound(binding) =
527            BindOutcome::of(ResourceOp::Patched, schedulable(1), "n1".to_owned())
528        else {
529            panic!("expected Bound");
530        };
531        assert_eq!(binding.pod_key(), &key());
532        assert_eq!(binding.node_name(), "n1");
533    }
534
535    #[test]
536    fn the_unschedulable_condition_is_pod_scheduled_false() {
537        let c = unschedulable_condition("0/1 nodes".to_owned());
538        assert_eq!(
539            (c.condition_type, c.status, c.reason, c.message.as_str()),
540            (
541                "PodScheduled",
542                ConditionStatus::False,
543                "Unschedulable",
544                "0/1 nodes"
545            )
546        );
547    }
548}