engenho_controllers/node_port.rs
1//! NODEPORT ALLOCATION.
2//!
3//! ★ WHY IT WAS MISSING AND WHY THAT SHOWS. `Service.spec.type: NodePort`
4//! was accepted, stored, and then did nothing: no port was assigned, so
5//! `kubectl get svc` showed an empty `nodePort` column and nothing outside
6//! the cluster could reach the service. The Service reported no error —
7//! the field simply stayed absent — which is the worst shape a gap can
8//! take, because the operator's YAML was correct and the cluster agreed
9//! with it right up until they tried to connect.
10//!
11//! ★ THE RANGE IS A CONTRACT WITH THE NODE, NOT A PREFERENCE. 30000–32767
12//! is upstream's default `--service-node-port-range`, and it is chosen to
13//! sit above the ephemeral-port floor so an allocated `NodePort` cannot
14//! collide with an outbound connection's source port. Allocating outside
15//! it produces a service that works until the kernel happens to pick the
16//! same port for something else — an intermittent failure with no
17//! discoverable cause.
18//!
19//! ★ AN EXPLICIT REQUEST IS HONOURED OR REFUSED, NEVER SILENTLY MOVED. A
20//! user who wrote `nodePort: 30080` has almost certainly written it into a
21//! firewall rule or a load-balancer config too. Quietly assigning 30081
22//! instead would produce a service that is up, reachable on a port nobody
23//! configured, and unreachable on the one everybody did.
24//!
25//! ★ THE ALLOCATOR IS RESEEDED FROM LIVE SERVICES, never persisted
26//! separately. The Services ARE the ledger — the same decision
27//! `cluster_ip` makes, and for the same reason: a second copy of the
28//! allocation state is a second thing that can be wrong, and on restart
29//! the wrong one wins silently.
30
31use std::collections::BTreeSet;
32
33use thiserror::Error;
34
35/// Upstream's default `--service-node-port-range`.
36pub const DEFAULT_RANGE: (u16, u16) = (30000, 32767);
37
38/// Allocation failures.
39#[derive(Debug, Clone, PartialEq, Eq, Error)]
40pub enum NodePortError {
41 /// Every port in the range is taken.
42 #[error("no NodePort available in {low}-{high}: the range is exhausted")]
43 Exhausted { low: u16, high: u16 },
44 /// The requested port lies outside the configured range.
45 #[error("requested nodePort {port} is outside the range {low}-{high}")]
46 OutOfRange { port: u16, low: u16, high: u16 },
47 /// The requested port is already held by another Service.
48 #[error("requested nodePort {port} is already allocated")]
49 AlreadyAllocated { port: u16 },
50}
51
52/// Collision-free `NodePort` allocation over a fixed range.
53#[derive(Debug, Clone)]
54pub struct NodePortAllocator {
55 low: u16,
56 high: u16,
57 in_use: BTreeSet<u16>,
58}
59
60impl Default for NodePortAllocator {
61 fn default() -> Self {
62 Self::new(DEFAULT_RANGE.0, DEFAULT_RANGE.1)
63 }
64}
65
66impl NodePortAllocator {
67 /// A new allocator over `[low, high]`, inclusive at both ends.
68 #[must_use]
69 pub fn new(low: u16, high: u16) -> Self {
70 Self {
71 low,
72 high,
73 in_use: BTreeSet::new(),
74 }
75 }
76
77 /// Mark a port as held.
78 ///
79 /// Used to reseed from live Services at startup. Returns whether the
80 /// port was newly claimed — a caller reseeding can detect a DUPLICATE
81 /// in the live set, which means two Services already believe they own
82 /// the same port and no allocator decision can fix it.
83 pub fn claim(&mut self, port: u16) -> bool {
84 self.in_use.insert(port)
85 }
86
87 /// Release a port back to the range.
88 pub fn release(&mut self, port: u16) {
89 self.in_use.remove(&port);
90 }
91
92 /// Is this port currently held?
93 #[must_use]
94 pub fn is_allocated(&self, port: u16) -> bool {
95 self.in_use.contains(&port)
96 }
97
98 /// Honour an explicitly requested port, or say precisely why not.
99 pub fn allocate_specific(&mut self, port: u16) -> Result<u16, NodePortError> {
100 if port < self.low || port > self.high {
101 return Err(NodePortError::OutOfRange {
102 port,
103 low: self.low,
104 high: self.high,
105 });
106 }
107 if !self.in_use.insert(port) {
108 return Err(NodePortError::AlreadyAllocated { port });
109 }
110 Ok(port)
111 }
112
113 /// Allocate the lowest free port.
114 ///
115 /// Lowest-first rather than random: it makes the same sequence of
116 /// creates produce the same assignments, which is what lets a test
117 /// assert an allocation at all and what makes an operator's firewall
118 /// rules stable across a cluster rebuild.
119 pub fn allocate(&mut self) -> Result<u16, NodePortError> {
120 for port in self.low..=self.high {
121 if self.in_use.insert(port) {
122 return Ok(port);
123 }
124 }
125 Err(NodePortError::Exhausted {
126 low: self.low,
127 high: self.high,
128 })
129 }
130}
131
132/// Does this Service type get `NodePorts`?
133///
134/// `LoadBalancer` does too — upstream allocates a `NodePort` for it as the
135/// backing path, and omitting that would make a `LoadBalancer` Service
136/// unreachable on every cloud whose controller programs the balancer to
137/// forward at the node port.
138#[must_use]
139pub fn wants_node_ports(service_type: &str) -> bool {
140 matches!(service_type, "NodePort" | "LoadBalancer")
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 #[test]
148 fn the_default_range_is_upstreams() {
149 // Chosen to sit above the ephemeral-port floor so an allocated
150 // NodePort cannot collide with an outbound connection's source
151 // port. Allocating outside it yields intermittent, causeless
152 // failures.
153 assert_eq!(DEFAULT_RANGE, (30000, 32767));
154 let a = NodePortAllocator::default();
155 assert_eq!((a.low, a.high), (30000, 32767));
156 }
157
158 #[test]
159 fn allocation_is_collision_free_and_deterministic() {
160 // Anti-vacuity plus the stability property: the same sequence of
161 // creates must produce the same assignments, or an operator's
162 // firewall rules break on every cluster rebuild.
163 let mut a = NodePortAllocator::new(30000, 30002);
164 assert_eq!(a.allocate(), Ok(30000));
165 assert_eq!(a.allocate(), Ok(30001));
166 assert_eq!(a.allocate(), Ok(30002));
167 assert_eq!(
168 a.allocate(),
169 Err(NodePortError::Exhausted {
170 low: 30000,
171 high: 30002
172 })
173 );
174 }
175
176 #[test]
177 fn an_explicit_request_is_honoured_exactly_or_refused() {
178 // Quietly assigning a NEIGHBOURING port would produce a service
179 // that is up, reachable on a port nobody configured, and
180 // unreachable on the one written into every firewall rule.
181 let mut a = NodePortAllocator::default();
182 assert_eq!(a.allocate_specific(30080), Ok(30080));
183 assert_eq!(
184 a.allocate_specific(30080),
185 Err(NodePortError::AlreadyAllocated { port: 30080 })
186 );
187 // Never silently moved to 30081.
188 assert!(!a.is_allocated(30081));
189 }
190
191 #[test]
192 fn a_request_outside_the_range_is_refused_with_the_bounds() {
193 let mut a = NodePortAllocator::default();
194 assert_eq!(
195 a.allocate_specific(8080),
196 Err(NodePortError::OutOfRange {
197 port: 8080,
198 low: 30000,
199 high: 32767
200 })
201 );
202 assert_eq!(
203 a.allocate_specific(40000),
204 Err(NodePortError::OutOfRange {
205 port: 40000,
206 low: 30000,
207 high: 32767
208 })
209 );
210 }
211
212 #[test]
213 fn an_explicitly_taken_port_is_skipped_by_automatic_allocation() {
214 let mut a = NodePortAllocator::new(30000, 30002);
215 assert_eq!(a.allocate_specific(30000), Ok(30000));
216 assert_eq!(a.allocate(), Ok(30001), "must not hand out a held port");
217 }
218
219 #[test]
220 fn a_released_port_is_reusable() {
221 let mut a = NodePortAllocator::new(30000, 30000);
222 assert_eq!(a.allocate(), Ok(30000));
223 assert!(a.allocate().is_err());
224 a.release(30000);
225 assert_eq!(a.allocate(), Ok(30000));
226 }
227
228 #[test]
229 fn claim_reports_a_duplicate_in_the_live_set() {
230 // Reseeding from live Services is how the allocator survives a
231 // restart. A duplicate there means two Services ALREADY believe
232 // they own the same port — no allocator decision fixes that, and
233 // the caller must be able to see it rather than have it swallowed.
234 let mut a = NodePortAllocator::default();
235 assert!(a.claim(30080), "first claim is new");
236 assert!(!a.claim(30080), "second claim reports the collision");
237 }
238
239 #[test]
240 fn load_balancer_services_get_node_ports_too() {
241 // Upstream allocates one as the backing path; omitting it makes a
242 // LoadBalancer unreachable on every cloud whose controller
243 // programs the balancer to forward at the node port.
244 assert!(wants_node_ports("NodePort"));
245 assert!(wants_node_ports("LoadBalancer"));
246 assert!(!wants_node_ports("ClusterIP"));
247 assert!(!wants_node_ports("ExternalName"));
248 }
249
250 #[test]
251 fn a_single_port_range_is_usable_not_degenerate() {
252 // An off-by-one in the inclusive bound would make this range empty,
253 // and the failure would only appear on a cluster configured with a
254 // tiny range.
255 let mut a = NodePortAllocator::new(31000, 31000);
256 assert_eq!(a.allocate(), Ok(31000));
257 }
258}