| 188 | } |
| 189 | |
| 190 | pub fn allocate(&mut self, sandbox_id: &str) -> Result<SubnetAllocation, String> { |
| 191 | let pool_size = 1u32 << (32 - self.prefix_len); |
| 192 | let max_subnets = pool_size / 4; |
| 193 | |
| 194 | if u32::try_from(self.allocated.len()).unwrap_or(u32::MAX) >= max_subnets { |
| 195 | return Err("subnet pool exhausted".to_string()); |
| 196 | } |
| 197 | |
| 198 | while self |
| 199 | .allocated |
| 200 | .values() |
| 201 | .any(|a| a.offset == self.next_offset) |
| 202 | { |
| 203 | self.next_offset = (self.next_offset + 1) % max_subnets; |
| 204 | } |
| 205 | |
| 206 | let base_u32 = u32::from(self.base); |
| 207 | let subnet_base = base_u32 + (self.next_offset * 4); |
| 208 | let host_ip = Ipv4Addr::from(subnet_base + 1); |
| 209 | let guest_ip = Ipv4Addr::from(subnet_base + 2); |
| 210 | |
| 211 | let allocation = SubnetAllocation { |
| 212 | host_ip, |
| 213 | guest_ip, |
| 214 | prefix_len: 30, |
| 215 | offset: self.next_offset, |
| 216 | }; |
| 217 | |
| 218 | self.allocated.insert(sandbox_id.to_string(), allocation); |
| 219 | self.next_offset = (self.next_offset + 1) % max_subnets; |
| 220 | |
| 221 | let alloc = &self.allocated[sandbox_id]; |
| 222 | Ok(SubnetAllocation { |
| 223 | host_ip: alloc.host_ip, |
| 224 | guest_ip: alloc.guest_ip, |
| 225 | prefix_len: alloc.prefix_len, |
| 226 | offset: alloc.offset, |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | pub fn release(&mut self, sandbox_id: &str) { |
| 231 | self.allocated.remove(sandbox_id); |