ip.py 30 KB

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