OpenStack Dashboard (Horizon)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # Copyright 2012, Nachi Ueno, NTT MCL, Inc.
  2. # All rights reserved.
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. """
  15. Views for managing Neutron Routers.
  16. """
  17. import logging
  18. from django.core.urlresolvers import reverse
  19. from django.core.urlresolvers import reverse_lazy
  20. from django.utils.translation import ugettext_lazy as _
  21. from horizon import exceptions
  22. from horizon import forms
  23. from horizon import messages
  24. from openstack_dashboard import api
  25. LOG = logging.getLogger(__name__)
  26. class CreateForm(forms.SelfHandlingForm):
  27. name = forms.CharField(max_length=255, label=_("Router Name"),
  28. required=False)
  29. admin_state_up = forms.BooleanField(label=_("Enable Admin State"),
  30. initial=True,
  31. required=False)
  32. external_network = forms.ThemableChoiceField(label=_("External Network"),
  33. required=False)
  34. mode = forms.ChoiceField(label=_("Router Type"))
  35. ha = forms.ChoiceField(label=_("High Availability Mode"))
  36. az_hints = forms.MultipleChoiceField(
  37. label=_("Availability Zone Hints"),
  38. required=False,
  39. help_text=_("Availability Zones where the router may be scheduled. "
  40. "Leaving this unset is equivalent to selecting all "
  41. "Availability Zones"))
  42. failure_url = 'horizon:project:routers:index'
  43. def __init__(self, request, *args, **kwargs):
  44. super(CreateForm, self).__init__(request, *args, **kwargs)
  45. self.dvr_allowed = api.neutron.get_feature_permission(self.request,
  46. "dvr", "create")
  47. if self.dvr_allowed:
  48. mode_choices = [('server_default', _('Use Server Default')),
  49. ('centralized', _('Centralized')),
  50. ('distributed', _('Distributed'))]
  51. self.fields['mode'].choices = mode_choices
  52. else:
  53. del self.fields['mode']
  54. self.ha_allowed = api.neutron.get_feature_permission(self.request,
  55. "l3-ha", "create")
  56. if self.ha_allowed:
  57. ha_choices = [('server_default', _('Use Server Default')),
  58. ('enabled', _('Enable HA mode')),
  59. ('disabled', _('Disable HA mode'))]
  60. self.fields['ha'].choices = ha_choices
  61. else:
  62. del self.fields['ha']
  63. networks = self._get_network_list(request)
  64. if networks:
  65. self.fields['external_network'].choices = networks
  66. else:
  67. del self.fields['external_network']
  68. az_supported = api.neutron.is_extension_supported(
  69. self.request, 'router_availability_zone')
  70. if az_supported:
  71. zones = api.neutron.list_availability_zones(self.request, 'router',
  72. 'available')
  73. self.fields['az_hints'].choices = [(zone['name'], zone['name'])
  74. for zone in zones]
  75. else:
  76. del self.fields['az_hints']
  77. def _get_network_list(self, request):
  78. search_opts = {'router:external': True}
  79. try:
  80. networks = api.neutron.network_list(request, **search_opts)
  81. except Exception as e:
  82. LOG.info('Failed to get network list: %s', e)
  83. msg = _('Failed to get network list.')
  84. messages.warning(request, msg)
  85. networks = []
  86. choices = [(network.id, network.name or network.id)
  87. for network in networks]
  88. if choices:
  89. choices.insert(0, ("", _("Select network")))
  90. return choices
  91. def handle(self, request, data):
  92. try:
  93. params = {'name': data['name']}
  94. if 'admin_state_up' in data and data['admin_state_up']:
  95. params['admin_state_up'] = data['admin_state_up']
  96. if 'external_network' in data and data['external_network']:
  97. params['external_gateway_info'] = {'network_id':
  98. data['external_network']}
  99. if 'az_hints' in data and data['az_hints']:
  100. params['availability_zone_hints'] = data['az_hints']
  101. if (self.dvr_allowed and data['mode'] != 'server_default'):
  102. params['distributed'] = (data['mode'] == 'distributed')
  103. if (self.ha_allowed and data['ha'] != 'server_default'):
  104. params['ha'] = (data['ha'] == 'enabled')
  105. router = api.neutron.router_create(request, **params)
  106. message = _('Router %s was successfully created.') % data['name']
  107. messages.success(request, message)
  108. return router
  109. except Exception as exc:
  110. LOG.info('Failed to create router: %s', exc)
  111. if exc.status_code == 409:
  112. msg = _('Quota exceeded for resource router.')
  113. else:
  114. msg = _('Failed to create router "%s".') % data['name']
  115. redirect = reverse(self.failure_url)
  116. exceptions.handle(request, msg, redirect=redirect)
  117. return False
  118. class UpdateForm(forms.SelfHandlingForm):
  119. name = forms.CharField(label=_("Name"), required=False)
  120. admin_state = forms.BooleanField(label=_("Enable Admin State"),
  121. required=False)
  122. mode = forms.ThemableChoiceField(label=_("Router Type"))
  123. ha = forms.BooleanField(label=_("High Availability Mode"), required=False)
  124. redirect_url = reverse_lazy('horizon:project:routers:index')
  125. def __init__(self, request, *args, **kwargs):
  126. super(UpdateForm, self).__init__(request, *args, **kwargs)
  127. self.dvr_allowed = api.neutron.get_feature_permission(self.request,
  128. "dvr", "update")
  129. if not self.dvr_allowed:
  130. del self.fields['mode']
  131. elif self.initial.get('mode') == 'distributed':
  132. # Neutron supports only changing from centralized to
  133. # distributed now.
  134. mode_choices = [('distributed', _('Distributed'))]
  135. self.fields['mode'].widget = forms.TextInput(attrs={'readonly':
  136. 'readonly'})
  137. self.fields['mode'].choices = mode_choices
  138. else:
  139. mode_choices = [('centralized', _('Centralized')),
  140. ('distributed', _('Distributed'))]
  141. self.fields['mode'].choices = mode_choices
  142. # TODO(amotoki): Due to Neutron Bug 1378525, Neutron disables
  143. # PUT operation. It will be fixed in Kilo cycle.
  144. # self.ha_allowed = api.neutron.get_feature_permission(
  145. # self.request, "l3-ha", "update")
  146. self.ha_allowed = False
  147. if not self.ha_allowed:
  148. del self.fields['ha']
  149. def handle(self, request, data):
  150. try:
  151. params = {'admin_state_up': data['admin_state'],
  152. 'name': data['name']}
  153. if self.dvr_allowed:
  154. params['distributed'] = (data['mode'] == 'distributed')
  155. if self.ha_allowed:
  156. params['ha'] = data['ha']
  157. router = api.neutron.router_update(request,
  158. self.initial['router_id'],
  159. **params)
  160. msg = _('Router %s was successfully updated.') % data['name']
  161. messages.success(request, msg)
  162. return router
  163. except Exception as exc:
  164. LOG.info('Failed to update router %(id)s: %(exc)s',
  165. {'id': self.initial['router_id'], 'exc': exc})
  166. msg = _('Failed to update router %s') % data['name']
  167. exceptions.handle(request, msg, redirect=self.redirect_url)