forms.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. APISelect, BootstrapMixin, BulkEditNullBooleanSelect, ChainedModelChoiceField, CSVChoiceField,
  11. ExpandableIPAddressField, FilterChoiceField, FlexibleModelChoiceField, Livesearch, ReturnURLForm, SlugField,
  12. 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 = ['name', 'rd', 'tenant', 'enforce_unique', 'description']
  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 = ['name', 'slug', 'is_private']
  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 = ['prefix', 'rir', 'date_added', 'description']
  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 = ['name', 'slug']
  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 = [
  248. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan_vid', 'status', 'role', 'is_pool', 'description',
  249. ]
  250. def clean(self):
  251. super(PrefixCSVForm, self).clean()
  252. site = self.cleaned_data.get('site')
  253. vlan_group = self.cleaned_data.get('vlan_group')
  254. vlan_vid = self.cleaned_data.get('vlan_vid')
  255. # Validate VLAN
  256. if vlan_group and vlan_vid:
  257. try:
  258. self.instance.vlan = VLAN.objects.get(site=site, group__name=vlan_group, vid=vlan_vid)
  259. except VLAN.DoesNotExist:
  260. if site:
  261. raise forms.ValidationError("VLAN {} not found in site {} group {}".format(
  262. vlan_vid, site, vlan_group
  263. ))
  264. else:
  265. raise forms.ValidationError("Global VLAN {} not found in group {}".format(vlan_vid, vlan_group))
  266. except MultipleObjectsReturned:
  267. raise forms.ValidationError(
  268. "Multiple VLANs with VID {} found in group {}".format(vlan_vid, vlan_group)
  269. )
  270. elif vlan_vid:
  271. try:
  272. self.instance.vlan = VLAN.objects.get(site=site, group__isnull=True, vid=vlan_vid)
  273. except VLAN.DoesNotExist:
  274. if site:
  275. raise forms.ValidationError("VLAN {} not found in site {}".format(vlan_vid, site))
  276. else:
  277. raise forms.ValidationError("Global VLAN {} not found".format(vlan_vid))
  278. except MultipleObjectsReturned:
  279. raise forms.ValidationError("Multiple VLANs with VID {} found".format(vlan_vid))
  280. class PrefixBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  281. pk = forms.ModelMultipleChoiceField(queryset=Prefix.objects.all(), widget=forms.MultipleHiddenInput)
  282. site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False)
  283. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF')
  284. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  285. status = forms.ChoiceField(choices=add_blank_choice(PREFIX_STATUS_CHOICES), required=False)
  286. role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False)
  287. is_pool = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Is a pool')
  288. description = forms.CharField(max_length=100, required=False)
  289. class Meta:
  290. nullable_fields = ['site', 'vrf', 'tenant', 'role', 'description']
  291. def prefix_status_choices():
  292. status_counts = {}
  293. for status in Prefix.objects.values('status').annotate(count=Count('status')).order_by('status'):
  294. status_counts[status['status']] = status['count']
  295. return [(s[0], '{} ({})'.format(s[1], status_counts.get(s[0], 0))) for s in PREFIX_STATUS_CHOICES]
  296. class PrefixFilterForm(BootstrapMixin, CustomFieldFilterForm):
  297. model = Prefix
  298. q = forms.CharField(required=False, label='Search')
  299. within_include = forms.CharField(required=False, label='Search within', widget=forms.TextInput(attrs={
  300. 'placeholder': 'Prefix',
  301. }))
  302. family = forms.ChoiceField(required=False, choices=IP_FAMILY_CHOICES, label='Address family')
  303. mask_length = forms.ChoiceField(required=False, choices=PREFIX_MASK_LENGTH_CHOICES, label='Mask length')
  304. vrf = FilterChoiceField(
  305. queryset=VRF.objects.annotate(filter_count=Count('prefixes')),
  306. to_field_name='rd',
  307. label='VRF',
  308. null_label='-- Global --'
  309. )
  310. tenant = FilterChoiceField(
  311. queryset=Tenant.objects.annotate(filter_count=Count('prefixes')),
  312. to_field_name='slug',
  313. null_label='-- None --'
  314. )
  315. status = forms.MultipleChoiceField(choices=prefix_status_choices, required=False)
  316. site = FilterChoiceField(
  317. queryset=Site.objects.annotate(filter_count=Count('prefixes')),
  318. to_field_name='slug',
  319. null_label='-- None --'
  320. )
  321. role = FilterChoiceField(
  322. queryset=Role.objects.annotate(filter_count=Count('prefixes')),
  323. to_field_name='slug',
  324. null_label='-- None --'
  325. )
  326. expand = forms.BooleanField(required=False, label='Expand prefix hierarchy')
  327. #
  328. # IP addresses
  329. #
  330. class IPAddressForm(BootstrapMixin, TenancyForm, ReturnURLForm, CustomFieldForm):
  331. interface = forms.ModelChoiceField(
  332. queryset=Interface.objects.all(),
  333. required=False
  334. )
  335. nat_site = forms.ModelChoiceField(
  336. queryset=Site.objects.all(),
  337. required=False,
  338. label='Site',
  339. widget=forms.Select(
  340. attrs={'filter-for': 'nat_rack'}
  341. )
  342. )
  343. nat_rack = ChainedModelChoiceField(
  344. queryset=Rack.objects.all(),
  345. chains=(
  346. ('site', 'nat_site'),
  347. ),
  348. required=False,
  349. label='Rack',
  350. widget=APISelect(
  351. api_url='/api/dcim/racks/?site_id={{nat_site}}',
  352. display_field='display_name',
  353. attrs={'filter-for': 'nat_device', 'nullable': 'true'}
  354. )
  355. )
  356. nat_device = ChainedModelChoiceField(
  357. queryset=Device.objects.all(),
  358. chains=(
  359. ('site', 'nat_site'),
  360. ('rack', 'nat_rack'),
  361. ),
  362. required=False,
  363. label='Device',
  364. widget=APISelect(
  365. api_url='/api/dcim/devices/?site_id={{nat_site}}&rack_id={{nat_rack}}',
  366. display_field='display_name',
  367. attrs={'filter-for': 'nat_inside'}
  368. )
  369. )
  370. nat_inside = ChainedModelChoiceField(
  371. queryset=IPAddress.objects.all(),
  372. chains=(
  373. ('interface__device', 'nat_device'),
  374. ),
  375. required=False,
  376. label='IP Address',
  377. widget=APISelect(
  378. api_url='/api/ipam/ip-addresses/?device_id={{nat_device}}',
  379. display_field='address'
  380. )
  381. )
  382. livesearch = forms.CharField(
  383. required=False,
  384. label='Search',
  385. widget=Livesearch(
  386. query_key='q',
  387. query_url='ipam-api:ipaddress-list',
  388. field_to_update='nat_inside',
  389. obj_label='address'
  390. )
  391. )
  392. primary_for_parent = forms.BooleanField(required=False, label='Make this the primary IP for the device/VM')
  393. class Meta:
  394. model = IPAddress
  395. fields = [
  396. 'address', 'vrf', 'status', 'role', 'description', 'interface', 'primary_for_parent', 'nat_site',
  397. 'nat_rack', 'nat_inside', 'tenant_group', 'tenant',
  398. ]
  399. def __init__(self, *args, **kwargs):
  400. # Initialize helper selectors
  401. instance = kwargs.get('instance')
  402. initial = kwargs.get('initial', {}).copy()
  403. if instance and instance.nat_inside and instance.nat_inside.device is not None:
  404. initial['nat_site'] = instance.nat_inside.device.site
  405. initial['nat_rack'] = instance.nat_inside.device.rack
  406. initial['nat_device'] = instance.nat_inside.device
  407. kwargs['initial'] = initial
  408. super(IPAddressForm, self).__init__(*args, **kwargs)
  409. self.fields['vrf'].empty_label = 'Global'
  410. # Limit interface selections to those belonging to the parent device/VM
  411. if self.instance and self.instance.interface:
  412. self.fields['interface'].queryset = Interface.objects.filter(
  413. device=self.instance.interface.device, virtual_machine=self.instance.interface.virtual_machine
  414. )
  415. else:
  416. self.fields['interface'].choices = []
  417. # Initialize primary_for_parent if IP address is already assigned
  418. if self.instance.pk and self.instance.interface is not None:
  419. parent = self.instance.interface.parent
  420. if (
  421. self.instance.address.version == 4 and parent.primary_ip4_id == self.instance.pk or
  422. self.instance.address.version == 6 and parent.primary_ip6_id == self.instance.pk
  423. ):
  424. self.initial['primary_for_parent'] = True
  425. def clean(self):
  426. super(IPAddressForm, self).clean()
  427. # Primary IP assignment is only available if an interface has been assigned.
  428. if self.cleaned_data.get('primary_for_parent') and not self.cleaned_data.get('interface'):
  429. self.add_error(
  430. 'primary_for_parent', "Only IP addresses assigned to an interface can be designated as primary IPs."
  431. )
  432. def save(self, *args, **kwargs):
  433. ipaddress = super(IPAddressForm, self).save(*args, **kwargs)
  434. # Assign this IPAddress as the primary for the associated Device.
  435. if self.cleaned_data['primary_for_parent']:
  436. parent = self.cleaned_data['interface'].parent
  437. if ipaddress.address.version == 4:
  438. parent.primary_ip4 = ipaddress
  439. else:
  440. parent.primary_ip6 = ipaddress
  441. parent.save()
  442. # Clear assignment as primary for device if set.
  443. else:
  444. try:
  445. if ipaddress.address.version == 4:
  446. device = ipaddress.primary_ip4_for
  447. device.primary_ip4 = None
  448. else:
  449. device = ipaddress.primary_ip6_for
  450. device.primary_ip6 = None
  451. device.save()
  452. except Device.DoesNotExist:
  453. pass
  454. return ipaddress
  455. class IPAddressBulkCreateForm(BootstrapMixin, forms.Form):
  456. pattern = ExpandableIPAddressField(label='Address pattern')
  457. class IPAddressBulkAddForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  458. class Meta:
  459. model = IPAddress
  460. fields = ['address', 'vrf', 'status', 'role', 'description', 'tenant_group', 'tenant']
  461. def __init__(self, *args, **kwargs):
  462. super(IPAddressBulkAddForm, self).__init__(*args, **kwargs)
  463. self.fields['vrf'].empty_label = 'Global'
  464. class IPAddressCSVForm(forms.ModelForm):
  465. vrf = forms.ModelChoiceField(
  466. queryset=VRF.objects.all(),
  467. required=False,
  468. to_field_name='rd',
  469. help_text='Route distinguisher of the assigned VRF',
  470. error_messages={
  471. 'invalid_choice': 'VRF not found.',
  472. }
  473. )
  474. tenant = forms.ModelChoiceField(
  475. queryset=Tenant.objects.all(),
  476. to_field_name='name',
  477. required=False,
  478. help_text='Name of the assigned tenant',
  479. error_messages={
  480. 'invalid_choice': 'Tenant not found.',
  481. }
  482. )
  483. status = CSVChoiceField(
  484. choices=IPADDRESS_STATUS_CHOICES,
  485. help_text='Operational status'
  486. )
  487. role = CSVChoiceField(
  488. choices=IPADDRESS_ROLE_CHOICES,
  489. required=False,
  490. help_text='Functional role'
  491. )
  492. device = FlexibleModelChoiceField(
  493. queryset=Device.objects.all(),
  494. required=False,
  495. to_field_name='name',
  496. help_text='Name or ID of assigned device',
  497. error_messages={
  498. 'invalid_choice': 'Device not found.',
  499. }
  500. )
  501. virtual_machine = forms.ModelChoiceField(
  502. queryset=VirtualMachine.objects.all(),
  503. required=False,
  504. to_field_name='name',
  505. help_text='Name of assigned virtual machine',
  506. error_messages={
  507. 'invalid_choice': 'Virtual machine not found.',
  508. }
  509. )
  510. interface_name = forms.CharField(
  511. help_text='Name of assigned interface',
  512. required=False
  513. )
  514. is_primary = forms.BooleanField(
  515. help_text='Make this the primary IP for the assigned device',
  516. required=False
  517. )
  518. class Meta:
  519. model = IPAddress
  520. fields = [
  521. 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface_name', 'is_primary',
  522. 'description',
  523. ]
  524. def clean(self):
  525. super(IPAddressCSVForm, self).clean()
  526. device = self.cleaned_data.get('device')
  527. virtual_machine = self.cleaned_data.get('virtual_machine')
  528. interface_name = self.cleaned_data.get('interface_name')
  529. is_primary = self.cleaned_data.get('is_primary')
  530. # Validate interface
  531. if interface_name and device:
  532. try:
  533. self.instance.interface = Interface.objects.get(device=device, name=interface_name)
  534. except Interface.DoesNotExist:
  535. raise forms.ValidationError("Invalid interface {} for device {}".format(
  536. interface_name, device
  537. ))
  538. elif interface_name and virtual_machine:
  539. try:
  540. self.instance.interface = Interface.objects.get(virtual_machine=virtual_machine, name=interface_name)
  541. except Interface.DoesNotExist:
  542. raise forms.ValidationError("Invalid interface {} for virtual machine {}".format(
  543. interface_name, virtual_machine
  544. ))
  545. elif interface_name:
  546. raise forms.ValidationError("Interface given ({}) but parent device/virtual machine not specified".format(
  547. interface_name
  548. ))
  549. elif device:
  550. raise forms.ValidationError("Device specified ({}) but interface missing".format(device))
  551. elif virtual_machine:
  552. raise forms.ValidationError("Virtual machine specified ({}) but interface missing".format(virtual_machine))
  553. # Validate is_primary
  554. if is_primary and not device and not virtual_machine:
  555. raise forms.ValidationError("No device or virtual machine specified; cannot set as primary IP")
  556. def save(self, *args, **kwargs):
  557. # Set interface
  558. if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
  559. self.instance.interface = Interface.objects.get(
  560. device=self.cleaned_data['device'],
  561. name=self.cleaned_data['interface_name']
  562. )
  563. elif self.cleaned_data['virtual_machine'] and self.cleaned_data['interface_name']:
  564. self.instance.interface = Interface.objects.get(
  565. virtual_machine=self.cleaned_data['virtual_machine'],
  566. name=self.cleaned_data['interface_name']
  567. )
  568. ipaddress = super(IPAddressCSVForm, self).save(*args, **kwargs)
  569. # Set as primary for device/VM
  570. if self.cleaned_data['is_primary']:
  571. parent = self.cleaned_data['device'] or self.cleaned_data['virtual_machine']
  572. if self.instance.address.version == 4:
  573. parent.primary_ip4 = ipaddress
  574. elif self.instance.address.version == 6:
  575. parent.primary_ip6 = ipaddress
  576. parent.save()
  577. return ipaddress
  578. class IPAddressBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  579. pk = forms.ModelMultipleChoiceField(queryset=IPAddress.objects.all(), widget=forms.MultipleHiddenInput)
  580. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF')
  581. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  582. status = forms.ChoiceField(choices=add_blank_choice(IPADDRESS_STATUS_CHOICES), required=False)
  583. role = forms.ChoiceField(choices=add_blank_choice(IPADDRESS_ROLE_CHOICES), required=False)
  584. description = forms.CharField(max_length=100, required=False)
  585. class Meta:
  586. nullable_fields = ['vrf', 'role', 'tenant', 'description']
  587. class IPAddressAssignForm(BootstrapMixin, forms.Form):
  588. vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, label='VRF', empty_label='Global')
  589. address = forms.CharField(label='IP Address')
  590. def ipaddress_status_choices():
  591. status_counts = {}
  592. for status in IPAddress.objects.values('status').annotate(count=Count('status')).order_by('status'):
  593. status_counts[status['status']] = status['count']
  594. return [(s[0], '{} ({})'.format(s[1], status_counts.get(s[0], 0))) for s in IPADDRESS_STATUS_CHOICES]
  595. def ipaddress_role_choices():
  596. role_counts = {}
  597. for role in IPAddress.objects.values('role').annotate(count=Count('role')).order_by('role'):
  598. role_counts[role['role']] = role['count']
  599. return [(r[0], '{} ({})'.format(r[1], role_counts.get(r[0], 0))) for r in IPADDRESS_ROLE_CHOICES]
  600. class IPAddressFilterForm(BootstrapMixin, CustomFieldFilterForm):
  601. model = IPAddress
  602. q = forms.CharField(required=False, label='Search')
  603. parent = forms.CharField(required=False, label='Parent Prefix', widget=forms.TextInput(attrs={
  604. 'placeholder': 'Prefix',
  605. }))
  606. family = forms.ChoiceField(required=False, choices=IP_FAMILY_CHOICES, label='Address family')
  607. mask_length = forms.ChoiceField(required=False, choices=IPADDRESS_MASK_LENGTH_CHOICES, label='Mask length')
  608. vrf = FilterChoiceField(
  609. queryset=VRF.objects.annotate(filter_count=Count('ip_addresses')),
  610. to_field_name='rd',
  611. label='VRF',
  612. null_label='-- Global --'
  613. )
  614. tenant = FilterChoiceField(
  615. queryset=Tenant.objects.annotate(filter_count=Count('ip_addresses')),
  616. to_field_name='slug',
  617. null_label='-- None --'
  618. )
  619. status = forms.MultipleChoiceField(choices=ipaddress_status_choices, required=False)
  620. role = forms.MultipleChoiceField(choices=ipaddress_role_choices, required=False)
  621. #
  622. # VLAN groups
  623. #
  624. class VLANGroupForm(BootstrapMixin, forms.ModelForm):
  625. slug = SlugField()
  626. class Meta:
  627. model = VLANGroup
  628. fields = ['site', 'name', 'slug']
  629. class VLANGroupCSVForm(forms.ModelForm):
  630. site = forms.ModelChoiceField(
  631. queryset=Site.objects.all(),
  632. required=False,
  633. to_field_name='name',
  634. help_text='Name of parent site',
  635. error_messages={
  636. 'invalid_choice': 'Site not found.',
  637. }
  638. )
  639. slug = SlugField()
  640. class Meta:
  641. model = VLANGroup
  642. fields = ['site', 'name', 'slug']
  643. help_texts = {
  644. 'name': 'Name of VLAN group',
  645. }
  646. class VLANGroupFilterForm(BootstrapMixin, forms.Form):
  647. site = FilterChoiceField(
  648. queryset=Site.objects.annotate(filter_count=Count('vlan_groups')),
  649. to_field_name='slug',
  650. null_label='-- Global --'
  651. )
  652. #
  653. # VLANs
  654. #
  655. class VLANForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  656. site = forms.ModelChoiceField(
  657. queryset=Site.objects.all(),
  658. required=False,
  659. widget=forms.Select(
  660. attrs={'filter-for': 'group', 'nullable': 'true'}
  661. )
  662. )
  663. group = ChainedModelChoiceField(
  664. queryset=VLANGroup.objects.all(),
  665. chains=(
  666. ('site', 'site'),
  667. ),
  668. required=False,
  669. label='Group',
  670. widget=APISelect(
  671. api_url='/api/ipam/vlan-groups/?site_id={{site}}',
  672. )
  673. )
  674. class Meta:
  675. model = VLAN
  676. fields = ['site', 'group', 'vid', 'name', 'status', 'role', 'description', 'tenant_group', 'tenant']
  677. help_texts = {
  678. 'site': "Leave blank if this VLAN spans multiple sites",
  679. 'group': "VLAN group (optional)",
  680. 'vid': "Configured VLAN ID",
  681. 'name': "Configured VLAN name",
  682. 'status': "Operational status of this VLAN",
  683. 'role': "The primary function of this VLAN",
  684. }
  685. class VLANCSVForm(forms.ModelForm):
  686. site = forms.ModelChoiceField(
  687. queryset=Site.objects.all(),
  688. required=False,
  689. to_field_name='name',
  690. help_text='Name of parent site',
  691. error_messages={
  692. 'invalid_choice': 'Site not found.',
  693. }
  694. )
  695. group_name = forms.CharField(
  696. help_text='Name of VLAN group',
  697. required=False
  698. )
  699. tenant = forms.ModelChoiceField(
  700. queryset=Tenant.objects.all(),
  701. to_field_name='name',
  702. required=False,
  703. help_text='Name of assigned tenant',
  704. error_messages={
  705. 'invalid_choice': 'Tenant not found.',
  706. }
  707. )
  708. status = CSVChoiceField(
  709. choices=VLAN_STATUS_CHOICES,
  710. help_text='Operational status'
  711. )
  712. role = forms.ModelChoiceField(
  713. queryset=Role.objects.all(),
  714. required=False,
  715. to_field_name='name',
  716. help_text='Functional role',
  717. error_messages={
  718. 'invalid_choice': 'Invalid role.',
  719. }
  720. )
  721. class Meta:
  722. model = VLAN
  723. fields = ['site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description']
  724. help_texts = {
  725. 'vid': 'Numeric VLAN ID (1-4095)',
  726. 'name': 'VLAN name',
  727. }
  728. def clean(self):
  729. super(VLANCSVForm, self).clean()
  730. site = self.cleaned_data.get('site')
  731. group_name = self.cleaned_data.get('group_name')
  732. # Validate VLAN group
  733. if group_name:
  734. try:
  735. self.instance.group = VLANGroup.objects.get(site=site, name=group_name)
  736. except VLANGroup.DoesNotExist:
  737. if site:
  738. raise forms.ValidationError("VLAN group {} not found for site {}".format(group_name, site))
  739. else:
  740. raise forms.ValidationError("Global VLAN group {} not found".format(group_name))
  741. class VLANBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  742. pk = forms.ModelMultipleChoiceField(queryset=VLAN.objects.all(), widget=forms.MultipleHiddenInput)
  743. site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False)
  744. group = forms.ModelChoiceField(queryset=VLANGroup.objects.all(), required=False)
  745. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  746. status = forms.ChoiceField(choices=add_blank_choice(VLAN_STATUS_CHOICES), required=False)
  747. role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False)
  748. description = forms.CharField(max_length=100, required=False)
  749. class Meta:
  750. nullable_fields = ['site', 'group', 'tenant', 'role', 'description']
  751. def vlan_status_choices():
  752. status_counts = {}
  753. for status in VLAN.objects.values('status').annotate(count=Count('status')).order_by('status'):
  754. status_counts[status['status']] = status['count']
  755. return [(s[0], '{} ({})'.format(s[1], status_counts.get(s[0], 0))) for s in VLAN_STATUS_CHOICES]
  756. class VLANFilterForm(BootstrapMixin, CustomFieldFilterForm):
  757. model = VLAN
  758. q = forms.CharField(required=False, label='Search')
  759. site = FilterChoiceField(
  760. queryset=Site.objects.annotate(filter_count=Count('vlans')),
  761. to_field_name='slug',
  762. null_label='-- Global --'
  763. )
  764. group_id = FilterChoiceField(
  765. queryset=VLANGroup.objects.annotate(filter_count=Count('vlans')),
  766. label='VLAN group',
  767. null_label='-- None --'
  768. )
  769. tenant = FilterChoiceField(
  770. queryset=Tenant.objects.annotate(filter_count=Count('vlans')),
  771. to_field_name='slug',
  772. null_label='-- None --'
  773. )
  774. status = forms.MultipleChoiceField(choices=vlan_status_choices, required=False)
  775. role = FilterChoiceField(
  776. queryset=Role.objects.annotate(filter_count=Count('vlans')),
  777. to_field_name='slug',
  778. null_label='-- None --'
  779. )
  780. #
  781. # Services
  782. #
  783. class ServiceForm(BootstrapMixin, forms.ModelForm):
  784. class Meta:
  785. model = Service
  786. fields = ['name', 'protocol', 'port', 'ipaddresses', 'description']
  787. help_texts = {
  788. 'ipaddresses': "IP address assignment is optional. If no IPs are selected, the service is assumed to be "
  789. "reachable via all IPs assigned to the device.",
  790. }
  791. def __init__(self, *args, **kwargs):
  792. super(ServiceForm, self).__init__(*args, **kwargs)
  793. # Limit IP address choices to those assigned to interfaces of the parent device/VM
  794. if self.instance.device:
  795. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  796. interface__device=self.instance.device
  797. )
  798. elif self.instance.virtual_machine:
  799. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  800. interface__virtual_machine=self.instance.virtual_machine
  801. )
  802. else:
  803. self.fields['ipaddresses'].choices = []