models.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. import netaddr
  2. from django.conf import settings
  3. from django.contrib.contenttypes.fields import GenericRelation
  4. from django.core.exceptions import ValidationError, ObjectDoesNotExist
  5. from django.core.validators import MaxValueValidator, MinValueValidator
  6. from django.db import models
  7. from django.db.models import F, Q
  8. from django.urls import reverse
  9. from taggit.managers import TaggableManager
  10. from dcim.models import Device, Interface
  11. from extras.models import CustomFieldModel, ObjectChange, TaggedItem
  12. from extras.utils import extras_features
  13. from utilities.models import ChangeLoggedModel
  14. from utilities.utils import serialize_object
  15. from virtualization.models import VirtualMachine
  16. from .choices import *
  17. from .constants import *
  18. from .fields import IPNetworkField, IPAddressField
  19. from .managers import IPAddressManager
  20. from .querysets import PrefixQuerySet
  21. from .validators import DNSValidator
  22. __all__ = (
  23. 'Aggregate',
  24. 'IPAddress',
  25. 'Prefix',
  26. 'RIR',
  27. 'Role',
  28. 'Service',
  29. 'VLAN',
  30. 'VLANGroup',
  31. 'VRF',
  32. )
  33. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  34. class VRF(ChangeLoggedModel, CustomFieldModel):
  35. """
  36. A virtual routing and forwarding (VRF) table represents a discrete layer three forwarding domain (e.g. a routing
  37. table). Prefixes and IPAddresses can optionally be assigned to VRFs. (Prefixes and IPAddresses not assigned to a VRF
  38. are said to exist in the "global" table.)
  39. """
  40. name = models.CharField(
  41. max_length=50
  42. )
  43. rd = models.CharField(
  44. max_length=VRF_RD_MAX_LENGTH,
  45. unique=True,
  46. blank=True,
  47. null=True,
  48. verbose_name='Route distinguisher'
  49. )
  50. tenant = models.ForeignKey(
  51. to='tenancy.Tenant',
  52. on_delete=models.PROTECT,
  53. related_name='vrfs',
  54. blank=True,
  55. null=True
  56. )
  57. enforce_unique = models.BooleanField(
  58. default=True,
  59. verbose_name='Enforce unique space',
  60. help_text='Prevent duplicate prefixes/IP addresses within this VRF'
  61. )
  62. description = models.CharField(
  63. max_length=200,
  64. blank=True
  65. )
  66. custom_field_values = GenericRelation(
  67. to='extras.CustomFieldValue',
  68. content_type_field='obj_type',
  69. object_id_field='obj_id'
  70. )
  71. tags = TaggableManager(through=TaggedItem)
  72. csv_headers = ['name', 'rd', 'tenant', 'enforce_unique', 'description']
  73. clone_fields = [
  74. 'tenant', 'enforce_unique', 'description',
  75. ]
  76. class Meta:
  77. ordering = ('name', 'rd', 'pk') # (name, rd) may be non-unique
  78. verbose_name = 'VRF'
  79. verbose_name_plural = 'VRFs'
  80. def __str__(self):
  81. return self.display_name or super().__str__()
  82. def get_absolute_url(self):
  83. return reverse('ipam:vrf', args=[self.pk])
  84. def to_csv(self):
  85. return (
  86. self.name,
  87. self.rd,
  88. self.tenant.name if self.tenant else None,
  89. self.enforce_unique,
  90. self.description,
  91. )
  92. @property
  93. def display_name(self):
  94. if self.rd:
  95. return "{} ({})".format(self.name, self.rd)
  96. return self.name
  97. class RIR(ChangeLoggedModel):
  98. """
  99. A Regional Internet Registry (RIR) is responsible for the allocation of a large portion of the global IP address
  100. space. This can be an organization like ARIN or RIPE, or a governing standard such as RFC 1918.
  101. """
  102. name = models.CharField(
  103. max_length=50,
  104. unique=True
  105. )
  106. slug = models.SlugField(
  107. unique=True
  108. )
  109. is_private = models.BooleanField(
  110. default=False,
  111. verbose_name='Private',
  112. help_text='IP space managed by this RIR is considered private'
  113. )
  114. description = models.CharField(
  115. max_length=200,
  116. blank=True
  117. )
  118. csv_headers = ['name', 'slug', 'is_private', 'description']
  119. class Meta:
  120. ordering = ['name']
  121. verbose_name = 'RIR'
  122. verbose_name_plural = 'RIRs'
  123. def __str__(self):
  124. return self.name
  125. def get_absolute_url(self):
  126. return "{}?rir={}".format(reverse('ipam:aggregate_list'), self.slug)
  127. def to_csv(self):
  128. return (
  129. self.name,
  130. self.slug,
  131. self.is_private,
  132. self.description,
  133. )
  134. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  135. class Aggregate(ChangeLoggedModel, CustomFieldModel):
  136. """
  137. An aggregate exists at the root level of the IP address space hierarchy in NetBox. Aggregates are used to organize
  138. the hierarchy and track the overall utilization of available address space. Each Aggregate is assigned to a RIR.
  139. """
  140. prefix = IPNetworkField()
  141. rir = models.ForeignKey(
  142. to='ipam.RIR',
  143. on_delete=models.PROTECT,
  144. related_name='aggregates',
  145. verbose_name='RIR'
  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. custom_field_values = GenericRelation(
  156. to='extras.CustomFieldValue',
  157. content_type_field='obj_type',
  158. object_id_field='obj_id'
  159. )
  160. tags = TaggableManager(through=TaggedItem)
  161. csv_headers = ['prefix', 'rir', 'date_added', 'description']
  162. clone_fields = [
  163. 'rir', 'date_added', 'description',
  164. ]
  165. class Meta:
  166. ordering = ('prefix', 'pk') # prefix may be non-unique
  167. def __str__(self):
  168. return str(self.prefix)
  169. def get_absolute_url(self):
  170. return reverse('ipam:aggregate', args=[self.pk])
  171. def clean(self):
  172. if self.prefix:
  173. # Clear host bits from prefix
  174. self.prefix = self.prefix.cidr
  175. # /0 masks are not acceptable
  176. if self.prefix.prefixlen == 0:
  177. raise ValidationError({
  178. 'prefix': "Cannot create aggregate with /0 mask."
  179. })
  180. # Ensure that the aggregate being added is not covered by an existing aggregate
  181. covering_aggregates = Aggregate.objects.filter(prefix__net_contains_or_equals=str(self.prefix))
  182. if self.pk:
  183. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  184. if covering_aggregates:
  185. raise ValidationError({
  186. 'prefix': "Aggregates cannot overlap. {} is already covered by an existing aggregate ({}).".format(
  187. self.prefix, covering_aggregates[0]
  188. )
  189. })
  190. # Ensure that the aggregate being added does not cover an existing aggregate
  191. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  192. if self.pk:
  193. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  194. if covered_aggregates:
  195. raise ValidationError({
  196. 'prefix': "Aggregates cannot overlap. {} covers an existing aggregate ({}).".format(
  197. self.prefix, covered_aggregates[0]
  198. )
  199. })
  200. def to_csv(self):
  201. return (
  202. self.prefix,
  203. self.rir.name,
  204. self.date_added,
  205. self.description,
  206. )
  207. @property
  208. def family(self):
  209. if self.prefix:
  210. return self.prefix.version
  211. return None
  212. def get_utilization(self):
  213. """
  214. Determine the prefix utilization of the aggregate and return it as a percentage.
  215. """
  216. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  217. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  218. return int(float(child_prefixes.size) / self.prefix.size * 100)
  219. class Role(ChangeLoggedModel):
  220. """
  221. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  222. "Management."
  223. """
  224. name = models.CharField(
  225. max_length=50,
  226. unique=True
  227. )
  228. slug = models.SlugField(
  229. unique=True
  230. )
  231. weight = models.PositiveSmallIntegerField(
  232. default=1000
  233. )
  234. description = models.CharField(
  235. max_length=200,
  236. blank=True,
  237. )
  238. csv_headers = ['name', 'slug', 'weight', 'description']
  239. class Meta:
  240. ordering = ['weight', 'name']
  241. def __str__(self):
  242. return self.name
  243. def to_csv(self):
  244. return (
  245. self.name,
  246. self.slug,
  247. self.weight,
  248. self.description,
  249. )
  250. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  251. class Prefix(ChangeLoggedModel, CustomFieldModel):
  252. """
  253. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be assigned to Sites and
  254. VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role. A Prefix can also be
  255. assigned to a VLAN where appropriate.
  256. """
  257. prefix = IPNetworkField(
  258. help_text='IPv4 or IPv6 network with mask'
  259. )
  260. site = models.ForeignKey(
  261. to='dcim.Site',
  262. on_delete=models.PROTECT,
  263. related_name='prefixes',
  264. blank=True,
  265. null=True
  266. )
  267. vrf = models.ForeignKey(
  268. to='ipam.VRF',
  269. on_delete=models.PROTECT,
  270. related_name='prefixes',
  271. blank=True,
  272. null=True,
  273. verbose_name='VRF'
  274. )
  275. tenant = models.ForeignKey(
  276. to='tenancy.Tenant',
  277. on_delete=models.PROTECT,
  278. related_name='prefixes',
  279. blank=True,
  280. null=True
  281. )
  282. vlan = models.ForeignKey(
  283. to='ipam.VLAN',
  284. on_delete=models.PROTECT,
  285. related_name='prefixes',
  286. blank=True,
  287. null=True,
  288. verbose_name='VLAN'
  289. )
  290. status = models.CharField(
  291. max_length=50,
  292. choices=PrefixStatusChoices,
  293. default=PrefixStatusChoices.STATUS_ACTIVE,
  294. verbose_name='Status',
  295. help_text='Operational status of this prefix'
  296. )
  297. role = models.ForeignKey(
  298. to='ipam.Role',
  299. on_delete=models.SET_NULL,
  300. related_name='prefixes',
  301. blank=True,
  302. null=True,
  303. help_text='The primary function of this prefix'
  304. )
  305. is_pool = models.BooleanField(
  306. verbose_name='Is a pool',
  307. default=False,
  308. help_text='All IP addresses within this prefix are considered usable'
  309. )
  310. description = models.CharField(
  311. max_length=200,
  312. blank=True
  313. )
  314. custom_field_values = GenericRelation(
  315. to='extras.CustomFieldValue',
  316. content_type_field='obj_type',
  317. object_id_field='obj_id'
  318. )
  319. objects = PrefixQuerySet.as_manager()
  320. tags = TaggableManager(through=TaggedItem)
  321. csv_headers = [
  322. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan_vid', 'status', 'role', 'is_pool', 'description',
  323. ]
  324. clone_fields = [
  325. 'site', 'vrf', 'tenant', 'vlan', 'status', 'role', 'is_pool', 'description',
  326. ]
  327. STATUS_CLASS_MAP = {
  328. 'container': 'default',
  329. 'active': 'primary',
  330. 'reserved': 'info',
  331. 'deprecated': 'danger',
  332. }
  333. class Meta:
  334. ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique
  335. verbose_name_plural = 'prefixes'
  336. def __str__(self):
  337. return str(self.prefix)
  338. def get_absolute_url(self):
  339. return reverse('ipam:prefix', args=[self.pk])
  340. def clean(self):
  341. if self.prefix:
  342. # /0 masks are not acceptable
  343. if self.prefix.prefixlen == 0:
  344. raise ValidationError({
  345. 'prefix': "Cannot create prefix with /0 mask."
  346. })
  347. # Disallow host masks
  348. if self.prefix.version == 4 and self.prefix.prefixlen == 32:
  349. raise ValidationError({
  350. 'prefix': "Cannot create host addresses (/32) as prefixes. Create an IPv4 address instead."
  351. })
  352. elif self.prefix.version == 6 and self.prefix.prefixlen == 128:
  353. raise ValidationError({
  354. 'prefix': "Cannot create host addresses (/128) as prefixes. Create an IPv6 address instead."
  355. })
  356. # Enforce unique IP space (if applicable)
  357. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  358. duplicate_prefixes = self.get_duplicates()
  359. if duplicate_prefixes:
  360. raise ValidationError({
  361. 'prefix': "Duplicate prefix found in {}: {}".format(
  362. "VRF {}".format(self.vrf) if self.vrf else "global table",
  363. duplicate_prefixes.first(),
  364. )
  365. })
  366. def save(self, *args, **kwargs):
  367. if isinstance(self.prefix, netaddr.IPNetwork):
  368. # Clear host bits from prefix
  369. self.prefix = self.prefix.cidr
  370. super().save(*args, **kwargs)
  371. def to_csv(self):
  372. return (
  373. self.prefix,
  374. self.vrf.name if self.vrf else None,
  375. self.tenant.name if self.tenant else None,
  376. self.site.name if self.site else None,
  377. self.vlan.group.name if self.vlan and self.vlan.group else None,
  378. self.vlan.vid if self.vlan else None,
  379. self.get_status_display(),
  380. self.role.name if self.role else None,
  381. self.is_pool,
  382. self.description,
  383. )
  384. @property
  385. def family(self):
  386. if self.prefix:
  387. return self.prefix.version
  388. return None
  389. def _set_prefix_length(self, value):
  390. """
  391. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  392. e.g. for bulk editing.
  393. """
  394. if self.prefix is not None:
  395. self.prefix.prefixlen = value
  396. prefix_length = property(fset=_set_prefix_length)
  397. def get_status_class(self):
  398. return self.STATUS_CLASS_MAP.get(self.status)
  399. def get_duplicates(self):
  400. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  401. def get_child_prefixes(self):
  402. """
  403. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  404. Prefixes belonging to any VRF.
  405. """
  406. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  407. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  408. else:
  409. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  410. def get_child_ips(self):
  411. """
  412. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  413. child IPAddresses belonging to any VRF.
  414. """
  415. if self.vrf is None and self.status == PrefixStatusChoices.STATUS_CONTAINER:
  416. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  417. else:
  418. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  419. def get_available_prefixes(self):
  420. """
  421. Return all available Prefixes within this prefix as an IPSet.
  422. """
  423. prefix = netaddr.IPSet(self.prefix)
  424. child_prefixes = netaddr.IPSet([child.prefix for child in self.get_child_prefixes()])
  425. available_prefixes = prefix - child_prefixes
  426. return available_prefixes
  427. def get_available_ips(self):
  428. """
  429. Return all available IPs within this prefix as an IPSet.
  430. """
  431. prefix = netaddr.IPSet(self.prefix)
  432. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  433. available_ips = prefix - child_ips
  434. # All IP addresses within a pool are considered usable
  435. if self.is_pool:
  436. return available_ips
  437. # All IP addresses within a point-to-point prefix (IPv4 /31 or IPv6 /127) are considered usable
  438. if (
  439. self.prefix.version == 4 and self.prefix.prefixlen == 31 # RFC 3021
  440. ) or (
  441. self.prefix.version == 6 and self.prefix.prefixlen == 127 # RFC 6164
  442. ):
  443. return available_ips
  444. # Omit first and last IP address from the available set
  445. available_ips -= netaddr.IPSet([
  446. netaddr.IPAddress(self.prefix.first),
  447. netaddr.IPAddress(self.prefix.last),
  448. ])
  449. return available_ips
  450. def get_first_available_prefix(self):
  451. """
  452. Return the first available child prefix within the prefix (or None).
  453. """
  454. available_prefixes = self.get_available_prefixes()
  455. if not available_prefixes:
  456. return None
  457. return available_prefixes.iter_cidrs()[0]
  458. def get_first_available_ip(self):
  459. """
  460. Return the first available IP within the prefix (or None).
  461. """
  462. available_ips = self.get_available_ips()
  463. if not available_ips:
  464. return None
  465. return '{}/{}'.format(next(available_ips.__iter__()), self.prefix.prefixlen)
  466. def get_utilization(self):
  467. """
  468. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  469. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  470. """
  471. if self.status == PrefixStatusChoices.STATUS_CONTAINER:
  472. queryset = Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  473. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  474. return int(float(child_prefixes.size) / self.prefix.size * 100)
  475. else:
  476. # Compile an IPSet to avoid counting duplicate IPs
  477. child_count = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()]).size
  478. prefix_size = self.prefix.size
  479. if self.prefix.version == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  480. prefix_size -= 2
  481. return int(float(child_count) / prefix_size * 100)
  482. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  483. class IPAddress(ChangeLoggedModel, CustomFieldModel):
  484. """
  485. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  486. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  487. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  488. Interfaces can have zero or more IPAddresses assigned to them.
  489. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  490. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  491. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  492. """
  493. address = IPAddressField(
  494. help_text='IPv4 or IPv6 address (with mask)'
  495. )
  496. vrf = models.ForeignKey(
  497. to='ipam.VRF',
  498. on_delete=models.PROTECT,
  499. related_name='ip_addresses',
  500. blank=True,
  501. null=True,
  502. verbose_name='VRF'
  503. )
  504. tenant = models.ForeignKey(
  505. to='tenancy.Tenant',
  506. on_delete=models.PROTECT,
  507. related_name='ip_addresses',
  508. blank=True,
  509. null=True
  510. )
  511. status = models.CharField(
  512. max_length=50,
  513. choices=IPAddressStatusChoices,
  514. default=IPAddressStatusChoices.STATUS_ACTIVE,
  515. help_text='The operational status of this IP'
  516. )
  517. role = models.CharField(
  518. max_length=50,
  519. choices=IPAddressRoleChoices,
  520. blank=True,
  521. help_text='The functional role of this IP'
  522. )
  523. interface = models.ForeignKey(
  524. to='dcim.Interface',
  525. on_delete=models.CASCADE,
  526. related_name='ip_addresses',
  527. blank=True,
  528. null=True
  529. )
  530. nat_inside = models.OneToOneField(
  531. to='self',
  532. on_delete=models.SET_NULL,
  533. related_name='nat_outside',
  534. blank=True,
  535. null=True,
  536. verbose_name='NAT (Inside)',
  537. help_text='The IP for which this address is the "outside" IP'
  538. )
  539. dns_name = models.CharField(
  540. max_length=255,
  541. blank=True,
  542. validators=[DNSValidator],
  543. verbose_name='DNS Name',
  544. help_text='Hostname or FQDN (not case-sensitive)'
  545. )
  546. description = models.CharField(
  547. max_length=200,
  548. blank=True
  549. )
  550. custom_field_values = GenericRelation(
  551. to='extras.CustomFieldValue',
  552. content_type_field='obj_type',
  553. object_id_field='obj_id'
  554. )
  555. objects = IPAddressManager()
  556. tags = TaggableManager(through=TaggedItem)
  557. csv_headers = [
  558. 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface_name', 'is_primary',
  559. 'dns_name', 'description',
  560. ]
  561. clone_fields = [
  562. 'vrf', 'tenant', 'status', 'role', 'description',
  563. ]
  564. STATUS_CLASS_MAP = {
  565. 'active': 'primary',
  566. 'reserved': 'info',
  567. 'deprecated': 'danger',
  568. 'dhcp': 'success',
  569. }
  570. ROLE_CLASS_MAP = {
  571. 'loopback': 'default',
  572. 'secondary': 'primary',
  573. 'anycast': 'warning',
  574. 'vip': 'success',
  575. 'vrrp': 'success',
  576. 'hsrp': 'success',
  577. 'glbp': 'success',
  578. 'carp': 'success',
  579. }
  580. class Meta:
  581. ordering = ('address', 'pk') # address may be non-unique
  582. verbose_name = 'IP address'
  583. verbose_name_plural = 'IP addresses'
  584. def __str__(self):
  585. return str(self.address)
  586. def get_absolute_url(self):
  587. return reverse('ipam:ipaddress', args=[self.pk])
  588. def get_duplicates(self):
  589. return IPAddress.objects.filter(vrf=self.vrf, address__net_host=str(self.address.ip)).exclude(pk=self.pk)
  590. def clean(self):
  591. if self.address:
  592. # /0 masks are not acceptable
  593. if self.address.prefixlen == 0:
  594. raise ValidationError({
  595. 'address': "Cannot create IP address with /0 mask."
  596. })
  597. # Enforce unique IP space (if applicable)
  598. if self.role not in IPADDRESS_ROLES_NONUNIQUE and ((
  599. self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE
  600. ) or (
  601. self.vrf and self.vrf.enforce_unique
  602. )):
  603. duplicate_ips = self.get_duplicates()
  604. if duplicate_ips:
  605. raise ValidationError({
  606. 'address': "Duplicate IP address found in {}: {}".format(
  607. "VRF {}".format(self.vrf) if self.vrf else "global table",
  608. duplicate_ips.first(),
  609. )
  610. })
  611. if self.pk:
  612. # Check for primary IP assignment that doesn't match the assigned device/VM
  613. device = Device.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  614. if device:
  615. if self.interface is None:
  616. raise ValidationError({
  617. 'interface': "IP address is primary for device {} but not assigned".format(device)
  618. })
  619. elif (device.primary_ip4 == self or device.primary_ip6 == self) and self.interface.device != device:
  620. raise ValidationError({
  621. 'interface': "IP address is primary for device {} but assigned to {} ({})".format(
  622. device, self.interface.device, self.interface
  623. )
  624. })
  625. vm = VirtualMachine.objects.filter(Q(primary_ip4=self) | Q(primary_ip6=self)).first()
  626. if vm:
  627. if self.interface is None:
  628. raise ValidationError({
  629. 'interface': "IP address is primary for virtual machine {} but not assigned".format(vm)
  630. })
  631. elif (vm.primary_ip4 == self or vm.primary_ip6 == self) and self.interface.virtual_machine != vm:
  632. raise ValidationError({
  633. 'interface': "IP address is primary for virtual machine {} but assigned to {} ({})".format(
  634. vm, self.interface.virtual_machine, self.interface
  635. )
  636. })
  637. def save(self, *args, **kwargs):
  638. # Force dns_name to lowercase
  639. self.dns_name = self.dns_name.lower()
  640. super().save(*args, **kwargs)
  641. def to_objectchange(self, action):
  642. # Annotate the assigned Interface (if any)
  643. try:
  644. parent_obj = self.interface
  645. except ObjectDoesNotExist:
  646. parent_obj = None
  647. return ObjectChange(
  648. changed_object=self,
  649. object_repr=str(self),
  650. action=action,
  651. related_object=parent_obj,
  652. object_data=serialize_object(self)
  653. )
  654. def to_csv(self):
  655. # Determine if this IP is primary for a Device
  656. if self.address.version == 4 and getattr(self, 'primary_ip4_for', False):
  657. is_primary = True
  658. elif self.address.version == 6 and getattr(self, 'primary_ip6_for', False):
  659. is_primary = True
  660. else:
  661. is_primary = False
  662. return (
  663. self.address,
  664. self.vrf.name if self.vrf else None,
  665. self.tenant.name if self.tenant else None,
  666. self.get_status_display(),
  667. self.get_role_display(),
  668. self.device.identifier if self.device else None,
  669. self.virtual_machine.name if self.virtual_machine else None,
  670. self.interface.name if self.interface else None,
  671. is_primary,
  672. self.dns_name,
  673. self.description,
  674. )
  675. @property
  676. def family(self):
  677. if self.address:
  678. return self.address.version
  679. return None
  680. def _set_mask_length(self, value):
  681. """
  682. Expose the IPNetwork object's prefixlen attribute on the parent model so that it can be manipulated directly,
  683. e.g. for bulk editing.
  684. """
  685. if self.address is not None:
  686. self.address.prefixlen = value
  687. mask_length = property(fset=_set_mask_length)
  688. @property
  689. def device(self):
  690. if self.interface:
  691. return self.interface.device
  692. return None
  693. @property
  694. def virtual_machine(self):
  695. if self.interface:
  696. return self.interface.virtual_machine
  697. return None
  698. def get_status_class(self):
  699. return self.STATUS_CLASS_MAP.get(self.status)
  700. def get_role_class(self):
  701. return self.ROLE_CLASS_MAP[self.role]
  702. class VLANGroup(ChangeLoggedModel):
  703. """
  704. A VLAN group is an arbitrary collection of VLANs within which VLAN IDs and names must be unique.
  705. """
  706. name = models.CharField(
  707. max_length=50
  708. )
  709. slug = models.SlugField()
  710. site = models.ForeignKey(
  711. to='dcim.Site',
  712. on_delete=models.PROTECT,
  713. related_name='vlan_groups',
  714. blank=True,
  715. null=True
  716. )
  717. description = models.CharField(
  718. max_length=200,
  719. blank=True
  720. )
  721. csv_headers = ['name', 'slug', 'site', 'description']
  722. class Meta:
  723. ordering = ('site', 'name', 'pk') # (site, name) may be non-unique
  724. unique_together = [
  725. ['site', 'name'],
  726. ['site', 'slug'],
  727. ]
  728. verbose_name = 'VLAN group'
  729. verbose_name_plural = 'VLAN groups'
  730. def __str__(self):
  731. return self.name
  732. def get_absolute_url(self):
  733. return reverse('ipam:vlangroup_vlans', args=[self.pk])
  734. def to_csv(self):
  735. return (
  736. self.name,
  737. self.slug,
  738. self.site.name if self.site else None,
  739. self.description,
  740. )
  741. def get_next_available_vid(self):
  742. """
  743. Return the first available VLAN ID (1-4094) in the group.
  744. """
  745. vids = [vlan['vid'] for vlan in self.vlans.order_by('vid').values('vid')]
  746. for i in range(1, 4095):
  747. if i not in vids:
  748. return i
  749. return None
  750. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  751. class VLAN(ChangeLoggedModel, CustomFieldModel):
  752. """
  753. A VLAN is a distinct layer two forwarding domain identified by a 12-bit integer (1-4094). Each VLAN must be assigned
  754. to a Site, however VLAN IDs need not be unique within a Site. A VLAN may optionally be assigned to a VLANGroup,
  755. within which all VLAN IDs and names but be unique.
  756. Like Prefixes, each VLAN is assigned an operational status and optionally a user-defined Role. A VLAN can have zero
  757. or more Prefixes assigned to it.
  758. """
  759. site = models.ForeignKey(
  760. to='dcim.Site',
  761. on_delete=models.PROTECT,
  762. related_name='vlans',
  763. blank=True,
  764. null=True
  765. )
  766. group = models.ForeignKey(
  767. to='ipam.VLANGroup',
  768. on_delete=models.PROTECT,
  769. related_name='vlans',
  770. blank=True,
  771. null=True
  772. )
  773. vid = models.PositiveSmallIntegerField(
  774. verbose_name='ID',
  775. validators=[MinValueValidator(1), MaxValueValidator(4094)]
  776. )
  777. name = models.CharField(
  778. max_length=64
  779. )
  780. tenant = models.ForeignKey(
  781. to='tenancy.Tenant',
  782. on_delete=models.PROTECT,
  783. related_name='vlans',
  784. blank=True,
  785. null=True
  786. )
  787. status = models.CharField(
  788. max_length=50,
  789. choices=VLANStatusChoices,
  790. default=VLANStatusChoices.STATUS_ACTIVE
  791. )
  792. role = models.ForeignKey(
  793. to='ipam.Role',
  794. on_delete=models.SET_NULL,
  795. related_name='vlans',
  796. blank=True,
  797. null=True
  798. )
  799. description = models.CharField(
  800. max_length=200,
  801. blank=True
  802. )
  803. custom_field_values = GenericRelation(
  804. to='extras.CustomFieldValue',
  805. content_type_field='obj_type',
  806. object_id_field='obj_id'
  807. )
  808. tags = TaggableManager(through=TaggedItem)
  809. csv_headers = ['site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description']
  810. clone_fields = [
  811. 'site', 'group', 'tenant', 'status', 'role', 'description',
  812. ]
  813. STATUS_CLASS_MAP = {
  814. 'active': 'primary',
  815. 'reserved': 'info',
  816. 'deprecated': 'danger',
  817. }
  818. class Meta:
  819. ordering = ('site', 'group', 'vid', 'pk') # (site, group, vid) may be non-unique
  820. unique_together = [
  821. ['group', 'vid'],
  822. ['group', 'name'],
  823. ]
  824. verbose_name = 'VLAN'
  825. verbose_name_plural = 'VLANs'
  826. def __str__(self):
  827. return self.display_name or super().__str__()
  828. def get_absolute_url(self):
  829. return reverse('ipam:vlan', args=[self.pk])
  830. def clean(self):
  831. # Validate VLAN group
  832. if self.group and self.group.site != self.site:
  833. raise ValidationError({
  834. 'group': "VLAN group must belong to the assigned site ({}).".format(self.site)
  835. })
  836. def to_csv(self):
  837. return (
  838. self.site.name if self.site else None,
  839. self.group.name if self.group else None,
  840. self.vid,
  841. self.name,
  842. self.tenant.name if self.tenant else None,
  843. self.get_status_display(),
  844. self.role.name if self.role else None,
  845. self.description,
  846. )
  847. @property
  848. def display_name(self):
  849. if self.vid and self.name:
  850. return "{} ({})".format(self.vid, self.name)
  851. return None
  852. def get_status_class(self):
  853. return self.STATUS_CLASS_MAP[self.status]
  854. def get_members(self):
  855. # Return all interfaces assigned to this VLAN
  856. return Interface.objects.filter(
  857. Q(untagged_vlan_id=self.pk) |
  858. Q(tagged_vlans=self.pk)
  859. ).distinct()
  860. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  861. class Service(ChangeLoggedModel, CustomFieldModel):
  862. """
  863. A Service represents a layer-four service (e.g. HTTP or SSH) running on a Device or VirtualMachine. A Service may
  864. optionally be tied to one or more specific IPAddresses belonging to its parent.
  865. """
  866. device = models.ForeignKey(
  867. to='dcim.Device',
  868. on_delete=models.CASCADE,
  869. related_name='services',
  870. verbose_name='device',
  871. null=True,
  872. blank=True
  873. )
  874. virtual_machine = models.ForeignKey(
  875. to='virtualization.VirtualMachine',
  876. on_delete=models.CASCADE,
  877. related_name='services',
  878. null=True,
  879. blank=True
  880. )
  881. name = models.CharField(
  882. max_length=30
  883. )
  884. protocol = models.CharField(
  885. max_length=50,
  886. choices=ServiceProtocolChoices
  887. )
  888. port = models.PositiveIntegerField(
  889. validators=[MinValueValidator(SERVICE_PORT_MIN), MaxValueValidator(SERVICE_PORT_MAX)],
  890. verbose_name='Port number'
  891. )
  892. ipaddresses = models.ManyToManyField(
  893. to='ipam.IPAddress',
  894. related_name='services',
  895. blank=True,
  896. verbose_name='IP addresses'
  897. )
  898. description = models.CharField(
  899. max_length=200,
  900. blank=True
  901. )
  902. custom_field_values = GenericRelation(
  903. to='extras.CustomFieldValue',
  904. content_type_field='obj_type',
  905. object_id_field='obj_id'
  906. )
  907. tags = TaggableManager(through=TaggedItem)
  908. csv_headers = ['device', 'virtual_machine', 'name', 'protocol', 'port', 'description']
  909. class Meta:
  910. ordering = ('protocol', 'port', 'pk') # (protocol, port) may be non-unique
  911. def __str__(self):
  912. return '{} ({}/{})'.format(self.name, self.port, self.get_protocol_display())
  913. def get_absolute_url(self):
  914. return reverse('ipam:service', args=[self.pk])
  915. @property
  916. def parent(self):
  917. return self.device or self.virtual_machine
  918. def clean(self):
  919. # A Service must belong to a Device *or* to a VirtualMachine
  920. if self.device and self.virtual_machine:
  921. raise ValidationError("A service cannot be associated with both a device and a virtual machine.")
  922. if not self.device and not self.virtual_machine:
  923. raise ValidationError("A service must be associated with either a device or a virtual machine.")
  924. def to_csv(self):
  925. return (
  926. self.device.name if self.device else None,
  927. self.virtual_machine.name if self.virtual_machine else None,
  928. self.name,
  929. self.get_protocol_display(),
  930. self.port,
  931. self.description,
  932. )