forms.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. from django import forms
  2. from django.core.exceptions import MultipleObjectsReturned
  3. from django.core.validators import MaxValueValidator, MinValueValidator
  4. from taggit.forms import TagField
  5. from dcim.models import Site, Rack, Device, Interface
  6. from extras.forms import AddRemoveTagsForm, CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm
  7. from tenancy.forms import TenancyForm
  8. from tenancy.models import Tenant
  9. from utilities.forms import (
  10. add_blank_choice, APISelect, APISelectMultiple, BootstrapMixin, BulkEditNullBooleanSelect, ChainedModelChoiceField,
  11. CSVChoiceField, ExpandableIPAddressField, FilterChoiceField, FlexibleModelChoiceField, ReturnURLForm, SlugField,
  12. StaticSelect2, StaticSelect2Multiple, BOOLEAN_WITH_BLANK_CHOICES
  13. )
  14. from virtualization.models import VirtualMachine
  15. from .constants import (
  16. IP_PROTOCOL_CHOICES, IPADDRESS_ROLE_CHOICES, IPADDRESS_STATUS_CHOICES, PREFIX_STATUS_CHOICES, VLAN_STATUS_CHOICES,
  17. )
  18. from .models import Aggregate, IPAddress, Prefix, RIR, Role, Service, VLAN, VLANGroup, VRF
  19. IP_FAMILY_CHOICES = [
  20. ('', 'All'),
  21. (4, 'IPv4'),
  22. (6, 'IPv6'),
  23. ]
  24. PREFIX_MASK_LENGTH_CHOICES = add_blank_choice([(i, i) for i in range(1, 128)])
  25. IPADDRESS_MASK_LENGTH_CHOICES = add_blank_choice([(i, i) for i in range(1, 129)])
  26. #
  27. # VRFs
  28. #
  29. class VRFForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  30. tags = TagField(
  31. required=False
  32. )
  33. class Meta:
  34. model = VRF
  35. fields = [
  36. 'name', 'rd', 'enforce_unique', 'description', 'tenant_group', 'tenant', 'tags',
  37. ]
  38. labels = {
  39. 'rd': "RD",
  40. }
  41. help_texts = {
  42. 'rd': "Route distinguisher in any format",
  43. }
  44. class VRFCSVForm(forms.ModelForm):
  45. tenant = forms.ModelChoiceField(
  46. queryset=Tenant.objects.all(),
  47. required=False,
  48. to_field_name='name',
  49. help_text='Name of assigned tenant',
  50. error_messages={
  51. 'invalid_choice': 'Tenant not found.',
  52. }
  53. )
  54. class Meta:
  55. model = VRF
  56. fields = VRF.csv_headers
  57. help_texts = {
  58. 'name': 'VRF name',
  59. }
  60. class VRFBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  61. pk = forms.ModelMultipleChoiceField(
  62. queryset=VRF.objects.all(),
  63. widget=forms.MultipleHiddenInput()
  64. )
  65. tenant = forms.ModelChoiceField(
  66. queryset=Tenant.objects.all(),
  67. required=False,
  68. widget=APISelect(
  69. api_url="/api/tenancy/tenants/"
  70. )
  71. )
  72. enforce_unique = forms.NullBooleanField(
  73. required=False,
  74. widget=BulkEditNullBooleanSelect(),
  75. label='Enforce unique space'
  76. )
  77. description = forms.CharField(
  78. max_length=100,
  79. required=False
  80. )
  81. class Meta:
  82. nullable_fields = [
  83. 'tenant', 'description',
  84. ]
  85. class VRFFilterForm(BootstrapMixin, CustomFieldFilterForm):
  86. model = VRF
  87. q = forms.CharField(
  88. required=False,
  89. label='Search'
  90. )
  91. tenant = FilterChoiceField(
  92. queryset=Tenant.objects.all(),
  93. to_field_name='slug',
  94. null_label='-- None --',
  95. widget=APISelectMultiple(
  96. api_url="/api/tenancy/tenants/",
  97. value_field="slug",
  98. null_option=True,
  99. )
  100. )
  101. #
  102. # RIRs
  103. #
  104. class RIRForm(BootstrapMixin, forms.ModelForm):
  105. slug = SlugField()
  106. class Meta:
  107. model = RIR
  108. fields = [
  109. 'name', 'slug', 'is_private',
  110. ]
  111. class RIRCSVForm(forms.ModelForm):
  112. slug = SlugField()
  113. class Meta:
  114. model = RIR
  115. fields = RIR.csv_headers
  116. help_texts = {
  117. 'name': 'RIR name',
  118. }
  119. class RIRFilterForm(BootstrapMixin, forms.Form):
  120. is_private = forms.NullBooleanField(
  121. required=False,
  122. label='Private',
  123. widget=StaticSelect2(
  124. choices=BOOLEAN_WITH_BLANK_CHOICES
  125. )
  126. )
  127. #
  128. # Aggregates
  129. #
  130. class AggregateForm(BootstrapMixin, CustomFieldForm):
  131. tags = TagField(
  132. required=False
  133. )
  134. class Meta:
  135. model = Aggregate
  136. fields = [
  137. 'prefix', 'rir', 'date_added', 'description', 'tags',
  138. ]
  139. help_texts = {
  140. 'prefix': "IPv4 or IPv6 network",
  141. 'rir': "Regional Internet Registry responsible for this prefix",
  142. 'date_added': "Format: YYYY-MM-DD",
  143. }
  144. widgets = {
  145. 'rir': APISelect(
  146. api_url="/api/ipam/rirs/"
  147. )
  148. }
  149. class AggregateCSVForm(forms.ModelForm):
  150. rir = forms.ModelChoiceField(
  151. queryset=RIR.objects.all(),
  152. to_field_name='name',
  153. help_text='Name of parent RIR',
  154. error_messages={
  155. 'invalid_choice': 'RIR not found.',
  156. }
  157. )
  158. class Meta:
  159. model = Aggregate
  160. fields = Aggregate.csv_headers
  161. class AggregateBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  162. pk = forms.ModelMultipleChoiceField(
  163. queryset=Aggregate.objects.all(),
  164. widget=forms.MultipleHiddenInput()
  165. )
  166. rir = forms.ModelChoiceField(
  167. queryset=RIR.objects.all(),
  168. required=False,
  169. label='RIR',
  170. widget=APISelect(
  171. api_url="/api/ipam/rirs/"
  172. )
  173. )
  174. date_added = forms.DateField(
  175. required=False
  176. )
  177. description = forms.CharField(
  178. max_length=100,
  179. required=False
  180. )
  181. class Meta:
  182. nullable_fields = [
  183. 'date_added', 'description',
  184. ]
  185. class AggregateFilterForm(BootstrapMixin, CustomFieldFilterForm):
  186. model = Aggregate
  187. q = forms.CharField(
  188. required=False,
  189. label='Search'
  190. )
  191. family = forms.ChoiceField(
  192. required=False,
  193. choices=IP_FAMILY_CHOICES,
  194. label='Address family',
  195. widget=StaticSelect2()
  196. )
  197. rir = FilterChoiceField(
  198. queryset=RIR.objects.all(),
  199. to_field_name='slug',
  200. label='RIR',
  201. widget=APISelectMultiple(
  202. api_url="/api/ipam/rirs/",
  203. value_field="slug",
  204. )
  205. )
  206. #
  207. # Roles
  208. #
  209. class RoleForm(BootstrapMixin, forms.ModelForm):
  210. slug = SlugField()
  211. class Meta:
  212. model = Role
  213. fields = [
  214. 'name', 'slug',
  215. ]
  216. class RoleCSVForm(forms.ModelForm):
  217. slug = SlugField()
  218. class Meta:
  219. model = Role
  220. fields = Role.csv_headers
  221. help_texts = {
  222. 'name': 'Role name',
  223. }
  224. #
  225. # Prefixes
  226. #
  227. class PrefixForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  228. site = forms.ModelChoiceField(
  229. queryset=Site.objects.all(),
  230. required=False,
  231. label='Site',
  232. widget=APISelect(
  233. api_url="/api/dcim/sites/",
  234. filter_for={
  235. 'vlan_group': 'site_id',
  236. 'vlan': 'site_id',
  237. },
  238. attrs={
  239. 'nullable': 'true',
  240. }
  241. )
  242. )
  243. vlan_group = ChainedModelChoiceField(
  244. queryset=VLANGroup.objects.all(),
  245. chains=(
  246. ('site', 'site'),
  247. ),
  248. required=False,
  249. label='VLAN group',
  250. widget=APISelect(
  251. api_url='/api/ipam/vlan-groups/',
  252. filter_for={
  253. 'vlan': 'group_id'
  254. },
  255. attrs={
  256. 'nullable': 'true',
  257. }
  258. )
  259. )
  260. vlan = ChainedModelChoiceField(
  261. queryset=VLAN.objects.all(),
  262. chains=(
  263. ('site', 'site'),
  264. ('group', 'vlan_group'),
  265. ),
  266. required=False,
  267. label='VLAN',
  268. widget=APISelect(
  269. api_url='/api/ipam/vlans/',
  270. display_field='display_name'
  271. )
  272. )
  273. tags = TagField(required=False)
  274. class Meta:
  275. model = Prefix
  276. fields = [
  277. 'prefix', 'vrf', 'site', 'vlan', 'status', 'role', 'is_pool', 'description', 'tenant_group', 'tenant',
  278. 'tags',
  279. ]
  280. widgets = {
  281. 'vrf': APISelect(
  282. api_url="/api/ipam/vrfs/"
  283. ),
  284. 'status': StaticSelect2(),
  285. 'role': APISelect(
  286. api_url="/api/ipam/roles/"
  287. )
  288. }
  289. def __init__(self, *args, **kwargs):
  290. # Initialize helper selectors
  291. instance = kwargs.get('instance')
  292. initial = kwargs.get('initial', {}).copy()
  293. if instance and instance.vlan is not None:
  294. initial['vlan_group'] = instance.vlan.group
  295. kwargs['initial'] = initial
  296. super().__init__(*args, **kwargs)
  297. self.fields['vrf'].empty_label = 'Global'
  298. class PrefixCSVForm(forms.ModelForm):
  299. vrf = forms.ModelChoiceField(
  300. queryset=VRF.objects.all(),
  301. required=False,
  302. to_field_name='rd',
  303. help_text='Route distinguisher of parent VRF',
  304. error_messages={
  305. 'invalid_choice': 'VRF not found.',
  306. }
  307. )
  308. tenant = forms.ModelChoiceField(
  309. queryset=Tenant.objects.all(),
  310. required=False,
  311. to_field_name='name',
  312. help_text='Name of assigned tenant',
  313. error_messages={
  314. 'invalid_choice': 'Tenant not found.',
  315. }
  316. )
  317. site = forms.ModelChoiceField(
  318. queryset=Site.objects.all(),
  319. required=False,
  320. to_field_name='name',
  321. help_text='Name of parent site',
  322. error_messages={
  323. 'invalid_choice': 'Site not found.',
  324. }
  325. )
  326. vlan_group = forms.CharField(
  327. help_text='Group name of assigned VLAN',
  328. required=False
  329. )
  330. vlan_vid = forms.IntegerField(
  331. help_text='Numeric ID of assigned VLAN',
  332. required=False
  333. )
  334. status = CSVChoiceField(
  335. choices=PREFIX_STATUS_CHOICES,
  336. help_text='Operational status'
  337. )
  338. role = forms.ModelChoiceField(
  339. queryset=Role.objects.all(),
  340. required=False,
  341. to_field_name='name',
  342. help_text='Functional role',
  343. error_messages={
  344. 'invalid_choice': 'Invalid role.',
  345. }
  346. )
  347. class Meta:
  348. model = Prefix
  349. fields = Prefix.csv_headers
  350. def clean(self):
  351. super().clean()
  352. site = self.cleaned_data.get('site')
  353. vlan_group = self.cleaned_data.get('vlan_group')
  354. vlan_vid = self.cleaned_data.get('vlan_vid')
  355. # Validate VLAN
  356. if vlan_group and vlan_vid:
  357. try:
  358. self.instance.vlan = VLAN.objects.get(site=site, group__name=vlan_group, vid=vlan_vid)
  359. except VLAN.DoesNotExist:
  360. if site:
  361. raise forms.ValidationError("VLAN {} not found in site {} group {}".format(
  362. vlan_vid, site, vlan_group
  363. ))
  364. else:
  365. raise forms.ValidationError("Global VLAN {} not found in group {}".format(vlan_vid, vlan_group))
  366. except MultipleObjectsReturned:
  367. raise forms.ValidationError(
  368. "Multiple VLANs with VID {} found in group {}".format(vlan_vid, vlan_group)
  369. )
  370. elif vlan_vid:
  371. try:
  372. self.instance.vlan = VLAN.objects.get(site=site, group__isnull=True, vid=vlan_vid)
  373. except VLAN.DoesNotExist:
  374. if site:
  375. raise forms.ValidationError("VLAN {} not found in site {}".format(vlan_vid, site))
  376. else:
  377. raise forms.ValidationError("Global VLAN {} not found".format(vlan_vid))
  378. except MultipleObjectsReturned:
  379. raise forms.ValidationError("Multiple VLANs with VID {} found".format(vlan_vid))
  380. class PrefixBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  381. pk = forms.ModelMultipleChoiceField(
  382. queryset=Prefix.objects.all(),
  383. widget=forms.MultipleHiddenInput()
  384. )
  385. site = forms.ModelChoiceField(
  386. queryset=Site.objects.all(),
  387. required=False,
  388. widget=APISelect(
  389. api_url="/api/dcim/sites/"
  390. )
  391. )
  392. vrf = forms.ModelChoiceField(
  393. queryset=VRF.objects.all(),
  394. required=False,
  395. label='VRF',
  396. widget=APISelect(
  397. api_url="/api/ipam/vrfs/"
  398. )
  399. )
  400. prefix_length = forms.IntegerField(
  401. min_value=1,
  402. max_value=127,
  403. required=False
  404. )
  405. tenant = forms.ModelChoiceField(
  406. queryset=Tenant.objects.all(),
  407. required=False,
  408. widget=APISelect(
  409. api_url="/api/tenancy/tenants/"
  410. )
  411. )
  412. status = forms.ChoiceField(
  413. choices=add_blank_choice(PREFIX_STATUS_CHOICES),
  414. required=False,
  415. widget=StaticSelect2()
  416. )
  417. role = forms.ModelChoiceField(
  418. queryset=Role.objects.all(),
  419. required=False,
  420. widget=APISelect(
  421. api_url="/api/ipam/roles/"
  422. )
  423. )
  424. is_pool = forms.NullBooleanField(
  425. required=False,
  426. widget=BulkEditNullBooleanSelect(),
  427. label='Is a pool'
  428. )
  429. description = forms.CharField(
  430. max_length=100,
  431. required=False
  432. )
  433. class Meta:
  434. nullable_fields = [
  435. 'site', 'vrf', 'tenant', 'role', 'description',
  436. ]
  437. class PrefixFilterForm(BootstrapMixin, CustomFieldFilterForm):
  438. model = Prefix
  439. q = forms.CharField(
  440. required=False,
  441. label='Search'
  442. )
  443. within_include = forms.CharField(
  444. required=False,
  445. widget=forms.TextInput(
  446. attrs={
  447. 'placeholder': 'Prefix',
  448. }
  449. ),
  450. label='Search within'
  451. )
  452. family = forms.ChoiceField(
  453. required=False,
  454. choices=IP_FAMILY_CHOICES,
  455. label='Address family',
  456. widget=StaticSelect2()
  457. )
  458. mask_length = forms.ChoiceField(
  459. required=False,
  460. choices=PREFIX_MASK_LENGTH_CHOICES,
  461. label='Mask length',
  462. widget=StaticSelect2()
  463. )
  464. vrf = FilterChoiceField(
  465. queryset=VRF.objects.all(),
  466. to_field_name='rd',
  467. label='VRF',
  468. null_label='-- Global --',
  469. widget=APISelectMultiple(
  470. api_url="/api/ipam/vrfs/",
  471. value_field="slug",
  472. null_option=True,
  473. )
  474. )
  475. tenant = FilterChoiceField(
  476. queryset=Tenant.objects.all(),
  477. to_field_name='slug',
  478. null_label='-- None --',
  479. widget=APISelectMultiple(
  480. api_url="/api/tenancy/tenants/",
  481. value_field="slug",
  482. null_option=True,
  483. )
  484. )
  485. status = forms.MultipleChoiceField(
  486. choices=PREFIX_STATUS_CHOICES,
  487. required=False,
  488. widget=StaticSelect2Multiple()
  489. )
  490. site = FilterChoiceField(
  491. queryset=Site.objects.all(),
  492. to_field_name='slug',
  493. null_label='-- None --',
  494. widget=APISelectMultiple(
  495. api_url="/api/dcim/sites/",
  496. value_field="slug",
  497. null_option=True,
  498. )
  499. )
  500. role = FilterChoiceField(
  501. queryset=Role.objects.all(),
  502. to_field_name='slug',
  503. null_label='-- None --',
  504. widget=APISelectMultiple(
  505. api_url="/api/ipam/roles/",
  506. value_field="slug",
  507. null_option=True,
  508. )
  509. )
  510. expand = forms.BooleanField(
  511. required=False,
  512. label='Expand prefix hierarchy'
  513. )
  514. #
  515. # IP addresses
  516. #
  517. class IPAddressForm(BootstrapMixin, TenancyForm, ReturnURLForm, CustomFieldForm):
  518. interface = forms.ModelChoiceField(
  519. queryset=Interface.objects.all(),
  520. required=False
  521. )
  522. nat_site = forms.ModelChoiceField(
  523. queryset=Site.objects.all(),
  524. required=False,
  525. label='Site',
  526. widget=APISelect(
  527. api_url="/api/dcim/sites/",
  528. filter_for={
  529. 'nat_rack': 'site_id',
  530. 'nat_device': 'site_id'
  531. }
  532. )
  533. )
  534. nat_rack = ChainedModelChoiceField(
  535. queryset=Rack.objects.all(),
  536. chains=(
  537. ('site', 'nat_site'),
  538. ),
  539. required=False,
  540. label='Rack',
  541. widget=APISelect(
  542. api_url='/api/dcim/racks/',
  543. display_field='display_name',
  544. filter_for={
  545. 'nat_device': 'rack_id'
  546. },
  547. attrs={
  548. 'nullable': 'true'
  549. }
  550. )
  551. )
  552. nat_device = ChainedModelChoiceField(
  553. queryset=Device.objects.all(),
  554. chains=(
  555. ('site', 'nat_site'),
  556. ('rack', 'nat_rack'),
  557. ),
  558. required=False,
  559. label='Device',
  560. widget=APISelect(
  561. api_url='/api/dcim/devices/',
  562. display_field='display_name',
  563. filter_for={
  564. 'nat_inside': 'device_id'
  565. }
  566. )
  567. )
  568. nat_inside = ChainedModelChoiceField(
  569. queryset=IPAddress.objects.all(),
  570. chains=(
  571. ('interface__device', 'nat_device'),
  572. ),
  573. required=False,
  574. label='IP Address',
  575. widget=APISelect(
  576. api_url='/api/ipam/ip-addresses/',
  577. display_field='address'
  578. )
  579. )
  580. primary_for_parent = forms.BooleanField(
  581. required=False,
  582. label='Make this the primary IP for the device/VM'
  583. )
  584. tags = TagField(
  585. required=False
  586. )
  587. class Meta:
  588. model = IPAddress
  589. fields = [
  590. 'address', 'vrf', 'status', 'role', 'description', 'interface', 'primary_for_parent', 'nat_site',
  591. 'nat_rack', 'nat_inside', 'tenant_group', 'tenant', 'tags',
  592. ]
  593. widgets = {
  594. 'status': StaticSelect2(),
  595. 'role': StaticSelect2(),
  596. 'vrf': APISelect(
  597. api_url="/api/ipam/vrfs/"
  598. )
  599. }
  600. def __init__(self, *args, **kwargs):
  601. # Initialize helper selectors
  602. instance = kwargs.get('instance')
  603. initial = kwargs.get('initial', {}).copy()
  604. if instance and instance.nat_inside and instance.nat_inside.device is not None:
  605. initial['nat_site'] = instance.nat_inside.device.site
  606. initial['nat_rack'] = instance.nat_inside.device.rack
  607. initial['nat_device'] = instance.nat_inside.device
  608. kwargs['initial'] = initial
  609. super().__init__(*args, **kwargs)
  610. self.fields['vrf'].empty_label = 'Global'
  611. # Limit interface selections to those belonging to the parent device/VM
  612. if self.instance and self.instance.interface:
  613. self.fields['interface'].queryset = Interface.objects.filter(
  614. device=self.instance.interface.device, virtual_machine=self.instance.interface.virtual_machine
  615. )
  616. else:
  617. self.fields['interface'].choices = []
  618. # Initialize primary_for_parent if IP address is already assigned
  619. if self.instance.pk and self.instance.interface is not None:
  620. parent = self.instance.interface.parent
  621. if (
  622. self.instance.address.version == 4 and parent.primary_ip4_id == self.instance.pk or
  623. self.instance.address.version == 6 and parent.primary_ip6_id == self.instance.pk
  624. ):
  625. self.initial['primary_for_parent'] = True
  626. def clean(self):
  627. super().clean()
  628. # Primary IP assignment is only available if an interface has been assigned.
  629. if self.cleaned_data.get('primary_for_parent') and not self.cleaned_data.get('interface'):
  630. self.add_error(
  631. 'primary_for_parent', "Only IP addresses assigned to an interface can be designated as primary IPs."
  632. )
  633. def save(self, *args, **kwargs):
  634. ipaddress = super().save(*args, **kwargs)
  635. # Assign/clear this IPAddress as the primary for the associated Device/VirtualMachine.
  636. if self.cleaned_data['primary_for_parent']:
  637. parent = self.cleaned_data['interface'].parent
  638. if ipaddress.address.version == 4:
  639. parent.primary_ip4 = ipaddress
  640. else:
  641. parent.primary_ip6 = ipaddress
  642. parent.save()
  643. elif self.cleaned_data['interface']:
  644. parent = self.cleaned_data['interface'].parent
  645. if ipaddress.address.version == 4 and parent.primary_ip4 == ipaddress:
  646. parent.primary_ip4 = None
  647. parent.save()
  648. elif ipaddress.address.version == 6 and parent.primary_ip6 == ipaddress:
  649. parent.primary_ip6 = None
  650. parent.save()
  651. return ipaddress
  652. class IPAddressBulkCreateForm(BootstrapMixin, forms.Form):
  653. pattern = ExpandableIPAddressField(
  654. label='Address pattern'
  655. )
  656. class IPAddressBulkAddForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  657. class Meta:
  658. model = IPAddress
  659. fields = [
  660. 'address', 'vrf', 'status', 'role', 'description', 'tenant_group', 'tenant',
  661. ]
  662. widgets = {
  663. 'status': StaticSelect2(),
  664. 'role': StaticSelect2(),
  665. 'vrf': APISelect(
  666. api_url="/api/ipam/vrfs/"
  667. )
  668. }
  669. def __init__(self, *args, **kwargs):
  670. super().__init__(*args, **kwargs)
  671. self.fields['vrf'].empty_label = 'Global'
  672. class IPAddressCSVForm(forms.ModelForm):
  673. vrf = forms.ModelChoiceField(
  674. queryset=VRF.objects.all(),
  675. required=False,
  676. to_field_name='rd',
  677. help_text='Route distinguisher of the assigned VRF',
  678. error_messages={
  679. 'invalid_choice': 'VRF not found.',
  680. }
  681. )
  682. tenant = forms.ModelChoiceField(
  683. queryset=Tenant.objects.all(),
  684. to_field_name='name',
  685. required=False,
  686. help_text='Name of the assigned tenant',
  687. error_messages={
  688. 'invalid_choice': 'Tenant not found.',
  689. }
  690. )
  691. status = CSVChoiceField(
  692. choices=IPADDRESS_STATUS_CHOICES,
  693. help_text='Operational status'
  694. )
  695. role = CSVChoiceField(
  696. choices=IPADDRESS_ROLE_CHOICES,
  697. required=False,
  698. help_text='Functional role'
  699. )
  700. device = FlexibleModelChoiceField(
  701. queryset=Device.objects.all(),
  702. required=False,
  703. to_field_name='name',
  704. help_text='Name or ID of assigned device',
  705. error_messages={
  706. 'invalid_choice': 'Device not found.',
  707. }
  708. )
  709. virtual_machine = forms.ModelChoiceField(
  710. queryset=VirtualMachine.objects.all(),
  711. required=False,
  712. to_field_name='name',
  713. help_text='Name of assigned virtual machine',
  714. error_messages={
  715. 'invalid_choice': 'Virtual machine not found.',
  716. }
  717. )
  718. interface_name = forms.CharField(
  719. help_text='Name of assigned interface',
  720. required=False
  721. )
  722. is_primary = forms.BooleanField(
  723. help_text='Make this the primary IP for the assigned device',
  724. required=False
  725. )
  726. class Meta:
  727. model = IPAddress
  728. fields = IPAddress.csv_headers
  729. def clean(self):
  730. super().clean()
  731. device = self.cleaned_data.get('device')
  732. virtual_machine = self.cleaned_data.get('virtual_machine')
  733. interface_name = self.cleaned_data.get('interface_name')
  734. is_primary = self.cleaned_data.get('is_primary')
  735. # Validate interface
  736. if interface_name and device:
  737. try:
  738. self.instance.interface = Interface.objects.get(device=device, name=interface_name)
  739. except Interface.DoesNotExist:
  740. raise forms.ValidationError("Invalid interface {} for device {}".format(
  741. interface_name, device
  742. ))
  743. elif interface_name and virtual_machine:
  744. try:
  745. self.instance.interface = Interface.objects.get(virtual_machine=virtual_machine, name=interface_name)
  746. except Interface.DoesNotExist:
  747. raise forms.ValidationError("Invalid interface {} for virtual machine {}".format(
  748. interface_name, virtual_machine
  749. ))
  750. elif interface_name:
  751. raise forms.ValidationError("Interface given ({}) but parent device/virtual machine not specified".format(
  752. interface_name
  753. ))
  754. elif device:
  755. raise forms.ValidationError("Device specified ({}) but interface missing".format(device))
  756. elif virtual_machine:
  757. raise forms.ValidationError("Virtual machine specified ({}) but interface missing".format(virtual_machine))
  758. # Validate is_primary
  759. if is_primary and not device and not virtual_machine:
  760. raise forms.ValidationError("No device or virtual machine specified; cannot set as primary IP")
  761. def save(self, *args, **kwargs):
  762. # Set interface
  763. if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
  764. self.instance.interface = Interface.objects.get(
  765. device=self.cleaned_data['device'],
  766. name=self.cleaned_data['interface_name']
  767. )
  768. elif self.cleaned_data['virtual_machine'] and self.cleaned_data['interface_name']:
  769. self.instance.interface = Interface.objects.get(
  770. virtual_machine=self.cleaned_data['virtual_machine'],
  771. name=self.cleaned_data['interface_name']
  772. )
  773. ipaddress = super().save(*args, **kwargs)
  774. # Set as primary for device/VM
  775. if self.cleaned_data['is_primary']:
  776. parent = self.cleaned_data['device'] or self.cleaned_data['virtual_machine']
  777. if self.instance.address.version == 4:
  778. parent.primary_ip4 = ipaddress
  779. elif self.instance.address.version == 6:
  780. parent.primary_ip6 = ipaddress
  781. parent.save()
  782. return ipaddress
  783. class IPAddressBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  784. pk = forms.ModelMultipleChoiceField(
  785. queryset=IPAddress.objects.all(),
  786. widget=forms.MultipleHiddenInput()
  787. )
  788. vrf = forms.ModelChoiceField(
  789. queryset=VRF.objects.all(),
  790. required=False,
  791. label='VRF',
  792. widget=APISelect(
  793. api_url="/api/ipam/vrfs/"
  794. )
  795. )
  796. mask_length = forms.IntegerField(
  797. min_value=1,
  798. max_value=128,
  799. required=False
  800. )
  801. tenant = forms.ModelChoiceField(
  802. queryset=Tenant.objects.all(),
  803. required=False,
  804. widget=APISelect(
  805. api_url="/api/tenancy/tenants/"
  806. )
  807. )
  808. status = forms.ChoiceField(
  809. choices=add_blank_choice(IPADDRESS_STATUS_CHOICES),
  810. required=False,
  811. widget=StaticSelect2()
  812. )
  813. role = forms.ChoiceField(
  814. choices=add_blank_choice(IPADDRESS_ROLE_CHOICES),
  815. required=False,
  816. widget=StaticSelect2()
  817. )
  818. description = forms.CharField(
  819. max_length=100, required=False
  820. )
  821. class Meta:
  822. nullable_fields = [
  823. 'vrf', 'role', 'tenant', 'description',
  824. ]
  825. class IPAddressAssignForm(BootstrapMixin, forms.Form):
  826. vrf = forms.ModelChoiceField(
  827. queryset=VRF.objects.all(),
  828. required=False,
  829. label='VRF',
  830. empty_label='Global',
  831. widget=APISelect(
  832. api_url="/api/ipam/vrfs/"
  833. )
  834. )
  835. address = forms.CharField(
  836. label='IP Address'
  837. )
  838. class IPAddressFilterForm(BootstrapMixin, CustomFieldFilterForm):
  839. model = IPAddress
  840. q = forms.CharField(
  841. required=False,
  842. label='Search'
  843. )
  844. parent = forms.CharField(
  845. required=False,
  846. widget=forms.TextInput(
  847. attrs={
  848. 'placeholder': 'Prefix',
  849. }
  850. ),
  851. label='Parent Prefix'
  852. )
  853. family = forms.ChoiceField(
  854. required=False,
  855. choices=IP_FAMILY_CHOICES,
  856. label='Address family',
  857. widget=StaticSelect2()
  858. )
  859. mask_length = forms.ChoiceField(
  860. required=False,
  861. choices=IPADDRESS_MASK_LENGTH_CHOICES,
  862. label='Mask length',
  863. widget=StaticSelect2()
  864. )
  865. vrf = FilterChoiceField(
  866. queryset=VRF.objects.all(),
  867. to_field_name='rd',
  868. label='VRF',
  869. null_label='-- Global --',
  870. widget=APISelectMultiple(
  871. api_url="/api/ipam/vrfs/",
  872. value_field="slug",
  873. null_option=True,
  874. )
  875. )
  876. tenant = FilterChoiceField(
  877. queryset=Tenant.objects.all(),
  878. to_field_name='slug',
  879. null_label='-- None --',
  880. widget=APISelectMultiple(
  881. api_url="/api/tenancy/tenants/",
  882. value_field="slug",
  883. null_option=True,
  884. )
  885. )
  886. status = forms.MultipleChoiceField(
  887. choices=IPADDRESS_STATUS_CHOICES,
  888. required=False,
  889. widget=StaticSelect2Multiple()
  890. )
  891. role = forms.MultipleChoiceField(
  892. choices=IPADDRESS_ROLE_CHOICES,
  893. required=False,
  894. widget=StaticSelect2Multiple()
  895. )
  896. #
  897. # VLAN groups
  898. #
  899. class VLANGroupForm(BootstrapMixin, forms.ModelForm):
  900. slug = SlugField()
  901. class Meta:
  902. model = VLANGroup
  903. fields = [
  904. 'site', 'name', 'slug',
  905. ]
  906. widgets = {
  907. 'site': APISelect(
  908. api_url="/api/dcim/sites/"
  909. )
  910. }
  911. class VLANGroupCSVForm(forms.ModelForm):
  912. site = forms.ModelChoiceField(
  913. queryset=Site.objects.all(),
  914. required=False,
  915. to_field_name='name',
  916. help_text='Name of parent site',
  917. error_messages={
  918. 'invalid_choice': 'Site not found.',
  919. }
  920. )
  921. slug = SlugField()
  922. class Meta:
  923. model = VLANGroup
  924. fields = VLANGroup.csv_headers
  925. help_texts = {
  926. 'name': 'Name of VLAN group',
  927. }
  928. class VLANGroupFilterForm(BootstrapMixin, forms.Form):
  929. site = FilterChoiceField(
  930. queryset=Site.objects.all(),
  931. to_field_name='slug',
  932. null_label='-- Global --',
  933. widget=APISelectMultiple(
  934. api_url="/api/dcim/sites/",
  935. value_field="slug",
  936. null_option=True,
  937. )
  938. )
  939. #
  940. # VLANs
  941. #
  942. class VLANForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  943. site = forms.ModelChoiceField(
  944. queryset=Site.objects.all(),
  945. required=False,
  946. widget=APISelect(
  947. api_url="/api/dcim/sites/",
  948. filter_for={
  949. 'group': 'site_id'
  950. },
  951. attrs={
  952. 'nullable': 'true',
  953. }
  954. )
  955. )
  956. group = ChainedModelChoiceField(
  957. queryset=VLANGroup.objects.all(),
  958. chains=(
  959. ('site', 'site'),
  960. ),
  961. required=False,
  962. label='Group',
  963. widget=APISelect(
  964. api_url='/api/ipam/vlan-groups/',
  965. )
  966. )
  967. tags = TagField(required=False)
  968. class Meta:
  969. model = VLAN
  970. fields = [
  971. 'site', 'group', 'vid', 'name', 'status', 'role', 'description', 'tenant_group', 'tenant', 'tags',
  972. ]
  973. help_texts = {
  974. 'site': "Leave blank if this VLAN spans multiple sites",
  975. 'group': "VLAN group (optional)",
  976. 'vid': "Configured VLAN ID",
  977. 'name': "Configured VLAN name",
  978. 'status': "Operational status of this VLAN",
  979. 'role': "The primary function of this VLAN",
  980. }
  981. widgets = {
  982. 'status': StaticSelect2(),
  983. 'role': APISelect(
  984. api_url="/api/ipam/roles/"
  985. )
  986. }
  987. class VLANCSVForm(forms.ModelForm):
  988. site = forms.ModelChoiceField(
  989. queryset=Site.objects.all(),
  990. required=False,
  991. to_field_name='name',
  992. help_text='Name of parent site',
  993. error_messages={
  994. 'invalid_choice': 'Site not found.',
  995. }
  996. )
  997. group_name = forms.CharField(
  998. help_text='Name of VLAN group',
  999. required=False
  1000. )
  1001. tenant = forms.ModelChoiceField(
  1002. queryset=Tenant.objects.all(),
  1003. to_field_name='name',
  1004. required=False,
  1005. help_text='Name of assigned tenant',
  1006. error_messages={
  1007. 'invalid_choice': 'Tenant not found.',
  1008. }
  1009. )
  1010. status = CSVChoiceField(
  1011. choices=VLAN_STATUS_CHOICES,
  1012. help_text='Operational status'
  1013. )
  1014. role = forms.ModelChoiceField(
  1015. queryset=Role.objects.all(),
  1016. required=False,
  1017. to_field_name='name',
  1018. help_text='Functional role',
  1019. error_messages={
  1020. 'invalid_choice': 'Invalid role.',
  1021. }
  1022. )
  1023. class Meta:
  1024. model = VLAN
  1025. fields = VLAN.csv_headers
  1026. help_texts = {
  1027. 'vid': 'Numeric VLAN ID (1-4095)',
  1028. 'name': 'VLAN name',
  1029. }
  1030. def clean(self):
  1031. super().clean()
  1032. site = self.cleaned_data.get('site')
  1033. group_name = self.cleaned_data.get('group_name')
  1034. # Validate VLAN group
  1035. if group_name:
  1036. try:
  1037. self.instance.group = VLANGroup.objects.get(site=site, name=group_name)
  1038. except VLANGroup.DoesNotExist:
  1039. if site:
  1040. raise forms.ValidationError(
  1041. "VLAN group {} not found for site {}".format(group_name, site)
  1042. )
  1043. else:
  1044. raise forms.ValidationError(
  1045. "Global VLAN group {} not found".format(group_name)
  1046. )
  1047. class VLANBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  1048. pk = forms.ModelMultipleChoiceField(
  1049. queryset=VLAN.objects.all(),
  1050. widget=forms.MultipleHiddenInput()
  1051. )
  1052. site = forms.ModelChoiceField(
  1053. queryset=Site.objects.all(),
  1054. required=False,
  1055. widget=APISelect(
  1056. api_url="/api/dcim/sites/"
  1057. )
  1058. )
  1059. group = forms.ModelChoiceField(
  1060. queryset=VLANGroup.objects.all(),
  1061. required=False,
  1062. widget=APISelect(
  1063. api_url="/api/ipam/vlan-groups/"
  1064. )
  1065. )
  1066. tenant = forms.ModelChoiceField(
  1067. queryset=Tenant.objects.all(),
  1068. required=False,
  1069. widget=APISelect(
  1070. api_url="/api/tenancy/tenants/"
  1071. )
  1072. )
  1073. status = forms.ChoiceField(
  1074. choices=add_blank_choice(VLAN_STATUS_CHOICES),
  1075. required=False,
  1076. widget=StaticSelect2()
  1077. )
  1078. role = forms.ModelChoiceField(
  1079. queryset=Role.objects.all(),
  1080. required=False,
  1081. widget=APISelect(
  1082. api_url="/api/ipam/roles/"
  1083. )
  1084. )
  1085. description = forms.CharField(
  1086. max_length=100,
  1087. required=False
  1088. )
  1089. class Meta:
  1090. nullable_fields = [
  1091. 'site', 'group', 'tenant', 'role', 'description',
  1092. ]
  1093. class VLANFilterForm(BootstrapMixin, CustomFieldFilterForm):
  1094. model = VLAN
  1095. q = forms.CharField(
  1096. required=False,
  1097. label='Search'
  1098. )
  1099. site = FilterChoiceField(
  1100. queryset=Site.objects.all(),
  1101. to_field_name='slug',
  1102. null_label='-- Global --',
  1103. widget=APISelectMultiple(
  1104. api_url="/api/dcim/sites/",
  1105. value_field="slug",
  1106. null_option=True,
  1107. )
  1108. )
  1109. group_id = FilterChoiceField(
  1110. queryset=VLANGroup.objects.all(),
  1111. label='VLAN group',
  1112. null_label='-- None --',
  1113. widget=APISelectMultiple(
  1114. api_url="/api/ipam/vlan-groups/",
  1115. null_option=True,
  1116. )
  1117. )
  1118. tenant = FilterChoiceField(
  1119. queryset=Tenant.objects.all(),
  1120. to_field_name='slug',
  1121. null_label='-- None --',
  1122. widget=APISelectMultiple(
  1123. api_url="/api/tenancy/tenants/",
  1124. value_field="slug",
  1125. null_option=True,
  1126. )
  1127. )
  1128. status = forms.MultipleChoiceField(
  1129. choices=VLAN_STATUS_CHOICES,
  1130. required=False,
  1131. widget=StaticSelect2Multiple()
  1132. )
  1133. role = FilterChoiceField(
  1134. queryset=Role.objects.all(),
  1135. to_field_name='slug',
  1136. null_label='-- None --',
  1137. widget=APISelectMultiple(
  1138. api_url="/api/ipam/roles/",
  1139. value_field="slug",
  1140. null_option=True,
  1141. )
  1142. )
  1143. #
  1144. # Services
  1145. #
  1146. class ServiceForm(BootstrapMixin, CustomFieldForm):
  1147. tags = TagField(
  1148. required=False
  1149. )
  1150. class Meta:
  1151. model = Service
  1152. fields = [
  1153. 'name', 'protocol', 'port', 'ipaddresses', 'description', 'tags',
  1154. ]
  1155. help_texts = {
  1156. 'ipaddresses': "IP address assignment is optional. If no IPs are selected, the service is assumed to be "
  1157. "reachable via all IPs assigned to the device.",
  1158. }
  1159. widgets = {
  1160. 'protocol': StaticSelect2(),
  1161. 'ipaddresses': StaticSelect2Multiple(),
  1162. }
  1163. def __init__(self, *args, **kwargs):
  1164. super().__init__(*args, **kwargs)
  1165. # Limit IP address choices to those assigned to interfaces of the parent device/VM
  1166. if self.instance.device:
  1167. vc_interface_ids = [i['id'] for i in self.instance.device.vc_interfaces.values('id')]
  1168. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  1169. interface_id__in=vc_interface_ids
  1170. )
  1171. elif self.instance.virtual_machine:
  1172. self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
  1173. interface__virtual_machine=self.instance.virtual_machine
  1174. )
  1175. else:
  1176. self.fields['ipaddresses'].choices = []
  1177. class ServiceFilterForm(BootstrapMixin, CustomFieldFilterForm):
  1178. model = Service
  1179. q = forms.CharField(
  1180. required=False,
  1181. label='Search'
  1182. )
  1183. protocol = forms.ChoiceField(
  1184. choices=add_blank_choice(IP_PROTOCOL_CHOICES),
  1185. required=False,
  1186. widget=StaticSelect2Multiple()
  1187. )
  1188. port = forms.IntegerField(
  1189. required=False,
  1190. )
  1191. class ServiceBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  1192. pk = forms.ModelMultipleChoiceField(
  1193. queryset=Service.objects.all(),
  1194. widget=forms.MultipleHiddenInput()
  1195. )
  1196. protocol = forms.ChoiceField(
  1197. choices=add_blank_choice(IP_PROTOCOL_CHOICES),
  1198. required=False,
  1199. widget=StaticSelect2()
  1200. )
  1201. port = forms.IntegerField(
  1202. validators=[
  1203. MinValueValidator(1),
  1204. MaxValueValidator(65535),
  1205. ],
  1206. required=False
  1207. )
  1208. description = forms.CharField(
  1209. max_length=100,
  1210. required=False
  1211. )
  1212. class Meta:
  1213. nullable_fields = [
  1214. 'site', 'tenant', 'role', 'description',
  1215. ]