ip.py 30 KB

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