Example #1
0
 def _get_volumes(self, search_opts=None):
     try:
         return cinder.volume_list(self.request, search_opts=search_opts)
     except Exception:
         exceptions.handle(self.request,
                           _('Unable to retrieve volume list.'))
         return []
Example #2
0
 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.'))
Example #3
0
    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")
Example #4
0
    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)
Example #5
0
    def objects(self):
        """ Returns a list of objects given the subfolder's path.

        The path is from the kwargs of the request.
        """
        if not hasattr(self, "_objects"):
            objects = []
            self._more = None
            marker = self.request.GET.get('marker', None)
            container_name = self.kwargs['container_name']
            subfolder = self.kwargs['subfolder_path']
            prefix = None
            if container_name:
                self.navigation_selection = True
                if subfolder:
                    prefix = subfolder
                try:
                    objects, self._more = api.swift_get_objects(self.request,
                                                                container_name,
                                                                marker=marker,
                                                                prefix=prefix)
                except:
                    self._more = None
                    objects = []
                    msg = _('Unable to retrieve object list.')
                    exceptions.handle(self.request, msg)
            self._objects = objects
        return self._objects
Example #6
0
 def get_context_data(self, **kwargs):
     context = super(CreateView, self).get_context_data(**kwargs)
     try:
         context['usages'] = quotas.tenant_limit_usages(self.request)
     except Exception:
         exceptions.handle(self.request)
     return context
Example #7
0
 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)
Example #8
0
    def __init__(self, request, context, *args, **kwargs):
        super(SetAdvancedAction, self).__init__(request, context,
                                                *args, **kwargs)
        try:
            if not api.nova.extension_supported("DiskConfig", request):
                del self.fields['disk_config']
            else:
                # Set our disk_config choices
                config_choices = [("AUTO", _("Automatic")),
                                  ("MANUAL", _("Manual"))]
                self.fields['disk_config'].choices = config_choices
            # Only show the Config Drive option for the Launch Instance
            # workflow (not Resize Instance) and only if the extension
            # is supported.
            if context.get('workflow_slug') != 'launch_instance' or (
                    not api.nova.extension_supported("ConfigDrive", request)):
                del self.fields['config_drive']

            if not api.nova.extension_supported("ServerGroups", request):
                del self.fields['server_group']
            else:
                server_group_choices = instance_utils.server_group_field_data(
                    request)
                self.fields['server_group'].choices = server_group_choices
        except Exception:
            exceptions.handle(request, _('Unable to retrieve extensions '
                                         'information.'))
Example #9
0
    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)
Example #10
0
def tenant_limit_usages(request):
    # TODO(licostan): This method shall be removed from Quota module.
    # ProjectUsage/BaseUsage maybe used instead on volume/image dashboards.
    limits = {}

    try:
        limits.update(nova.tenant_absolute_limits(request))
    except Exception:
        msg = _("Unable to retrieve compute limit information.")
        exceptions.handle(request, msg)

    if base.is_service_enabled(request, 'volume'):
        try:
            limits.update(cinder.tenant_absolute_limits(request))
            volumes = cinder.volume_list(request)
            snapshots = cinder.volume_snapshot_list(request)
            total_size = sum([getattr(volume, 'size', 0) for volume
                              in volumes])
            limits['gigabytesUsed'] = total_size
            limits['volumesUsed'] = len(volumes)
            limits['snapshotsUsed'] = len(snapshots)
        except Exception:
            msg = _("Unable to retrieve volume limit information.")
            exceptions.handle(request, msg)

    return limits
Example #11
0
 def get_hosts(self, *args, **kwargs):
     try:
         return api.nova.host_list(self.request)
     except Exception:
         redirect = reverse("horizon:admin:instances:index")
         msg = _('Unable to retrieve host information.')
         exceptions.handle(self.request, msg, redirect=redirect)
Example #12
0
    def populate_instance_id_choices(self, request, context):
        try:
            targets = api.network.floating_ip_target_list(self.request)
        except:
            redirect = reverse("horizon:project:access_and_security:index")
            exceptions.handle(self.request, _("Unable to retrieve instance list."), redirect=redirect)
        instances = []
        for target in targets:
            instances.append((target.id, target.name))

        # Sort instances for easy browsing
        instances = sorted(instances, key=lambda x: x[1])

        neutron_enabled = api.base.is_service_enabled(request, "network")
        if instances:
            if neutron_enabled:
                label = _("Select a port")
            else:
                label = _("Select an instance")
            instances.insert(0, ("", label))
        else:
            if neutron_enabled:
                label = _("No ports available")
            else:
                label = _("No instances available")
            instances = (("", label),)
        return instances
Example #13
0
 def get_chain_images_data(self):
     try:
         chain = self._get_data()
         chain_images = api.quantum.chain_image_list_for_chain(self.request,
                                           chain_id=chain.id)
         for chain_image in chain_images:
             instance_id = chain_image.instance_id
             try:
                 instance = api.nova.server_get(self.request, instance_id)
                 setattr(chain_image, 'instance_uuid', instance.id)
                 #xx = getattr(instance,'OS-EXT-SRV-ATTR:instance_name','')
                 #setattr(chain_image, 'instance_uuid', xx)
             except:
                 msg = _('Unable to retrieve details for instance "%s".') \
                   % (instance_id)
                 setattr(chain_image, 'instance_uuid', '')
                 #api.quantum.chain_image_modify(self.request, chain.id,
                 #                            instance_uuid='NULL')
                 
                                               
         
     except:
         chain_images = []
         msg = _('Image list can not be retrieved.')
         exceptions.handle(self.request, msg)
     for s in chain_images:
         s.set_id_as_name_if_empty()
     return chain_images
Example #14
0
 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)
Example #15
0
 def handle(self, request, data):
     try:
         api.network.floating_ip_associate(request, data["ip_id"], data["instance_id"])
     except:
         exceptions.handle(request)
         return False
     return True
Example #16
0
 def get_data(self):
     mid = self.kwargs['monitor_id']
     try:
         return api.lbaas.pool_health_monitor_get(self.request, mid)
     except Exception:
         exceptions.handle(self.request,
                           _('Unable to retrieve monitor details.'))
    def get_data(self):
        pools = []
        pool_usages = []
        # TODO pools status
        try:
            pools = vsmapi.pool_list(self.request,)
            pool_usages = vsmapi.pool_usages(self.request)
            logging.debug("resp body in view: %s" % pools)
        except:
            exceptions.handle(self.request,
                              _('Unable to retrieve storage pool list. '))
        pool_usage_dict = {}
        for usage in pool_usages:
            pool_usage_dict.setdefault(str(usage.pool_id), usage)

        for pool in pools:
            pool['id'] = str(pool['id'])
            if pool['id'] in pool_usage_dict:
                pool['attach_status'] = pool_usage_dict[pool['id']].attach_status
            else:
                pool['attach_status'] = "no"

        pools = [x for x in pools if x['tag'] != "SYSTEM"]
        pools = [x for x in pools if x['attach_status'] == "no"]
        pools = [x for x in pools if x['tag'] != "SYSTEM" and not x['erasure_code_status']
             and not str(x['cache_tier_status']).startswith("Cache pool for")]
        return pools
 def handle(self, request, data):
     try:
         LOG.info('Creating user with name "%s"' % data['name'])
         new_user = api.user_create(request,
                         data['name'],
                         data['email'],
                         data['password'],
                         data['tenant_id'],
                         True)
         messages.success(request,
                          _('User "%s" was successfully created.')
                          % data['name'])
         try:
             default_role = api.keystone.get_default_role(request)
             if default_role:
                 api.add_tenant_user_role(request,
                                          data['tenant_id'],
                                          new_user.id,
                                          default_role.id)
         except:
             exceptions.handle(request,
                               _('Unable to add user to primary project.'))
         return shortcuts.redirect('horizon:syspanel:users:index')
     except:
         exceptions.handle(request, _('Unable to create user.'))
         return shortcuts.redirect('horizon:syspanel:users:index')
Example #19
0
 def get_data(self):
     mid = self.kwargs['member_id']
     try:
         return api.lbaas.member_get(self.request, mid)
     except Exception:
         exceptions.handle(self.request,
                           _('Unable to retrieve member details.'))
Example #20
0
 def __init__(self, request, *args, **kwargs):
     super(AccountInfoAction, self).__init__(request,
                                             *args,
                                             **kwargs)
     random_num = random.sample('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 12)
     safeCard = ''.join(random_num)
     validate.set_session(self.request, 'safeCard', safeCard)
     self.fields['safeCard'].initial = safeCard
     if not request.user.is_superuser:
         self.fields['default_role_id'].widget = forms.HiddenInput()
     else:
         try:
             roles = api.keystone.role_list(request)
             role_choices = [(r.id, r.name) for r in roles]
             if role_choices:
                 default_role_name = settings.OPENSTACK_KEYSTONE_DEFAULT_ROLE
                 role_choices = [r for r in role_choices if r[1] == default_role_name] + \
                                [r for r in role_choices if r[1] != default_role_name]
                 self.fields['default_role_id'].choices = role_choices
                 self.fields['default_role_id'].required = True
             else:
                 self.fields['default_role_id'].choices = [('', _("No roles"))]
         except Exception:
             self.fields['default_role_id'].choices = [('', _("No roles"))]
             exceptions.handle(request, _('Failed to retrieve role list'))
Example #21
0
 def __init__(self, request, package, *args, **kwargs):
     super(UpdatePackageForm, self).__init__(*args, **kwargs)
     if package.type == 'Application':
         self.fields['categories'].choices = [('',
                                               'No categories available')]
         try:
             categories = api.muranoclient(request).packages.categories()
             if categories:
                 self.fields['categories'].choices = [(c, c)
                                                      for c in categories]
             if package.categories:
                 self.fields['categories'].initial = dict(
                     (key, True) for key in package.categories)
         except (exc.HTTPException, Exception):
             msg = 'Unable to get list of categories'
             LOG.exception(msg)
             redirect = reverse('horizon:murano:packages:index')
             exceptions.handle(request,
                               _(msg),
                               redirect=redirect)
     else:
         del self.fields['categories']
     self.fields['name'].initial = package.name
     self.fields['tags'].initial = ', '.join(package.tags)
     self.fields['is_public'].initial = package.is_public
     self.fields['enabled'].initial = package.enabled
     self.fields['description'].initial = package.description
Example #22
0
    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)
Example #23
0
    def __init__(self, request, context, *args, **kwargs):
        self._init_images_cache()
        self.request = request
        self.context = context
        super(SetInstanceDetailsAction, self).__init__(
            request, context, *args, **kwargs)

        # Hide the device field if the hypervisor doesn't support it.
        if not nova.can_set_mount_point():
            self.fields['device_name'].widget = forms.widgets.HiddenInput()

        source_type_choices = [
            ('', _("Select source")),
            ("image_id", _("Boot from image")),
            ("instance_snapshot_id", _("Boot from snapshot")),
        ]
        if cinder.is_volume_service_enabled(request):
            source_type_choices.append(("volume_id", _("Boot from volume")))

            try:
                if api.nova.extension_supported("BlockDeviceMappingV2Boot",
                                                request):
                    source_type_choices.append(
                        ("volume_image_id",
                         _("Boot from image (creates a new volume)")))
            except Exception:
                exceptions.handle(request, _('Unable to retrieve extensions '
                                             'information.'))

            source_type_choices.append(
                ("volume_snapshot_id",
                 _("Boot from volume snapshot (creates a new volume)")))
        self.fields['source_type'].choices = source_type_choices
 def handle(self, request, data):
     instance_choices = dict(self.fields['instance'].choices)
     instance_name = instance_choices.get(data['instance'],
                                          _("Unknown instance (None)"))
     # The name of the instance in the choices list has the ID appended to
     # it, so let's slice that off...
     instance_name = instance_name.rsplit(" (")[0]
     try:
         attach = api.nova.instance_volume_attach(request,
                                                  data['volume_id'],
                                                  data['instance'],
                                                  data.get('device', ''))
         volume = cinder.volume_get(request, data['volume_id'])
         if not volume.display_name:
             volume_name = volume.id
         else:
             volume_name = volume.display_name
         message = _('Attaching volume %(vol)s to instance '
                      '%(inst)s on %(dev)s.') % {"vol": volume_name,
                                                 "inst": instance_name,
                                                 "dev": attach.device}
         messages.info(request, message)
         return True
     except:
         redirect = reverse("horizon:project:volumes:index")
         exceptions.handle(request,
                           _('Unable to attach volume.'),
                           redirect=redirect)
Example #25
0
    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)
Example #26
0
    def __init__(self, request, context, *args, **kwargs):
        self._init_images_cache()
        self.request = request
        self.context = context
        super(SetInstanceDetailsAction, self).__init__(
            request, context, *args, **kwargs)
        source_type_choices = [
            ('', _("Select source")),
            ("image_id", _("Boot from image")),
            ("instance_snapshot_id", _("Boot from snapshot")),
        ]
        if base.is_service_enabled(request, 'volume'):
            source_type_choices.append(("volume_id", _("Boot from volume")))

            try:
                if api.nova.extension_supported("BlockDeviceMappingV2Boot",
                                                request):
                    source_type_choices.append(("volume_image_id",
                            _("Boot from image (creates a new volume)")))
            except Exception:
                exceptions.handle(request, _('Unable to retrieve extensions '
                                            'information.'))

            source_type_choices.append(("volume_snapshot_id",
                    _("Boot from volume snapshot (creates a new volume)")))
        self.fields['source_type'].choices = source_type_choices
Example #27
0
    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),
        }

        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:
            stack_preview = api.heat.stack_preview(self.request, **fields)
            request.method = 'GET'
            return self.next_view.as_view()(request,
                                            stack_preview=stack_preview)
        except Exception:
            exceptions.handle(request)
Example #28
0
 def handle(self, request, data):
     try:
         api.nova.server_update(request, data["instance_id"], data["name"])
     except Exception:
         exceptions.handle(request, ignore=True)
         return False
     return True
Example #29
0
    def __init__(self, request, *args, **kwargs):
        super(UpdateInstanceSecurityGroupsAction, self).__init__(request, *args, **kwargs)
        err_msg = _("Unable to retrieve security group list. " "Please try again later.")
        context = args[0]
        instance_id = context.get("instance_id", "")

        default_role_name = self.get_default_role_field_name()
        self.fields[default_role_name] = forms.CharField(required=False)
        self.fields[default_role_name].initial = "member"

        # Get list of available security groups
        all_groups = []
        try:
            all_groups = api.network.security_group_list(request)
        except Exception:
            exceptions.handle(request, err_msg)
        groups_list = [(group.id, group.name) for group in all_groups]

        instance_groups = []
        try:
            instance_groups = api.network.server_security_groups(request, instance_id)
        except Exception:
            exceptions.handle(request, err_msg)
        field_name = self.get_member_field_name("member")
        self.fields[field_name] = forms.MultipleChoiceField(required=False)
        self.fields[field_name].choices = groups_list
        self.fields[field_name].initial = [group.id for group in instance_groups]
Example #30
0
    def _update_project_quota(self, request, data, project_id):
        # Update the project quota.
        nova_data = dict(
            [(key, data[key]) for key in NOVA_QUOTA_FIELDS])
        data['region_id'] = request.user.services_region
        try:
            nova.tenant_quota_update(request, project_id, region=data['region_id'], **nova_data)

            if base.is_service_enabled(request, 'volume'):
                cinder_data = dict([(key, data[key]) for key in
                                    quotas.CINDER_QUOTA_FIELDS])
                cinder.tenant_quota_update(request,
                                           project_id,
                                           region=data['region_id'],
                                           **cinder_data)
            if api.base.is_service_enabled(request, 'network') and \
                    api.neutron.is_quotas_extension_supported(request):
                neutron_data = {}
                for key in NEUTRON_QUOTA_FIELDS:
                    neutron_data[key] = data[key]
                api.neutron.tenant_quota_update(request,
                                                project_id,
                                                region=data['region_id'],
                                                **neutron_data)
        except Exception:
            raise
            exceptions.handle(request, _('Unable to set project quotas.'))
Example #31
0
    def handle(self, request, data):
        meta = api.glance.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']
        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
Example #32
0
    def handle(self, request, data):
        try:
            volume = cinder.volume_get(request, data['volume_id'])
            force = False
            message = _('Creating volume snapshot "%s".') % data['name']
            if volume.status == 'in-use':
                force = True
                message = _('Forcing to create snapshot "%s" '
                            'from attached volume.') % data['name']

            user_snap_total = cinder.volume_snapshot_list(request)

            try:
                if len(user_snap_total) >= USER_QUOTA:
                    message = _(
                        'As per Expostack policy, only %s snapshots are allowed per user in a perticular project.'
                        'Please contact [email protected] for any queries.'
                    ) % USER_QUOTA
                raise messages.error(request, message)
            except:
                return

            snapshot = cinder.volume_snapshot_create(request,
                                                     data['volume_id'],
                                                     data['name'],
                                                     data['description'],
                                                     force=force)

            messages.info(request, message)
            return snapshot
        except Exception as e:
            redirect = reverse("horizon:project:volumes:index")
            msg = _('Unable to create volume snapshot.')
            if e.code == 413:
                msg = _('Requested snapshot would exceed the allowed quota.')
            exceptions.handle(request, msg, redirect=redirect)
Example #33
0
    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)
Example #34
0
 def handle(self, request, context):
     context['admin_state_up'] = (context['admin_state_up'] == 'True')
     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)
Example #35
0
    def handle(self, request, data):
        try:
            if data['node_name'] is not None:
                node = api.tuskar.Node.create(
                    request, data['node_name'], data['cpus'],
                    data['memory_mb'], data['local_gb'],
                    data['prov_mac_address'], data['pm_address'],
                    data['pm_user'], data['pm_password'],
                    data['terminal_port'])
            if node:
                node_id = node.id
            else:
                node_id = None

            # Then, register the Rack, including the node if it exists
            api.tuskar.Rack.create(request, data['name'],
                                   data['resource_class_id'], data['location'],
                                   data['subnet'], [{
                                       'id': node_id
                                   }])

            return True
        except Exception:
            exceptions.handle(request, _("Unable to create rack."))
Example #36
0
    def __init__(self, request, *args, **kwargs):
        super(AddMemberAction, self).__init__(request, *args, **kwargs)

        pool_id_choices = [('', _("Select a Pool"))]
        try:
            pools = api.lbaas.pools_get(request)
        except Exception:
            pools = []
            exceptions.handle(request, _('Unable to retrieve pools list.'))
        pools = sorted(pools, key=lambda pool: pool.name)
        for p in pools:
            pool_id_choices.append((p.id, p.name))
        self.fields['pool_id'].choices = pool_id_choices

        members_choices = []
        try:
            servers, has_more = api.nova.server_list(request)
        except Exception:
            servers = []
            exceptions.handle(request, _('Unable to retrieve instances list.'))

        if len(servers) == 0:
            self.fields['members'].label = _("No servers available. "
                                             "Click Add to cancel.")
            self.fields['members'].required = False
            self.fields['members'].help_text = _("Select members "
                                                 "for this pool ")
            self.fields['pool_id'].required = False
            self.fields['weight'].required = False
            self.fields['protocol_port'].required = False
            return

        for m in servers:
            members_choices.append((m.id, m.name))
        self.fields['members'].choices = sorted(members_choices,
                                                key=lambda member: member[1])
Example #37
0
    def get_help_text(self, extra_context=None):
        extra = {} if extra_context is None else dict(extra_context)
        try:
            extra['usages'] = quotas.tenant_limit_usages(self.request)
            extra['usages_json'] = json.dumps(extra['usages'])
            extra['cinder_enabled'] = \
                base.is_service_enabled(self.request, 'volume')
            flavors = json.dumps([f._info for f in
                                  instance_utils.flavor_list(self.request)])
            extra['flavors'] = flavors
            images = image_utils.get_available_images(
                self.request, self.initial['project_id'], self._images_cache)
            if images is not None:
                attrs = [{'id': i.id,
                          'min_disk': getattr(i, 'min_disk', 0),
                          'min_ram': getattr(i, 'min_ram', 0),
                          'size': functions.bytes_to_gigabytes(i.size)}
                         for i in images]
                extra['images'] = json.dumps(attrs)

        except Exception:
            exceptions.handle(self.request,
                              _("Unable to retrieve quota information."))
        return super(SetInstanceDetailsAction, self).get_help_text(extra)
Example #38
0
    def test_handle_translated(self):
        translated_unicode = u'\u30b3\u30f3\u30c6\u30ca\u30fc\u304c' \
                             u'\u7a7a\u3067\u306f\u306a\u3044\u305f' \
                             u'\u3081\u3001\u524a\u9664\u3067\u304d' \
                             u'\u307e\u305b\u3093\u3002'
        # Japanese translation of:
        # 'Because the container is not empty, it can not be deleted.'

        expected = [
            'error',
            force_text(translated_unicode + '\u2026' + translated_unicode), ''
        ]

        req = self.request
        req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
        try:
            raise exceptions.Conflict(translated_unicode)
        except exceptions.Conflict:
            exceptions.handle(req)

        # The real test here is to make sure the handle method doesn't throw a
        # UnicodeEncodeError, but making sure the message is correct and
        # useful as well.
        self.assertCountEqual(req.horizon['async_messages'], [expected])
Example #39
0
 def handle(self, request, data, **kwargs):
     router_id = self.initial['router_id']
     try:
         route = {
             'nexthop': data['nexthop'],
             'destination': data['destination']
         }
         api.router_static_route_add(request, router_id, route)
         msg = _('Static route added')
         LOG.debug(msg)
         messages.success(request, msg)
         return True
     except neutron_exc.BadRequest as e:
         msg = (_('Invalid format for routes : %s') % e)
         LOG.info(msg)
         messages.error(request, msg)
         redirect = reverse(self.failure_url, args=[router_id])
         exceptions.handle(request, msg, redirect=redirect)
     except Exception as e:
         msg = (_('Failed to add route : %s') % e)
         LOG.info(msg)
         messages.error(request, msg)
         redirect = reverse(self.failure_url, args=[router_id])
         exceptions.handle(request, msg, redirect=redirect)
Example #40
0
    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)

            is_public = (self.enable_public_share_type_creation
                         and data["is_public"])
            share_type = manila.share_type_create(request,
                                                  data["name"],
                                                  spec_dhss,
                                                  is_public=is_public)
            if set_dict:
                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
Example #41
0
 def handle(self, request, data):
     redirect = reverse("horizon:project:access_and_security:"
                        "security_groups:detail", args=[data['id']])
     try:
         rule = api.network.security_group_rule_create(
             request,
             filters.get_int_or_uuid(data['id']),
             data['direction'],
             data['ethertype'],
             data['ip_protocol'],
             data['from_port'],
             data['to_port'],
             data['cidr'],
             data['security_group'])
         messages.success(request,
                          _('Successfully added rule: %s')
                          % six.text_type(rule))
         return rule
     except exceptions.Conflict as error:
         exceptions.handle(request, error, redirect=redirect)
     except Exception:
         exceptions.handle(request,
                           _('Unable to add rule to security group.'),
                           redirect=redirect)
Example #42
0
 def _create_network(self, request, data):
     try:
         params = {
             'name': data['net_name'],
             'admin_state_up': (data['admin_state'] == 'True'),
             'shared': data['shared']
         }
         if api.neutron.is_port_profiles_supported():
             params['net_profile_id'] = data['net_profile_id']
         network = api.neutron.network_create(request, **params)
         self.context['net_id'] = network.id
         msg = (_('Network "%s" was successfully created.') %
                network.name_or_id)
         LOG.debug(msg)
         return network
     except Exception as e:
         msg = (_('Failed to create network "%(network)s": %(reason)s') % {
             "network": data['net_name'],
             "reason": e
         })
         LOG.info(msg)
         redirect = self.get_failure_url()
         exceptions.handle(request, msg, redirect=redirect)
         return False
    def get_initial(self):
        initial = super(UpdateProjectView, self).get_initial()

        project_id = self.kwargs['tenant_id']
        initial['project_id'] = project_id

        try:
            # get initial project info
            project_info = api.keystone.tenant_get(self.request,
                                                   project_id,
                                                   admin=True)
            for field in PROJECT_INFO_FIELDS:
                initial[field] = getattr(project_info, field, None)

            # get initial project quota
            quota_data = quotas.get_tenant_quota_data(self.request,
                                                      tenant_id=project_id)
            for field in quotas.QUOTA_FIELDS:
                initial[field] = quota_data.get(field).limit
        except:
            exceptions.handle(self.request,
                              _('Unable to retrieve project details.'),
                              redirect=reverse(INDEX_URL))
        return initial
Example #44
0
    def __init__(self, request, context, *args, **kwargs):
        super(CreateSubnetInfoAction, self).__init__(request, context, *args,
                                                     **kwargs)
        if not settings.OPENSTACK_NEUTRON_NETWORK['enable_ipv6']:
            self.fields['ip_version'].widget = forms.HiddenInput()
            self.fields['ip_version'].initial = 4

        try:
            if api.neutron.is_extension_supported(request,
                                                  'subnet_allocation'):
                self.fields['subnetpool'].choices = \
                    self.get_subnetpool_choices(request)
            else:
                self.hide_subnetpool_choices()
        except Exception:
            self.hide_subnetpool_choices()
            msg = _('Unable to initialize subnetpools')
            exceptions.handle(request, msg)
        if len(self.fields['subnetpool'].choices) > 1:
            # Pre-populate prefixlen choices to satisfy Django
            # ChoiceField Validation. This is overridden w/data from
            # subnetpool on select.
            self.fields['prefixlen'].choices = \
                zip(list(range(0, 128 + 1)),
                    list(range(0, 128 + 1)))
            # Populate data-fields for switching the prefixlen field
            # when user selects a subnetpool other than
            # "Provider default pool"
            for (id_, name) in self.fields['subnetpool'].choices:
                if not id_:
                    continue
                key = 'data-subnetpool-' + id_
                self.fields['prefixlen'].widget.attrs[key] = \
                    _('Network Mask')
        else:
            self.hide_subnetpool_choices()
Example #45
0
    def __init__(self, request, *args, **kwargs):
        super(UpdateVip, self).__init__(request, *args, **kwargs)

        pool_id_choices = []
        try:
            tenant_id = request.user.tenant_id
            pools = api.lbaas.pool_list(request, tenant_id=tenant_id)
        except Exception:
            pools = []
            exceptions.handle(request,
                              _('Unable to retrieve pools list.'))
        pools = sorted(pools,
                       key=lambda pool: pool.name)
        for p in pools:
            if (p.vip_id is None) or (p.id == kwargs['initial']['pool_id']):
                pool_id_choices.append((p.id, p.name))
        self.fields['pool_id'].choices = pool_id_choices

        session_persistence_choices = []
        for mode in ('SOURCE_IP', 'HTTP_COOKIE', 'APP_COOKIE'):
            session_persistence_choices.append((mode, mode))
        session_persistence_choices.append(('', _('No session persistence')))
        self.fields[
            'session_persistence'].choices = session_persistence_choices
Example #46
0
    def get_data(self):
        try:
            cluster_id = self.kwargs['cluster_id']
            cluster = api.trove.cluster_get(self.request, cluster_id)
        except Exception:
            redirect = reverse('horizon:project:database_clusters:index')
            msg = _('Unable to retrieve details '
                    'for database cluster: %s') % cluster_id
            exceptions.handle(self.request, msg, redirect=redirect)
        try:
            cluster.full_flavor = api.trove.flavor_get(
                self.request, cluster.instances[0]["flavor"]["id"])
        except Exception:
            LOG.error('Unable to retrieve flavor details'
                      ' for database cluster: %s' % cluster_id)
        cluster.num_instances = len(cluster.instances)

        # Todo(saurabhs) Set mgmt_url to dispaly Mgmt Console URL on
        # cluster details page
        # for instance in cluster.instances:
        #   if instance['type'] == "master":
        #       cluster.mgmt_url = "https://%s:5450/webui" % instance['ip'][0]

        return cluster
Example #47
0
    def handle(self, request, data):
        prefix_length = len(self.param_prefix)
        params_list = [(k[prefix_length:], v) for (k, v) in data.items()
                       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),
            'files': json.loads(data.get('parameters')).get('files'),
            'template': json.loads(data.get('parameters')).get('template')
        }
        if data.get('password'):
            fields['password'] = data.get('password')

        if data.get('environment_data'):
            fields['environment'] = data.get('environment_data')

        try:
            api.heat.stack_create(self.request, **fields)
            messages.info(request, _("Stack creation started."))
            return True
        except Exception:
            exceptions.handle(request)
Example #48
0
    def get_instances_data(self):
        try:
            marker = self.request.GET.get(
                tables.AppTable._meta.pagination_param, None)

            instances, self._has_more = api.nova.server_list(self.request,
                                                             search_opts={
                                                                 'marker':
                                                                 marker,
                                                                 'paginate':
                                                                 True
                                                             })

            pods = self._get_pods()
            print("===============pods=================")
            print(pods)
            print("================================")
            return pods
        except Exception:
            self._has_more = False
            error_message = _('Unable to get instances')
            exceptions.handle(self.request, error_message)

            return []
Example #49
0
    def handle(self, request, context):
        custom_script = context.get('customization_script', '')

        # Determine volume mapping options
        if context.get('volume_type', None):
            if (context['delete_on_terminate']):
                del_on_terminate = 1
            else:
                del_on_terminate = 0
            mapping_opts = ("%s::%s" %
                            (context['volume_id'], del_on_terminate))
            dev_mapping = {context['device_name']: mapping_opts}
        else:
            dev_mapping = None

        netids = context.get('network_id', None)
        if netids:
            nics = [{"net-id": netid, "v4-fixed-ip": ""} for netid in netids]
        else:
            nics = None

        try:
            api.nova.server_create(request,
                                   context['name'],
                                   context['source_id'],
                                   context['flavor'],
                                   context['keypair_id'],
                                   normalize_newlines(custom_script),
                                   context['security_group_ids'],
                                   dev_mapping,
                                   nics=nics,
                                   instance_count=int(context['count']))
            return True
        except:
            exceptions.handle(request)
            return False
Example #50
0
    def _get_volume_types(self):
        try:
            volume_types = cinder.volume_type_list(self.request)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve volume type list.'))

        # check if we have default volume type so we can present the
        # description of no volume type differently
        no_type_description = None
        if self.default_vol_type is None:
            message = \
                _("If \"No volume type\" is selected, the volume will be "
                  "created without a volume type.")

            no_type_description = encoding.force_text(message)

        type_descriptions = [{'name': 'no_type',
                              'description': no_type_description}] + \
                            [{'name': type.name,
                              'description': getattr(type, "description", "")}
                             for type in volume_types]

        return json.dumps(type_descriptions)
    def _get_neutron_usage(self, limits, resource_name):
        resource_map = {
            'floatingip': {
                'api': api.neutron.tenant_floating_ip_list,
                'limit_name': 'totalFloatingIpsUsed',
                'message': _('Unable to retrieve floating IP addresses.')
            },
            'security_group': {
                'api': api.neutron.security_group_list,
                'limit_name': 'totalSecurityGroupsUsed',
                'message': _('Unable to retrieve security groups.')
            }
        }

        resource = resource_map[resource_name]
        try:
            method = resource['api']
            current_used = len(method(self.request))
        except Exception:
            current_used = 0
            msg = resource['message']
            exceptions.handle(self.request, msg)

        limits[resource['limit_name']] = current_used
Example #52
0
    def prepare_source_fields_if_volume_specified(self, request):
        self.fields['availability_zone'].choices = \
            availability_zones(request)
        volume = None
        try:
            volume = self.get_volume(request, request.GET["volume_id"])
        except Exception:
            msg = _('Unable to load the specified volume. %s')
            exceptions.handle(request, msg % request.GET['volume_id'])

        if volume is not None:
            self.fields['name'].initial = volume.name
            self.fields['description'].initial = volume.description
            min_vol_size = volume.size
            size_help_text = (_('Volume size must be equal to or greater '
                                'than the origin volume size (%s)') %
                              filesizeformat(volume.size))
            self.fields['size'].initial = min_vol_size
            self.fields['size'].help_text = size_help_text
            self.fields['volume_source'].choices = ((volume.id, volume), )
            self.fields['type'].initial = volume.type
            del self.fields['snapshot_source']
            del self.fields['image_source']
            del self.fields['volume_source_type']
Example #53
0
    def handle(self, request, data):
        volume_id = self.initial['id']

        try:
            # 'aki','ari','ami' container formats are supported by glance,
            # but they need matching disk format to use.
            # Glance usually uses 'bare' for other disk formats except
            # amazon's. Please check the comment in CreateImageForm class
            cinder.volume_upload_to_image(request, volume_id, data['force'],
                                          data['image_name'],
                                          DEFAULT_CONTAINER_FORMAT,
                                          data['disk_format'])
            message = _(
                'Successfully sent the request to upload volume to image '
                'for volume: "%s"') % data['name']
            messages.info(request, message)

            return True
        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            error_message = _(
                'Unable to upload volume to image for volume: "%s"') \
                % data['name']
            exceptions.handle(request, error_message, redirect=redirect)
Example #54
0
    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 settings.ENFORCE_PASSWORD_CHECK:
            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:
            response = api.keystone.user_update_password(request,
                                                         user_id,
                                                         password,
                                                         admin=False)
            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 as exc:
            response = exceptions.handle(request, ignore=True)
            match = re.match((r'The password does not match the '
                              r'requirements:(.*?) [(]HTTP 400[)]'), str(exc),
                             re.UNICODE | re.MULTILINE)
            if match:
                info = match.group(1)
                messages.error(
                    request,
                    _('The password does not match the '
                      'requirements: %s') % info)
            else:
                messages.error(request,
                               _('Unable to update the user password.'))

        if isinstance(response, http.HttpResponse):
            return response

        return True
Example #55
0
    def handle(self, request, data):
        host_id = data['host_id']

        lvgs = data['lvg'][:]

        # GUI only allows one disk to be picked
        if data['pv_type'] == 'disk':
            data['disk_or_part_uuid'] = data['disks'][:]
        else:
            data['disk_or_part_uuid'] = data['partitions'][:]

        data['ilvg_uuid'] = lvgs

        try:
            del data['host_id']
            del data['disks']
            del data['hostname']
            del data['lvg']
            del data['partitions']

            stor = stx_api.sysinv.host_pv_create(request, **data)

            msg = _('Physical volume was successfully created.')
            messages.success(request, msg)
            return stor
        except exc.ClientException as ce:
            msg = _('Failed to create physical volume.')

            # Allow REST API error message to appear on UI
            w_msg = str(ce)
            if ('Warning:' in w_msg):
                LOG.info(ce)
                messages.warning(request, w_msg.split(':', 1)[-1])
            else:
                LOG.error(ce)
                messages.error(request, w_msg)

            # Redirect to host details pg
            redirect = reverse(self.failure_url, args=[host_id])
            return shortcuts.redirect(redirect)
        except Exception as e:
            msg = _('Failed to create physical volume.')
            LOG.error(e)

            # if not a rest API error, throw default
            redirect = reverse(self.failure_url, args=[host_id])
            return exceptions.handle(request, message=e, redirect=redirect)
Example #56
0
    def handle(self, request, data):
        # create the project
        try:
            desc = data['description']
            self.object = api.keystone.tenant_create(request,
                                                     name=data['name'],
                                                     description=desc,
                                                     enabled=data['enabled'])
        except:
            exceptions.handle(request, ignore=True)
            return False

        project_id = self.object.id

        # update project members
        users_to_add = 0
        try:
            available_roles = api.keystone.role_list(request)

            # count how many users are to be added
            for role in available_roles:
                role_list = data["role_" + role.id]
                users_to_add += len(role_list)
            # add new users to project
            for role in available_roles:
                role_list = data["role_" + role.id]
                users_added = 0
                for user in role_list:
                    api.keystone.add_tenant_user_role(request,
                                                      project=project_id,
                                                      user=user,
                                                      role=role.id)
                    users_added += 1
                users_to_add -= users_added
        except:
            exceptions.handle(request, _('Failed to add %s project members '
                                         'and set project quotas.'
                                         % users_to_add))

        # Update the project quota.
        nova_data = dict([(key, data[key]) for key in NOVA_QUOTA_FIELDS])
        try:
            nova.tenant_quota_update(request, project_id, **nova_data)

            if is_service_enabled(request, 'volume'):
                cinder_data = dict([(key, data[key]) for key in
                                    CINDER_QUOTA_FIELDS])
                cinder.tenant_quota_update(request,
                                           project_id,
                                           **cinder_data)
        except:
            exceptions.handle(request, _('Unable to set project quotas.'))
        return True
Example #57
0
    def __init__(self, request, *args, **kwargs):
        super(UpdatePortInfoAction, self).__init__(request, *args, **kwargs)
        try:
            if api.neutron.is_extension_supported(request, 'binding'):
                neutron_settings = getattr(settings,
                                           'OPENSTACK_NEUTRON_NETWORK', {})
                supported_vnic_types = neutron_settings.get(
                    'supported_vnic_types', ['*'])
                if supported_vnic_types:
                    if supported_vnic_types == ['*']:
                        vnic_type_choices = api.neutron.VNIC_TYPES
                    else:
                        vnic_type_choices = [
                            vnic_type for vnic_type in api.neutron.VNIC_TYPES
                            if vnic_type[0] in supported_vnic_types
                        ]
                    self.fields['binding__vnic_type'] = (
                        forms.ThemableChoiceField(
                            choices=vnic_type_choices,
                            label=_("Binding: VNIC Type"),
                            required=False))
        except Exception:
            msg = _("Unable to verify the VNIC types extension in Neutron")
            exceptions.handle(self.request, msg)

        try:
            if api.neutron.is_extension_supported(request, 'mac-learning'):
                self.fields['mac_state'] = forms.BooleanField(
                    label=_("MAC Learning State"),
                    initial=False,
                    required=False)
        except Exception:
            msg = _("Unable to retrieve MAC learning state")
            exceptions.handle(self.request, msg)

        try:
            if api.neutron.is_extension_supported(request, 'port-security'):
                self.fields['port_security_enabled'] = forms.BooleanField(
                    label=_("Port Security"),
                    required=False,
                    widget=forms.CheckboxInput(
                        attrs={
                            'class': 'switchable',
                            'data-slug': 'port_security_enabled',
                            'data-hide-tab':
                            'update_port__update_security_groups',
                            'data-hide-on-checked': 'false'
                        }))
        except Exception:
            msg = _("Unable to retrieve port security state")
            exceptions.handle(self.request, msg)
Example #58
0
    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

            del data['journal_locations']
            del data['id']

            # 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)
Example #59
0
    def __init__(self, request, *args, **kwargs):
        super(CreatePort, self).__init__(request, *args, **kwargs)

        try:
            if api.neutron.is_extension_supported(request, 'binding'):
                neutron_settings = getattr(settings,
                                           'OPENSTACK_NEUTRON_NETWORK', {})
                supported_vnic_types = neutron_settings.get(
                    'supported_vnic_types', ['*'])
                if supported_vnic_types:
                    if supported_vnic_types == ['*']:
                        vnic_type_choices = VNIC_TYPES
                    else:
                        vnic_type_choices = [
                            vnic_type for vnic_type in VNIC_TYPES
                            if vnic_type[0] in supported_vnic_types
                        ]

                    self.fields['binding__vnic_type'] = \
                        forms.ThemableChoiceField(
                            choices=vnic_type_choices,
                            label=_("Binding: VNIC Type"),
                            help_text=_(
                                "The VNIC type that is bound to the neutron "
                                "port"),
                            required=False)
        except Exception:
            msg = _("Unable to verify the VNIC types extension in Neutron")
            exceptions.handle(self.request, msg)

        try:
            if api.neutron.is_extension_supported(request, 'mac-learning'):
                self.fields['mac_state'] = forms.BooleanField(
                    label=_("MAC Learning State"),
                    initial=False,
                    required=False)
        except Exception:
            msg = _("Unable to retrieve MAC learning state")
            exceptions.handle(self.request, msg)

        try:
            if api.neutron.is_extension_supported(request, 'port-security'):
                self.fields['port_security_enabled'] = forms.BooleanField(
                    label=_("Port Security"),
                    help_text=_("Enable anti-spoofing rules for the port"),
                    initial=True,
                    required=False)
        except Exception:
            msg = _("Unable to retrieve port security state")
            exceptions.handle(self.request, msg)
Example #60
0
    def get_data(self):
        instances = []
        marker = self.request.GET.get(
            project_tables.AdminInstancesTable._meta.pagination_param, None)
        try:
            instances, self._more = api.nova.server_list(
                                        self.request,
                                        search_opts={'marker': marker,
                                                     'paginate': True},
                                        all_tenants=True)
        except Exception:
            self._more = False
            exceptions.handle(self.request,
                              _('Unable to retrieve instance list.'))
        if instances:
            # Gather our flavors to correlate against IDs
            try:
                flavors = api.nova.flavor_list(self.request)
            except Exception:
                # If fails to retrieve flavor list, creates an empty list.
                flavors = []

            # Gather our tenants to correlate against IDs
            try:
                tenants, has_more = api.keystone.tenant_list(self.request)
            except Exception:
                tenants = []
                msg = _('Unable to retrieve instance project information.')
                exceptions.handle(self.request, msg)

            full_flavors = SortedDict([(f.id, f) for f in flavors])
            tenant_dict = SortedDict([(t.id, t) for t in tenants])
            # Loop through instances to get flavor and tenant info.
            for inst in instances:
                flavor_id = inst.flavor["id"]
                try:
                    if flavor_id in full_flavors:
                        inst.full_flavor = full_flavors[flavor_id]
                    else:
                        # If the flavor_id is not in full_flavors list,
                        # gets it via nova api.
                        inst.full_flavor = api.nova.flavor_get(
                                            self.request, flavor_id)
                except Exception:
                    msg = _('Unable to retrieve instance size information.')
                    exceptions.handle(self.request, msg)
                tenant = tenant_dict.get(inst.tenant_id, None)
                inst.tenant_name = getattr(tenant, "name", None)
        return instances