1use std::collections::{BTreeMap, BTreeSet};
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53
54use async_trait::async_trait;
55use engenho_config::parse_ipv4_cidr;
56use engenho_store::StoreMesh;
57use serde_json::Value;
58use thiserror::Error;
59
60use crate::admission::{
61 AdmissionAction, AdmissionDecision, AdmissionError, AdmissionRequest, AdmissionWebhook,
62};
63
64#[derive(Debug, Clone, Error, PartialEq, Eq)]
70pub enum AllocatorError {
71 #[error("invalid service CIDR: {0}")]
73 InvalidCidr(String),
74 #[error("service CIDR {cidr} is exhausted ({held} VIPs in use)")]
77 PoolExhausted {
78 cidr: String,
80 held: usize,
82 },
83}
84
85engenho_substrate::impl_error_kind! {
86 AllocatorError {
87 (InvalidCidr(_)) => "invalid_cidr",
88 { PoolExhausted { .. } } => "pool_exhausted",
89 }
90}
91
92#[derive(Clone, Debug)]
104pub struct ClusterIpAllocator {
105 cidr: String,
107 base: u32,
109 first: u32,
112 last: u32,
115 in_use: BTreeSet<u32>,
117}
118
119impl ClusterIpAllocator {
120 pub fn new(cidr: &str) -> Result<Self, AllocatorError> {
126 let (base, prefix) = parse_ipv4_cidr(cidr).map_err(AllocatorError::InvalidCidr)?;
127 let host_bits = 32 - u32::from(prefix);
131 let (first, last) = if prefix >= 31 {
132 let size = if host_bits == 0 { 1 } else { 2 };
134 (base, base.saturating_add(size - 1))
135 } else {
136 let block_size = 1u64 << host_bits;
137 let broadcast = u64::from(base) + block_size - 1;
138 let last = u32::try_from(broadcast - 1).unwrap_or(u32::MAX);
143 (base + 1, last)
144 };
145 Ok(Self {
146 cidr: cidr.to_string(),
147 base,
148 first,
149 last,
150 in_use: BTreeSet::new(),
151 })
152 }
153
154 pub fn reserve(&mut self, ip: &str) -> bool {
159 match ip_to_u32(ip) {
160 Some(v) if v >= self.base && v <= self.last => self.in_use.insert(v),
161 _ => false,
162 }
163 }
164
165 pub fn release(&mut self, ip: &str) {
167 if let Some(v) = ip_to_u32(ip) {
168 self.in_use.remove(&v);
169 }
170 }
171
172 pub fn allocate(&mut self) -> Result<String, AllocatorError> {
179 let mut candidate = self.first;
180 while candidate <= self.last {
181 if !self.in_use.contains(&candidate) {
182 self.in_use.insert(candidate);
183 return Ok(u32_to_ip(candidate));
184 }
185 if candidate == u32::MAX {
187 break;
188 }
189 candidate += 1;
190 }
191 Err(AllocatorError::PoolExhausted {
192 cidr: self.cidr.clone(),
193 held: self.in_use.len(),
194 })
195 }
196
197 #[must_use]
199 pub fn held(&self) -> usize {
200 self.in_use.len()
201 }
202
203 #[must_use]
205 pub fn is_held(&self, ip: &str) -> bool {
206 ip_to_u32(ip).is_some_and(|v| self.in_use.contains(&v))
207 }
208}
209
210fn ip_to_u32(ip: &str) -> Option<u32> {
212 let octets: Vec<&str> = ip.split('.').collect();
213 if octets.len() != 4 {
214 return None;
215 }
216 let mut v: u32 = 0;
217 for oct in octets {
218 let byte: u8 = oct.parse().ok()?;
219 v = (v << 8) | u32::from(byte);
220 }
221 Some(v)
222}
223
224fn u32_to_ip(v: u32) -> String {
230 format!(
231 "{}.{}.{}.{}",
232 (v >> 24) & 0xff,
233 (v >> 16) & 0xff,
234 (v >> 8) & 0xff,
235 v & 0xff
236 )
237}
238
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub enum ServiceVipDisposition {
246 NeedsAllocation,
248 Headless,
250 ExternalName,
252 AlreadyAssigned,
254}
255
256#[must_use]
258pub fn classify_service(svc: &Value) -> ServiceVipDisposition {
259 let spec = svc.get("spec");
260 let svc_type = spec
261 .and_then(|s| s.get("type"))
262 .and_then(Value::as_str)
263 .unwrap_or("ClusterIP");
264 if svc_type == "ExternalName" {
265 return ServiceVipDisposition::ExternalName;
266 }
267 let cluster_ip = spec
268 .and_then(|s| s.get("clusterIP"))
269 .and_then(Value::as_str);
270 match cluster_ip {
271 Some("None") => ServiceVipDisposition::Headless,
272 None | Some("") => ServiceVipDisposition::NeedsAllocation,
273 Some(_concrete) => ServiceVipDisposition::AlreadyAssigned,
274 }
275}
276
277#[async_trait]
287pub trait ServiceIpSource: Send + Sync {
288 async fn held_cluster_ips(&self) -> Vec<String>;
294}
295
296pub struct StoreServiceIpSource {
299 store: Arc<StoreMesh>,
300}
301
302impl StoreServiceIpSource {
303 #[must_use]
305 pub fn new(store: Arc<StoreMesh>) -> Self {
306 Self { store }
307 }
308}
309
310#[async_trait]
311impl ServiceIpSource for StoreServiceIpSource {
312 async fn held_cluster_ips(&self) -> Vec<String> {
313 let services = self.store.list("", "v1", "Service", None).await;
314 let mut ips = Vec::new();
315 for (_key, svc) in services {
316 if let Some(ip) = svc
317 .get("spec")
318 .and_then(|s| s.get("clusterIP"))
319 .and_then(Value::as_str)
320 {
321 ips.push(ip.to_string());
322 }
323 if let Some(arr) = svc
324 .get("spec")
325 .and_then(|s| s.get("clusterIPs"))
326 .and_then(Value::as_array)
327 {
328 for v in arr {
329 if let Some(ip) = v.as_str() {
330 ips.push(ip.to_string());
331 }
332 }
333 }
334 }
335 ips
336 }
337}
338
339pub struct ClusterIpDefaultingWebhook {
355 cidr: String,
357 source: Arc<dyn ServiceIpSource>,
359 granted: tokio::sync::Mutex<BTreeMap<String, Instant>>,
363 grant_ttl: Duration,
365}
366
367const GRANT_TTL: Duration = Duration::from_secs(120);
368
369impl ClusterIpDefaultingWebhook {
370 #[must_use]
372 pub fn new(cidr: impl Into<String>, source: Arc<dyn ServiceIpSource>) -> Self {
373 Self {
374 cidr: cidr.into(),
375 source,
376 granted: tokio::sync::Mutex::new(BTreeMap::new()),
377 grant_ttl: GRANT_TTL,
378 }
379 }
380
381 #[must_use]
384 pub fn with_grant_ttl(mut self, ttl: Duration) -> Self {
385 self.grant_ttl = ttl;
386 self
387 }
388
389 fn is_service(key: &engenho_store::resource::ResourceKey) -> bool {
391 key.group.is_empty() && key.version == "v1" && key.kind == "Service"
392 }
393}
394
395#[async_trait]
396impl AdmissionWebhook for ClusterIpDefaultingWebhook {
397 fn name(&self) -> &'static str {
398 "cluster-ip-allocator"
399 }
400
401 async fn review(
402 &self,
403 request: &AdmissionRequest,
404 ) -> Result<AdmissionDecision, AdmissionError> {
405 if request.action != AdmissionAction::Put || !Self::is_service(&request.key) {
407 return Ok(AdmissionDecision::Allow);
408 }
409 let Some(svc) = &request.value else {
410 return Ok(AdmissionDecision::Allow);
411 };
412
413 match classify_service(svc) {
414 ServiceVipDisposition::NeedsAllocation => {}
415 _ => return Ok(AdmissionDecision::Allow),
417 }
418
419 let mut allocator = match ClusterIpAllocator::new(&self.cidr) {
423 Ok(a) => a,
424 Err(e) => {
425 return Err(AdmissionError::Backend(e.to_string()));
429 }
430 };
431 let mut granted = self.granted.lock().await;
432 let held: BTreeSet<String> = self.source.held_cluster_ips().await.into_iter().collect();
433 granted.retain(|ip, at| !held.contains(ip) && at.elapsed() < self.grant_ttl);
434 for ip in held.iter().chain(granted.keys()) {
435 allocator.reserve(ip);
436 }
437
438 let vip = match allocator.allocate() {
439 Ok(ip) => ip,
440 Err(e) => {
441 return Ok(AdmissionDecision::Deny(e.to_string()));
444 }
445 };
446 granted.insert(vip.clone(), Instant::now());
447 drop(granted);
448
449 let mut mutated = svc.clone();
452 let spec = mutated.as_object_mut().and_then(|o| {
453 o.entry("spec")
454 .or_insert_with(|| Value::Object(Default::default()))
455 .as_object_mut()
456 });
457 let Some(spec) = spec else {
458 return Ok(AdmissionDecision::Deny(
460 "Service has a non-object spec; cannot assign clusterIP".to_string(),
461 ));
462 };
463 spec.insert("clusterIP".to_string(), Value::String(vip.clone()));
464 spec.insert(
465 "clusterIPs".to_string(),
466 Value::Array(vec![Value::String(vip)]),
467 );
468 Ok(AdmissionDecision::Mutate(mutated))
469 }
470}
471
472#[derive(Clone, Default)]
474pub struct StaticServiceIpSource {
475 ips: Vec<String>,
476}
477
478impl StaticServiceIpSource {
479 #[must_use]
481 pub fn new(ips: Vec<String>) -> Self {
482 Self { ips }
483 }
484}
485
486#[async_trait]
487impl ServiceIpSource for StaticServiceIpSource {
488 async fn held_cluster_ips(&self) -> Vec<String> {
489 self.ips.clone()
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use engenho_store::resource::ResourceKey;
497 use serde_json::json;
498
499 #[test]
502 fn allocate_starts_at_first_host() {
503 let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
504 assert_eq!(a.allocate().unwrap(), "10.96.0.1");
506 }
507
508 #[test]
509 fn two_allocations_are_distinct_and_sequential() {
510 let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
511 let v1 = a.allocate().unwrap();
512 let v2 = a.allocate().unwrap();
513 assert_ne!(v1, v2, "collision-free");
514 assert_eq!(v1, "10.96.0.1");
515 assert_eq!(v2, "10.96.0.2");
516 }
517
518 #[test]
519 fn reserve_skips_held_vips() {
520 let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
521 a.reserve("10.96.0.1");
522 a.reserve("10.96.0.2");
523 assert_eq!(a.allocate().unwrap(), "10.96.0.3");
525 }
526
527 #[test]
528 fn release_returns_vip_to_pool() {
529 let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
530 let v1 = a.allocate().unwrap(); assert_eq!(a.held(), 1);
532 a.release(&v1);
533 assert_eq!(a.held(), 0);
534 assert_eq!(a.allocate().unwrap(), "10.96.0.1");
536 }
537
538 #[test]
539 fn reserve_ignores_out_of_range_and_non_vip() {
540 let mut a = ClusterIpAllocator::new("10.96.0.0/24").unwrap();
541 assert!(!a.reserve("None"));
542 assert!(!a.reserve(""));
543 assert!(!a.reserve("192.168.1.1")); assert!(!a.reserve("not-an-ip"));
545 assert_eq!(a.held(), 0);
546 }
547
548 #[test]
549 fn small_cidr_exhausts_with_typed_error() {
550 let mut a = ClusterIpAllocator::new("10.0.0.0/30").unwrap();
552 assert_eq!(a.allocate().unwrap(), "10.0.0.1");
553 assert_eq!(a.allocate().unwrap(), "10.0.0.2");
554 let err = a.allocate().unwrap_err();
555 assert_eq!(err.kind(), "pool_exhausted");
556 }
557
558 #[test]
559 fn invalid_cidr_is_typed_error() {
560 let err = ClusterIpAllocator::new("nonsense").unwrap_err();
561 assert_eq!(err.kind(), "invalid_cidr");
562 }
563
564 #[test]
565 fn allocation_survives_restart_via_reseed() {
566 let mut p1 = ClusterIpAllocator::new("10.96.0.0/16").unwrap();
570 let held1 = p1.allocate().unwrap(); let held2 = p1.allocate().unwrap(); let mut p2 = ClusterIpAllocator::new("10.96.0.0/16").unwrap();
575 p2.reserve(&held1);
576 p2.reserve(&held2);
577 let next = p2.allocate().unwrap();
578 assert_ne!(next, held1);
579 assert_ne!(next, held2);
580 assert_eq!(next, "10.96.0.3", "recomputes from the durable set");
581 }
582
583 #[test]
586 fn classify_default_service_needs_allocation() {
587 let svc = json!({"spec": {"ports": [{"port": 80}]}});
588 assert_eq!(
589 classify_service(&svc),
590 ServiceVipDisposition::NeedsAllocation
591 );
592 let svc2 = json!({"spec": {"type": "ClusterIP", "clusterIP": ""}});
593 assert_eq!(
594 classify_service(&svc2),
595 ServiceVipDisposition::NeedsAllocation
596 );
597 }
598
599 #[test]
600 fn classify_headless_service() {
601 let svc = json!({"spec": {"clusterIP": "None"}});
602 assert_eq!(classify_service(&svc), ServiceVipDisposition::Headless);
603 }
604
605 #[test]
606 fn classify_external_name_service() {
607 let svc = json!({"spec": {"type": "ExternalName", "externalName": "db.example.com"}});
608 assert_eq!(classify_service(&svc), ServiceVipDisposition::ExternalName);
609 }
610
611 #[test]
612 fn classify_already_assigned() {
613 let svc = json!({"spec": {"clusterIP": "10.96.5.5"}});
614 assert_eq!(
615 classify_service(&svc),
616 ServiceVipDisposition::AlreadyAssigned
617 );
618 }
619
620 fn svc_request(svc: Value) -> AdmissionRequest {
623 AdmissionRequest {
624 action: AdmissionAction::Put,
625 key: ResourceKey::namespaced("", "v1", "Service", "default", "podinfo"),
626 value: Some(svc),
627 current: None,
628 user_info: engenho_types::auth::UserInfo::default(),
629 }
630 }
631
632 #[tokio::test]
633 async fn webhook_allocates_vip_for_default_service() {
634 let source = Arc::new(StaticServiceIpSource::new(vec![]));
635 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
636 let req = svc_request(json!({
637 "kind": "Service", "apiVersion": "v1",
638 "metadata": {"name": "podinfo"},
639 "spec": {"selector": {"app": "podinfo"}, "ports": [{"port": 80}]}
640 }));
641 match wh.review(&req).await.unwrap() {
642 AdmissionDecision::Mutate(v) => {
643 let ip = v["spec"]["clusterIP"].as_str().unwrap();
644 assert_eq!(ip, "10.96.0.1");
645 assert_eq!(v["spec"]["clusterIPs"][0], "10.96.0.1");
647 }
648 other => panic!("expected Mutate, got {other:?}"),
649 }
650 }
651
652 #[tokio::test]
653 async fn webhook_skips_held_vips_collision_free() {
654 let source = Arc::new(StaticServiceIpSource::new(vec![
656 "10.96.0.1".into(),
657 "10.96.0.2".into(),
658 ]));
659 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
660 let req = svc_request(json!({
661 "kind": "Service", "apiVersion": "v1",
662 "metadata": {"name": "new"}, "spec": {"ports": [{"port": 80}]}
663 }));
664 match wh.review(&req).await.unwrap() {
665 AdmissionDecision::Mutate(v) => {
666 assert_eq!(v["spec"]["clusterIP"], "10.96.0.3");
667 }
668 other => panic!("expected Mutate, got {other:?}"),
669 }
670 }
671
672 #[tokio::test]
673 async fn webhook_leaves_headless_untouched() {
674 let source = Arc::new(StaticServiceIpSource::new(vec![]));
675 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
676 let req = svc_request(json!({
677 "kind": "Service", "apiVersion": "v1",
678 "metadata": {"name": "headless"},
679 "spec": {"clusterIP": "None", "selector": {"app": "x"}}
680 }));
681 assert!(matches!(
683 wh.review(&req).await.unwrap(),
684 AdmissionDecision::Allow
685 ));
686 }
687
688 #[tokio::test]
689 async fn webhook_leaves_external_name_untouched() {
690 let source = Arc::new(StaticServiceIpSource::new(vec![]));
691 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
692 let req = svc_request(json!({
693 "kind": "Service", "apiVersion": "v1",
694 "metadata": {"name": "ext"},
695 "spec": {"type": "ExternalName", "externalName": "db.example.com"}
696 }));
697 assert!(matches!(
698 wh.review(&req).await.unwrap(),
699 AdmissionDecision::Allow
700 ));
701 }
702
703 #[tokio::test]
704 async fn webhook_honors_operator_pinned_clusterip() {
705 let source = Arc::new(StaticServiceIpSource::new(vec![]));
706 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
707 let req = svc_request(json!({
708 "kind": "Service", "apiVersion": "v1",
709 "metadata": {"name": "pinned"},
710 "spec": {"clusterIP": "10.96.7.7", "ports": [{"port": 80}]}
711 }));
712 assert!(matches!(
714 wh.review(&req).await.unwrap(),
715 AdmissionDecision::Allow
716 ));
717 }
718
719 #[tokio::test]
720 async fn webhook_ignores_non_service_kinds() {
721 let source = Arc::new(StaticServiceIpSource::new(vec![]));
722 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
723 let req = AdmissionRequest {
724 action: AdmissionAction::Put,
725 key: ResourceKey::namespaced("", "v1", "Pod", "default", "p"),
726 value: Some(json!({"kind": "Pod"})),
727 current: None,
728 user_info: engenho_types::auth::UserInfo::default(),
729 };
730 assert!(matches!(
731 wh.review(&req).await.unwrap(),
732 AdmissionDecision::Allow
733 ));
734 }
735
736 #[tokio::test]
737 async fn webhook_denies_on_pool_exhaustion() {
738 let source = Arc::new(StaticServiceIpSource::new(vec![
740 "10.0.0.1".into(),
741 "10.0.0.2".into(),
742 ]));
743 let wh = ClusterIpDefaultingWebhook::new("10.0.0.0/30", source);
744 let req = svc_request(json!({
745 "kind": "Service", "apiVersion": "v1",
746 "metadata": {"name": "doomed"}, "spec": {"ports": [{"port": 80}]}
747 }));
748 match wh.review(&req).await.unwrap() {
749 AdmissionDecision::Deny(reason) => assert!(reason.contains("exhausted")),
750 other => panic!("expected Deny, got {other:?}"),
751 }
752 }
753
754 #[tokio::test]
755 async fn webhook_restart_persistence_via_store_reseed() {
756 let live_after_restart = Arc::new(StaticServiceIpSource::new(vec![
760 "10.96.0.1".into(),
761 "10.96.0.2".into(),
762 "10.96.0.3".into(),
763 ]));
764 let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", live_after_restart);
765 let req = svc_request(json!({
766 "kind": "Service", "apiVersion": "v1",
767 "metadata": {"name": "post-restart"}, "spec": {"ports": [{"port": 80}]}
768 }));
769 match wh.review(&req).await.unwrap() {
770 AdmissionDecision::Mutate(v) => {
771 assert_eq!(v["spec"]["clusterIP"], "10.96.0.4");
772 }
773 other => panic!("expected Mutate, got {other:?}"),
774 }
775 }
776
777 fn vip_of(decision: AdmissionDecision) -> String {
778 match decision {
779 AdmissionDecision::Mutate(v) => v["spec"]["clusterIP"].as_str().unwrap().to_string(),
780 other => panic!("expected Mutate, got {other:?}"),
781 }
782 }
783
784 #[tokio::test]
785 async fn concurrent_creates_never_share_a_vip_before_any_of_them_commits() {
786 let source = Arc::new(StaticServiceIpSource::new(vec![]));
787 let wh = Arc::new(ClusterIpDefaultingWebhook::new("10.97.0.0/16", source));
788 let reviews = ["grafana", "kube-state-metrics", "operator"].map(|name| {
789 let wh = wh.clone();
790 tokio::spawn(async move {
791 let req = svc_request(json!({
792 "kind": "Service", "apiVersion": "v1",
793 "metadata": {"name": name}, "spec": {"ports": [{"port": 80}]}
794 }));
795 vip_of(wh.review(&req).await.unwrap())
796 })
797 });
798 let mut vips = BTreeSet::new();
799 for r in reviews {
800 vips.insert(r.await.unwrap());
801 }
802 assert_eq!(vips.len(), 3, "{vips:?}");
803 }
804
805 #[tokio::test]
806 async fn a_grant_that_never_committed_returns_to_the_pool_after_its_ttl() {
807 let source = Arc::new(StaticServiceIpSource::new(vec![]));
808 let wh = ClusterIpDefaultingWebhook::new("10.97.0.0/16", source)
809 .with_grant_ttl(std::time::Duration::ZERO);
810 let req = svc_request(json!({
811 "kind": "Service", "apiVersion": "v1",
812 "metadata": {"name": "a"}, "spec": {"ports": [{"port": 80}]}
813 }));
814 assert_eq!(vip_of(wh.review(&req).await.unwrap()), "10.97.0.1");
815 assert_eq!(vip_of(wh.review(&req).await.unwrap()), "10.97.0.1");
816 }
817
818 #[test]
819 fn u32_ip_roundtrip() {
820 assert_eq!(u32_to_ip(ip_to_u32("10.96.0.1").unwrap()), "10.96.0.1");
821 assert_eq!(
822 u32_to_ip(ip_to_u32("255.255.255.255").unwrap()),
823 "255.255.255.255"
824 );
825 assert_eq!(u32_to_ip(0), "0.0.0.0");
826 }
827}