Example #1
0
    def update(self, req, image_id, changes):
        image_repo = self.gateway.get_repo(req.context)
        try:
            image = image_repo.get(image_id)

            for change in changes:
                change_method_name = '_do_%s' % change['op']
                assert hasattr(self, change_method_name)
                change_method = getattr(self, change_method_name)
                change_method(req, image, change)

            if changes:
                image_repo.save(image)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Invalid as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.InvalidParameterValue as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.StorageQuotaFull as e:
            msg = (_("Denying attempt to upload image because it exceeds the"
                     " quota: %s") % utils.exception_to_str(e))
            LOG.warn(msg)
            raise webob.exc.HTTPRequestEntityTooLarge(
                explanation=msg, request=req, content_type='text/plain')
        except exception.LimitExceeded as e:
            LOG.exception(utils.exception_to_str(e))
            raise webob.exc.HTTPRequestEntityTooLarge(
                explanation=e.msg, request=req, content_type='text/plain')

        return image
Example #2
0
    def index(self, req, marker=None, limit=None, sort_key='created_at',
              sort_dir='desc', filters=None):
        result = {}
        if filters is None:
            filters = {}
        filters['deleted'] = False

        if limit is None:
            limit = CONF.limit_param_default
        limit = min(CONF.api_limit_max, limit)

        task_repo = self.gateway.get_task_stub_repo(req.context)
        try:
            tasks = task_repo.list(marker, limit, sort_key,
                                   sort_dir, filters)
            if len(tasks) != 0 and len(tasks) == limit:
                result['next_marker'] = tasks[-1].task_id
        except (exception.NotFound, exception.InvalidSortKey,
                exception.InvalidFilterRangeValue) as e:
            LOG.warn(utils.exception_to_str(e))
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.warn(utils.exception_to_str(e))
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        result['tasks'] = tasks
        return result
    def optical_switch_delete(self, req, id):
        """
        Deletes a optical_switch from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about optical_switch

        :raises HTTPBadRequest if x-service-disk-name is missing
        """
        self._enforce(req, 'optical_switch_delete')
        try:
            registry.delete_optical_switch_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find optical switch to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete optical switch: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        else:
            return Response(body='', status=200)
Example #4
0
    def create(self, req, image, extra_properties, tags):
        image_factory = self.gateway.get_image_factory(req.context)
        image_repo = self.gateway.get_repo(req.context)
        try:
            image = image_factory.new_image(extra_properties=extra_properties,
                                            tags=tags, **image)
            image_repo.add(image)
        except exception.DuplicateLocation as dup:
            raise webob.exc.HTTPBadRequest(explanation=dup.msg)
        except exception.Invalid as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.InvalidParameterValue as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.LimitExceeded as e:
            LOG.warn(utils.exception_to_str(e))
            raise webob.exc.HTTPRequestEntityTooLarge(
                explanation=e.msg, request=req, content_type='text/plain')
        except exception.Duplicate as dupex:
            raise webob.exc.HTTPConflict(explanation=dupex.msg)
        except exception.ReservedProperty as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.ReadonlyProperty as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except TypeError as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPBadRequest(
                explanation=utils.exception_to_str(e))

        return image
Example #5
0
    def optical_switch_delete(self, req, id):
        """
        Deletes a optical_switch from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about optical_switch

        :raises HTTPBadRequest if x-service-disk-name is missing
        """
        self._enforce(req, 'optical_switch_delete')
        try:
            registry.delete_optical_switch_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find optical switch to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete optical switch: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        else:
            return Response(body='', status=200)
Example #6
0
 def get_template_detail(self, req, template_id):
     """
     delete a existing cluster template with the registry.
     :param request: The WSGI/Webob Request object
     :param id: The opaque image identifie
     :retval Returns the updated image information as a mapping
     """
     self._enforce(req, 'get_template_detail')
     try:
         template = registry.template_detail_metadata(req.context, template_id)
         return {'template': template}
     except exception.NotFound as e:
         msg = (_("Failed to find template: %s") %
                utils.exception_to_str(e))
         LOG.error(msg)
         raise HTTPNotFound(explanation=msg,
                            request=req,
                            content_type="text/plain")
     except exception.Forbidden as e:
         msg = (_("Forbidden to get template: %s") %
                utils.exception_to_str(e))
         LOG.error(msg)
         raise HTTPForbidden(explanation=msg,
                             request=req,
                             content_type="text/plain")
     except exception.InUseByStore as e:
         msg = (_("template %(id)s could not be get because it is in use: "
                  "%(exc)s") % {"id": template_id, "exc": utils.exception_to_str(e)})
         LOG.error(msg)
         raise HTTPConflict(explanation=msg,
                            request=req,
                            content_type="text/plain")
     else:
         return Response(body='', status=200)
Example #7
0
def main():
    """The main function."""

    try:
        config.parse_args()
    except RuntimeError as e:
        sys.exit("ERROR: %s" % utils.exception_to_str(e))

    # Setup logging
    logging.setup('glance')

    if CONF.token:
        CONF.slavetoken = CONF.token
        CONF.mastertoken = CONF.token

    command = lookup_command(CONF.command)

    try:
        command(CONF, CONF.args)
    except TypeError as e:
        LOG.error(_LE(command.__doc__) % {'prog': command.__name__})  # noqa
        sys.exit("ERROR: %s" % utils.exception_to_str(e))
    except ValueError as e:
        LOG.error(_LE(command.__doc__) % {'prog': command.__name__})  # noqa
        sys.exit("ERROR: %s" % utils.exception_to_str(e))
Example #8
0
    def cinder_volume_delete(self, req, id):
        """
        Deletes a service_disk from Daisy.
 
        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about service_disk

        :raises HTTPBadRequest if x-service-disk-name is missing
        """
        self._enforce(req, 'delete_cinder_volume')
        try:
            registry.delete_cinder_volume_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find cinder volume to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete cinder volume: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("cindre volume %(id)s could not be deleted because it is in use: "
                     "%(exc)s") % {"id": id, "exc": utils.exception_to_str(e)})
            LOG.warn(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            return Response(body='', status=200)
Example #9
0
    def update_all(self, req, image_id, body):
        """
        Replaces the members of the image with those specified in the
        body.  The body is a dict with the following format::

            {"memberships": [
                {"member_id": <MEMBER_ID>,
                 ["can_share": [True|False]]}, ...
            ]}
        """
        self._check_can_access_image_members(req.context)
        self._enforce(req, 'modify_member')
        self._raise_404_if_image_deleted(req, image_id)

        memberships = body.get('memberships')
        if memberships:
            new_number_of_members = len(body['memberships'])
            self._enforce_image_member_quota(req, new_number_of_members)

        try:
            registry.replace_members(req.context, image_id, body)
            self._update_store_acls(req, image_id)
        except exception.Invalid as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.NotFound as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)

        return webob.exc.HTTPNoContent()
Example #10
0
    def set_data(self, data, size=None):
        self.send_notification('image.prepare', self.repo)

        notify_error = self.notifier.error
        try:
            self.repo.set_data(data, size)
        except glance_store.StorageFull as e:
            msg = (_("Image storage media is full: %s") %
                   utils.exception_to_str(e))
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
        except glance_store.StorageWriteDenied as e:
            msg = (_("Insufficient permissions on image storage media: %s")
                   % utils.exception_to_str(e))
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPServiceUnavailable(explanation=msg)
        except ValueError as e:
            msg = (_("Cannot save data for image %(image_id)s: %(error)s") %
                   {'image_id': self.repo.image_id,
                    'error': utils.exception_to_str(e)})
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPBadRequest(
                explanation=utils.exception_to_str(e))
        except exception.Duplicate as e:
            msg = (_("Unable to upload duplicate image data for image"
                     "%(image_id)s: %(error)s") %
                   {'image_id': self.repo.image_id,
                    'error': utils.exception_to_str(e)})
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPConflict(explanation=msg)
        except exception.Forbidden as e:
            msg = (_("Not allowed to upload image data for image %(image_id)s:"
                     " %(error)s") % {'image_id': self.repo.image_id,
                                      'error': utils.exception_to_str(e)})
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPForbidden(explanation=msg)
        except exception.NotFound as e:
            msg = (_("Image %(image_id)s could not be found after upload."
                     " The image may have been deleted during the upload:"
                     " %(error)s") % {'image_id': self.repo.image_id,
                                      'error': utils.exception_to_str(e)})
            _send_notification(notify_error, 'image.upload', msg)
            raise webob.exc.HTTPNotFound(explanation=utils.exception_to_str(e))
        except webob.exc.HTTPError as e:
            with excutils.save_and_reraise_exception():
                msg = (_("Failed to upload image data for image %(image_id)s"
                         " due to HTTP error: %(error)s") %
                       {'image_id': self.repo.image_id,
                        'error': utils.exception_to_str(e)})
                _send_notification(notify_error, 'image.upload', msg)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                msg = (_("Failed to upload image data for image %(image_id)s "
                         "due to internal error: %(error)s") %
                       {'image_id': self.repo.image_id,
                        'error': utils.exception_to_str(e)})
                _send_notification(notify_error, 'image.upload', msg)
        else:
            self.send_notification('image.upload', self.repo)
            self.send_notification('image.activate', self.repo)
Example #11
0
    def cinder_volume_update(self, req, id, disk_meta):
        for key in disk_meta.keys():
            if key not in CINDER_VOLUME_BACKEND_PARAMS:
                msg = "'%s' must be given for cinder volume config" % key
                raise HTTPBadRequest(explanation=msg,
                                    request=req,
                                    content_type="text/plain")
        if disk_meta.has_key('role_id'):
            self._raise_404_if_role_deleted(req,disk_meta['role_id'])
        if (disk_meta.has_key('volume_driver') and
            disk_meta['volume_driver'] not in CINDER_VOLUME_BACKEND_DRIVER):
            msg = "volume_driver %s is not supported" % disk_meta['volume_driver']
            raise HTTPBadRequest(explanation=msg,
                                request=req,
                                    content_type="text/plain")
                                        
        self._is_cinder_volume_repeat(req, disk_meta, id)
        self._is_data_ips_valid(req, id, disk_meta)

        try:
            cinder_volume_meta = registry.update_cinder_volume_metadata(req.context,
                                                      id,
                                                      disk_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update cinder_volume metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find cinder_volume to update: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update cinder_volume: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warn(utils.exception_to_str(e))
            raise HTTPConflict(body=_('cinder_volume operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('cinder_volume.update', cinder_volume_meta)

        return {'disk_meta': cinder_volume_meta}
Example #12
0
        def rollback(e):
            set_attr('error', utils.exception_to_str(e))

            invalid_path = self.get_image_filepath(image_id, 'invalid')
            LOG.debug("Fetch of cache file failed (%(e)s), rolling back by "
                      "moving '%(incomplete_path)s' to "
                      "'%(invalid_path)s'" %
                      {'e': utils.exception_to_str(e),
                       'incomplete_path': incomplete_path,
                       'invalid_path': invalid_path})
            os.rename(incomplete_path, invalid_path)
Example #13
0
    def update_service(self, req, id, service_meta):
        """
        Updates an existing service with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'modify_image')
        orig_service_meta = self.get_service_meta_or_404(req, id)

        # Do not allow any updates on a deleted image.
        # Fix for LP Bug #1060930
        if orig_service_meta['deleted']:
            msg = _("Forbidden to update deleted service.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        try:
            service_meta = registry.update_service_metadata(req.context,
                                                            id,
                                                            service_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update service metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find service to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update service: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('service.update', service_meta)

        return {'service_meta': service_meta}
    def update_version_patch(self, req, id, version_patch_meta):
        """
        Updates an existing version patch with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_version_patch')
        orig_version_meta = self.get_version_patch_meta_or_404(req, id)

        if orig_version_meta['deleted']:
            msg = _("Forbidden to update deleted version patch.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        try:
            version_patch_meta = registry.update_version_patch_metadata(
                req.context,
                id,
                version_patch_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update version patch. Got error: %s")
                   % utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find version patch to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update version patch: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('version_patchs.update', version_patch_meta)

        return {'version_patch_meta': version_patch_meta}
Example #15
0
    def update_service(self, req, id, service_meta):
        """
        Updates an existing service with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'modify_image')
        orig_service_meta = self.get_service_meta_or_404(req, id)

        # Do not allow any updates on a deleted image.
        # Fix for LP Bug #1060930
        if orig_service_meta['deleted']:
            msg = _("Forbidden to update deleted service.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        try:
            service_meta = registry.update_service_metadata(
                req.context, id, service_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update service metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find service to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update service: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('service.update', service_meta)

        return {'service_meta': service_meta}
    def update_host_template(self, req, template_id, host_template):
        """
        Updates an existing Template with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_host_template')
        #orig_Template_meta = self.get_Template_meta_or_404(req, id)
        '''
        if orig_Template_meta['deleted']:
            msg = _("Forbidden to update deleted Template.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        '''
        try:
            host_template = registry.update_host_template_metadata(req.context,
                                                            template_id,
                                                            host_template)

        except exception.Invalid as e:
            msg = (_("Failed to update template metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find host_template to update: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update host_template: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warn(utils.exception_to_str(e))
            raise HTTPConflict(body=_('host_template operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('host_template.update', host_template)

        return {'host_template': host_template}
    def update_config_set(self, req, id, body):
        """Updates an existing config_set with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        config_set_data = body['config_set']
        try:
            updated_config_set = self.db_api.config_set_update(
                req.context, id, config_set_data)

            msg = _LI("Updating metadata for config_set %(id)s") % {'id': id}
            LOG.info(msg)
            if 'config_set' not in updated_config_set:
                config_set_data = dict(config_set=updated_config_set)
            return config_set_data
        except exception.Invalid as e:
            msg = (_("Failed to update config_set metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("config_set %(id)s not found") % {'id': id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='config_set not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for config_set %(id)s") % {'id': id}
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden:
            # If it's private and doesn't belong to them, don't let on
            # that it exists
            msg = _LI("Access denied to config_set %(id)s but returning"
                      " 'not found'") % {
                          'id': id
                      }
            LOG.info(msg)
            raise exc.HTTPNotFound(body='config_set not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='config_set operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(_LE("Unable to update config_set %s") % id)
            raise
Example #18
0
    def update_host_template(self, req, template_id, host_template):
        """
        Updates an existing Template with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_host_template')
        # orig_Template_meta = self.get_Template_meta_or_404(req, id)
        '''
        if orig_Template_meta['deleted']:
            msg = _("Forbidden to update deleted Template.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        '''
        try:
            host_template = registry.update_host_template_metadata(
                req.context, template_id, host_template)

        except exception.Invalid as e:
            msg = (_("Failed to update template metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find host_template to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update host_template: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('host_template operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('host_template.update', host_template)

        return {'host_template': host_template}
Example #19
0
    def update_network(self, req, network_id, body):
        """Updates an existing network with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        network_data = body['network']
        try:
            updated_network = self.db_api.network_update(
                req.context, network_id, network_data)

            msg = _LI("Updating metadata for network %(network_id)s") % {
                'network_id': network_id
            }
            LOG.info(msg)
            if 'network' not in updated_network:
                network_data = dict(network=updated_network)
            return network_data
        except exception.Invalid as e:
            msg = (_("Failed to update network metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("Network %(network_id)s not found") % {
                'network_id': network_id
            }
            LOG.info(msg)
            raise exc.HTTPNotFound(body='Network not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for public network %(network_id)s") % {
                'network_id': network_id
            }
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden as e:
            LOG.info(e)
            raise exc.HTTPForbidden(e)
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='Network operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(_LE("Unable to update network %s") % network_id)
            raise
Example #20
0
    def delete_network(self, req, network_id):
        """
        Deletes a network from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about host

        :raises HTTPBadRequest if x-host-name is missing
        """
        self._enforce(req, 'delete_network')
        # self._raise_404_if_cluster_deleted(req, cluster_id)
        # self._raise_404_if_network_deleted(req, network_id)
        network = self.get_network_meta_or_404(req, network_id)
        if network['deleted']:
            msg = _("Network with identifier %s has been deleted.") % \
                network_id
            raise HTTPNotFound(msg)
        if network['type'] != 'custom':
            msg = _("Type of network was not custom, can not "
                    "delete this network.")
            raise HTTPForbidden(msg)
        try:
            registry.delete_network_metadata(req.context, network_id)
        except exception.NotFound as e:
            msg = (_("Failed to find network to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete network: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("Network %(id)s could not be deleted "
                     "because it is in use: "
                     "%(exc)s") % {
                         "id": id,
                         "exc": utils.exception_to_str(e)
                     })
            LOG.warning(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            # self.notifier.info('host.delete', host)
            return Response(body='', status=200)
Example #21
0
    def update_config_set(self, req, id, body):
        """Updates an existing config_set with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        config_set_data = body['config_set']
        try:
            updated_config_set = self.db_api.config_set_update(
                req.context, id, config_set_data)

            msg = _LI("Updating metadata for config_set %(id)s") % {'id': id}
            LOG.info(msg)
            if 'config_set' not in updated_config_set:
                config_set_data = dict(config_set=updated_config_set)
            return config_set_data
        except exception.Invalid as e:
            msg = (_("Failed to update config_set metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("config_set %(id)s not found") % {'id': id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='config_set not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for config_set %(id)s") % {'id': id}
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden:
            # If it's private and doesn't belong to them, don't let on
            # that it exists
            msg = _LI("Access denied to config_set %(id)s but returning"
                      " 'not found'") % {'id': id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='config_set not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='config_set operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(_LE("Unable to update config_set %s") % id)
            raise
Example #22
0
 def get_template_detail(self, req, template_id):
     """
     delete a existing cluster template with the registry.
     :param request: The WSGI/Webob Request object
     :param id: The opaque image identifie
     :retval Returns the updated image information as a mapping
     """
     self._enforce(req, 'get_template_detail')
     try:
         template = registry.template_detail_metadata(
             req.context, template_id)
         if template.get("tecs_version_id", None):
             template['tecs_version_id'] = ""
         obj = subprocess.Popen(
             "which daisy-manage >/dev/null "
             "&& daisy-manage db_version",
             shell=True,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE)
         (stdoutput, erroutput) = obj.communicate()
         if stdoutput:
             template['version'] = stdoutput.strip('\n')
         return {'template': template}
     except exception.NotFound as e:
         msg = (_("Failed to find template: %s") %
                utils.exception_to_str(e))
         LOG.error(msg)
         raise HTTPNotFound(explanation=msg,
                            request=req,
                            content_type="text/plain")
     except exception.Forbidden as e:
         msg = (_("Forbidden to get template: %s") %
                utils.exception_to_str(e))
         LOG.error(msg)
         raise HTTPForbidden(explanation=msg,
                             request=req,
                             content_type="text/plain")
     except exception.InUseByStore as e:
         msg = (_("template %(id)s could not be get because it is in use: "
                  "%(exc)s") % {
                      "id": template_id,
                      "exc": utils.exception_to_str(e)
                  })
         LOG.error(msg)
         raise HTTPConflict(explanation=msg,
                            request=req,
                            content_type="text/plain")
     else:
         return Response(body='', status=200)
Example #23
0
    def cinder_volume_update(self, req, id, body):
        """Updates an existing cinder_volume with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        cinder_volume_data = body['cinder_volume']
        try:
            updated_cinder_volume = self.db_api.cinder_volume_update(
                req.context, id, cinder_volume_data)

            msg = _LI("Updating metadata for cinder_volume %("
                      "cinder_volume_id)s") % {
                'cinder_volume_id': id}
            LOG.info(msg)
            if 'cinder_volume' not in updated_cinder_volume:
                cinder_volume_data = dict(cinder_volume=updated_cinder_volume)
            return cinder_volume_data
        except exception.Invalid as e:
            msg = (_("Failed to update cinder_volume metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("cinder_volume %(cinder_volume_id)s not found") % {
                'cinder_volume_id': id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='cinder_volume not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for public cinder_volume %("
                      "cinder_volume_id)s") % {
                'cinder_volume_id': id}
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden:
            raise
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='cinder_volume operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(_LE("Unable to update cinder_volume %s") % id)
            raise
Example #24
0
    def update_network(self, req, network_id, body):
        """Updates an existing network with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        network_data = body['network']
        try:
            updated_network = self.db_api.network_update(
                req.context, network_id, network_data)

            msg = _LI("Updating metadata for network %(network_id)s") % {
                'network_id': network_id}
            LOG.info(msg)
            if 'network' not in updated_network:
                network_data = dict(network=updated_network)
            return network_data
        except exception.Invalid as e:
            msg = (_("Failed to update network metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("Network %(network_id)s not found") % {
                'network_id': network_id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='Network not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for public network %(network_id)s") % {
                'network_id': network_id}
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden as e:
            LOG.info(e)
            raise exc.HTTPForbidden(e)
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='Network operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(_LE("Unable to update network %s") % network_id)
            raise
Example #25
0
    def delete_network(self, req, network_id):
        """
        Deletes a network from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about host

        :raises HTTPBadRequest if x-host-name is missing
        """
        self._enforce(req, 'delete_network')
        # self._raise_404_if_cluster_deleted(req, cluster_id)
        # self._raise_404_if_network_deleted(req, network_id)
        network = self.get_network_meta_or_404(req, network_id)
        if network['deleted']:
            msg = _("Network with identifier %s has been deleted.") % \
                network_id
            raise HTTPNotFound(msg)
        if network['type'] != 'custom':
            msg = _("Type of network was not custom, can not "
                    "delete this network.")
            raise HTTPForbidden(msg)
        try:
            registry.delete_network_metadata(req.context, network_id)
        except exception.NotFound as e:
            msg = (_("Failed to find network to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete network: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("Network %(id)s could not be deleted "
                     "because it is in use: "
                     "%(exc)s") % {"id": id, "exc": utils.exception_to_str(e)})
            LOG.warning(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            # self.notifier.info('host.delete', host)
            return Response(body='', status=200)
 def update(self, req, metadata_object, namespace, object_name):
     meta_repo = self.gateway.get_metadef_object_repo(req.context)
     try:
         metadef_object = meta_repo.get(namespace, object_name)
         metadef_object._old_name = metadef_object.name
         metadef_object.name = wsme_utils._get_value(
             metadata_object.name)
         metadef_object.description = wsme_utils._get_value(
             metadata_object.description)
         metadef_object.required = wsme_utils._get_value(
             metadata_object.required)
         metadef_object.properties = wsme_utils._get_value(
             metadata_object.properties)
         updated_metadata_obj = meta_repo.save(metadef_object)
     except exception.Forbidden as e:
         raise webob.exc.HTTPForbidden(explanation=e.msg)
     except exception.NotFound as e:
         raise webob.exc.HTTPNotFound(explanation=e.msg)
     except exception.Duplicate as e:
         raise webob.exc.HTTPConflict(explanation=e.msg)
     except Exception as e:
         LOG.error(utils.exception_to_str(e))
         raise webob.exc.HTTPInternalServerError()
     return MetadefObject.to_wsme_model(
         updated_metadata_obj,
         get_object_href(namespace, updated_metadata_obj),
         self.obj_schema_link)
Example #27
0
    def index(self, req, namespace, marker=None, limit=None,
              sort_key='created_at', sort_dir='desc', filters=None):
        try:
            filters = filters or dict()
            filters['namespace'] = namespace

            tag_repo = self.gateway.get_metadef_tag_repo(req.context)
            if marker:
                metadef_tag = tag_repo.get(namespace, marker)
                marker = metadef_tag.tag_id

            db_metatag_list = tag_repo.list(
                marker=marker, limit=limit, sort_key=sort_key,
                sort_dir=sort_dir, filters=filters)

            tag_list = [MetadefTag(**{'name': db_metatag.name})
                        for db_metatag in db_metatag_list]

            metadef_tags = MetadefTags()
            metadef_tags.tags = tag_list
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()

        return metadef_tags
Example #28
0
    def search(self, req, query, index, doc_type=None, fields=None, offset=0,
               limit=10):
        if fields is None:
            fields = []

        try:
            search_repo = self.gateway.get_catalog_search_repo(req.context)
            result = search_repo.search(index,
                                        doc_type,
                                        query,
                                        fields,
                                        offset,
                                        limit,
                                        True)

            for plugin in self.plugins:
                result = plugin.obj.filter_result(result, req.context)

            return result
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Duplicate as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()
Example #29
0
    def execute(self, image_id):
        """Finishing the task flow

        :param image_id: Glance Image ID
        """
        task = script_utils.get_task(self.task_repo, self.task_id)
        if task is None:
            return
        try:
            task.succeed({'image_id': image_id})
        except Exception as e:
            # Note: The message string contains Error in it to indicate
            # in the task.message that it's a error message for the user.

            # TODO(nikhil): need to bring back save_and_reraise_exception when
            # necessary
            err_msg = ("Error: " + six.text_type(type(e)) + ': ' +
                       common_utils.exception_to_str(e))
            log_msg = err_msg + _LE("Task ID %s") % task.task_id
            LOG.exception(log_msg)

            task.fail(err_msg)
        finally:
            self.task_repo.save(task)

        LOG.info(_LI("%(task_id)s of %(task_type)s completed") %
                 {'task_id': self.task_id, 'task_type': self.task_type})
Example #30
0
    def host_template_detail(self, req, template_id):
        """Registers a new service_disk with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the service_disk

        :retval Returns the newly-created service_disk information as a mapping,
                which will include the newly-created service_disk's internal id
                in the 'id' field
        """
        
        if template_id and not utils.is_uuid_like(template_id):
            msg = _LI("Rejecting template delete request for invalid template "
                      "id '%(bad_id)s'") % {'bad_id': template_id}
            LOG.info(msg)
            msg = _("Invalid template id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            template_data = self.db_api.host_template_get(req.context, template_id)
            #service_disk_data = dict(service_disk=make_image_dict(service_disk_data))
            msg = (_LI("Successfully get template information:%s") % template_id)
            LOG.info(msg)
            if 'template' not in template_data:
                template_data = dict(host_template=template_data)
            return template_data
        except exception.Invalid as e:
            msg = (_("Failed to get template metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to get template %s"), template_id)
            raise
Example #31
0
    def add_version(self, req, body):
        """Registers a new version with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the version

        :retval Returns the newly-created version information as a mapping,
                which will include the newly-created version's internal id
                in the 'id' field
        """

        version_data = body["version_metadata"]

        try:
            version_data = self.db_api.version_add(req.context, version_data)
            msg = (_LI("Successfully created node %s") %
                   version_data["id"])
            LOG.info(msg)
            version_data = dict(version_metadata=version_data)
            return version_data
        except exception.Duplicate:
            msg = (_("version with identifier %s already exists!") %
                   version_data['name'])
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add version metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create version %s"),
                          version_data['name'])
            raise
 def process(self, ctxt, publisher_id, event_type, payload, metadata):
     try:
         actions = {
             "metadef_namespace.create": self.create_ns,
             "metadef_namespace.update": self.update_ns,
             "metadef_namespace.delete": self.delete_ns,
             "metadef_object.create": self.create_obj,
             "metadef_object.update": self.update_obj,
             "metadef_object.delete": self.delete_obj,
             "metadef_property.create": self.create_prop,
             "metadef_property.update": self.update_prop,
             "metadef_property.delete": self.delete_prop,
             "metadef_resource_type.create": self.create_rs,
             "metadef_resource_type.delete": self.delete_rs,
             "metadef_tag.create": self.create_tag,
             "metadef_tag.update": self.update_tag,
             "metadef_tag.delete": self.delete_tag,
             "metadef_namespace.delete_properties": self.delete_props,
             "metadef_namespace.delete_objects": self.delete_objects,
             "metadef_namespace.delete_tags": self.delete_tags
         }
         actions[event_type](payload)
         return oslo_messaging.NotificationResult.HANDLED
     except Exception as e:
         LOG.error(utils.exception_to_str(e))
Example #33
0
 def get(self, req, task_id):
     try:
         task_repo = self.gateway.get_task_repo(req.context)
         task = task_repo.get(task_id)
     except exception.NotFound as e:
         msg = (_LW("Failed to find task %(task_id)s. Reason: %(reason)s") %
                {'task_id': task_id, 'reason': utils.exception_to_str(e)})
         LOG.warn(msg)
         raise webob.exc.HTTPNotFound(explanation=e.msg)
     except exception.Forbidden as e:
         msg = (_LW("Forbidden to get task %(task_id)s. Reason:"
                    " %(reason)s") %
                {'task_id': task_id, 'reason': utils.exception_to_str(e)})
         LOG.warn(msg)
         raise webob.exc.HTTPForbidden(explanation=e.msg)
     return task
Example #34
0
def safe_delete_from_backend(context, image_id, location):
    """
    Given a location, delete an image from the store and
    update location status to db.

    This function try to handle all known exceptions which might be raised
    by those calls on store and DB modules in its implementation.

    :param context: The request context
    :param image_id: The image identifier
    :param location: The image location entry
    """

    try:
        ret = store_api.delete_from_backend(location['url'], context=context)
        location['status'] = 'deleted'
        if 'id' in location:
            db_api.get_api().image_location_delete(context, image_id,
                                                   location['id'], 'deleted')
        return ret
    except store_api.NotFound:
        msg = _LW('Failed to delete image %s in store from URI') % image_id
        LOG.warn(msg)
    except store_api.StoreDeleteNotSupported as e:
        LOG.warn(utils.exception_to_str(e))
    except store_api.UnsupportedBackend:
        exc_type = sys.exc_info()[0].__name__
        msg = (_LE('Failed to delete image %(image_id)s from store: %(exc)s') %
               dict(image_id=image_id, exc=exc_type))
        LOG.error(msg)
Example #35
0
    def template_delete(self, req, template_id):
        """Registers a new template with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the template

        :retval Returns the newly-created template information as a mapping,
                which will include the newly-created template's internal id
                in the 'id' field
        """
        if template_id and not utils.is_uuid_like(template_id):
            msg = _LI("Rejecting template delete request for invalid template "
                      "id '%(bad_id)s'") % {
                          'bad_id': template_id
                      }
            LOG.info(msg)
            msg = _("Invalid template id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            template_data = self.db_api.template_destroy(
                req.context, template_id)
            msg = (_LI("Successfully deleted template %s") % template_id)
            LOG.info(msg)
            if 'template' not in template_data:
                template_data = dict(template=template_data)
            return template_data
        except exception.Invalid as e:
            msg = (_("Failed to delete template metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to delete template %s"), template_id)
            raise
    def update(self, req, user_ns, namespace):
        namespace_repo = self.gateway.get_metadef_namespace_repo(req.context)
        try:
            ns_obj = namespace_repo.get(namespace)
            ns_obj._old_namespace = ns_obj.namespace
            ns_obj.namespace = wsme_utils._get_value(user_ns.namespace)
            ns_obj.display_name = wsme_utils._get_value(user_ns.display_name)
            ns_obj.description = wsme_utils._get_value(user_ns.description)
            # Following optional fields will default to same values as in
            # create namespace if not specified
            ns_obj.visibility = (
                wsme_utils._get_value(user_ns.visibility) or 'private')
            ns_obj.protected = (
                wsme_utils._get_value(user_ns.protected) or False)
            ns_obj.owner = (
                wsme_utils._get_value(user_ns.owner) or req.context.owner)
            updated_namespace = namespace_repo.save(ns_obj)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Duplicate as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()

        return Namespace.to_wsme_model(updated_namespace,
                                       get_namespace_href(updated_namespace),
                                       self.ns_schema_link)
Example #37
0
def _execute(t_id, task_repo, image_repo, image_factory):
    task = script_utils.get_task(task_repo, t_id)

    if task is None:
        # NOTE: This happens if task is not found in the database. In
        # such cases, there is no way to update the task status so,
        # it's ignored here.
        return

    try:
        task_input = script_utils.unpack_task_input(task)

        uri = script_utils.validate_location_uri(task_input.get('import_from'))
        image_id = import_image(image_repo, image_factory, task_input, t_id,
                                uri)

        task.succeed({'image_id': image_id})
    except Exception as e:
        # Note: The message string contains Error in it to indicate
        # in the task.message that it's a error message for the user.

        # TODO(nikhil): need to bring back save_and_reraise_exception when
        # necessary
        err_msg = ("Error: " + six.text_type(type(e)) + ': ' +
                   common_utils.exception_to_str(e))
        log_msg = _LE(err_msg + ("Task ID %s" % task.task_id))  # noqa
        LOG.exception(log_msg)

        task.fail(_LE(err_msg))  # noqa
    finally:
        task_repo.save(task)
Example #38
0
    def detail(self, req, id):
        """Registers a new hwm with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the template

        :retval Returns the newly-created template information as a mapping,
                which will include the newly-created template's internal id
                in the 'id' field
        """
        if id and not utils.is_uuid_like(id):
            msg = _LI("Rejecting hwm delete request for invalid hwm "
                      "id '%(bad_id)s'") % {'bad_id': id}
            LOG.info(msg)
            msg = _("Invalid hwm id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            hwm_data = self.db_api.hwm_get(req.context, id)
            msg = (_LI("Successfully get hwm information:%s") % id)
            LOG.info(msg)
            if 'hwm' not in hwm_data:
                hwm_data = dict(hwm=hwm_data)
            return hwm_data
        except exception.Invalid as e:
            msg = (_("Failed to get hwm metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to get hwm %s"), id)
            raise
Example #39
0
    def add_host_patch_history(self, req, body):
        """Registers a new version with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the version

        :retval Returns the newly-created version information as a mapping,
                which will include the newly-created version's internal id
                in the 'id' field
        """

        patch_history_meta = body["patch_history"]
        try:
            patch_history = self.db_api.add_host_patch_history(
                req.context, patch_history_meta)
            version_data = dict(patch_history=patch_history)
            return version_data
        except exception.Duplicate:
            msg = (_("patch history with identifier %s already exists!") %
                   patch_history_meta['patch_name'])
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add patch history metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create patch history %s"),
                          patch_history_meta['patch_name'])
            raise
Example #40
0
    def update_version_patch(self, req, version_patch_id, body):
        """Updates an existing version with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        version_data = body['version_patch']
        try:
            updated_version_patch = self.db_api.version_patch_update(
                req.context, version_patch_id, version_data)

            msg = _LI("Updating metadata for version %s") % version_patch_id
            LOG.info(msg)
            version_data = dict(version_patch=updated_version_patch)
            return version_data
        except exception.Invalid as e:
            msg = (_("Failed to update version patch metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("version %(version_patch_id)s not found") % {
                'version_patch_id': version_patch_id
            }
            LOG.info(msg)
            raise exc.HTTPNotFound(body='version not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.ForbiddenPublicImage:
            msg = _LI("Update denied for public version %s") % version_patch_id
            LOG.info(msg)
            raise exc.HTTPForbidden()
        except exception.Forbidden as e:
            LOG.info(e)
            raise exc.HTTPForbidden(e)
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='version patch operation conflicts',
                                   request=req,
                                   content_type='text/plain')
        except Exception:
            LOG.exception(
                _LE("Unable to update version patch %s") % version_patch_id)
            raise
Example #41
0
    def delete_service(self, req, id):
        """
        Deletes a service from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about service

        :raises HTTPBadRequest if x-service-name is missing
        """
        self._enforce(req, 'delete_service')

        # service = self.get_service_meta_or_404(req, id)
        print "delete_service:%s" % id
        try:
            registry.delete_service_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find service to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete service: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("service %(id)s could not be deleted "
                     "because it is in use: "
                     "%(exc)s") % {
                         "id": id,
                         "exc": utils.exception_to_str(e)
                     })
            LOG.warning(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            # self.notifier.info('service.delete', service)
            return Response(body='', status=200)
Example #42
0
    def get_host_template_detail(self, req, template_id):
        """
        delete a existing cluster template with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'get_host_template_detail')
        try:
            host_template = registry.host_template_detail_metadata(
                req.context, template_id)
            return {'host_template': host_template}
        except exception.NotFound as e:
            msg = (_("Failed to find host template: %s") %
                   utils.exception_to_str(e))
            LOG.error(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to get host template: %s") %
                   utils.exception_to_str(e))
            LOG.error(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("host template %(id)s could not be get "
                     "because it is in use: "
                     "%(exc)s") % {
                         "id": template_id,
                         "exc": utils.exception_to_str(e)
                     })
            LOG.error(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            # self.notifier.info('host.delete', host)
            return Response(body='', status=200)
Example #43
0
    def delete_config(self, req, config_meta):
        """
        Deletes a config from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about config

        :raises HTTPBadRequest if x-config-name is missing
        """
        self._enforce(req, 'delete_config')

        try:
            for id in config_meta['config']:
                registry.delete_config_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find config to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete config: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("config %(id)s could not be "
                     "deleted because it is in use: "
                     "%(exc)s") % {
                         "id": id,
                         "exc": utils.exception_to_str(e)
                     })
            LOG.warning(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            # self.notifier.info('config.delete', config)
            return Response(body='', status=200)
Example #44
0
    def delete_cluster_host(self, req, cluster_id, host_id):
        """
        Delete a host with host_id from project with cluster_id.
        """
        self._enforce(req, 'delete_cluster_host')
        self._raise_404_if_project_deleted(req, cluster_id)
        self._raise_404_if_host_deleted(req, host_id)

        try:
            registry.delete_cluster_host(req.context, cluster_id, host_id)
            is_ssh_host = daisy_cmn._judge_ssh_host(req, host_id)
            host_data = {'tecs_version_id': '', 'tecs_patch_id': ''}
            if not is_ssh_host:
                host_data.update({'os_status': 'init'})
            registry.update_host_metadata(req.context, host_id, host_data)
        except exception.NotFound as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)
Example #45
0
    def get_host_projects(self, req, host_id):
        """
        Retrieves list of image memberships for the given member.

        :param req: the Request object coming from the wsgi layer
        :param id: the opaque member identifier
        :retval The response body is a mapping of the following form::

            {'multi_projects': [
                {'cluster_id': <PROJECT>, ...}, ...
            ]}
        """
        try:
            members = registry.get_host_projects(req.context, host_id)
        except exception.NotFound as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        return dict(multi_projects=members)
Example #46
0
    def add_cluster_host(self, req, cluster_id, host_id, body=None):
        """
        Adds a host with host_id to project with cluster_id.
        """
        self._enforce(req, 'add_cluster_host')
        self._raise_404_if_project_deleted(req, cluster_id)
        self._raise_404_if_host_deleted(req, host_id)

        try:
            registry.add_cluster_host(req.context, cluster_id, host_id)
        except exception.Invalid as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.NotFound as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug(utils.exception_to_str(e))
            raise webob.exc.HTTPNotFound(explanation=e.msg)

        return webob.exc.HTTPNoContent()
Example #47
0
    def optical_switch_update(self, req, id, body):
        """Updates an existing optical_switch with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the image
        :param id:  The opaque internal identifier for the image

        :retval Returns the updated image information as a mapping,
        """
        optical_switch_data = body['optical_switch']
        try:
            updated_optical_switch = self.db_api.optical_switch_update(
                req.context, id, optical_switch_data)

            msg = _LI("Updating metadata for optical_switch %("
                      "optical_switch_id)s") % {
                'optical_switch_id': id}
            LOG.info(msg)
            if 'optical_switch' not in updated_optical_switch:
                optical_switch_data = \
                    dict(optical_switch=updated_optical_switch)
            return optical_switch_data
        except exception.Invalid as e:
            msg = (_("Failed to update optical_switch metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except exception.NotFound:
            msg = _LI("optical_switch %(optical_switch_id)s "
                      "not found") % {'optical_switch_id': id}
            LOG.info(msg)
            raise exc.HTTPNotFound(body='optical_switch not found',
                                   request=req,
                                   content_type='text/plain')
        except exception.Conflict as e:
            LOG.info(utils.exception_to_str(e))
            raise exc.HTTPConflict(body='optical_switch '
                                        'operation conflicts',
                                   request=req,
                                   content_type='text/plain')
Example #48
0
    def cinder_volume_delete(self, req, id):
        """
        Deletes a service_disk from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about service_disk

        :raises HTTPBadRequest if x-service-disk-name is missing
        """
        self._enforce(req, 'delete_cinder_volume')
        try:
            registry.delete_cinder_volume_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find cinder volume to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete cinder volume: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("cindre volume %(id)s could not "
                     "be deleted because it is in use: "
                     "%(exc)s") % {
                         "id": id,
                         "exc": utils.exception_to_str(e)
                     })
            LOG.warning(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            return Response(body='', status=200)
Example #49
0
    def cinder_volume_add(self, req, body):
        """Registers a new cinder_volume with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the cinder_volume

        :retval Returns the newly-created cinder_volume
        information as a mapping,
                which will include the newly-created
                cinder_volume's internal id
                in the 'id' field
        """

        cinder_volume_data = body["cinder_volume"]

        id = cinder_volume_data.get('id')

        # role = service_disk_data.get('role')
        # add id and role
        # if role
        # self.db_api.get_role(req.context,role)

        if id and not utils.is_uuid_like(id):
            msg = _LI("Rejecting cinder_volume creation request for "
                      "invalid cinder_volume "
                      "id '%(bad_id)s'") % {'bad_id': id}
            LOG.info(msg)
            msg = _("Invalid cinder_volume id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            cinder_volume_data = self.db_api.cinder_volume_add(
                req.context, cinder_volume_data)
            msg = (_LI("Successfully created cinder_volume %s") %
                   cinder_volume_data["id"])
            LOG.info(msg)
            if 'cinder_volume' not in cinder_volume_data:
                cinder_volume_data = dict(cinder_volume=cinder_volume_data)
            return cinder_volume_data
        except exception.Duplicate:
            msg = _("cinder_volume with identifier %s already exists!") % id
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add cinder_volume metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create cinder_volume %s"), id)
            raise
Example #50
0
    def service_disk_update(self, req, id, disk_meta):
        self._enforce(req, 'service_disk_update')
        self._service_disk_update_meta_valid(req, id, disk_meta)
        try:
            service_disk_meta = registry.update_service_disk_metadata(
                req.context, id, disk_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update role metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find role to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update role: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('role.update', service_disk_meta)

        return {'disk_meta': service_disk_meta}
Example #51
0
    def add_network(self, req, body):
        """Registers a new network with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the network

        :retval Returns the newly-created network information as a mapping,
                which will include the newly-created network's internal id
                in the 'id' field
        """

        network_data = body["network"]

        network_id = network_data.get('id')

        # role = network_data.get('role')
        # add network_id and role
        # if role
        # self.db_api.get_role(req.context,role)

        if network_id and not utils.is_uuid_like(network_id):
            msg = _LI("Rejecting network creation request for invalid network "
                      "id '%(bad_id)s'") % {
                          'bad_id': network_id
                      }
            LOG.info(msg)
            msg = _("Invalid network id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            network_data = self.db_api.network_add(req.context, network_data)
            msg = (_LI("Successfully created node %s") % network_data["id"])
            LOG.info(msg)
            if 'network' not in network_data:
                network_data = dict(network=network_data)
            return network_data
        except exception.Duplicate:
            msg = _("node with identifier %s already exists!") % network_id
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add node metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create node %s"), network_id)
            raise
    def add_config_set(self, req, body):
        """Registers a new config_set with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the config_set

        :retval Returns the newly-created config_set information as a mapping,
                which will include the newly-created config_set's internal id
                in the 'id' field
        """

        config_set_data = body["config_set"]

        config_set_id = config_set_data.get('id')

        if config_set_id and not utils.is_uuid_like(config_set_id):
            msg = _LI("Rejecting config_set creation request for "
                      "invalid config_set "
                      "id '%(bad_id)s'") % {
                          'bad_id': config_set_id
                      }
            LOG.info(msg)
            msg = _("Invalid config_set id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            config_set_data = self.db_api.config_set_add(
                req.context, config_set_data)

            msg = (_LI("Successfully created config_set %s") %
                   config_set_data["id"])
            LOG.info(msg)
            if 'config_set' not in config_set_data:
                config_set_data = dict(config_set=config_set_data)
            return config_set_data
        except exception.Duplicate:
            msg = _("config_set with identifier %s already exists!") % \
                config_set_id
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add config_set metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create config_set %s"), config_set_id)
            raise
Example #53
0
def thread_bin(req, cluster_id, host, root_passwd, host_name_ip_list,
               host_prepare_file, docker_registry_ip, role_id_list):

    host_prepare_log = "/var/log/daisy/kolla_prepare_%s_%s.log" %\
                       (cluster_id, host['mgtip'])
    with open(host_prepare_log, "w+") as fp:
        try:
            _thread_bin(req, cluster_id, host, root_passwd, fp,
                        host_name_ip_list, host_prepare_file,
                        docker_registry_ip, role_id_list)
        except Exception as e:
            thread_flag['flag'] = False
            message = "Prepare for installation failed!"
            LOG.error(message)
            update_host_progress_to_db(req, role_id_list, host,
                                       kolla_state['INSTALL_FAILED'], message)
            fp.write(utils.exception_to_str(e))
Example #54
0
    def neutron_backend_add(self, req, body):
        """Registers a new neutron_backend with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the templatae

        :retval Returns the newly-created template information as a mapping,
                which will include the newly-created template's internal id
                in the 'id' field
        """
        neutron_backend_data = body["neutron_backend"]
        id = neutron_backend_data.get('id')

        if id and not utils.is_uuid_like(id):
            msg = _LI("Rejecting neutron_backend creation "
                      "request for invalid neutron_backend "
                      "id '%(bad_id)s'") % {
                          'bad_id': id
                      }
            LOG.info(msg)
            msg = _("Invalid neutron_backend id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            neutron_backend_data = self.db_api.neutron_backend_add(
                req.context, neutron_backend_data)
            msg = (_LI("Successfully created neutron_backend %s") %
                   neutron_backend_data["id"])
            LOG.info(msg)
            if 'neutron_backend' not in neutron_backend_data:
                neutron_backend_data = dict(
                    neutron_backend=neutron_backend_data)
            return neutron_backend_data
        except exception.Duplicate:
            msg = _("neutron_backend with identifier %s already exists!") % id
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add neutron_backend metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create neutron_backend %s"), id)
            raise
Example #55
0
    def host_template_update(self, req, template_id, body):
        """Registers a new service_disk with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the service_disk

        :retval Returns the newly-created service_disk information
        as a mapping,
                which will include the newly-created service_disk's internal id
                in the 'id' field
        """
        template_data = body["template"]
        # template_id = template_data.get('template_id')
        if template_id and not utils.is_uuid_like(template_id):
            msg = _LI("Rejecting cluster template creation request for "
                      "invalid template "
                      "id '%(bad_id)s'") % {
                          'bad_id': template_id
                      }
            LOG.info(msg)
            msg = _("Invalid template id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            template_data = self.db_api.host_template_update(
                req.context, template_id, template_data)
            msg = (_LI("Successfully updated template %s") %
                   template_data["id"])
            LOG.info(msg)
            if 'template' not in template_data:
                template_data = dict(host_template=template_data)
            return template_data
        except exception.Duplicate:
            msg = _("template with identifier %s already exists!") % \
                template_id
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to update template metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to update template %s"), template_id)
            raise
Example #56
0
    def add_version_patch(self, req, body):
        """Registers a new version with the registry.

        :param req: wsgi Request object
        :param body: Dictionary of information about the version

        :retval Returns the newly-created version information as a mapping,
                which will include the newly-created version's internal id
                in the 'id' field
        """

        version_patch_data = body["version_patch"]
        version_patch_id = version_patch_data.get('id')
        if version_patch_id and not utils.is_uuid_like(version_patch_id):
            msg = _LI("Rejecting version creation request for invalid version "
                      "id '%(bad_id)s'") % {
                          'bad_id': version_patch_id
                      }
            LOG.info(msg)
            msg = _("Invalid version id format")
            return exc.HTTPBadRequest(explanation=msg)

        try:
            version_patch_data = self.db_api.version_patch_add(
                req.context, version_patch_data)
            msg = (_LI("Successfully created node %s") %
                   version_patch_data["id"])
            LOG.info(msg)
            if 'version_patch' not in version_patch_data:
                version_patch_data = dict(version_patch=version_patch_data)
            return version_patch_data
        except exception.Duplicate:
            msg = (_("version patch with identifier %s"
                     " already exists!") % version_patch_id)
            LOG.warning(msg)
            return exc.HTTPConflict(msg)
        except exception.Invalid as e:
            msg = (_("Failed to add version patch metadata. "
                     "Got error: %s") % utils.exception_to_str(e))
            LOG.error(msg)
            return exc.HTTPBadRequest(msg)
        except Exception:
            LOG.exception(_LE("Unable to create node %s"), version_patch_id)
            raise