Exemplo n.º 1
0
def _translate_image_exception(image_id, exc_value):
    if isinstance(exc_value, (glanceclient.exc.Forbidden,
                    glanceclient.exc.Unauthorized)):
        return exception.ImageNotAuthorized(image_id=image_id)
    if isinstance(exc_value, glanceclient.exc.NotFound):
        return exception.ImageNotFound(image_id=image_id)
    if isinstance(exc_value, glanceclient.exc.BadRequest):
        return exception.ImageBadRequest(image_id=image_id,
                                         response=six.text_type(exc_value))
    return exc_value
Exemplo n.º 2
0
    def show(self, context, image_id, include_locations=False,
             show_deleted=True):
        """Returns a dict with image data for the given opaque image id.

        :param context: The context object to pass to image client
        :param image_id: The UUID of the image
        :param include_locations: (Optional) include locations in the returned
                                  dict of information if the image service API
                                  supports it. If the image service API does
                                  not support the locations attribute, it will
                                  still be included in the returned dict, as an
                                  empty list.
        :param show_deleted: (Optional) show the image even the status of
                             image is deleted.
        """
        version = 1
        if include_locations:
            version = 2
        try:
            image = self._client.call(context, version, 'get', image_id)
        except Exception:
            _reraise_translated_image_exception(image_id)

        if not show_deleted and getattr(image, 'deleted', False):
            raise exception.ImageNotFound(image_id=image_id)

        if not _is_image_available(context, image):
            raise exception.ImageNotFound(image_id=image_id)

        image = _translate_from_glance(image,
                                       include_locations=include_locations)
        if include_locations:
            locations = image.get('locations', None) or []
            du = image.get('direct_url', None)
            if du:
                locations.append({'url': du, 'metadata': {}})
            image['locations'] = locations

        return image
Exemplo n.º 3
0
    def delete(self, context, image_id):
        """Delete the given image.

        :raises: ImageNotFound if the image does not exist.
        :raises: NotAuthorized if the user is not an owner.
        :raises: ImageNotAuthorized if the user is not authorized.

        """
        try:
            self._client.call(context, 1, 'delete', image_id)
        except glanceclient.exc.NotFound:
            raise exception.ImageNotFound(image_id=image_id)
        except glanceclient.exc.HTTPForbidden:
            raise exception.ImageNotAuthorized(image_id=image_id)
        return True
Exemplo n.º 4
0
 def safe_image_show(ctx, image_id):
     if image_id:
         return self.image_api.get(ctx, image_id, show_deleted=False)
     else:
         raise exception.ImageNotFound(image_id='')
Exemplo n.º 5
0
    def volume_create(self, context, instance, image_id=None, size=None):
        '''Create volume for lxc in image sys or creating hybridcontainer '''

        # 1. volume size check
        root_size = instance.get_flavor().get('root_gb', None)
        vol_size = size or root_size

        if not vol_size:
            _msg = "volume size input is None."
            raise exception_ex.ProviderCreateVolumeFailed(reason=_msg)

        kwargs = {}
        kwargs['Size'] = vol_size
        # 2. available zone from configure file or BD
        # if change from parameter, here should modify.
        try:
            project_mapper = \
                self._get_project_mapper(context, context.project_id)
        except exception_ex.AccountNotConfig:
            LOG.warn(_LE("Get project mapper failed in db."))
            project_mapper = None

        if not project_mapper:
            az = CONF.availability_zone or None
        else:
            az = project_mapper.get('availability_zone', None)
        if not az:
            LOG.error(_LE("Create volume error: availability zone is none."))
            raise exception_ex.AvailabilityZoneNotFountError
        kwargs['AvailabilityZone'] = az

        # volume id for caa
        volume_id = str(uuid.uuid4())
        provider_snapshot_id = None
        # if image id is not None and image id is base vm
        if image_id and image_id == "base":
            # get base vm image id in aws
            try:
                provider_image_id = \
                    self._get_provider_base_image_id(context, image_id)
                # get base vm image snapshot id in aws
                kwargs = {'ImageIds': [provider_image_id]}
                images = self.aws_client.get_aws_client(context)\
                                        .describe_images(**kwargs)
                image = images[0]
                block_device_mappings = image.get('BlockDeviceMappings')
                for bdm in block_device_mappings:
                    device_name = bdm.get('DeviceName')
                    if device_name == '/dev/sda1' or \
                       device_name == '/dev/xvda':
                        provider_snapshot_id = \
                            bdm.get('Ebs', {})['SnapshotId']
                        break
            except Exception as e:
                LOG.error(_LE('Query basevm image %(i)s in aws error: %(e)s'),
                          {
                              'i': image_id,
                              'e': e
                          })
                raise exception.ImageNotFound(image_id=image_id)
        elif image_id:
            provider_snapshot_id = \
                self._get_provider_image_id(context, image_id)
        else:
            provider_snapshot_id = None

        if provider_snapshot_id:
            kwargs['SnapshotId'] = provider_snapshot_id

        # 3. create volume
        volume = None
        try:
            # 3.1 create volume
            aws_client = self.aws_client.get_aws_client(context)
            volume = aws_client.create_volume(**kwargs)
            # 3.2. create volume tag
            tags = [{'Key': 'caa_volume_id', 'Value': volume_id}]
            aws_client.create_tags(Resources=[volume['VolumeId']], Tags=tags)
        except Exception as e:
            _msg = "Aws create volume error: %s" % traceback.format_exc(e)
            if volume:
                LOG.error(_msg)
                self.aws_client.get_aws_client(context)\
                               .delete_volume(VolumeId=volume['VolumeId'])
            raise exception_ex.ProviderCreateVolumeFailed(reason=_msg)

        # 4. create volume mapper
        try:
            values = {'provider_volume_id': volume['VolumeId']}
            self.caa_db_api.volume_mapper_create(context, volume_id,
                                                 context.project_id, values)
        except Exception as ex:
            _msg = (_LE("volume_mapper_create failed! vol: %(id)s,ex: %(ex)s"),
                    {
                        'id': volume['VolumeId'],
                        'ex': ex
                    })
            LOG.error(_msg)
            aws_client = self.aws_client.get_aws_client(context)
            aws_client.delete_volume(VolumeId=volume['VolumeId'])
            raise exception_ex.ProviderCreateVolumeFailed(reason=_msg)

        return volume_id