ip.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. utilization = int(float(child_prefixes.size) / self.prefix.size * 100)
  158. return min(utilization, 100)
  159. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  160. class Role(OrganizationalModel):
  161. """
  162. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  163. "Management."
  164. """
  165. name = models.CharField(
  166. max_length=100,
  167. unique=True
  168. )
  169. slug = models.SlugField(
  170. max_length=100,
  171. unique=True
  172. )
  173. weight = models.PositiveSmallIntegerField(
  174. default=1000
  175. )
  176. description = models.CharField(
  177. max_length=200,
  178. blank=True,
  179. )
  180. objects = RestrictedQuerySet.as_manager()
  181. csv_headers = ['name', 'slug', 'weight', 'description']
  182. class Meta:
  183. ordering = ['weight', 'name']
  184. def __str__(self):
  185. return self.name
  186. def get_absolute_url(self):
  187. return reverse('ipam:role', args=[self.pk])
  188. def to_csv(self):
  189. return (
  190. self.name,
  191. self.slug,
  192. self.weight,
  193. self.description,
  194. )
  195. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  196. class Prefix(PrimaryModel):
  197. """
  198. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be assigned to Sites and
  199. VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role. A Prefix can also be
  200. assigned to a VLAN where appropriate.
  201. """
  202. prefix = IPNetworkField(
  203. help_text='IPv4 or IPv6 network with mask'
  204. )
  205. site = models.ForeignKey(
  206. to='dcim.Site',
  207. on_delete=models.PROTECT,
  208. related_name='prefixes',
  209. blank=True,
  210. null=True
  211. )
  212. vrf = models.ForeignKey(
  213. to='ipam.VRF',
  214. on_delete=models.PROTECT,
  215. related_name='prefixes',
  216. blank=True,
  217. null=True,
  218. verbose_name='VRF'
  219. )
  220. tenant = models.ForeignKey(
  221. to='tenancy.Tenant',
  222. on_delete=models.PROTECT,
  223. related_name='prefixes',
  224. blank=True,
  225. null=True
  226. )
  227. vlan = models.ForeignKey(
  228. to='ipam.VLAN',
  229. on_delete=models.PROTECT,
  230. related_name='prefixes',
  231. blank=True,
  232. null=True,
  233. verbose_name='VLAN'
  234. )
  235. status = models.CharField(
  236. max_length=50,
  237. choices=PrefixStatusChoices,
  238. default=PrefixStatusChoices.STATUS_ACTIVE,
  239. verbose_name='Status',
  240. help_text='Operational status of this prefix'
  241. )
  242. role = models.ForeignKey(
  243. to='ipam.Role',
  244. on_delete=models.SET_NULL,
  245. related_name='prefixes',
  246. blank=True,
  247. null=True,
  248. help_text='The primary function of this prefix'
  249. )
  250. is_pool = models.BooleanField(
  251. verbose_name='Is a pool',
  252. default=False,
  253. help_text='All IP addresses within this prefix are considered usable'
  254. )
  255. description = models.CharField(
  256. max_length=200,
  257. blank=True
  258. )
  259. # Cached depth & child counts
  260. _depth = models.PositiveSmallIntegerField(
  261. default=0,
  262. editable=False
  263. )
  264. _children = models.PositiveBigIntegerField(
  265. default=0,
  266. editable=False
  267. )
  268. objects = PrefixQuerySet.as_manager()
  269. csv_headers = [
  270. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan', 'status', 'role', 'is_pool', 'description',
  271. ]
  272. clone_fields = [
  273. 'site', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'description',
  274. ]
  275. class Meta:
  276. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  277. verbose_name_plural = 'prefixes'
  278. def __init__(self, *args, **kwargs):
  279. super().__init__(*args, **kwargs)
  280. # Cache the original prefix and VRF so we can check if they have changed on post_save
  281. self._prefix = self.prefix
  282. self._vrf = self.vrf
  283. def __str__(self):
  284. return str(self.prefix)
  285. def get_absolute_url(self):
  286. return reverse('ipam:prefix', args=[self.pk])
  287. def clean(self):
  288. super().clean()
  289. if self.prefix:
  290. # /0 masks are not acceptable
  291. if self.prefix.prefixlen == 0:
  292. raise ValidationError({
  293. 'prefix': "Cannot create prefix with /0 mask."
  294. })
  295. # Enforce unique IP space (if applicable)
  296. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  297. duplicate_prefixes = self.get_duplicates()
  298. if duplicate_prefixes:
  299. raise ValidationError({
  300. 'prefix': "Duplicate prefix found in {}: {}".format(
  301. "VRF {}".format(self.vrf) if self.vrf else "global table",
  302. duplicate_prefixes.first(),
  303. )
  304. })
  305. def save(self, *args, **kwargs):
  306. if isinstance(self.prefix, netaddr.IPNetwork):
  307. # Clear host bits from prefix
  308. self.prefix = self.prefix.cidr
  309. super().save(*args, **kwargs)
  310. def to_csv(self):
  311. return (
  312. self.prefix,
  313. self.vrf.name if self.vrf else None,
  314. self.tenant.name if self.tenant else None,
  315. self.site.name if self.site else None,
  316. self.vlan.group.name if self.vlan and self.vlan.group else None,
  317. self.vlan.vid if self.vlan else None,
  318. self.get_status_display(),
  319. self.role.name if self.role else None,
  320. self.is_pool,
  321. self.description,
  322. )
  323. @property
  324. def family(self):
  325. if self.prefix:
  326. return self.prefix.version
  327. return None
  328. @property
  329. def depth(self):
  330. return self._depth
  331. @property
  332. def children(self):
  333. return self._children
  334. def _set_prefix_length(self, value):
  335. """
  336. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  337. e.g. for bulk editing.
  338. """
  339. if self.prefix is not None:
  340. self.prefix.prefixlen = value
  341. prefix_length = property(fset=_set_prefix_length)
  342. def get_status_class(self):
  343. return PrefixStatusChoices.CSS_CLASSES.get(self.status)
  344. def get_parents(self, include_self=False):
  345. """
  346. Return all containing Prefixes in the hierarchy.
  347. """
  348. lookup = 'net_contains_or_equals' if include_self else 'net_contains'
  349. return Prefix.objects.filter(**{
  350. 'vrf': self.vrf,
  351. f'prefix__{lookup}': self.prefix
  352. })
  353. def get_children(self, include_self=False):
  354. """
  355. Return all covered Prefixes in the hierarchy.
  356. """
  357. lookup = 'net_contained_or_equal' if include_self else 'net_contained'
  358. return Prefix.objects.filter(**{
  359. 'vrf': self.vrf,
  360. f'prefix__{lookup}': self.prefix
  361. })
  362. def get_duplicates(self):
  363. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  364. def get_child_prefixes(self):
  365. """
  366. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  367. Prefixes belonging to any VRF.
  368. """
  369. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  370. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  371. else:
  372. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  373. def get_child_ips(self):
  374. """
  375. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  376. child IPAddresses belonging to any VRF.
  377. """
  378. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  379. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  380. else:
  381. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  382. def get_available_prefixes(self):
  383. """
  384. Return all available Prefixes within this prefix as an IPSet.
  385. """
  386. prefix = netaddr.IPSet(self.prefix)
  387. child_prefixes = netaddr.IPSet([child.prefix for child in self.get_child_prefixes()])
  388. available_prefixes = prefix - child_prefixes
  389. return available_prefixes
  390. def get_available_ips(self):
  391. """
  392. Return all available IPs within this prefix as an IPSet.
  393. """
  394. prefix = netaddr.IPSet(self.prefix)
  395. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  396. available_ips = prefix - child_ips
  397. # IPv6, pool, or IPv4 /31-/32 sets are fully usable
  398. if self.family == 6 or self.is_pool or (self.family == 4 and self.prefix.prefixlen >= 31):
  399. return available_ips
  400. # For "normal" IPv4 prefixes, omit first and last addresses
  401. available_ips -= netaddr.IPSet([
  402. netaddr.IPAddress(self.prefix.first),
  403. netaddr.IPAddress(self.prefix.last),
  404. ])
  405. return available_ips
  406. def get_first_available_prefix(self):
  407. """
  408. Return the first available child prefix within the prefix (or None).
  409. """
  410. available_prefixes = self.get_available_prefixes()
  411. if not available_prefixes:
  412. return None
  413. return available_prefixes.iter_cidrs()[0]
  414. def get_first_available_ip(self):
  415. """
  416. Return the first available IP within the prefix (or None).
  417. """
  418. available_ips = self.get_available_ips()
  419. if not available_ips:
  420. return None
  421. return '{}/{}'.format(next(available_ips.__iter__()), self.prefix.prefixlen)
  422. def get_utilization(self):
  423. """
  424. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  425. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  426. """
  427. if self.status == PrefixStatusChoices.STATUS_CONTAINER:
  428. queryset = Prefix.objects.filter(
  429. prefix__net_contained=str(self.prefix),
  430. vrf=self.vrf
  431. )
  432. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  433. utilization = int(float(child_prefixes.size) / self.prefix.size * 100)
  434. else:
  435. # Compile an IPSet to avoid counting duplicate IPs
  436. child_count = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()]).size
  437. prefix_size = self.prefix.size
  438. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  439. prefix_size -= 2
  440. utilization = int(float(child_count) / prefix_size * 100)
  441. return min(utilization, 100)
  442. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  443. class IPAddress(PrimaryModel):
  444. """
  445. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  446. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  447. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  448. Interfaces can have zero or more IPAddresses assigned to them.
  449. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  450. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  451. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  452. """
  453. address = IPAddressField(
  454. help_text='IPv4 or IPv6 address (with mask)'
  455. )
  456. vrf = models.ForeignKey(
  457. to='ipam.VRF',
  458. on_delete=models.PROTECT,
  459. related_name='ip_addresses',
  460. blank=True,
  461. null=True,
  462. verbose_name='VRF'
  463. )
  464. tenant = models.ForeignKey(
  465. to='tenancy.Tenant',
  466. on_delete=models.PROTECT,
  467. related_name='ip_addresses',
  468. blank=True,
  469. null=True
  470. )
  471. status = models.CharField(
  472. max_length=50,
  473. choices=IPAddressStatusChoices,
  474. default=IPAddressStatusChoices.STATUS_ACTIVE,
  475. help_text='The operational status of this IP'
  476. )
  477. role = models.CharField(
  478. max_length=50,
  479. choices=IPAddressRoleChoices,
  480. blank=True,
  481. help_text='The functional role of this IP'
  482. )
  483. assigned_object_type = models.ForeignKey(
  484. to=ContentType,
  485. limit_choices_to=IPADDRESS_ASSIGNMENT_MODELS,
  486. on_delete=models.PROTECT,
  487. related_name='+',
  488. blank=True,
  489. null=True
  490. )
  491. assigned_object_id = models.PositiveIntegerField(
  492. blank=True,
  493. null=True
  494. )
  495. assigned_object = GenericForeignKey(
  496. ct_field='assigned_object_type',
  497. fk_field='assigned_object_id'
  498. )
  499. nat_inside = models.OneToOneField(
  500. to='self',
  501. on_delete=models.SET_NULL,
  502. related_name='nat_outside',
  503. blank=True,
  504. null=True,
  505. verbose_name='NAT (Inside)',
  506. help_text='The IP for which this address is the "outside" IP'
  507. )
  508. dns_name = models.CharField(
  509. max_length=255,
  510. blank=True,
  511. validators=[DNSValidator],
  512. verbose_name='DNS Name',
  513. help_text='Hostname or FQDN (not case-sensitive)'
  514. )
  515. description = models.CharField(
  516. max_length=200,
  517. blank=True
  518. )
  519. objects = IPAddressManager()
  520. csv_headers = [
  521. 'address', 'vrf', 'tenant', 'status', 'role', 'assigned_object_type', 'assigned_object_id', 'is_primary',
  522. 'dns_name', 'description',
  523. ]
  524. clone_fields = [
  525. 'vrf', 'tenant', 'status', 'role', 'description',
  526. ]
  527. class Meta:
  528. ordering = ('address', 'pk') # address may be non-unique
  529. verbose_name = 'IP address'
  530. verbose_name_plural = 'IP addresses'
  531. def __str__(self):
  532. return str(self.address)
  533. def get_absolute_url(self):
  534. return reverse('ipam:ipaddress', args=[self.pk])
  535. def get_duplicates(self):
  536. return IPAddress.objects.filter(
  537. vrf=self.vrf,
  538. address__net_host=str(self.address.ip)
  539. ).exclude(pk=self.pk)
  540. def clean(self):
  541. super().clean()
  542. if self.address:
  543. # /0 masks are not acceptable
  544. if self.address.prefixlen == 0:
  545. raise ValidationError({
  546. 'address': "Cannot create IP address with /0 mask."
  547. })
  548. # Enforce unique IP space (if applicable)
  549. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  550. duplicate_ips = self.get_duplicates()
  551. if duplicate_ips and (
  552. self.role not in IPADDRESS_ROLES_NONUNIQUE or
  553. any(dip.role not in IPADDRESS_ROLES_NONUNIQUE for dip in duplicate_ips)
  554. ):
  555. raise ValidationError({
  556. 'address': "Duplicate IP address found in {}: {}".format(
  557. "VRF {}".format(self.vrf) if self.vrf else "global table",
  558. duplicate_ips.first(),
  559. )
  560. })
  561. # Check for primary IP assignment that doesn't match the assigned device/VM
  562. if self.pk:
  563. for cls, attr in ((Device, 'device'), (VirtualMachine, 'virtual_machine')):
  564. parent = cls.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  565. if parent and getattr(self.assigned_object, attr) != parent:
  566. # Check for a NAT relationship
  567. if not self.nat_inside or getattr(self.nat_inside.assigned_object, attr) != parent:
  568. raise ValidationError({
  569. 'interface': f"IP address is primary for {cls._meta.model_name} {parent} but "
  570. f"not assigned to it!"
  571. })
  572. # Validate IP status selection
  573. if self.status == IPAddressStatusChoices.STATUS_SLAAC and self.family != 6:
  574. raise ValidationError({
  575. 'status': "Only IPv6 addresses can be assigned SLAAC status"
  576. })
  577. def save(self, *args, **kwargs):
  578. # Force dns_name to lowercase
  579. self.dns_name = self.dns_name.lower()
  580. super().save(*args, **kwargs)
  581. def to_objectchange(self, action):
  582. # Annotate the assigned object, if any
  583. return super().to_objectchange(action, related_object=self.assigned_object)
  584. def to_csv(self):
  585. # Determine if this IP is primary for a Device
  586. is_primary = False
  587. if self.address.version == 4 and getattr(self, 'primary_ip4_for', False):
  588. is_primary = True
  589. elif self.address.version == 6 and getattr(self, 'primary_ip6_for', False):
  590. is_primary = True
  591. obj_type = None
  592. if self.assigned_object_type:
  593. obj_type = f'{self.assigned_object_type.app_label}.{self.assigned_object_type.model}'
  594. return (
  595. self.address,
  596. self.vrf.name if self.vrf else None,
  597. self.tenant.name if self.tenant else None,
  598. self.get_status_display(),
  599. self.get_role_display(),
  600. obj_type,
  601. self.assigned_object_id,
  602. is_primary,
  603. self.dns_name,
  604. self.description,
  605. )
  606. @property
  607. def family(self):
  608. if self.address:
  609. return self.address.version
  610. return None
  611. def _set_mask_length(self, value):
  612. """
  613. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  614. e.g. for bulk editing.
  615. """
  616. if self.address is not None:
  617. self.address.prefixlen = value
  618. mask_length = property(fset=_set_mask_length)
  619. def get_status_class(self):
  620. return IPAddressStatusChoices.CSS_CLASSES.get(self.status)
  621. def get_role_class(self):
  622. return IPAddressRoleChoices.CSS_CLASSES.get(self.role)