2
0

ip.py 35 KB

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