def handle(self, request, data): try: template = data["template"] template = json.loads(template) template = template["node_group_template"] if not data["name"] and "name" not in template.keys(): return False if data["name"]: template["name"] = data["name"] template["security_groups"] = data["security_groups"] template["floating_ip_pool"] = data["floating_ip_pool"] template["flavor_id"] = data["flavor"] template["image_id"] = data["image_id"] saharaclient.nodegroup_template_create(request, **template) return True except api_base.APIException as e: self.error_description = str(e) return False except Exception as e: if isinstance(e, TypeError): raise exceptions.BadRequest( _("Template JSON contained invalid key")) else: raise exceptions.BadRequest(_("Could not parse template"))
def import_object(request, **kwargs): args = {} try: object_type = kwargs.pop('object_type') except TypeError: raise exceptions.BadRequest("Object type must be included in kwargs") for (key, value) in kwargs.items(): if key in ['data', 'key']: # the data was passed in b64 encoded because some of the bytes # were changed when the raw bytes were passed from the form value = base64.b64decode(value) if (issubclass(object_type, key_type.Key) and key in IMPORT_KEY_ATTRIBUTES): args[str(key)] = value elif object_type == x_509.X509 and key in IMPORT_CERT_ATTRIBUTES: args[str(key)] = value elif (object_type == passphrase.Passphrase and key in IMPORT_PASSPHRASE_ATTRIBUTES): args[str(key)] = value elif (object_type == opaque_data.OpaqueData and key in IMPORT_DATA_ATTRIBUTES): args[str(key)] = value else: raise exceptions.BadRequest("Attribute must be in %s" % ",".join(IMPORT_KEY_ATTRIBUTES)) key = object_type(**args) created_uuid = key_manager().store(get_context(request), key) return created_uuid
def handle(self, request, data): try: template = data["template_upload"] template = json.loads(template) template = template["cluster_template"] if "name" not in template.keys(): return False if "neutron_management_network" in template: template["net_id"] = ( template.pop("neutron_management_network")) # default_image_id is not supported by the client now if "default_image_id" in template: template.pop("default_image_id") node_groups = [] ids = json.loads(data['forms_ids']) for id in ids: name = data['group_name_' + str(id)] template_id = data['template_id_' + str(id)] count = data['count_' + str(id)] raw_ng = data.get("serialized_" + str(id)) if raw_ng and raw_ng != 'null': ng = json.loads(utils.deserialize(str(raw_ng))) else: ng = dict() ng["name"] = name ng["count"] = count if template_id and template_id != u'None': ng["node_group_template_id"] = template_id node_groups.append(ng) template["node_groups"] = node_groups saharaclient.cluster_template_create(request, **template) return True except api_base.APIException as e: self.error_description = str(e) return False except Exception as e: if isinstance(e, TypeError): raise exceptions.BadRequest( _("Template JSON contained invalid key")) else: raise exceptions.BadRequest(_("Could not parse template"))
def _test_edit_volume_type_access(self, exception=False): volume_type = self.cinder_volume_types.list()[2] volume_type.id = u'1' keystone.tenant_list(IsA(http.HttpRequest)).AndReturn( [self.tenants.list(), False]) type_access = self.cinder_type_access.list() formData = {'member': [u'3'], 'volume_type_id': volume_type.id} volume_type = cinder.volume_type_get(IsA( http.HttpRequest), volume_type.id).AndReturn(volume_type) cinder.volume_type_access_list(IsA(http.HttpRequest), volume_type.id).AndReturn(type_access) cinder.volume_type_add_project_access(IsA(http.HttpRequest), volume_type.id, u'3') if exception: cinder.volume_type_remove_project_access( IsA(http.HttpRequest), volume_type.id, u'1')\ .AndRaise(exceptions.BadRequest()) else: cinder.volume_type_remove_project_access(IsA(http.HttpRequest), volume_type.id, u'1') self.mox.ReplayAll() url = reverse('horizon:admin:volume_types:edit_access', args=[volume_type.id]) res = self.client.post(url, formData) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL)
def test_delete_volume_type_exception(self): volume_type = self.volume_types.first() formData = {'action': 'volume_types__delete__%s' % volume_type.id} encryption_list = (self.cinder_volume_encryption_types.list()[0], self.cinder_volume_encryption_types.list()[1]) cinder.volume_type_list_with_qos_associations( IsA(http.HttpRequest)).\ AndReturn(self.volume_types.list()) cinder.qos_spec_list(IsA(http.HttpRequest)).\ AndReturn(self.cinder_qos_specs.list()) cinder.volume_encryption_type_list(IsA(http.HttpRequest))\ .AndReturn(encryption_list) cinder.volume_type_delete(IsA(http.HttpRequest), str(volume_type.id))\ .AndRaise(exceptions.BadRequest()) self.mox.ReplayAll() res = self.client.post( reverse('horizon:admin:volumes:volumes_tab'), formData) redirect = reverse('horizon:admin:volumes:volumes_tab') self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, redirect)
def _cleanup_params(attrs, check, **params): args = {} run = False for (key, value) in params.items(): if key == "run": run = value elif key == "cpu": args[key] = float(value) elif key == "memory" or key == "disk": args[key] = int(value) elif key == "interactive" or key == "mounts" or key == "nets" \ or key == "security_groups" or key == "hints"\ or key == "auto_remove" or key == "auto_heal": args[key] = value elif key == "restart_policy": args[key] = utils.check_restart_policy(value) elif key == "environment" or key == "labels": values = {} vals = _helper_commas_value(value) for v in vals: kv = v.split("=", 1) values[kv[0]] = kv[1] args[str(key)] = values elif key == "command": args[key] = shlex.split(value) elif key in attrs: if value is None: value = '' args[str(key)] = str(value) elif check: raise exceptions.BadRequest("Key must be in %s" % ",".join(attrs)) return args, run
def _cleanup_params(attrs, check, **params): args = {} run = False for (key, value) in params.items(): if key == "run": run = value elif key == "cpu": args[key] = float(value) elif key == "memory": args[key] = int(value) elif key == "interactive" or key == "nets" \ or key == "security_groups" or key == "hints": args[key] = value elif key == "restart_policy": args[key] = utils.check_restart_policy(value) elif key == "environment" or key == "labels": values = {} vals = value.split(",") for v in vals: kv = v.split("=", 1) values[kv[0]] = kv[1] args[str(key)] = values elif key in attrs: if value is None: value = '' args[str(key)] = str(value) elif check: LOG.debug('zunclient xxx exception %s xxx' % key) raise exceptions.BadRequest("Key must be in %s" % ",".join(attrs)) return args, run
def _test_edit_volume_type_access(self, exception=False): volume_type = self.cinder_volume_types.list()[2] volume_type.id = u'1' type_access = self.cinder_type_access.list() formData = {'member': [u'3'], 'volume_type_id': volume_type.id} self.mock_tenant_list.return_value = [self.tenants.list(), False] self.mock_volume_type_get.return_value = volume_type self.mock_volume_type_access_list.return_value = type_access self.mock_volume_type_add_project_access.return_value = None if exception: self.mock_volume_type_remove_project_access.side_effect = \ exceptions.BadRequest() else: self.mock_volume_type_remove_project_access.return_value = None url = reverse('horizon:admin:volume_types:edit_access', args=[volume_type.id]) res = self.client.post(url, formData) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.mock_tenant_list.assert_called_once_with(test.IsHttpRequest()) self.mock_volume_type_get.assert_called_once_with( test.IsHttpRequest(), volume_type.id) self.mock_volume_type_access_list.assert_called_once_with( test.IsHttpRequest(), volume_type.id) self.mock_volume_type_add_project_access.assert_called_once_with( test.IsHttpRequest(), volume_type.id, u'3') self.mock_volume_type_remove_project_access.assert_called_once_with( test.IsHttpRequest(), volume_type.id, u'1')
def list(request, object_type=None): try: list = key_manager().list(get_context(request), object_type=object_type, metadata_only=True) except castellan_exception.KeyManagerError as e: raise exceptions.BadRequest("Could not list objects: %s" % e.message) return list
def certificate_create(request, **kwargs): args = {} for (key, value) in kwargs.items(): if key in CERTIFICATE_CREATE_ATTRS: args[key] = value else: raise exceptions.BadRequest("Key must be in %s" % ",".join(CERTIFICATE_CREATE_ATTRS)) return magnumclient(request).certificates.create(**args)
def generate_symmetric_key(request, **kwargs): args = {} for (key, value) in kwargs.items(): if key in GENERATE_ATTRIBUTES: args[str(key)] = value else: raise exceptions.BadRequest("Key must be in %s" % ",".join(GENERATE_ATTRIBUTES)) created_uuid = key_manager().create_key(get_context(request), **args) return created_uuid
def generate_key_pair(request, **kwargs): args = {} for (key, value) in kwargs.items(): if key in GENERATE_ATTRIBUTES: args[str(key)] = value else: raise exceptions.BadRequest("Key must be in %s" % ",".join(GENERATE_ATTRIBUTES)) private_uuid, public_uuid = key_manager().create_key_pair( get_context(request), **args) return "{priv} + {pub}".format(priv=private_uuid, pub=public_uuid)
def UpdateReviewState(project, expertid, from_states, to_state): reviewer = GetReviewerInstanceById( project, expertid, project_expected_states=['start_review'], reviewer_expected_states=[REVIEWER_SELECTED]) if reviewer.review_state in from_states: reviewer.review_state = to_state reviewer.save() else: _input = {'projectid': str(project), 'expertid': expertid} raise exceptions.BadRequest( _('Expert %(expertid)s comments for project with id %(projectid)s can not be changed' ) % _input)
def post(self, request, *args, **kwargs): pattern = re.compile("^[A-Za-z][A-Za-z0-9_-]*$") if not pattern.match(request.POST["prefix_name"]): raise exceptions.BadRequest('Prefix must begin with a ' 'letter and contain only letters, ' 'numbers, _ or -.') self.prefix_name = request.POST["prefix_name"] # set an empty role list for this prefix, to force a # record creation on the back end. config = puppet_config(self.prefix_name, self.tenant_id) config.set_role_list([])
def __init__(self, *args, **kwargs): try: request = args[0] template_string = "" if "template_upload" in kwargs: template_upload = kwargs.pop('template_upload') super(ImportNodegroupTemplateDetailsForm, self).__init__(*args, **kwargs) template_string = template_upload.read() self.fields["template"].initial = template_string else: super(ImportNodegroupTemplateDetailsForm, self).__init__(*args, **kwargs) template_string = self.data["template"] template_json = json.loads(template_string) template_json = template_json["node_group_template"] security_group_list = neutron.security_group_list(request) security_group_choices = \ [(sg.id, sg.name) for sg in security_group_list] self.fields["security_groups"].choices = security_group_choices pools = neutron.floating_ip_pools_list(request) pool_choices = [(pool.id, pool.name) for pool in pools] pool_choices.insert(0, (None, "Do not assign floating IPs")) self.fields["floating_ip_pool"].choices = pool_choices flavors = nova_utils.flavor_list(request) if flavors: self.fields["flavor"].choices = nova_utils.sort_flavor_list( request, flavors) else: self.fields["flavor"].choices = [] version = (template_json.get("hadoop_version", None) or template_json["plugin_version"]) self.fields["image_id"].choices = \ self._populate_image_choices(request, template_json["plugin_name"], version) except (ValueError, KeyError): raise exceptions.BadRequest(_("Could not parse template")) except Exception: exceptions.handle(request)
def test_delete_group_type_exception(self): group_type = self.cinder_group_types.first() formData = {'action': 'group_types__delete__%s' % group_type.id} self.mock_group_type_list.return_value = \ self.cinder_group_types.list() self.mock_group_type_delete.side_effect = exceptions.BadRequest() res = self.client.post(INDEX_URL, formData) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.mock_group_type_list.\ assert_called_once_with(test.IsHttpRequest()) self.mock_group_type_delete.assert_called_once_with( test.IsHttpRequest(), group_type.id)
def secret_update(request, id, **kwargs): args = {} for (key, value) in kwargs.items(): if key in ATTRIBUTES: args[str(key)] = value else: raise exceptions.BadRequest( "Key must be in %s" % ",".join(ATTRIBUTES)) # updated = apiclient(request).secret.update(id, **args) # update dummy response args["uuid"] = id args["updated_at"] = datetime.now().isoformat() updated = StubResponse(args) for k in args: setattr(updated, k, args[k]) STUB_DATA[updated.uuid] = updated return updated
def __init__(self, *args, **kwargs): try: request = args[0] template_string = "" self.next_view = kwargs.pop("next_view") if "template_upload" in kwargs: template_upload = kwargs.pop("template_upload") super(ImportClusterTemplateNameForm, self).__init__(*args, **kwargs) template_string = template_upload.read() self.fields["template_upload"].initial = template_string else: super(ImportClusterTemplateNameForm, self).__init__(*args, **kwargs) except (ValueError, KeyError): raise exceptions.BadRequest(_("Could not parse template")) except Exception: exceptions.handle(request)
def _cleanup_params(attrs, create, **params): args = {} for (key, value) in params.items(): if key in attrs: if value is None: if create: value = '' else: continue args[str(key)] = str(value) elif create: raise exceptions.BadRequest("Key must be in %s" % ",".join(attrs)) if key == "labels": if isinstance(value, str) or isinstance(value, unicode): labels = {} vals = value.split(",") for v in vals: kv = v.split("=", 1) labels[kv[0]] = kv[1] args["labels"] = labels else: args["labels"] = value return args
def test_delete_volume_type_exception(self): volume_type = self.cinder_volume_types.first() formData = {'action': 'volume_types__delete__%s' % volume_type.id} encryption_list = (self.cinder_volume_encryption_types.list()[0], self.cinder_volume_encryption_types.list()[1]) self.mock_volume_type_list_with_qos_associations.return_value = \ self.cinder_volume_types.list() self.mock_qos_spec_list.return_value = self.cinder_qos_specs.list() self.mock_volume_encryption_type_list.return_value = encryption_list self.mock_volume_type_delete.side_effect = exceptions.BadRequest() res = self.client.post(INDEX_URL, formData) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.mock_volume_type_list_with_qos_associations.\ assert_called_once_with(test.IsHttpRequest()) self.mock_qos_spec_list.assert_called_once_with(test.IsHttpRequest()) self.mock_volume_encryption_type_list.assert_called_once_with( test.IsHttpRequest()) self.mock_volume_type_delete.assert_called_once_with( test.IsHttpRequest(), str(volume_type.id))
def __init__(self, *args, **kwargs): try: request = args[0] template_string = "" if "template_upload" in kwargs: template_string = kwargs.pop("template_upload") super(ImportClusterTemplateNodegroupsForm, self).__init__(*args, **kwargs) self.fields["template_upload"].initial = template_string else: super(ImportClusterTemplateNodegroupsForm, self).__init__(*args, **kwargs) template_string = self.data["template_upload"] template_json = json.loads(template_string) template_json = template_json["cluster_template"] req = request.GET.copy() req.update(request.POST) plugin = template_json["plugin_name"] version = (template_json.get("hadoop_version", None) or template_json["plugin_version"]) if not plugin or not version: self.templates = saharaclient.nodegroup_template_find(request) else: self.templates = saharaclient.nodegroup_template_find( request, plugin_name=plugin, hadoop_version=version) deletable = req.get("deletable", dict()) if "forms_ids" in req: self.groups = [] for id in json.loads(req["forms_ids"]): group_name = "group_name_" + str(id) template_id = "template_id_" + str(id) count = "count_" + str(id) serialized = "serialized_" + str(id) self.groups.append({ "name": req[group_name], "template_id": req[template_id], "count": req[count], "id": id, "deletable": deletable.get(req[group_name], "true"), "serialized": req[serialized] }) whelpers.build_node_group_fields(self, group_name, template_id, count, serialized) except (ValueError, KeyError): raise exceptions.BadRequest(_("Could not parse template")) except Exception: exceptions.handle(request)
def volume_type_delete(request, volume_type_id): try: return cinderclient(request).volume_types.delete(volume_type_id) except cinder_exception.BadRequest: raise exceptions.BadRequest(_( "This volume type is used by one or more volumes."))
# enable following after client product implemented. # c = {{cookiecutter.api_module}}_client.Client( # username=request.user.username, # project_id=request.user.tenant_id, # input_auth_token=request.user.token.id, # api_url=api_url) return c def {{cookiecutter.panel}}_create(request, **kwargs): args = {} for (key, value) in kwargs.items(): if key in ATTRIBUTES: args[str(key)] = value else: raise exceptions.BadRequest( "Key must be in %s" % ",".join(ATTRIBUTES)) # created = apiclient(request).{{cookiecutter.panel}}s.create(**args) # create dummy response args["uuid"] = uuid.uuid1().hex args["created_at"] = datetime.now().isoformat() created = StubResponse(args) for k in args: setattr(created, k, args[k]) STUB_DATA[created.uuid] = created return created def {{cookiecutter.panel}}_update(request, id, **kwargs): args = {}