ip.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. mark_utilized = models.BooleanField(
  255. default=False,
  256. help_text="Treat as 100% utilized"
  257. )
  258. description = models.CharField(
  259. max_length=200,
  260. blank=True
  261. )
  262. objects = PrefixQuerySet.as_manager()
  263. csv_headers = [
  264. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized',
  265. 'description',
  266. ]
  267. clone_fields = [
  268. 'site', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'description',
  269. ]
  270. class Meta:
  271. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  272. verbose_name_plural = 'prefixes'
  273. def __str__(self):
  274. return str(self.prefix)
  275. def get_absolute_url(self):
  276. return reverse('ipam:prefix', args=[self.pk])
  277. def clean(self):
  278. super().clean()
  279. if self.prefix:
  280. # /0 masks are not acceptable
  281. if self.prefix.prefixlen == 0:
  282. raise ValidationError({
  283. 'prefix': "Cannot create prefix with /0 mask."
  284. })
  285. # Disallow host masks
  286. if self.prefix.version == 4 and self.prefix.prefixlen == 32:
  287. raise ValidationError({
  288. 'prefix': "Cannot create host addresses (/32) as prefixes. Create an IPv4 address instead."
  289. })
  290. elif self.prefix.version == 6 and self.prefix.prefixlen == 128:
  291. raise ValidationError({
  292. 'prefix': "Cannot create host addresses (/128) as prefixes. Create an IPv6 address instead."
  293. })
  294. # Enforce unique IP space (if applicable)
  295. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  296. duplicate_prefixes = self.get_duplicates()
  297. if duplicate_prefixes:
  298. raise ValidationError({
  299. 'prefix': "Duplicate prefix found in {}: {}".format(
  300. "VRF {}".format(self.vrf) if self.vrf else "global table",
  301. duplicate_prefixes.first(),
  302. )
  303. })
  304. def save(self, *args, **kwargs):
  305. if isinstance(self.prefix, netaddr.IPNetwork):
  306. # Clear host bits from prefix
  307. self.prefix = self.prefix.cidr
  308. super().save(*args, **kwargs)
  309. def to_csv(self):
  310. return (
  311. self.prefix,
  312. self.vrf.name if self.vrf else None,
  313. self.tenant.name if self.tenant else None,
  314. self.site.name if self.site else None,
  315. self.vlan.group.name if self.vlan and self.vlan.group else None,
  316. self.vlan.vid if self.vlan else None,
  317. self.get_status_display(),
  318. self.role.name if self.role else None,
  319. self.is_pool,
  320. self.mark_utilized,
  321. self.description,
  322. )
  323. @property
  324. def family(self):
  325. if self.prefix:
  326. return self.prefix.version
  327. return None
  328. def _set_prefix_length(self, value):
  329. """
  330. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  331. e.g. for bulk editing.
  332. """
  333. if self.prefix is not None:
  334. self.prefix.prefixlen = value
  335. prefix_length = property(fset=_set_prefix_length)
  336. def get_status_class(self):
  337. return PrefixStatusChoices.CSS_CLASSES.get(self.status)
  338. def get_duplicates(self):
  339. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  340. def get_child_prefixes(self):
  341. """
  342. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  343. Prefixes belonging to any VRF.
  344. """
  345. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  346. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  347. else:
  348. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  349. def get_child_ips(self):
  350. """
  351. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  352. child IPAddresses belonging to any VRF.
  353. """
  354. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  355. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  356. else:
  357. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  358. def get_available_prefixes(self):
  359. """
  360. Return all available Prefixes within this prefix as an IPSet.
  361. """
  362. prefix = netaddr.IPSet(self.prefix)
  363. child_prefixes = netaddr.IPSet([child.prefix for child in self.get_child_prefixes()])
  364. available_prefixes = prefix - child_prefixes
  365. return available_prefixes
  366. def get_available_ips(self):
  367. """
  368. Return all available IPs within this prefix as an IPSet.
  369. """
  370. if self.mark_utilized:
  371. return list()
  372. prefix = netaddr.IPSet(self.prefix)
  373. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  374. available_ips = prefix - child_ips
  375. # IPv6, pool, or IPv4 /31 sets are fully usable
  376. if self.family == 6 or self.is_pool or self.prefix.prefixlen == 31:
  377. return available_ips
  378. # For "normal" IPv4 prefixes, omit first and last addresses
  379. available_ips -= netaddr.IPSet([
  380. netaddr.IPAddress(self.prefix.first),
  381. netaddr.IPAddress(self.prefix.last),
  382. ])
  383. return available_ips
  384. def get_first_available_prefix(self):
  385. """
  386. Return the first available child prefix within the prefix (or None).
  387. """
  388. available_prefixes = self.get_available_prefixes()
  389. if not available_prefixes:
  390. return None
  391. return available_prefixes.iter_cidrs()[0]
  392. def get_first_available_ip(self):
  393. """
  394. Return the first available IP within the prefix (or None).
  395. """
  396. available_ips = self.get_available_ips()
  397. if not available_ips:
  398. return None
  399. return '{}/{}'.format(next(available_ips.__iter__()), self.prefix.prefixlen)
  400. def get_utilization(self):
  401. """
  402. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  403. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  404. """
  405. if self.mark_utilized:
  406. return 100
  407. if self.status == PrefixStatusChoices.STATUS_CONTAINER:
  408. queryset = Prefix.objects.filter(
  409. prefix__net_contained=str(self.prefix),
  410. vrf=self.vrf
  411. )
  412. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  413. return int(float(child_prefixes.size) / self.prefix.size * 100)
  414. else:
  415. # Compile an IPSet to avoid counting duplicate IPs
  416. child_count = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()]).size
  417. prefix_size = self.prefix.size
  418. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  419. prefix_size -= 2
  420. return int(float(child_count) / prefix_size * 100)
  421. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  422. class IPAddress(PrimaryModel):
  423. """
  424. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  425. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  426. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  427. Interfaces can have zero or more IPAddresses assigned to them.
  428. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  429. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  430. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  431. """
  432. address = IPAddressField(
  433. help_text='IPv4 or IPv6 address (with mask)'
  434. )
  435. vrf = models.ForeignKey(
  436. to='ipam.VRF',
  437. on_delete=models.PROTECT,
  438. related_name='ip_addresses',
  439. blank=True,
  440. null=True,
  441. verbose_name='VRF'
  442. )
  443. tenant = models.ForeignKey(
  444. to='tenancy.Tenant',
  445. on_delete=models.PROTECT,
  446. related_name='ip_addresses',
  447. blank=True,
  448. null=True
  449. )
  450. status = models.CharField(
  451. max_length=50,
  452. choices=IPAddressStatusChoices,
  453. default=IPAddressStatusChoices.STATUS_ACTIVE,
  454. help_text='The operational status of this IP'
  455. )
  456. role = models.CharField(
  457. max_length=50,
  458. choices=IPAddressRoleChoices,
  459. blank=True,
  460. help_text='The functional role of this IP'
  461. )
  462. assigned_object_type = models.ForeignKey(
  463. to=ContentType,
  464. limit_choices_to=IPADDRESS_ASSIGNMENT_MODELS,
  465. on_delete=models.PROTECT,
  466. related_name='+',
  467. blank=True,
  468. null=True
  469. )
  470. assigned_object_id = models.PositiveIntegerField(
  471. blank=True,
  472. null=True
  473. )
  474. assigned_object = GenericForeignKey(
  475. ct_field='assigned_object_type',
  476. fk_field='assigned_object_id'
  477. )
  478. nat_inside = models.OneToOneField(
  479. to='self',
  480. on_delete=models.SET_NULL,
  481. related_name='nat_outside',
  482. blank=True,
  483. null=True,
  484. verbose_name='NAT (Inside)',
  485. help_text='The IP for which this address is the "outside" IP'
  486. )
  487. dns_name = models.CharField(
  488. max_length=255,
  489. blank=True,
  490. validators=[DNSValidator],
  491. verbose_name='DNS Name',
  492. help_text='Hostname or FQDN (not case-sensitive)'
  493. )
  494. description = models.CharField(
  495. max_length=200,
  496. blank=True
  497. )
  498. objects = IPAddressManager()
  499. csv_headers = [
  500. 'address', 'vrf', 'tenant', 'status', 'role', 'assigned_object_type', 'assigned_object_id', 'is_primary',
  501. 'dns_name', 'description',
  502. ]
  503. clone_fields = [
  504. 'vrf', 'tenant', 'status', 'role', 'description',
  505. ]
  506. class Meta:
  507. ordering = ('address', 'pk') # address may be non-unique
  508. verbose_name = 'IP address'
  509. verbose_name_plural = 'IP addresses'
  510. def __str__(self):
  511. return str(self.address)
  512. def get_absolute_url(self):
  513. return reverse('ipam:ipaddress', args=[self.pk])
  514. def get_duplicates(self):
  515. return IPAddress.objects.filter(
  516. vrf=self.vrf,
  517. address__net_host=str(self.address.ip)
  518. ).exclude(pk=self.pk)
  519. def clean(self):
  520. super().clean()
  521. if self.address:
  522. # /0 masks are not acceptable
  523. if self.address.prefixlen == 0:
  524. raise ValidationError({
  525. 'address': "Cannot create IP address with /0 mask."
  526. })
  527. # Enforce unique IP space (if applicable)
  528. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  529. duplicate_ips = self.get_duplicates()
  530. if duplicate_ips and (
  531. self.role not in IPADDRESS_ROLES_NONUNIQUE or
  532. any(dip.role not in IPADDRESS_ROLES_NONUNIQUE for dip in duplicate_ips)
  533. ):
  534. raise ValidationError({
  535. 'address': "Duplicate IP address found in {}: {}".format(
  536. "VRF {}".format(self.vrf) if self.vrf else "global table",
  537. duplicate_ips.first(),
  538. )
  539. })
  540. # Check for primary IP assignment that doesn't match the assigned device/VM
  541. if self.pk:
  542. device = Device.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  543. if device:
  544. if getattr(self.assigned_object, 'device', None) != device:
  545. raise ValidationError({
  546. 'interface': f"IP address is primary for device {device} but not assigned to it!"
  547. })
  548. vm = VirtualMachine.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  549. if vm:
  550. if getattr(self.assigned_object, 'virtual_machine', None) != vm:
  551. raise ValidationError({
  552. 'vminterface': f"IP address is primary for virtual machine {vm} but not assigned to it!"
  553. })
  554. # Validate IP status selection
  555. if self.status == IPAddressStatusChoices.STATUS_SLAAC and self.family != 6:
  556. raise ValidationError({
  557. 'status': "Only IPv6 addresses can be assigned SLAAC status"
  558. })
  559. def save(self, *args, **kwargs):
  560. # Force dns_name to lowercase
  561. self.dns_name = self.dns_name.lower()
  562. super().save(*args, **kwargs)
  563. def to_objectchange(self, action):
  564. # Annotate the assigned object, if any
  565. return super().to_objectchange(action, related_object=self.assigned_object)
  566. def to_csv(self):
  567. # Determine if this IP is primary for a Device
  568. is_primary = False
  569. if self.address.version == 4 and getattr(self, 'primary_ip4_for', False):
  570. is_primary = True
  571. elif self.address.version == 6 and getattr(self, 'primary_ip6_for', False):
  572. is_primary = True
  573. obj_type = None
  574. if self.assigned_object_type:
  575. obj_type = f'{self.assigned_object_type.app_label}.{self.assigned_object_type.model}'
  576. return (
  577. self.address,
  578. self.vrf.name if self.vrf else None,
  579. self.tenant.name if self.tenant else None,
  580. self.get_status_display(),
  581. self.get_role_display(),
  582. obj_type,
  583. self.assigned_object_id,
  584. is_primary,
  585. self.dns_name,
  586. self.description,
  587. )
  588. @property
  589. def family(self):
  590. if self.address:
  591. return self.address.version
  592. return None
  593. def _set_mask_length(self, value):
  594. """
  595. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  596. e.g. for bulk editing.
  597. """
  598. if self.address is not None:
  599. self.address.prefixlen = value
  600. mask_length = property(fset=_set_mask_length)
  601. def get_status_class(self):
  602. return IPAddressStatusChoices.CSS_CLASSES.get(self.status)
  603. def get_role_class(self):
  604. return IPAddressRoleChoices.CSS_CLASSES.get(self.role)