def email_verify_and_update(request): """If the verification_key is correct, change the user email.""" # check the verification_key name = request.user.name new_email = request.GET.get('new_email') signer = Signer() expected_verification_key = signer.sign(name + new_email).split(':')[1] if expected_verification_key == request.GET.get('verification_key'): # now update email user_id = request.user.id # if we dont set password to None we get a dict-key error in api/keystone api.keystone.user_update( request, user_id, name=new_email, password=None) msg = 'Email changed succesfully.' messages.success(request, msg) else: msg = 'Invalid verification key. Email not updated.' messages.error(request, msg) # redirect user to settings home response = redirect('horizon:settings:multisettings:index') return response
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, table, request, obj_ids): try: username, password = api.trove.root_enable(request, obj_ids) table.data[0].enabled = True table.data[0].password = password except Exception: messages.error(request, _('There was a problem enabling root.'))
def get_datasources_tables_data(self): try: datasources = congress.datasources_list(self.request) except Exception as e: msg = _('Unable to get services list: %s') % str(e) messages.error(self.request, msg) return [] ds_temp = [] for ds in datasources: ds_id = ds['id'] try: ds_tables = congress.datasource_tables_list(self.request, ds_id) except Exception as e: msg_args = {'ds_id': ds_id, 'error': str(e)} msg = _('Unable to get tables list for service "%(ds_id)s": ' '%(error)s') % msg_args messages.error(self.request, msg) return [] for table in ds_tables: table.set_value('datasource_id', ds_id) table.set_value('datasource_name', ds['name']) table.set_value('datasource_driver', ds['driver']) table.set_id_as_name_if_empty() # Object ids within a Horizon table must be unique. Otherwise, # Horizon will cache the column values for the object by id and # use the same column values for all rows with the same id. table.set_value('table_id', table['id']) table.set_value('id', '%s-%s' % (ds_id, table['table_id'])) ds_temp.append(table) logger.debug("ds_temp %s" % ds_temp) return ds_temp
def handle(self, request, data): if 'upload' in self.request.POST: # if upload button was pressed, stay on the same page # but show content of the CSV file in table racks_str = self.cleaned_data['csv_file'] self.initial['racks'] = CSVRack.from_str(racks_str) self.data['uploaded_data'] = base64.b64encode(racks_str) return False else: fails = [] successes = [] racks_str = self.cleaned_data['uploaded_data'] racks = CSVRack.from_str(base64.b64decode(racks_str)) # get the resource class ids by resource class names rclass_ids = dict((rc.name, rc.id) for rc in api.tuskar.ResourceClass.list(request)) for rack in racks: try: r = api.tuskar.Rack.create(request, rack.name, rclass_ids[rack.resource_class], rack.region, rack.subnet) api.tuskar.Rack.register_nodes(r, rack.nodes) successes.append(rack.name) except: LOG.exception("Exception in processing rack CSV file.") fails.append(rack.name) if successes: messages.success(request, _('Added %d racks.') % len(successes)) if fails: messages.error(request, _('Failed to add following racks: %s') % (',').join(fails)) return True
def delete(self, request, obj_id): try: # detach all interfaces before attempting to delete the router search_opts = {'device_owner': 'network:router_interface', 'device_id': obj_id} ports = api.neutron.port_list(request, **search_opts) for port in ports: api.neutron.router_remove_interface(request, obj_id, port_id=port.id) api.neutron.router_delete(request, obj_id) except q_ext.NeutronClientException as e: # TODO(amotoki): Revisit why Http302 needs to be raised. # We have this pattern ONLY HERE. # Can't we merge two except clauses? LOG.info('Unable to delete router %(id)s: %(exc)s', {'id': obj_id, 'exc': e}) obj = self.table.get_object_by_id(obj_id) name = self.table.get_object_display(obj) msg = _('Unable to delete router "%s"') % name messages.error(request, msg) redirect = reverse(self.redirect_url) raise exceptions.Http302(redirect, message=msg) except Exception as e: LOG.info('Unable to delete router %(id)s: %(exc)s', {'id': obj_id, 'exc': e}) obj = self.table.get_object_by_id(obj_id) name = self.table.get_object_display(obj) msg = _('Unable to delete router "%s"') % name exceptions.handle(request, msg)
def get_datasources_tables_data(self): try: datasources = congress.datasources_list(self.request) except Exception as e: msg = _('Unable to get services list: %s') % e.message messages.error(self.request, msg) return [] ds_temp = [] for ds in datasources: ds_id = ds['id'] try: ds_tables = congress.datasource_tables_list(self.request, ds_id) except Exception as e: msg_args = {'ds_id': ds_id, 'error': e.message} msg = _('Unable to get tables list for service "%(ds_id)s": ' '%(error)s') % msg_args messages.error(self.request, msg) return [] for table in ds_tables: table.set_value('datasource_id', ds_id) table.set_value('datasource_name', ds['name']) table.set_value('datasource_driver', ds['driver']) table.set_id_as_name_if_empty() ds_temp.append(table) logger.info("ds_temp %s" % ds_temp) return ds_temp
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 get_policies_tables_data(self): try: policies = congress.policies_list(self.request) except Exception as e: msg = _('Unable to get policies list: %s') % e.message messages.error(self.request, msg) return [] policies_tables = [] for policy in policies: policy_name = policy['name'] try: policy_tables = congress.policy_tables_list(self.request, policy_name) except Exception as e: msg_args = {'policy_name': policy_name, 'error': e.message} msg = _('Unable to get tables list for policy ' '"%(policy_name)s": %(error)s') % msg_args messages.error(self.request, msg) return [] for pt in policy_tables: pt.set_id_as_name_if_empty() pt.set_policy_details(policy) policies_tables.extend(policy_tables) return policies_tables
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, **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, table, request, obj_ids): datum_display_objs = [] for datum_id in obj_ids: datum = table.get_object_by_id(datum_id) datum_display = table.get_object_display(datum) or datum_id datum_display_objs.append(datum_display) display_str = functions.lazy_join(", ", datum_display_objs) try: cluster_id = table.kwargs['cluster_id'] data = [{'id': instance_id} for instance_id in obj_ids] api.trove.cluster_shrink(request, cluster_id, data) LOG.info('%s: "%s"' % (self._get_action_name(past=True), display_str)) msg = _('Removed instances from cluster.') messages.info(request, msg) except Exception as ex: LOG.error('Action %s Failed for %s' % (self._get_action_name(past=True).lower(), display_str), ex) msg = _('Unable to remove instances from cluster: %s') messages.error(request, msg % ex.message) return shortcuts.redirect(self.get_success_url(request))
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 delete(self, request, obj_id): try: cache = CacheRule.objects.get(pk=obj_id) domain = Domain.objects.get(pk=cache.domain_id) domain_manager = middware.DomainManage() ret = domain_manager.find(domain.domain_id) domain_class = ret.getDomain() cacheBehaviors = domain_class.cacheBehaviors if cacheBehaviors is not None: for i in cacheBehaviors: if cache.pathPattern == i.pathPattern: cacheBehaviors.remove(i) domain_class = middware.domainApi.Domain(domainId=domain.domain_id, cacheBehaviors=cacheBehaviors) domain_manager.modify(domain_class) cache.delete() except Exception: obj = self.table.get_object_by_id(obj_id) name = self.table.get_object_display(obj) msg = _('Unable to delete domain %s') % name LOG.info(msg) messages.error(request, msg) exceptions.handle(request, msg) redirect = reverse(self.redirect_url) raise exceptions.Http302(redirect, message=msg)
def get_data(self): snapshot = [] try: snapshot = Snapshots(self.request).get_snapshots() except Exception, e: messages.error(self.request,_(e.message)) LOG.error(e.message)
def delete(self, request, obj_id): try: # 执行删除前状态检查,当状态为"unverified"或"failed"时直接删除数据库记录 # 否则更新状态为"deleted",保证数据统计时有记录,然后调用网宿api,删除加速记录 domain = Domain.objects.get(pk=obj_id) cdn = middware.DomainManage() if domain.status == "unverified" or domain.status == "failed" or domain.status == "addfailed" \ or domain.status == 'verified': domain.delete() elif domain.status == 'inProgress': msg = _("%s status is %s, can not do this action") % (domain.domain_name, _(domain.status)) messages.warning(request, msg) else: domain.status = 'deleted' domain.deleted_at = datetime.now() domain.save() cdn.delete(domainId=domain.domain_id) except Exception: name = self.table.get_object_display(obj_id) msg = _('Unable to delete domain %s') % name LOG.info(msg) messages.error(request, msg) exceptions.handle(request, msg) redirect = reverse(self.redirect_url) raise exceptions.Http302(redirect, message=msg)
def delete(self, request, obj_id): try: access = AccessControl.objects.get(pk=obj_id) domain = Domain.objects.get(pk=access.domain_id) domain_manager = middware.DomainManage() ret = domain_manager.find(domain.domain_id) domain_class = ret.getDomain() visitControlRules = domain_class.visitControlRules if visitControlRules is not None: for i in domain_class.visitControlRules: if access.pathPattern == i.pathPattern: visitControlRules.remove(i) domain_class = middware.domainApi.Domain(domainId=domain.domain_id, visitControlRules=domain_class.visitControlRules) domain_manager.modify(domain_class) access.delete() except Exception: obj = self.table.get_object_by_id(obj_id) name = self.table.get_object_display(obj) msg = _('Unable to delete domain %s') % name LOG.info(msg) messages.error(request, msg) exceptions.handle(request, msg) redirect = reverse(self.redirect_url) raise exceptions.Http302(redirect, message=msg)
def download_rc_file(request): tenant_id = request.user.tenant_id tenant_name = request.user.tenant_name template = 'project/access_and_security/api_access/openrc.sh.template' try: keystone_url = api.base.url_for(request, 'identity', endpoint_type='publicURL') context = {'user': request.user, 'auth_url': keystone_url, 'tenant_id': tenant_id, 'tenant_name': tenant_name} response = shortcuts.render(request, template, context, content_type="text/plain") response['Content-Disposition'] = ('attachment; ' 'filename=%s-openrc.sh' % tenant_name) response['Content-Length'] = str(len(response.content)) return response except Exception as e: LOG.exception("Exception in DownloadOpenRCForm.") messages.error(request, _('Error Downloading RC File: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
def allowed(self, request, datum): #LOG.error("CEPH_LOG PRESENTPOOL: ALLOW <") LOG.info("CEPH_LOG PRESENTPOOL: datum %s" % datum) if datum: for data in self.table.data: if not (data['status'] in ("running", "whatever")): raise ValueError("Some Pools' status is not correct!") appnodes = vsmapi.appnode_list(request) if len(appnodes) < 1: raise ValueError("No Openstack Node!!") for appnode in appnodes: if appnode.ssh_status != "reachable": messages.error(request, "Can't SSH to AppNode %s" % appnode.ip) raise Exception("abc") if datum['status'] not in ("running", "whatever"): raise ValueError("Pool %s status is not correct!" % datum['name']) pool_usages = vsmapi.pool_usages(request) if datum['id'] in [str(p.pool_id) for p in pool_usages]: raise ValueError("Pool %s already Connected to Openstack" % datum['name']) #LOG.error("CEPH_LOG PRESENTPOOL: ALLOW >") return True
def summarize(self, start, end): if not api.nova.extension_supported('SimpleTenantUsage', self.request): return if start <= end and start <= self.today: # The API can't handle timezone aware datetime, so convert back # to naive UTC just for this last step. start = timezone.make_naive(start, timezone.utc) end = timezone.make_naive(end, timezone.utc) try: self.usage_list = self.get_usage_list(start, end) except Exception: exceptions.handle(self.request, _('Unable to retrieve usage information.')) elif end < start: messages.error(self.request, _("Invalid time period. The end date should be " "more recent than the start date.")) elif start > self.today: messages.error(self.request, _("Invalid time period. You are requesting " "data from the future which may not exist.")) for project_usage in self.usage_list: project_summary = project_usage.get_summary() for key, value in project_summary.items(): self.summary.setdefault(key, 0) self.summary[key] += value
def update(self, request, initial): try: # public filter removed images, _more = glance.image_list_detailed(request) except: images = [] exceptions.handle(request, _("Unable to retrieve public images.")) image_mapping, image_choices = {}, [] for image in images: murano_property = image.properties.get('murano_image_info') if murano_property: # convert to dict because # only string can be stored in image metadata property try: murano_json = ast.literal_eval(murano_property) except ValueError: messages.error(request, _("Invalid value in image metadata")) else: title = murano_json.get('title') image_id = murano_json.get('id') if title and image_id: image_mapping[smart_text(title)] = smart_text(image_id) for name in sorted(image_mapping.keys()): image_choices.append((image_mapping[name], name)) if image_choices: image_choices.insert(0, ("", _("Select Image"))) else: image_choices.insert(0, ("", _("No images available"))) self.choices = image_choices
def handle(self, request, data): failed, succeeded = [], [] user_is_editable = api.keystone.keystone_can_edit_user() user = data.pop('id') tenant = data.pop('tenant_id') if user_is_editable: password = data.pop('password') data.pop('confirm_password', None) if user_is_editable: # Update user details msg_bits = (_('name'), _('email')) try: api.keystone.user_update(request, user, **data) succeeded.extend(msg_bits) except: failed.extend(msg_bits) exceptions.handle(request, ignore=True) # Update default tenant msg_bits = (_('primary project'),) try: api.keystone.user_update_tenant(request, user, tenant) succeeded.extend(msg_bits) except: failed.append(msg_bits) exceptions.handle(request, ignore=True) # Check for existing roles # Show a warning if no role exists for the tenant user_roles = api.keystone.roles_for_user(request, user, tenant) if not user_roles: messages.warning(request, _('The user %s has no role defined for' + ' that project.') % data.get('name', None)) if user_is_editable: # If present, update password # FIXME(gabriel): password change should be its own form and view if password: msg_bits = (_('password'),) try: api.keystone.user_update_password(request, user, password) succeeded.extend(msg_bits) if user == request.user.id: logout(request) except: failed.extend(msg_bits) exceptions.handle(request, ignore=True) if succeeded: messages.success(request, _('User has been updated successfully.')) if failed: failed = map(force_unicode, failed) messages.error(request, _('Unable to update %(attributes)s for the user.') % {"attributes": ", ".join(failed)}) return True
def download_juju_env_file(request): tenant_id = request.user.tenant_id tenant_name = request.user.tenant_name region = request.user.services_region if region is None: region = "" template = 'project/access_and_security/api_access/juju.environments.template' try: keystone_url = api.base.url_for(request, 'identity', endpoint_type='publicURL') context = {'auth_url': keystone_url, 'tenant_name': tenant_name, 'user': request.user, 'region': region} response = shortcuts.render(request, template, context, content_type="text/yaml") response['Content-Disposition'] = ('attachment; ' 'filename="%s-environments.yaml"' % tenant_name) response['Content-Length'] = str(len(response.content)) return response except Exception as e: LOG.exception("Exception in DownloadJujuEnvironmentsForm.") messages.error(request, _('Error Downloading Juju Environments File: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
def handle(self, request, data): try: # Set Cipher to None if empty if data['cipher'] == u'': data['cipher'] = None volume_type_id = data.pop('volume_type_id') volume_type_name = data.pop('name') # Update encryption for the volume type volume_type = cinder.\ volume_encryption_type_update(request, volume_type_id, data) messages.success(request, _('Successfully updated encryption for ' 'volume type: %s') % volume_type_name) return volume_type except NotImplementedError: messages.error(request, _('Updating encryption is not ' 'implemented. Unable to update ' ' encrypted volume type.')) except Exception: redirect = reverse("horizon:admin:volume_types:index") exceptions.handle(request, _('Unable to update encrypted volume type.'), redirect=redirect) return False
def get_policies_tables_data(self): try: policies = congress.policies_list(self.request) except Exception as e: msg = _('Unable to get policies list: %s') % str(e) messages.error(self.request, msg) return [] policies_tables = [] for policy in policies: policy_name = policy['name'] try: policy_tables = congress.policy_tables_list(self.request, policy_name) except Exception as e: msg_args = {'policy_name': policy_name, 'error': str(e)} msg = _('Unable to get tables list for policy ' '"%(policy_name)s": %(error)s') % msg_args messages.error(self.request, msg) return [] for pt in policy_tables: pt.set_id_as_name_if_empty() pt.set_policy_details(policy) # Object ids within a Horizon table must be unique. Otherwise, # Horizon will cache the column values for the object by id and # use the same column values for all rows with the same id. pt.set_value('table_id', pt['id']) pt.set_value('id', '%s-%s' % (policy_name, pt['table_id'])) policies_tables.extend(policy_tables) return policies_tables
def handle_unauthorized( request, message, redirect, ignore, escalate, handled, force_silence, force_log, log_method, log_entry, log_level ): if ignore: return NotAuthorized if not force_silence and not handled: log_method(error_color("Unauthorized: %s" % log_entry)) if not handled: if message: message = _("Unauthorized: %s") % message # We get some pretty useless error messages back from # some clients, so let's define our own fallback. fallback = _("Unauthorized. Please try logging in again.") messages.error(request, message or fallback) # Escalation means logging the user out and raising NotAuthorized # so the middleware will redirect them appropriately. if escalate: # Prevents creation of circular import. django.contrib.auth # requires openstack_dashboard.settings to be loaded (by trying to # access settings.CACHES in in django.core.caches) while # openstack_dashboard.settings requires django.contrib.auth to be # loaded while importing openstack_auth.utils from django.contrib.auth import logout # noqa logout(request) raise NotAuthorized # Otherwise continue and present our "unauthorized" error message. return NotAuthorized
def populate_subnet_id_choices(self, request): tenant_id = self.request.user.tenant_id networks = [] try: networks = api.neutron.network_list_for_tenant(request, tenant_id) except Exception as e: msg = _('Failed to get network list %s') % e.message LOG.info(msg) messages.error(request, msg) router_id = request.REQUEST.get('router_id', self.initial.get('router_id')) if router_id: redirect = reverse(self.failure_url, args=[router_id]) else: redirect = reverse('horizon:project:routers:index') exceptions.handle(request, msg, redirect=redirect) return choices = [] for n in networks: net_name = n.name + ': ' if n.name else '' choices += [(subnet.id, '%s%s (%s)' % (net_name, subnet.cidr, subnet.name or subnet.id)) for subnet in n['subnets']] if choices: choices.insert(0, ("", _("Select Subnet"))) else: choices.insert(0, ("", _("No subnets available"))) return choices
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) # response = http.HttpResponseRedirect(settings.LOGOUT_URL) response = http.HttpResponseRedirect('/horizon/auth/login') userid = request.user.id print "this is setting userid : '%s'" % userid print "this is setting data['new_password'] : '******'" % data['new_password'] update_user_password(userid, data['new_password']) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False return True
def get_data(self, request, instance_id): instance = api.nova.server_get(request, instance_id) instance.full_flavor = api.nova.flavor_get(request, instance.flavor["id"]) error = get_instance_error(instance) if error: messages.error(request, error) return instance
def allowed(self, request, osd=None): if osd is not None: if osd['vsm_status'] not in UNINIT_STATES: msg = _('Only osd with VSM status "%s" will be added'%UNINIT_STATES) messages.error(request, msg) return False return True
def handle(self, request, data): try: rules = json.loads(data["rules"]) new_mapping = api.keystone.mapping_create(request, data["id"], rules=rules) messages.success(request, _("Mapping created successfully.")) return new_mapping except exceptions.Conflict: msg = _('Mapping ID "%s" is already used.') % data["id"] messages.error(request, msg) except (TypeError, ValueError): msg = _("Unable to create mapping. Rules has malformed JSON data.") messages.error(request, msg) except Exception: exceptions.handle(request, _("Unable to create mapping.")) return False
def handle(self, table, request, obj_ids): for obj_id in obj_ids: try: stage_id = obj_id.split('-', 1)[1] result = stx_api.vim.abort_strategy(request, self.strategy_name, stage_id) if result is None: messages.error( request, "Strategy stage %s abort in progress" % stage_id) else: messages.success(request, "Strategy stage %s aborted" % stage_id) except Exception as ex: LOG.exception(ex) messages.error(request, str(ex))
def servers_update_addresses(request, servers): """Retrieve servers networking information from Neutron if enabled. Should be used when up to date networking information is required, and Nova's networking info caching mechanism is not fast enough. """ # Get all (filtered for relevant servers) information from Neutron try: ports = port_list(request, device_id=[instance.id for instance in servers]) fips = FloatingIpManager(request) if fips.is_supported(): floating_ips = fips.list(port_id=[port.id for port in ports]) else: floating_ips = [] networks = network_list(request, id=[port.network_id for port in ports]) except Exception: error_message = _('Unable to connect to Neutron.') LOG.error(error_message) messages.error(request, error_message) return # Map instance to its ports instances_ports = collections.defaultdict(list) for port in ports: instances_ports[port.device_id].append(port) # Map port to its floating ips ports_floating_ips = collections.defaultdict(list) for fip in floating_ips: ports_floating_ips[fip.port_id].append(fip) # Map network id to its name network_names = dict(((network.id, network.name) for network in networks)) for server in servers: try: addresses = _server_get_addresses(request, server, instances_ports, ports_floating_ips, network_names) except Exception as e: LOG.error(e) else: server.addresses = addresses
def _set_external_network(self, router, ext_net_dict): gateway_info = router.external_gateway_info if gateway_info: ext_net_id = gateway_info['network_id'] if ext_net_id in ext_net_dict: gateway_info['network'] = ext_net_dict[ext_net_id] else: msg_params = {'ext_net_id': ext_net_id, 'router_id': router.id} msg = _('External network "%(ext_net_id)s" expected but not ' 'found for router "%(router_id)s".') % msg_params messages.error(self.request, msg) # gateway_info['network'] is just the network name, so putting # in a smallish error message in the table is reasonable. # Translators: The usage is "<UUID of ext_net> (Not Found)" gateway_info['network'] = pgettext_lazy( 'External network not found', u'%s (Not Found)') % ext_net_id
def populate_mapping_id_choices(self, request): try: mappings = api.keystone.mapping_list(request) except Exception as e: LOG.info('Failed to get mapping list %s', e) msg = _('Failed to get mapping list %s') % e messages.error(request, msg) choices = [(m.id, m.id) for m in mappings] choices.sort() if choices: choices.insert(0, ("", _("Select Mapping"))) else: choices.insert(0, ("", _("No mappings available"))) self.fields['mapping_id'].choices = choices
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) messages.success(request, _('Password changed.')) except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False return True
def _ensure_images(name, package): try: imgs = muranoclient_utils.ensure_images( glance_client=glance_client, image_specs=package.images(), base_url=base_url) for img in imgs: msg = _("Added {0}, {1} image to glance").format( img['name'], img['id'], ) messages.success(self.request, msg) LOG.info(msg) except Exception as e: msg = _("Error {0} occurred while installing " "images for {1}").format(e, name) messages.error(self.request, msg) LOG.exception(msg)
def download_vm_overlay(request): try: image_id = request.GET.get('image_id', None) image_name = request.GET.get('image_name', None) if image_id is None: raise client = api.glance.glanceclient(request) body = client.images.data(image_id) response = http.HttpResponse(body, content_type="application/octet-stream") response[ 'Content-Disposition'] = 'attachment; filename="%s"' % image_name return response except Exception, e: messages.error(request, _('Error Downloading VM overlay: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
def get_data(self): request = self.request plats = [] try: request_api = RequestApi() plats = request_api.getRequestInfo( 'api/heterogeneous/platforms/hosts') if plats and type(plats) == type([]): plats.sort(key=lambda aggregate: aggregate['name'].lower()) res = DictList2ObjectList(plats) return res elif plats and type(plats) == type( {}) and plats.get('action') == 'failed': messages.error(request, _('Unable to retrieve hosts list.')) except Exception: exceptions.handle(request, _('Unable to retrieve hosts list.')) return []
def handle(self, request, context): authUrl = "http://*****:*****@127.0.0.1:61209" #server = xmlrpclib.ServerProxy(authUrl) context_computing_nodes = context['computing_nodes'] node_list = [] for node in context_computing_nodes: node_list.append(node) cluster_id = self.get_cluster_id(self.get_absolute_url()) result = server.add_node(cluster_id,node_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 _format_address(mac, ip, type): try: version = netaddr.IPAddress(ip).version except Exception as e: LOG.error('Unable to parse IP address %(ip)s: %(exc)s', { 'ip': ip, 'exc': e }) error_message = _('Unable to parse IP address %s.') % ip messages.error(request, error_message) raise return { u'OS-EXT-IPS-MAC:mac_addr': mac, u'version': version, u'addr': ip, u'OS-EXT-IPS:type': type }
def get_data(self): try: policy_id = self.kwargs['policy_name'] rules = congress.show_library_policy(self.request, policy_id)['rules'] for r in rules: head = r['rule'].split(congress.RULE_SEPARATOR)[0] name = (head.split('(')[0]).replace('_', ' ').title() name = name.split('[')[0] r.set_value('name', name) r.set_id_if_empty(uuid.uuid4()) return rules except Exception as e: msg = _('Unable to list rules of library policy: %s') % str(e) LOG.exception(msg) messages.error(self.request, msg) return []
def get_policy_rules_data(self): policy_name = self.kwargs['policy_name'] try: policy_rules = congress.policy_rules_list(self.request, policy_name) except Exception as e: msg_args = {'policy_name': policy_name, 'error': str(e)} msg = _('Unable to get rules in policy "%(policy_name)s": ' '%(error)s') % msg_args LOG.error(msg) messages.error(self.request, msg) redirect = reverse('horizon:admin:policies:index') raise exceptions.Http302(redirect) for r in policy_rules: r.set_id_as_name_if_empty() return policy_rules
def handle(self, request, data): group_id = data.pop('group_id') try: api.keystone.group_update(request, group_id=group_id, name=data['name'], description=data['description']) messages.success(request, _('Group has been updated successfully.')) except exceptions.Conflict: msg = _('Group "%s" already exists.') % data['name'] messages.error(request, msg) except Exception: exceptions.handle(request, _('Unable to update the group.')) return False return True
def handle(self, request, data): name = data.pop('name') project = data.pop('project') try: billing_client = chakra.AccountBilling() body = {"balance": 0, "ref_resource": project, "name": name} accounts, resultStatus = billing_client.create_account(body) if resultStatus != 200: messages.error(request, _('Unable to create the account.')) else: messages.success(request, _('Account has been created successfully.')) except Exception: messages.error(request, _('Unable to create the account.')) return True
def handle(self, request, data): try: tenant_id = self.request.user.tenant_id domain = [ i for i in Domain.objects.filter(domain_name=data['domain_name']) if i.status != 'deleted' ] # 判断域名是否已添加 if domain: message = _('Domain %s has created.') % data['domain_name'] messages.error(request, message) return [] else: p = Domain(tenant_id=tenant_id, domain_name=data['domain_name'], domain_cname='-', source_type=data['source_type']) p.save() if data['source_type'] == 'ip': for i in data['origin_config_a'].strip('\r\n').split( '\r\n'): o = p.sourceaddress_set.create(source_address=i) o.save() else: o = p.sourceaddress_set.create( source_address=data['origin_config_b']) o.save() # 将domain_name和随机生成的uui绑定存储到memcache中,为域名鉴权提供依据 memcached_servers = settings.CACHES.get("default").get( "LOCATION") mc = memcache.Client(memcached_servers) mc.set(str(data['domain_name']), str(uuid.uuid4())) message = _( 'Domain %s was successfully created') % data['domain_name'] messages.success(request, message) return data['domain_name'] except exceptions as exc: if exc.status_code == 409: msg = _('Quota exceeded for resource domain.') else: msg = _('Failed to create Domain %s') % data['name'] LOG.info(msg) redirect = self.failure_url exceptions.handle(request, msg, redirect=redirect) return False
def handle(self, request, data): try: response = stx_api.vim.create_strategy( request, stx_api.vim.STRATEGY_SW_PATCH, data.get('controller_apply_type', 'ignore'), data.get('storage_apply_type', 'ignore'), 'ignore', data['worker_apply_type'], data['max_parallel_worker_hosts'], data['default_instance_action'], data['alarm_restrictions']) if not response: messages.error(request, "Strategy creation failed") except Exception: redirect = reverse(self.failure_url) exceptions.handle(request, "Strategy creation failed", redirect=redirect) return True
def handle(self, request, data): try: associate = ElasticIPs(request).associate_addr( data['id'], data['instance_id']) if associate == True: messages.success(request, _('Successfully Associated: %s') % data['id']) else: messages.error( request, _('Unable to associate address: %s') % data['id']) return True except Exception, e: redirect = reverse("horizon:amazon:elastic_ip:index") messages.error(request, _(e.message)) LOG.error(e.message) exceptions.handle_redirect(request, redirect)
def handle(self, request, data): user_id = data.pop('id') password = data.pop('password') admin_password = None # Throw away the password confirmation, we're done with it. data.pop('confirm_password', None) # Verify admin password before changing user password if getattr(settings, 'ENFORCE_PASSWORD_CHECK', False): admin_password = data.pop('admin_password') if not api.keystone.user_verify_admin_password( request, admin_password): self.api_error(_('The admin password is incorrect.')) return False try: if is_m1_user_admin(request): ksclient = get_admin_ksclient() if api.keystone.VERSIONS.active < 3: response = ksclient.users.update_password( user_id, password) else: response = ksclient.users.update(user_id, password=password) else: response = api.keystone.user_update_password( request, user_id, password) if user_id == request.user.id: return utils.logout_with_message( request, _('Password changed. Please log in to continue.'), redirect=False) messages.success(request, _('User password has been updated successfully.')) except Exception: response = exceptions.handle(request, ignore=True) messages.error(request, _('Unable to update the user password.')) if isinstance(response, http.HttpResponse): return response else: return True
def delete(self, request, obj_id): try: with transaction.atomic(): q_args = { 'registration__userid': obj_id, 'project__projectname': request.user.tenant_name } Expiration.objects.filter(**q_args).delete() PrjRequest.objects.filter(**q_args).delete() PrjRole.objects.filter(**q_args).delete() roles_obj = client_factory(request).roles role_assign_obj = client_factory(request).role_assignments arg_dict = {'project': request.user.tenant_id, 'user': obj_id} for r_item in role_assign_obj.list(**arg_dict): roles_obj.revoke(r_item.role['id'], **arg_dict) tmpres = EMail.objects.filter(registration__userid=obj_id) member_email = tmpres[0].email if tmpres else None member_name = tmpres[0].registration.username if tmpres else None tmpres = EMail.objects.filter(registration__userid=request.user.id) admin_email = tmpres[0].email if tmpres else None noti_params = { 'username': member_name, 'admin_address': admin_email, 'project': request.user.tenant_name } notifyUser(request=request, rcpt=member_email, action=MEMBER_REMOVED, context=noti_params, dst_user_id=obj_id) notifyAdmin(request=request, action=MEMBER_REMOVED_ADM, context=noti_params) except: LOG.error("Grant revoke error", exc_info=True) messages.error(request, _('Unable to delete member from tenant.'))
def handle(self, request, data): stor_id = data['id'] try: # Obtain journal information. journal = data['journal_locations'][:] if journal: data['journal_location'] = journal else: data['journal_location'] = None data['journal_size_mib'] = \ stx_api.sysinv.JOURNAL_DEFAULT_SIZE * 1024 del data['journal_locations'] del data['id'] del data['journal_size_gib'] # The REST API takes care of updating the stor journal information. stor = stx_api.sysinv.host_stor_update(request, stor_id, **data) msg = _('Storage volume was successfully updated.') LOG.debug(msg) messages.success(request, msg) return stor except exc.ClientException as ce: msg = _('Failed to update storage volume.') LOG.info(msg) LOG.error(ce) # Allow REST API error message to appear on UI. messages.error(request, ce) # Redirect to host details pg. redirect = reverse(self.failure_url, args=[stor_id]) return shortcuts.redirect(redirect) except Exception as e: msg = _('Failed to update storage volume.') LOG.info(msg) LOG.error(e) # if not a rest API error, throw default redirect = reverse(self.failure_url, args=[stor_id]) return exceptions.handle(request, message=e, redirect=redirect)
def create_keystone_user(request, data): domain = api.keystone.get_default_domain(request, False) try: LOG.info('Creating user with name "%s"', data['name']) # add extra information if api.keystone.VERSIONS.active >= 3: EXTRA_INFO = getattr(settings, 'USER_TABLE_EXTRA_INFO', {}) kwargs = dict((key, data.get(key)) for key in EXTRA_INFO) else: kwargs = {} new_user = \ api.keystone.user_create(request, name=data['name'], email=data['email'], description=data['description'] or None, password=data['password'], project=data['project'] or None, enabled=data['enabled'], domain=domain.id, **kwargs) 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 exceptions.Conflict: msg = _('User name "%s" is already used.') % data['name'] messages.error(request, msg) except Exception: exceptions.handle(request, _('Unable to create user.'))
def handle(self, request, data): meta = create_image_metadata(data) # Add image source file or URL to metadata if (api.glance.get_image_upload_mode() != 'off' and policy.check( (("image", "upload_image"), ), request) and data.get('image_file', None)): meta['data'] = data['image_file'] elif data.get('is_copying'): meta['copy_from'] = data['image_url'] try: urllib2.urlopen(data['image_url']) except Exception: msg = _('Unable to create new image: ' 'Invalid url: %s ') % data['image_url'] messages.error(request, msg) return False else: meta['location'] = data['image_url'] try: image = api.glance.image_create(request, **meta) messages.info( request, _('Your image %s has been queued for creation.') % meta['name']) return image except Exception as e: msg = _('Unable to create new image') # TODO(nikunj2512): Fix this once it is fixed in glance client if hasattr(e, 'code') and e.code == 400: if "Invalid disk format" in e.details: msg = _('Unable to create new image: Invalid disk format ' '%s for image.') % meta['disk_format'] elif "Image name too long" in e.details: msg = _('Unable to create new image: Image name too long.') elif "not supported" in e.details: msg = _('Unable to create new image: URL scheme not ' 'supported.') exceptions.handle(request, msg) return False
def handle(self, table, request, obj_ids): action_success = [] action_failure = [] action_not_allowed = [] for datum_id in obj_ids: datum = table.get_object_by_id(datum_id) datum_display = table.get_object_display(datum) or datum_id if not table._filter_action(self, request, datum): action_not_allowed.append(datum_display) LOG.warning('Permission denied to %s: "%s"' % (self._get_action_name(past=True).lower(), datum_display)) continue try: self.action(request, datum_id) # Call update to invoke changes if needed self.update(request, datum) action_success.append(datum_display) self.success_ids.append(datum_id) LOG.info('%s: "%s"' % (self._get_action_name(past=True), datum_display)) except Exception as ex: # Handle the exception but silence it since we'll display # an aggregate error message later. Otherwise we'd get # multiple error messages displayed to the user. action_failure.append(datum_display) action_description = ( self._get_action_name(past=True).lower(), datum_display) LOG.error( 'Action %(action)s Failed for %(reason)s', { 'action': action_description, 'reason': ex}) if action_not_allowed: msg = _('You are not allowed to %(action)s: %(objs)s') params = {"action": self._get_action_name(action_not_allowed).lower(), "objs": functions.lazy_join(", ", action_not_allowed)} messages.error(request, msg % params) if action_failure: msg = _('Unable to %(action)s: %(objs)s') params = {"action": self._get_action_name(action_failure).lower(), "objs": functions.lazy_join(", ", action_failure)} messages.error(request, msg % params) return shortcuts.redirect(self.get_success_url(request))
def handle(self, request, data): try: LOG.info('Creating application credential with name "%s"', data['name']) expiration = None if data['expiration_date']: if data['expiration_time']: expiration_time = data['expiration_time'] else: expiration_time = datetime.datetime.min.time() expiration = datetime.datetime.combine( data['expiration_date'], expiration_time) else: if data['expiration_time']: expiration_time = data['expiration_time'] expiration_date = datetime.date.today() expiration = datetime.datetime.combine(expiration_date, expiration_time) if data['roles']: # the role list received from the form is a list of dicts # encoded as strings roles = [{'name': role_name} for role_name in data['roles']] else: roles = None new_app_cred = api.keystone.application_credential_create( request, name=data['name'], description=data['description'] or None, secret=data['secret'] or None, expires_at=expiration or None, roles=roles, unrestricted=data['unrestricted'] ) self.request.session['application_credential'] = \ new_app_cred.to_dict() request.method = 'GET' return self.next_view.as_view()(request) except exceptions.Conflict: msg = (_('Application credential name "%s" is already used.') % data['name']) messages.error(request, msg) except Exception: exceptions.handle(request, _('Unable to create application credential.'))
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False
def _download_rc_file_for_template(request, context, template, filename=None): try: content = render_to_string(template, context, request=request) content = '\n'.join( [line for line in content.split('\n') if line.strip()]) response = http.HttpResponse(content, content_type="text/plain") if not filename: filename = '%s-openrc.sh' % context['tenant_name'] disposition = 'attachment; filename="%s"' % filename response['Content-Disposition'] = disposition.encode('utf-8') response['Content-Length'] = str(len(response.content)) return response except Exception as e: LOG.exception("Exception in DownloadOpenRCForm.") messages.error(request, _('Error Downloading RC File: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
def get_context_data(self, request): stack = self.tab_group.kwargs['stack'] try: stack_identifier = '%s/%s' % (stack.stack_name, stack.id) events = api.heat.events_list(self.request, stack_identifier) LOG.debug('got events %s', events) # The stack id is needed to generate the resource URL. for event in events: event.stack_id = stack.id except Exception: events = [] messages.error( request, _('Unable to get events for stack "%s".') % stack.stack_name) return { "stack": stack, "table": project_tables.EventsTable(request, data=events), }
def handle(self, request, data): try: if data['flavor']: #snapshot = api.nova.dev_snapshot_list(request, data['instance_id']) snapshot = None if not snapshot and data.get("flavor"): api.nova.server_resize(request, data['instance_id'], data['flavor'], data.get("disk_config", "AUTO")) else: if snapshot: raise pass else: pass except Exception: messages.error(request, _("Can not resize the instance when the devsnapshot exist.")) return False return True
def get_date_range(self): if not hasattr(self, "start") or not hasattr(self, "end"): args_start = (self.today.year, self.today.month, 1) args_end = (self.today.year, self.today.month, self.today.day) form = self.get_form() if form.is_valid(): start = form.cleaned_data['start'] end = form.cleaned_data['end'] args_start = (start.year, start.month, start.day) args_end = (end.year, end.month, end.day) elif form.is_bound: messages.error( self.request, _("Invalid date format: " "Using today as default.")) self.start = self.get_start(*args_start) self.end = self.get_end(*args_end) return self.start, self.end