예제 #1
0
파일: forms.py 프로젝트: artofwar/stack
    def handle(self, request, data):
        image_id = data['image_id']
        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:
            vol = api.volume_attach(request,
                                    data['volume_id'],
                                    data['instance'],
                                    data.get('device', ''))
            vol_name = api.volume_get(request, data['volume_id']).display_name

            message = _('Attaching volume %(vol)s to instance '
                         '%(inst)s on %(dev)s.') % {"vol": vol_name,
                                                    "inst": instance_name,
                                                    "dev": vol.device}
            messages.info(request, message)
            return True
        except:
            redirect = reverse("horizon:nova:volumes:index")
            exceptions.handle(request,
                              _('Unable to attach volume.'),
                              redirect=redirect)


        try:
            image = api.image_update(request, image_id, **meta)
            messages.success(request, _('Image was successfully updated.'))
            return image
        except:
            exceptions.handle(request, error_updating % image_id)
예제 #2
0
파일: tables.py 프로젝트: CLisa/horizon
    def single(self, table, request, instance_id):
        try:
            # target_id is port_id for Neutron and instance_id for Nova Network
            # (Neutron API wrapper returns a 'portid_fixedip' string)
            targets = api.network.floating_ip_target_list_by_instance(
                request, instance_id)

            target_ids = [t.split('_')[0] for t in targets]

            fips = [fip for fip in api.network.tenant_floating_ip_list(request)
                    if fip.port_id in target_ids]
            # Removing multiple floating IPs at once doesn't work, so this pops
            # off the first one.
            if fips:
                fip = fips.pop()
                api.network.floating_ip_disassociate(request,
                                                     fip.id, fip.port_id)
                messages.success(request,
                                 _("Successfully disassociated "
                                   "floating IP: %s") % fip.ip)
            else:
                messages.info(request, _("No floating IPs to disassociate."))
        except Exception:
            exceptions.handle(request,
                              _("Unable to disassociate floating IP."))
        return shortcuts.redirect("horizon:project:instances:index")
 def handle(self, request, 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)
예제 #4
0
    def get_data(self):
        tenants = []
        domain_context = self.request.session.get('domain_context', None)

        if policy.check((("identity", "identity:list_projects"),),
                        self.request):
            try:
                tenants, _more = keystone_api.tenant_list(
                    self.request,
                    domain=domain_context,
                    paginate=False)
            except Exception:
                exceptions.handle(self.request,
                                  _("Unable to retrieve project list."))
        elif policy.check((("identity", "identity:list_user_projects"),),
                          self.request):
            try:
                tenants, _more = keystone_api.tenant_list(
                    self.request,
                    user=self.request.user.id,
                    paginate=False,
                    admin=False)
            except Exception:
                exceptions.handle(self.request,
                                  _("Unable to retrieve project information."))
        else:
            msg = \
                _("Insufficient privilege level to view project information.")
            messages.info(self.request, msg)
        return tenants
예제 #5
0
파일: forms.py 프로젝트: CCI-MOC/horizon
    def handle(self, request, data):
        group_id = self.initial['group_id']
        name = self.initial['name']
        search_opts = {'group_id': group_id}

        try:
            # get list of assigned volumes
            assigned_vols = []
            volumes = cinder.volume_list(request,
                                         search_opts=search_opts)
            for volume in volumes:
                assigned_vols.append(volume.id)

            cinder.group_update(request, group_id,
                                remove_volumes=assigned_vols)

            message = _('Removing volumes from volume group "%s"') % name
            messages.info(request, message)
            return True

        except Exception:
            redirect = reverse(self.failure_url)
            exceptions.handle(request,
                              _('Errors occurred in removing volumes '
                                'from group.'),
                              redirect=redirect)
예제 #6
0
    def handle(self, request, data):
        instance_id = self.initial.get("instance_id", None)
        volume_choices = dict(self.fields['volume'].choices)
        volume = volume_choices.get(data['volume'],
                                    _("Unknown volume (None)"))
        volume_id = data.get('volume')

        device = data.get('device') or None

        try:
            attach = api.nova.instance_volume_attach(request,
                                                     volume_id,
                                                     instance_id,
                                                     device)

            message = _('Attaching volume %(vol)s to instance '
                        '%(inst)s on %(dev)s.') % {"vol": volume,
                                                   "inst": instance_id,
                                                   "dev": attach.device}
            messages.info(request, message)
        except Exception:
            redirect = reverse('horizon:project:instances:index')
            exceptions.handle(request,
                              _('Unable to attach volume.'),
                              redirect=redirect)
        return True
예제 #7
0
파일: forms.py 프로젝트: jaisins/horizon
    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:
            error_message = _(
                'Unable to upload volume to image for volume: "%s"') \
                % data['name']
            exceptions.handle(request, error_message)

            return False
예제 #8
0
    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']
        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
예제 #9
0
파일: views.py 프로젝트: openstack/horizon
    def get_data(self):
        if not policy.check((("image", "get_images"),), self.request):
            msg = _("Insufficient privilege level to retrieve image list.")
            messages.info(self.request, msg)
            return []
        prev_marker = self.request.GET.get(images_tables.ImagesTable._meta.prev_pagination_param, None)

        if prev_marker is not None:
            marker = prev_marker
        else:
            marker = self.request.GET.get(images_tables.ImagesTable._meta.pagination_param, None)
        reversed_order = prev_marker is not None
        try:
            images, self._more, self._prev = api.glance.image_list_detailed(
                self.request,
                marker=marker,
                paginate=True,
                sort_dir="asc",
                sort_key="name",
                reversed_order=reversed_order,
            )
        except Exception:
            images = []
            self._prev = self._more = False
            exceptions.handle(self.request, _("Unable to retrieve images."))
        return images
예제 #10
0
파일: forms.py 프로젝트: haminhcong/horizon
    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),
            '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_update(self.request, stack_id=stack_id, **fields)
            messages.info(request, _("Stack update started."))
            return True
        except Exception:
            exceptions.handle(request)
예제 #11
0
    def handle(self, request, data):
        try:
            snapshot_strategy = cinder.volume_snapshot_strategy_create(request,
                                                              data['volume_id'],
                                                              data['name'],
                                                              data['snapshot_at'],
                                                              data['keep_last_sunday'],
                                                              data['max_keep_number'],
                                                              data['status'])
            message = _('Creating volume snapshot strategy "%s".') % data['name']
            messages.info(request, message)

            # operation log
            config = _('Strategy ID: %s Strategy Name: %s') %(snapshot_strategy.id, data['name'])
            api.logger.Logger(request).create(resource_type='strategy', action_name='Create Snapshot Strategy',
                                                       resource_name='Strategy', config=config,
                                                       status='Success')

            return snapshot_strategy
        except Exception as e:
            redirect = reverse("horizon:storage:snapshots:strategies_tab")
            msg = _('Unable to create volume snapshot strategy.')
            code = getattr(e, 'code', None)
            if code is not None and code == 413:
                msg = _('Requested snapshot would exceed the allowed quota.')
            exceptions.handle(request,
                              msg,
                              redirect=redirect)

            # operation log
            api.logger.Logger(request).create(resource_type='strategy', action_name='Create Snapshot Strategy',
                                                       resource_name='Strategy', config=msg,
                                                       status='Error')
예제 #12
0
파일: base.py 프로젝트: sdsingh/horizon
    def take_action(self, action_name, obj_id=None, obj_ids=None):
        """
        Locates the appropriate action and routes the object
        data to it. The action should return an HTTP redirect
        if successful, or a value which evaluates to ``False``
        if unsuccessful.
        """
        # See if we have a list of ids
        obj_ids = obj_ids or self.request.POST.getlist("object_ids")
        action = self.base_actions.get(action_name, None)
        if not action or action.method != self.request.method:
            # We either didn't get an action or we're being hacked. Goodbye.
            return None

        # Meanhile, back in Gotham...
        if not action.requires_input or obj_id or obj_ids:
            if obj_id:
                obj_id = self.sanitize_id(obj_id)
            if obj_ids:
                obj_ids = [self.sanitize_id(i) for i in obj_ids]
            # Single handling is easy
            if not action.handles_multiple:
                response = action.single(self, self.request, obj_id)
            # Otherwise figure out what to pass along
            else:
                # Preference given to a specific id, since that implies
                # the user selected an action for just one row.
                if obj_id:
                    obj_ids = [obj_id]
                response = action.multiple(self, self.request, obj_ids)
            return response
        elif action and action.requires_input and not (obj_id or obj_ids):
            messages.info(self.request, _("Please select a row before taking that action."))
        return None
예제 #13
0
파일: views.py 프로젝트: 28607895/horizon
    def get_data(self):
        domains = []
        domain_id = api.keystone.get_effective_domain_id(self.request)

        if policy.check((("identity", "identity:list_domains"),),
                        self.request):
            try:
                if domain_id:
                    domain = api.keystone.domain_get(self.request, domain_id)
                    domains.append(domain)
                else:
                    domains = api.keystone.domain_list(self.request)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve domain list.'))
        elif policy.check((("identity", "identity:get_domain"),),
                          self.request):
            try:
                domain = api.keystone.domain_get(self.request, domain_id)
                domains.append(domain)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve domain information.'))
        else:
            msg = _("Insufficient privilege level to view domain information.")
            messages.info(self.request, msg)
        return domains
예제 #14
0
    def handle(self, request, data):
        snapshot_id = self.initial['snapshot_id']
        try:
            api.cinder.volume_snapshot_update(request,
                                          snapshot_id,
                                          data['name'],
                                          data['description'])

            message = _('Updating volume snapshot "%s"') % data['name']
            messages.info(request, message)

            # operation log
            config = '\n'.join(['Snap ID: '+ snapshot_id, 'Snap Name: ' + data['name']])
            api.logger.Logger(request).create(resource_type='snapshot', action_name='Update Snapshot',
                                                       resource_name='Snapshot', config=config,
                                                       status='Success')
            return True
        except Exception:
            redirect = reverse("horizon:storage:volumes:index")
            exceptions.handle(request,
                              _('Unable to update volume snapshot.'),
                              redirect=redirect)

            # operation log
            api.logger.Logger(request).create(resource_type='snapshot', action_name='Update Snapshot',
                                                       resource_name='Snapshot', config='Unable to update volume snapshot',
                                                       status='Error')
예제 #15
0
파일: views.py 프로젝트: amotoki/horizon
    def get_data(self):
        groups = []
        filters = self.get_filters()
        self._needs_filter_first = False

        if policy.check((("identity", "identity:list_groups"),),
                        self.request):

            # If filter_first is set and if there are not other filters
            # selected, then search criteria must be provided and
            # return an empty list
            filter_first = getattr(settings, 'FILTER_DATA_FIRST', {})
            if filter_first.get('identity.groups', False) \
                    and len(filters) == 0:
                self._needs_filter_first = True
                return groups

            domain_id = identity.get_domain_id_for_operation(self.request)
            try:
                groups = api.keystone.group_list(self.request,
                                                 domain=domain_id,
                                                 filters=filters)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve group list.'))
        else:
            msg = _("Insufficient privilege level to view group information.")
            messages.info(self.request, msg)
        return groups
예제 #16
0
 def get_data(self):
     tenants = []
     marker = self.request.GET.get(
         project_tables.TenantsTable._meta.pagination_param, None)
     domain_context = self.request.session.get('domain_context', None)
     self._more = False
     if policy.check((("sdscontroller", "sdscontroller:list_projects"),),
                     self.request):
         try:
             tenants, self._more = api.keystone.tenant_list(
                 self.request,
                 domain=domain_context,
                 paginate=True,
                 marker=marker)
         except Exception:
             exceptions.handle(self.request,
                               _("Unable to retrieve project list."))
     elif policy.check((("sdscontroller", "sdscontroller:list_user_projects"),),
                       self.request):
         try:
             tenants, self._more = api.keystone.tenant_list(
                 self.request,
                 user=self.request.user.id,
                 paginate=True,
                 marker=marker,
                 admin=False)
         except Exception:
             exceptions.handle(self.request,
                               _("Unable to retrieve project information."))
     else:
         msg = \
             _("Insufficient privilege level to view project information.")
         messages.info(self.request, msg)
     return tenants
예제 #17
0
파일: views.py 프로젝트: amotoki/horizon
    def get_data(self):
        domains = []
        domain_context = self.request.session.get('domain_context')

        if policy.check((
            ("identity", "identity:list_domains"),
        ), self.request) and not domain_context:
            try:
                domains = api.keystone.domain_list(self.request)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve domain list.'))
        elif policy.check((
            ("identity", "identity:get_domain"),
        ), self.request):
            try:
                domain_id = identity.get_domain_id_for_operation(self.request)
                domain = api.keystone.domain_get(self.request, domain_id)
                domains.append(domain)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve domain information.'))
        else:
            msg = _("Insufficient privilege level to view domain information.")
            messages.info(self.request, msg)
        return domains
예제 #18
0
파일: forms.py 프로젝트: deponian/horizon
    def handle(self, request, data):
        instance_id = self.initial.get("instance_id", None)
        volume_choices = dict(self.fields['volume'].choices)
        volume = volume_choices.get(data['volume'],
                                    _("Unknown volume (None)"))
        volume_id = data.get('volume')

        device = data.get('device') or None

        try:
            attach = api.nova.instance_volume_attach(request,
                                                     volume_id,
                                                     instance_id,
                                                     device)

            message = _('Attaching volume %(vol)s to instance '
                        '%(inst)s on %(dev)s.') % {"vol": volume,
                                                   "inst": instance_id,
                                                   "dev": attach.device}
            messages.info(request, message)
        except Exception as ex:
            redirect = reverse('horizon:project:instances:index')
            if isinstance(ex, api.nova.VolumeMultiattachNotSupported):
                # Use the specific error from the specific message.
                msg = six.text_type(ex)
            else:
                # Use a generic error message.
                msg = _('Unable to attach volume.')
            exceptions.handle(request, msg, redirect=redirect)
        return True
예제 #19
0
파일: forms.py 프로젝트: CCI-MOC/horizon
    def handle(self, request, data):
        group_id = self.initial['group_id']
        try:
            message = _('Creating group snapshot "%s".') \
                % data['name']
            snapshot = cinder.group_snapshot_create(request,
                                                    group_id,
                                                    data['name'],
                                                    data['description'])

            messages.info(request, message)
            return snapshot
        except Exception as e:
            redirect = reverse("horizon:project:volume_groups:index")
            msg = _('Unable to create group snapshot.')
            if e.code == 413:
                msg = _('Requested snapshot would exceed the allowed quota.')
            else:
                search_opts = {'group_id': group_id}
                volumes = cinder.volume_list(request,
                                             search_opts=search_opts)
                if not volumes:
                    msg = _('Unable to create snapshot. '
                            'group must contain volumes.')

            exceptions.handle(request,
                              msg,
                              redirect=redirect)
예제 #20
0
    def handle(self, request, data):
        volume_id = self.initial['volume_id']
        try:
            cinder.volume_update(request, volume_id, data['name'],
                                 data['description'])
        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            exceptions.handle(request,
                              _('Unable to update volume.'),
                              redirect=redirect)

        # only update bootable flag if modified
        make_bootable = data['bootable']
        if make_bootable != self.initial['bootable']:
            try:
                cinder.volume_set_bootable(request, volume_id, make_bootable)
            except Exception:
                redirect = reverse("horizon:project:volumes:index")
                exceptions.handle(request,
                                  _('Unable to set bootable flag on volume.'),
                                  redirect=redirect)

        message = _('Updating volume "%s"') % data['name']
        messages.info(request, message)
        return True
예제 #21
0
파일: forms.py 프로젝트: cloudiaan/horizon
    def handle(self, request, data):
        cgroup_id = self.initial['cgroup_id']
        name = self.initial['name']
        search_opts = {'consistencygroup_id': cgroup_id}

        try:
            # get list of assigned volumes
            assigned_vols = []
            volumes = cinder.volume_list(request,
                                         search_opts=search_opts)
            for volume in volumes:
                assigned_vols.append(volume.id)

            assigned_vols_str = ",".join(assigned_vols)
            cinder.volume_cgroup_update(request,
                                        cgroup_id,
                                        remove_vols=assigned_vols_str)

            message = _('Removing volumes from volume consistency '
                        'group "%s"') % name
            messages.info(request, message)
            return True

        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            exceptions.handle(request, _('Errors occurred in removing volumes '
                                         'from consistency group.'),
                              redirect=redirect)
예제 #22
0
파일: views.py 프로젝트: deponian/horizon
    def get_data(self):
        roles = []
        filters = self.get_filters()

        self._needs_filter_first = False

        if policy.check((("identity", "identity:list_roles"),),
                        self.request):

            # If filter_first is set and if there are not other filters
            # selected, then search criteria must be provided
            # and return an empty list
            filter_first = getattr(settings, 'FILTER_DATA_FIRST', {})
            if filter_first.get('identity.roles', False) and len(filters) == 0:
                self._needs_filter_first = True
                return roles

            try:
                roles = api.keystone.role_list(self.request,
                                               filters=filters)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve roles list.'))
        else:
            msg = _("Insufficient privilege level to view role information.")
            messages.info(self.request, msg)
        return roles
예제 #23
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        # do not profile ajax requests for now
        if not self.is_enabled(request) or request.is_ajax():
            return None

        trace_info = profiler_utils.signed_unpack(
            request.META.get('X-Trace-Info'),
            request.META.get('X-Trace-HMAC'),
            self.hmac_keys)

        if not self._trace_is_valid(trace_info):
            return None

        profiler.init(**trace_info)
        info = {
            'request': {
                'path': request.path,
                'query': request.GET.urlencode(),
                'method': request.method,
                'scheme': request.scheme
            }
        }
        with api.traced(request, view_func.__name__, info) as trace_id:
            response = view_func(request, *view_args, **view_kwargs)
            url = reverse('horizon:developer:profiler:index')
            message = safestring.mark_safe(
                _('Traced with id %(id)s. Go to <a href="%(url)s">page</a>') %
                {'id': trace_id, 'url': url})
            messages.info(request, message)
            return response
예제 #24
0
    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]

        # api requires non-empty device name or None
        device = data.get('device') or None

        try:
            attach = api.nova.instance_volume_attach(request,
                                                     data['volume_id'],
                                                     data['instance'],
                                                     device)
            volume = cinder.volume_get(request, data['volume_id'])
            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 Exception:
            redirect = reverse("horizon:sdscontroller:sds_volumes:index")
            exceptions.handle(request,
                              _('Unable to attach volume.'),
                              redirect=redirect)
예제 #25
0
    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))
예제 #26
0
    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"))
예제 #27
0
파일: forms.py 프로젝트: cloudiaan/horizon
    def handle(self, request, data):
        try:
            message = _('Creating consistency group snapshot "%s".') \
                % data['name']
            snapshot = cinder.volume_cg_snapshot_create(request,
                                                        data['cgroup_id'],
                                                        data['name'],
                                                        data['description'])

            messages.info(request, message)
            return snapshot
        except Exception as e:
            redirect = reverse("horizon:project:volumes:index")
            msg = _('Unable to create consistency group snapshot.')
            if e.code == 413:
                msg = _('Requested snapshot would exceed the allowed quota.')
            else:
                search_opts = {'consistentcygroup_id': data['cgroup_id']}
                volumes = cinder.volume_list(request, search_opts=search_opts)
                if len(volumes) == 0:
                    msg = _('Unable to create snapshot. Consistency group '
                            'must contain volumes.')

            exceptions.handle(request,
                              msg,
                              redirect=redirect)
예제 #28
0
    def handle(self, request, data):
        template_data = self.create_kwargs(data)
        logo_file = self.request.FILES['logo']

        values = {'user_id': request.user.id,
                  'project_id': request.user.tenant_id,
                  'name': data['name'],
                  'description': '',
                  'website': '',
                  'category': data['category'],
                  'template_data': template_data,
                  'author': request.user.username,
                  'logo': logo_file.name,
                  'is_public': True}

        try:
            self.handle_uploaded_file(logo_file)
            db_api.application_create(request, values)
            message = _('Successfully upload '
                        'application template %s') % values['name']
            messages.info(request, message)
            return True
        except Exception:
            error_message = _(
                'Unable to upload application template %s') % values['name']
            exceptions.handle(request, error_message)
            return False
예제 #29
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']
            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)
예제 #30
0
파일: views.py 프로젝트: haminhcong/horizon
    def get_data(self):
        users = []
        filters = self.get_filters()
        if policy.check((("identity", "identity:list_users"),),
                        self.request):
            domain_context = api.keystone.get_effective_domain_id(self.request)
            try:
                users = api.keystone.user_list(self.request,
                                               domain=domain_context,
                                               filters=filters)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve user list.'))
        elif policy.check((("identity", "identity:get_user"),),
                          self.request):
            try:
                user = api.keystone.user_get(self.request,
                                             self.request.user.id)
                users.append(user)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve user information.'))
        else:
            msg = _("Insufficient privilege level to view user information.")
            messages.info(self.request, msg)

        if api.keystone.VERSIONS.active >= 3:
            domain_lookup = api.keystone.domain_lookup(self.request)
            for u in users:
                u.domain_name = domain_lookup.get(u.domain_id)
        return users
예제 #31
0
    def handle(self, request, data):
        snapshot_id = self.initial['snapshot_id']
        try:
            sg_api.volume_snapshot_update(request, snapshot_id, data['name'],
                                          data['description'])

            message = _('Updating volume snapshot "%s"') % data['name']
            messages.info(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:storage-gateway:snapshots:index")
            exceptions.handle(request,
                              _('Unable to update volume snapshot.'),
                              redirect=redirect)
예제 #32
0
파일: forms.py 프로젝트: miurahr/horizon
    def handle(self, request, data):
        volume_id = self.initial['volume_id']
        try:
            cinder.volume_update(request, volume_id, data['name'],
                                 data['description'])

            message = _('Updating volume "%s"') % data['name']
            messages.info(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            exceptions.handle(request,
                              _('Unable to update volume.'),
                              redirect=redirect)
예제 #33
0
    def handle(self, request, data):
        try:
            snapshot = api.volume_snapshot_create(request, data['volume_id'],
                                                  data['name'],
                                                  data['description'])

            message = _('Creating volume snapshot "%s"') % data['name']
            messages.info(request, message)
            return snapshot
        except:
            redirect = reverse("horizon:project:images_and_snapshots:index")
            exceptions.handle(request,
                              _('Unable to create volume snapshot.'),
                              redirect=redirect)
예제 #34
0
 def get_data(self):
     if not policy.check(
             (("compute", "os_compute_api:os-keypairs:index"),),
             self.request):
         msg = _("Insufficient privilege level to retrieve key pair list.")
         messages.info(self.request, msg)
         return []
     try:
         keypairs = nova.keypair_list(self.request)
     except Exception:
         keypairs = []
         exceptions.handle(self.request,
                           _('Unable to retrieve key pair list.'))
     return keypairs
예제 #35
0
 def get_data(self):
     mappings = []
     if policy.check((("identity", "identity:list_mappings"), ),
                     self.request):
         try:
             mappings = api.keystone.mapping_list(self.request)
         except Exception:
             exceptions.handle(self.request,
                               _('Unable to retrieve mapping list.'))
     else:
         msg = _("Insufficient privilege level to view mapping "
                 "information.")
         messages.info(self.request, msg)
     return mappings
예제 #36
0
 def handle(self, request, data):
     instance = data.get('instance_id')
     image = data.get('image')
     password = data.get('password') or None
     disk_config = data.get('disk_config', None)
     try:
         api.nova.server_rebuild(request, instance, image, password,
                                 disk_config)
         messages.info(request, _('Rebuilding instance %s.') % instance)
     except Exception:
         redirect = reverse('horizon:project:instances:index')
         exceptions.handle(request, _("Unable to rebuild instance."),
                           redirect=redirect)
     return True
예제 #37
0
    def handle(self, request, data):

        try:
            backup = sg_api.volume_backup_create(request, data['volume_id'],
                                                 data['name'],
                                                 data['description'])
            message = _('Creating volume backup "%s"') % data['name']
            messages.info(request, message)
            return backup
        except Exception:
            redirect = reverse('horizon:storage-gateway:volumes:index')
            exceptions.handle(request,
                              _('Unable to create volume backup.'),
                              redirect=redirect)
예제 #38
0
 def get_data(self):
     roles = []
     filters = self.get_filters()
     if policy.check((("identity", "identity:list_roles"),),
                     self.request):
         try:
             roles = api.keystone.role_list(self.request,
                                            filters=filters)
         except Exception:
             exceptions.handle(self.request,
                               _('Unable to retrieve roles list.'))
     else:
         msg = _("Insufficient privilege level to view role information.")
         messages.info(self.request, msg)
     return roles
예제 #39
0
    def handle(self, request, data):
        cgroup_id = self.initial['cgroup_id']
        try:
            cinder.volume_cgroup_update(request, cgroup_id, data['name'],
                                        data['description'])

            message = _('Updating volume consistency '
                        'group "%s"') % data['name']
            messages.info(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:virtual:volumes:index")
            exceptions.handle(request,
                              _('Unable to update volume consistency group.'),
                              redirect=redirect)
예제 #40
0
    def handle(self, request, data, *args, **kwargs):
        share_net_id = self.initial['share_network_id']
        try:
            manila.share_network_update(request, share_net_id,
                                        name=data['name'],
                                        description=data['description'])

            message = _('Updating share network "%s"') % data['name']
            messages.info(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:project:shares:index")
            exceptions.handle(request,
                              _('Unable to update share network.'),
                              redirect=redirect)
예제 #41
0
 def _delete_network(self, request, network):
     """Delete the created network when subnet creation failed."""
     try:
         api.neutron.network_delete(request, network.id)
         msg = _('Delete the created network "%s" '
                 'due to subnet creation failure.') % network.name
         LOG.debug(msg)
         redirect = self.get_failure_url()
         messages.info(request, msg)
         raise exceptions.Http302(redirect)
     except Exception:
         msg = _('Failed to delete network "%s"') % network.name
         LOG.info(msg)
         redirect = self.get_failure_url()
         exceptions.handle(request, msg, redirect=redirect)
예제 #42
0
def switch(request, tenant_id, **kwargs):
    """Wrapper for ``openstack_auth.views.switch`` to add a message
    for the user.
    """
    user_organization = request.user.default_project_id
    response = openstack_auth_views.switch(request, tenant_id, **kwargs)
    if tenant_id != user_organization:
        organization_name = next(o.name for o in request.organizations 
                         if o.id == tenant_id)
        msg = ("Your identity has changed. Now you are acting on behalf "
               "of the \"{0}\" organization. Use the top-right menu to " 
               "regain your identity as individual user.").format(
               organization_name)
        messages.info(request, msg)
    return response
예제 #43
0
 def get_data(self):
     groups = []
     domain_context = self.request.session.get('domain_context', None)
     if policy.check((("identity", "identity:list_groups"),),
                     self.request):
         try:
             groups = api.keystone.group_list(self.request,
                                              domain=domain_context)
         except Exception:
             exceptions.handle(self.request,
                               _('Unable to retrieve group list.'))
     else:
         msg = _("Insufficient privilege level to view group information.")
         messages.info(self.request, msg)
     return groups
예제 #44
0
 def get_data(self):
     idps = []
     if policy.check((("identity", "identity:list_identity_providers"),),
                     self.request):
         try:
             idps = api.keystone.identity_provider_list(self.request)
         except Exception:
             exceptions.handle(
                 self.request,
                 _('Unable to retrieve identity provider list.'))
     else:
         msg = _("Insufficient privilege level to view identity provider "
                 "information.")
         messages.info(self.request, msg)
     return idps
예제 #45
0
파일: forms.py 프로젝트: wilk/horizon
    def handle(self, request, data):
        volume_id = self.initial['id']
        try:
            volume = cinder.volume_extend(request,
                                          volume_id,
                                          data['new_size'])

            message = _('Extending volume: "%s"') % data['name']
            messages.info(request, message)
            return volume
        except Exception:
            redirect = reverse("horizon:project:volumes:index")
            exceptions.handle(request,
                              _('Unable to extend volume.'),
                              redirect=redirect)
예제 #46
0
파일: forms.py 프로젝트: redondos/horizon
    def handle(self, request, data):
        try:
            # FIXME(johnp): cinderclient currently returns a useless
            # error message when the quota is exceeded when trying to create
            # a volume, so we need to check for that scenario here before we
            # send it off to try and create.
            usages = quotas.tenant_quota_usages(request)

            snapshot_id = None
            if (data.get("snapshot_source", None)):
                # Create from Snapshot
                snapshot = self.get_snapshot(request, data["snapshot_source"])
                snapshot_id = snapshot.id
                if (data['size'] < snapshot.size):
                    error_message = _('The volume size cannot be less than '
                                      'the snapshot size (%sGB)' %
                                      snapshot.size)
                    raise ValidationError(error_message)
            else:
                if type(data['size']) is str:
                    data['size'] = int(data['size'])

            if usages['gigabytes']['available'] < data['size']:
                error_message = _('A volume of %(req)iGB cannot be created as '
                                  'you only have %(avail)iGB of your quota '
                                  'available.')
                params = {
                    'req': data['size'],
                    'avail': usages['gigabytes']['available']
                }
                raise ValidationError(error_message % params)
            elif usages['volumes']['available'] <= 0:
                error_message = _('You are already using all of your available'
                                  ' volumes.')
                raise ValidationError(error_message)

            volume = cinder.volume_create(request,
                                          data['size'],
                                          data['name'],
                                          data['description'],
                                          data['type'],
                                          snapshot_id=snapshot_id)
            message = 'Creating volume "%s"' % data['name']
            messages.info(request, message)
            return volume
        except ValidationError, e:
            self.api_error(e.messages[0])
            return False
예제 #47
0
 def handle(self, request, data):
     try:
         params = {}
         if data.get('tenant_id'):
             params['tenant_id'] = data['tenant_id']
         router = api.quantum.router_create(request,
                                            name=data['name'], **params)
         message = 'Creating router "%s"' % data['name']
         messages.info(request, message)
         return router
     except:
         msg = _('Failed to create router "%s".') % data['name']
         LOG.warn(msg)
         redirect = reverse(self.failure_url)
         exceptions.handle(request, msg, redirect=redirect)
         return False
예제 #48
0
파일: workflows.py 프로젝트: mssumanth/Temp
 def _delete_vpn(self, request, vpn):
     """Delete the created network when site creation failed"""
     try:
         #api.quantum.network_delete(request, network.id)
         msg = _('Delete the created VPN "%s" '
                 'due to site addition failure.') % vpn_name
         LOG.debug(msg)
         redirect = self.get_failure_url()
         messages.info(request, msg)
         raise exceptions.Http302(redirect)
         #return exceptions.RecoverableError
     except:
         msg = _('Failed to delete VPN %s') % vpn_id
         LOG.info(msg)
         redirect = self.get_failure_url()
         exceptions.handle(request, msg, redirect=redirect)
예제 #49
0
    def handle(self, request, data):
        replication_id = self.initial['replication_id']
        try:
            sg_api.volume_replication_update(request,
                                             replication_id,
                                             name=data['name'],
                                             description=data['description'])
        except Exception:
            redirect = reverse("horizon:storage-gateway:replications:index")
            exceptions.handle(request,
                              _('Unable to update replication.'),
                              redirect=redirect)

        message = _('Updating replication "%s"') % data['name']
        messages.info(request, message)
        return True
예제 #50
0
    def handle(self, table, request, obj_ids):
        projectid = table.kwargs['projectid']
        experts = []
        for expertid in obj_ids:
            expert = table.get_object_by_id(expertid)
            experts.append(expert)

        (project, has_in_pool, has_in_project, has_unavailable) = \
            project_db_handle.AddCandidates(projectid, experts)
        all_experts = []
        has_in_project_experts = []
        has_in_pool_experts = []
        has_unavailable_experts = []
        for expert in experts:
            if expert in has_in_project:
                has_in_project_experts.append(expert)
            elif expert in has_in_pool:
                has_in_pool_experts.append(expert)
            elif expert in has_unavailable:
                has_unavailable_experts.append(expert)
            else:
                all_experts.append(expert)

        if all_experts:
            names = expert_db_handle.get_all_expert_names(all_experts)
            messages.success(
                request,
                u"以下专家:%s,已加入项目%s的候选专家列表" % (names, project.projectname))
        if has_in_pool_experts:
            names = expert_db_handle.get_all_expert_names(has_in_pool_experts)
            messages.info(
                request, u"以下专家:%s,未加入项目%s的候选专家列表,原因:%s" %
                (names, project.projectname, u"已存在于候选专家列表中"))
        if has_unavailable_experts:
            names = expert_db_handle.get_all_expert_names(
                has_unavailable_experts)
            messages.info(
                request, u"以下专家:%s,未加入项目%s的候选专家列表,原因:%s" %
                (names, project.projectname, u"已从候选专家列表或评审专家列表中删除"))
        if has_in_project_experts:
            names = expert_db_handle.get_all_expert_names(
                has_in_project_experts)
            messages.error(
                request, u"以下专家:%s,未加入项目%s的候选专家列表,原因:%s" %
                (names, project.projectname, u"已参与该项目评审"))

        return shortcuts.redirect(self.get_success_url(request))
 def handle(self, request, data):
     try:
         volume = sg_api.volume_get(request, data['volume_id'])
         message = _('Creating volume snapshot "%s".') % data['name']
         if volume.status == 'in-use':
             message = _('Forcing to create snapshot "%s" '
                         'from attached volume.') % data['name']
         snapshot = sg_api.volume_snapshot_create(request,
                                                  data['volume_id'],
                                                  data['name'],
                                                  data['description'])
         messages.info(request, message)
         return snapshot
     except Exception:
         redirect = reverse("horizon:storage-gateway:volumes:index")
         msg = _('Unable to create volume snapshot.')
         exceptions.handle(request, msg, redirect=redirect)
예제 #52
0
 def single(self, table, request, pool_id):
     try:
         pool = api.lbaas.pool_get(request, pool_id)
         fips = api.network.tenant_floating_ip_list(request)
         vip_fips = [fip for fip in fips if fip.port_id == pool.vip.port_id]
         if not vip_fips:
             messages.info(request, _("No floating IPs to disassociate."))
         else:
             api.network.floating_ip_disassociate(request, vip_fips[0].id)
             messages.success(
                 request,
                 _("Successfully disassociated "
                   "floating IP: %s") % fip.ip)
     except Exception:
         exceptions.handle(request,
                           _("Unable to disassociate floating IP."))
     return shortcuts.redirect(request.get_full_path())
예제 #53
0
 def get_data(self):
     groups = []
     domain_id = api.keystone.get_effective_domain_id(self.request)
     filters = self.get_filters()
     if policy.check((("identity", "identity:list_groups"), ),
                     self.request):
         try:
             groups = api.keystone.group_list(self.request,
                                              domain=domain_id,
                                              filters=filters)
         except Exception:
             exceptions.handle(self.request,
                               _('Unable to retrieve group list.'))
     else:
         msg = _("Insufficient privilege level to view group information.")
         messages.info(self.request, msg)
     return groups
예제 #54
0
    def handle(self, request, data):
        snapshot_id = self.initial['snapshot_id']
        try:
            snapshot = cinder.volume_snapshot_update(request, snapshot_id,
                                                     data['name'],
                                                     data['description'])

            name_or_id = (snapshot["snapshot"]["name"]
                          or snapshot["snapshot"]["id"])
            message = _('Updating volume snapshot "%s"') % name_or_id
            messages.info(request, message)
            return True
        except Exception:
            redirect = reverse("horizon:project:snapshots:index")
            exceptions.handle(request,
                              _('Unable to update volume snapshot.'),
                              redirect=redirect)
 def handle(self, request, data):
     try:
         result = None
         volume = cinder.volume_get(request, data['volume_id'])
         if not volume:
             message = _('Volume not exist,id:"%s".') % data['volume_id']
         else:
             message = _('Enabling volume "%s".') % data['name']
             result = sg_api.volume_enable(request, data['volume_id'],
                                           data['name'],
                                           data['description'])
         messages.info(request, message)
         return result
     except Exception:
         redirect = reverse("horizon:storage-gateway:volumes:index")
         msg = _('Unable to enable volume:%s.') % data['volume_id']
         exceptions.handle(request, msg, redirect=redirect)
예제 #56
0
    def handle(self, request, data):
        try:

            message = _('Creating consistency group "%s".') % data['name']
            cgroup = cinder.volume_cgroup_create_from_source(
                request,
                data['name'],
                cg_snapshot_id=data['cg_snapshot_id'],
                description=data['description'])

            messages.info(request, message)
            return cgroup
        except Exception:
            redirect = reverse("horizon:admin:volumes:index")
            msg = _('Unable to create consistency '
                    'group "%s" from snapshot.') % data['name']
            exceptions.handle(request, msg, redirect=redirect)
예제 #57
0
    def handle(self, request, data):
        try:
            params = _populate_node_params(data['name'],
                                           data['profile_id'],
                                           data['cluster_id'],
                                           data['role'],
                                           data['metadata'])

            node = senlin.node_create(request, **params)
            msg = _('Creating node "%s" successfully') % data['name']
            messages.info(request, msg)
            return node
        except Exception:
            redirect = reverse("horizon:cluster:nodes:index")
            exceptions.handle(request,
                              _("Unable to create node."),
                              redirect=redirect)
예제 #58
0
    def handle(self, request, data):
        try:

            message = _('Creating group "%s".') % data['name']
            group = cinder.group_create_from_source(
                request,
                data['name'],
                group_snapshot_id=data['vg_snapshot_id'],
                description=data['description'])

            messages.info(request, message)
            return group
        except Exception:
            redirect = reverse("horizon:project:vg_snapshots:index")
            msg = (_('Unable to create group "%s" from snapshot.') %
                   data['name'])
            exceptions.handle(request, msg, redirect=redirect)
예제 #59
0
    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
예제 #60
0
 def handle(self, request, data):
     try:
         block_migration = data['block_migration']
         disk_over_commit = data['disk_over_commit']
         api.nova.server_live_migrate(request,
                                      data['instance_id'],
                                      data['host'],
                                      block_migration=block_migration,
                                      disk_over_commit=disk_over_commit)
         msg = _('The instance is preparing the live migration '
                 'to host "%s".') % data['host']
         messages.info(request, msg)
         return True
     except Exception:
         msg = _('Failed to live migrate instance to '
                 'host "%s".') % data['host']
         redirect = reverse('horizon:admin:instances:index')
         exceptions.handle(request, msg, redirect=redirect)