ip.py 31 KB

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