ip.py 32 KB

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