vlans.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.contrib.postgres.fields import ArrayField, IntegerRangeField
  4. from django.core.exceptions import ValidationError
  5. from django.core.validators import MaxValueValidator, MinValueValidator
  6. from django.db import models
  7. from django.db.backends.postgresql.psycopg_any import NumericRange
  8. from django.utils.translation import gettext_lazy as _
  9. from dcim.models import Interface, Site, SiteGroup
  10. from ipam.choices import *
  11. from ipam.constants import *
  12. from ipam.querysets import VLANGroupQuerySet, VLANQuerySet
  13. from netbox.models import NetBoxModel, OrganizationalModel, PrimaryModel
  14. from utilities.data import check_ranges_overlap, ranges_to_string, ranges_to_string_list
  15. from virtualization.models import VMInterface
  16. __all__ = (
  17. 'VLAN',
  18. 'VLANGroup',
  19. 'VLANTranslationPolicy',
  20. 'VLANTranslationRule',
  21. )
  22. def default_vid_ranges():
  23. return [NumericRange(VLAN_VID_MIN, VLAN_VID_MAX + 1)]
  24. class VLANGroup(OrganizationalModel):
  25. """
  26. A VLAN group is an arbitrary collection of VLANs within which VLAN IDs and names must be unique. Each group must
  27. define one or more ranges of valid VLAN IDs, and may be assigned a specific scope.
  28. """
  29. name = models.CharField(
  30. verbose_name=_('name'),
  31. max_length=100,
  32. db_collation="natural_sort"
  33. )
  34. slug = models.SlugField(
  35. verbose_name=_('slug'),
  36. max_length=100
  37. )
  38. scope_type = models.ForeignKey(
  39. to='contenttypes.ContentType',
  40. on_delete=models.CASCADE,
  41. blank=True,
  42. null=True
  43. )
  44. scope_id = models.PositiveBigIntegerField(
  45. blank=True,
  46. null=True
  47. )
  48. scope = GenericForeignKey(
  49. ct_field='scope_type',
  50. fk_field='scope_id'
  51. )
  52. vid_ranges = ArrayField(
  53. IntegerRangeField(),
  54. verbose_name=_('VLAN ID ranges'),
  55. default=default_vid_ranges
  56. )
  57. total_vlan_ids = models.PositiveBigIntegerField(
  58. default=VLAN_VID_MAX - VLAN_VID_MIN + 1,
  59. )
  60. tenant = models.ForeignKey(
  61. to='tenancy.Tenant',
  62. on_delete=models.PROTECT,
  63. related_name='vlan_groups',
  64. blank=True,
  65. null=True
  66. )
  67. objects = VLANGroupQuerySet.as_manager()
  68. class Meta:
  69. ordering = ('name', 'pk') # Name may be non-unique
  70. indexes = (
  71. models.Index(fields=('name', 'id')), # Default ordering
  72. models.Index(fields=('scope_type', 'scope_id')),
  73. )
  74. constraints = (
  75. models.UniqueConstraint(
  76. fields=('scope_type', 'scope_id', 'name'),
  77. name='%(app_label)s_%(class)s_unique_scope_name'
  78. ),
  79. models.UniqueConstraint(
  80. fields=('scope_type', 'scope_id', 'slug'),
  81. name='%(app_label)s_%(class)s_unique_scope_slug'
  82. ),
  83. )
  84. verbose_name = _('VLAN group')
  85. verbose_name_plural = _('VLAN groups')
  86. def clean(self):
  87. super().clean()
  88. # Validate scope assignment
  89. if self.scope_type and not self.scope_id:
  90. raise ValidationError(_("Cannot set scope_type without scope_id."))
  91. if self.scope_id and not self.scope_type:
  92. raise ValidationError(_("Cannot set scope_id without scope_type."))
  93. # Validate VID ranges
  94. for vid_range in self.vid_ranges:
  95. lower_vid = vid_range.lower if vid_range.lower_inc else vid_range.lower + 1
  96. upper_vid = vid_range.upper if vid_range.upper_inc else vid_range.upper - 1
  97. if lower_vid < VLAN_VID_MIN:
  98. raise ValidationError({
  99. 'vid_ranges': _("Starting VLAN ID in range ({value}) cannot be less than {minimum}").format(
  100. value=lower_vid, minimum=VLAN_VID_MIN
  101. )
  102. })
  103. if upper_vid > VLAN_VID_MAX:
  104. raise ValidationError({
  105. 'vid_ranges': _("Ending VLAN ID in range ({value}) cannot exceed {maximum}").format(
  106. value=upper_vid, maximum=VLAN_VID_MAX
  107. )
  108. })
  109. if lower_vid > upper_vid:
  110. raise ValidationError({
  111. 'vid_ranges': _(
  112. "Ending VLAN ID in range must be greater than or equal to the starting VLAN ID ({range})"
  113. ).format(range=f'{lower_vid}-{upper_vid}')
  114. })
  115. # Check for overlapping VID ranges
  116. if self.vid_ranges and check_ranges_overlap(self.vid_ranges):
  117. raise ValidationError({'vid_ranges': _("Ranges cannot overlap.")})
  118. def save(self, *args, **kwargs):
  119. self.total_vlan_ids = 0
  120. for vid_range in self.vid_ranges:
  121. # VID range is inclusive on lower-bound, exclusive on upper-bound
  122. self.total_vlan_ids += vid_range.upper - vid_range.lower
  123. super().save(*args, **kwargs)
  124. def get_available_vids(self):
  125. """
  126. Return all available VLANs within this group.
  127. """
  128. available_vlans = set()
  129. for vlan_range in self.vid_ranges:
  130. available_vlans = available_vlans.union({
  131. vid for vid in range(vlan_range.lower, vlan_range.upper)
  132. })
  133. available_vlans -= set(VLAN.objects.filter(group=self).values_list('vid', flat=True))
  134. return sorted(available_vlans)
  135. def get_next_available_vid(self):
  136. """
  137. Return the first available VLAN ID (1-4094) in the group.
  138. """
  139. available_vids = self.get_available_vids()
  140. if available_vids:
  141. return available_vids[0]
  142. return None
  143. def get_child_vlans(self):
  144. """
  145. Return all VLANs within this group.
  146. """
  147. return VLAN.objects.filter(group=self).order_by('vid')
  148. @property
  149. def vid_ranges_items(self):
  150. """
  151. Property that converts VID ranges to a list of string representations.
  152. """
  153. return ranges_to_string_list(self.vid_ranges)
  154. @property
  155. def vid_ranges_list(self):
  156. """
  157. Property that converts VID ranges into a string representation.
  158. """
  159. return ranges_to_string(self.vid_ranges)
  160. class VLAN(PrimaryModel):
  161. """
  162. A VLAN is a distinct layer two forwarding domain identified by a 12-bit integer (1-4094). Each VLAN must be assigned
  163. to a Site, however VLAN IDs need not be unique within a Site. A VLAN may optionally be assigned to a VLANGroup,
  164. within which all VLAN IDs and names but be unique.
  165. Like Prefixes, each VLAN is assigned an operational status and optionally a user-defined Role. A VLAN can have zero
  166. or more Prefixes assigned to it.
  167. """
  168. site = models.ForeignKey(
  169. to='dcim.Site',
  170. on_delete=models.PROTECT,
  171. related_name='vlans',
  172. blank=True,
  173. null=True,
  174. help_text=_("The specific site to which this VLAN is assigned (if any)")
  175. )
  176. group = models.ForeignKey(
  177. to='ipam.VLANGroup',
  178. on_delete=models.PROTECT,
  179. related_name='vlans',
  180. blank=True,
  181. null=True,
  182. help_text=_("VLAN group (optional)")
  183. )
  184. vid = models.PositiveSmallIntegerField(
  185. verbose_name=_('VLAN ID'),
  186. validators=(
  187. MinValueValidator(VLAN_VID_MIN),
  188. MaxValueValidator(VLAN_VID_MAX)
  189. ),
  190. help_text=_("Numeric VLAN ID (1-4094)")
  191. )
  192. name = models.CharField(
  193. verbose_name=_('name'),
  194. max_length=64
  195. )
  196. tenant = models.ForeignKey(
  197. to='tenancy.Tenant',
  198. on_delete=models.PROTECT,
  199. related_name='vlans',
  200. blank=True,
  201. null=True
  202. )
  203. status = models.CharField(
  204. verbose_name=_('status'),
  205. max_length=50,
  206. choices=VLANStatusChoices,
  207. default=VLANStatusChoices.STATUS_ACTIVE,
  208. help_text=_("Operational status of this VLAN")
  209. )
  210. role = models.ForeignKey(
  211. to='ipam.Role',
  212. on_delete=models.SET_NULL,
  213. related_name='vlans',
  214. blank=True,
  215. null=True,
  216. help_text=_("The primary function of this VLAN")
  217. )
  218. qinq_svlan = models.ForeignKey(
  219. to='self',
  220. on_delete=models.PROTECT,
  221. related_name='qinq_cvlans',
  222. blank=True,
  223. null=True
  224. )
  225. qinq_role = models.CharField(
  226. verbose_name=_('Q-in-Q role'),
  227. max_length=50,
  228. choices=VLANQinQRoleChoices,
  229. blank=True,
  230. null=True,
  231. help_text=_("Customer/service VLAN designation (for Q-in-Q/IEEE 802.1ad)")
  232. )
  233. l2vpn_terminations = GenericRelation(
  234. to='vpn.L2VPNTermination',
  235. content_type_field='assigned_object_type',
  236. object_id_field='assigned_object_id',
  237. related_query_name='vlan'
  238. )
  239. objects = VLANQuerySet.as_manager()
  240. clone_fields = [
  241. 'site', 'group', 'tenant', 'status', 'role', 'description', 'qinq_role', 'qinq_svlan',
  242. ]
  243. class Meta:
  244. ordering = ('site', 'group', 'vid', 'pk') # (site, group, vid) may be non-unique
  245. indexes = (
  246. models.Index(fields=('site', 'group', 'vid', 'id')), # Default ordering
  247. )
  248. constraints = (
  249. models.UniqueConstraint(
  250. fields=('group', 'vid'),
  251. name='%(app_label)s_%(class)s_unique_group_vid'
  252. ),
  253. models.UniqueConstraint(
  254. fields=('group', 'name'),
  255. name='%(app_label)s_%(class)s_unique_group_name'
  256. ),
  257. models.UniqueConstraint(
  258. fields=('qinq_svlan', 'vid'),
  259. name='%(app_label)s_%(class)s_unique_qinq_svlan_vid'
  260. ),
  261. models.UniqueConstraint(
  262. fields=('qinq_svlan', 'name'),
  263. name='%(app_label)s_%(class)s_unique_qinq_svlan_name'
  264. ),
  265. )
  266. verbose_name = _('VLAN')
  267. verbose_name_plural = _('VLANs')
  268. def __str__(self):
  269. return f'{self.name} ({self.vid})'
  270. def clean(self):
  271. super().clean()
  272. # Validate VLAN group (if assigned)
  273. if self.group and self.site and self.group.scope_type == ContentType.objects.get_for_model(Site):
  274. if self.site != self.group.scope:
  275. raise ValidationError(
  276. _(
  277. "VLAN is assigned to group {group} (scope: {scope}); cannot also assign to site {site}."
  278. ).format(group=self.group, scope=self.group.scope, site=self.site)
  279. )
  280. if self.group and self.site and self.group.scope_type == ContentType.objects.get_for_model(SiteGroup):
  281. if self.site not in self.group.scope.sites.all():
  282. raise ValidationError(
  283. _(
  284. "The assigned site {site} is not a member of the assigned group {group} (scope: {scope})."
  285. ).format(group=self.group, scope=self.group.scope, site=self.site)
  286. )
  287. # Check that the VLAN ID is permitted in the assigned group (if any)
  288. if self.group:
  289. if not any([self.vid in r for r in self.group.vid_ranges]):
  290. raise ValidationError({
  291. 'vid': _(
  292. "VID must be in ranges {ranges} for VLANs in group {group}"
  293. ).format(ranges=ranges_to_string(self.group.vid_ranges), group=self.group)
  294. })
  295. # Only Q-in-Q customer VLANs may be assigned to a service VLAN
  296. if self.qinq_svlan and self.qinq_role != VLANQinQRoleChoices.ROLE_CUSTOMER:
  297. raise ValidationError({
  298. 'qinq_svlan': _("Only Q-in-Q customer VLANs maybe assigned to a service VLAN.")
  299. })
  300. # A Q-in-Q customer VLAN must be assigned to a service VLAN
  301. if self.qinq_role == VLANQinQRoleChoices.ROLE_CUSTOMER and not self.qinq_svlan:
  302. raise ValidationError({
  303. 'qinq_role': _("A Q-in-Q customer VLAN must be assigned to a service VLAN.")
  304. })
  305. def get_status_color(self):
  306. return VLANStatusChoices.colors.get(self.status)
  307. def get_qinq_role_color(self):
  308. return VLANQinQRoleChoices.colors.get(self.qinq_role)
  309. def get_interfaces(self):
  310. # Return all device interfaces assigned to this VLAN
  311. return Interface.objects.filter(
  312. Q(untagged_vlan_id=self.pk) |
  313. Q(tagged_vlans=self.pk)
  314. ).distinct()
  315. def get_vminterfaces(self):
  316. # Return all VM interfaces assigned to this VLAN
  317. return VMInterface.objects.filter(
  318. Q(untagged_vlan_id=self.pk) |
  319. Q(tagged_vlans=self.pk)
  320. ).distinct()
  321. @property
  322. def l2vpn_termination(self):
  323. return self.l2vpn_terminations.first()
  324. class VLANTranslationPolicy(PrimaryModel):
  325. name = models.CharField(
  326. verbose_name=_('name'),
  327. max_length=100,
  328. unique=True,
  329. )
  330. class Meta:
  331. verbose_name = _('VLAN translation policy')
  332. verbose_name_plural = _('VLAN translation policies')
  333. ordering = ('name',)
  334. def __str__(self):
  335. return self.name
  336. class VLANTranslationRule(NetBoxModel):
  337. policy = models.ForeignKey(
  338. to=VLANTranslationPolicy,
  339. related_name='rules',
  340. on_delete=models.CASCADE,
  341. )
  342. description = models.CharField(
  343. verbose_name=_('description'),
  344. max_length=200,
  345. blank=True
  346. )
  347. local_vid = models.PositiveSmallIntegerField(
  348. verbose_name=_('Local VLAN ID'),
  349. validators=(
  350. MinValueValidator(VLAN_VID_MIN),
  351. MaxValueValidator(VLAN_VID_MAX)
  352. ),
  353. help_text=_("Numeric VLAN ID (1-4094)")
  354. )
  355. remote_vid = models.PositiveSmallIntegerField(
  356. verbose_name=_('Remote VLAN ID'),
  357. validators=(
  358. MinValueValidator(VLAN_VID_MIN),
  359. MaxValueValidator(VLAN_VID_MAX)
  360. ),
  361. help_text=_("Numeric VLAN ID (1-4094)")
  362. )
  363. prerequisite_models = (
  364. 'ipam.VLANTranslationPolicy',
  365. )
  366. clone_fields = ['policy']
  367. class Meta:
  368. verbose_name = _('VLAN translation rule')
  369. ordering = ('policy', 'local_vid',)
  370. constraints = (
  371. models.UniqueConstraint(
  372. fields=('policy', 'local_vid'),
  373. name='%(app_label)s_%(class)s_unique_policy_local_vid'
  374. ),
  375. models.UniqueConstraint(
  376. fields=('policy', 'remote_vid'),
  377. name='%(app_label)s_%(class)s_unique_policy_remote_vid'
  378. ),
  379. )
  380. def __str__(self):
  381. return f'{self.local_vid} -> {self.remote_vid} ({self.policy})'
  382. def to_objectchange(self, action):
  383. objectchange = super().to_objectchange(action)
  384. objectchange.related_object = self.policy
  385. return objectchange