ip.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. import netaddr
  2. from django.contrib.contenttypes.fields import GenericForeignKey
  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 IPNetworkField, IPAddressField
  15. from ipam.lookups import Host
  16. from ipam.managers import IPAddressManager
  17. from ipam.querysets import 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. 'Aggregate',
  24. 'IPAddress',
  25. 'IPRange',
  26. 'Prefix',
  27. 'RIR',
  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. verbose_name = _('aggregate')
  100. verbose_name_plural = _('aggregates')
  101. def __str__(self):
  102. return str(self.prefix)
  103. def clean(self):
  104. super().clean()
  105. if self.prefix:
  106. # /0 masks are not acceptable
  107. if self.prefix.prefixlen == 0:
  108. raise ValidationError({
  109. 'prefix': _("Cannot create aggregate with /0 mask.")
  110. })
  111. # Ensure that the aggregate being added is not covered by an existing aggregate
  112. covering_aggregates = Aggregate.objects.filter(
  113. prefix__net_contains_or_equals=str(self.prefix)
  114. )
  115. if self.pk:
  116. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  117. if covering_aggregates:
  118. raise ValidationError({
  119. 'prefix': _(
  120. "Aggregates cannot overlap. {prefix} is already covered by an existing aggregate ({aggregate})."
  121. ).format(
  122. prefix=self.prefix,
  123. aggregate=covering_aggregates[0]
  124. )
  125. })
  126. # Ensure that the aggregate being added does not cover an existing aggregate
  127. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  128. if self.pk:
  129. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  130. if covered_aggregates:
  131. raise ValidationError({
  132. 'prefix': _(
  133. "Prefixes cannot overlap aggregates. {prefix} covers an existing aggregate ({aggregate})."
  134. ).format(
  135. prefix=self.prefix,
  136. aggregate=covered_aggregates[0]
  137. )
  138. })
  139. @property
  140. def family(self):
  141. if self.prefix:
  142. return self.prefix.version
  143. return None
  144. @property
  145. def ipv6_full(self):
  146. if self.prefix and self.prefix.version == 6:
  147. return netaddr.IPAddress(self.prefix).format(netaddr.ipv6_full)
  148. def get_child_prefixes(self):
  149. """
  150. Return all Prefixes within this Aggregate
  151. """
  152. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  153. def get_utilization(self):
  154. """
  155. Determine the prefix utilization of the aggregate and return it as a percentage.
  156. """
  157. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  158. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  159. utilization = float(child_prefixes.size) / self.prefix.size * 100
  160. return min(utilization, 100)
  161. class Role(OrganizationalModel):
  162. """
  163. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  164. "Management."
  165. """
  166. weight = models.PositiveSmallIntegerField(
  167. verbose_name=_('weight'),
  168. default=1000
  169. )
  170. class Meta:
  171. ordering = ('weight', 'name')
  172. verbose_name = _('role')
  173. verbose_name_plural = _('roles')
  174. def __str__(self):
  175. return self.name
  176. class Prefix(ContactsMixin, GetAvailablePrefixesMixin, CachedScopeMixin, PrimaryModel):
  177. """
  178. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be scoped to certain
  179. areas and/or assigned to VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role.
  180. A Prefix can also be assigned to a VLAN where appropriate.
  181. """
  182. prefix = IPNetworkField(
  183. verbose_name=_('prefix'),
  184. help_text=_('IPv4 or IPv6 network with mask')
  185. )
  186. vrf = models.ForeignKey(
  187. to='ipam.VRF',
  188. on_delete=models.PROTECT,
  189. related_name='prefixes',
  190. blank=True,
  191. null=True,
  192. verbose_name=_('VRF')
  193. )
  194. tenant = models.ForeignKey(
  195. to='tenancy.Tenant',
  196. on_delete=models.PROTECT,
  197. related_name='prefixes',
  198. blank=True,
  199. null=True
  200. )
  201. vlan = models.ForeignKey(
  202. to='ipam.VLAN',
  203. on_delete=models.PROTECT,
  204. related_name='prefixes',
  205. blank=True,
  206. null=True
  207. )
  208. status = models.CharField(
  209. max_length=50,
  210. choices=PrefixStatusChoices,
  211. default=PrefixStatusChoices.STATUS_ACTIVE,
  212. verbose_name=_('status'),
  213. help_text=_('Operational status of this prefix')
  214. )
  215. role = models.ForeignKey(
  216. to='ipam.Role',
  217. on_delete=models.SET_NULL,
  218. related_name='prefixes',
  219. blank=True,
  220. null=True,
  221. help_text=_('The primary function of this prefix')
  222. )
  223. is_pool = models.BooleanField(
  224. verbose_name=_('is a pool'),
  225. default=False,
  226. help_text=_('All IP addresses within this prefix are considered usable')
  227. )
  228. mark_utilized = models.BooleanField(
  229. verbose_name=_('mark utilized'),
  230. default=False,
  231. help_text=_("Treat as fully utilized")
  232. )
  233. # Cached depth & child counts
  234. _depth = models.PositiveSmallIntegerField(
  235. default=0,
  236. editable=False
  237. )
  238. _children = models.PositiveBigIntegerField(
  239. default=0,
  240. editable=False
  241. )
  242. objects = PrefixQuerySet.as_manager()
  243. clone_fields = (
  244. 'scope_type', 'scope_id', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'description',
  245. )
  246. class Meta:
  247. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  248. verbose_name = _('prefix')
  249. verbose_name_plural = _('prefixes')
  250. indexes = [
  251. GistIndex(
  252. fields=['prefix'],
  253. name='ipam_prefix_gist_idx',
  254. opclasses=['inet_ops'],
  255. ),
  256. ]
  257. def __init__(self, *args, **kwargs):
  258. super().__init__(*args, **kwargs)
  259. # Cache the original prefix and VRF so we can check if they have changed on post_save
  260. self._prefix = self.__dict__.get('prefix')
  261. self._vrf_id = self.__dict__.get('vrf_id')
  262. def __str__(self):
  263. return str(self.prefix)
  264. def clean(self):
  265. super().clean()
  266. if self.prefix:
  267. # /0 masks are not acceptable
  268. if self.prefix.prefixlen == 0:
  269. raise ValidationError({
  270. 'prefix': _("Cannot create prefix with /0 mask.")
  271. })
  272. # Enforce unique IP space (if applicable)
  273. if (self.vrf is None and get_config().ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  274. duplicate_prefixes = self.get_duplicates()
  275. if duplicate_prefixes:
  276. table = _("VRF {vrf}").format(vrf=self.vrf) if self.vrf else _("global table")
  277. raise ValidationError({
  278. 'prefix': _("Duplicate prefix found in {table}: {prefix}").format(
  279. table=table,
  280. prefix=duplicate_prefixes.first(),
  281. )
  282. })
  283. def save(self, *args, **kwargs):
  284. if isinstance(self.prefix, netaddr.IPNetwork):
  285. # Clear host bits from prefix
  286. self.prefix = self.prefix.cidr
  287. # Cache objects associated with the terminating object (for filtering)
  288. self.cache_related_objects()
  289. super().save(*args, **kwargs)
  290. @property
  291. def family(self):
  292. return self.prefix.version if self.prefix else None
  293. @property
  294. def mask_length(self):
  295. return self.prefix.prefixlen if self.prefix else None
  296. @property
  297. def ipv6_full(self):
  298. if self.prefix and self.prefix.version == 6:
  299. return netaddr.IPAddress(self.prefix).format(netaddr.ipv6_full)
  300. @property
  301. def depth(self):
  302. return self._depth
  303. @property
  304. def children(self):
  305. return self._children
  306. def _set_prefix_length(self, value):
  307. """
  308. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  309. e.g. for bulk editing.
  310. """
  311. if self.prefix is not None:
  312. self.prefix.prefixlen = value
  313. prefix_length = property(fset=_set_prefix_length)
  314. def get_status_color(self):
  315. return PrefixStatusChoices.colors.get(self.status)
  316. def get_parents(self, include_self=False):
  317. """
  318. Return all containing Prefixes in the hierarchy.
  319. """
  320. lookup = 'net_contains_or_equals' if include_self else 'net_contains'
  321. return Prefix.objects.filter(**{
  322. 'vrf': self.vrf,
  323. f'prefix__{lookup}': self.prefix
  324. })
  325. def get_children(self, include_self=False):
  326. """
  327. Return all covered Prefixes in the hierarchy.
  328. """
  329. lookup = 'net_contained_or_equal' if include_self else 'net_contained'
  330. return Prefix.objects.filter(**{
  331. 'vrf': self.vrf,
  332. f'prefix__{lookup}': self.prefix
  333. })
  334. def get_duplicates(self):
  335. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  336. def get_child_prefixes(self):
  337. """
  338. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  339. Prefixes belonging to any VRF.
  340. """
  341. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  342. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  343. else:
  344. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  345. def get_child_ranges(self, **kwargs):
  346. """
  347. Return all IPRanges within this Prefix and VRF.
  348. """
  349. return IPRange.objects.filter(
  350. vrf=self.vrf,
  351. start_address__net_host_contained=str(self.prefix),
  352. end_address__net_host_contained=str(self.prefix),
  353. **kwargs
  354. )
  355. def get_child_ips(self):
  356. """
  357. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  358. child IPAddresses belonging to any VRF.
  359. """
  360. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  361. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  362. else:
  363. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  364. def get_available_ips(self):
  365. """
  366. Return all available IPs within this prefix as an IPSet.
  367. """
  368. prefix = netaddr.IPSet(self.prefix)
  369. child_ips = netaddr.IPSet([
  370. ip.address.ip for ip in self.get_child_ips()
  371. ])
  372. child_ranges = netaddr.IPSet([
  373. iprange.range for iprange in self.get_child_ranges().filter(mark_populated=True)
  374. ])
  375. available_ips = prefix - child_ips - child_ranges
  376. # IPv6 /127's, pool, or IPv4 /31-/32 sets are fully usable
  377. if (self.family == 6 and self.prefix.prefixlen >= 127) or self.is_pool or (
  378. self.family == 4 and self.prefix.prefixlen >= 31
  379. ):
  380. return available_ips
  381. if self.family == 4:
  382. # For "normal" IPv4 prefixes, omit first and last addresses
  383. available_ips -= netaddr.IPSet([
  384. netaddr.IPAddress(self.prefix.first),
  385. netaddr.IPAddress(self.prefix.last),
  386. ])
  387. else:
  388. # For IPv6 prefixes, omit the Subnet-Router anycast address
  389. # per RFC 4291
  390. available_ips -= netaddr.IPSet([netaddr.IPAddress(self.prefix.first)])
  391. return available_ips
  392. def get_first_available_ip(self):
  393. """
  394. Return the first available IP within the prefix (or None).
  395. """
  396. available_ips = self.get_available_ips()
  397. if not available_ips:
  398. return None
  399. return '{}/{}'.format(next(available_ips.__iter__()), self.prefix.prefixlen)
  400. def get_utilization(self):
  401. """
  402. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  403. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  404. """
  405. if self.mark_utilized:
  406. return 100
  407. if self.status == PrefixStatusChoices.STATUS_CONTAINER:
  408. queryset = Prefix.objects.filter(
  409. prefix__net_contained=str(self.prefix),
  410. vrf=self.vrf
  411. )
  412. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  413. utilization = float(child_prefixes.size) / self.prefix.size * 100
  414. else:
  415. # Compile an IPSet to avoid counting duplicate IPs
  416. child_ips = netaddr.IPSet()
  417. for iprange in self.get_child_ranges().filter(mark_utilized=True):
  418. child_ips.add(iprange.range)
  419. for ip in self.get_child_ips():
  420. child_ips.add(ip.address.ip)
  421. prefix_size = self.prefix.size
  422. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  423. prefix_size -= 2
  424. utilization = float(child_ips.size) / prefix_size * 100
  425. return min(utilization, 100)
  426. class IPRange(ContactsMixin, PrimaryModel):
  427. """
  428. A range of IP addresses, defined by start and end addresses.
  429. """
  430. start_address = IPAddressField(
  431. verbose_name=_('start address'),
  432. help_text=_('IPv4 or IPv6 address (with mask)')
  433. )
  434. end_address = IPAddressField(
  435. verbose_name=_('end address'),
  436. help_text=_('IPv4 or IPv6 address (with mask)')
  437. )
  438. size = models.PositiveIntegerField(
  439. verbose_name=_('size'),
  440. editable=False
  441. )
  442. vrf = models.ForeignKey(
  443. to='ipam.VRF',
  444. on_delete=models.PROTECT,
  445. related_name='ip_ranges',
  446. blank=True,
  447. null=True,
  448. verbose_name=_('VRF')
  449. )
  450. tenant = models.ForeignKey(
  451. to='tenancy.Tenant',
  452. on_delete=models.PROTECT,
  453. related_name='ip_ranges',
  454. blank=True,
  455. null=True
  456. )
  457. status = models.CharField(
  458. verbose_name=_('status'),
  459. max_length=50,
  460. choices=IPRangeStatusChoices,
  461. default=IPRangeStatusChoices.STATUS_ACTIVE,
  462. help_text=_('Operational status of this range')
  463. )
  464. role = models.ForeignKey(
  465. to='ipam.Role',
  466. on_delete=models.SET_NULL,
  467. related_name='ip_ranges',
  468. blank=True,
  469. null=True,
  470. help_text=_('The primary function of this range')
  471. )
  472. mark_populated = models.BooleanField(
  473. verbose_name=_('mark populated'),
  474. default=False,
  475. help_text=_("Prevent the creation of IP addresses within this range")
  476. )
  477. mark_utilized = models.BooleanField(
  478. verbose_name=_('mark utilized'),
  479. default=False,
  480. help_text=_("Report space as fully utilized")
  481. )
  482. clone_fields = (
  483. 'vrf', 'tenant', 'status', 'role', 'description', 'mark_populated', 'mark_utilized',
  484. )
  485. class Meta:
  486. ordering = (F('vrf').asc(nulls_first=True), 'start_address', 'pk') # (vrf, start_address) may be non-unique
  487. verbose_name = _('IP range')
  488. verbose_name_plural = _('IP ranges')
  489. def __str__(self):
  490. return self.name
  491. def clean(self):
  492. super().clean()
  493. if self.start_address and self.end_address:
  494. # Check that start & end IP versions match
  495. if self.start_address.version != self.end_address.version:
  496. raise ValidationError({
  497. 'end_address': _("Starting and ending IP address versions must match")
  498. })
  499. # Check that the start & end IP prefix lengths match
  500. if self.start_address.prefixlen != self.end_address.prefixlen:
  501. raise ValidationError({
  502. 'end_address': _("Starting and ending IP address masks must match")
  503. })
  504. # Check that the ending address is greater than the starting address
  505. if not self.end_address > self.start_address:
  506. raise ValidationError({
  507. 'end_address': _(
  508. "Ending address must be greater than the starting address ({start_address})"
  509. ).format(start_address=self.start_address)
  510. })
  511. # Check for overlapping ranges
  512. overlapping_ranges = (
  513. IPRange.objects.exclude(pk=self.pk)
  514. .filter(vrf=self.vrf)
  515. .filter(
  516. # Starts inside
  517. Q(
  518. start_address__host__inet__gte=self.start_address.ip,
  519. start_address__host__inet__lte=self.end_address.ip,
  520. ) |
  521. # Ends inside
  522. Q(
  523. end_address__host__inet__gte=self.start_address.ip,
  524. end_address__host__inet__lte=self.end_address.ip,
  525. ) |
  526. # Starts & ends outside
  527. Q(
  528. start_address__host__inet__lte=self.start_address.ip,
  529. end_address__host__inet__gte=self.end_address.ip,
  530. )
  531. )
  532. )
  533. if overlapping_ranges.exists():
  534. raise ValidationError(
  535. _("Defined addresses overlap with range {overlapping_range} in VRF {vrf}").format(
  536. overlapping_range=overlapping_ranges.first(),
  537. vrf=self.vrf
  538. ))
  539. # Validate maximum size
  540. MAX_SIZE = 2 ** 32 - 1
  541. if int(self.end_address.ip - self.start_address.ip) + 1 > MAX_SIZE:
  542. raise ValidationError(
  543. _("Defined range exceeds maximum supported size ({max_size})").format(max_size=MAX_SIZE)
  544. )
  545. def save(self, *args, **kwargs):
  546. # Record the range's size (number of IP addresses)
  547. self.size = int(self.end_address.ip - self.start_address.ip) + 1
  548. super().save(*args, **kwargs)
  549. @property
  550. def family(self):
  551. return self.start_address.version if self.start_address else None
  552. @property
  553. def range(self):
  554. return netaddr.IPRange(self.start_address.ip, self.end_address.ip)
  555. @property
  556. def mask_length(self):
  557. return self.start_address.prefixlen if self.start_address else None
  558. @cached_property
  559. def name(self):
  560. """
  561. Return an efficient string representation of the IP range.
  562. """
  563. separator = ':' if self.family == 6 else '.'
  564. start_chunks = str(self.start_address.ip).split(separator)
  565. end_chunks = str(self.end_address.ip).split(separator)
  566. base_chunks = []
  567. for a, b in zip(start_chunks, end_chunks):
  568. if a == b:
  569. base_chunks.append(a)
  570. base_str = separator.join(base_chunks)
  571. start_str = separator.join(start_chunks[len(base_chunks):])
  572. end_str = separator.join(end_chunks[len(base_chunks):])
  573. return f'{base_str}{separator}{start_str}-{end_str}/{self.start_address.prefixlen}'
  574. def _set_prefix_length(self, value):
  575. """
  576. Expose the IPRange object's prefixlen attribute on the parent model so that it can be manipulated directly,
  577. e.g. for bulk editing.
  578. """
  579. self.start_address.prefixlen = value
  580. self.end_address.prefixlen = value
  581. prefix_length = property(fset=_set_prefix_length)
  582. def get_status_color(self):
  583. return IPRangeStatusChoices.colors.get(self.status)
  584. def get_child_ips(self):
  585. """
  586. Return all IPAddresses within this IPRange and VRF.
  587. """
  588. return IPAddress.objects.filter(
  589. address__gte=self.start_address,
  590. address__lte=self.end_address,
  591. vrf=self.vrf
  592. )
  593. def get_available_ips(self):
  594. """
  595. Return all available IPs within this range as an IPSet.
  596. """
  597. if self.mark_populated:
  598. return netaddr.IPSet()
  599. range = netaddr.IPRange(self.start_address.ip, self.end_address.ip)
  600. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  601. return netaddr.IPSet(range) - child_ips
  602. @cached_property
  603. def first_available_ip(self):
  604. """
  605. Return the first available IP within the range (or None).
  606. """
  607. available_ips = self.get_available_ips()
  608. if not available_ips:
  609. return None
  610. return '{}/{}'.format(next(available_ips.__iter__()), self.start_address.prefixlen)
  611. @cached_property
  612. def utilization(self):
  613. """
  614. Determine the utilization of the range and return it as a percentage.
  615. """
  616. if self.mark_utilized:
  617. return 100
  618. # Compile an IPSet to avoid counting duplicate IPs
  619. child_count = netaddr.IPSet([
  620. ip.address.ip for ip in self.get_child_ips()
  621. ]).size
  622. return min(float(child_count) / self.size * 100, 100)
  623. class IPAddress(ContactsMixin, PrimaryModel):
  624. """
  625. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  626. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  627. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  628. Interfaces can have zero or more IPAddresses assigned to them.
  629. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  630. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  631. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  632. """
  633. address = IPAddressField(
  634. verbose_name=_('address'),
  635. help_text=_('IPv4 or IPv6 address (with mask)')
  636. )
  637. vrf = models.ForeignKey(
  638. to='ipam.VRF',
  639. on_delete=models.PROTECT,
  640. related_name='ip_addresses',
  641. blank=True,
  642. null=True,
  643. verbose_name=_('VRF')
  644. )
  645. tenant = models.ForeignKey(
  646. to='tenancy.Tenant',
  647. on_delete=models.PROTECT,
  648. related_name='ip_addresses',
  649. blank=True,
  650. null=True
  651. )
  652. status = models.CharField(
  653. verbose_name=_('status'),
  654. max_length=50,
  655. choices=IPAddressStatusChoices,
  656. default=IPAddressStatusChoices.STATUS_ACTIVE,
  657. help_text=_('The operational status of this IP')
  658. )
  659. role = models.CharField(
  660. verbose_name=_('role'),
  661. max_length=50,
  662. choices=IPAddressRoleChoices,
  663. blank=True,
  664. null=True,
  665. help_text=_('The functional role of this IP')
  666. )
  667. assigned_object_type = models.ForeignKey(
  668. to='contenttypes.ContentType',
  669. on_delete=models.PROTECT,
  670. related_name='+',
  671. blank=True,
  672. null=True
  673. )
  674. assigned_object_id = models.PositiveBigIntegerField(
  675. blank=True,
  676. null=True
  677. )
  678. assigned_object = GenericForeignKey(
  679. ct_field='assigned_object_type',
  680. fk_field='assigned_object_id'
  681. )
  682. nat_inside = models.ForeignKey(
  683. to='self',
  684. on_delete=models.SET_NULL,
  685. related_name='nat_outside',
  686. blank=True,
  687. null=True,
  688. verbose_name=_('NAT (inside)'),
  689. help_text=_('The IP for which this address is the "outside" IP')
  690. )
  691. dns_name = models.CharField(
  692. max_length=255,
  693. blank=True,
  694. validators=[DNSValidator],
  695. verbose_name=_('DNS name'),
  696. help_text=_('Hostname or FQDN (not case-sensitive)')
  697. )
  698. objects = IPAddressManager()
  699. clone_fields = (
  700. 'vrf', 'tenant', 'status', 'role', 'dns_name', 'description',
  701. )
  702. class Meta:
  703. ordering = ('address', 'pk') # address may be non-unique
  704. indexes = (
  705. models.Index(Cast(Host('address'), output_field=IPAddressField()), name='ipam_ipaddress_host'),
  706. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  707. )
  708. verbose_name = _('IP address')
  709. verbose_name_plural = _('IP addresses')
  710. def __str__(self):
  711. return str(self.address)
  712. def __init__(self, *args, **kwargs):
  713. super().__init__(*args, **kwargs)
  714. # Denote the original assigned object (if any) for validation in clean()
  715. self._original_assigned_object_id = self.__dict__.get('assigned_object_id')
  716. self._original_assigned_object_type_id = self.__dict__.get('assigned_object_type_id')
  717. @property
  718. def ipv6_full(self):
  719. if self.address and self.address.version == 6:
  720. return netaddr.IPAddress(self.address).format(netaddr.ipv6_full)
  721. def get_duplicates(self):
  722. return IPAddress.objects.filter(
  723. vrf=self.vrf,
  724. address__net_host=str(self.address.ip)
  725. ).exclude(pk=self.pk)
  726. def get_next_available_ip(self):
  727. """
  728. Return the next available IP address within this IP's network (if any)
  729. """
  730. if self.address and self.address.broadcast:
  731. start_ip = self.address.ip + 1
  732. end_ip = self.address.broadcast - 1
  733. if start_ip <= end_ip:
  734. available_ips = netaddr.IPSet(netaddr.IPRange(start_ip, end_ip))
  735. available_ips -= netaddr.IPSet([
  736. address.ip for address in IPAddress.objects.filter(
  737. vrf=self.vrf,
  738. address__gt=self.address,
  739. address__net_contained_or_equal=self.address.cidr
  740. ).values_list('address', flat=True)
  741. ])
  742. if available_ips:
  743. return next(iter(available_ips))
  744. def get_related_ips(self):
  745. """
  746. Return all IPAddresses belonging to the same VRF.
  747. """
  748. return IPAddress.objects.exclude(address=str(self.address)).filter(
  749. vrf=self.vrf, address__net_contained_or_equal=str(self.address)
  750. )
  751. def clean(self):
  752. super().clean()
  753. if self.address:
  754. # /0 masks are not acceptable
  755. if self.address.prefixlen == 0:
  756. raise ValidationError({
  757. 'address': _("Cannot create IP address with /0 mask.")
  758. })
  759. # Do not allow assigning a network ID or broadcast address to an interface.
  760. if self.assigned_object:
  761. if self.address.ip == self.address.network:
  762. msg = _("{ip} is a network ID, which may not be assigned to an interface.").format(
  763. ip=self.address.ip
  764. )
  765. if self.address.version == 4 and self.address.prefixlen not in (31, 32):
  766. raise ValidationError(msg)
  767. if self.address.version == 6 and self.address.prefixlen not in (127, 128):
  768. raise ValidationError(msg)
  769. if (
  770. self.address.version == 4 and self.address.ip == self.address.broadcast and
  771. self.address.prefixlen not in (31, 32)
  772. ):
  773. msg = _("{ip} is a broadcast address, which may not be assigned to an interface.").format(
  774. ip=self.address.ip
  775. )
  776. raise ValidationError(msg)
  777. # Enforce unique IP space (if applicable)
  778. if (self.vrf is None and get_config().ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  779. duplicate_ips = self.get_duplicates()
  780. if duplicate_ips and (
  781. self.role not in IPADDRESS_ROLES_NONUNIQUE or
  782. any(dip.role not in IPADDRESS_ROLES_NONUNIQUE for dip in duplicate_ips)
  783. ):
  784. table = _("VRF {vrf}").format(vrf=self.vrf) if self.vrf else _("global table")
  785. raise ValidationError({
  786. 'address': _("Duplicate IP address found in {table}: {ipaddress}").format(
  787. table=table,
  788. ipaddress=duplicate_ips.first(),
  789. )
  790. })
  791. # Disallow the creation of IPAddresses within an IPRange with mark_populated=True
  792. parent_range = IPRange.objects.filter(
  793. start_address__lte=self.address,
  794. end_address__gte=self.address,
  795. vrf=self.vrf,
  796. mark_populated=True
  797. ).first()
  798. if parent_range:
  799. raise ValidationError({
  800. 'address': _(
  801. "Cannot create IP address {ip} inside range {range}."
  802. ).format(ip=self.address, range=parent_range)
  803. })
  804. if self._original_assigned_object_id and self._original_assigned_object_type_id:
  805. parent = getattr(self.assigned_object, 'parent_object', None)
  806. ct = ContentType.objects.get_for_id(self._original_assigned_object_type_id)
  807. original_assigned_object = ct.get_object_for_this_type(pk=self._original_assigned_object_id)
  808. original_parent = getattr(original_assigned_object, 'parent_object', None)
  809. # can't use is_primary_ip as self.assigned_object might be changed
  810. is_primary = False
  811. if self.family == 4 and hasattr(original_parent, 'primary_ip4'):
  812. if original_parent.primary_ip4_id == self.pk:
  813. is_primary = True
  814. if self.family == 6 and hasattr(original_parent, 'primary_ip6'):
  815. if original_parent.primary_ip6_id == self.pk:
  816. is_primary = True
  817. if is_primary and (parent != original_parent):
  818. raise ValidationError(
  819. _("Cannot reassign IP address while it is designated as the primary IP for the parent object")
  820. )
  821. # Validate IP status selection
  822. if self.status == IPAddressStatusChoices.STATUS_SLAAC and self.family != 6:
  823. raise ValidationError({
  824. 'status': _("Only IPv6 addresses can be assigned SLAAC status")
  825. })
  826. def save(self, *args, **kwargs):
  827. # Force dns_name to lowercase
  828. self.dns_name = self.dns_name.lower()
  829. super().save(*args, **kwargs)
  830. def clone(self):
  831. attrs = super().clone()
  832. # Populate the address field with the next available IP (if any)
  833. if next_available_ip := self.get_next_available_ip():
  834. attrs['address'] = f'{next_available_ip}/{self.address.prefixlen}'
  835. return attrs
  836. def to_objectchange(self, action):
  837. objectchange = super().to_objectchange(action)
  838. objectchange.related_object = self.assigned_object
  839. return objectchange
  840. @property
  841. def family(self):
  842. if self.address:
  843. return self.address.version
  844. return None
  845. @property
  846. def is_oob_ip(self):
  847. if self.assigned_object:
  848. parent = getattr(self.assigned_object, 'parent_object', None)
  849. if hasattr(parent, 'oob_ip') and parent.oob_ip_id == self.pk:
  850. return True
  851. return False
  852. @property
  853. def is_primary_ip(self):
  854. if self.assigned_object:
  855. parent = getattr(self.assigned_object, 'parent_object', None)
  856. if self.family == 4 and hasattr(parent, 'primary_ip4') and parent.primary_ip4_id == self.pk:
  857. return True
  858. if self.family == 6 and hasattr(parent, 'primary_ip6') and parent.primary_ip6_id == self.pk:
  859. return True
  860. return False
  861. def _set_mask_length(self, value):
  862. """
  863. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  864. e.g. for bulk editing.
  865. """
  866. if self.address is not None:
  867. self.address.prefixlen = value
  868. mask_length = property(fset=_set_mask_length)
  869. def get_status_color(self):
  870. return IPAddressStatusChoices.colors.get(self.status)
  871. def get_role_color(self):
  872. return IPAddressRoleChoices.colors.get(self.role)