ip.py 35 KB

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