vlans.py 14 KB

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