Skip to content

Commit

Permalink
[web] use namedtuple for subnet usage reporting
Browse files Browse the repository at this point in the history
This is cleaner than just dynamically setting attributes on `Subnet`.
  • Loading branch information
lukasjuhrich committed Aug 17, 2023
1 parent 30b99e5 commit 310c36a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 16 deletions.
36 changes: 24 additions & 12 deletions pycroft/lib/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,26 @@ def get_subnets_for_room(room: Room) -> list[Subnet]:
if s.address.version == 4]


def get_subnets_with_usage() -> list[Subnet]:

def calculate_max_ips(subnet: Subnet) -> int:
max_ips = subnet.address.numhosts - 2
if subnet.reserved_addresses_bottom:
max_ips -= subnet.reserved_addresses_bottom
if subnet.reserved_addresses_top:
max_ips -= subnet.reserved_addresses_top
return max_ips


class SubnetUsage(t.NamedTuple):
max_ips: int
used_ips: int

@property
def free_ips(self) -> int:
return self.max_ips - self.used_ips


def get_subnets_with_usage() -> list[tuple[Subnet, SubnetUsage]]:
is_unreserved_ip = and_(
IP.address >= cast(func.host(func.network(
Subnet.address) + Subnet.reserved_addresses_bottom + 1), IPAddress),
Expand All @@ -90,17 +109,10 @@ def get_subnets_with_usage() -> list[Subnet]:
.group_by(Subnet.id)
).all()

subnets = []
for subnet, used_ips in subnets_with_used_ips:
max_ips = subnet.address.numhosts - 2
if subnet.reserved_addresses_bottom:
max_ips -= subnet.reserved_addresses_bottom
if subnet.reserved_addresses_top:
max_ips -= subnet.reserved_addresses_top
subnet.used_ips = used_ips
subnet.max_ips = max_ips
subnets.append(subnet)
return subnets
return [
(subnet, SubnetUsage(max_ips=calculate_max_ips(subnet), used_ips=used_ips))
for subnet, used_ips in subnets_with_used_ips
]


def ptr_name(
Expand Down
2 changes: 1 addition & 1 deletion stubs/ipaddr.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ class _BaseNet(_IPAddrBase):
def with_hostmask(self):
...
@property
def numhosts(self):
def numhosts(self) -> int:
...
@property
def version(self) -> None:
Expand Down
6 changes: 3 additions & 3 deletions web/blueprints/infrastructure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ def subnets_json() -> ResponseValue:
address=str(subnet.address),
gateway=str(subnet.gateway),
reserved=format_reserved_addresses(subnet),
free_ips=f"{subnet.max_ips - subnet.used_ips}",
free_ips_formatted=f"{subnet.max_ips - subnet.used_ips} (von {subnet.max_ips})",
free_ips=str(usage.free_ips),
free_ips_formatted=f"{usage.free_ips} (von {usage.max_ips})",
)
for subnet in get_subnets_with_usage()
for subnet, usage in get_subnets_with_usage()
]
).model_dump()

Expand Down

0 comments on commit 310c36a

Please sign in to comment.