-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers.rs
More file actions
3114 lines (2849 loc) · 117 KB
/
Copy pathhelpers.rs
File metadata and controls
3114 lines (2849 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Erick Bourgeois, RBC Capital Markets
// SPDX-License-Identifier: Apache-2.0
//! # Reconciliation helper functions
//!
//! Pure utility functions used by the [`scheduled_machine`](super::scheduled_machine)
//! reconciler. Separated here to keep the main reconciler focused on the
//! state-machine logic.
//!
//! ## Organisation
//! - **Resource distribution** — consistent hashing for multi-instance deployments
//! - **Schedule evaluation** — timezone-aware day/hour range matching
//! - **Finalizer management** — add, check, and remove the 5-spot finalizer
//! - **Kill switch** — immediate machine removal path
//! - **Grace period** — elapsed-time check against the shutdown timeout
//! - **Duration parsing** — bounded `"5m"` / `"10s"` / `"1h"` string parser
//! - **Kubernetes event helpers** — phase-transition event construction
//! - **Status update helpers** — `patch_status` wrappers that also record events
//! - **Security validation** — label prefix rejection and API group allowlist
//! - **CAPI resource creation / deletion** — bootstrap, infra, and Machine lifecycle
//! - **Node draining** — cordon + pod eviction with timeout
//! - **Error policy** — controller requeue-on-error strategy
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use chrono::{DateTime, Datelike, Timelike, Utc};
use chrono_tz::Tz;
use k8s_openapi::api::core::v1::ObjectReference;
use kube::{
api::{Api, Patch, PatchParams},
runtime::{
controller::Action,
events::{Event as KubeEvent, EventType},
},
Client, Resource, ResourceExt,
};
use serde_json::json;
use tracing::{debug, error, info, warn};
use super::{Context, ReconcilerError};
use crate::constants::{
ALLOWED_BOOTSTRAP_API_GROUPS, ALLOWED_INFRASTRUCTURE_API_GROUPS, API_VERSION_FULL,
CAPI_CLUSTER_NAME_LABEL, CAPI_GROUP, CAPI_MACHINE_API_VERSION, CAPI_MACHINE_API_VERSION_FULL,
CAPI_RESOURCE_MACHINES, CONDITION_STATUS_TRUE, CONDITION_TYPE_READY, DEFAULT_INSTANCE_ID,
ENV_OPERATOR_INSTANCE_ID, ERROR_REQUEUE_SECS, FINALIZER_CLEANUP_TIMEOUT_SECS,
FINALIZER_SCHEDULED_MACHINE, MAX_BACKOFF_SECS, MAX_CLUSTER_NAME_LEN, MAX_DURATION_SECS,
MAX_KILL_IF_COMMANDS_COUNT, MAX_KILL_IF_COMMAND_LEN, MAX_RECONCILE_RETRIES, PHASE_ACTIVE,
PHASE_ERROR, PHASE_INACTIVE, PHASE_SHUTTING_DOWN, PHASE_TERMINATED,
POD_EVICTION_GRACE_PERIOD_SECS, REASON_GRACE_PERIOD, REASON_KILL_SWITCH,
REASON_RECONCILE_SUCCEEDED, RESERVED_LABEL_PREFIXES, TIMER_REQUEUE_SECS,
};
use crate::crd::{Condition, NodeRef, ScheduledMachine, ScheduledMachineStatus};
use crate::metrics::{
record_emergency_drain, record_emergency_reclaim, record_node_drain, record_pod_eviction,
EmergencyDrainOutcome,
};
// ============================================================================
// Resource processing and consistent hashing
// ============================================================================
/// Determine if this operator instance should process a specific resource
/// Uses consistent hashing to distribute resources across instances
pub fn should_process_resource(
name: &str,
namespace: &str,
priority: u8,
instance_count: u32,
) -> bool {
if instance_count <= 1 {
return true;
}
// Create consistent hash of resource identifier with priority influence
let resource_id = format!("{namespace}/{name}");
let priority_modifier = u64::from(priority) * 1000;
// Simple hash function (in production, consider using a proper hash)
let mut hash: u64 = 0;
for byte in resource_id.bytes() {
hash = hash.wrapping_mul(31).wrapping_add(u64::from(byte));
}
hash = hash.wrapping_add(priority_modifier);
#[allow(clippy::cast_possible_truncation)]
let assigned_instance = (hash % u64::from(instance_count)) as u32;
let current_instance = std::env::var(ENV_OPERATOR_INSTANCE_ID)
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_INSTANCE_ID);
debug!(
resource = %resource_id,
priority = priority,
assigned_instance = assigned_instance,
current_instance = current_instance,
"Resource assignment check"
);
assigned_instance == current_instance
}
// ============================================================================
// Schedule evaluation
// ============================================================================
/// Evaluate if a machine should be active based on schedule
///
/// # Errors
/// Returns error if timezone is invalid or weekday/hour parsing fails
pub fn evaluate_schedule(
schedule: &crate::crd::ScheduleSpec,
check_time: Option<DateTime<Utc>>,
) -> Result<bool, ReconcilerError> {
if !schedule.enabled {
return Ok(false);
}
let now = check_time.unwrap_or_else(Utc::now);
// Parse timezone
let tz: Tz = schedule.timezone.parse().map_err(|_| {
ReconcilerError::ScheduleError(format!("Invalid timezone: {}", schedule.timezone))
})?;
let current_time = now.with_timezone(&tz);
// Check weekday (Monday = 0, Sunday = 6)
#[allow(clippy::cast_possible_truncation)]
let current_weekday = current_time.weekday().num_days_from_monday() as u8;
let allowed_weekdays = schedule
.get_active_weekdays()
.map_err(|e| ReconcilerError::ScheduleError(format!("Failed to parse weekdays: {e}")))?
.ok_or_else(|| ReconcilerError::ScheduleError("No weekday schedule defined".to_string()))?;
debug!(
current_weekday = current_weekday,
allowed_weekdays = ?allowed_weekdays,
"Weekday check"
);
if !allowed_weekdays.contains(¤t_weekday) {
return Ok(false);
}
// Check hour
#[allow(clippy::cast_possible_truncation)]
let current_hour = current_time.hour() as u8;
let allowed_hours = schedule
.get_active_hours()
.map_err(|e| ReconcilerError::ScheduleError(format!("Failed to parse hours: {e}")))?
.ok_or_else(|| ReconcilerError::ScheduleError("No hour schedule defined".to_string()))?;
debug!(
current_hour = current_hour,
allowed_hours = ?allowed_hours,
"Hour check"
);
Ok(allowed_hours.contains(¤t_hour))
}
// ============================================================================
// ============================================================================
// Finalizer management
// ============================================================================
/// Return `true` if the resource already carries the 5-spot finalizer.
///
/// Used as a guard in [`reconcile_scheduled_machine`] to avoid adding the
/// finalizer a second time when the resource has already been processed.
pub fn has_finalizer(resource: &ScheduledMachine) -> bool {
resource
.meta()
.finalizers
.as_ref()
.is_some_and(|f| f.contains(&FINALIZER_SCHEDULED_MACHINE.to_string()))
}
/// Add the 5-spot finalizer to a `ScheduledMachine` resource.
///
/// The finalizer prevents Kubernetes from deleting the resource until the
/// controller has successfully run cleanup logic (see [`handle_deletion`]).
/// After patching the finalizer, the function requeues immediately
/// (`Duration::from_secs(0)`) so the main reconcile loop can proceed to the
/// `Pending` phase in the same reconciliation cycle.
///
/// # Errors
/// Returns [`ReconcilerError::InvalidConfig`] if the resource has no namespace,
/// or a kube API error if the merge-patch call fails.
pub async fn add_finalizer(
resource: Arc<ScheduledMachine>,
ctx: Arc<Context>,
) -> Result<Action, ReconcilerError> {
let namespace = resource.namespace().ok_or_else(|| {
ReconcilerError::InvalidConfig("ScheduledMachine must be namespaced".to_string())
})?;
let name = resource.name_any();
info!(
resource = %name,
namespace = %namespace,
"Adding finalizer"
);
let api: Api<ScheduledMachine> = Api::namespaced(ctx.client.clone(), &namespace);
let mut finalizers = resource.meta().finalizers.clone().unwrap_or_default();
finalizers.push(FINALIZER_SCHEDULED_MACHINE.to_string());
let patch = json!({
"metadata": {
"finalizers": finalizers
}
});
api.patch(&name, &PatchParams::default(), &Patch::Merge(&patch))
.await?;
Ok(Action::requeue(Duration::from_secs(0)))
}
/// Outcome of a timed cleanup attempt — produced by
/// [`run_cleanup_with_timeout`] and consumed by [`handle_deletion`] to
/// classify what happened to a finalizer-cleanup future.
///
/// The variants are deliberately *not* an `enum E { Ok, Err(_) }`: the
/// caller must distinguish "cleanup itself returned an error" (retry)
/// from "cleanup did not complete in time" (force-remove the finalizer
/// to unblock namespace deletion). Folding the timeout into a generic
/// error was the source of the original bug.
#[derive(Debug)]
pub enum CleanupOutcome {
/// The cleanup future completed within the timeout with `Ok(())`.
Completed,
/// The cleanup future completed within the timeout with `Err(_)`.
/// Caller should propagate the error and retry on the next reconcile.
Failed(ReconcilerError),
/// The cleanup future did NOT complete within the timeout. Caller
/// should force-remove the finalizer to prevent stalling namespace
/// deletion and surface a Warning event so operators verify orphans.
TimedOut,
}
/// Wrap a cleanup future in a hard timeout and classify the outcome.
///
/// Pulled out as a standalone async function so the three branches can be
/// unit-tested in microseconds (`tokio::test(start_paused = true)`)
/// without mocking the kube API.
pub async fn run_cleanup_with_timeout<F>(timeout_duration: Duration, cleanup: F) -> CleanupOutcome
where
F: std::future::Future<Output = Result<(), ReconcilerError>>,
{
match tokio::time::timeout(timeout_duration, cleanup).await {
Ok(Ok(())) => CleanupOutcome::Completed,
Ok(Err(e)) => CleanupOutcome::Failed(e),
Err(_) => CleanupOutcome::TimedOut,
}
}
/// Build the `Warning` Kubernetes Event surfaced on a `ScheduledMachine`
/// whose finalizer was force-removed because cleanup exceeded
/// [`FINALIZER_CLEANUP_TIMEOUT_SECS`].
///
/// The note is the only operator-facing signal in `kubectl describe`, so
/// it MUST direct the operator to the orphan-cleanup runbook — the
/// controller has accepted that CAPI Machine + bootstrap/infra resources
/// may now be unowned and require manual verification.
#[must_use]
pub fn build_finalizer_timeout_event(timeout_secs: u64) -> KubeEvent {
KubeEvent {
type_: EventType::Warning,
reason: "FinalizerCleanupTimedOut".to_string(),
note: Some(format!(
"Finalizer cleanup exceeded {timeout_secs}s timeout. The finalizer was \
force-removed to unblock namespace deletion. Operators MUST manually verify \
that the CAPI Machine and its bootstrap/infrastructure resources have been \
cleaned up — orphan resources are possible. See the troubleshooting docs \
('Orphan resources after finalizer timeout') for the runbook."
)),
action: "FinalizerCleanupTimedOut".to_string(),
secondary: None,
}
}
/// Run finalizer cleanup when a `ScheduledMachine` is being deleted.
///
/// If the resource is currently in the `Active` or `ShuttingDown` phase the
/// corresponding CAPI Machine (and its child resources) are removed from the
/// cluster first. The removal is wrapped in a hard
/// [`FINALIZER_CLEANUP_TIMEOUT_SECS`] timeout so a hung API call cannot
/// block namespace deletion or cluster upgrades indefinitely.
///
/// On timeout the finalizer is **force-removed** (the reverse of the
/// original behaviour, which propagated the error and stalled deletion
/// indefinitely). The trade-off: a misbehaving Pod Disruption Budget on
/// a tenant workload can no longer block namespace deletion, but the
/// CAPI Machine and bootstrap/infrastructure resources may be left as
/// orphans. A `FinalizerCleanupTimedOut` Warning event is published on
/// the SM and `fivespot_finalizer_cleanup_timeouts_total` is incremented
/// so operators can detect and reconcile orphans.
///
/// On a non-timeout cleanup error (e.g., real CAPI delete failure) the
/// finalizer is **kept** and the error is propagated so the controller
/// retries on the next reconcile.
///
/// Once cleanup succeeds (or is skipped for non-running phases, or is
/// force-removed on timeout) the finalizer string is removed from
/// `metadata.finalizers`. After this patch Kubernetes considers the
/// resource fully deleted.
///
/// # Errors
/// - [`ReconcilerError::InvalidConfig`] — resource has no namespace
/// - [`ReconcilerError::CapiError`] — CAPI Machine delete call failed
/// (returned without removing the finalizer; reconciler retries)
/// - kube API error — finalizer patch call failed
///
/// Note: [`ReconcilerError::TimeoutError`] is no longer returned from this
/// function — timeouts now drive the force-remove path rather than
/// propagating up.
pub async fn handle_deletion(
resource: Arc<ScheduledMachine>,
ctx: Arc<Context>,
) -> Result<Action, ReconcilerError> {
let namespace = resource.namespace().ok_or_else(|| {
ReconcilerError::InvalidConfig("ScheduledMachine must be namespaced".to_string())
})?;
let name = resource.name_any();
let current_phase = resource.status.as_ref().and_then(|s| s.phase.as_deref());
info!(
resource = %name,
namespace = %namespace,
phase = current_phase.unwrap_or("(none)"),
deletion_timestamp = ?resource.meta().deletion_timestamp,
"DELETE: ScheduledMachine deletion requested — running finalizer cleanup"
);
// Wrap machine removal in a hard timeout so a hung removal cannot block
// namespace deletion or cluster upgrades indefinitely.
let cleanup_timeout = Duration::from_secs(FINALIZER_CLEANUP_TIMEOUT_SECS);
if let Some(phase) = current_phase {
if matches!(phase, PHASE_ACTIVE | PHASE_SHUTTING_DOWN) {
info!(
resource = %name,
namespace = %namespace,
timeout_secs = FINALIZER_CLEANUP_TIMEOUT_SECS,
"Removing machine from cluster before deletion"
);
let outcome = run_cleanup_with_timeout(
cleanup_timeout,
remove_machine_from_cluster(&resource, &ctx.client, &namespace),
)
.await;
match outcome {
CleanupOutcome::Completed => {
debug!(
resource = %name,
namespace = %namespace,
"Cleanup completed within timeout"
);
}
CleanupOutcome::Failed(e) => {
// Real cleanup error (e.g. CAPI delete failed): keep the
// finalizer, propagate the error, and let the reconciler
// retry with exponential back-off.
return Err(e);
}
CleanupOutcome::TimedOut => {
// Always increment the metric + emit Warning event so
// operators see timeouts regardless of which mode is on.
crate::metrics::record_finalizer_cleanup_timeout();
let object_ref = ObjectReference {
api_version: Some(API_VERSION_FULL.to_string()),
kind: Some(crate::constants::KIND_SCHEDULED_MACHINE.to_string()),
name: Some(name.clone()),
namespace: Some(namespace.clone()),
..Default::default()
};
let event = build_finalizer_timeout_event(FINALIZER_CLEANUP_TIMEOUT_SECS);
publish_best_effort(&ctx, &object_ref, event, "finalizer-timeout").await;
if ctx.force_finalizer_on_timeout {
// Force-remove path (default): log and fall through
// to finalizer removal so namespace deletion can
// proceed.
warn!(
resource = %name,
namespace = %namespace,
timeout_secs = FINALIZER_CLEANUP_TIMEOUT_SECS,
"Finalizer cleanup timed out; force-removing finalizer to unblock \
namespace deletion. Operators MUST verify CAPI Machine + \
bootstrap/infrastructure resources have been cleaned up — \
orphans are possible."
);
} else {
// Strict-cleanup mode: keep the finalizer and
// propagate the timeout so the reconciler retries.
// Operators must have an external sweep to garbage-
// collect stuck SMs in this mode.
error!(
resource = %name,
namespace = %namespace,
timeout_secs = FINALIZER_CLEANUP_TIMEOUT_SECS,
"Finalizer cleanup timed out; strict-cleanup mode enabled, \
keeping finalizer and retrying. SM deletion is BLOCKED until \
cleanup succeeds."
);
return Err(ReconcilerError::TimeoutError(format!(
"Finalizer cleanup timed out after {FINALIZER_CLEANUP_TIMEOUT_SECS}s for {name}"
)));
}
}
}
}
}
// Remove finalizer
let api: Api<ScheduledMachine> = Api::namespaced(ctx.client.clone(), &namespace);
let mut finalizers = resource.meta().finalizers.clone().unwrap_or_default();
finalizers.retain(|f| f != FINALIZER_SCHEDULED_MACHINE);
let patch = json!({
"metadata": {
"finalizers": finalizers
}
});
api.patch(&name, &PatchParams::default(), &Patch::Merge(&patch))
.await?;
info!(
resource = %name,
namespace = %namespace,
"DELETE: finalizer removed — Kubernetes will now delete the ScheduledMachine"
);
Ok(Action::await_change())
}
// ============================================================================
// Kill switch handling
// ============================================================================
/// Execute an emergency kill-switch that immediately removes the machine from
/// its cluster and transitions it to the `Terminated` phase.
///
/// The kill switch is an operator-level escape hatch for situations where the
/// normal graceful shutdown period must be bypassed (e.g., cost runaway,
/// security incident). Unlike the ordinary shutdown path, no grace period is
/// observed — removal happens synchronously in the reconcile loop.
///
/// The machine is only removed when its current phase is `Active` or
/// `ShuttingDown`. Resources already in `Inactive` or `Terminated` are left
/// untouched; the function simply records the `Terminated` phase to ensure
/// the status is up to date.
///
/// # Errors
/// - [`ReconcilerError::InvalidConfig`] — resource has no namespace
/// - [`ReconcilerError::CapiError`] — CAPI Machine delete call failed
/// - kube API error — status patch call failed
pub async fn handle_kill_switch(
resource: Arc<ScheduledMachine>,
ctx: Arc<Context>,
) -> Result<Action, ReconcilerError> {
let namespace = resource.namespace().ok_or_else(|| {
ReconcilerError::InvalidConfig("ScheduledMachine must be namespaced".to_string())
})?;
let name = resource.name_any();
let current_phase = resource.status.as_ref().and_then(|s| s.phase.as_deref());
// Only remove if not already inactive or terminated
if let Some(phase) = current_phase {
if phase != PHASE_INACTIVE
&& phase != PHASE_TERMINATED
&& matches!(phase, PHASE_ACTIVE | PHASE_SHUTTING_DOWN)
{
info!(
resource = %name,
namespace = %namespace,
phase = %phase,
"KILL: removing CAPI Machine due to kill switch"
);
remove_machine_from_cluster(&resource, &ctx.client, &namespace).await?;
} else {
info!(
resource = %name,
namespace = %namespace,
phase = %phase,
"KILL: kill switch set but machine not running — recording Terminated phase only"
);
}
}
let from_phase = resource.status.as_ref().and_then(|s| s.phase.as_deref());
update_phase(
&ctx,
&namespace,
&name,
from_phase,
PHASE_TERMINATED,
Some(REASON_KILL_SWITCH),
Some("Machine terminated due to kill switch"),
false, // in_schedule: kill switch overrides schedule
)
.await?;
Ok(Action::requeue(Duration::from_secs(TIMER_REQUEUE_SECS)))
}
// ============================================================================
// Grace period management
// ============================================================================
/// Return `true` when the graceful shutdown timeout has been exceeded.
///
/// The grace period is tracked via the `last_transition_time` field of the
/// status condition whose `reason` equals [`REASON_GRACE_PERIOD`]. That
/// timestamp is written by [`update_phase_with_grace_period`] when the
/// machine first enters the `ShuttingDown` phase.
///
/// If no such condition is found (e.g., the resource was transitioned to
/// `ShuttingDown` by an older controller version that did not record the
/// condition), the function conservatively returns `true` so the drain
/// proceeds without getting stuck.
///
/// # Errors
/// - [`ReconcilerError::InvalidConfig`] — resource has no `.status` sub-resource
/// or the recorded timestamp is not valid RFC-3339
pub fn check_grace_period_elapsed(resource: &ScheduledMachine) -> Result<bool, ReconcilerError> {
let status = resource
.status
.as_ref()
.ok_or_else(|| ReconcilerError::InvalidConfig("Resource has no status".to_string()))?;
// Check for grace period start time in conditions
let grace_start_str = status
.conditions
.iter()
.find(|c| c.reason == REASON_GRACE_PERIOD)
.map(|c| c.last_transition_time.as_str());
if let Some(start_time_str) = grace_start_str {
// Parse RFC3339 timestamp
let start_time = DateTime::parse_from_rfc3339(start_time_str)
.map_err(|e| ReconcilerError::InvalidConfig(format!("Invalid timestamp: {e}")))?
.with_timezone(&Utc);
let timeout = parse_duration(&resource.spec.graceful_shutdown_timeout)?;
let now = Utc::now();
let elapsed = now.signed_duration_since(start_time);
let elapsed_secs = elapsed.num_seconds();
debug!(
grace_start = %start_time,
elapsed_secs,
timeout_secs = timeout.as_secs(),
"Grace period check"
);
// Clock-skew guard: if the recorded start timestamp is *ahead* of the
// current wall clock (NTP step, VM freeze-thaw, or a manual clock
// adjustment), `elapsed_secs` is negative. The prior
// `elapsed.num_seconds() >= timeout.as_secs() as i64` expression
// silently returned false in that case and could bypass the
// graceful-drain window entirely. Treat any negative elapsed as
// "timeout reached" so the reconciler forces progress rather than
// stalling on a misbehaving clock.
if elapsed_secs < 0 {
warn!(
grace_start = %start_time,
now_utc = %now,
elapsed_secs,
"Negative elapsed time detected (clock adjustment?); treating grace period as elapsed"
);
return Ok(true);
}
// Safe cast: u64 timeout converted to i64 cannot wrap because
// MAX_DURATION_SECS (24h) fits in i64, and elapsed_secs is now
// known non-negative.
#[allow(clippy::cast_possible_wrap)]
Ok(elapsed_secs >= timeout.as_secs() as i64)
} else {
// No grace period started yet
Ok(true)
}
}
/// Parse duration string (e.g., "5m", "10s", "1h")
///
/// # Errors
/// Returns error on empty input, invalid format, integer overflow, or values exceeding 24 hours.
pub fn parse_duration(duration_str: &str) -> Result<Duration, ReconcilerError> {
let duration_str = duration_str.trim();
if duration_str.is_empty() {
return Err(ReconcilerError::InvalidConfig(
"Empty duration string".to_string(),
));
}
// Reject non-ASCII early. split_at(len - 1) below indexes by bytes; a
// multi-byte UTF-8 code point at the tail panics. Legal units are s/m/h
// (all ASCII) so any non-ASCII byte is already an invalid input.
if !duration_str.is_ascii() {
return Err(ReconcilerError::InvalidConfig(format!(
"Invalid duration (non-ASCII): {duration_str:?}"
)));
}
let (value_str, unit) = duration_str.split_at(duration_str.len() - 1);
let value: u64 = value_str.parse().map_err(|_| {
ReconcilerError::InvalidConfig(format!("Invalid duration value: {duration_str}"))
})?;
let multiplier: u64 = match unit {
"s" => 1,
"m" => 60,
"h" => 3600,
_ => {
return Err(ReconcilerError::InvalidConfig(format!(
"Invalid duration unit: '{unit}'. Use 's', 'm', or 'h'"
)))
}
};
let seconds = value.checked_mul(multiplier).ok_or_else(|| {
ReconcilerError::InvalidConfig(format!(
"Duration overflow: '{duration_str}' exceeds representable range"
))
})?;
if seconds > MAX_DURATION_SECS {
return Err(ReconcilerError::InvalidConfig(format!(
"Duration {seconds}s exceeds maximum of {MAX_DURATION_SECS}s (24h)"
)));
}
Ok(Duration::from_secs(seconds))
}
// ============================================================================
// Kubernetes Event helpers
// ============================================================================
/// Build a Kubernetes Event for a phase transition.
///
/// Returns `EventType::Warning` for `Error` and `Terminated` phases (actionable
/// operator alert); `EventType::Normal` for all other transitions.
pub fn build_phase_transition_event(
from_phase: Option<&str>,
to_phase: &str,
reason: &str,
message: &str,
) -> KubeEvent {
let event_type = if to_phase == PHASE_ERROR || to_phase == PHASE_TERMINATED {
EventType::Warning
} else {
EventType::Normal
};
KubeEvent {
type_: event_type,
reason: reason.to_string(),
note: Some(format!(
"{} -> {}: {}",
from_phase.unwrap_or("Unknown"),
to_phase,
message
)),
action: format!("PhaseTransitionTo{to_phase}"),
secondary: None,
}
}
// ============================================================================
// Status update helpers
// ============================================================================
/// Update phase and status condition, recording an immutable Kubernetes Event
/// for audit trail (SOX §404, NIST AU-2/AU-3).
///
/// The `from_phase` parameter captures the previous phase for before/after logging.
/// Event recording is best-effort — a failure to publish the event is logged as a
/// warning but does not abort the phase transition.
#[allow(clippy::too_many_arguments)]
pub async fn update_phase(
ctx: &Context,
namespace: &str,
name: &str,
from_phase: Option<&str>,
phase: &str,
reason: Option<&str>,
message: Option<&str>,
in_schedule: bool,
) -> Result<(), ReconcilerError> {
let resolved_reason = reason.unwrap_or(REASON_RECONCILE_SUCCEEDED);
let resolved_message = message.unwrap_or("Phase transition completed");
info!(
resource = %name,
namespace = %namespace,
from = from_phase.unwrap_or("Unknown"),
to = %phase,
reason = %resolved_reason,
"Phase transition"
);
// Record an immutable Kubernetes Event for the audit trail
let object_ref = ObjectReference {
api_version: Some(crate::constants::API_VERSION_FULL.to_string()),
kind: Some(crate::constants::KIND_SCHEDULED_MACHINE.to_string()),
name: Some(name.to_string()),
namespace: Some(namespace.to_string()),
..Default::default()
};
let event = build_phase_transition_event(from_phase, phase, resolved_reason, resolved_message);
if let Err(e) = ctx.recorder.publish(&event, &object_ref).await {
warn!(
resource = %name,
namespace = %namespace,
error = %e,
"Failed to record phase transition event (audit trail incomplete)"
);
}
let api: Api<ScheduledMachine> = Api::namespaced(ctx.client.clone(), namespace);
let condition = Condition::new(
CONDITION_TYPE_READY,
CONDITION_STATUS_TRUE,
resolved_reason,
resolved_message,
);
let status = ScheduledMachineStatus {
phase: Some(phase.to_string()),
message: Some(resolved_message.to_string()),
conditions: vec![condition],
in_schedule,
ready: phase == PHASE_ACTIVE,
..Default::default()
};
let patch = json!({
"status": status
});
api.patch_status(name, &PatchParams::default(), &Patch::Merge(&patch))
.await?;
Ok(())
}
/// Patch the status with the current time as `lastScheduledTime`, recording
/// an immutable audit event.
///
/// Used when the machine transitions to `Active` after being provisioned on
/// schedule. The `lastScheduledTime` field lets operators audit when the
/// last scheduled window began.
///
/// # Errors
/// Same as [`update_phase`].
#[allow(dead_code)] // TODO: Use this when machine creation is implemented
#[allow(clippy::too_many_arguments)]
pub async fn update_phase_with_last_schedule(
ctx: &Context,
namespace: &str,
name: &str,
from_phase: Option<&str>,
phase: &str,
reason: Option<&str>,
message: Option<&str>,
in_schedule: bool,
) -> Result<(), ReconcilerError> {
let resolved_reason = reason.unwrap_or(REASON_RECONCILE_SUCCEEDED);
let resolved_message = message.unwrap_or("Phase transition completed");
info!(
resource = %name,
namespace = %namespace,
from = from_phase.unwrap_or("Unknown"),
to = %phase,
reason = %resolved_reason,
"Phase transition"
);
let object_ref = ObjectReference {
api_version: Some(crate::constants::API_VERSION_FULL.to_string()),
kind: Some(crate::constants::KIND_SCHEDULED_MACHINE.to_string()),
name: Some(name.to_string()),
namespace: Some(namespace.to_string()),
..Default::default()
};
let event = build_phase_transition_event(from_phase, phase, resolved_reason, resolved_message);
if let Err(e) = ctx.recorder.publish(&event, &object_ref).await {
warn!(resource = %name, error = %e, "Failed to record phase transition event");
}
let api: Api<ScheduledMachine> = Api::namespaced(ctx.client.clone(), namespace);
let condition = Condition::new(
CONDITION_TYPE_READY,
CONDITION_STATUS_TRUE,
resolved_reason,
resolved_message,
);
let status = ScheduledMachineStatus {
phase: Some(phase.to_string()),
message: Some(resolved_message.to_string()),
conditions: vec![condition],
last_scheduled_time: Some(Utc::now().to_rfc3339()),
in_schedule,
ready: phase == PHASE_ACTIVE,
..Default::default()
};
let patch = json!({
"status": status
});
api.patch_status(name, &PatchParams::default(), &Patch::Merge(&patch))
.await?;
Ok(())
}
/// Patch the status to `ShuttingDown` and stamp the current time into the
/// `last_transition_time` of the grace-period condition.
///
/// This timestamp is later read by [`check_grace_period_elapsed`] to decide
/// when the drain window has closed. Recording it here — rather than
/// computing elapsed time from an external clock — makes the grace period
/// robust to controller restarts.
///
/// # Errors
/// Same as [`update_phase`].
#[allow(clippy::too_many_arguments)]
pub async fn update_phase_with_grace_period(
ctx: &Context,
namespace: &str,
name: &str,
from_phase: Option<&str>,
phase: &str,
reason: Option<&str>,
message: Option<&str>,
in_schedule: bool,
) -> Result<(), ReconcilerError> {
let resolved_reason = reason.unwrap_or(REASON_GRACE_PERIOD);
let resolved_message = message.unwrap_or("Grace period started");
info!(
resource = %name,
namespace = %namespace,
from = from_phase.unwrap_or("Unknown"),
to = %phase,
reason = %resolved_reason,
"Phase transition"
);
let object_ref = ObjectReference {
api_version: Some(crate::constants::API_VERSION_FULL.to_string()),
kind: Some(crate::constants::KIND_SCHEDULED_MACHINE.to_string()),
name: Some(name.to_string()),
namespace: Some(namespace.to_string()),
..Default::default()
};
let event = build_phase_transition_event(from_phase, phase, resolved_reason, resolved_message);
if let Err(e) = ctx.recorder.publish(&event, &object_ref).await {
warn!(resource = %name, error = %e, "Failed to record phase transition event");
}
let api: Api<ScheduledMachine> = Api::namespaced(ctx.client.clone(), namespace);
let condition = Condition::new(
CONDITION_TYPE_READY,
CONDITION_STATUS_TRUE,
resolved_reason,
resolved_message,
);
let status = ScheduledMachineStatus {
phase: Some(phase.to_string()),
message: Some(resolved_message.to_string()),
conditions: vec![condition],
in_schedule,
ready: phase == PHASE_ACTIVE,
..Default::default()
};
let patch = json!({
"status": status
});
api.patch_status(name, &PatchParams::default(), &Patch::Merge(&patch))
.await?;
Ok(())
}
// ============================================================================
// Security validation helpers
// ============================================================================
/// Reject label/annotation maps that contain reserved key prefixes.
///
/// Users must not be able to override system labels such as
/// `cluster.x-k8s.io/cluster-name` or `kubernetes.io/*` via `machineTemplate`.
pub fn validate_labels(
labels: &BTreeMap<String, String>,
field: &str,
) -> Result<(), ReconcilerError> {
for key in labels.keys() {
for prefix in RESERVED_LABEL_PREFIXES {
if key.starts_with(prefix) {
return Err(ReconcilerError::ValidationError(format!(
"{field} key '{key}' uses reserved prefix '{prefix}'"
)));
}
}
}
Ok(())
}
/// Reject `spec.clusterName` values that exceed the effective CAPI cap or
/// contain characters unsafe for log / label / metric emission.
///
/// CAPI itself inherits the Kubernetes 253-char DNS-1123 subdomain cap on
/// `Cluster.metadata.name`, but the name flows downstream into DNS labels
/// (63 chars) and the `cluster.x-k8s.io/cluster-name` label value. 63 is
/// therefore the *effective* upper bound — see [`MAX_CLUSTER_NAME_LEN`].
///
/// The character check rejects control chars, whitespace, and non-ASCII so
/// a malicious CR cannot forge log records via embedded newlines or bloat
/// Prometheus label cardinality with exotic Unicode.
///
/// # Errors
/// [`ReconcilerError::ValidationError`] if the name is empty, too long, or
/// contains a disallowed character.
pub fn validate_cluster_name(cluster_name: &str) -> Result<(), ReconcilerError> {
if cluster_name.is_empty() {
return Err(ReconcilerError::ValidationError(
"spec.clusterName must not be empty".to_string(),
));
}
if cluster_name.len() > MAX_CLUSTER_NAME_LEN {
return Err(ReconcilerError::ValidationError(format!(
"spec.clusterName length {} exceeds maximum of {MAX_CLUSTER_NAME_LEN} characters",
cluster_name.len()
)));
}
// Allow ASCII letters, digits, '-', '.', '_' — the intersection of
// DNS-1123 subdomain and Kubernetes label-value charsets. Anything
// outside that (including embedded NUL, newline, or multi-byte UTF-8)
// is rejected with a single uniform error.
if !cluster_name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.' || b == b'_')
{
return Err(ReconcilerError::ValidationError(format!(
"spec.clusterName contains invalid character(s); allowed: ASCII alphanumerics, '-', '.', '_' (got: {cluster_name:?})"
)));
}
Ok(())
}
/// Reject `spec.killIfCommands` lists that exceed the count cap or contain
/// an over-length / empty pattern.
///
/// The reclaim agent evaluates each pattern against every PID in `/proc`;
/// without a cap, a single CR can pin an entire node's agent CPU or balloon
/// the per-node `ConfigMap` projection. Empty patterns would match every
/// process and are almost certainly a mistake rather than an intentional
/// kill-all rule — reject them loudly.
///
/// `None` and `Some(&[])` are both accepted: the controller treats them
/// identically ("no reclaim agent on this node").
///
/// # Errors
/// [`ReconcilerError::ValidationError`] on any violation, naming the
/// offending index so operators can fix the CR quickly.
pub fn validate_kill_if_commands(commands: Option<&[String]>) -> Result<(), ReconcilerError> {
let Some(cmds) = commands else {
return Ok(());
};
if cmds.len() > MAX_KILL_IF_COMMANDS_COUNT {
return Err(ReconcilerError::ValidationError(format!(
"spec.killIfCommands has {} entries, exceeds maximum of {MAX_KILL_IF_COMMANDS_COUNT}",
cmds.len()
)));
}
for (idx, cmd) in cmds.iter().enumerate() {