Mistral Horizon plugin.
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 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright 2014 - StackStorm, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain 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,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import six
  15. from django.core.urlresolvers import reverse
  16. from django.utils.translation import ugettext_lazy as _
  17. from horizon import exceptions
  18. from horizon import forms
  19. from horizon import messages
  20. from mistraldashboard import api
  21. class ExecuteForm(forms.SelfHandlingForm):
  22. workflow_name = forms.CharField(
  23. label=_("Workflow"),
  24. required=True,
  25. widget=forms.TextInput(attrs={'readonly': 'readonly'})
  26. )
  27. task_name = forms.CharField(
  28. label=_("Task name"),
  29. required=False,
  30. widget=forms.TextInput()
  31. )
  32. def __init__(self, *args, **kwargs):
  33. super(ExecuteForm, self).__init__(*args, **kwargs)
  34. self._generate_parameter_fields(kwargs["initial"]["parameter_list"])
  35. def _generate_parameter_fields(self, list):
  36. self.workflow_parameters = []
  37. for entry in list.split(","):
  38. label, _, default = entry.partition("=")
  39. label = label.strip()
  40. self.workflow_parameters.append(label)
  41. if default == "None":
  42. default = None
  43. required = False
  44. else:
  45. required = True
  46. self.fields[label] = forms.CharField(label=label,
  47. required=required,
  48. initial=default)
  49. def handle(self, request, data):
  50. try:
  51. data['workflow_identifier'] = data.pop('workflow_name')
  52. data['workflow_input'] = {}
  53. for param in self.workflow_parameters:
  54. value = data.pop(param)
  55. if value == "":
  56. value = None
  57. data['workflow_input'][param] = value
  58. ex = api.execution_create(request, **data)
  59. msg = _('Execution has been created with id "%s".') % ex.id
  60. messages.success(request, msg)
  61. return True
  62. except Exception as e:
  63. msg = _('Failed to execute workflow "%s".') % e
  64. redirect = reverse('horizon:mistral:workflows:index')
  65. exceptions.handle(request, msg, redirect=redirect)
  66. class DefinitionForm(forms.SelfHandlingForm):
  67. definition_source = forms.ChoiceField(
  68. label=_('Definition Source'),
  69. choices=[('file', _('File')),
  70. ('raw', _('Direct Input'))],
  71. widget=forms.Select(
  72. attrs={'class': 'switchable',
  73. 'data-slug': 'definitionsource'})
  74. )
  75. definition_upload = forms.FileField(
  76. label=_('Definition File'),
  77. help_text=_('A local definition to upload.'),
  78. widget=forms.FileInput(
  79. attrs={'class': 'switched',
  80. 'data-switch-on': 'definitionsource',
  81. 'data-definitionsource-file': _('Definition File')}
  82. ),
  83. required=False
  84. )
  85. definition_data = forms.CharField(
  86. label=_('Definition Data'),
  87. help_text=_('The raw contents of the definition.'),
  88. widget=forms.widgets.Textarea(
  89. attrs={'class': 'switched',
  90. 'data-switch-on': 'definitionsource',
  91. 'data-definitionsource-raw': _('Definition Data'),
  92. 'rows': 4}
  93. ),
  94. required=False
  95. )
  96. def __init__(self, *args, **kwargs):
  97. self.next_view = kwargs.pop('next_view')
  98. super(DefinitionForm, self).__init__(*args, **kwargs)
  99. def clean(self):
  100. cleaned_data = super(DefinitionForm, self).clean()
  101. if cleaned_data.get('definition_upload'):
  102. files = self.request.FILES
  103. cleaned_data['definition'] = files['definition_upload'].read()
  104. elif cleaned_data.get('definition_data'):
  105. cleaned_data['definition'] = cleaned_data['definition_data']
  106. else:
  107. raise forms.ValidationError(
  108. _('You must specify the definition source.'))
  109. try:
  110. validated = api.workflow_validate(
  111. self.request,
  112. cleaned_data['definition']
  113. )
  114. except Exception as e:
  115. raise forms.ValidationError(six.text_type(e))
  116. if not validated.get('valid'):
  117. raise forms.ValidationError(
  118. validated.get('error', _('Validated failed')))
  119. return cleaned_data
  120. def handle(self, request, data):
  121. kwargs = {'definition': data['definition']}
  122. request.method = 'GET'
  123. return self.next_view.as_view()(request, **kwargs)
  124. class CreateForm(forms.SelfHandlingForm):
  125. definition = forms.CharField(
  126. widget=forms.widgets.Textarea(
  127. attrs={'rows': 12}
  128. ),
  129. required=False
  130. )
  131. def handle(self, request, data):
  132. try:
  133. api.workflow_create(request, data['definition'])
  134. msg = _('Successfully created workflow.')
  135. messages.success(request, msg)
  136. return True
  137. except Exception:
  138. msg = _('Failed to create workflow.')
  139. redirect = reverse('horizon:mistral:workflows:index')
  140. exceptions.handle(request, msg, redirect=redirect)
  141. class UpdateForm(CreateForm):
  142. def handle(self, request, data):
  143. try:
  144. api.workflow_update(request, data['definition'])
  145. msg = _('Successfully updated workflow.')
  146. messages.success(request, msg)
  147. return True
  148. except Exception:
  149. msg = _('Failed to update workflow.')
  150. redirect = reverse('horizon:mistral:workflows:index')
  151. exceptions.handle(request, msg, redirect=redirect)