forms.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. from __future__ import unicode_literals
  2. from django import forms
  3. from django.core.exceptions import MultipleObjectsReturned
  4. from django.db.models import Count
  5. from dcim.models import Site, Rack, Device, Interface
  6. from extras.forms import CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm
  7. from tenancy.forms import TenancyForm
  8. from tenancy.models import Tenant
  9. from utilities.forms import (
  10. AnnotatedMultipleChoiceField, APISelect, BootstrapMixin, BulkEditNullBooleanSelect, ChainedModelChoiceField,
  11. CSVChoiceField, ExpandableIPAddressField, FilterChoiceField, FlexibleModelChoiceField, Livesearch, ReturnURLForm,
  12. SlugField, add_blank_choice,
  13. )
  14. from virtualization.models import VirtualMachine
  15. from .constants import IPADDRESS_ROLE_CHOICES, IPADDRESS_STATUS_CHOICES, PREFIX_STATUS_CHOICES, VLAN_STATUS_CHOICES
  16. from .models import Aggregate, IPAddress, Prefix, RIR, Role, Service, VLAN, VLANGroup, VRF
  17. IP_FAMILY_CHOICES = [
  18. ('', 'All'),
  19. (4, 'IPv4'),
  20. (6, 'IPv6'),
  21. ]
  22. PREFIX_MASK_LENGTH_CHOICES = add_blank_choice([(i, i) for i in range(1, 128)])
  23. IPADDRESS_MASK_LENGTH_CHOICES = add_blank_choice([(i, i) for i in range(1, 129)])
  24. #
  25. # VRFs
  26. #
  27. class VRFForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  28. class Meta:
  29. model = VRF
  30. fields = ['name', 'rd', 'enforce_unique', 'description', 'tenant_group', 'tenant']
  31. labels = {
  32. 'rd': "RD",
  33. }
  34. help_texts = {
  35. 'rd': "Route distinguisher in any format",
  36. }
  37. class VRFCSVForm(forms.ModelForm):
  38. tenant = forms.ModelChoiceField(
  39. queryset=Tenant.objects.all(),
  40. required=False,
  41. to_field_name='name',
  42. help_text='Name of assigned tenant',
  43. error_messages={
  44. 'invalid_choice': 'Tenant not found.',
  45. }
  46. )
  47. class Meta:
  48. model = VRF
  49. fields = VRF.csv_headers
  50. help_texts = {
  51. 'name': 'VRF name',
  52. }
  53. class VRFBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  54. pk = forms.ModelMultipleChoiceField(queryset=VRF.objects.all(), widget=forms.MultipleHiddenInput)
  55. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  56. enforce_unique = forms.NullBooleanField(
  57. required=False, widget=BulkEditNullBooleanSelect, label='Enforce unique space'
  58. )
  59. description = forms.CharField(max_length=100, required=False)
  60. class Meta:
  61. nullable_fields = ['tenant', 'description']
  62. class VRFFilterForm(BootstrapMixin, CustomFieldFilterForm):
  63. model = VRF
  64. q = forms.CharField(required=False, label='Search')
  65. tenant = FilterChoiceField(
  66. queryset=Tenant.objects.annotate(filter_count=Count('vrfs')),
  67. to_field_name='slug',
  68. null_label='-- None --'
  69. )
  70. #
  71. # RIRs
  72. #
  73. class RIRForm(BootstrapMixin, forms.ModelForm):
  74. slug = SlugField()
  75. class Meta:
  76. model = RIR
  77. fields = ['name', 'slug', 'is_private']
  78. class RIRCSVForm(forms.ModelForm):
  79. slug = SlugField()
  80. class Meta:
  81. model = RIR
  82. fields = RIR.csv_headers
  83. help_texts = {
  84. 'name': 'RIR name',
  85. }
  86. class RIRFilterForm(BootstrapMixin, forms.Form):
  87. is_private = forms.NullBooleanField(required=False, label='Private', widget=forms.Select(choices=[
  88. ('', '---------'),
  89. ('True', 'Yes'),
  90. ('False', 'No'),
  91. ]))
  92. #
  93. # Aggregates
  94. #
  95. class AggregateForm(BootstrapMixin, CustomFieldForm):
  96. class Meta:
  97. model = Aggregate
  98. fields = ['prefix', 'rir', 'date_added', 'description']
  99. help_texts = {
  100. 'prefix': "IPv4 or IPv6 network",
  101. 'rir': "Regional Internet Registry responsible for this prefix",
  102. 'date_added': "Format: YYYY-MM-DD",
  103. }
  104. class AggregateCSVForm(forms.ModelForm):
  105. rir = forms.ModelChoiceField(
  106. queryset=RIR.objects.all(),
  107. to_field_name='name',
  108. help_text='Name of parent RIR',
  109. error_messages={
  110. 'invalid_choice': 'RIR not found.',
  111. }
  112. )
  113. class Meta:
  114. model = Aggregate
  115. fields = Aggregate.csv_headers
  116. class AggregateBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  117. pk = forms.ModelMultipleChoiceField(queryset=Aggregate.objects.all(), widget=forms.MultipleHiddenInput)
  118. rir = forms.ModelChoiceField(queryset=RIR.objects.all(), required=False, label='RIR')
  119. date_added = forms.DateField(required=False)
  120. description = forms.CharField(max_length=100, required=False)
  121. class Meta:
  122. nullable_fields = ['date_added', 'description']
  123. class AggregateFilterForm(BootstrapMixin, CustomFieldFilterForm):
  124. model = Aggregate
  125. q = forms.CharField(required=False, label='Search')
  126. family = forms.ChoiceField(required=False, choices=IP_FAMILY_CHOICES, label='Address Family')
  127. rir = FilterChoiceField(
  128. queryset=RIR.objects.annotate(filter_count=Count('aggregates')),
  129. to_field_name='slug',
  130. label='RIR'
  131. )
  132. #
  133. # Roles
  134. #
  135. class RoleForm(BootstrapMixin, forms.ModelForm):
  136. slug = SlugField()
  137. class Meta:
  138. model = Role
  139. fields = ['name', 'slug']
  140. class RoleCSVForm(forms.ModelForm):
  141. slug = SlugField()
  142. class Meta:
  143. model = Role
  144. fields = Role.csv_headers
  145. help_texts = {
  146. 'name': 'Role name',
  147. }
  148. #
  149. # Prefixes
  150. #
  151. class PrefixForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  152. site = forms.ModelChoiceField(
  153. queryset=Site.objects.all(),
  154. required=False,
  155. label='Site',
  156. widget=forms.Select(
  157. attrs={'filter-for': 'vlan_group', 'nullable': 'true'}
  158. )
  159. )
  160. vlan_group = ChainedModelChoiceField(
  161. queryset=VLANGroup.objects.all(),
  162. chains=(
  163. ('site', 'site'),
  164. ),
  165. required=False,
  166. label='VLAN group',
  167. widget=APISelect(
  168. api_url='/api/ipam/vlan-groups/?site_id={{site}}',
  169. attrs={'filter-for': 'vlan', 'nullable': 'true'}
  170. )
  171. )
  172. vlan = ChainedModelChoiceField(
  173. queryset=VLAN.objects.all(),
  174. chains=(
  175. ('site', 'site'),
  176. ('group', 'vlan_group'),
  177. ),
  178. required=False,
  179. label='VLAN',
  180. widget=APISelect(
  181. api_url='/api/ipam/vlans/?site_id={{site}}&group_id={{vlan_group}}', display_field='display_name'
  182. )
  183. )
  184. class Meta:
  185. model = Prefix
  186. fields = ['prefix', 'vrf', 'site', 'vlan', 'status', 'role', 'is_pool', 'description', 'tenant_group', 'tenant']
  187. def __init__(self, *args, **kwargs):
  188. # Initialize helper selectors
  189. instance = kwargs.get('instance')
  190. initial = kwargs.get('initial', {}).copy()
  191. if instance and instance.vlan is not None:
  192. initial['vlan_group'] = instance.vlan.group
  193. kwargs['initial'] = initial
  194. super(PrefixForm, self).__init__(*args, **kwargs)
  195. self.fields['vrf'].empty_label = 'Global'
  196. class PrefixCSVForm(forms.ModelForm):
  197. vrf = forms.ModelChoiceField(
  198. queryset=VRF.objects.all(),
  199. required=False,
  200. to_field_name='rd',
  201. help_text='Route distinguisher of parent VRF',
  202. error_messages={
  203. 'invalid_choice': 'VRF not found.',
  204. }
  205. )
  206. tenant = forms.ModelChoiceField(
  207. queryset=Tenant.objects.all(),
  208. required=False,
  209. to_field_name='name',
  210. help_text='Name of assigned tenant',
  211. error_messages={
  212. 'invalid_choice': 'Tenant not found.',
  213. }
  214. )
  215. site = forms.ModelChoiceField(
  216. queryset=Site.objects.all(),
  217. required=False,
  218. to_field_name='name',
  219. help_text='Name of parent site',
  220. error_messages={
  221. 'invalid_choice': 'Site not found.',
  222. }
  223. )
  224. vlan_group = forms.CharField(
  225. help_text='Group name of assigned VLAN',
  226. required=False
  227. )
  228. vlan_vid = forms.IntegerField(
  229. help_text='Numeric ID of assigned VLAN',
  230. required=False
  231. )
  232. status = CSVChoiceField(
  233. choices=PREFIX_STATUS_CHOICES,
  234. help_text='Operational status'
  235. )
  236. role = forms.ModelChoiceField(
  237. queryset=Role.objects.all(),
  238. required=False,
  239. to_field_name='name',
  240. help_text='Functional role',
  241. error_messages={
  242. 'invalid_choice': 'Invalid role.',
  243. }
  244. )
  245. class Meta:
  246. model = Prefix
  247. fields = Prefix.csv_headers
  248. def clean(self):
  249. super(PrefixCSVForm, self).clean()
  250. site = self.cleaned_data.get('site')
  251. vlan_group = self.cleaned_data.get('vlan_group')
  252. vlan_vid = self.cleaned_data.get('vlan_vid')
  253. # Validate VLAN
  254. if vlan_group and vlan_vid:
  255. try:
  256. self.instance.vlan = VLAN.objects.get(site=site, group__name=vlan_group, vid=vlan_vid)
  257. except VLAN.DoesNotExist:
  258. if site:
  259. raise forms.ValidationError("VLAN {} not found in site {} group {}".format(
  260. vlan_vid, site, vlan_group
  261. ))
  262. else:
  263. raise forms.ValidationError("Global VLAN {} not found in group {}".format(vlan_vid, vlan_group))
  264. except MultipleObjectsReturned:
  265. raise forms.ValidationError(
  266. "Multiple VLANs with VID {} found in group {}".format(vlan_vid, vlan_group)
  267. )
  268. elif vlan_vid:
  269. try:
  270. self.instance.vlan = VLAN.objects.get(site=site, group__isnull=True, vid=vlan_vid)
  271. except VLAN.DoesNotExist:
  272. if site:
  273. raise forms.ValidationError("VLAN {} not found in site {}".format(vlan_vid, site))
  274. else:
  275. raise forms.ValidationError("Global VLAN {} not found".format(vlan_vid))
  276. except MultipleObjectsReturned:
  277. raise forms.ValidationError("Multiple VLANs with VID {} found".format(vlan_vid))
  278. class PrefixBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  279. pk = forms.ModelMultipleChoiceField(queryset=Prefix.objects.all(), widget=forms.MultipleHiddenInput)
  280. site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False)
  281. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF')
  282. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  283. status = forms.ChoiceField(choices=add_blank_choice(PREFIX_STATUS_CHOICES), required=False)
  284. role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False)
  285. is_pool = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Is a pool')
  286. description = forms.CharField(max_length=100, required=False)
  287. class Meta:
  288. nullable_fields = ['site', 'vrf', 'tenant', 'role', 'description']
  289. class PrefixFilterForm(BootstrapMixin, CustomFieldFilterForm):
  290. model = Prefix
  291. q = forms.CharField(required=False, label='Search')
  292. within_include = forms.CharField(required=False, label='Search within', widget=forms.TextInput(attrs={
  293. 'placeholder': 'Prefix',
  294. }))
  295. family = forms.ChoiceField(required=False, choices=IP_FAMILY_CHOICES, label='Address family')
  296. mask_length = forms.ChoiceField(required=False, choices=PREFIX_MASK_LENGTH_CHOICES, label='Mask length')
  297. vrf = FilterChoiceField(
  298. queryset=VRF.objects.annotate(filter_count=Count('prefixes')),
  299. to_field_name='rd',
  300. label='VRF',
  301. null_label='-- Global --'
  302. )
  303. tenant = FilterChoiceField(
  304. queryset=Tenant.objects.annotate(filter_count=Count('prefixes')),
  305. to_field_name='slug',
  306. null_label='-- None --'
  307. )
  308. status = AnnotatedMultipleChoiceField(
  309. choices=PREFIX_STATUS_CHOICES,
  310. annotate=Prefix.objects.all(),
  311. annotate_field='status',
  312. required=False
  313. )
  314. site = FilterChoiceField(
  315. queryset=Site.objects.annotate(filter_count=Count('prefixes')),
  316. to_field_name='slug',
  317. null_label='-- None --'
  318. )
  319. role = FilterChoiceField(
  320. queryset=Role.objects.annotate(filter_count=Count('prefixes')),
  321. to_field_name='slug',
  322. null_label='-- None --'
  323. )
  324. expand = forms.BooleanField(required=False, label='Expand prefix hierarchy')
  325. #
  326. # IP addresses
  327. #
  328. class IPAddressForm(BootstrapMixin, TenancyForm, ReturnURLForm, CustomFieldForm):
  329. interface = forms.ModelChoiceField(
  330. queryset=Interface.objects.all(),
  331. required=False
  332. )
  333. nat_site = forms.ModelChoiceField(
  334. queryset=Site.objects.all(),
  335. required=False,
  336. label='Site',
  337. widget=forms.Select(
  338. attrs={'filter-for': 'nat_rack'}
  339. )
  340. )
  341. nat_rack = ChainedModelChoiceField(
  342. queryset=Rack.objects.all(),
  343. chains=(
  344. ('site', 'nat_site'),
  345. ),
  346. required=False,
  347. label='Rack',
  348. widget=APISelect(
  349. api_url='/api/dcim/racks/?site_id={{nat_site}}',
  350. display_field='display_name',
  351. attrs={'filter-for': 'nat_device', 'nullable': 'true'}
  352. )
  353. )
  354. nat_device = ChainedModelChoiceField(
  355. queryset=Device.objects.all(),
  356. chains=(
  357. ('site', 'nat_site'),
  358. ('rack', 'nat_rack'),
  359. ),
  360. required=False,
  361. label='Device',
  362. widget=APISelect(
  363. api_url='/api/dcim/devices/?site_id={{nat_site}}&rack_id={{nat_rack}}',
  364. display_field='display_name',
  365. attrs={'filter-for': 'nat_inside'}
  366. )
  367. )
  368. nat_inside = ChainedModelChoiceField(
  369. queryset=IPAddress.objects.all(),
  370. chains=(
  371. ('interface__device', 'nat_device'),
  372. ),
  373. required=False,
  374. label='IP Address',
  375. widget=APISelect(
  376. api_url='/api/ipam/ip-addresses/?device_id={{nat_device}}',
  377. display_field='address'
  378. )
  379. )
  380. livesearch = forms.CharField(
  381. required=False,
  382. label='Search',
  383. widget=Livesearch(
  384. query_key='q',
  385. query_url='ipam-api:ipaddress-list',
  386. field_to_update='nat_inside',
  387. obj_label='address'
  388. )
  389. )
  390. primary_for_parent = forms.BooleanField(required=False, label='Make this the primary IP for the device/VM')
  391. class Meta:
  392. model = IPAddress
  393. fields = [
  394. 'address', 'vrf', 'status', 'role', 'description', 'interface', 'primary_for_parent', 'nat_site',
  395. 'nat_rack', 'nat_inside', 'tenant_group', 'tenant',
  396. ]
  397. def __init__(self, *args, **kwargs):
  398. # Initialize helper selectors
  399. instance = kwargs.get('instance')
  400. initial = kwargs.get('initial', {}).copy()
  401. if instance and instance.nat_inside and instance.nat_inside.device is not None:
  402. initial['nat_site'] = instance.nat_inside.device.site
  403. initial['nat_rack'] = instance.nat_inside.device.rack
  404. initial['nat_device'] = instance.nat_inside.device
  405. kwargs['initial'] = initial
  406. super(IPAddressForm, self).__init__(*args, **kwargs)
  407. self.fields['vrf'].empty_label = 'Global'
  408. # Limit interface selections to those belonging to the parent device/VM
  409. if self.instance and self.instance.interface:
  410. self.fields['interface'].queryset = Interface.objects.filter(
  411. device=self.instance.interface.device, virtual_machine=self.instance.interface.virtual_machine
  412. )
  413. else:
  414. self.fields['interface'].choices = []
  415. # Initialize primary_for_parent if IP address is already assigned
  416. if self.instance.pk and self.instance.interface is not None:
  417. parent = self.instance.interface.parent
  418. if (
  419. self.instance.address.version == 4 and parent.primary_ip4_id == self.instance.pk or
  420. self.instance.address.version == 6 and parent.primary_ip6_id == self.instance.pk
  421. ):
  422. self.initial['primary_for_parent'] = True
  423. def clean(self):
  424. super(IPAddressForm, self).clean()
  425. # Primary IP assignment is only available if an interface has been assigned.
  426. if self.cleaned_data.get('primary_for_parent') and not self.cleaned_data.get('interface'):
  427. self.add_error(
  428. 'primary_for_parent', "Only IP addresses assigned to an interface can be designated as primary IPs."
  429. )
  430. def save(self, *args, **kwargs):
  431. ipaddress = super(IPAddressForm, self).save(*args, **kwargs)
  432. # Assign this IPAddress as the primary for the associated Device.
  433. if self.cleaned_data['primary_for_parent']:
  434. parent = self.cleaned_data['interface'].parent
  435. if ipaddress.address.version == 4:
  436. parent.primary_ip4 = ipaddress
  437. else:
  438. parent.primary_ip6 = ipaddress
  439. parent.save()
  440. # Clear assignment as primary for device if set.
  441. elif self.cleaned_data['interface']:
  442. parent = self.cleaned_data['interface'].parent
  443. if ipaddress.address.version == 4 and parent.primary_ip4 == self:
  444. parent.primary_ip4 = None
  445. parent.save()
  446. elif ipaddress.address.version == 6 and parent.primary_ip6 == self:
  447. parent.primary_ip6 = None
  448. parent.save()
  449. return ipaddress
  450. class IPAddressBulkCreateForm(BootstrapMixin, forms.Form):
  451. pattern = ExpandableIPAddressField(label='Address pattern')
  452. class IPAddressBulkAddForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  453. class Meta:
  454. model = IPAddress
  455. fields = ['address', 'vrf', 'status', 'role', 'description', 'tenant_group', 'tenant']
  456. def __init__(self, *args, **kwargs):
  457. super(IPAddressBulkAddForm, self).__init__(*args, **kwargs)
  458. self.fields['vrf'].empty_label = 'Global'
  459. class IPAddressCSVForm(forms.ModelForm):
  460. vrf = forms.ModelChoiceField(
  461. queryset=VRF.objects.all(),
  462. required=False,
  463. to_field_name='rd',
  464. help_text='Route distinguisher of the assigned VRF',
  465. error_messages={
  466. 'invalid_choice': 'VRF not found.',
  467. }
  468. )
  469. tenant = forms.ModelChoiceField(
  470. queryset=Tenant.objects.all(),
  471. to_field_name='name',
  472. required=False,
  473. help_text='Name of the assigned tenant',
  474. error_messages={
  475. 'invalid_choice': 'Tenant not found.',
  476. }
  477. )
  478. status = CSVChoiceField(
  479. choices=IPADDRESS_STATUS_CHOICES,
  480. help_text='Operational status'
  481. )
  482. role = CSVChoiceField(
  483. choices=IPADDRESS_ROLE_CHOICES,
  484. required=False,
  485. help_text='Functional role'
  486. )
  487. device = FlexibleModelChoiceField(
  488. queryset=Device.objects.all(),
  489. required=False,
  490. to_field_name='name',
  491. help_text='Name or ID of assigned device',
  492. error_messages={
  493. 'invalid_choice': 'Device not found.',
  494. }
  495. )
  496. virtual_machine = forms.ModelChoiceField(
  497. queryset=VirtualMachine.objects.all(),
  498. required=False,
  499. to_field_name='name',
  500. help_text='Name of assigned virtual machine',
  501. error_messages={
  502. 'invalid_choice': 'Virtual machine not found.',
  503. }
  504. )
  505. interface_name = forms.CharField(
  506. help_text='Name of assigned interface',
  507. required=False
  508. )
  509. is_primary = forms.BooleanField(
  510. help_text='Make this the primary IP for the assigned device',
  511. required=False
  512. )
  513. class Meta:
  514. model = IPAddress
  515. fields = IPAddress.csv_headers
  516. def clean(self):
  517. super(IPAddressCSVForm, self).clean()
  518. device = self.cleaned_data.get('device')
  519. virtual_machine = self.cleaned_data.get('virtual_machine')
  520. interface_name = self.cleaned_data.get('interface_name')
  521. is_primary = self.cleaned_data.get('is_primary')
  522. # Validate interface
  523. if interface_name and device:
  524. try:
  525. self.instance.interface = Interface.objects.get(device=device, name=interface_name)
  526. except Interface.DoesNotExist:
  527. raise forms.ValidationError("Invalid interface {} for device {}".format(
  528. interface_name, device
  529. ))
  530. elif interface_name and virtual_machine:
  531. try:
  532. self.instance.interface = Interface.objects.get(virtual_machine=virtual_machine, name=interface_name)
  533. except Interface.DoesNotExist:
  534. raise forms.ValidationError("Invalid interface {} for virtual machine {}".format(
  535. interface_name, virtual_machine
  536. ))
  537. elif interface_name:
  538. raise forms.ValidationError("Interface given ({}) but parent device/virtual machine not specified".format(
  539. interface_name
  540. ))
  541. elif device:
  542. raise forms.ValidationError("Device specified ({}) but interface missing".format(device))
  543. elif virtual_machine:
  544. raise forms.ValidationError("Virtual machine specified ({}) but interface missing".format(virtual_machine))
  545. # Validate is_primary
  546. if is_primary and not device and not virtual_machine:
  547. raise forms.ValidationError("No device or virtual machine specified; cannot set as primary IP")
  548. def save(self, *args, **kwargs):
  549. # Set interface
  550. if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
  551. self.instance.interface = Interface.objects.get(
  552. device=self.cleaned_data['device'],
  553. name=self.cleaned_data['interface_name']
  554. )
  555. elif self.cleaned_data['virtual_machine'] and self.cleaned_data['interface_name']:
  556. self.instance.interface = Interface.objects.get(
  557. virtual_machine=self.cleaned_data['virtual_machine'],
  558. name=self.cleaned_data['interface_name']
  559. )
  560. ipaddress = super(IPAddressCSVForm, self).save(*args, **kwargs)
  561. # Set as primary for device/VM
  562. if self.cleaned_data['is_primary']:
  563. parent = self.cleaned_data['device'] or self.cleaned_data['virtual_machine']
  564. if self.instance.address.version == 4:
  565. parent.primary_ip4 = ipaddress
  566. elif self.instance.address.version == 6:
  567. parent.primary_ip6 = ipaddress
  568. parent.save()
  569. return ipaddress
  570. class IPAddressBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  571. pk = forms.ModelMultipleChoiceField(queryset=IPAddress.objects.all(), widget=forms.MultipleHiddenInput)
  572. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF')
  573. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  574. status = forms.ChoiceField(choices=add_blank_choice(IPADDRESS_STATUS_CHOICES), required=False)
  575. role = forms.ChoiceField(choices=add_blank_choice(IPADDRESS_ROLE_CHOICES), required=False)
  576. description = forms.CharField(max_length=100, required=False)
  577. class Meta:
  578. nullable_fields = ['vrf', 'role', 'tenant', 'description']
  579. class IPAddressAssignForm(BootstrapMixin, forms.Form):
  580. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF', empty_label='Global')
  581. address = forms.CharField(label='IP Address')
  582. class IPAddressFilterForm(BootstrapMixin, CustomFieldFilterForm):
  583. model = IPAddress
  584. q = forms.CharField(required=False, label='Search')
  585. parent = forms.CharField(required=False, label='Parent Prefix', widget=forms.TextInput(attrs={
  586. 'placeholder': 'Prefix',
  587. }))
  588. family = forms.ChoiceField(required=False, choices=IP_FAMILY_CHOICES, label='Address family')
  589. mask_length = forms.ChoiceField(required=False, choices=IPADDRESS_MASK_LENGTH_CHOICES, label='Mask length')
  590. vrf = FilterChoiceField(
  591. queryset=VRF.objects.annotate(filter_count=Count('ip_addresses')),
  592. to_field_name='rd',
  593. label='VRF',
  594. null_label='-- Global --'
  595. )
  596. tenant = FilterChoiceField(
  597. queryset=Tenant.objects.annotate(filter_count=Count('ip_addresses')),
  598. to_field_name='slug',
  599. null_label='-- None --'
  600. )
  601. status = AnnotatedMultipleChoiceField(
  602. choices=IPADDRESS_STATUS_CHOICES,
  603. annotate=IPAddress.objects.all(),
  604. annotate_field='status',
  605. required=False
  606. )
  607. role = AnnotatedMultipleChoiceField(
  608. choices=IPADDRESS_ROLE_CHOICES,
  609. annotate=IPAddress.objects.all(),
  610. annotate_field='role',
  611. required=False
  612. )
  613. #
  614. # VLAN groups
  615. #
  616. class VLANGroupForm(BootstrapMixin, forms.ModelForm):
  617. slug = SlugField()
  618. class Meta:
  619. model = VLANGroup
  620. fields = ['site', 'name', 'slug']
  621. class VLANGroupCSVForm(forms.ModelForm):
  622. site = forms.ModelChoiceField(
  623. queryset=Site.objects.all(),
  624. required=False,
  625. to_field_name='name',
  626. help_text='Name of parent site',
  627. error_messages={
  628. 'invalid_choice': 'Site not found.',
  629. }
  630. )
  631. slug = SlugField()
  632. class Meta:
  633. model = VLANGroup
  634. fields = VLANGroup.csv_headers
  635. help_texts = {
  636. 'name': 'Name of VLAN group',
  637. }
  638. class VLANGroupFilterForm(BootstrapMixin, forms.Form):
  639. site = FilterChoiceField(
  640. queryset=Site.objects.annotate(filter_count=Count('vlan_groups')),
  641. to_field_name='slug',
  642. null_label='-- Global --'
  643. )
  644. #
  645. # VLANs
  646. #
  647. class VLANForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  648. site = forms.ModelChoiceField(
  649. queryset=Site.objects.all(),
  650. required=False,
  651. widget=forms.Select(
  652. attrs={'filter-for': 'group', 'nullable': 'true'}
  653. )
  654. )
  655. group = ChainedModelChoiceField(
  656. queryset=VLANGroup.objects.all(),
  657. chains=(
  658. ('site', 'site'),
  659. ),
  660. required=False,
  661. label='Group',
  662. widget=APISelect(
  663. api_url='/api/ipam/vlan-groups/?site_id={{site}}',
  664. )
  665. )
  666. class Meta:
  667. model = VLAN
  668. fields = ['site', 'group', 'vid', 'name', 'status', 'role', 'description', 'tenant_group', 'tenant']
  669. help_texts = {
  670. 'site': "Leave blank if this VLAN spans multiple sites",
  671. 'group': "VLAN group (optional)",
  672. 'vid': "Configured VLAN ID",
  673. 'name': "Configured VLAN name",
  674. 'status': "Operational status of this VLAN",
  675. 'role': "The primary function of this VLAN",
  676. }
  677. class VLANCSVForm(forms.ModelForm):
  678. site = forms.ModelChoiceField(
  679. queryset=Site.objects.all(),
  680. required=False,
  681. to_field_name='name',
  682. help_text='Name of parent site',
  683. error_messages={
  684. 'invalid_choice': 'Site not found.',
  685. }
  686. )
  687. group_name = forms.CharField(
  688. help_text='Name of VLAN group',
  689. required=False
  690. )
  691. tenant = forms.ModelChoiceField(
  692. queryset=Tenant.objects.all(),
  693. to_field_name='name',
  694. required=False,
  695. help_text='Name of assigned tenant',
  696. error_messages={
  697. 'invalid_choice': 'Tenant not found.',
  698. }
  699. )
  700. status = CSVChoiceField(
  701. choices=VLAN_STATUS_CHOICES,
  702. help_text='Operational status'
  703. )
  704. role = forms.ModelChoiceField(
  705. queryset=Role.objects.all(),
  706. required=False,
  707. to_field_name='name',
  708. help_text='Functional role',
  709. error_messages={
  710. 'invalid_choice': 'Invalid role.',
  711. }
  712. )
  713. class Meta:
  714. model = VLAN
  715. fields = VLAN.csv_headers
  716. help_texts = {
  717. 'vid': 'Numeric VLAN ID (1-4095)',
  718. 'name': 'VLAN name',
  719. }
  720. def clean(self):
  721. super(VLANCSVForm, self).clean()
  722. site = self.cleaned_data.get('site')
  723. group_name = self.cleaned_data.get('group_name')
  724. # Validate VLAN group
  725. if group_name:
  726. try:
  727. self.instance.group = VLANGroup.objects.get(site=site, name=group_name)
  728. except VLANGroup.DoesNotExist:
  729. if site:
  730. raise forms.ValidationError("VLAN group {} not found for site {}".format(group_name, site))
  731. else:
  732. raise forms.ValidationError("Global VLAN group {} not found".format(group_name))
  733. class VLANBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  734. pk = forms.ModelMultipleChoiceField(queryset=VLAN.objects.all(), widget=forms.MultipleHiddenInput)
  735. site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False)
  736. group = forms.ModelChoiceField(queryset=VLANGroup.objects.all(), required=False)
  737. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  738. status = forms.ChoiceField(choices=add_blank_choice(VLAN_STATUS_CHOICES), required=False)
  739. role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False)
  740. description = forms.CharField(max_length=100, required=False)
  741. class Meta:
  742. nullable_fields = ['site', 'group', 'tenant', 'role', 'description']
  743. class VLANFilterForm(BootstrapMixin, CustomFieldFilterForm):
  744. model = VLAN
  745. q = forms.CharField(required=False, label='Search')
  746. site = FilterChoiceField(
  747. queryset=Site.objects.annotate(filter_count=Count('vlans')),
  748. to_field_name='slug',
  749. null_label='-- Global --'
  750. )
  751. group_id = FilterChoiceField(
  752. queryset=VLANGroup.objects.annotate(filter_count=Count('vlans')),
  753. label='VLAN group',
  754. null_label='-- None --'
  755. )
  756. tenant = FilterChoiceField(
  757. queryset=Tenant.objects.annotate(filter_count=Count('vlans')),
  758. to_field_name='slug',
  759. null_label='-- None --'
  760. )
  761. status = AnnotatedMultipleChoiceField(
  762. choices=VLAN_STATUS_CHOICES,
  763. annotate=VLAN.objects.all(),
  764. annotate_field='status',
  765. required=False
  766. )
  767. role = FilterChoiceField(
  768. queryset=Role.objects.annotate(filter_count=Count('vlans')),
  769. to_field_name='slug',
  770. null_label='-- None --'
  771. )
  772. #
  773. # Services
  774. #
  775. class ServiceForm(BootstrapMixin, forms.ModelForm):
  776. class Meta:
  777. model = Service
  778. fields = ['name', 'protocol', 'port', 'ipaddresses', 'description']
  779. help_texts = {
  780. 'ipaddresses': "IP address assignment is optional. If no IPs are selected, the service is assumed to be "
  781. "reachable via all IPs assigned to the device.",
  782. }
  783. def __init__(self, *args, **kwargs):
  784. super(ServiceForm, self).__init__(*args, **kwargs)
  785. # Limit IP address choices to those assigned to interfaces of the parent device/VM
  786. if self.instance.device:
  787. vc_interface_ids = [i['id'] for i in self.instance.device.vc_interfaces.values('id')]
  788. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  789. interface_id__in=vc_interface_ids
  790. )
  791. elif self.instance.virtual_machine:
  792. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  793. interface__virtual_machine=self.instance.virtual_machine
  794. )
  795. else:
  796. self.fields['ipaddresses'].choices = []