ip.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. import netaddr
  2. from django.conf import settings
  3. from django.contrib.contenttypes.fields import GenericForeignKey
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.core.exceptions import ValidationError
  6. from django.db import models
  7. from django.db.models import F
  8. from django.urls import reverse
  9. from dcim.models import Device
  10. from extras.utils import extras_features
  11. from netbox.models import OrganizationalModel, PrimaryModel
  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 utilities.querysets import RestrictedQuerySet
  19. from virtualization.models import VirtualMachine
  20. __all__ = (
  21. 'Aggregate',
  22. 'IPAddress',
  23. 'Prefix',
  24. 'RIR',
  25. 'Role',
  26. )
  27. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  28. class RIR(OrganizationalModel):
  29. """
  30. A Regional Internet Registry (RIR) is responsible for the allocation of a large portion of the global IP address
  31. space. This can be an organization like ARIN or RIPE, or a governing standard such as RFC 1918.
  32. """
  33. name = models.CharField(
  34. max_length=100,
  35. unique=True
  36. )
  37. slug = models.SlugField(
  38. max_length=100,
  39. unique=True
  40. )
  41. is_private = models.BooleanField(
  42. default=False,
  43. verbose_name='Private',
  44. help_text='IP space managed by this RIR is considered private'
  45. )
  46. description = models.CharField(
  47. max_length=200,
  48. blank=True
  49. )
  50. objects = RestrictedQuerySet.as_manager()
  51. csv_headers = ['name', 'slug', 'is_private', 'description']
  52. class Meta:
  53. ordering = ['name']
  54. verbose_name = 'RIR'
  55. verbose_name_plural = 'RIRs'
  56. def __str__(self):
  57. return self.name
  58. def get_absolute_url(self):
  59. return reverse('ipam:rir', args=[self.pk])
  60. def to_csv(self):
  61. return (
  62. self.name,
  63. self.slug,
  64. self.is_private,
  65. self.description,
  66. )
  67. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  68. class Aggregate(PrimaryModel):
  69. """
  70. An aggregate exists at the root level of the IP address space hierarchy in NetBox. Aggregates are used to organize
  71. the hierarchy and track the overall utilization of available address space. Each Aggregate is assigned to a RIR.
  72. """
  73. prefix = IPNetworkField()
  74. rir = models.ForeignKey(
  75. to='ipam.RIR',
  76. on_delete=models.PROTECT,
  77. related_name='aggregates',
  78. verbose_name='RIR'
  79. )
  80. tenant = models.ForeignKey(
  81. to='tenancy.Tenant',
  82. on_delete=models.PROTECT,
  83. related_name='aggregates',
  84. blank=True,
  85. null=True
  86. )
  87. date_added = models.DateField(
  88. blank=True,
  89. null=True
  90. )
  91. description = models.CharField(
  92. max_length=200,
  93. blank=True
  94. )
  95. objects = RestrictedQuerySet.as_manager()
  96. csv_headers = ['prefix', 'rir', 'tenant', 'date_added', 'description']
  97. clone_fields = [
  98. 'rir', 'tenant', 'date_added', 'description',
  99. ]
  100. class Meta:
  101. ordering = ('prefix', 'pk') # prefix may be non-unique
  102. def __str__(self):
  103. return str(self.prefix)
  104. def get_absolute_url(self):
  105. return reverse('ipam:aggregate', args=[self.pk])
  106. def clean(self):
  107. super().clean()
  108. if self.prefix:
  109. # Clear host bits from prefix
  110. self.prefix = self.prefix.cidr
  111. # /0 masks are not acceptable
  112. if self.prefix.prefixlen == 0:
  113. raise ValidationError({
  114. 'prefix': "Cannot create aggregate with /0 mask."
  115. })
  116. # Ensure that the aggregate being added is not covered by an existing aggregate
  117. covering_aggregates = Aggregate.objects.filter(
  118. prefix__net_contains_or_equals=str(self.prefix)
  119. )
  120. if self.pk:
  121. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  122. if covering_aggregates:
  123. raise ValidationError({
  124. 'prefix': "Aggregates cannot overlap. {} is already covered by an existing aggregate ({}).".format(
  125. self.prefix, covering_aggregates[0]
  126. )
  127. })
  128. # Ensure that the aggregate being added does not cover an existing aggregate
  129. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  130. if self.pk:
  131. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  132. if covered_aggregates:
  133. raise ValidationError({
  134. 'prefix': "Aggregates cannot overlap. {} covers an existing aggregate ({}).".format(
  135. self.prefix, covered_aggregates[0]
  136. )
  137. })
  138. def to_csv(self):
  139. return (
  140. self.prefix,
  141. self.rir.name,
  142. self.tenant.name if self.tenant else None,
  143. self.date_added,
  144. self.description,
  145. )
  146. @property
  147. def family(self):
  148. if self.prefix:
  149. return self.prefix.version
  150. return None
  151. def get_utilization(self):
  152. """
  153. Determine the prefix utilization of the aggregate and return it as a percentage.
  154. """
  155. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  156. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  157. return int(float(child_prefixes.size) / self.prefix.size * 100)
  158. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  159. class Role(OrganizationalModel):
  160. """
  161. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  162. "Management."
  163. """
  164. name = models.CharField(
  165. max_length=100,
  166. unique=True
  167. )
  168. slug = models.SlugField(
  169. max_length=100,
  170. unique=True
  171. )
  172. weight = models.PositiveSmallIntegerField(
  173. default=1000
  174. )
  175. description = models.CharField(
  176. max_length=200,
  177. blank=True,
  178. )
  179. objects = RestrictedQuerySet.as_manager()
  180. csv_headers = ['name', 'slug', 'weight', 'description']
  181. class Meta:
  182. ordering = ['weight', 'name']
  183. def __str__(self):
  184. return self.name
  185. def get_absolute_url(self):
  186. return reverse('ipam:role', args=[self.pk])
  187. def to_csv(self):
  188. return (
  189. self.name,
  190. self.slug,
  191. self.weight,
  192. self.description,
  193. )
  194. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  195. class Prefix(PrimaryModel):
  196. """
  197. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be assigned to Sites and
  198. VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role. A Prefix can also be
  199. assigned to a VLAN where appropriate.
  200. """
  201. prefix = IPNetworkField(
  202. help_text='IPv4 or IPv6 network with mask'
  203. )
  204. site = models.ForeignKey(
  205. to='dcim.Site',
  206. on_delete=models.PROTECT,
  207. related_name='prefixes',
  208. blank=True,
  209. null=True
  210. )
  211. vrf = models.ForeignKey(
  212. to='ipam.VRF',
  213. on_delete=models.PROTECT,
  214. related_name='prefixes',
  215. blank=True,
  216. null=True,
  217. verbose_name='VRF'
  218. )
  219. tenant = models.ForeignKey(
  220. to='tenancy.Tenant',
  221. on_delete=models.PROTECT,
  222. related_name='prefixes',
  223. blank=True,
  224. null=True
  225. )
  226. vlan = models.ForeignKey(
  227. to='ipam.VLAN',
  228. on_delete=models.PROTECT,
  229. related_name='prefixes',
  230. blank=True,
  231. null=True,
  232. verbose_name='VLAN'
  233. )
  234. status = models.CharField(
  235. max_length=50,
  236. choices=PrefixStatusChoices,
  237. default=PrefixStatusChoices.STATUS_ACTIVE,
  238. verbose_name='Status',
  239. help_text='Operational status of this prefix'
  240. )
  241. role = models.ForeignKey(
  242. to='ipam.Role',
  243. on_delete=models.SET_NULL,
  244. related_name='prefixes',
  245. blank=True,
  246. null=True,
  247. help_text='The primary function of this prefix'
  248. )
  249. is_pool = models.BooleanField(
  250. verbose_name='Is a pool',
  251. default=False,
  252. help_text='All IP addresses within this prefix are considered usable'
  253. )
  254. description = models.CharField(
  255. max_length=200,
  256. blank=True
  257. )
  258. # Cached depth & child counts
  259. _depth = models.PositiveSmallIntegerField(
  260. default=0,
  261. editable=False
  262. )
  263. _children = models.PositiveBigIntegerField(
  264. default=0,
  265. editable=False
  266. )
  267. objects = PrefixQuerySet.as_manager()
  268. csv_headers = [
  269. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan', 'status', 'role', 'is_pool', 'description',
  270. ]
  271. clone_fields = [
  272. 'site', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'description',
  273. ]
  274. class Meta:
  275. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  276. verbose_name_plural = 'prefixes'
  277. def __init__(self, *args, **kwargs):
  278. super().__init__(*args, **kwargs)
  279. # Cache the original prefix and VRF so we can check if they have changed on post_save
  280. self._prefix = self.prefix
  281. self._vrf = self.vrf
  282. def __str__(self):
  283. return str(self.prefix)
  284. def get_absolute_url(self):
  285. return reverse('ipam:prefix', args=[self.pk])
  286. def clean(self):
  287. super().clean()
  288. if self.prefix:
  289. # /0 masks are not acceptable
  290. if self.prefix.prefixlen == 0:
  291. raise ValidationError({
  292. 'prefix': "Cannot create prefix with /0 mask."
  293. })
  294. # Disallow host masks
  295. if self.prefix.version == 4 and self.prefix.prefixlen == 32:
  296. raise ValidationError({
  297. 'prefix': "Cannot create host addresses (/32) as prefixes. Create an IPv4 address instead."
  298. })
  299. elif self.prefix.version == 6 and self.prefix.prefixlen == 128:
  300. raise ValidationError({
  301. 'prefix': "Cannot create host addresses (/128) as prefixes. Create an IPv6 address instead."
  302. })
  303. # Enforce unique IP space (if applicable)
  304. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  305. duplicate_prefixes = self.get_duplicates()
  306. if duplicate_prefixes:
  307. raise ValidationError({
  308. 'prefix': "Duplicate prefix found in {}: {}".format(
  309. "VRF {}".format(self.vrf) if self.vrf else "global table",
  310. duplicate_prefixes.first(),
  311. )
  312. })
  313. def save(self, *args, **kwargs):
  314. if isinstance(self.prefix, netaddr.IPNetwork):
  315. # Clear host bits from prefix
  316. self.prefix = self.prefix.cidr
  317. super().save(*args, **kwargs)
  318. def to_csv(self):
  319. return (
  320. self.prefix,
  321. self.vrf.name if self.vrf else None,
  322. self.tenant.name if self.tenant else None,
  323. self.site.name if self.site else None,
  324. self.vlan.group.name if self.vlan and self.vlan.group else None,
  325. self.vlan.vid if self.vlan else None,
  326. self.get_status_display(),
  327. self.role.name if self.role else None,
  328. self.is_pool,
  329. self.description,
  330. )
  331. @property
  332. def family(self):
  333. if self.prefix:
  334. return self.prefix.version
  335. return None
  336. @property
  337. def depth(self):
  338. return self._depth
  339. @property
  340. def children(self):
  341. return self._children
  342. def _set_prefix_length(self, value):
  343. """
  344. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  345. e.g. for bulk editing.
  346. """
  347. if self.prefix is not None:
  348. self.prefix.prefixlen = value
  349. prefix_length = property(fset=_set_prefix_length)
  350. def get_status_class(self):
  351. return PrefixStatusChoices.CSS_CLASSES.get(self.status)
  352. def get_parents(self, include_self=False):
  353. """
  354. Return all containing Prefixes in the hierarchy.
  355. """
  356. lookup = 'net_contains_or_equals' if include_self else 'net_contains'
  357. return Prefix.objects.filter(**{
  358. 'vrf': self.vrf,
  359. f'prefix__{lookup}': self.prefix
  360. })
  361. def get_children(self, include_self=False):
  362. """
  363. Return all covered Prefixes in the hierarchy.
  364. """
  365. lookup = 'net_contained_or_equal' if include_self else 'net_contained'
  366. return Prefix.objects.filter(**{
  367. 'vrf': self.vrf,
  368. f'prefix__{lookup}': self.prefix
  369. })
  370. def get_duplicates(self):
  371. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  372. def get_child_prefixes(self):
  373. """
  374. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  375. Prefixes belonging to any VRF.
  376. """
  377. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  378. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  379. else:
  380. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  381. def get_child_ips(self):
  382. """
  383. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  384. child IPAddresses belonging to any VRF.
  385. """
  386. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  387. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  388. else:
  389. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  390. def get_available_prefixes(self):
  391. """
  392. Return all available Prefixes within this prefix as an IPSet.
  393. """
  394. prefix = netaddr.IPSet(self.prefix)
  395. child_prefixes = netaddr.IPSet([child.prefix for child in self.get_child_prefixes()])
  396. available_prefixes = prefix - child_prefixes
  397. return available_prefixes
  398. def get_available_ips(self):
  399. """
  400. Return all available IPs within this prefix as an IPSet.
  401. """
  402. prefix = netaddr.IPSet(self.prefix)
  403. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  404. available_ips = prefix - child_ips
  405. # IPv6, pool, or IPv4 /31 sets are fully usable
  406. if self.family == 6 or self.is_pool or self.prefix.prefixlen == 31:
  407. return available_ips
  408. # For "normal" IPv4 prefixes, omit first and last addresses
  409. available_ips -= netaddr.IPSet([
  410. netaddr.IPAddress(self.prefix.first),
  411. netaddr.IPAddress(self.prefix.last),
  412. ])
  413. return available_ips
  414. def get_first_available_prefix(self):
  415. """
  416. Return the first available child prefix within the prefix (or None).
  417. """
  418. available_prefixes = self.get_available_prefixes()
  419. if not available_prefixes:
  420. return None
  421. return available_prefixes.iter_cidrs()[0]
  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.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. return int(float(child_prefixes.size) / self.prefix.size * 100)
  442. else:
  443. # Compile an IPSet to avoid counting duplicate IPs
  444. child_count = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()]).size
  445. prefix_size = self.prefix.size
  446. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  447. prefix_size -= 2
  448. return int(float(child_count) / prefix_size * 100)
  449. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  450. class IPAddress(PrimaryModel):
  451. """
  452. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  453. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  454. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  455. Interfaces can have zero or more IPAddresses assigned to them.
  456. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  457. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  458. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  459. """
  460. address = IPAddressField(
  461. help_text='IPv4 or IPv6 address (with mask)'
  462. )
  463. vrf = models.ForeignKey(
  464. to='ipam.VRF',
  465. on_delete=models.PROTECT,
  466. related_name='ip_addresses',
  467. blank=True,
  468. null=True,
  469. verbose_name='VRF'
  470. )
  471. tenant = models.ForeignKey(
  472. to='tenancy.Tenant',
  473. on_delete=models.PROTECT,
  474. related_name='ip_addresses',
  475. blank=True,
  476. null=True
  477. )
  478. status = models.CharField(
  479. max_length=50,
  480. choices=IPAddressStatusChoices,
  481. default=IPAddressStatusChoices.STATUS_ACTIVE,
  482. help_text='The operational status of this IP'
  483. )
  484. role = models.CharField(
  485. max_length=50,
  486. choices=IPAddressRoleChoices,
  487. blank=True,
  488. help_text='The functional role of this IP'
  489. )
  490. assigned_object_type = models.ForeignKey(
  491. to=ContentType,
  492. limit_choices_to=IPADDRESS_ASSIGNMENT_MODELS,
  493. on_delete=models.PROTECT,
  494. related_name='+',
  495. blank=True,
  496. null=True
  497. )
  498. assigned_object_id = models.PositiveIntegerField(
  499. blank=True,
  500. null=True
  501. )
  502. assigned_object = GenericForeignKey(
  503. ct_field='assigned_object_type',
  504. fk_field='assigned_object_id'
  505. )
  506. nat_inside = models.OneToOneField(
  507. to='self',
  508. on_delete=models.SET_NULL,
  509. related_name='nat_outside',
  510. blank=True,
  511. null=True,
  512. verbose_name='NAT (Inside)',
  513. help_text='The IP for which this address is the "outside" IP'
  514. )
  515. dns_name = models.CharField(
  516. max_length=255,
  517. blank=True,
  518. validators=[DNSValidator],
  519. verbose_name='DNS Name',
  520. help_text='Hostname or FQDN (not case-sensitive)'
  521. )
  522. description = models.CharField(
  523. max_length=200,
  524. blank=True
  525. )
  526. objects = IPAddressManager()
  527. csv_headers = [
  528. 'address', 'vrf', 'tenant', 'status', 'role', 'assigned_object_type', 'assigned_object_id', 'is_primary',
  529. 'dns_name', 'description',
  530. ]
  531. clone_fields = [
  532. 'vrf', 'tenant', 'status', 'role', 'description',
  533. ]
  534. class Meta:
  535. ordering = ('address', 'pk') # address may be non-unique
  536. verbose_name = 'IP address'
  537. verbose_name_plural = 'IP addresses'
  538. def __str__(self):
  539. return str(self.address)
  540. def get_absolute_url(self):
  541. return reverse('ipam:ipaddress', args=[self.pk])
  542. def get_duplicates(self):
  543. return IPAddress.objects.filter(
  544. vrf=self.vrf,
  545. address__net_host=str(self.address.ip)
  546. ).exclude(pk=self.pk)
  547. def clean(self):
  548. super().clean()
  549. if self.address:
  550. # /0 masks are not acceptable
  551. if self.address.prefixlen == 0:
  552. raise ValidationError({
  553. 'address': "Cannot create IP address with /0 mask."
  554. })
  555. # Enforce unique IP space (if applicable)
  556. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  557. duplicate_ips = self.get_duplicates()
  558. if duplicate_ips and (
  559. self.role not in IPADDRESS_ROLES_NONUNIQUE or
  560. any(dip.role not in IPADDRESS_ROLES_NONUNIQUE for dip in duplicate_ips)
  561. ):
  562. raise ValidationError({
  563. 'address': "Duplicate IP address found in {}: {}".format(
  564. "VRF {}".format(self.vrf) if self.vrf else "global table",
  565. duplicate_ips.first(),
  566. )
  567. })
  568. # Check for primary IP assignment that doesn't match the assigned device/VM
  569. if self.pk:
  570. device = Device.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  571. if device:
  572. if getattr(self.assigned_object, 'device', None) != device:
  573. raise ValidationError({
  574. 'interface': f"IP address is primary for device {device} but not assigned to it!"
  575. })
  576. vm = VirtualMachine.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  577. if vm:
  578. if getattr(self.assigned_object, 'virtual_machine', None) != vm:
  579. raise ValidationError({
  580. 'vminterface': f"IP address is primary for virtual machine {vm} but not assigned to it!"
  581. })
  582. # Validate IP status selection
  583. if self.status == IPAddressStatusChoices.STATUS_SLAAC and self.family != 6:
  584. raise ValidationError({
  585. 'status': "Only IPv6 addresses can be assigned SLAAC status"
  586. })
  587. def save(self, *args, **kwargs):
  588. # Force dns_name to lowercase
  589. self.dns_name = self.dns_name.lower()
  590. super().save(*args, **kwargs)
  591. def to_objectchange(self, action):
  592. # Annotate the assigned object, if any
  593. return super().to_objectchange(action, related_object=self.assigned_object)
  594. def to_csv(self):
  595. # Determine if this IP is primary for a Device
  596. is_primary = False
  597. if self.address.version == 4 and getattr(self, 'primary_ip4_for', False):
  598. is_primary = True
  599. elif self.address.version == 6 and getattr(self, 'primary_ip6_for', False):
  600. is_primary = True
  601. obj_type = None
  602. if self.assigned_object_type:
  603. obj_type = f'{self.assigned_object_type.app_label}.{self.assigned_object_type.model}'
  604. return (
  605. self.address,
  606. self.vrf.name if self.vrf else None,
  607. self.tenant.name if self.tenant else None,
  608. self.get_status_display(),
  609. self.get_role_display(),
  610. obj_type,
  611. self.assigned_object_id,
  612. is_primary,
  613. self.dns_name,
  614. self.description,
  615. )
  616. @property
  617. def family(self):
  618. if self.address:
  619. return self.address.version
  620. return None
  621. def _set_mask_length(self, value):
  622. """
  623. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  624. e.g. for bulk editing.
  625. """
  626. if self.address is not None:
  627. self.address.prefixlen = value
  628. mask_length = property(fset=_set_mask_length)
  629. def get_status_class(self):
  630. return IPAddressStatusChoices.CSS_CLASSES.get(self.status)
  631. def get_role_class(self):
  632. return IPAddressRoleChoices.CSS_CLASSES.get(self.role)