示例#1
0
文件: manager.py 项目: Bloomie/smaug
    def show_checkpoint(self, context, provider_id, checkpoint_id):
        # TODO(wangliuan)
        LOG.info(_LI("Starting show checkpoints. "
                     "provider_id:%s"), provider_id)
        LOG.info(_LI("checkpoint_id:%s"), checkpoint_id)

        return_stub = {
            "id": "2220f8b1-975d-4621-a872-fa9afb43cb6c",
            "project_id": "446a04d8-6ff5-4e0e-99a4-827a6389e9ff",
            "status": "committed",
            "protection_plan": {
                "id": "2a9ce1f3-cc1a-4516-9435-0ebb13caa398",
                "name": "My 3 tier application",
                "resources": [
                    {
                        "id": "64e51e85-4f31-441f-9a5d-6e93e3196628",
                        "type": "OS::Nova::Server",
                        "extended_info": {
                            "name": "VM1",
                            "backup status": "done",
                            "available_memory": 512
                        }
                    }
                ]
            },
            "provider_id": "efc6a88b-9096-4bb6-8634-cda182a6e12a"
        }
        return return_stub
示例#2
0
    def __exit__(self, ex_type, ex_value, ex_traceback):
        if not ex_value:
            return True

        if isinstance(ex_value, exception.NotAuthorized):
            raise Fault(webob.exc.HTTPForbidden(explanation=ex_value.msg))
        elif isinstance(ex_value, exception.Invalid):
            raise Fault(
                exception.ConvertedException(code=ex_value.code,
                                             explanation=ex_value.msg))
        elif isinstance(ex_value, TypeError):
            exc_info = (ex_type, ex_value, ex_traceback)
            LOG.error(_LE('Exception handling resource: %s'),
                      ex_value,
                      exc_info=exc_info)
            raise Fault(webob.exc.HTTPBadRequest())
        elif isinstance(ex_value, Fault):
            LOG.info(_LI("Fault thrown: %s"), ex_value)
            raise ex_value
        elif isinstance(ex_value, webob.exc.HTTPException):
            LOG.info(_LI("HTTP exception thrown: %s"), ex_value)
            raise Fault(ex_value)

        # We didn't handle the exception
        return False
示例#3
0
    def checkpoints_index(self, req, provider_id):
        """Returns a list of checkpoints, transformed through view builder."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show checkpoints list. "
                     "provider_id:%s"), provider_id)

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        utils.remove_invalid_filter_options(
            context,
            filters,
            self._get_checkpoint_filter_options())

        utils.check_filters(filters)
        checkpoints = self._checkpoints_get_all(
            context, provider_id, marker, limit,
            sort_keys=sort_keys, sort_dirs=sort_dirs,
            filters=filters, offset=offset)

        retval_checkpoints = self._checkpoint_view_builder.detail_list(
            req, checkpoints)

        LOG.info(_LI("Show checkpoints list request issued successfully."))

        return retval_checkpoints
示例#4
0
    def index(self, req):
        """Returns a list of plans, transformed through view builder."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show plan list"), context=context)

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        utils.remove_invalid_filter_options(context, filters,
                                            self._get_plan_filter_options())

        utils.check_filters(filters)
        plans = self._get_all(context,
                              marker,
                              limit,
                              sort_keys=sort_keys,
                              sort_dirs=sort_dirs,
                              filters=filters,
                              offset=offset)

        retval_plans = self._view_builder.detail_list(req, plans)

        LOG.info(_LI("Show plan list request issued successfully."))

        return retval_plans
示例#5
0
    def show_checkpoint(self, context, provider_id, checkpoint_id):
        # TODO(wangliuan)
        LOG.info(_LI("Starting show checkpoints. "
                     "provider_id:%s"), provider_id)
        LOG.info(_LI("checkpoint_id:%s"), checkpoint_id)

        return_stub = {
            "id": "6f193601-39f8-4a81-993b-4d847393a0ee",
            "project_id": "446a04d8-6ff5-4e0e-99a4-827a6389e9ff",
            "status": "committed",
            "protection_plan": {
                "id": "2a9ce1f3-cc1a-4516-9435-0ebb13caa398",
                "name": "My 3 tier application",
                "resources": [
                    {
                        "id": "64e51e85-4f31-441f-9a5d-6e93e3196628",
                        "type": "OS::Nova::Server",
                        "extended_info": {
                            "name": "VM1",
                            "backup status": "done",
                            "available_memory": 512
                        }
                    }
                ]
            },
            "provider_id": "cf56bd3e-97a7-4078-b6d5-f36246333fd9"
        }
        return return_stub
示例#6
0
    def checkpoints_index(self, req, provider_id):
        """Returns a list of checkpoints, transformed through view builder."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show checkpoints list. " "provider_id:%s"), provider_id)

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        utils.remove_invalid_filter_options(
            context, filters, self._get_checkpoint_filter_options())

        utils.check_filters(filters)
        checkpoints = self._checkpoints_get_all(context,
                                                provider_id,
                                                marker,
                                                limit,
                                                sort_keys=sort_keys,
                                                sort_dirs=sort_dirs,
                                                filters=filters,
                                                offset=offset)

        retval_checkpoints = self._checkpoint_view_builder.detail_list(
            req, checkpoints)

        LOG.info(_LI("Show checkpoints list request issued successfully."))

        return retval_checkpoints
示例#7
0
    def show(self, req, id):
        """Return data about the given protectable_type."""
        context = req.environ['smaug.context']
        protectable_type = id
        LOG.info(
            _LI("Show the information of a given"
                " protectable type: %s"), protectable_type)

        protectable_types = self._get_all(context)

        if protectable_type not in protectable_types:
            msg = _("Invalid protectable type provided.")
            raise exception.InvalidInput(reason=msg)

        check_policy(context, 'get')
        try:
            retval_protectable_type = self.protection_api.\
                show_protectable_type(context, protectable_type)
        except exception.ProtectableTypeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(
            _LI("Show the protectable type information"
                " issued successfully."))
        return self._view_builder.show(req, retval_protectable_type)
示例#8
0
    def show_checkpoint(self, context, provider_id, checkpoint_id):
        # TODO(wangliuan)
        LOG.info(_LI("Starting show checkpoints. "
                     "provider_id:%s"), provider_id)
        LOG.info(_LI("checkpoint_id:%s"), checkpoint_id)

        return_stub = {
            "id": "2220f8b1-975d-4621-a872-fa9afb43cb6c",
            "project_id": "446a04d8-6ff5-4e0e-99a4-827a6389e9ff",
            "status": "committed",
            "protection_plan": {
                "id":
                "2a9ce1f3-cc1a-4516-9435-0ebb13caa398",
                "name":
                "My 3 tier application",
                "resources": [{
                    "id": "64e51e85-4f31-441f-9a5d-6e93e3196628",
                    "type": "OS::Nova::Server",
                    "extended_info": {
                        "name": "VM1",
                        "backup status": "done",
                        "available_memory": 512
                    }
                }]
            },
            "provider_id": "efc6a88b-9096-4bb6-8634-cda182a6e12a"
        }
        return return_stub
示例#9
0
文件: restores.py 项目: Bloomie/smaug
    def index(self, req):
        """Returns a list of restores, transformed through view builder."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show restore list"), context=context)

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        utils.remove_invalid_filter_options(
            context,
            filters,
            self._get_restore_filter_options())

        utils.check_filters(filters)
        restores = self._get_all(context, marker, limit,
                                 sort_keys=sort_keys,
                                 sort_dirs=sort_dirs,
                                 filters=filters,
                                 offset=offset)

        retval_restores = self._view_builder.detail_list(req, restores)

        LOG.info(_LI("Show restore list request issued successfully."))

        return retval_restores
示例#10
0
    def show(self, req, id):
        """Return data about the given provider id."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show provider with id: %s"), id)

        try:
            provider = self._provider_get(context, id)
        except exception.ProviderNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show provider request issued successfully."),
                 resource={'id': provider.get("id")})
        return self._view_builder.detail(req, provider)
示例#11
0
    def show(self, req, id):
        """Return data about the given provider id."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show provider with id: %s"), id)

        try:
            provider = self._provider_get(context, id)
        except exception.ProviderNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show provider request issued successfully."),
                 resource={'id': provider.get("id")})
        return self._view_builder.detail(req, provider)
示例#12
0
    def delete(self, req, id):
        """Delete a plan."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Delete plan with id: %s"), id, context=context)

        try:
            plan = self._plan_get(context, id)
        except exception.PlanNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        check_policy(context, 'delete', plan)
        plan.destroy()
        LOG.info(_LI("Delete plan request issued successfully."),
                 resource={'id': plan.id})
示例#13
0
    def index(self, req):
        """Returns a list of protectable_types,

        transformed through view builder.
        """
        context = req.environ['smaug.context']
        LOG.info(_LI("Show protectable type list"), context=context)

        protectable_types = self._get_all(context)
        retval_protectable_types = {"protectable_type": protectable_types}

        LOG.info(
            _LI("Show protectable type list request issued"
                " successfully."))
        return retval_protectable_types
示例#14
0
def create(context, conf):
    register_opts(conf)

    if hasattr(conf.swift_client, 'swift_auth_url') and \
            conf.swift_client.swift_auth_url:
        connection = swift.Connection(
            authurl=conf.swift_client.swift_auth_url,
            auth_version=conf.swift_client.swift_auth_version,
            tenant_name=conf.swift_client.swift_tenant_name,
            user=conf.swift_client.swift_user,
            key=conf.swift_client.swift_key,
            retries=conf.swift_client.swift_retry_attempts,
            starting_backoff=conf.swift_client.swift_retry_backoff,
            insecure=conf.swift_client.swift_auth_insecure,
            cacert=conf.swift_client.swift_ca_cert_file)
    else:
        try:
            url = utils.get_url(SERVICE, context, conf,
                                append_project_fmt='%(url)s/AUTH_%(project)s')
        except Exception:
            LOG.error(_LE("Get swift service endpoint url failed"))
            raise
        LOG.info(_LI("Creating swift client with url %s."), url)
        connection = swift.Connection(
            preauthurl=url,
            preauthtoken=context.auth_token,
            retries=conf.swift_client.swift_retry_attempts,
            starting_backoff=conf.swift_client.swift_retry_backoff,
            insecure=conf.swift_client.swift_auth_insecure,
            cacert=conf.swift_client.swift_ca_cert_file)
    return connection
示例#15
0
def create(context, conf):
    conf.register_opts(nova_client_opts, group=SERVICE + '_client')
    try:
        url = utils.get_url(SERVICE,
                            context,
                            conf,
                            append_project_fmt='%(url)s/%(project)s')
    except Exception:
        LOG.error(_LE("Get nova service endpoint url failed."))
        raise

    LOG.info(_LI('Creating nova client with url %s.'), url)

    extensions = nc.discover_extensions(NOVACLIENT_VERSION)

    args = {
        'project_id': context.project_id,
        'auth_token': context.auth_token,
        'extensions': extensions,
    }

    client = nc.Client(NOVACLIENT_VERSION, **args)
    client.client.set_management_url(url)

    return client
示例#16
0
    def _get_all(self, context):
        check_policy(context, 'get_all')

        protectable_types = self.protection_api.list_protectable_types(context)

        LOG.info(_LI("Get all protectable types completed successfully."))
        return protectable_types
示例#17
0
    def _checkpoints_get_all(self, context, provider_id, marker=None,
                             limit=None, sort_keys=None, sort_dirs=None,
                             filters=None, offset=None):
        check_policy(context, 'checkpoint_get_all')

        if filters is None:
            filters = {}

        try:
            if limit is not None:
                limit = int(limit)
                if limit <= 0:
                    msg = _('limit param must be positive')
                    raise exception.InvalidInput(reason=msg)
        except ValueError:
            msg = _('limit param must be an integer')
            raise exception.InvalidInput(reason=msg)

        if filters:
            LOG.debug("Searching by: %s.", six.text_type(filters))

        checkpoints = self.protection_api.list_checkpoints(
            context, provider_id, marker, limit,
            sort_keys=sort_keys,
            sort_dirs=sort_dirs,
            filters=filters,
            offset=offset)

        LOG.info(_LI("Get all checkpoints completed successfully."))
        return checkpoints
示例#18
0
文件: manager.py 项目: Bloomie/smaug
    def delete(self, context, provider_id, checkpoint_id):
        # TODO(wangliuan)
        LOG.info(_LI("Starting protection service:delete action"))
        LOG.debug('provider_id :%s checkpoint_id:%s', provider_id,
                  checkpoint_id)

        return True
示例#19
0
文件: manager.py 项目: Bloomie/smaug
    def restore(self, context, restore=None):
        LOG.info(_LI("Starting restore service:restore action"))
        LOG.debug('restore :%s tpye:%s', restore,
                  type(restore))

        # TODO(wangliuan)
        return True
示例#20
0
    def list_protectable_instances(self, context,
                                   protectable_type=None,
                                   marker=None,
                                   limit=None,
                                   sort_keys=None,
                                   sort_dirs=None,
                                   filters=None):

        LOG.info(_LI("Start to list protectable instances of type: %s"),
                 protectable_type)

        try:
            resource_instances = self.protectable_registry.list_resources(
                context, protectable_type)
        except exception.ListProtectableResourceFailed as err:
            LOG.error(_LE("List resources of type %(type)s failed: %(err)s"),
                      {'type': protectable_type,
                       'err': six.text_type(err)})
            raise

        result = []
        for resource in resource_instances:
            result.append(dict(id=resource.id, name=resource.name))

        return result
示例#21
0
文件: manager.py 项目: Bloomie/smaug
    def list_checkpoints(self, context, provider_id, marker=None, limit=None,
                         sort_keys=None, sort_dirs=None, filters=None):
        LOG.info(_LI("Starting list checkpoints. "
                     "provider_id:%s"), provider_id)

        return_stub = [
            {
                "id": "2220f8b1-975d-4621-a872-fa9afb43cb6c",
                "project_id": "446a04d8-6ff5-4e0e-99a4-827a6389e9ff",
                "status": "comitted",
                "provider_id": "efc6a88b-9096-4bb6-8634-cda182a6e12a",
                "protection_plan": {
                    "id": "2a9ce1f3-cc1a-4516-9435-0ebb13caa398",
                    "name": "My 3 tier application",
                    "resources": [
                        {
                            "id": "64e51e85-4f31-441f-9a5d-6e93e3196628",
                            "type": "OS::Nova::Server"
                        },
                        {
                            "id": "61e51e85-4f31-441f-9a5d-6e93e3196628",
                            "type": "OS::Cinder::Volume"
                        },
                        {
                            "id": "62e51e85-4f31-441f-9a5d-6e93e3196628",
                            "type": "OS::Cinder::Volume"
                        }
                    ],
                }
            }
        ]
        return return_stub
示例#22
0
    def list_protectable_dependents(self, context, protectable_id,
                                    protectable_type):
        LOG.info(
            _LI("Start to list dependents of resource "
                "(type:%(type)s, id:%(id)s)"), {
                    'type': protectable_type,
                    'id': protectable_id
                })

        parent_resource = Resource(type=protectable_type,
                                   id=protectable_id,
                                   name="")

        try:
            dependent_resources = \
                self.protectable_registry.fetch_dependent_resources(
                    context, parent_resource)
        except exception.ListProtectableResourceFailed as err:
            LOG.error(
                _LE("List dependent resources of (%(res)s) "
                    "failed: %(err)s"), {
                        'res': parent_resource,
                        'err': six.text_type(err)
                    })
            raise

        result = []
        for resource in dependent_resources:
            result.append(
                dict(type=resource.type, id=resource.id, name=resource.name))

        return result
示例#23
0
def create(context, conf, **kwargs):
    auth_url = kwargs["auth_url"]
    username = kwargs["username"]
    password = kwargs["password"]
    tenant_name = context.project_name
    LOG.info(_LI('Creating heat client with url %s.'), auth_url)
    try:
        keystone = kc.Client(version=KEYSTONECLIENT_VERSION,
                             username=username,
                             tenant_name=tenant_name,
                             password=password,
                             auth_url=auth_url)

        auth_token = keystone.auth_ref['token']['id']
        heat_endpoint = ''
        services = keystone.auth_ref['serviceCatalog']
        for service in services:
            if service['name'] == 'heat':
                heat_endpoint = service['endpoints'][0]['publicURL']
        heat = hc.Client(HEATCLIENT_VERSION, endpoint=heat_endpoint,
                         token=auth_token)
        return heat
    except Exception:
        LOG.error(_LE('Creating heat client with url %s.'), auth_url)
        raise
示例#24
0
    def protect(self, context, plan):
        """create protection for the given plan

        :param plan: Define that protection plan should be done
        """

        LOG.info(_LI("Starting protection service:protect action"))
        LOG.debug('protecting  :%s tpye:%s', plan, type(plan))

        if not plan:
            raise exception.InvalidPlan(reason='the protection plan is None')
        provider_id = plan.get('provider_id', None)
        plan_id = plan.get('id', None)
        provider = self.provider_registry.show_provider(provider_id)
        if not provider:
            raise exception.ProviderNotFound(provider_id=provider_id)
        try:
            protection_flow = self.worker.get_flow(context,
                                                   constants.OPERATION_PROTECT,
                                                   plan=plan,
                                                   provider=provider)
        except Exception:
            LOG.exception(_LE("Failed to create protection flow,plan:%s"),
                          plan_id)
            raise exception.SmaugException(
                _("Failed to create protection flow"))
        try:
            self.worker.run_flow(protection_flow)
        except Exception:
            LOG.exception(_LE("Failed to run protection flow"))
            raise
        finally:
            checkpoint = self.worker.flow_outputs(protection_flow,
                                                  target='checkpoint')
            return {'checkpoint_id': checkpoint.id}
示例#25
0
文件: manager.py 项目: Bloomie/smaug
    def list_protectable_dependents(self, context,
                                    protectable_id,
                                    protectable_type):
        LOG.info(_LI("Start to list dependents of resource "
                     "(type:%(type)s, id:%(id)s)"),
                 {'type': protectable_type,
                  'id': protectable_id})

        parent_resource = Resource(type=protectable_type, id=protectable_id,
                                   name="")

        try:
            dependent_resources = \
                self.protectable_registry.fetch_dependent_resources(
                    context, parent_resource)
        except exception.ListProtectableResourceFailed as err:
            LOG.error(_LE("List dependent resources of (%(res)s) "
                          "failed: %(err)s"),
                      {'res': parent_resource,
                       'err': six.text_type(err)})
            raise

        result = []
        for resource in dependent_resources:
            result.append(dict(type=resource.type, id=resource.id,
                               name=resource.name))

        return result
示例#26
0
    def instances_show(self, req, protectable_type, protectable_id):
        """Return a instance about the given protectable_type and id."""

        context = req.environ['smaug.context']
        LOG.info(_LI("Show the instance of a given protectable"
                     " type: %s"), protectable_type)

        protectable_types = self._get_all(context)

        if protectable_type not in protectable_types:
            msg = _("Invalid protectable type provided.")
            raise exception.InvalidInput(reason=msg)

        instance = self.protection_api.\
            show_protectable_instance(context, protectable_type,
                                      protectable_id)
        if instance is None:
            raise exception.InvalidProtectableInstance(
                protectable_id=instance.get('id'))

        dependents = self.protection_api.\
            list_protectable_dependents(context, protectable_id,
                                        protectable_type)
        instance["dependent_resources"] = dependents

        retval_instance = self._view_builder.detail(req, instance)
        return retval_instance
示例#27
0
    def instances_show(self, req, protectable_type, protectable_id):
        """Return a instance about the given protectable_type and id."""

        context = req.environ['smaug.context']
        LOG.info(_LI("Show the instance of a given protectable"
                     " type: %s"), protectable_type)

        protectable_types = self._get_all(context)

        if protectable_type not in protectable_types:
            msg = _("Invalid protectable type provided.")
            raise exception.InvalidInput(reason=msg)

        instance = self.protection_api.\
            show_protectable_instance(context, protectable_type,
                                      protectable_id)
        if instance is None:
            raise exception.InvalidProtectableInstance(
                protectable_id=instance.get('id'))

        dependents = self.protection_api.\
            list_protectable_dependents(context, protectable_id,
                                        protectable_type)
        instance["dependent_resources"] = dependents

        retval_instance = self._view_builder.detail(req, instance)
        return retval_instance
示例#28
0
    def delete(self, context, provider_id, checkpoint_id):
        # TODO(wangliuan)
        LOG.info(_LI("Starting protection service:delete action"))
        LOG.debug('provider_id :%s checkpoint_id:%s', provider_id,
                  checkpoint_id)

        return True
示例#29
0
    def list_checkpoints(self,
                         context,
                         provider_id,
                         marker=None,
                         limit=None,
                         sort_keys=None,
                         sort_dirs=None,
                         filters=None):
        LOG.info(_LI("Starting list checkpoints. "
                     "provider_id:%s"), provider_id)

        return_stub = [{
            "id": "2220f8b1-975d-4621-a872-fa9afb43cb6c",
            "project_id": "446a04d8-6ff5-4e0e-99a4-827a6389e9ff",
            "status": "comitted",
            "provider_id": "efc6a88b-9096-4bb6-8634-cda182a6e12a",
            "protection_plan": {
                "id":
                "2a9ce1f3-cc1a-4516-9435-0ebb13caa398",
                "name":
                "My 3 tier application",
                "resources": [{
                    "id": "64e51e85-4f31-441f-9a5d-6e93e3196628",
                    "type": "OS::Nova::Server"
                }, {
                    "id": "61e51e85-4f31-441f-9a5d-6e93e3196628",
                    "type": "OS::Cinder::Volume"
                }, {
                    "id": "62e51e85-4f31-441f-9a5d-6e93e3196628",
                    "type": "OS::Cinder::Volume"
                }],
            }
        }]
        return return_stub
示例#30
0
    def _get_all(self, context):
        check_policy(context, 'get_all')

        protectable_types = self.protection_api.list_protectable_types(context)

        LOG.info(_LI("Get all protectable types completed successfully."))
        return protectable_types
示例#31
0
    def index(self, req):
        """Returns a list of protectable_types,

        transformed through view builder.
        """
        context = req.environ['smaug.context']
        LOG.info(_LI("Show protectable type list"), context=context)

        protectable_types = self._get_all(context)
        retval_protectable_types = {
            "protectable_type": protectable_types
        }

        LOG.info(_LI("Show protectable type list request issued"
                     " successfully."))
        return retval_protectable_types
示例#32
0
 def _plan_update(self, context, plan, fields):
     if plan['status'] != 'suspended':
         LOG.info(
             _LI("Unable to update plan, "
                 "because it is in %s state."), plan['status'])
         msg = _("The plan can be only updated in suspended status.")
         raise exception.InvalidPlan(reason=msg)
     # TODO(chenying) replication scene: need call rpc API when
     # the status of the plan is changed.
     if isinstance(plan, objects_base.SmaugObject):
         plan.update(fields)
         plan.save()
         LOG.info(_LI("Plan updated successfully."), resource=plan)
     else:
         msg = _("The parameter plan must be a object of "
                 "SmaugObject class.")
         raise exception.InvalidInput(reason=msg)
示例#33
0
文件: restores.py 项目: Bloomie/smaug
    def show(self, req, id):
        """Return data about the given restore."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show restore with id: %s"), id, context=context)

        if not uuidutils.is_uuid_like(id):
            msg = _("Invalid restore id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            restore = self._restore_get(context, id)
        except exception.RestoreNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show restore request issued successfully."),
                 resource={'id': restore.id})
        return self._view_builder.detail(req, restore)
示例#34
0
    def show(self, req, id):
        """Return data about the given plan."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show plan with id: %s"), id, context=context)

        if not uuidutils.is_uuid_like(id):
            msg = _("Invalid plan id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            plan = self._plan_get(context, id)
        except exception.PlanNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show plan request issued successfully."),
                 resource={'id': plan.id})
        return self._view_builder.detail(req, plan)
示例#35
0
    def checkpoints_show(self, req, provider_id, checkpoint_id):
        """Return data about the given checkpoint id."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show checkpoint with id: %s."), checkpoint_id)
        LOG.info(_LI("provider_id: %s."), provider_id)

        try:
            checkpoint = self._checkpoint_get(context, provider_id,
                                              checkpoint_id)
        except exception.CheckpointNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show checkpoint request issued successfully."))
        LOG.info(_LI("checkpoint: %s"), checkpoint)
        retval = self._checkpoint_view_builder.detail(req, checkpoint)
        LOG.info(_LI("retval: %s"), retval)
        return retval
示例#36
0
    def checkpoints_show(self, req, provider_id, checkpoint_id):
        """Return data about the given checkpoint id."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Show checkpoint with id: %s."),
                 checkpoint_id)
        LOG.info(_LI("provider_id: %s."), provider_id)

        try:
            checkpoint = self._checkpoint_get(context, provider_id,
                                              checkpoint_id)
        except exception.CheckpointNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show checkpoint request issued successfully."))
        LOG.info(_LI("checkpoint: %s"), checkpoint)
        retval = self._checkpoint_view_builder.detail(req, checkpoint)
        LOG.info(_LI("retval: %s"), retval)
        return retval
示例#37
0
    def checkpoints_delete(self, req, provider_id, checkpoint_id):
        """Delete a checkpoint."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Delete checkpoint with id: %s."), checkpoint_id)
        LOG.info(_LI("provider_id: %s."), provider_id)

        if not uuidutils.is_uuid_like(provider_id):
            msg = _("Invalid provider id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        if not uuidutils.is_uuid_like(checkpoint_id):
            msg = _("Invalid checkpoint id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        check_policy(context, 'checkpoint_delete')
        self.protection_api.delete(context, provider_id, checkpoint_id)

        LOG.info(_LI("Delete checkpoint request issued successfully."))
        return {}
示例#38
0
文件: manager.py 项目: Bloomie/smaug
    def protect(self, context, plan):
        """create protection for the given plan

        :param plan: Define that protection plan should be done
        """
        LOG.info(_LI("Starting protection service:protect action"))
        LOG.debug('protecting  :%s tpye:%s', plan,
                  type(plan))

        # TODO(wangliuan)
        return True
示例#39
0
    def _get_all(self,
                 context,
                 marker=None,
                 limit=None,
                 sort_keys=None,
                 sort_dirs=None,
                 filters=None,
                 offset=None):
        check_policy(context, 'get_all')

        if filters is None:
            filters = {}

        all_tenants = utils.get_bool_param('all_tenants', filters)

        try:
            if limit is not None:
                limit = int(limit)
                if limit <= 0:
                    msg = _('limit param must be positive')
                    raise exception.InvalidInput(reason=msg)
        except ValueError:
            msg = _('limit param must be an integer')
            raise exception.InvalidInput(reason=msg)

        if filters:
            LOG.debug("Searching by: %s.", six.text_type(filters))

        if context.is_admin and all_tenants:
            # Need to remove all_tenants to pass the filtering below.
            del filters['all_tenants']
            restores = objects.RestoreList.get_all(context,
                                                   marker,
                                                   limit,
                                                   sort_keys=sort_keys,
                                                   sort_dirs=sort_dirs,
                                                   filters=filters,
                                                   offset=offset)
        else:
            restores = objects.RestoreList.get_all_by_project(
                context,
                context.project_id,
                marker,
                limit,
                sort_keys=sort_keys,
                sort_dirs=sort_dirs,
                filters=filters,
                offset=offset)

        LOG.info(_LI("Get all restores completed successfully."))
        return restores
示例#40
0
    def show(self, req, id):
        """Return data about the given protectable_type."""
        context = req.environ['smaug.context']
        protectable_type = id
        LOG.info(_LI("Show the information of a given"
                     " protectable type: %s"), protectable_type)

        protectable_types = self._get_all(context)

        if protectable_type not in protectable_types:
            msg = _("Invalid protectable type provided.")
            raise exception.InvalidInput(reason=msg)

        check_policy(context, 'get')
        try:
            retval_protectable_type = self.protection_api.\
                show_protectable_type(context, protectable_type)
        except exception.ProtectableTypeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        LOG.info(_LI("Show the protectable type information"
                     " issued successfully."))
        return self._view_builder.show(req, retval_protectable_type)
示例#41
0
    def _restore_get(self, context, restore_id):
        if not uuidutils.is_uuid_like(restore_id):
            msg = _("Invalid restore id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        restore = objects.Restore.get_by_id(context, restore_id)
        try:
            check_policy(context, 'get', restore)
        except exception.PolicyNotAuthorized:
            # raise RestoreNotFound instead to make sure smaug behaves
            # as it used to
            raise exception.RestoreNotFound(restore_id=restore_id)
        LOG.info(_LI("Restore info retrieved successfully."))
        return restore
示例#42
0
    def wait(self):
        """Block, until the server has stopped.

        Waits on the server's eventlet to finish, then returns.

        :returns: None

        """
        try:
            if self._server is not None:
                self._pool.waitall()
                self._server.wait()
        except greenlet.GreenletExit:
            LOG.info(_LI("WSGI server has stopped."))
示例#43
0
    def _plan_get(self, context, plan_id):
        if not uuidutils.is_uuid_like(plan_id):
            msg = _("Invalid plan id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        plan = objects.Plan.get_by_id(context, plan_id)
        try:
            check_policy(context, 'get', plan)
        except exception.PolicyNotAuthorized:
            # raise PlanNotFound instead to make sure smaug behaves
            # as it used to
            raise exception.PlanNotFound(plan_id=plan_id)
        LOG.info(_LI("Plan info retrieved successfully."), resource=plan)
        return plan
示例#44
0
    def stop(self):
        """Stop this server.

        This is not a very nice action, as currently the method by which a
        server is stopped is by killing its eventlet.

        :returns: None

        """
        LOG.info(_LI("Stopping WSGI server."))
        if self._server is not None:
            # Resize pool to stop new requests from being processed
            self._pool.resize(0)
            self._server.kill()
示例#45
0
文件: restores.py 项目: Bloomie/smaug
    def _restore_update(self, context, restore_id, fields):
        try:
            restore = self._restore_get(context, restore_id)
        except exception.RestoreNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        if isinstance(restore, objects_base.SmaugObject):
            restore.update(fields)
            restore.save()
            LOG.info(_LI("restore updated successfully."))
        else:
            msg = _("The parameter restore must be a object of "
                    "SmaugObject class.")
            raise exception.InvalidInput(reason=msg)
示例#46
0
    def _restore_update(self, context, restore_id, fields):
        try:
            restore = self._restore_get(context, restore_id)
        except exception.RestoreNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        if isinstance(restore, objects_base.SmaugObject):
            restore.update(fields)
            restore.save()
            LOG.info(_LI("restore updated successfully."))
        else:
            msg = _("The parameter restore must be a object of "
                    "SmaugObject class.")
            raise exception.InvalidInput(reason=msg)
示例#47
0
    def checkpoints_delete(self, req, provider_id, checkpoint_id):
        """Delete a checkpoint."""
        context = req.environ['smaug.context']

        LOG.info(_LI("Delete checkpoint with id: %s."),
                 checkpoint_id)
        LOG.info(_LI("provider_id: %s."), provider_id)

        if not uuidutils.is_uuid_like(provider_id):
            msg = _("Invalid provider id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        if not uuidutils.is_uuid_like(checkpoint_id):
            msg = _("Invalid checkpoint id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        check_policy(context, 'checkpoint_delete')
        self.protection_api.delete(context,
                                   provider_id,
                                   checkpoint_id)

        LOG.info(_LI("Delete checkpoint request issued successfully."))
        return {}
示例#48
0
文件: restores.py 项目: Bloomie/smaug
    def _restore_get(self, context, restore_id):
        if not uuidutils.is_uuid_like(restore_id):
            msg = _("Invalid restore id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        restore = objects.Restore.get_by_id(context, restore_id)
        try:
            check_policy(context, 'get', restore)
        except exception.PolicyNotAuthorized:
            # raise RestoreNotFound instead to make sure smaug behaves
            # as it used to
            raise exception.RestoreNotFound(restore_id=restore_id)
        LOG.info(_LI("Restore info retrieved successfully."))
        return restore
示例#49
0
    def stop(self):
        """Stop this server.

        This is not a very nice action, as currently the method by which a
        server is stopped is by killing its eventlet.

        :returns: None

        """
        LOG.info(_LI("Stopping WSGI server."))
        if self._server is not None:
            # Resize pool to stop new requests from being processed
            self._pool.resize(0)
            self._server.kill()
示例#50
0
    def wait(self):
        """Block, until the server has stopped.

        Waits on the server's eventlet to finish, then returns.

        :returns: None

        """
        try:
            if self._server is not None:
                self._pool.waitall()
                self._server.wait()
        except greenlet.GreenletExit:
            LOG.info(_LI("WSGI server has stopped."))
示例#51
0
文件: wsgi.py 项目: Bloomie/smaug
    def __exit__(self, ex_type, ex_value, ex_traceback):
        if not ex_value:
            return True

        if isinstance(ex_value, exception.NotAuthorized):
            raise Fault(webob.exc.HTTPForbidden(explanation=ex_value.msg))
        elif isinstance(ex_value, exception.Invalid):
            raise Fault(exception.ConvertedException(
                code=ex_value.code, explanation=ex_value.msg))
        elif isinstance(ex_value, TypeError):
            exc_info = (ex_type, ex_value, ex_traceback)
            LOG.error(_LE(
                'Exception handling resource: %s'),
                ex_value, exc_info=exc_info)
            raise Fault(webob.exc.HTTPBadRequest())
        elif isinstance(ex_value, Fault):
            LOG.info(_LI("Fault thrown: %s"), ex_value)
            raise ex_value
        elif isinstance(ex_value, webob.exc.HTTPException):
            LOG.info(_LI("HTTP exception thrown: %s"), ex_value)
            raise Fault(ex_value)

        # We didn't handle the exception
        return False
示例#52
0
文件: glance.py 项目: Bloomie/smaug
def create(context, conf):
    conf.register_opts(glance_client_opts, group=SERVICE + '_client')
    try:
        url = utils.get_url(SERVICE, context, conf)
    except Exception:
        LOG.error(_LE("Get glance service endpoint url failed"))
        raise

    LOG.info(_LI("Creating glance client with url %s."), url)

    args = {
        'endpoint': url,
        'token': context.auth_token,
    }

    return gc.Client(GLANCECLIENT_VERSION, **args)
示例#53
0
def create(context, conf):
    conf.register_opts(glance_client_opts, group=SERVICE + '_client')
    try:
        url = utils.get_url(SERVICE, context, conf)
    except Exception:
        LOG.error(_LE("Get glance service endpoint url failed"))
        raise

    LOG.info(_LI("Creating glance client with url %s."), url)

    args = {
        'endpoint': url,
        'token': context.auth_token,
    }

    return gc.Client(GLANCECLIENT_VERSION, **args)
示例#54
0
    def _provider_get(self, context, provider_id):
        if not uuidutils.is_uuid_like(provider_id):
            msg = _("Invalid provider id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            check_policy(context, 'get')
        except exception.PolicyNotAuthorized:
            # raise ProviderNotFound instead to make sure smaug behaves
            # as it used to
            raise exception.ProviderNotFound(provider_id=provider_id)

        provider = self.protection_api.show_provider(context, provider_id)

        LOG.info(_LI("Provider info retrieved successfully."))
        return provider
示例#55
0
def create(context, conf):
    conf.register_opts(neutron_client_opts, group=SERVICE + '_client')
    try:
        url = utils.get_url(SERVICE, context, conf)
    except Exception:
        LOG.error(_LE("Get neutron service endpoint url failed"))
        raise

    LOG.info(_LI("Creating neutron client with url %s."), url)

    args = {
        'endpoint_url': url,
        'token': context.auth_token,
    }

    return neutron_client.Client(**args)
示例#56
0
    def _provider_get(self, context, provider_id):
        if not uuidutils.is_uuid_like(provider_id):
            msg = _("Invalid provider id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            check_policy(context, 'get')
        except exception.PolicyNotAuthorized:
            # raise ProviderNotFound instead to make sure smaug behaves
            # as it used to
            raise exception.ProviderNotFound(provider_id=provider_id)

        provider = self.protection_api.show_provider(context, provider_id)

        LOG.info(_LI("Provider info retrieved successfully."))
        return provider
示例#57
0
文件: neutron.py 项目: Bloomie/smaug
def create(context, conf):
    conf.register_opts(neutron_client_opts, group=SERVICE + '_client')
    try:
        url = utils.get_url(SERVICE, context, conf)
    except Exception:
        LOG.error(_LE("Get neutron service endpoint url failed"))
        raise

    LOG.info(_LI("Creating neutron client with url %s."), url)

    args = {
        'endpoint_url': url,
        'token': context.auth_token,
    }

    return neutron_client.Client(**args)
示例#58
0
文件: service.py 项目: Bloomie/smaug
    def start(self):
        version_string = version.version_string()
        LOG.info(_LI('Starting %(topic)s node (version %(version_string)s)'),
                 {'topic': self.topic, 'version_string': version_string})
        self.model_disconnected = False
        ctxt = context.get_admin_context()
        try:
            service_ref = db.service_get_by_args(ctxt,
                                                 self.host,
                                                 self.binary)
            self.service_id = service_ref['id']
        except exception.NotFound:
            self._create_service_ref(ctxt)

        self.manager.init_host(service_id=self.service_id)

        LOG.debug("Creating RPC server for service %s", self.topic)

        target = messaging.Target(topic=self.topic, server=self.host)
        endpoints = [self.manager]
        endpoints.extend(self.manager.additional_endpoints)
        serializer = objects_base.SmaugObjectSerializer()
        self.rpcserver = rpc.get_server(target, endpoints, serializer)
        self.rpcserver.start()

        self.manager.init_host_with_rpc()

        if self.report_interval:
            pulse = loopingcall.FixedIntervalLoopingCall(
                self.report_state)
            pulse.start(interval=self.report_interval,
                        initial_delay=self.report_interval)
            self.timers.append(pulse)

        if self.periodic_interval:
            if self.periodic_fuzzy_delay:
                initial_delay = random.randint(0, self.periodic_fuzzy_delay)
            else:
                initial_delay = None

            periodic = loopingcall.FixedIntervalLoopingCall(
                self.periodic_tasks)
            periodic.start(interval=self.periodic_interval,
                           initial_delay=initial_delay)
            self.timers.append(periodic)