def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] fields = { "stack_name": data.get("stack_name"), "timeout_mins": data.get("timeout_mins"), "disable_rollback": not (data.get("enable_rollback")), "parameters": dict(params_list), "password": data.get("password"), } if data.get("template_data"): fields["template"] = data.get("template_data") else: fields["template_url"] = data.get("template_url") if data.get("environment_data"): fields["environment"] = data.get("environment_data") try: api.heat.stack_create(self.request, **fields) messages.success(request, _("Stack creation started.")) return True except Exception: exceptions.handle(request)
def handle(self, request, data): domain = api.keystone.get_default_domain(self.request) try: LOG.info('Creating user with name "%s"' % data['name']) if "email" in data: data['email'] = data['email'] or None new_user = api.keystone.user_create(request, name=data['name'], email=data['email'], password=data['password'], project=data['project'], enabled=True, domain=domain.id) messages.success(request, _('User "%s" was successfully created.') % data['name']) if data['project'] and data['role_id']: roles = api.keystone.roles_for_user(request, new_user.id, data['project']) or [] assigned = [role for role in roles if role.id == str( data['role_id'])] if not assigned: try: api.keystone.add_tenant_user_role(request, data['project'], new_user.id, data['role_id']) except Exception: exceptions.handle(request, _('Unable to add user ' 'to primary project.')) return new_user except Exception: exceptions.handle(request, _('Unable to create user.'))
def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] fields = { 'stack_name': data.get('stack_name'), 'timeout_mins': data.get('timeout_mins'), 'disable_rollback': not(data.get('enable_rollback')), 'parameters': dict(params_list), 'password': data.get('password') } if data.get('template_data'): fields['template'] = data.get('template_data') else: fields['template_url'] = data.get('template_url') if data.get('environment_data'): fields['environment'] = data.get('environment_data') try: api.heat.stack_create(self.request, **fields) messages.success(request, _("Stack creation started.")) return True except Exception: exceptions.handle(request)
def handle(self, request, data): image_id = data['image_id'] error_updating = _('Unable to update image "%s".') if data['disk_format'] in ['aki', 'ari', 'ami']: container_format = data['disk_format'] else: container_format = 'bare' meta = {'is_public': data['public'], 'protected': data['protected'], 'disk_format': data['disk_format'], 'container_format': container_format, 'name': data['name'], 'properties': {'description': data['description']}} if data['kernel']: meta['properties']['kernel_id'] = data['kernel'] if data['ramdisk']: meta['properties']['ramdisk_id'] = data['ramdisk'] if data['architecture']: meta['properties']['architecture'] = data['architecture'] # Ensure we do not delete properties that have already been # set on an image. meta['purge_props'] = False try: image = api.glance.image_update(request, image_id, **meta) messages.success(request, _('Image was successfully updated.')) return image except Exception: exceptions.handle(request, error_updating % image_id)
def handle(self, request, data, **kwargs): try: if 'rule_to_delete' in request.POST: rulemanager.remove_rules(request, [request.POST['rule_to_delete']], router_id=data['router_id']) except Exception: exceptions.handle(request, _('Unable to delete router rule.')) try: if 'nexthops' not in data: data['nexthops'] = '' if data['source'] == '0.0.0.0/0': data['source'] = 'any' if data['destination'] == '0.0.0.0/0': data['destination'] = 'any' rule = {'action': data['action'], 'source': data['source'], 'destination': data['destination'], 'nexthops': data['nexthops'].split(',')} rulemanager.add_rule(request, router_id=data['router_id'], newrule=rule) msg = _('Router rule added') LOG.debug(msg) messages.success(request, msg) return True except Exception as e: msg = _('Failed to add router rule %s') % e LOG.info(msg) messages.error(request, msg) redirect = reverse(self.failure_url, args=[data['router_id']]) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] stack_id = data.get("stack_id") fields = { "stack_name": data.get("stack_name"), "timeout_mins": data.get("timeout_mins"), "disable_rollback": not (data.get("enable_rollback")), "parameters": dict(params_list), "password": data.get("password"), } # if the user went directly to this form, resubmit the existing # template data. otherwise, submit what they had from the first form if data.get("template_data"): fields["template"] = data.get("template_data") elif data.get("template_url"): fields["template_url"] = data.get("template_url") elif data.get("parameters"): fields["template"] = data.get("parameters") try: api.heat.stack_update(self.request, stack_id=stack_id, **fields) messages.success(request, _("Stack update started.")) return True except Exception: exceptions.handle(request)
def handle(self, request, data): vol_type_id = self.initial['type_id'] new_qos_spec_id = data['qos_spec_choice'] # Update QOS Spec association information try: # NOTE - volume types can only be associated with # ONE QOS Spec at a time # first we need to un-associate the current QOS Spec, if it exists cur_qos_spec_id = self.initial['cur_qos_spec_id'] if cur_qos_spec_id: qos_spec = cinder.qos_spec_get(request, cur_qos_spec_id) cinder.qos_spec_disassociate(request, qos_spec, vol_type_id) # now associate with new QOS Spec, if user wants one associated if new_qos_spec_id != '-1': qos_spec = cinder.qos_spec_get(request, new_qos_spec_id) cinder.qos_spec_associate(request, qos_spec, vol_type_id) messages.success(request, _('Successfully updated QoS Spec association.')) return True except Exception: redirect = reverse("horizon:admin:volumes:index") exceptions.handle(request, _('Error updating QoS Spec association.'), redirect=redirect)
def handle(self, request, data): try: params = {'name': data['name'], 'tenant_id': data['tenant_id'], 'admin_state_up': (data['admin_state'] == 'True'), 'shared': data['shared'], 'router:external': data['external']} if api.neutron.is_port_profiles_supported(): params['net_profile_id'] = data['net_profile_id'] if api.neutron.is_extension_supported(request, 'provider'): network_type = data['network_type'] params['provider:network_type'] = network_type if network_type in ['flat', 'vlan']: params['provider:physical_network'] = ( data['physical_network']) if network_type in ['vlan', 'gre', 'vxlan']: params['provider:segmentation_id'] = ( data['segmentation_id']) network = api.neutron.network_create(request, **params) msg = _('Network %s was successfully created.') % data['name'] LOG.debug(msg) messages.success(request, msg) return network except Exception: redirect = reverse('horizon:admin:networks:index') msg = _('Failed to create network %s') % data['name'] exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): app_id = self.initial.get('app_id') LOG.debug('Updating package {0} with {1}'.format(app_id, data)) try: data['tags'] = [t.strip() for t in data['tags'].split(',')] result = api.muranoclient(request).packages.update(app_id, data) messages.success(request, _('Package modified.')) return result except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) exceptions.handle( request, msg, redirect=reverse('horizon:murano:packages:index')) except Exception as original_e: reason = '' exc_info = sys.exc_info() if hasattr(original_e, 'details'): try: error = json.loads(original_e.details).get('error') if error: reason = error.get('message') except ValueError: # Let horizon operate with original exception raise exc_info[0], exc_info[1], exc_info[2] msg = _('Failed to upload the package. {0}').format(reason) LOG.exception(msg) redirect = reverse('horizon:murano:packages:index') exceptions.handle(request, _(msg), redirect=redirect)
def handle(self, request, data): data['input'] = convert_empty_string_to_none(data['input']) data['params'] = convert_empty_string_to_none(data['params']) data['deadline'] = convert_empty_string_to_none(data['deadline']) data['job_duration'] = convert_empty_string_to_none( data['job_duration'] ) try: api.delay_tolerant_workload_create( request, data['name'], data['workflow_id'], data['input'], data['params'], data['job_duration'], data['deadline'], ) msg = _('Successfully created Delay Tolerant Workload.') messages.success(request, msg) return True finally: pass
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 settings.HORIZON_IMAGES_ALLOW_UPLOAD and data['image_file']: 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: exceptions.handle(request, _('Unable to create new image.'))
def handle(self, request, data): try: # We must specify tenant_id of the network which a subnet is # created for if admin user does not belong to the tenant. network = api.neutron.network_get(request, data['network_id']) data['tenant_id'] = network.tenant_id data['admin_state_up'] = (data['admin_state'] == 'True') del data['network_name'] del data['admin_state'] if 'mac_state' in data: data['mac_learning_enabled'] = data['mac_state'] del data['mac_state'] port = api.neutron.port_create(request, **data) msg = _('Port %s was successfully created.') % port['id'] LOG.debug(msg) messages.success(request, msg) return port except Exception: msg = _('Failed to create a port for network %s') \ % data['network_id'] LOG.info(msg) redirect = reverse('horizon:admin:networks:detail', args=(data['network_id'],)) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): id = self.initial['id'] old_metadata = self.initial['metadata'] try: new_metadata = json.loads(self.data['metadata']) metadata = dict( (item['key'], str(item['value'])) for item in new_metadata ) for key in old_metadata: if key not in metadata: metadata[key] = None api.nova.aggregate_set_metadata(request, id, metadata) message = _('Metadata successfully updated.') messages.success(request, message) except Exception: msg = _('Unable to update the aggregate metadata.') exceptions.handle(request, msg) return False return True
def handle(self, request, data): try: rc.poll() messages.success(request, _('Routers were polled')) except Exception: exceptions.handle(request, _('Unable to poll routers.')) return True
def handle(self, request, data): domain = api.daolicloud.get_default_domain(self.request) try: desc = '%s tenant' % data['name'] LOG.info('Creating user with name "%s"' % data['name']) new_tenant = api.daolicloud.tenant_create(request, name=data['name'], description=desc, enabled=True, domain=domain.id) new_user = api.daolicloud.user_create(request, name=data['name'], email=data['email'], password=data['password'], project=new_tenant.id, enabled=True, domain=domain.id) messages.success(request, _('User "%s" was successfully created.') % data['name']) return new_user except exceptions.Conflict: msg = _('User name "%s" is already used.') % data['name'] exceptions.handle(request, msg, redirect=reverse('message')) except Exception: exceptions.handle(request, _('Unable to create user.'), redirect=reverse('message'))
def handle(self, request, data): id = self.initial['id'] old_metadata = self.initial['metadata'] try: new_metadata = json.loads(self.data['metadata']) metadata = dict( (item['key'], str(item['value'])) for item in new_metadata ) remove_props = [key for key in old_metadata if key not in metadata] api.glance.image_update_properties(request, id, remove_props, **metadata) message = _('Metadata successfully updated.') messages.success(request, message) except Exception: exceptions.handle(request, _('Unable to update the image metadata.')) return False return True
def handle(self, request, data): # TODO deliver a cluster id in data data['cluster_id'] = 1 try: LOG.error("CEPH_LOG in ADD ip, %s" % str(data)) appnodes = vsm_api.appnode_list(request) for appnode in appnodes: if data['ip'] == appnode.ip: messages.error(request, "duplicate ip address") return False body = { 'appnodes': [data['ip'],] } ips = [data['ip'],] LOG.error("CEPH_LOG in handle body %s" % str(body)) ret = vsm_api.add_appnodes(request, ips) messages.success(request, _('Successfully add ip: %s') % data['ip']) return ret except: redirect = reverse("horizon:vsm:zonemgmt:index") exceptions.handle(request, _('Unable to create zone.'), redirect=redirect)
def _create_reset_password_token(self, request, email): LOG.info('Creating reset token for %s.', email) try: user = fiware_api.keystone.check_email(request, email) if not user.enabled: msg = ('The email address you have specified is registered but not ' 'activated. Please check your email for the activation link ' 'or request a new one. If your problem ' 'persits, please contact [email protected]') messages.error(request, msg) return False reset_password_token = fiware_api.keystone.get_reset_token(request, user) token = reset_password_token.id user = reset_password_token.user email_utils.send_reset_email(email, token, user) messages.success(request, ('Reset email send to %s') % email) return True except ks_exceptions.NotFound: LOG.debug('email address %s is not registered', email) msg = ('Sorry. You have specified an email address that is not ' 'registered to any of our user accounts. If your problem ' 'persits, please contact: [email protected]') messages.error(request, msg) except Exception as e: msg = ('An error occurred, try again later.') messages.error(request, msg) return False
def _resend_confirmation_email(self, request, email): try: user = fiware_api.keystone.check_email(request, email) if user.enabled: msg = ('Email was already confirmed, please try signing in') LOG.debug('email address %s was already confirmed', email) messages.error(request, msg) return False activation_key = fiware_api.keystone.new_activation_key(request, user) email_utils.send_activation_email(user, activation_key.id) msg = ('Resended confirmation instructions to %s') %email messages.success(request, msg) return True except ks_exceptions.NotFound: LOG.debug('email address %s is not registered', email) msg = ('Sorry. You have specified an email address that is not ' 'registered to any our our user accounts. If your problem ' 'persits, please contact: [email protected]') messages.error(request, msg) except Exception: msg = ('An error occurred, try again later.') messages.error(request, msg) return False
def handle(self, request, data): try: vnf_name = data['vnf_name'] vnfd_id = data['vnfd_id'] vim_id = data['vim_id'] region_name = data['region_name'] param_val = data['param_values'] config_val = data['config_values'] vnf_arg = {'vnf': {'vnfd_id': vnfd_id, 'name': vnf_name, 'vim_id': vim_id}} if region_name: vnf_arg.setdefault('placement_attr', {})[ region_name] = region_name vnf_attr = vnf_arg['vnf'].setdefault('attributes', {}) if param_val: vnf_attr['param_values'] = param_val if config_val: vnf_attr['config'] = config_val api.tacker.create_vnf(request, vnf_arg) messages.success(request, _('VNF %s create operation initiated.') % vnf_name) return True except Exception as e: exceptions.handle(request, _('Failed to create VNF: %s') % e.message)
def handle(self, request, data): if data: with api.handled_exceptions(self.request): category = api.muranoclient(self.request).categories.add(data) messages.success(request, _('Category {0} created.').format(data['name'])) return category
def handle(self, request, data, **kwargs): try: if "rule_to_delete" in request.POST: rulemanager.remove_rules(request, [request.POST["rule_to_delete"]], router_id=data["router_id"]) except Exception: exceptions.handle(request, _("Unable to delete router rule.")) try: if "nexthops" not in data: data["nexthops"] = "" if data["source"] == "0.0.0.0/0": data["source"] = "any" if data["destination"] == "0.0.0.0/0": data["destination"] = "any" rule = { "action": data["action"], "source": data["source"], "destination": data["destination"], "nexthops": data["nexthops"].split(","), } rulemanager.add_rule(request, router_id=data["router_id"], newrule=rule) msg = _("Router rule added") LOG.debug(msg) messages.success(request, msg) return True except Exception as e: msg = _("Failed to add router rule %s") % e LOG.info(msg) messages.error(request, msg) redirect = reverse(self.failure_url, args=[data["router_id"]]) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): domain = api.keystone.get_default_domain(self.request) try: LOG.info('Creating user with name "%s"' % data['name']) new_user = api.keystone.user_create(request, name=data['name'], email=data['email'], password=data['password'], project=data['project'], enabled=True, domain=domain.id) messages.success(request, _('User "%s" was successfully created.') % data['name']) if data['role_id']: try: api.keystone.add_tenant_user_role(request, data['project'], new_user.id, data['role_id']) except Exception: exceptions.handle(request, _('Unable to add user ' 'to primary project.')) return new_user except Exception: exceptions.handle(request, _('Unable to create user.'))
def handle(self, table, request, obj_ids): if not table.data: msg = _("Cannot grow cluster. No instances specified.") messages.info(request, msg) return shortcuts.redirect(request.build_absolute_uri()) datum_display_objs = [] for instance in table.data: msg = _("[flavor=%(flavor)s, volume=%(volume)s, name=%(name)s, " "type=%(type)s, related_to=%(related_to)s]") params = {"flavor": instance.flavor_id, "volume": instance.volume, "name": instance.name, "type": instance.type, "related_to": instance.related_to} datum_display_objs.append(msg % params) display_str = functions.lazy_join(", ", datum_display_objs) cluster_id = table.kwargs['cluster_id'] try: api.trove.cluster_grow(request, cluster_id, table.data) LOG.info('%s: "%s"' % (_("Grow Cluster"), display_str)) msg = _('Scheduled growing of cluster.') messages.success(request, msg) except Exception as ex: LOG.error('Action %s Failed for %s' % (_("grow cluster"), display_str), ex) msg = _('Unable to grow cluster: %s') messages.error(request, msg % ex.message) finally: cluster_manager.delete(cluster_id) return shortcuts.redirect(urlresolvers.reverse( "horizon:project:database_clusters:index"))
def handle(self, request, data): try: body = { 'pool': { 'name': data['name'], 'storageGroupId': data['storage_group'], 'replicationFactor': data['replication_factor'], 'tag': data['tag'], 'clusterId': '0', 'createdBy': 'VSM' } } rsp, ret = vsm_api.create_storage_pool(request,body=body) res = str(ret['message']).strip( ) if res.startswith('pool') and res.endswith('created'): messages.success(request, _('Successfully created storage pool: %s') % data['name']) else: messages.error(request, _('Because %s, failed to create storage pool') % ret['message']) return ret except: redirect = reverse("horizon:vsm:poolsmanagement:index") exceptions.handle(request, _('Unable to create storage pool.'), redirect=redirect)
def handle(self, request, data): response = shortcuts.redirect(request.build_absolute_uri()) # Language lang_code = data['language'] if lang_code and translation.check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, expires=_one_year()) # Timezone request.session['django_timezone'] = pytz.timezone( data['timezone']).zone response.set_cookie('django_timezone', data['timezone'], expires=_one_year()) request.session['horizon_pagesize'] = data['pagesize'] response.set_cookie('horizon_pagesize', data['pagesize'], expires=_one_year()) request.session['instance_log_length'] = data['instance_log_length'] response.set_cookie('instance_log_length', data['instance_log_length'], expires=_one_year()) with translation.override(lang_code): messages.success(request, encoding.force_text(_("Settings saved."))) return response
def handle(self, request, context): context['admin_state_up'] = (context['admin_state_up'] == 'True') if context['session_persistence']: stype = context['session_persistence'] if stype == 'APP_COOKIE': cookie = context['cookie_name'] context['session_persistence'] = {'type': stype, 'cookie_name': cookie} else: context['session_persistence'] = {'type': stype} else: context['session_persistence'] = {} try: data = {'vip': {'name': context['name'], 'description': context['description'], 'pool_id': context['pool_id'], 'session_persistence': context['session_persistence'], 'connection_limit': context['connection_limit'], 'admin_state_up': context['admin_state_up'], }} vip = api.lbaas.vip_update(request, context['vip_id'], **data) msg = _('VIP %s was successfully updated.') % context['name'] LOG.debug(msg) messages.success(request, msg) return vip except Exception: msg = _('Failed to update VIP %s') % context['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): port_id = self.initial['port_id'] try: LOG.debug('params = %s', data) extension_kwargs = {} if 'binding__vnic_type' in data: extension_kwargs['binding__vnic_type'] = \ data['binding__vnic_type'] if 'mac_state' in data: extension_kwargs['mac_learning_enabled'] = data['mac_state'] if 'port_security_enabled' in data: extension_kwargs['port_security_enabled'] = \ data['port_security_enabled'] port = api.neutron.port_update(request, port_id, name=data['name'], admin_state_up=data['admin_state'], **extension_kwargs) msg = _('Port %s was successfully updated.') % port_id messages.success(request, msg) return port except Exception as e: LOG.info('Failed to update port %(id)s: %(exc)s', {'id': port_id, 'exc': e}) msg = _('Failed to update port %s') % port_id redirect = reverse(self.failure_url, args=[self.initial['network_id']]) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] stack_id = data.get('stack_id') fields = { 'stack_name': data.get('stack_name'), 'timeout_mins': data.get('timeout_mins'), 'disable_rollback': not(data.get('enable_rollback')), 'parameters': dict(params_list), 'password': data.get('password') } # if the user went directly to this form, resubmit the existing # template data. otherwise, submit what they had from the first form if data.get('template_data'): fields['template'] = data.get('template_data') elif data.get('template_url'): fields['template_url'] = data.get('template_url') elif data.get('parameters'): fields['template'] = data.get('parameters') try: api.heat.stack_update(self.request, stack_id=stack_id, **fields) messages.success(request, _("Stack update started.")) return True except Exception: exceptions.handle(request)
def single(self, table, request, instance_id): try: # target_id is port_id for Neutron and instance_id for Nova Network # (Neutron API wrapper returns a 'portid_fixedip' string) targets = api.network.floating_ip_target_list_by_instance( request, instance_id) target_ids = [t.split('_')[0] for t in targets] fips = [fip for fip in api.network.tenant_floating_ip_list(request) if fip.port_id in target_ids] # Removing multiple floating IPs at once doesn't work, so this pops # off the first one. if fips: fip = fips.pop() api.network.floating_ip_disassociate(request, fip.id, fip.port_id) messages.success(request, _("Successfully disassociated " "floating IP: %s") % fip.ip) else: messages.info(request, _("No floating IPs to disassociate.")) except Exception: exceptions.handle(request, _("Unable to disassociate floating IP.")) return shortcuts.redirect("horizon:project:instances:index")
def handle(self, request, context): policy_target_id = self.initial['policy_target_id'] url = reverse("horizon:project:policytargets:policy_targetdetails", kwargs={'policy_target_id': policy_target_id}) try: policy_target = client.policy_target_get(request, policy_target_id) old_policy_rule_sets = policy_target.get( "consumed_policy_rule_sets") for policy_rule_set in context['policy_rule_set']: old_policy_rule_sets.remove(policy_rule_set) consumed = dict([(item, 'string') for item in old_policy_rule_sets]) client.policy_target_update( request, policy_target_id, consumed_policy_rule_sets=consumed) msg = _('Policy Rule Set removed successfully!') messages.success(request, msg) LOG.debug(msg) return http.HttpResponseRedirect(url) except Exception: msg = _('Failed to remove policy_rule_set!') redirect = url LOG.error(msg) exceptions.handle(request, msg, redirect=redirect)
def single(self, table, request, instance_id): try: fips = [ fip for fip in api.network.tenant_floating_ip_list(request) if fip.port_id == instance_id ] # Removing multiple floating IPs at once doesn't work, so this pops # off the first one. if fips: fip = fips.pop() api.network.floating_ip_disassociate(request, fip.id, instance_id) api.network.tenant_floating_ip_release(request, fip.id) messages.success( request, _("Successfully disassociated " "floating IP: %s") % fip.ip) else: messages.info(request, _("No floating IPs to disassociate.")) except: exceptions.handle(request, _("Unable to disassociate floating IP.")) return shortcuts.redirect("horizon:project:instances:index")
def handle(self, request, data): try: send_data = {'name': data['name']} if data['description']: send_data['description'] = data['description'] share_net_id = data.get('neutron_net_id', data.get('nova_net_id')) share_net_id = share_net_id.strip() if self.neutron_enabled and share_net_id: send_data['neutron_net_id'] = share_net_id subnet_key = 'subnet-choices-%s' % share_net_id if subnet_key in data: send_data['neutron_subnet_id'] = data[subnet_key] elif not self.neutron_enabled and share_net_id: send_data['nova_net_id'] = data['nova_net_id'] share_network = manila.share_network_create(request, **send_data) messages.success( request, _('Successfully created share' ' network: %s') % send_data['name']) return share_network except Exception: exceptions.handle(request, _('Unable to create share network.')) return False
def handle(self, request, data): try: LOG.debug('request = %(req)s, params = %(params)s', { 'req': request, 'params': data }) params = { 'name': data['name'], 'segment_range': data['segment_range'], 'multicast_ip_range': data['multicast_ip_range'] } profile = api.neutron.profile_update(request, data['profile_id'], **params) msg = _('Network Profile %s ' 'was successfully updated.') % data['name'] LOG.debug(msg) messages.success(request, msg) return profile except Exception: msg = _('Failed to update ' 'network profile (%s).') % data['name'] redirect = reverse('horizon:router:nexus1000v:index') exceptions.handle(request, msg, redirect=redirect) return False
def handle(self, request, context): try: data = { 'health_monitor': { 'delay': context['delay'], 'timeout': context['timeout'], 'max_retries': context['max_retries'], 'admin_state_up': context['admin_state_up'] } } monitor = api.lbaas.pool_health_monitor_update( request, context['monitor_id'], **data) msg = _('Health monitor %s was successfully updated.')\ % context['monitor_id'] LOG.debug(msg) messages.success(request, msg) return monitor except Exception: msg = _('Failed to update health monitor %s')\ % context['monitor_id'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): try: LOG.debug('request = %(req)s, params = %(params)s', {'req': request, 'params': data}) profile = api.neutron.profile_modify(request, data['profile_id'], name=data['name'], segment_type= data['segment_type'], segment_range= data['segment_range'], physical_network= data['physical_network']) msg = _('Network Profile %s ' 'was successfully updated.') % data['profile_id'] LOG.debug(msg) messages.success(request, msg) return profile except Exception: LOG.error('Failed to update network profile (%s).', data['profile_id']) redirect = reverse('horizon:router:nexus1000v:index') exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): try: user = fiware_api.keystone.user_get(request, data['userID']) api.keystone.user_update( request, user.id, username=data['username'], website=data['website'], description=data['description'], # city=data['city'], password='') # NOTE(garcianavalon) No need for keeping this name updated # anymore # api.keystone.tenant_update(request, # user.default_project_id, # name=data['username']) LOG.debug('User {0} updated'.format(data['userID'])) messages.success(request, ('User updated successfully')) except Exception: messages.error('An error ocurred, try again later') return shortcuts.redirect('horizon:idm:users:detail', data['userID'])
def handle(self, request, data): try: params = {'name': data['name']} if (self.dvr_allowed and data['mode'] != 'server_default'): params['distributed'] = (data['mode'] == 'distributed') if (self.ha_allowed and data['ha'] != 'server_default'): params['ha'] = (data['ha'] == 'enabled') router = api.neutron.router_create(request, **params) operate_log(request.user.username, request.user.roles, data["name"] + " router create") message = _('Router %s was successfully created.') % data['name'] messages.success(request, message) return router except Exception as exc: if exc.status_code == 409: msg = _('Quota exceeded for resource router.') else: msg = _('Failed to create router "%s".') % data['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) return False
def handle(self, request, data): cpuProfileName = data['profilename'] try: cpuProfile = sysinv.host_cpuprofile_create(request, **data) msg = _( 'Cpu Profile "%s" was successfully created.') % cpuProfileName LOG.debug(msg) messages.success(request, msg) return cpuProfile except exc.ClientException as ce: # Display REST API error message on UI messages.error(request, ce) LOG.error(ce) # Redirect to failure pg redirect = reverse(self.failure_url, args=[data['host_id']]) return shortcuts.redirect(redirect) except Exception: msg = _('Failed to create cpu profile "%s".') % cpuProfileName LOG.info(msg) redirect = reverse(self.failure_url, args=[data['host_id']]) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): user = data.pop('id') # Throw away the password confirmation, we're done with it. data.pop('confirm_password', None) data.pop('domain_id') data.pop('domain_name') try: if "email" in data: data['email'] = data['email'] or None response = api.keystone.user_update(request, user, **data) messages.success(request, _('User has been updated successfully.')) except Exception: response = exceptions.handle(request, ignore=True) messages.error(request, _('Unable to update the user.')) if isinstance(response, http.HttpResponse): return response else: return True
def handle(self, request, context): try: data = { 'vpnservice': { 'name': context['name'], 'description': context['description'], 'admin_state_up': context['admin_state_up'], } } vpnservice = api_vpn.vpnservice_update( request, self.initial['vpnservice_id'], **data) msg = (_('VPN service %s was successfully updated.') % context['name']) messages.success(request, msg) return vpnservice except Exception as e: LOG.info('Failed to update VPN service %(id)s: %(exc)s', { 'id': self.initial['vpnservice_id'], 'exc': e }) msg = _('Failed to update VPN service %s') % context['name'] redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): sec_service_id = self.initial['sec_service_id'] try: manila.security_service_update( request, sec_service_id, dns_ip=data['dns_ip'], ou=data['ou'], server=data['server'], domain=data['domain'], password=data.get('password') or None, user=data['user'], name=data['name'], description=data['description']) message = _('Successfully updated security service ' '"%s"') % data['name'] messages.success(request, message) return True except Exception: redirect = reverse("horizon:project:security_services:index") exceptions.handle(request, _('Unable to update security service.'), redirect=redirect)
def post(self, request, *args, **kwargs): obj_ids = request.POST.getlist('object_ids') action = request.POST['action'] m = re.search('.delete([a-z]+)', action).group(1) if obj_ids == []: obj_ids.append(re.search('([0-9a-z-]+)$', action).group(1)) if m in self.delete_actions: delete_action = self.delete_actions[m] for obj_id in obj_ids: success_msg = "Deleted {0} {1}".format(delete_action[NOUN], obj_id) failure_msg = "Unable to delete {0} {1}".format( delete_action[NOUN], obj_id) try: delete_action[ACTION](request, obj_id) messages.success(request, success_msg) except Exception as ex: exceptions.handle(request, failure_msg) LOG.exception(ex) return self.get(request, *args, **kwargs)
def handle(self, request, data): sg_id = self.initial['share_group_id'] try: manila.share_group_reset_state(request, sg_id, data["status"]) message = _( "Reseting share group ('%(id)s') status from '%(from)s' " "to '%(to)s'.") % { "id": (self.initial['share_group_name'] or self.initial['share_group_id']), "from": self.initial['share_group_status'], "to": data["status"] } messages.success(request, message) return True except Exception: redirect = reverse("horizon:admin:share_groups:index") exceptions.handle( request, _("Unable to reset status of share group '%s'.") % sg_id, redirect=redirect) return False
def handle(self, request, data): try: data_bytes = data.get('object_bytes') data_uuid = client.import_object( request, data=data_bytes, name=data['name'], object_type=opaque_data.OpaqueData) if data['name']: data_identifier = data['name'] else: data_identifier = data_uuid messages.success( request, _('Successfully imported object: %s') % data_identifier) return data_uuid except Exception as e: msg = _('Unable to import object: %s') messages.error(msg % e) exceptions.handle(request, ignore=True) self.api_error(_('Unable to import object.')) return False
def handle(self, request, context): policy_id = self.initial['policy_id'] policy_name_or_id = self.initial['name'] or policy_id try: insert_rule_id = context['firewall_rule_id'] insert_rule = api.fwaas.rule_get(request, insert_rule_id) body = {'firewall_rule_id': insert_rule_id, 'insert_before': context['insert_before'], 'insert_after': context['insert_after']} policy = api.fwaas.policy_insert_rule(request, policy_id, **body) msg = _('Rule %(rule)s was successfully inserted to policy ' '%(policy)s.') % { 'rule': insert_rule.name or insert_rule.id, 'policy': policy_name_or_id} LOG.debug(msg) messages.success(request, msg) return policy except Exception as e: msg = _('Failed to insert rule to policy %(name)s: %(reason)s') % { 'name': policy_id, 'reason': e} LOG.error(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, context): context['admin_state_up'] = (context['admin_state_up'] == 'True') try: data = { 'vpnservice': { 'name': context['name'], 'description': context['description'], 'admin_state_up': context['admin_state_up'], } } vpnservice = api.vpn.vpnservice_update(request, context['vpnservice_id'], **data) msg = (_('VPN Service %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) return vpnservice except Exception as e: msg = _('Failed to update VPN Service %s') % context['name'] LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, context): authUrl = "http://*****:*****@127.0.0.1:61209" #server = xmlrpclib.ServerProxy(authUrl) context_computing_nodes = context['computing_nodes'] context_detection = context['detection'] node_list = [] detection_list = [] for node in context_computing_nodes: node_list.append(node) cluster_id = self.get_cluster_id(self.get_absolute_url()) for detection in context_detection: detection_list.append(detection) result = server.add_node(cluster_id, node_list, detection_list) self.success_url = urlresolvers.reverse(self.success_url, args=[cluster_id]) if result["code"] == 'failed': # error self.failure_message = result["message"] messages.error(request, result["message"]) return False self.success_message = _('Add new Computing Node %s to HA Cluster.' % (",".join(node_list))) messages.success(request, self.success_message) return True
def handle(self, request, data): try: params = { 'admin_state_up': data['admin_state'], 'name': data['name'] } if self.dvr_allowed: params['distributed'] = (data['mode'] == 'distributed') if self.ha_allowed: params['ha'] = data['ha'] router = api.neutron.router_update(request, self.initial['router_id'], **params) msg = _('Router %s was successfully updated.') % data['name'] messages.success(request, msg) return router except Exception as exc: LOG.info('Failed to update router %(id)s: %(exc)s', { 'id': self.initial['router_id'], 'exc': exc }) msg = _('Failed to update router %s') % data['name'] exceptions.handle(request, msg, redirect=self.redirect_url)
def handle(self, request, data): authUrl = "http://" + config.get("rpc", "rpc_username") + ":" + config.get("rpc", "rpc_password") + "@127.0.0.1:" + config.get( "rpc", "rpc_bind_port") server = xmlrpclib.ServerProxy(authUrl) err_msg = _('Unable to remove protection of HA instance: %s ' % data['name']) if data['protection'] == 'False': cluster_id = self.get_cluster_by_instance(server, data['instance_id']) result = server.deleteInstance(cluster_id, data['instance_id']) if result["code"] == 'failed': err_msg = result["message"] messages.error(request, err_msg) return False try: instance = api.nova.server_get(self.request, data['instance_id']) except Exception: redirect = reverse("horizon:haProject:ha_instances:index") msg = _('Unable to retrieve instance details.') exceptions.handle(self.request, msg, redirect=redirect) return False success_message = _('Deleted Instance:%s from HA Cluster.' % instance.name) messages.success(request, success_message) return True
def handle(self, request, data): id = self.initial['id'] old_metadata = self.initial['metadata'] try: new_metadata = json.loads(self.data['metadata']) metadata = dict( (item['key'], str(item['value'])) for item in new_metadata) for key in old_metadata: if key not in metadata: metadata[key] = None api.nova.aggregate_set_metadata(request, id, metadata) message = _('Metadata successfully updated.') messages.success(request, message) except Exception: msg = _('Unable to update the aggregate metadata.') exceptions.handle(request, msg) return False return True
def handle(self, request, data): id = data.pop('id') name = data.pop('name') project = data.pop('project') balance = data.pop('balance') try: billing_client = chakra.AccountBilling() body = { "balance": float(balance), "ref_resource": project, "name": name } accounts, resultStatus = billing_client.update_accounts(body, id) if resultStatus != 500: messages.success(request, _('Account has been updated successfully.')) else: messages.error(request, _('Unable to update the account.')) except Exception: messages.error(request, _('Unable to update the account.')) return True
def handle(self, request, data): instance_id = data['instance_id'] try: net_id = port_id = fixed_ip = None if data['specification_method'] == 'port': port_id = data.get('port') else: net_id = data.get('network') if data.get('fixed_ip'): fixed_ip = data.get('fixed_ip') api.nova.interface_attach(request, instance_id, net_id=net_id, fixed_ip=fixed_ip, port_id=port_id) msg = _('Attaching interface for instance %s.') % instance_id messages.success(request, msg) except Exception: redirect = reverse('horizon:project:instances:index') exceptions.handle(request, _("Unable to attach interface."), redirect=redirect) return True
def handle(self, request, data): try: params = { 'name': data['name'], 'type': data['type'], 'description': data['description'], 'mtu': data['mtu'], 'vlan_transparent': data['vlan_transparent'] } network = api.neutron.provider_network_create(request, **params) msg = (_('Provider network %s was successfully created.') % data['name']) LOG.debug(msg) messages.success(request, msg) return network except neutron_exceptions.NeutronClientException as e: redirect = reverse('horizon:admin:providernets:index') exceptions.handle(request, e.message, redirect=redirect) except Exception: redirect = reverse('horizon:admin:providernets:index') msg = _('Failed to create provider network %s') % data['name'] exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, data): try: # Admin ignore quota param = {} if data['floating_ip_address']: param['floating_ip_address'] = data['floating_ip_address'] if data['description']: param['description'] = data['description'] subnet = api.neutron.subnet_get(request, data['pool']) param['subnet_id'] = subnet.id fip = api.neutron.tenant_floating_ip_allocate( request, pool=subnet.network_id, tenant_id=data['tenant'], **param) messages.success( request, _('Allocated floating IP %(ip)s.') % {"ip": fip.ip}) return fip except Exception: redirect = reverse('horizon:admin:floating_ips:index') msg = _('Unable to allocate floating IP.') exceptions.handle(request, msg, redirect=redirect)
def handle(self, request, context): context['admin_state_up'] = (context['admin_state_up'] == 'True') try: data = { 'pool': { 'name': context['name'], 'description': context['description'], 'lb_method': context['lb_method'], 'admin_state_up': context['admin_state_up'], } } pool = api.lbaas.pool_update(request, context['pool_id'], **data) msg = _('Pool %s was successfully updated.') % context['name'] LOG.debug(msg) messages.success(request, msg) # operation log config = _('Pool Name: %s') % context['name'] api.logger.Logger(request).create(resource_type='loadblance', action_name='Update Loadblance', resource_name='Loadblance', config=config, status='Success') return pool except Exception: msg = _('Failed to update pool %s') % context['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) # operation log api.logger.Logger(request).create(resource_type='loadblance', action_name='Update Loadblance', resource_name='Loadblance', config=msg, status='Error')
def handle(self, request, data): try: vim_name = data['vim_name'] description = data['vim_description'] password = data['password'] username = data['username'] project_name = data['project_name'] is_default = data['is_default'] auth_url = data['auth_url'] vim_type = 'openstack' domain_name = data['domain_name'] vim_arg = { 'vim': { 'name': vim_name, 'description': description, 'type': vim_type, 'auth_url': auth_url, 'auth_cred': { 'username': username, 'password': password, 'user_domain_name': domain_name }, 'vim_project': { 'name': project_name, 'project_domain_name': domain_name }, 'is_default': is_default } } api.tacker.create_vim(request, vim_arg) messages.success( request, _('VIM %s create operation initiated.') % vim_name) return True except Exception as e: exceptions.handle(request, _('Failed to register VIM: %s') % e.message)
def handle(self, request, data): try: spec_dhss = data['spec_driver_handles_share_servers'].lower() allowed_dhss_values = ('true', 'false') if spec_dhss not in allowed_dhss_values: msg = _("Improper value set to required extra spec " "'spec_driver_handles_share_servers'. " "Allowed values are %s. " "Case insensitive.") % allowed_dhss_values raise ValidationError(message=msg) set_dict, unset_list = utils.parse_str_meta(data['extra_specs']) if unset_list: msg = _("Expected only pairs of key=value.") raise ValidationError(message=msg) share_type = manila.share_type_create(request, data["name"], spec_dhss, data["is_public"]) if set_dict: # NOTE(vponomaryov): remove following when # bug #1435819 is fixed. if "driver_handles_share_servers" not in set_dict.keys(): set_dict["driver_handles_share_servers"] = spec_dhss manila.share_type_set_extra_specs(request, share_type.id, set_dict) msg = _("Successfully created share type: %s") % share_type.name messages.success(request, msg) return True except ValidationError as e: # handle error without losing dialog self.api_error(e.messages[0]) return False except Exception: exceptions.handle(request, _('Unable to create share type.')) return False
def handle(self, request, data): try: driver_options = data.get('driver_options') or {} driver_options_error_msg = _( "Got improper value for field 'driver_options'. " "Expected only pairs of key=value.") if driver_options and isinstance(driver_options, six.string_types): try: set_dict, unset_list = utils.parse_str_meta(driver_options) if unset_list: raise ValidationError(message=driver_options_error_msg) driver_options = set_dict except ValidationError as e: self.api_error(e.messages[0]) return False elif not isinstance(driver_options, dict): self.api_error(driver_options_error_msg) return False manila.share_manage(request, service_host=data['host'], protocol=data['protocol'], export_path=data['export_location'], driver_options=driver_options, share_type=data['share_type'], name=data['name'], description=data['description']) share_name = data.get('name', data.get('id')) messages.success( request, _('Successfully sent the request to manage share: %s') % share_name) return True except Exception: exceptions.handle(request, _("Unable to manage share")) return False
def handle(self, request, data): try: # We must specify tenant_id of the network which a subnet is # created for if admin user does not belong to the tenant. network = api.neutron.network_get(request, data['network_id']) # data['tenant_id'] = network.tenant_id if data['tenant_id'] == 'null': data['tenant_id'] = network.tenant_id data['admin_state_up'] = (data['admin_state'] == 'True') del data['network_name'] del data['admin_state'] if data['qos_policy_id'] == '': del data['qos_policy_id'] if data['fixed_ip']: data['fixed_ips'] = [{'ip_address': data['fixed_ip']}] del data['fixed_ip'] else: del data['fixed_ip'] if data['mac_address']: pass else: del data['mac_address'] if 'mac_state' in data: data['mac_learning_enabled'] = data['mac_state'] del data['mac_state'] port = api.neutron.port_create(request, **data) msg = _('Port %s was successfully created.') % port['id'] LOG.debug(msg) messages.success(request, msg) return port except Exception: msg = _('Failed to create a port for network %s') \ % data['network_id'] LOG.info(msg) redirect = reverse(self.failure_url, args=(data['network_id'], )) exceptions.handle(request, msg, redirect=redirect)