models.py 34 KB

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