ip.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. import netaddr
  2. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.contrib.postgres.indexes import GistIndex
  5. from django.core.exceptions import ValidationError
  6. from django.db import models
  7. from django.db.models import F
  8. from django.db.models.functions import Cast
  9. from django.utils.functional import cached_property
  10. from django.utils.translation import gettext_lazy as _
  11. from dcim.models.mixins import CachedScopeMixin
  12. from ipam.choices import *
  13. from ipam.constants import *
  14. from ipam.fields import IPAddressField, IPNetworkField
  15. from ipam.lookups import Host
  16. from ipam.managers import IPAddressManager
  17. from ipam.querysets import IPRangeQuerySet, PrefixQuerySet
  18. from ipam.validators import DNSValidator
  19. from netbox.config import get_config
  20. from netbox.models import OrganizationalModel, PrimaryModel
  21. from netbox.models.features import ContactsMixin
  22. __all__ = (
  23. 'RIR',
  24. 'Aggregate',
  25. 'IPAddress',
  26. 'IPRange',
  27. 'Prefix',
  28. 'Role',
  29. )
  30. class GetAvailablePrefixesMixin:
  31. def get_available_prefixes(self):
  32. """
  33. Return all available prefixes within this Aggregate or Prefix as an IPSet.
  34. """
  35. params = {
  36. 'prefix__net_contained': str(self.prefix)
  37. }
  38. if hasattr(self, 'vrf'):
  39. params['vrf'] = self.vrf
  40. child_prefixes = Prefix.objects.filter(**params).values_list('prefix', flat=True)
  41. return netaddr.IPSet(self.prefix) - netaddr.IPSet(child_prefixes)
  42. def get_first_available_prefix(self):
  43. """
  44. Return the first available child prefix within the prefix (or None).
  45. """
  46. available_prefixes = self.get_available_prefixes()
  47. if not available_prefixes:
  48. return None
  49. return available_prefixes.iter_cidrs()[0]
  50. class RIR(OrganizationalModel):
  51. """
  52. A Regional Internet Registry (RIR) is responsible for the allocation of a large portion of the global IP address
  53. space. This can be an organization like ARIN or RIPE, or a governing standard such as RFC 1918.
  54. """
  55. is_private = models.BooleanField(
  56. default=False,
  57. verbose_name=_('private'),
  58. help_text=_('IP space managed by this RIR is considered private')
  59. )
  60. class Meta:
  61. ordering = ('name',)
  62. verbose_name = _('RIR')
  63. verbose_name_plural = _('RIRs')
  64. class Aggregate(ContactsMixin, GetAvailablePrefixesMixin, PrimaryModel):
  65. """
  66. An aggregate exists at the root level of the IP address space hierarchy in NetBox. Aggregates are used to organize
  67. the hierarchy and track the overall utilization of available address space. Each Aggregate is assigned to a RIR.
  68. """
  69. prefix = IPNetworkField(
  70. help_text=_("IPv4 or IPv6 network")
  71. )
  72. rir = models.ForeignKey(
  73. to='ipam.RIR',
  74. on_delete=models.PROTECT,
  75. related_name='aggregates',
  76. verbose_name=_('RIR'),
  77. help_text=_("Regional Internet Registry responsible for this IP space")
  78. )
  79. tenant = models.ForeignKey(
  80. to='tenancy.Tenant',
  81. on_delete=models.PROTECT,
  82. related_name='aggregates',
  83. blank=True,
  84. null=True
  85. )
  86. date_added = models.DateField(
  87. verbose_name=_('date added'),
  88. blank=True,
  89. null=True
  90. )
  91. clone_fields = (
  92. 'rir', 'tenant', 'date_added', 'description',
  93. )
  94. prerequisite_models = (
  95. 'ipam.RIR',
  96. )
  97. class Meta:
  98. ordering = ('prefix', 'pk') # prefix may be non-unique
  99. indexes = (
  100. models.Index(fields=('prefix', 'id')), # Default ordering
  101. )
  102. verbose_name = _('aggregate')
  103. verbose_name_plural = _('aggregates')
  104. def __str__(self):
  105. return str(self.prefix)
  106. def clean(self):
  107. super().clean()
  108. if self.prefix:
  109. # /0 masks are not acceptable
  110. if self.prefix.prefixlen == 0:
  111. raise ValidationError({
  112. 'prefix': _("Cannot create aggregate with /0 mask.")
  113. })
  114. # Ensure that the aggregate being added is not covered by an existing aggregate
  115. covering_aggregates = Aggregate.objects.filter(
  116. prefix__net_contains_or_equals=str(self.prefix)
  117. )
  118. if self.pk:
  119. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  120. if covering_aggregates:
  121. raise ValidationError({
  122. 'prefix': _(
  123. "Aggregates cannot overlap. {prefix} is already covered by an existing aggregate ({aggregate})."
  124. ).format(
  125. prefix=self.prefix,
  126. aggregate=covering_aggregates[0]
  127. )
  128. })
  129. # Ensure that the aggregate being added does not cover an existing aggregate
  130. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  131. if self.pk:
  132. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  133. if covered_aggregates:
  134. raise ValidationError({
  135. 'prefix': _(
  136. "Prefixes cannot overlap aggregates. {prefix} covers an existing aggregate ({aggregate})."
  137. ).format(
  138. prefix=self.prefix,
  139. aggregate=covered_aggregates[0]
  140. )
  141. })
  142. @property
  143. def family(self):
  144. if not self.prefix:
  145. return None
  146. if isinstance(self.prefix, str):
  147. return netaddr.IPNetwork(self.prefix).version
  148. return self.prefix.version
  149. @property
  150. def ipv6_full(self):
  151. if self.prefix and self.prefix.version == 6:
  152. return netaddr.IPAddress(self.prefix).format(netaddr.ipv6_full)
  153. return None
  154. def get_child_prefixes(self):
  155. """
  156. Return all Prefixes within this Aggregate
  157. """
  158. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  159. def get_utilization(self):
  160. """
  161. Determine the prefix utilization of the aggregate and return it as a percentage.
  162. """
  163. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  164. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  165. utilization = float(child_prefixes.size) / self.prefix.size * 100
  166. return min(utilization, 100)
  167. class Role(OrganizationalModel):
  168. """
  169. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  170. "Management."
  171. """
  172. weight = models.PositiveSmallIntegerField(
  173. verbose_name=_('weight'),
  174. default=1000
  175. )
  176. class Meta:
  177. ordering = ('weight', 'name')
  178. indexes = (
  179. models.Index(fields=('weight', 'name')), # Default ordering
  180. )
  181. verbose_name = _('role')
  182. verbose_name_plural = _('roles')
  183. def __str__(self):
  184. return self.name
  185. class Prefix(ContactsMixin, GetAvailablePrefixesMixin, CachedScopeMixin, PrimaryModel):
  186. """
  187. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be scoped to certain
  188. areas and/or assigned to VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role.
  189. A Prefix can also be assigned to a VLAN where appropriate.
  190. """
  191. prefix = IPNetworkField(
  192. verbose_name=_('prefix'),
  193. help_text=_('IPv4 or IPv6 network with mask')
  194. )
  195. vrf = models.ForeignKey(
  196. to='ipam.VRF',
  197. on_delete=models.PROTECT,
  198. related_name='prefixes',
  199. blank=True,
  200. null=True,
  201. verbose_name=_('VRF')
  202. )
  203. tenant = models.ForeignKey(
  204. to='tenancy.Tenant',
  205. on_delete=models.PROTECT,
  206. related_name='prefixes',
  207. blank=True,
  208. null=True
  209. )
  210. vlan = models.ForeignKey(
  211. to='ipam.VLAN',
  212. on_delete=models.PROTECT,
  213. related_name='prefixes',
  214. blank=True,
  215. null=True
  216. )
  217. status = models.CharField(
  218. max_length=50,
  219. choices=PrefixStatusChoices,
  220. default=PrefixStatusChoices.STATUS_ACTIVE,
  221. verbose_name=_('status'),
  222. help_text=_('Operational status of this prefix')
  223. )
  224. role = models.ForeignKey(
  225. to='ipam.Role',
  226. on_delete=models.SET_NULL,
  227. related_name='prefixes',
  228. blank=True,
  229. null=True,
  230. help_text=_('The primary function of this prefix')
  231. )
  232. is_pool = models.BooleanField(
  233. verbose_name=_('is a pool'),
  234. default=False,
  235. help_text=_('All IP addresses within this prefix are considered usable')
  236. )
  237. mark_utilized = models.BooleanField(
  238. verbose_name=_('mark utilized'),
  239. default=False,
  240. help_text=_("Treat as fully utilized")
  241. )
  242. # Cached depth & child counts
  243. _depth = models.PositiveSmallIntegerField(
  244. default=0,
  245. editable=False
  246. )
  247. _children = models.PositiveBigIntegerField(
  248. default=0,
  249. editable=False
  250. )
  251. objects = PrefixQuerySet.as_manager()
  252. clone_fields = (
  253. 'scope', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'description',
  254. )
  255. class Meta:
  256. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  257. verbose_name = _('prefix')
  258. verbose_name_plural = _('prefixes')
  259. indexes = (
  260. models.Index(fields=('scope_type', 'scope_id')),
  261. GistIndex(fields=['prefix'], name='ipam_prefix_gist_idx', opclasses=['inet_ops']),
  262. )
  263. def __init__(self, *args, **kwargs):
  264. super().__init__(*args, **kwargs)
  265. # Cache the original prefix and VRF so we can check if they have changed on post_save
  266. self._prefix = self.__dict__.get('prefix')
  267. self._vrf_id = self.__dict__.get('vrf_id')
  268. def __str__(self):
  269. return str(self.prefix)
  270. def clean(self):
  271. super().clean()
  272. if self.prefix:
  273. # /0 masks are not acceptable
  274. if self.prefix.prefixlen == 0:
  275. raise ValidationError({
  276. 'prefix': _("Cannot create prefix with /0 mask.")
  277. })
  278. # Enforce unique IP space (if applicable)
  279. if (self.vrf is None and get_config().ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  280. duplicate_prefixes = self.get_duplicates()
  281. if duplicate_prefixes:
  282. table = _("VRF {vrf}").format(vrf=self.vrf) if self.vrf else _("global table")
  283. raise ValidationError({
  284. 'prefix': _("Duplicate prefix found in {table}: {prefix}").format(
  285. table=table,
  286. prefix=duplicate_prefixes.first(),
  287. )
  288. })
  289. def save(self, *args, **kwargs):
  290. if isinstance(self.prefix, netaddr.IPNetwork):
  291. # Clear host bits from prefix
  292. self.prefix = self.prefix.cidr
  293. # Cache objects associated with the terminating object (for filtering)
  294. self.cache_related_objects()
  295. super().save(*args, **kwargs)
  296. @property
  297. def family(self):
  298. if not self.prefix:
  299. return None
  300. if isinstance(self.prefix, str):
  301. return netaddr.IPNetwork(self.prefix).version
  302. return self.prefix.version
  303. @property
  304. def mask_length(self):
  305. if not self.prefix:
  306. return None
  307. if isinstance(self.prefix, str):
  308. return netaddr.IPNetwork(self.prefix).prefixlen
  309. return self.prefix.prefixlen
  310. @property
  311. def ipv6_full(self):
  312. if self.prefix and self.prefix.version == 6:
  313. return netaddr.IPAddress(self.prefix).format(netaddr.ipv6_full)
  314. return None
  315. @property
  316. def depth(self):
  317. return self._depth
  318. @property
  319. def children(self):
  320. return self._children
  321. def _set_prefix_length(self, value):
  322. """
  323. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  324. e.g. for bulk editing.
  325. """
  326. if self.prefix is not None:
  327. self.prefix.prefixlen = value
  328. prefix_length = property(fset=_set_prefix_length)
  329. def get_status_color(self):
  330. return PrefixStatusChoices.colors.get(self.status)
  331. @cached_property
  332. def aggregate(self):
  333. """
  334. Return the containing Aggregate for this Prefix, if any.
  335. """
  336. try:
  337. return Aggregate.objects.get(prefix__net_contains_or_equals=str(self.prefix))
  338. except Aggregate.DoesNotExist:
  339. return None
  340. def get_parents(self, include_self=False):
  341. """
  342. Return all containing Prefixes in the hierarchy.
  343. """
  344. lookup = 'net_contains_or_equals' if include_self else 'net_contains'
  345. return Prefix.objects.filter(**{
  346. 'vrf_id': self.vrf_id,
  347. f'prefix__{lookup}': self.prefix
  348. })
  349. def get_children(self, include_self=False):
  350. """
  351. Return all covered Prefixes in the hierarchy.
  352. """
  353. lookup = 'net_contained_or_equal' if include_self else 'net_contained'
  354. return Prefix.objects.filter(**{
  355. 'vrf_id': self.vrf_id,
  356. f'prefix__{lookup}': self.prefix
  357. })
  358. def get_duplicates(self):
  359. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  360. def get_child_prefixes(self):
  361. """
  362. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  363. Prefixes belonging to any VRF.
  364. """
  365. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  366. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  367. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  368. @property
  369. def usable_ip_bounds(self):
  370. """
  371. Return the first and last IPs considered usable for available-IP calculations.
  372. Pools and IPv4 /31-/32 / IPv6 /127-/128 are fully usable; otherwise IPv4 excludes
  373. network and broadcast, IPv6 excludes the subnet-router anycast address.
  374. """
  375. network = netaddr.IPNetwork(self.prefix)
  376. family = network.version
  377. first = network.first
  378. last = network.last
  379. mask_length = network.prefixlen
  380. if (
  381. self.is_pool
  382. or (family == 4 and mask_length >= 31)
  383. or (family == 6 and mask_length >= 127)
  384. ):
  385. return (
  386. netaddr.IPAddress(first, version=family),
  387. netaddr.IPAddress(last, version=family),
  388. )
  389. if family == 4:
  390. return (
  391. netaddr.IPAddress(first + 1, version=family),
  392. netaddr.IPAddress(last - 1, version=family),
  393. )
  394. return (
  395. netaddr.IPAddress(first + 1, version=family),
  396. netaddr.IPAddress(last, version=family),
  397. )
  398. @property
  399. def usable_size(self):
  400. """
  401. The number of usable host addresses within the prefix (excludes reserved addresses).
  402. """
  403. first_ip, last_ip = self.usable_ip_bounds
  404. return int(last_ip) - int(first_ip) + 1
  405. def get_child_ranges(self, **kwargs):
  406. """
  407. Return all IPRanges within this Prefix and VRF.
  408. """
  409. # A host BETWEEN over the prefix span uses the ipam_iprange_*_host btree indexes.
  410. prefix = netaddr.IPNetwork(self.prefix)
  411. bounds = (
  412. netaddr.IPAddress(prefix.first, version=prefix.version),
  413. netaddr.IPAddress(prefix.last, version=prefix.version),
  414. )
  415. return IPRange.objects.filter(
  416. vrf=self.vrf,
  417. start_address__host_between=bounds,
  418. end_address__host_between=bounds,
  419. **kwargs
  420. )
  421. def get_child_ips(self):
  422. """
  423. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  424. child IPAddresses belonging to any VRF.
  425. """
  426. # A host BETWEEN over the prefix span is index-sargable without the <<= containment recheck.
  427. prefix = netaddr.IPNetwork(self.prefix)
  428. bounds = (
  429. netaddr.IPAddress(prefix.first, version=prefix.version),
  430. netaddr.IPAddress(prefix.last, version=prefix.version),
  431. )
  432. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  433. return IPAddress.objects.filter(address__host_between=bounds)
  434. return IPAddress.objects.filter(address__host_between=bounds, vrf=self.vrf)
  435. def get_available_ips(self):
  436. """
  437. Return all available IPs within this prefix as an IPSet.
  438. """
  439. return netaddr.IPSet(
  440. cidr
  441. for start, end in self._available_intervals()
  442. for cidr in netaddr.iprange_to_cidrs(start, end)
  443. )
  444. def iter_available_ips(self):
  445. """
  446. Yield the available IPs within this prefix as netaddr.IPAddress objects, in
  447. ascending order. Unlike get_available_ips(), consumption is lazy: stopping
  448. early stops reading from the database.
  449. """
  450. for start, end in self._available_intervals():
  451. yield from netaddr.iter_iprange(start, end)
  452. def get_available_ip_count(self):
  453. """
  454. Return the number of available IPs within the prefix.
  455. """
  456. first_ip, last_ip = self.usable_ip_bounds
  457. usable_size = int(last_ip) - int(first_ip) + 1
  458. populated_intervals = self.get_child_ranges(mark_populated=True).get_intervals(first_ip, last_ip)
  459. populated_count = sum(int(end) - int(start) + 1 for start, end in populated_intervals)
  460. # Populated ranges already cover the usable span; skip the child-IP count entirely.
  461. if populated_count >= usable_size:
  462. return 0
  463. child_ip_count = (
  464. self.get_child_ips()
  465. .filter(address__host_between=(first_ip, last_ip))
  466. .count_distinct_hosts(exclude_intervals=populated_intervals)
  467. )
  468. return max(usable_size - populated_count - child_ip_count, 0)
  469. def get_ip_usage_summary(self):
  470. """
  471. Return the available IP count and utilization together as a dict, sharing a
  472. single distinct-host scan. Intended for detail views rendering both values;
  473. list views should call get_utilization() alone, which is cheaper per row.
  474. """
  475. # Marked-utilized and container utilization need no host scan; delegate.
  476. if self.mark_utilized or self.status == PrefixStatusChoices.STATUS_CONTAINER:
  477. return {
  478. 'available_ip_count': self.get_available_ip_count(),
  479. 'utilization': self.get_utilization(),
  480. }
  481. first_ip, last_ip = self.usable_ip_bounds
  482. usable_size = int(last_ip) - int(first_ip) + 1
  483. populated_intervals = self.get_child_ranges(mark_populated=True).get_intervals(first_ip, last_ip)
  484. utilized_intervals = self.get_child_ranges(mark_utilized=True).get_intervals()
  485. counts = self.get_child_ips().count_distinct_hosts_pair(
  486. bounds=(first_ip, last_ip),
  487. bounded_exclude=populated_intervals,
  488. total_exclude=utilized_intervals,
  489. )
  490. populated_count = sum(int(end) - int(start) + 1 for start, end in populated_intervals)
  491. utilized_range_count = sum(int(end) - int(start) + 1 for start, end in utilized_intervals)
  492. prefix_size = self._get_utilization_denominator()
  493. return {
  494. 'available_ip_count': max(usable_size - populated_count - counts['bounded'], 0),
  495. 'utilization': min(float(utilized_range_count + counts['total']) / prefix_size * 100, 100),
  496. }
  497. def get_first_available_ip(self):
  498. """
  499. Return the first available IP within the prefix (or None).
  500. """
  501. first_ip, last_ip = self.usable_ip_bounds
  502. populated_intervals = self.get_child_ranges(mark_populated=True).get_intervals(first_ip, last_ip)
  503. first_available_ip = self.get_child_ips().first_available_host(
  504. first_ip, last_ip, exclude_intervals=populated_intervals,
  505. )
  506. if first_available_ip is None:
  507. return None
  508. return f'{first_available_ip}/{self.prefix.prefixlen}'
  509. def get_utilization(self):
  510. """
  511. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  512. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  513. """
  514. if self.mark_utilized:
  515. return 100
  516. if self.status == PrefixStatusChoices.STATUS_CONTAINER:
  517. queryset = Prefix.objects.filter(
  518. prefix__net_contained=str(self.prefix),
  519. vrf=self.vrf
  520. )
  521. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  522. utilization = float(child_prefixes.size) / self.prefix.size * 100
  523. else:
  524. prefix_size = self._get_utilization_denominator()
  525. utilized_intervals = self.get_child_ranges(mark_utilized=True).get_intervals()
  526. utilized_range_count = sum(int(end) - int(start) + 1 for start, end in utilized_intervals)
  527. # Utilized ranges already saturate the prefix; skip the child-IP count.
  528. if utilized_range_count >= prefix_size:
  529. return 100
  530. child_ip_count = self.get_child_ips().count_distinct_hosts(
  531. exclude_intervals=utilized_intervals,
  532. )
  533. utilization = float(utilized_range_count + child_ip_count) / prefix_size * 100
  534. return min(utilization, 100)
  535. def _available_intervals(self):
  536. """
  537. Yield the available (start, end) host intervals within the prefix.
  538. """
  539. first_ip, last_ip = self.usable_ip_bounds
  540. populated_intervals = self.get_child_ranges(mark_populated=True).get_intervals(first_ip, last_ip)
  541. return self.get_child_ips().available_intervals(
  542. first_ip, last_ip, exclude_intervals=populated_intervals,
  543. )
  544. def _get_utilization_denominator(self):
  545. """
  546. The address count utilization is measured against (IPv4 non-pool prefixes
  547. exclude the network and broadcast addresses; IPv6 uses the full prefix size).
  548. """
  549. prefix_size = self.prefix.size
  550. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  551. return prefix_size - 2
  552. return prefix_size
  553. class IPRange(ContactsMixin, PrimaryModel):
  554. """
  555. A range of IP addresses, defined by start and end addresses.
  556. """
  557. start_address = IPAddressField(
  558. verbose_name=_('start address'),
  559. help_text=_('IPv4 or IPv6 address (with mask)')
  560. )
  561. end_address = IPAddressField(
  562. verbose_name=_('end address'),
  563. help_text=_('IPv4 or IPv6 address (with mask)')
  564. )
  565. size = models.PositiveIntegerField(
  566. verbose_name=_('size'),
  567. editable=False
  568. )
  569. vrf = models.ForeignKey(
  570. to='ipam.VRF',
  571. on_delete=models.PROTECT,
  572. related_name='ip_ranges',
  573. blank=True,
  574. null=True,
  575. verbose_name=_('VRF')
  576. )
  577. tenant = models.ForeignKey(
  578. to='tenancy.Tenant',
  579. on_delete=models.PROTECT,
  580. related_name='ip_ranges',
  581. blank=True,
  582. null=True
  583. )
  584. status = models.CharField(
  585. verbose_name=_('status'),
  586. max_length=50,
  587. choices=IPRangeStatusChoices,
  588. default=IPRangeStatusChoices.STATUS_ACTIVE,
  589. help_text=_('Operational status of this range')
  590. )
  591. role = models.ForeignKey(
  592. to='ipam.Role',
  593. on_delete=models.SET_NULL,
  594. related_name='ip_ranges',
  595. blank=True,
  596. null=True,
  597. help_text=_('The primary function of this range')
  598. )
  599. mark_populated = models.BooleanField(
  600. verbose_name=_('mark populated'),
  601. default=False,
  602. help_text=_("Prevent the creation of IP addresses within this range")
  603. )
  604. mark_utilized = models.BooleanField(
  605. verbose_name=_('mark utilized'),
  606. default=False,
  607. help_text=_("Report space as fully utilized")
  608. )
  609. objects = IPRangeQuerySet.as_manager()
  610. clone_fields = (
  611. 'vrf', 'tenant', 'status', 'role', 'description', 'mark_populated', 'mark_utilized',
  612. )
  613. class Meta:
  614. ordering = (F('vrf').asc(nulls_first=True), 'start_address', 'pk') # (vrf, start_address) may be non-unique
  615. indexes = (
  616. models.Index(
  617. Cast(Host('start_address'), output_field=IPAddressField()),
  618. name='ipam_iprange_start_host',
  619. ),
  620. models.Index(
  621. Cast(Host('end_address'), output_field=IPAddressField()),
  622. name='ipam_iprange_end_host',
  623. ),
  624. )
  625. verbose_name = _('IP range')
  626. verbose_name_plural = _('IP ranges')
  627. def __str__(self):
  628. return self.name
  629. def clean(self):
  630. super().clean()
  631. if self.start_address and self.end_address:
  632. # Check that start & end IP versions match
  633. if self.start_address.version != self.end_address.version:
  634. raise ValidationError({
  635. 'end_address': _("Starting and ending IP address versions must match")
  636. })
  637. # Check that the start & end IP prefix lengths match
  638. if self.start_address.prefixlen != self.end_address.prefixlen:
  639. raise ValidationError({
  640. 'end_address': _("Starting and ending IP address masks must match")
  641. })
  642. # Equal start/end addresses are permitted for single-address ranges.
  643. # Use .ip (host portion) rather than the IPNetwork object to avoid comparing prefix lengths again.
  644. if self.end_address.ip < self.start_address.ip:
  645. raise ValidationError({
  646. 'end_address': _(
  647. "Ending address must be greater than or equal to the starting address ({start_address})"
  648. ).format(start_address=self.start_address)
  649. })
  650. # Check for overlapping ranges
  651. overlapping_ranges = (
  652. IPRange.objects.exclude(pk=self.pk)
  653. .filter(vrf=self.vrf)
  654. .filter(
  655. # Starts inside
  656. Q(
  657. start_address__host__inet__gte=self.start_address.ip,
  658. start_address__host__inet__lte=self.end_address.ip,
  659. ) |
  660. # Ends inside
  661. Q(
  662. end_address__host__inet__gte=self.start_address.ip,
  663. end_address__host__inet__lte=self.end_address.ip,
  664. ) |
  665. # Starts & ends outside
  666. Q(
  667. start_address__host__inet__lte=self.start_address.ip,
  668. end_address__host__inet__gte=self.end_address.ip,
  669. )
  670. )
  671. )
  672. if overlapping_ranges.exists():
  673. raise ValidationError(
  674. _("Defined addresses overlap with range {overlapping_range} in VRF {vrf}").format(
  675. overlapping_range=overlapping_ranges.first(),
  676. vrf=self.vrf
  677. ))
  678. # Validate maximum size
  679. MAX_SIZE = 2 ** 32 - 1
  680. if int(self.end_address.ip - self.start_address.ip) + 1 > MAX_SIZE:
  681. raise ValidationError(
  682. _("Defined range exceeds maximum supported size ({max_size})").format(max_size=MAX_SIZE)
  683. )
  684. def save(self, *args, **kwargs):
  685. # Record the range's size (number of IP addresses)
  686. self.size = int(self.end_address.ip - self.start_address.ip) + 1
  687. super().save(*args, **kwargs)
  688. @property
  689. def family(self):
  690. if not self.start_address:
  691. return None
  692. if isinstance(self.start_address, str):
  693. return netaddr.IPAddress(self.start_address.split('/')[0]).version
  694. return self.start_address.version
  695. @property
  696. def range(self):
  697. return netaddr.IPRange(self.start_address.ip, self.end_address.ip)
  698. @property
  699. def mask_length(self):
  700. return self.start_address.prefixlen if self.start_address else None
  701. @cached_property
  702. def name(self):
  703. """
  704. Return an efficient string representation of the IP range.
  705. """
  706. # Single-address ranges render both endpoints to stay distinct from IPAddress rows.
  707. if self.start_address.ip == self.end_address.ip:
  708. return f'{self.start_address.ip}-{self.end_address.ip}/{self.start_address.prefixlen}'
  709. separator = ':' if self.family == 6 else '.'
  710. start_chunks = str(self.start_address.ip).split(separator)
  711. end_chunks = str(self.end_address.ip).split(separator)
  712. base_chunks = []
  713. for a, b in zip(start_chunks, end_chunks):
  714. if a == b:
  715. base_chunks.append(a)
  716. base_str = separator.join(base_chunks)
  717. start_str = separator.join(start_chunks[len(base_chunks):])
  718. end_str = separator.join(end_chunks[len(base_chunks):])
  719. return f'{base_str}{separator}{start_str}-{end_str}/{self.start_address.prefixlen}'
  720. def _set_prefix_length(self, value):
  721. """
  722. Expose the IPRange object's prefixlen attribute on the parent model so that it can be manipulated directly,
  723. e.g. for bulk editing.
  724. """
  725. self.start_address.prefixlen = value
  726. self.end_address.prefixlen = value
  727. prefix_length = property(fset=_set_prefix_length)
  728. def get_status_color(self):
  729. return IPRangeStatusChoices.colors.get(self.status)
  730. @cached_property
  731. def first_available_ip(self):
  732. """
  733. Return the first available IP within the range (or None).
  734. """
  735. return self.get_first_available_ip()
  736. @property
  737. def utilization(self):
  738. """
  739. Determine the utilization of the range and return it as a percentage.
  740. """
  741. if self.mark_utilized:
  742. return 100
  743. return min(float(self._occupied_host_count) / self.size * 100, 100)
  744. def get_child_ips(self):
  745. """
  746. Return all IPAddresses within this IPRange and VRF.
  747. """
  748. return IPAddress.objects.filter(
  749. vrf=self.vrf,
  750. address__host_between=(self.start_address.ip, self.end_address.ip),
  751. )
  752. def get_available_ips(self):
  753. """
  754. Return all available IPs within this range as an IPSet.
  755. """
  756. return netaddr.IPSet(
  757. cidr
  758. for start, end in self._available_intervals()
  759. for cidr in netaddr.iprange_to_cidrs(start, end)
  760. )
  761. def iter_available_ips(self):
  762. """
  763. Yield the available IPs within this range as netaddr.IPAddress objects, in
  764. ascending order. Unlike get_available_ips(), consumption is lazy: stopping
  765. early stops reading from the database.
  766. """
  767. for start, end in self._available_intervals():
  768. yield from netaddr.iter_iprange(start, end)
  769. def get_available_ip_count(self):
  770. """
  771. Return the number of available IPs within the range.
  772. """
  773. if self.mark_populated:
  774. return 0
  775. return max(self.size - self._occupied_host_count, 0)
  776. def get_first_available_ip(self):
  777. """
  778. Return the first available IP within the range (or None).
  779. """
  780. if self.mark_populated:
  781. return None
  782. first_available_ip = self.get_child_ips().first_available_host(
  783. self.start_address.ip, self.end_address.ip,
  784. )
  785. if first_available_ip is None:
  786. return None
  787. return f'{first_available_ip}/{self.start_address.prefixlen}'
  788. def _available_intervals(self):
  789. """
  790. Yield the available (start, end) host intervals within the range.
  791. """
  792. if self.mark_populated:
  793. return iter(())
  794. return self.get_child_ips().available_intervals(
  795. self.start_address.ip, self.end_address.ip,
  796. )
  797. @cached_property
  798. def _occupied_host_count(self):
  799. """
  800. The number of distinct occupied hosts within the range, cached for the
  801. lifetime of the instance.
  802. """
  803. return self.get_child_ips().count_distinct_hosts()
  804. class IPAddress(ContactsMixin, PrimaryModel):
  805. """
  806. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  807. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  808. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  809. Interfaces can have zero or more IPAddresses assigned to them.
  810. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  811. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  812. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  813. """
  814. address = IPAddressField(
  815. verbose_name=_('address'),
  816. help_text=_('IPv4 or IPv6 address (with mask)')
  817. )
  818. vrf = models.ForeignKey(
  819. to='ipam.VRF',
  820. on_delete=models.PROTECT,
  821. related_name='ip_addresses',
  822. blank=True,
  823. null=True,
  824. verbose_name=_('VRF')
  825. )
  826. tenant = models.ForeignKey(
  827. to='tenancy.Tenant',
  828. on_delete=models.PROTECT,
  829. related_name='ip_addresses',
  830. blank=True,
  831. null=True
  832. )
  833. status = models.CharField(
  834. verbose_name=_('status'),
  835. max_length=50,
  836. choices=IPAddressStatusChoices,
  837. default=IPAddressStatusChoices.STATUS_ACTIVE,
  838. help_text=_('The operational status of this IP')
  839. )
  840. role = models.CharField(
  841. verbose_name=_('role'),
  842. max_length=50,
  843. choices=IPAddressRoleChoices,
  844. blank=True,
  845. null=True,
  846. help_text=_('The functional role of this IP')
  847. )
  848. assigned_object_type = models.ForeignKey(
  849. to='contenttypes.ContentType',
  850. on_delete=models.PROTECT,
  851. related_name='+',
  852. blank=True,
  853. null=True
  854. )
  855. assigned_object_id = models.PositiveBigIntegerField(
  856. blank=True,
  857. null=True
  858. )
  859. assigned_object = GenericForeignKey(
  860. ct_field='assigned_object_type',
  861. fk_field='assigned_object_id'
  862. )
  863. nat_inside = models.ForeignKey(
  864. to='self',
  865. on_delete=models.SET_NULL,
  866. related_name='nat_outside',
  867. blank=True,
  868. null=True,
  869. verbose_name=_('NAT (inside)'),
  870. help_text=_('The IP for which this address is the "outside" IP')
  871. )
  872. dns_name = models.CharField(
  873. max_length=255,
  874. blank=True,
  875. validators=[DNSValidator],
  876. verbose_name=_('DNS name'),
  877. help_text=_('Hostname or FQDN (not case-sensitive)')
  878. )
  879. l2vpn_terminations = GenericRelation(
  880. to='vpn.L2VPNTermination',
  881. content_type_field='assigned_object_type',
  882. object_id_field='assigned_object_id',
  883. related_query_name='ipaddress',
  884. )
  885. objects = IPAddressManager()
  886. clone_fields = (
  887. 'vrf', 'tenant', 'status', 'role', 'dns_name', 'description',
  888. )
  889. class Meta:
  890. ordering = ('address', 'pk') # address may be non-unique
  891. indexes = (
  892. models.Index(fields=('address', 'id')),
  893. # Default ordering (see IPAddressManager). The primary key must be included so that the index can
  894. # satisfy the ordering outright; without it PostgreSQL falls back to an incremental sort, which
  895. # measurably slows deep pagination.
  896. models.Index(
  897. Cast(Host('address'), output_field=IPAddressField()), F('id'), name='ipam_ipaddress_host'
  898. ),
  899. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  900. )
  901. verbose_name = _('IP address')
  902. verbose_name_plural = _('IP addresses')
  903. def __str__(self):
  904. return str(self.address)
  905. def __init__(self, *args, **kwargs):
  906. super().__init__(*args, **kwargs)
  907. # Denote the original assigned object (if any) for validation in clean()
  908. self._original_assigned_object_id = self.__dict__.get('assigned_object_id')
  909. self._original_assigned_object_type_id = self.__dict__.get('assigned_object_type_id')
  910. @property
  911. def ipv6_full(self):
  912. if self.address and self.address.version == 6:
  913. return netaddr.IPAddress(self.address).format(netaddr.ipv6_full)
  914. return None
  915. def get_duplicates(self):
  916. return IPAddress.objects.filter(
  917. vrf=self.vrf,
  918. address__net_host=str(self.address.ip)
  919. ).exclude(pk=self.pk)
  920. def get_next_available_ip(self):
  921. """
  922. Return the next available IP address within this IP's network (if any)
  923. """
  924. if self.address and self.address.broadcast:
  925. start_ip = self.address.ip + 1
  926. end_ip = self.address.broadcast - 1
  927. if start_ip <= end_ip:
  928. available_ips = netaddr.IPSet(netaddr.IPRange(start_ip, end_ip))
  929. available_ips -= netaddr.IPSet([
  930. address.ip for address in IPAddress.objects.filter(
  931. vrf=self.vrf,
  932. address__gt=self.address,
  933. address__net_contained_or_equal=self.address.cidr
  934. ).values_list('address', flat=True)
  935. ])
  936. if available_ips:
  937. return next(iter(available_ips))
  938. return None
  939. def get_related_ips(self):
  940. """
  941. Return all IPAddresses belonging to the same VRF.
  942. """
  943. return IPAddress.objects.exclude(address=str(self.address)).filter(
  944. vrf=self.vrf, address__net_contained_or_equal=str(self.address)
  945. )
  946. def clean(self):
  947. super().clean()
  948. if self.address:
  949. # /0 masks are not acceptable
  950. if self.address.prefixlen == 0:
  951. raise ValidationError({
  952. 'address': _("Cannot create IP address with /0 mask.")
  953. })
  954. # Do not allow assigning a network ID or broadcast address to an interface.
  955. if self.assigned_object:
  956. if self.address.ip == self.address.network:
  957. msg = _("{ip} is a network ID, which may not be assigned to an interface.").format(
  958. ip=self.address.ip
  959. )
  960. if self.address.version == 4 and self.address.prefixlen not in (31, 32):
  961. raise ValidationError(msg)
  962. if self.address.version == 6 and self.address.prefixlen not in (127, 128):
  963. raise ValidationError(msg)
  964. if (
  965. self.address.version == 4 and self.address.ip == self.address.broadcast and
  966. self.address.prefixlen not in (31, 32)
  967. ):
  968. msg = _("{ip} is a broadcast address, which may not be assigned to an interface.").format(
  969. ip=self.address.ip
  970. )
  971. raise ValidationError(msg)
  972. # Enforce unique IP space (if applicable)
  973. if (self.vrf is None and get_config().ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  974. duplicate_ips = self.get_duplicates()
  975. if duplicate_ips and (
  976. self.role not in IPADDRESS_ROLES_NONUNIQUE or
  977. any(dip.role not in IPADDRESS_ROLES_NONUNIQUE for dip in duplicate_ips)
  978. ):
  979. table = _("VRF {vrf}").format(vrf=self.vrf) if self.vrf else _("global table")
  980. raise ValidationError({
  981. 'address': _("Duplicate IP address found in {table}: {ipaddress}").format(
  982. table=table,
  983. ipaddress=duplicate_ips.first(),
  984. )
  985. })
  986. # Disallow the creation of IPAddresses within an IPRange with mark_populated=True
  987. parent_range_qs = IPRange.objects.filter(
  988. start_address__host__inet__lte=self.address.ip,
  989. end_address__host__inet__gte=self.address.ip,
  990. vrf=self.vrf,
  991. mark_populated=True,
  992. )
  993. if not self.pk and (parent_range := parent_range_qs.first()):
  994. raise ValidationError({
  995. 'address': _(
  996. "Cannot create IP address {ip} inside range {range}."
  997. ).format(ip=self.address, range=parent_range)
  998. })
  999. if self._original_assigned_object_id and self._original_assigned_object_type_id:
  1000. parent = getattr(self.assigned_object, 'parent_object', None)
  1001. ct = ContentType.objects.get_for_id(self._original_assigned_object_type_id)
  1002. original_assigned_object = ct.get_object_for_this_type(pk=self._original_assigned_object_id)
  1003. original_parent = getattr(original_assigned_object, 'parent_object', None)
  1004. # can't use is_primary_ip as self.assigned_object might be changed
  1005. is_primary = False
  1006. if self.family == 4 and hasattr(original_parent, 'primary_ip4'):
  1007. if original_parent.primary_ip4_id == self.pk:
  1008. is_primary = True
  1009. if self.family == 6 and hasattr(original_parent, 'primary_ip6'):
  1010. if original_parent.primary_ip6_id == self.pk:
  1011. is_primary = True
  1012. if is_primary and (parent != original_parent):
  1013. raise ValidationError(
  1014. _("Cannot reassign IP address while it is designated as the primary IP for the parent object")
  1015. )
  1016. # can't use is_oob_ip as self.assigned_object might be changed
  1017. if hasattr(original_parent, 'oob_ip') and original_parent.oob_ip_id == self.pk:
  1018. if parent != original_parent:
  1019. raise ValidationError(
  1020. _("Cannot reassign IP address while it is designated as the OOB IP for the parent object")
  1021. )
  1022. # Validate IP status selection
  1023. if self.status == IPAddressStatusChoices.STATUS_SLAAC and self.family != 6:
  1024. raise ValidationError({
  1025. 'status': _("Only IPv6 addresses can be assigned SLAAC status")
  1026. })
  1027. def save(self, *args, **kwargs):
  1028. # Force dns_name to lowercase
  1029. self.dns_name = self.dns_name.lower()
  1030. super().save(*args, **kwargs)
  1031. def clone(self):
  1032. attrs = super().clone()
  1033. # Populate the address field with the next available IP (if any)
  1034. if next_available_ip := self.get_next_available_ip():
  1035. attrs['address'] = f'{next_available_ip}/{self.address.prefixlen}'
  1036. return attrs
  1037. def to_objectchange(self, action):
  1038. objectchange = super().to_objectchange(action)
  1039. objectchange.related_object = self.assigned_object
  1040. return objectchange
  1041. @property
  1042. def family(self):
  1043. if not self.address:
  1044. return None
  1045. if isinstance(self.address, str):
  1046. return netaddr.IPNetwork(self.address).version
  1047. return self.address.version
  1048. @property
  1049. def is_oob_ip(self):
  1050. if self.assigned_object:
  1051. parent = getattr(self.assigned_object, 'parent_object', None)
  1052. if hasattr(parent, 'oob_ip') and parent.oob_ip_id == self.pk:
  1053. return True
  1054. return False
  1055. @property
  1056. def is_primary_ip(self):
  1057. if self.assigned_object:
  1058. parent = getattr(self.assigned_object, 'parent_object', None)
  1059. if self.family == 4 and hasattr(parent, 'primary_ip4') and parent.primary_ip4_id == self.pk:
  1060. return True
  1061. if self.family == 6 and hasattr(parent, 'primary_ip6') and parent.primary_ip6_id == self.pk:
  1062. return True
  1063. return False
  1064. def _set_mask_length(self, value):
  1065. """
  1066. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  1067. e.g. for bulk editing.
  1068. """
  1069. if self.address is not None:
  1070. self.address.prefixlen = value
  1071. mask_length = property(fset=_set_mask_length)
  1072. def get_status_color(self):
  1073. return IPAddressStatusChoices.colors.get(self.status)
  1074. def get_role_color(self):
  1075. return IPAddressRoleChoices.colors.get(self.role)