utils.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. from dataclasses import dataclass
  2. import netaddr
  3. from django.utils.translation import gettext_lazy as _
  4. from .constants import *
  5. from .models import Prefix, VLAN
  6. __all__ = (
  7. 'AvailableIPSpace',
  8. 'add_available_vlans',
  9. 'add_requested_prefixes',
  10. 'annotate_ip_space',
  11. 'get_next_available_prefix',
  12. 'rebuild_prefixes',
  13. )
  14. @dataclass
  15. class AvailableIPSpace:
  16. """
  17. A representation of available IP space between two IP addresses/ranges.
  18. """
  19. size: int
  20. first_ip: str
  21. @property
  22. def title(self):
  23. if self.size == 1:
  24. return _('1 IP available')
  25. if self.size <= 65536:
  26. return _('{count} IPs available').format(count=self.size)
  27. return _('Many IPs available')
  28. def add_requested_prefixes(parent, prefix_list, show_available=True, show_assigned=True):
  29. """
  30. Return a list of requested prefixes using show_available, show_assigned filters. If available prefixes are
  31. requested, create fake Prefix objects for all unallocated space within a prefix.
  32. :param parent: Parent Prefix instance
  33. :param prefix_list: Child prefixes list
  34. :param show_available: Include available prefixes.
  35. :param show_assigned: Show assigned prefixes.
  36. """
  37. child_prefixes = []
  38. # Add available prefixes to the table if requested
  39. if prefix_list and show_available:
  40. # Find all unallocated space, add fake Prefix objects to child_prefixes.
  41. # IMPORTANT: These are unsaved Prefix instances (pk=None). If this is ever changed to use
  42. # saved Prefix instances with real pks, bulk delete will fail for mixed-type selections
  43. # due to single-model form validation. See: https://github.com/netbox-community/netbox/issues/21176
  44. available_prefixes = netaddr.IPSet(parent) ^ netaddr.IPSet([p.prefix for p in prefix_list])
  45. available_prefixes = [Prefix(prefix=p, status=None) for p in available_prefixes.iter_cidrs()]
  46. child_prefixes = child_prefixes + available_prefixes
  47. # Add assigned prefixes to the table if requested
  48. if prefix_list and show_assigned:
  49. child_prefixes = child_prefixes + list(prefix_list)
  50. # Sort child prefixes after additions
  51. child_prefixes.sort(key=lambda p: p.prefix)
  52. return child_prefixes
  53. def annotate_ip_space(prefix):
  54. # Compile child objects
  55. records = []
  56. records.extend([
  57. (iprange.start_address.ip, iprange) for iprange in prefix.get_child_ranges(mark_populated=True)
  58. ])
  59. records.extend([
  60. (ip.address.ip, ip) for ip in prefix.get_child_ips()
  61. ])
  62. records = sorted(records, key=lambda x: x[0])
  63. # Determine the first & last valid IP addresses in the prefix
  64. if prefix.family == 4 and prefix.mask_length < 31 and not prefix.is_pool:
  65. # Ignore the network and broadcast addresses for non-pool IPv4 prefixes larger than /31
  66. first_ip_in_prefix = netaddr.IPAddress(prefix.prefix.first + 1)
  67. last_ip_in_prefix = netaddr.IPAddress(prefix.prefix.last - 1)
  68. else:
  69. first_ip_in_prefix = netaddr.IPAddress(prefix.prefix.first)
  70. last_ip_in_prefix = netaddr.IPAddress(prefix.prefix.last)
  71. if not records:
  72. return [
  73. AvailableIPSpace(
  74. size=int(last_ip_in_prefix - first_ip_in_prefix + 1),
  75. first_ip=f'{first_ip_in_prefix}/{prefix.mask_length}'
  76. )
  77. ]
  78. output = []
  79. prev_ip = None
  80. # Account for any available IPs before the first real IP
  81. if records[0][0] > first_ip_in_prefix:
  82. output.append(AvailableIPSpace(
  83. size=int(records[0][0] - first_ip_in_prefix),
  84. first_ip=f'{first_ip_in_prefix}/{prefix.mask_length}'
  85. ))
  86. # Add IP ranges & addresses, annotating available space in between records
  87. for record in records:
  88. if prev_ip:
  89. # Annotate available space
  90. if (diff := int(record[0]) - int(prev_ip)) > 1:
  91. first_skipped = f'{prev_ip + 1}/{prefix.mask_length}'
  92. output.append(AvailableIPSpace(
  93. size=diff - 1,
  94. first_ip=first_skipped
  95. ))
  96. output.append(record[1])
  97. # Update the previous IP address
  98. if hasattr(record[1], 'end_address'):
  99. prev_ip = record[1].end_address.ip
  100. else:
  101. prev_ip = record[0]
  102. # Include any remaining available IPs
  103. if prev_ip < last_ip_in_prefix:
  104. output.append(AvailableIPSpace(
  105. size=int(last_ip_in_prefix - prev_ip),
  106. first_ip=f'{prev_ip + 1}/{prefix.mask_length}'
  107. ))
  108. return output
  109. def available_vlans_from_range(vlans, vlan_group, vid_range):
  110. """
  111. Create fake records for all gaps between used VLANs
  112. """
  113. min_vid = int(vid_range.lower) if vid_range else VLAN_VID_MIN
  114. max_vid = int(vid_range.upper) if vid_range else VLAN_VID_MAX
  115. if not vlans:
  116. return [{
  117. 'vid': min_vid,
  118. 'vlan_group': vlan_group,
  119. 'available': max_vid - min_vid
  120. }]
  121. prev_vid = min_vid - 1
  122. new_vlans = []
  123. for vlan in vlans:
  124. # Ignore VIDs outside the range
  125. if not min_vid <= vlan.vid < max_vid:
  126. continue
  127. # Annotate any available VIDs between the previous (or minimum) VID
  128. # and the current VID
  129. if vlan.vid - prev_vid > 1:
  130. new_vlans.append({
  131. 'vid': prev_vid + 1,
  132. 'vlan_group': vlan_group,
  133. 'available': vlan.vid - prev_vid - 1,
  134. })
  135. prev_vid = vlan.vid
  136. # Annotate any remaining available VLANs
  137. if prev_vid < max_vid - 1:
  138. new_vlans.append({
  139. 'vid': prev_vid + 1,
  140. 'vlan_group': vlan_group,
  141. 'available': max_vid - prev_vid - 1,
  142. })
  143. return new_vlans
  144. def add_available_vlans(vlans, vlan_group):
  145. """
  146. Create fake records for all gaps between used VLANs
  147. """
  148. new_vlans = []
  149. for vid_range in vlan_group.vid_ranges:
  150. new_vlans.extend(available_vlans_from_range(vlans, vlan_group, vid_range))
  151. vlans = list(vlans) + new_vlans
  152. vlans.sort(key=lambda v: v.vid if type(v) is VLAN else v['vid'])
  153. return vlans
  154. def rebuild_prefixes(vrf):
  155. """
  156. Rebuild the prefix hierarchy for all prefixes in the specified VRF (or global table).
  157. """
  158. def contains(parent, child):
  159. return child in parent and child != parent
  160. def push_to_stack(prefix):
  161. # Increment child count on parent nodes
  162. for n in stack:
  163. n['children'] += 1
  164. stack.append({
  165. 'pk': [prefix['pk']],
  166. 'prefix': prefix['prefix'],
  167. 'children': 0,
  168. })
  169. stack = []
  170. update_queue = []
  171. prefixes = Prefix.objects.filter(vrf=vrf).values('pk', 'prefix')
  172. # Iterate through all Prefixes in the VRF, growing and shrinking the stack as we go
  173. for i, p in enumerate(prefixes):
  174. # Grow the stack if this is a child of the most recent prefix
  175. if not stack or contains(stack[-1]['prefix'], p['prefix']):
  176. push_to_stack(p)
  177. # Handle duplicate prefixes
  178. elif stack[-1]['prefix'] == p['prefix']:
  179. stack[-1]['pk'].append(p['pk'])
  180. # If this is a sibling or parent of the most recent prefix, pop nodes from the
  181. # stack until we reach a parent prefix (or the root)
  182. else:
  183. while stack and not contains(stack[-1]['prefix'], p['prefix']):
  184. node = stack.pop()
  185. for pk in node['pk']:
  186. update_queue.append(
  187. Prefix(pk=pk, _depth=len(stack), _children=node['children'])
  188. )
  189. push_to_stack(p)
  190. # Flush the update queue once it reaches 100 Prefixes
  191. if len(update_queue) >= 100:
  192. Prefix.objects.bulk_update(update_queue, ['_depth', '_children'])
  193. update_queue = []
  194. # Clear out any prefixes remaining in the stack
  195. while stack:
  196. node = stack.pop()
  197. for pk in node['pk']:
  198. update_queue.append(
  199. Prefix(pk=pk, _depth=len(stack), _children=node['children'])
  200. )
  201. # Final flush of any remaining Prefixes
  202. Prefix.objects.bulk_update(update_queue, ['_depth', '_children'])
  203. def get_next_available_prefix(ipset, prefix_size):
  204. """
  205. Given a prefix length, allocate the next available prefix from an IPSet.
  206. """
  207. for available_prefix in ipset.iter_cidrs():
  208. if prefix_size >= available_prefix.prefixlen:
  209. allocated_prefix = f"{available_prefix.network}/{prefix_size}"
  210. ipset.remove(allocated_prefix)
  211. return allocated_prefix
  212. return None