class UploadObject(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Object Name"), help_text=_("Slashes are allowed, and are treated " "as pseudo-folders by the Object " "Store.")) object_file = forms.FileField(label=_("File"), allow_empty_file=True) container_name = forms.CharField(widget=forms.HiddenInput()) def handle(self, request, data): object_file = self.files['object_file'] if data['path']: object_path = "/".join([data['path'].rstrip("/"), data['name']]) else: object_path = data['name'] try: obj = api.swift.swift_upload_object(request, data['container_name'], object_path, object_file) messages.success(request, _("Object was successfully uploaded.")) return obj except Exception: exceptions.handle(request, _("Unable to upload object."))
class UploadObject(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Object Name"), validators=[no_slash_validator]) object_file = forms.FileField(label=_("File")) container_name = forms.CharField(widget=forms.HiddenInput()) def handle(self, request, data): object_file = self.files['object_file'] if data['path']: object_path = "/".join([data['path'].rstrip("/"), data['name']]) else: object_path = data['name'] try: obj = api.swift_upload_object(request, data['container_name'], object_path, object_file) obj.metadata['orig-filename'] = object_file.name obj.sync_metadata() messages.success(request, _("Object was successfully uploaded.")) except: exceptions.handle(request, _("Unable to upload object.")) return shortcuts.redirect("horizon:nova:containers:object_index", data['container_name'], data['path'])
def __init__(self, request, *args, **kwargs): super(UploadFileForm, self).__init__(request, *args, **kwargs) sahara = saharaclient.client(request) self._generate_plugin_version_fields(sahara) self.fields['template_file'] = forms.FileField(label=_("Template"))
class UploadTemplate(forms.SelfHandlingForm): upload_template = forms.FileField(required=False) http_url = forms.CharField(required=False) def handle(self, request, data): if 'upload_template' in request.FILES: # local file upload template = request.FILES['upload_template'].read() template_name = request.FILES['upload_template'].name elif 'http_url' in request.POST and request.POST['http_url']: # download from a given url url = request.POST['http_url'] template_name = url.split('/')[-1] # TODO: make cache dir configurable via django settings # TODO: make disabling ssl verification configurable too h = httplib2.Http(".cache", disable_ssl_certificate_validation=True) resp, template = h.request(url, "GET") if resp.status not in (200, 304): messages.error(request, 'URL returned status %s' % resp.status) return False else: # neither file or url were given messages.error(request, "Please choose a file or provide a url") return False # store the template so we can render it next request.session['heat_template'] = template request.session['heat_template_name'] = template_name # No template validation is done here, We'll let heat do that for us return True
class UploadObject(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Object Name"), validators=[no_slash_validator]) object_file = forms.FileField(label=_("File"), allow_empty_file=True) container_name = forms.CharField(widget=forms.HiddenInput()) def handle(self, request, data): object_file = self.files['object_file'] if data['path']: object_path = "/".join([data['path'].rstrip("/"), data['name']]) else: object_path = data['name'] try: obj = api.swift_upload_object(request, data['container_name'], object_path, object_file) messages.success(request, _("Object was successfully uploaded.")) return obj except: exceptions.handle(request, _("Unable to upload object."))
class ImportForm(forms.SelfHandlingForm): name = forms.CharField( label=_("Stack name"), required=True, max_length=80, help_text=_("Stack name should be unique in the project")) importing = forms.FileField(label=_('OVA File'), help_text=_('A local importing to upload.'), widget=forms.FileInput(), required=False) def clean(self): cleaned_data = super(ImportForm, self).clean() return cleaned_data def handle(self, request, data): try: context = {} if data: context['name'] = data.get("name", "") context['importing'] = data.get("importing", "") utils.importOVA(self, request, context) return True except Exception: print traceback.format_exc() exceptions.handle(request, _("Unable to add importing OVA")) return False
def __init__(self, request, *args, **kwargs): super(DecryptPasswordInstanceForm, self).__init__(request, *args, **kwargs) instance_id = kwargs.get('initial', {}).get('instance_id') self.fields['instance_id'].initial = instance_id keypair_name = kwargs.get('initial', {}).get('keypair_name') self.fields['keypair_name'].initial = keypair_name try: result = api.nova.get_password(request, instance_id) if not result: _unavailable = _("Instance Password is not set" " or is not yet available") self.fields['encrypted_password'].initial = _unavailable else: self.fields['encrypted_password'].initial = result self.fields['private_key_file'] = forms.FileField( label=_('Private Key File'), widget=forms.FileInput(), required=True) self.fields['private_key'] = forms.CharField( widget=forms.widgets.Textarea(), label=_("OR Copy/Paste your Private Key"), required=True) _attrs = {'readonly': 'readonly'} self.fields['decrypted_password'] = forms.CharField( widget=forms.widgets.TextInput(_attrs), label=_("Password"), required=False) except Exception: redirect = reverse('horizon:project:instances:index') _error = _("Unable to retrieve instance password.") exceptions.handle(request, _error, redirect=redirect)
class CreateForm(forms.SelfHandlingForm): definition_source = forms.ChoiceField( label=_('Definition Source'), choices=[('file', _('File')), ('raw', _('Direct Input'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'definitionsource' })) definition_upload = forms.FileField( label=_('Definition File'), help_text=_('A local definition to upload.'), widget=forms.FileInput( attrs={ 'class': 'switched', 'data-switch-on': 'definitionsource', 'data-required-when-shown': 'true', 'data-definitionsource-file': _('Definition File') }), required=False) definition_data = forms.CharField( label=_('Definition Data'), help_text=_('The raw contents of the definition.'), widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'definitionsource', 'data-required-when-shown': 'true', 'data-definitionsource-raw': _('Definition Data'), 'rows': 4 }), required=False) def clean(self): cleaned_data = super(CreateForm, self).clean() if cleaned_data.get('definition_upload'): files = self.request.FILES cleaned_data['definition'] = files['definition_upload'].read() elif cleaned_data.get('definition_data'): cleaned_data['definition'] = cleaned_data['definition_data'] else: raise forms.ValidationError( _('You must specify the definition source.')) return cleaned_data def handle(self, request, data): try: api.action_create(request, data['definition']) msg = _('Successfully created action.') messages.success(request, msg) return True except Exception: msg = _('Failed to create action.') redirect = reverse('horizon:mistral:actions:index') exceptions.handle(request, msg, redirect=redirect)
class ReportInputForm(forms.Form): title = forms.CharField(max_length=32) subtitle = forms.CharField(max_length=128) description = forms.CharField() media_id = forms.IntegerField(min_value=1) # 标签:数据格式为JSON字符串,如:['行业月报', '综艺'] tags = forms.CharField(max_length=256) # 报告文件 report_file = forms.FileField()
class UploadMetricModule(forms.SelfHandlingForm): metric_module_file = forms.FileField(label=_("File"), required=True, allow_empty_file=False) class_name = forms.CharField( max_length=255, label=_("Class Name"), help_text=_("The main class of the metric module to be created."), widget=forms.TextInput(attrs={ "ng-model": "name", "not-blank": "" })) put = forms.BooleanField(required=False, label='Put') get = forms.BooleanField(required=False, label='Get') replicate = forms.BooleanField(required=False, label='Replicate') execution_server = forms.ChoiceField( label=_('Execution Server'), choices=[('proxy', _('Proxy Node')), ('object', _('Storage Node')), ('proxy/object', _('Proxy & Storage Nodes'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source' })) status = forms.CharField( max_length=255, label=_("Status"), initial='Stopped', widget=forms.HiddenInput( # hidden attrs={"ng-model": "status"})) def __init__(self, request, *args, **kwargs): super(UploadMetricModule, self).__init__(request, *args, **kwargs) @staticmethod def handle(request, data): metric_module_file = data['metric_module_file'] del data['metric_module_file'] try: response = api.add_metric_module_metadata(request, data, metric_module_file) if 200 <= response.status_code < 300: messages.success( request, _('Metric module was created and uploaded successfully.')) return data else: raise sdsexception.SdsException(response.text) except Exception as ex: redirect = reverse("horizon:crystal:metrics:index") error_message = "Unable to create metric module.\t %s" % ex.message exceptions.handle(request, _(error_message), redirect=redirect)
class ReportUpdateForm(forms.Form): id = forms.IntegerField(min_value=1) title = forms.CharField(max_length=32, required=False) subtitle = forms.CharField(max_length=128, required=False) description = forms.CharField(required=False) media_id = forms.IntegerField(min_value=1, required=False) # 标签:数据格式为JSON字符串,如:['行业月报', '综艺'] tags = forms.CharField(max_length=256, required=False) # 报告文件 report_file = forms.FileField(required=False)
class UpdateMetricModule(forms.SelfHandlingForm): metric_module_file = forms.FileField(label=_("File"), required=False, allow_empty_file=False) class_name = forms.CharField( max_length=255, label=_("Class Name"), help_text=_("The main class of the metric module to be created.")) put = forms.BooleanField(required=False, label='Put') get = forms.BooleanField(required=False, label='Get') replicate = forms.BooleanField(required=False, label='Replicate') execution_server = forms.ChoiceField( label=_('Execution Server'), choices=[('proxy', _('Proxy Node')), ('object', _('Storage Node')), ('proxy/object', _('Proxy & Storage Nodes'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source' })) def __init__(self, request, *args, **kwargs): super(UpdateMetricModule, self).__init__(request, *args, **kwargs) failure_url = 'horizon:crystal:metrics:index' def handle(self, request, data): metric_module_file = data['metric_module_file'] del data['metric_module_file'] metric_module_id = self.initial['id'] try: response = api.update_metric_module_metadata( request, metric_module_id, data) if 200 <= response.status_code < 300: try: if metric_module_file is not None: response = api.update_metric_module_data( request, metric_module_id, metric_module_file) if response.status_code > 300: # error raise sdsexception.SdsException(response.text) except Exception as ex: pass messages.success(request, _('Successfully metric module updated.')) return data else: raise sdsexception.SdsException(response.text) except Exception as ex: redirect = reverse("horizon:crystal:metrics:index") error_message = "Unable to update metric module.\t %s" % ex.message exceptions.handle(request, _(error_message), redirect=redirect)
class UploadObject(forms.SelfHandlingForm): name = forms.CharField(max_length="255", label=_("Object Name")) object_file = forms.FileField(label=_("File")) container_name = forms.CharField(widget=forms.HiddenInput()) def handle(self, request, data): api.swift_upload_object(request, data['container_name'], data['name'], self.files['object_file'].read()) messages.success(request, _("Object was successfully uploaded.")) return shortcuts.redirect("horizon:nova:containers:object_index", data['container_name'])
class CreateForm(forms.SelfHandlingForm): source_uri = forms.CharField(label=_("Source URI")) name = forms.CharField(label=_("Languagepack Name"), max_length=100) description = forms.CharField(label=_("Description"), required=False, max_length=255) param_file = forms.FileField(label=_("Parameter File"), required=False) lp_metadata = forms.FileField(label=_("Languagepack Metadata File"), required=False) def handle(self, request, data): LOG.info('CreateLanguagepack %s' % data) solum = solumclient(request) param_data = {} if data['param_file']: inf = data['param_file'].read() param_data = yaml.load(inf) lp_metadata = None if data['lp_metadata']: lp_metadata = json.dumps(json.load(data['lp_metadata'])) try: solum.languagepacks.create(name=data['name'], source_uri=data['source_uri'], lp_metadata=lp_metadata, lp_params=param_data, description=data['description']) message = _( 'Languagepack %s was successfully created.') % data['name'] messages.success(request, message) except Exception: redirect = reverse('horizon:solum:languagepacks:index') exceptions.handle(self.request, _('Unable to create languagepack.'), redirect=redirect) return True
class UpdateController(forms.SelfHandlingForm): controller_file = forms.FileField(label=_("File"), required=False, allow_empty_file=False) class_name = forms.CharField( max_length=255, label=_('Class Name'), help_text=_('The class name of the controller to be created.')) description = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 4}), label=_("Description"), required=False) valid_parameters = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 2}), label=_("Valid Parameters"), required=False) def __init__(self, request, *args, **kwargs): super(UpdateController, self).__init__(request, *args, **kwargs) def handle(self, request, data): controller_file = data['controller_file'] del data['controller_file'] try: response = api.update_controller_metadata(request, self.initial['id'], data) if 200 <= response.status_code < 300: try: if controller_file is not None: response = api.update_controller_data( request, self.initial['id'], controller_file) if response.status_code > 300: # error raise sdsexception.SdsException(response.text) except: pass messages.success( request, _('Successfully updated controller: %s') % self.initial['id']) return data else: raise sdsexception.SdsException(response.text) except Exception as ex: redirect = reverse("horizon:crystal:controllers:index") error_message = "Unable to update controller.\t %s" % ex.message exceptions.handle(request, _(error_message), redirect=redirect)
class CreateController(forms.SelfHandlingForm): controller_file = forms.FileField(label=_("File"), required=True, allow_empty_file=False) class_name = forms.CharField( max_length=255, label=_('Main Class'), help_text=_('The class name of the controller to be created.'), widget=forms.TextInput(attrs={ 'ng-model': 'name', 'not-blank': '' })) description = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 4}), label=_("Description"), required=False) valid_parameters = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 2}), label=_("Valid Parameters"), required=False) instances = forms.CharField( max_length=255, label=_("Instances"), initial=0, widget=forms.HiddenInput( # hidden attrs={"ng-model": "instances"})) def __init__(self, request, *args, **kwargs): super(CreateController, self).__init__(request, *args, **kwargs) @staticmethod def handle(request, data): controller_file = data['controller_file'] del data['controller_file'] try: response = api.add_controller(request, data, controller_file) if 200 <= response.status_code < 300: messages.success(request, _("Controller successfully created.")) return data else: raise sdsexception.SdsException(response.text) except Exception as ex: redirect = reverse("horizon:crystal:controllers:index") error_message = "Unable to create controller.\t %s" % ex.message exceptions.handle(request, _(error_message), redirect=redirect)
class ImportClusterTemplateFileForm(forms.SelfHandlingForm): class Meta(object): name = _("Import Cluster Template") def __init__(self, *args, **kwargs): self.next_view = kwargs.pop("next_view") super(ImportClusterTemplateFileForm, self).__init__(*args, **kwargs) template_upload = forms.FileField(label=_("Template File"), required=True) def handle(self, request, data): kwargs = {"template_upload": data["template_upload"]} request.method = "GET" return self.next_view.as_view()(request, **kwargs)
class ImportNodegroupTemplateFileForm(forms.SelfHandlingForm): class Meta(object): name = _("Import Node Group Template") def __init__(self, *args, **kwargs): self.next_view = kwargs.pop('next_view') super(ImportNodegroupTemplateFileForm, self).__init__(*args, **kwargs) template_upload = forms.FileField(label=_('Template File'), required=True) def handle(self, request, data): kwargs = {'template_upload': data['template_upload']} request.method = 'GET' return self.next_view.as_view()(request, **kwargs)
class UploadPatchForm(forms.SelfHandlingForm): failure_url = 'horizon:admin:software_management:index' patch_files = forms.FileField( label=_("Patch File(s)"), widget=forms.FileInput(attrs={ 'data-source-file': _('Patch File(s)'), 'multiple': "multiple" }), required=True) def __init__(self, *args, **kwargs): super(UploadPatchForm, self).__init__(*args, **kwargs) def clean(self): data = super(UploadPatchForm, self).clean() return data def handle(self, request, data): success_responses = [] failure_responses = [] for f in request.FILES.getlist('patch_files'): try: success_responses.append( stx_api.patch.upload_patch(request, f, f.name)) except Exception as ex: failure_responses.append(str(ex)) # Consolidate server responses into one success/error message # respectively if success_responses: if len(success_responses) == 1: messages.success(request, success_responses[0]) else: success_msg = "" for i in range(len(success_responses)): success_msg += str(i + 1) + ") " + success_responses[i] messages.success(request, success_msg) if failure_responses: if len(failure_responses) == 1: messages.error(request, failure_responses[0]) else: error_msg = "" for i in range(len(failure_responses)): error_msg += str(i + 1) + ") " + failure_responses[i] messages.error(request, error_msg) return True
class UploadObject(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Object Name"), help_text=_("Slashes are allowed, and are treated " "as pseudo-folders by the Object " "Store."), widget=forms.TextInput(attrs={ "ng-model": "name", "not-blank": "" })) object_file = forms.FileField(label=_("File"), required=False, allow_empty_file=True) container_name = forms.CharField(widget=forms.HiddenInput()) def _set_object_path(self, data): if data['path']: object_path = "/".join([data['path'].rstrip("/"), data['name']]) else: object_path = data['name'] return object_path def clean(self): data = super(UploadObject, self).clean() if 'object_file' not in self.files: self.files['object_file'] = None return data def handle(self, request, data): object_file = self.files['object_file'] object_path = self._set_object_path(data) try: obj = api.swift.swift_upload_object(request, data['container_name'], object_path, object_file) msg = force_unicode(_("Object was successfully uploaded.")) messages.success(request, msg) return obj except Exception: exceptions.handle(request, _("Unable to upload object."))
class ImportPlan(forms.SelfHandlingForm): plan_upload = forms.FileField( label=_('Plan File'), required=True) def __init__(self, request, *args, **kwargs): super(ImportPlan, self).__init__(request, *args, **kwargs) def handle(self, request, data): try: plan_file = request.FILES['plan_upload'] template = plan_file.read() api.create_plan_by_template(request, template) messages.success(request, _("Successfully imported plan: %s") % data['plan_upload'].name) return True except Exception: msg = _("Unable to import plan.") redirect = reverse('horizon:conveyor:plans:index') exceptions.handle(request, msg, redirect=redirect)
class TemplateForm(forms.SelfHandlingForm): class Meta: name = _('Select Template') help_text = _('Select a template to launch a stack.') # TODO(jomara) - update URL choice for template & environment files # w/ client side download when applicable base_choices = [('file', _('File')), ('raw', _('Direct Input'))] url_choice = [('url', _('URL'))] attributes = {'class': 'switchable', 'data-slug': 'templatesource'} template_source = forms.ChoiceField(label=_('Template Source'), choices=base_choices + url_choice, widget=forms.Select(attrs=attributes)) attributes = create_upload_form_attributes('template', 'file', _('Template File')) template_upload = forms.FileField( label=_('Template File'), help_text=_('A local template to upload.'), widget=forms.FileInput(attrs=attributes), required=False) attributes = create_upload_form_attributes('template', 'url', _('Template URL')) template_url = forms.URLField( label=_('Template URL'), help_text=_('An external (HTTP) URL to load the template from.'), widget=forms.TextInput(attrs=attributes), required=False) attributes = create_upload_form_attributes('template', 'raw', _('Template Data')) template_data = forms.CharField( label=_('Template Data'), help_text=_('The raw contents of the template.'), widget=forms.widgets.Textarea(attrs=attributes), required=False) attributes = {'data-slug': 'envsource', 'class': 'switchable'} environment_source = forms.ChoiceField( label=_('Environment Source'), choices=base_choices, widget=forms.Select(attrs=attributes), required=False) attributes = create_upload_form_attributes('env', 'file', _('Environment File')) environment_upload = forms.FileField( label=_('Environment File'), help_text=_('A local environment to upload.'), widget=forms.FileInput(attrs=attributes), required=False) attributes = create_upload_form_attributes('env', 'raw', _('Environment Data')) environment_data = forms.CharField( label=_('Environment Data'), help_text=_('The raw contents of the environment file.'), widget=forms.widgets.Textarea(attrs=attributes), required=False) def __init__(self, *args, **kwargs): self.next_view = kwargs.pop('next_view') super(TemplateForm, self).__init__(*args, **kwargs) def clean(self): cleaned = super(TemplateForm, self).clean() files = self.request.FILES self.clean_uploaded_files('template', _('template'), cleaned, files) self.clean_uploaded_files('environment', _('environment'), cleaned, files) # Validate the template and get back the params. kwargs = {} if cleaned['template_data']: kwargs['template'] = cleaned['template_data'] else: kwargs['template_url'] = cleaned['template_url'] if cleaned['environment_data']: kwargs['environment'] = cleaned['environment_data'] try: validated = api.heat.template_validate(self.request, **kwargs) cleaned['template_validate'] = validated except Exception as e: raise forms.ValidationError(unicode(e)) return cleaned def clean_uploaded_files(self, prefix, field_label, cleaned, files): """Cleans Template & Environment data from form upload. Does some of the crunchy bits for processing uploads vs raw data depending on what the user specified. Identical process for environment data & template data. :type prefix: str :param prefix: prefix (environment, template) of field :type field_label: str :param field_label: translated prefix str for messages :type input_type: dict :param prefix: existing cleaned fields from form :rtype: dict :return: cleaned dict including environment & template data """ upload_str = prefix + "_upload" data_str = prefix + "_data" url = cleaned.get(prefix + '_url') data = cleaned.get(prefix + '_data') has_upload = upload_str in files # Uploaded file handler if has_upload and not url: log_template_name = files[upload_str].name LOG.info('got upload %s' % log_template_name) tpl = files[upload_str].read() if tpl.startswith('{'): try: json.loads(tpl) except Exception as e: msg = _('There was a problem parsing the' ' %(prefix)s: %(error)s') msg = msg % {'prefix': prefix, 'error': e} raise forms.ValidationError(msg) cleaned[data_str] = tpl # URL handler elif url and (has_upload or data): msg = _('Please specify a %s using only one source method.') msg = msg % field_label raise forms.ValidationError(msg) elif prefix == 'template': # Check for raw template input - blank environment allowed if not url and not data: msg = _('You must specify a template via one of the ' 'available sources.') raise forms.ValidationError(msg) def create_kwargs(self, data): kwargs = { 'parameters': data['template_validate'], 'environment_data': data['environment_data'], 'template_data': data['template_data'], 'template_url': data['template_url'] } if data.get('stack_id'): kwargs['stack_id'] = data['stack_id'] return kwargs def handle(self, request, data): kwargs = self.create_kwargs(data) # NOTE (gabriel): This is a bit of a hack, essentially rewriting this # request so that we can chain it as an input to the next view... # but hey, it totally works. request.method = 'GET' return self.next_view.as_view()(request, **kwargs)
class CustomizeAction(workflows.Action): class Meta(object): name = _("Post-Creation") help_text_template = ("project/instances/" "_launch_customize_help.html") source_choices = [('', _('Select Script Source')), ('raw', _('Direct Input')), ('file', _('File'))] attributes = {'class': 'switchable', 'data-slug': 'scriptsource'} script_source = forms.ChoiceField(label=_('Customization Script Source'), choices=source_choices, widget=forms.Select(attrs=attributes), required=False) script_help = _("A script or set of commands to be executed after the " "instance has been built (max 16kb).") script_upload = forms.FileField( label=_('Script File'), help_text=script_help, widget=forms.FileInput( attrs={ 'class': 'switched', 'data-switch-on': 'scriptsource', 'data-scriptsource-file': _('Script File') }), required=False) script_data = forms.CharField( label=_('Script Data'), help_text=script_help, widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'scriptsource', 'data-scriptsource-raw': _('Script Data') }), required=False) def __init__(self, *args): super(CustomizeAction, self).__init__(*args) def clean(self): cleaned = super(CustomizeAction, self).clean() files = self.request.FILES script = self.clean_uploaded_files('script', files) if script is not None: cleaned['script_data'] = script return cleaned def clean_uploaded_files(self, prefix, files): upload_str = prefix + "_upload" has_upload = upload_str in files if has_upload: upload_file = files[upload_str] log_script_name = upload_file.name LOG.info('got upload %s' % log_script_name) if upload_file._size > 16 * units.Ki: # 16kb msg = _('File exceeds maximum size (16kb)') raise forms.ValidationError(msg) else: script = upload_file.read() if script != "": try: normalize_newlines(script) except Exception as e: msg = _('There was a problem parsing the' ' %(prefix)s: %(error)s') msg = msg % { 'prefix': prefix, 'error': six.text_type(e) } raise forms.ValidationError(msg) return script else: return None
class CreateImageForm(forms.SelfHandlingForm): name = forms.CharField(max_length="255", label=_("Name"), required=True) description = forms.CharField(widget=forms.widgets.Textarea( attrs={'class': 'modal-body-fixed-width'}), label=_("Description"), required=False) source_type = forms.ChoiceField( label=_('Image Source'), required=False, choices=[('url', _('Image Location')), ('file', _('Image File'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source'})) copy_from = forms.CharField(max_length="255", label=_("Image Location"), help_text=_("An external (HTTP) URL to load " "the image from."), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-url': _('Image Location')}), required=False) image_file = forms.FileField(label=_("Image File"), help_text=_("A local image to upload."), widget=forms.FileInput(attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-file': _('Image File')}), required=False) disk_format = forms.ChoiceField(label=_('Format'), required=True, choices=[], widget=forms.Select(attrs={'class': 'switchable'})) architecture = forms.CharField(max_length="255", label=_("Architecture"), required=False) minimum_disk = forms.IntegerField(label=_("Minimum Disk (GB)"), help_text=_('The minimum disk size' ' required to boot the' ' image. If unspecified, this' ' value defaults to 0' ' (no minimum).'), required=False) minimum_ram = forms.IntegerField(label=_("Minimum Ram (MB)"), help_text=_('The minimum memory size' ' required to boot the' ' image. If unspecified, this' ' value defaults to 0 (no' ' minimum).'), required=False) is_public = forms.BooleanField(label=_("Public"), required=False) protected = forms.BooleanField(label=_("Protected"), required=False) def __init__(self, request, *args, **kwargs): super(CreateImageForm, self).__init__(request, *args, **kwargs) if (not settings.HORIZON_IMAGES_ALLOW_UPLOAD or not policy.check((("image", "upload_image"),), request)): self._hide_file_source_type() if not policy.check((("image", "set_image_location"),), request): self._hide_url_source_type() if not policy.check((("image", "publicize_image"),), request): self._hide_is_public() self.fields['disk_format'].choices = IMAGE_FORMAT_CHOICES def _hide_file_source_type(self): self.fields['image_file'].widget = HiddenInput() source_type = self.fields['source_type'] source_type.choices = [choice for choice in source_type.choices if choice[0] != 'file'] if len(source_type.choices) == 1: source_type.widget = HiddenInput() def _hide_url_source_type(self): self.fields['copy_from'].widget = HiddenInput() source_type = self.fields['source_type'] source_type.choices = [choice for choice in source_type.choices if choice[0] != 'url'] if len(source_type.choices) == 1: source_type.widget = HiddenInput() def _hide_is_public(self): self.fields['is_public'].widget = HiddenInput() self.fields['is_public'].initial = False def clean(self): data = super(CreateImageForm, self).clean() # The image_file key can be missing based on particular upload # conditions. Code defensively for it here... image_file = data.get('image_file', None) image_url = data.get('copy_from', None) if not image_url and not image_file: raise ValidationError( _("A image or external image location must be specified.")) elif image_url and image_file: raise ValidationError( _("Can not specify both image and external image location.")) else: return data def handle(self, request, data): # Glance does not really do anything with container_format at the # moment. It requires it is set to the same disk_format for the three # Amazon image types, otherwise it just treats them as 'bare.' As such # we will just set that to be that here instead of bothering the user # with asking them for information we can already determine. if data['disk_format'] in ('ami', 'aki', 'ari',): container_format = data['disk_format'] else: container_format = 'bare' meta = {'is_public': data['is_public'], 'protected': data['protected'], 'disk_format': data['disk_format'], 'container_format': container_format, 'min_disk': (data['minimum_disk'] or 0), 'min_ram': (data['minimum_ram'] or 0), 'name': data['name'], 'properties': {}} if data['description']: meta['properties']['description'] = data['description'] if data['architecture']: meta['properties']['architecture'] = data['architecture'] if (settings.HORIZON_IMAGES_ALLOW_UPLOAD and policy.check((("image", "upload_image"),), request) and data.get('image_file', None)): meta['data'] = self.files['image_file'] else: meta['copy_from'] = data['copy_from'] try: image = api.glance.image_create(request, **meta) messages.success(request, _('Your image %s has been queued for creation.') % data['name']) return image except Exception: exceptions.handle(request, _('Unable to create new image.'))
def __init__(self, request, *args, **kwargs): super(JobBinaryCreateForm, self).__init__(request, *args, **kwargs) self.help_text_template = "job_binaries/_create_job_binary_help.html" self.fields["job_binary_name"] = forms.CharField(label=_("Name")) self.fields["job_binary_type"] = forms.ChoiceField( label=_("Storage type"), widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'jb_type' })) self.fields["job_binary_url"] = forms.CharField( label=_("URL"), required=False, widget=LabeledInput( attrs={ 'class': 'switched', 'data-switch-on': 'jb_type', 'data-jb_type-swift': _('URL') })) self.fields["job_binary_manila_share"] = forms.ChoiceField( label=_("Share"), required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'jb_type', 'data-jb_type-manila': _('Share') })) self.fields["job_binary_manila_path"] = forms.CharField( label=_("Path"), required=False, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'jb_type', 'data-jb_type-manila': _('Path') })) self.fields["job_binary_internal"] = forms.ChoiceField( label=_("Internal binary"), required=False, widget=forms.Select( attrs={ 'class': 'switched switchable', 'data-slug': 'jb_internal', 'data-switch-on': 'jb_type', 'data-jb_type-internal-db': _('Internal Binary') })) self.fields["job_binary_file"] = forms.FileField( label=_("Upload File"), required=False, widget=forms.ClearableFileInput( attrs={ 'class': 'switched', 'data-switch-on': 'jb_internal', 'data-jb_internal-uploadfile': _("Upload File") })) self.fields["job_binary_script_name"] = forms.CharField( label=_("Script name"), required=False, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'jb_internal', 'data-jb_internal-newscript': _("Script name") })) self.fields["job_binary_script"] = forms.CharField( label=_("Script text"), required=False, widget=forms.Textarea( attrs={ 'rows': 4, 'class': 'switched', 'data-switch-on': 'jb_internal', 'data-jb_internal-newscript': _("Script text") })) self.fields["job_binary_username"] = forms.CharField( label=_("Username"), required=False, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'jb_type', 'data-jb_type-swift': _('Username') })) self.fields["job_binary_password"] = forms.CharField( label=_("Password"), required=False, widget=forms.PasswordInput( attrs={ 'autocomplete': 'off', 'class': 'switched', 'data-switch-on': 'jb_type', 'data-jb_type-swift': _('Password') })) self.fields["job_binary_description"] = (forms.CharField( label=_("Description"), required=False, widget=forms.Textarea())) self.fields["is_public"] = acl_utils.get_is_public_form( _("job binary")) self.fields["is_protected"] = acl_utils.get_is_protected_form( _("job binary")) self.fields["job_binary_type"].choices =\ [("internal-db", "Internal database"), ("swift", "Swift")] self.fields["job_binary_internal"].choices =\ self.populate_job_binary_internal_choices(request) if saharaclient.base.is_service_enabled(request, 'share'): self.fields["job_binary_type"].choices.append(("manila", "Manila")) self.fields["job_binary_manila_share"].choices = ( self.populate_job_binary_manila_share_choices(request)) self.load_form_values()
class CreateNamespaceForm(forms.SelfHandlingForm): source_type = forms.ChoiceField( label=_('Namespace Definition Source'), required=False, choices=[('file', _('Metadata Definition File')), ('raw', _('Direct Input'))], widget=forms.Select( attrs={'class': 'switchable', 'data-slug': 'source'})) metadef_file = forms.FileField( label=_("Metadata Definition File"), help_text=_("A local metadata definition file to upload."), widget=forms.FileInput( attrs={'class': 'switched', 'data-switch-on': 'source', 'data-source-file': _('Metadata Definition File')}), required=False) direct_input = forms.CharField( label=_('Namespace JSON'), help_text=_('The JSON formatted contents of a namespace.'), widget=forms.widgets.Textarea( attrs={'class': 'switched', 'data-switch-on': 'source', 'data-source-raw': _('Namespace JSON')}), required=False) public = forms.BooleanField(label=_("Public"), required=False) protected = forms.BooleanField(label=_("Protected"), required=False) def __init__(self, request, *args, **kwargs): super(CreateNamespaceForm, self).__init__(request, *args, **kwargs) def clean(self): data = super(CreateNamespaceForm, self).clean() # The key can be missing based on particular upload # conditions. Code defensively for it here... metadef_file = data.get('metadef_file', None) metadata_raw = data.get('direct_input', None) if metadata_raw and metadef_file: raise ValidationError( _("Cannot specify both file and direct input.")) if not metadata_raw and not metadef_file: raise ValidationError( _("No input was provided for the namespace content.")) try: if metadef_file: ns_str = self.files['metadef_file'].read() else: ns_str = data['direct_input'] namespace = json.loads(ns_str) if data['public']: namespace['visibility'] = 'public' else: namespace['visibility'] = 'private' namespace['protected'] = data['protected'] for protected_prop in constants.METADEFS_PROTECTED_PROPS: namespace.pop(protected_prop, None) data['namespace'] = namespace except Exception as e: msg = _('There was a problem loading the namespace: %s.') % e raise forms.ValidationError(msg) return data def handle(self, request, data): try: namespace = glance.metadefs_namespace_create(request, data['namespace']) messages.success(request, _('Namespace %s has been created.') % namespace['namespace']) return namespace except Exception as e: msg = _('Unable to create new namespace. %s') msg %= e.message.split('Failed validating', 1)[0] exceptions.handle(request, message=msg) return False
class TemplateForm(forms.SelfHandlingForm): class Meta: name = _('Select Template') help_text = _('From here you can select a template to launch ' 'a stack.') template_source = forms.ChoiceField(label=_('Template Source'), choices=[('url', _('URL')), ('file', _('File')), ('raw', _('Direct Input'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source'})) template_upload = forms.FileField( label=_('Template File'), help_text=_('A local template to upload.'), widget=forms.FileInput(attrs={'class': 'switched', 'data-switch-on': 'source', 'data-source-file': _('Template File')}), required=False) template_url = forms.URLField( label=_('Template URL'), help_text=_('An external (HTTP) URL to load the template from.'), widget=forms.TextInput(attrs={'class': 'switched', 'data-switch-on': 'source', 'data-source-url': _('Template URL')}), required=False) template_data = forms.CharField( label=_('Template Data'), help_text=_('The raw contents of the template.'), widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-raw': _('Template Data')}), required=False) def __init__(self, *args, **kwargs): self.next_view = kwargs.pop('next_view') super(TemplateForm, self).__init__(*args, **kwargs) def clean(self): cleaned = super(TemplateForm, self).clean() template_url = cleaned.get('template_url') template_data = cleaned.get('template_data') files = self.request.FILES has_upload = 'template_upload' in files # Uploaded file handler if has_upload and not template_url: log_template_name = self.request.FILES['template_upload'].name LOG.info('got upload %s' % log_template_name) tpl = self.request.FILES['template_upload'].read() if tpl.startswith('{'): try: json.loads(tpl) except Exception as e: msg = _('There was a problem parsing the template: %s') % e raise forms.ValidationError(msg) cleaned['template_data'] = tpl # URL handler elif template_url and (has_upload or template_data): msg = _('Please specify a template using only one source method.') raise forms.ValidationError(msg) # Check for raw template input elif not template_url and not template_data: msg = _('You must specify a template via one of the ' 'available sources.') raise forms.ValidationError(msg) # Validate the template and get back the params. kwargs = {} if cleaned['template_data']: kwargs['template'] = cleaned['template_data'] else: kwargs['template_url'] = cleaned['template_url'] try: validated = api.heat.template_validate(self.request, **kwargs) cleaned['template_validate'] = validated except Exception as e: msg = exception_to_validation_msg(e) if not msg: msg = _('An unknown problem occurred validating the template.') LOG.exception(msg) raise forms.ValidationError(msg) return cleaned def handle(self, request, data): kwargs = {'parameters': data['template_validate'], 'template_data': data['template_data'], 'template_url': data['template_url']} # NOTE (gabriel): This is a bit of a hack, essentially rewriting this # request so that we can chain it as an input to the next view... # but hey, it totally works. request.method = 'GET' return self.next_view.as_view()(request, **kwargs)
class DeployMECA(forms.SelfHandlingForm): mca_name = forms.CharField(max_length=255, label=_("MECA Name")) description = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 4}), label=_("Description"), required=False) mcad_id = forms.ChoiceField(label=_("MECA Catalog Name")) vim_id = forms.ChoiceField(label=_("VIM Name"), required=False) source_type = forms.ChoiceField( label=_('Parameter Value Source'), required=False, choices=[('file', _('File')), ('raw', _('Direct Input'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source' })) param_file = forms.FileField( label=_('Parameter Value File'), help_text=_('A local Parameter Value file to upload.'), widget=forms.FileInput( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-file': _('Parameter Value File') }), required=False) direct_input = forms.CharField( label=_('Parameter Value YAML'), help_text=_('The YAML formatted contents of Parameter Values.'), widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-raw': _('Parameter Values') }), required=False) config_type = forms.ChoiceField( label=_('Configuration Value Source'), required=False, choices=[('file', _('File')), ('raw', _('Direct Input'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'config' })) config_file = forms.FileField( label=_('Configuration Value File'), help_text=_('MECA Configuration file with YAML ' 'formatted contents to upload.'), widget=forms.FileInput( attrs={ 'class': 'switched', 'data-switch-on': 'config', 'data-config-file': _('Configuration Value File') }), required=False) config_input = forms.CharField( label=_('Configuration Value YAML'), help_text=_('YAML formatted MECA configuration text.'), widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'config', 'data-config-raw': _('Configuration Values') }), required=False) def __init__(self, request, *args, **kwargs): super(DeployMECA, self).__init__(request, *args, **kwargs) try: mecad_list = api.apmec.mecad_list(request) available_choices_mecad = [(meca['id'], meca['name']) for meca in mecad_list] except Exception as e: available_choices_mecad = [] msg = _('Failed to retrieve available MECA Catalog nameca: %s') % e LOG.error(msg) try: vim_list = api.apmec.vim_list(request) available_choices_vims = [(vim['id'], vim['name']) for vim in vim_list] except Exception as e: available_choices_vims = [] msg = _('Failed to retrieve available VIM nameca: %s') % e LOG.error(msg) self.fields['mecad_id'].choices = [ ('', _('Select a MECA Catalog Name')) ] + available_choices_mecad self.fields['vim_id'].choices = [('', _('Select a VIM Name')) ] + available_choices_vims def clean(self): data = super(DeployMECA, self).clean() param_file = data.get('param_file', None) param_raw = data.get('direct_input', None) if param_raw and param_file: raise ValidationError( _("Cannot specify both file and direct input.")) if param_file and not param_file.name.endswith('.yaml'): raise ValidationError(_("Please upload .yaml file only.")) if param_file: data['param_values'] = self.files['param_file'].read() elif param_raw: data['param_values'] = data['direct_input'] else: data['param_values'] = None config_file = data.get('config_file', None) config_raw = data.get('config_input', None) if config_file and config_raw: raise ValidationError( _("Cannot specify both file and direct input.")) if config_file and not config_file.name.endswith('.yaml'): raise ValidationError(_("Only .yaml file uploads supported")) if config_file: data['config_values'] = self.files['config_file'].read() elif config_raw: data['config_values'] = data['config_input'] else: data['config_values'] = None return data def handle(self, request, data): try: meca_name = data['meca_name'] description = data['description'] mecad_id = data['mecad_id'] vim_id = data['vim_id'] param_val = data['param_values'] config_val = data['config_values'] meca_arg = { 'meca': { 'mecad_id': mecad_id, 'name': meca_name, 'description': description, 'vim_id': vim_id } } meca_attr = meca_arg['meca'].setdefault('attributes', {}) if param_val: meca_attr['param_values'] = param_val if config_val: meca_attr['config'] = config_val api.apmec.create_meca(request, meca_arg) mecasages.success( request, _('MECA %s create operation initiated.') % meca_name) return True except Exception as e: exceptions.handle(request, _('Failed to create MECA: %s') % e.message)
class JobBinaryCreateForm(forms.SelfHandlingForm): NEW_SCRIPT = "%%%NEWSCRIPT%%%" UPLOAD_BIN = "%%%UPLOADFILE%%%" job_binary_name = forms.CharField(label=_("Name")) job_binary_type = forms.ChoiceField(label=_("Storage type")) job_binary_url = forms.CharField(label=_("URL"), required=False, widget=LabeledInput()) job_binary_internal = forms.ChoiceField(label=_("Internal binary"), required=False) job_binary_file = forms.FileField(label=_("Upload File"), required=False) job_binary_script_name = forms.CharField(label=_("Script name"), required=False) job_binary_script = forms.CharField( label=_("Script text"), required=False, widget=forms.Textarea(attrs={'rows': 4})) job_binary_username = forms.CharField(label=_("Username"), required=False) job_binary_password = forms.CharField( label=_("Password"), required=False, widget=forms.PasswordInput(attrs={'autocomplete': 'off'})) job_binary_description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea()) def __init__(self, request, *args, **kwargs): super(JobBinaryCreateForm, self).__init__(request, *args, **kwargs) self.help_text_template = ("project/data_processing.job_binaries/" "_create_job_binary_help.html") self.fields["job_binary_type"].choices =\ [("internal-db", "Internal database"), ("swift", "Swift")] self.fields["job_binary_internal"].choices =\ self.populate_job_binary_internal_choices(request) def populate_job_binary_internal_choices(self, request): try: job_binaries = saharaclient.job_binary_internal_list(request) except Exception: exceptions.handle(request, _("Failed to get list of internal binaries.")) job_binaries = [] choices = [(job_binary.id, job_binary.name) for job_binary in job_binaries] choices.insert(0, (self.NEW_SCRIPT, '*Create a script')) choices.insert(0, (self.UPLOAD_BIN, '*Upload a new file')) return choices def handle(self, request, context): try: extra = {} bin_url = "%s://%s" % (context["job_binary_type"], context["job_binary_url"]) if (context["job_binary_type"] == "internal-db"): bin_url = self.handle_internal(request, context) elif (context["job_binary_type"] == "swift"): extra = self.handle_swift(request, context) saharaclient.job_binary_create(request, context["job_binary_name"], bin_url, context["job_binary_description"], extra) messages.success(request, "Successfully created job binary") return True except Exception: exceptions.handle(request, _("Unable to create job binary")) return False def get_help_text(self, extra_context=None): text = "" extra_context = extra_context or {} if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) context = template.RequestContext(self.request, extra_context) text += tmpl.render(context) else: text += defaultfilters.linebreaks(force_text(self.help_text)) return defaultfilters.safe(text) class Meta: name = _("Create Job Binary") help_text_template = ("project/data_processing.job_binaries/" "_create_job_binary_help.html") def handle_internal(self, request, context): result = "" bin_id = context["job_binary_internal"] if (bin_id == self.UPLOAD_BIN): try: result = saharaclient.job_binary_internal_create( request, self.get_unique_binary_name( request, request.FILES["job_binary_file"].name), request.FILES["job_binary_file"].read()) except Exception: exceptions.handle(request, _("Unable to upload job binary")) return None elif (bin_id == self.NEW_SCRIPT): try: result = saharaclient.job_binary_internal_create( request, self.get_unique_binary_name( request, context["job_binary_script_name"]), context["job_binary_script"]) except Exception: exceptions.handle(request, _("Unable to create job binary")) return None bin_id = result.id return "internal-db://%s" % bin_id def handle_swift(self, request, context): username = context["job_binary_username"] password = context["job_binary_password"] extra = {"user": username, "password": password} return extra def get_unique_binary_name(self, request, base_name): try: internals = saharaclient.job_binary_internal_list(request) except Exception: internals = [] exceptions.handle(request, _("Failed to fetch internal binary list")) names = [internal.name for internal in internals] if base_name in names: return "%s_%s" % (base_name, uuid.uuid1()) return base_name
class OnBoardVNF(forms.SelfHandlingForm): name = forms.CharField(max_length=255, label=_("Name")) description = forms.CharField( widget=forms.widgets.Textarea(attrs={'rows': 4}), label=_("Description"), required=False) source_type = forms.ChoiceField( label=_('TOSCA Template Source'), required=False, choices=[('file', _('TOSCA Template File')), ('raw', _('Direct Input'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'source' })) toscal_file = forms.FileField( label=_("TOSCA Template File"), help_text=_("A local TOSCA template file to upload."), widget=forms.FileInput( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-file': _('TOSCA Template File') }), required=False) direct_input = forms.CharField( label=_('TOSCA YAML'), help_text=_('The YAML formatted contents of a TOSCA template.'), widget=forms.widgets.Textarea( attrs={ 'class': 'switched', 'data-switch-on': 'source', 'data-source-raw': _('TOSCA YAML') }), required=False) def __init__(self, request, *args, **kwargs): super(OnBoardVNF, self).__init__(request, *args, **kwargs) def clean(self): data = super(OnBoardVNF, self).clean() # The key can be missing based on particular upload # conditions. Code defensively for it here... toscal_file = data.get('toscal_file', None) toscal_raw = data.get('direct_input', None) source_type = data.get("source_type") if source_type == "file" and not toscal_file: raise ValidationError(_("No TOSCA template file selected.")) if source_type == "raw" and not toscal_raw: raise ValidationError(_("No direct input specified.")) if toscal_file and not toscal_file.name.endswith(('.yaml', '.csar')): raise ValidationError( _("Only .yaml or .csar file uploads \ are supported")) try: if toscal_file: toscal_str = self.files['toscal_file'].read() else: toscal_str = data['direct_input'] # toscal = yaml.loads(toscal_str) data['tosca'] = toscal_str except Exception as e: msg = _('There was a problem loading the namespace: %s.') % e raise forms.ValidationError(msg) return data def handle(self, request, data): try: toscal = data['tosca'] vnfd_name = data['name'] vnfd_description = data['description'] tosca_arg = { 'vnfd': { 'name': vnfd_name, 'description': vnfd_description, 'attributes': { 'vnfd': toscal } } } vnfd_instance = api.tacker.create_vnfd(request, tosca_arg) messages.success( request, _('VNF Catalog entry %s has been created.') % vnfd_instance['vnfd']['name']) return toscal except Exception as e: msg = _('Unable to create TOSCA. %s') msg %= e.message.split('Failed validating', 1)[0] exceptions.handle(request, message=msg) return False