Skip to content

Commit b892409

Browse files
committed
refactor tracking of used/unused IP addrs
- make ip_addr_pool just a list of addressses - add "hostnames" dict of {hostname:address_in_use} to track used addresses
1 parent 128a789 commit b892409

File tree

1 file changed

+32
-10
lines changed

1 file changed

+32
-10
lines changed

ip_pool/ip_pool.py

+32-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import ipaddress
22
import json
3-
4-
from ipaddress import IPv4Interface, IPv4Network, IPv4Address
3+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network
54
from typing import Dict
65

76

@@ -14,12 +13,16 @@ def __init__(self, ipaddr_db_json_path: str):
1413
self.json_path = ipaddr_db_json_path
1514
self._ip_version = 4
1615
self._prefix_len = 0
17-
self._ipaddr_pool = {}
16+
self._ipaddr_pool = []
17+
self._hostnames = {}
1818
self._load_from_json(ipaddr_db_json_path)
1919

2020
@property
2121
def addresses(self):
22-
addresses = list(self._ipaddr_pool.keys())
22+
addresses = list(self._ipaddr_pool)
23+
addresses.extend(self._hostnames.keys())
24+
addresses.sort()
25+
2326
return addresses
2427

2528
def is_initialized(self):
@@ -32,25 +35,44 @@ def initialize(self, ipv4_cidr_address: str):
3235

3336
prefix_len, address_list = self._generate_addresses(ipv4_cidr_address)
3437

35-
for addr in address_list:
36-
self._ipaddr_pool[addr] = None
37-
38+
self._ipaddr_pool = address_list
3839
self._prefix_len = prefix_len
3940
self._save()
4041

4142
def _to_dict(self):
4243
_dict = {
4344
"ip_version": self._ip_version,
4445
"network_prefix_len": self._prefix_len,
45-
"addresses": {str(k): v for k, v in self._ipaddr_pool.items()}
46+
"unused_addresses": [str(k) for k in self._ipaddr_pool],
47+
"hostnames": {k: str(v) for k, v in self._hostnames.items()},
4648
}
49+
4750
return _dict
4851

4952
def _initialize_from_dict(self, ip_pool_dict: Dict):
5053
self._ip_version = ip_pool_dict["ip_version"]
5154
self._prefix_len = ip_pool_dict["network_prefix_len"]
52-
addrs = ip_pool_dict["addresses"]
53-
self._ipaddr_pool = {IPv4Address(k): v for k, v in addrs.items()}
55+
unused_addrs = ip_pool_dict["unused_addresses"]
56+
hostnames = ip_pool_dict["hostnames"]
57+
58+
pool = []
59+
# hostnames = {}
60+
61+
for addr_str in unused_addrs:
62+
addr = IPv4Address(addr_str)
63+
pool.append(addr)
64+
65+
for hostname, addr_str in hostnames.items():
66+
addr = IPv4Address(addr_str)
67+
if addr in hostnames.values():
68+
dupes = [hostname, hostnames[addr]]
69+
raise IPAddressPoolException(
70+
f"Address [{addr_str}] used more than once: {dupes} "
71+
)
72+
hostnames[hostname] = addr
73+
74+
self._hostnames = hostnames
75+
self._ipaddr_pool = pool
5476

5577
def _save(self):
5678
save_dict = self._to_dict()

0 commit comments

Comments
 (0)