Esempio n. 1
0
class AkamaiSanCertConfigController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(san_cert_name=rule.Rule(
        helpers.is_valid_domain_by_name(), helpers.abort_with_message))
    def get_one(self, san_cert_name):

        try:
            res = (self._driver.manager.ssl_certificate_controller.
                   get_san_cert_configuration(san_cert_name))
        except Exception as e:
            pecan.abort(400, str(e))

        return res

    @pecan.expose('json')
    @decorators.validate(
        san_cert_name=rule.Rule(helpers.is_valid_domain_by_name(),
                                helpers.abort_with_message),
        request=rule.Rule(
            helpers.json_matches_service_schema(
                ssl_certificate.SSLCertificateSchema.get_schema(
                    "config", "POST")), helpers.abort_with_message,
            stoplight_helpers.pecan_getter))
    def post(self, san_cert_name):
        config_json = json.loads(pecan.request.body.decode('utf-8'))

        try:
            res = (self._driver.manager.ssl_certificate_controller.
                   update_san_cert_configuration(san_cert_name, config_json))
        except Exception as e:
            pecan.abort(400, str(e))

        return res
Esempio n. 2
0
class ServiceStatusController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(ServiceStatusController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            service_status.ServiceStatusSchema.get_schema(
                "service_status", "POST")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def post(self):

        service_state_json = json.loads(pecan.request.body.decode('utf-8'))
        project_id = service_state_json['project_id']
        service_id = service_state_json['service_id']
        status = service_state_json['status']
        services_controller = self._driver.manager.services_controller

        status_code = None
        try:
            status_code = services_controller.set_service_provider_details(
                project_id, service_id, self.auth_token, status)
        except Exception as e:
            pecan.abort(404,
                        detail=('Setting state of service {0} on tenant: {1} '
                                'to {2} has failed, '
                                'Reason: {3}'.format(service_id, project_id,
                                                     status, str(e))))

        return pecan.Response(None, status_code)
Esempio n. 3
0
class OperatorServiceActionController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(OperatorServiceActionController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            service_action.ServiceActionSchema.get_schema(
                "service_action", "POST")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def post(self):

        service_state_json = json.loads(pecan.request.body.decode('utf-8'))
        service_action = service_state_json.get('action', None)
        project_id = service_state_json.get('project_id', None)
        domain_name = service_state_json.get('domain', None)
        services_controller = self._driver.manager.services_controller

        try:
            services_controller.services_action(project_id, service_action,
                                                domain_name)

        except Exception as e:
            pecan.abort(404,
                        detail=('Services action {0} on tenant: {1} failed, '
                                'Reason: {2}'.format(service_action,
                                                     project_id, str(e))))

        return pecan.Response(None, 202)
Esempio n. 4
0
class BackgroundJobController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(BackgroundJobController, self).__init__(driver)
        self.__class__.san_mapping = AkamaiSanMappingListController(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            background_jobs.BackgroundJobSchema.get_schema(
                "background_jobs", "POST")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def post(self):
        request_json = json.loads(pecan.request.body.decode('utf-8'))
        job_type = request_json.pop('job_type')

        sent = []
        ignored = []

        try:
            sent, ignored = self._driver.manager.background_job_controller.\
                post_job(job_type, request_json)
        except NotImplementedError as e:
            pecan.abort(400, str(e))

        return pecan.Response(
            json_body={
                "sent": sent,
                "ignored": ignored
            },
            status=202,
        )
Esempio n. 5
0
class DomainController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(DomainController, self).__init__(driver)

        self._conf = driver.conf

    @pecan.expose('json')
    @decorators.validate(domain_name=rule.Rule(
        helpers.is_valid_domain_by_name(), helpers.abort_with_message))
    def get_one(self, domain_name):
        services_controller = self._driver.manager.services_controller
        try:
            service_obj = services_controller.get_service_by_domain_name(
                domain_name)
        except LookupError:
            pecan.abort(404, detail='Domain %s cannot be found' % domain_name)
        # convert a service model into a response service model
        return resp_service_model.Model(service_obj, self)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(helpers.is_valid_provider_url(),
                                           helpers.abort_with_message,
                                           stoplight_helpers.pecan_getter))
    def get(self):
        services_controller = self._driver.manager.services_controller

        call_args = getattr(pecan.request.context, "call_args")
        provider_url = call_args.pop('provider_url')
        domains = services_controller.get_domains_by_provider_url(provider_url)

        return pecan.Response(json_body=domains, status=200)
Esempio n. 6
0
class ServicesAnalyticsController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(service_id=rule.Rule(helpers.is_valid_service_id(),
                                              helpers.abort_with_message),
                         request=rule.Rule(
                             helpers.is_valid_analytics_request(),
                             helpers.abort_with_message,
                             stoplight_helpers.pecan_getter))
    def get(self, service_id):
        '''Get Analytics By Domain Data'''

        call_args = getattr(pecan.request.context, "call_args")
        domain = call_args.pop('domain')
        analytics_controller = \
            self._driver.manager.analytics_controller
        try:
            res = analytics_controller.get_metrics_by_domain(
                self.project_id, domain, **call_args)
        except errors.ServiceNotFound:
            return pecan.Response(status=404)
        except Exception:
            return pecan.Response(status=500)
        else:
            return pecan.Response(json_body=res, status=200)
Esempio n. 7
0
class BackgroundJobController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(BackgroundJobController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            background_jobs.BackgroundJobSchema.get_schema(
                "background_jobs", "POST")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def post(self):
        request_json = json.loads(pecan.request.body.decode('utf-8'))
        job_type = request_json.pop('job_type')

        try:
            self._driver.manager.background_job_controller.post_job(
                job_type, request_json)
        except ValueError as e:
            pecan.abort(400, str(e))
        except NotImplementedError as e:
            pecan.abort(400, str(e))

        return pecan.Response(None, 202)
Esempio n. 8
0
class SSLCertificateController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(
        request=rule.Rule(
            helpers.json_matches_service_schema(
                ssl_certificate_validation.SSLCertificateSchema.get_schema(
                    "ssl_certificate",
                    "POST")),
            helpers.abort_with_message,
            stoplight_helpers.pecan_getter))
    def post(self):
        ssl_certificate_controller = (
            self._driver.manager.ssl_certificate_controller)

        certificate_info_dict = json.loads(pecan.request.body.decode('utf-8'))

        try:
            cert_obj = ssl_certificate.load_from_json(certificate_info_dict)
            ssl_certificate_controller.create_ssl_certificate(self.project_id,
                                                              cert_obj)
        except LookupError as e:
            pecan.abort(400, detail='Provisioning ssl certificate failed. '
                        'Reason: %s' % str(e))
        except ValueError as e:
            pecan.abort(400, detail='Provisioning ssl certificate failed. '
                        'Reason: %s' % str(e))

        return pecan.Response(None, 202)
Esempio n. 9
0
class AkamaiSSLCertificateController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AkamaiSSLCertificateController, self).__init__(driver)
        self.__class__.retry_list = AkamaiRetryListController(driver)
        self.__class__.config = AkamaiSanCertConfigController(driver)
Esempio n. 10
0
class AkamaiRetryListController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AkamaiRetryListController, self).__init__(driver)

    @pecan.expose('json')
    def get_all(self):
        retry_list = None
        try:
            retry_list = (self._driver.manager.ssl_certificate_controller.
                          get_san_retry_list())
        except Exception as e:
            pecan.abort(404, str(e))

        return retry_list

    @pecan.expose('json')
    def post(self):
        """Rerun retry-list mod-san requests."""
        sent, ignored = None, None
        try:
            sent, ignored = self._driver.manager.ssl_certificate_controller.\
                rerun_san_retry_list()
        except Exception as e:
            pecan.abort(404, str(e))

        return pecan.Response(json_body={
            "processing": sent,
            "failed_validation": ignored
        },
                              status=202)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            ssl_certificate.SSLCertificateSchema.get_schema(
                "retry_list", "PUT")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def put(self):
        """The input of the queue data must be a list of dictionaries:

        (after json loaded)
        [
          { "domain_name": <domain_name>,
            "project_id": <project_id>,
            "flavor_id": <flavor_id> }
        ]

        """
        try:
            queue_data = json.loads(pecan.request.body.decode('utf-8'))
            res, deleted = (self._driver.manager.ssl_certificate_controller.
                            update_san_retry_list(queue_data))
        except Exception as e:
            pecan.abort(400, str(e))

        # queue is the new queue, and deleted is deleted items
        return {"queue": res, "deleted": deleted}
Esempio n. 11
0
class HomeController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    def get(self):
        home_controller = self._driver.manager.home_controller
        return home_controller.get()
Esempio n. 12
0
    def _setup_app(self):
        root_controller = controllers.Root(self)

        pecan_hooks = [hooks.Context()]

        self._app = pecan.make_app(root_controller, hooks=pecan_hooks)

        controller_v1 = controllers.V1(self)
        root_controller.add_controller('v1.0', controller_v1)

        controller_v1.add_controller('services', controllers.Services(self))
Esempio n. 13
0
class AdminProviderDetailsController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AdminProviderDetailsController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(
        service_id=rule.Rule(helpers.is_valid_service_id(),
                             helpers.abort_with_message),
        request=rule.Rule(
            helpers.json_matches_service_schema(
                provider_details_update.ProviderDetailsUpdateSchema.get_schema(
                    "update_provider_access_url", "PATCH")),
            helpers.abort_with_message, stoplight_helpers.pecan_getter))
    def patch_one(self, service_id):
        request_json = json.loads(pecan.request.body.decode('utf-8'))
        project_id = request_json.get('project_id', None)
        domain_name = request_json.get('domain_name', None)
        operator_url = request_json.get('operator_url', None)
        provider_url = request_json.get('provider_url', None)

        if not helpers.is_valid_domain_name(domain_name):
            pecan.abort(400,
                        detail='Domain {0} is not valid'.format(domain_name))

        changes_made = False
        try:
            changes_made = self._driver.manager.services_controller.\
                update_access_url_service(
                    project_id,
                    service_id,
                    access_url_changes={
                        'domain_name': domain_name,
                        'operator_url': operator_url,
                        'provider_url': provider_url
                    }
                )
        except errors.ServiceNotFound:
            pecan.abort(
                404,
                detail='Service {0} could not be found'.format(service_id))
        except (errors.InvalidOperation, errors.InvalidResourceName) as e:
            pecan.abort(400, detail='{0}'.format(e))
        except (LookupError, ValueError):
            pecan.abort(
                404,
                detail='Domain {0} could not be found'.format(domain_name))

        status_code = 201 if changes_made is True else 202
        return pecan.Response(None, status=status_code)
Esempio n. 14
0
class AkamaiSanCertConfigController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(query=rule.Rule(
        helpers.is_valid_domain_by_name_or_akamai_setting(),
        helpers.abort_with_message))
    def get_one(self, query):

        if query == 'san_cert_hostname_limit':
            try:
                return (self._driver.manager.ssl_certificate_controller.
                        get_san_cert_hostname_limit())
            except Exception as e:
                pecan.abort(400, str(e))
        else:
            try:
                return (self._driver.manager.ssl_certificate_controller.
                        get_san_cert_configuration(query))
            except Exception as e:
                pecan.abort(400, str(e))

    @pecan.expose('json')
    @decorators.validate(
        query=rule.Rule(helpers.is_valid_domain_by_name_or_akamai_setting(),
                        helpers.abort_with_message),
        request=rule.Rule(
            helpers.json_matches_service_schema(
                ssl_certificate.SSLCertificateSchema.get_schema(
                    "config", "POST")), helpers.abort_with_message,
            stoplight_helpers.pecan_getter))
    def post(self, query):
        request_json = json.loads(pecan.request.body.decode('utf-8'))

        if query == 'san_cert_hostname_limit':
            try:
                self._driver.manager.ssl_certificate_controller. \
                    set_san_cert_hostname_limit(request_json)

                return pecan.Response(None, 202)
            except Exception as e:
                pecan.abort(400, str(e))
        else:
            try:
                res = (self._driver.manager.ssl_certificate_controller.
                       update_san_cert_configuration(query, request_json))
                return res
            except Exception as e:
                pecan.abort(400, str(e))
Esempio n. 15
0
class ProviderHealthController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    def get(self, provider_name):
        """Returns the health of provider."""

        health_controller = self._driver.manager.health_controller

        try:
            is_alive = health_controller.is_provider_alive(provider_name)
            return health_response.ProviderModel(is_alive)
        except KeyError:
            pecan.response.status = 404
Esempio n. 16
0
class HealthController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    def get(self):
        """Returns the health of storage and providers."""

        health_controller = self._driver.manager.health_controller

        is_alive, health_map = health_controller.health()
        if not is_alive:
            pecan.response.status = 503

        return health_response.HealthModel(self, health_map)
Esempio n. 17
0
class AdminCertController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AdminCertController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.is_valid_certificate_status(), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def get(self):
        ssl_certificate_controller = (
            self._driver.manager.ssl_certificate_controller)

        call_args = getattr(pecan.request.context, "call_args")
        status = call_args.pop('status')
        cert_domains = ssl_certificate_controller.get_certs_by_status(status)

        return pecan.Response(json_body=cert_domains, status=200)

    @pecan.expose('json')
    @decorators.validate(
        domain_name=rule.Rule(helpers.is_valid_domain_by_name(),
                              helpers.abort_with_message),
        request=rule.Rule(
            helpers.json_matches_service_schema(
                ssl_certificate.SSLCertificateSchema.get_schema(
                    "admin_cert_status", "PATCH")), helpers.abort_with_message,
            stoplight_helpers.pecan_getter))
    def patch_one(self, domain_name):

        ssl_certificate_controller = (
            self._driver.manager.ssl_certificate_controller)
        certificate_updates = json.loads(pecan.request.body.decode('utf-8'))[0]
        try:
            ssl_certificate_controller.update_certificate_status(
                domain_name, certificate_updates)
        except ValueError:
            pecan.abort(
                status_code=404,
                detail='Certificate could not be found for domain: {0}'.format(
                    domain_name))
        except Exception as e:
            pecan.abort(status_code=400, detail=util.help_escape(str(e)))

        return pecan.Response(body=None, status=204)
Esempio n. 18
0
class ServiceAssetsController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(service_id=rule.Rule(helpers.is_valid_service_id(),
                                              helpers.abort_with_message))
    def delete(self, service_id):
        purge_url = pecan.request.GET.get('url', '/*')
        purge_all = pecan.request.GET.get('all', False)
        hard = pecan.request.GET.get('hard', 'True')
        if purge_url:
            try:
                purge_url.encode('ascii')
            except (UnicodeDecodeError, UnicodeEncodeError):
                pecan.abort(400, detail='non ascii character present in url')
        if hard and hard.lower() == 'false':
            hard = 'False'
        if hard and hard.lower() == 'true':
            hard = 'True'
        try:
            hard = ast.literal_eval(hard)
        except ValueError:
            pecan.abort(400, detail='hard can only be set to True or False')
        if hard not in [True, False]:
            pecan.abort(400, detail='hard can only be set to True or False')
        purge_all = (True
                     if purge_all and purge_all.lower() == 'true' else False)
        if purge_all and purge_url != '/*':
            pecan.abort(400,
                        detail='Cannot provide all=true '
                        'and a url at the same time')
        services_controller = self._driver.manager.services_controller
        try:
            services_controller.purge(self.project_id, service_id, hard,
                                      purge_url)
        except errors.ServiceStatusNotDeployed as e:
            pecan.abort(400, detail=str(e))
        except LookupError as e:
            pecan.abort(404, detail=str(e))

        service_url = str(
            uri.encode(u'{0}/v1.0/services/{1}'.format(pecan.request.host_url,
                                                       service_id)))

        return pecan.Response(None, 202, headers={"Location": service_url})
Esempio n. 19
0
class AdminCertController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AdminCertController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.is_valid_certificate_status(), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def get(self):
        services_controller = self._driver.manager.services_controller

        call_args = getattr(pecan.request.context, "call_args")
        status = call_args.pop('status')
        cert_domains = services_controller.get_certs_by_status(status)

        return pecan.Response(json_body=cert_domains, status=200)
Esempio n. 20
0
class OperatorServiceLimitController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(OperatorServiceLimitController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            service_limit.ServiceLimitSchema.get_schema(
                "service_limit", "PUT")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter),
                         project_id=rule.Rule(helpers.is_valid_project_id(),
                                              helpers.abort_with_message))
    def put(self, project_id):

        service_state_json = json.loads(pecan.request.body.decode('utf-8'))
        project_limit = service_state_json.get('limit', None)

        services_controller = self._driver.manager.services_controller

        try:
            services_controller.services_limit(project_id, project_limit)
        except Exception as e:
            pecan.abort(404,
                        detail=('Services limit {0} on tenant: {1} failed, '
                                'Reason: {2}'.format(project_limit, project_id,
                                                     str(e))))

        return pecan.Response(None, 201)

    @pecan.expose('json')
    @decorators.validate(project_id=rule.Rule(helpers.is_valid_project_id(),
                                              helpers.abort_with_message))
    def get_one(self, project_id):
        services_controller = self._driver.manager.services_controller

        service_limits = services_controller.get_services_limit(project_id)

        return service_limits
Esempio n. 21
0
class DomainMigrationController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(DomainMigrationController, self).__init__(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            domain_migration.DomainMigrationServiceSchema.get_schema(
                "domain_migration", "POST")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def post(self):
        request_json = json.loads(pecan.request.body.decode('utf-8'))
        project_id = request_json.get('project_id', None)
        service_id = request_json.get('service_id', None)
        domain_name = request_json.get('domain_name', None)
        new_cert = request_json.get('new_cert', None)
        cert_status = request_json.get('cert_status', 'deployed')

        if not helpers.is_valid_domain_name(domain_name):
            pecan.abort(400,
                        detail='Domain {0} is not valid'.format(domain_name))

        # Akamai specific suffix:
        if not new_cert.endswith("edgekey.net"):
            new_cert = new_cert + ".edgekey.net"

        try:
            self._driver.manager.services_controller.migrate_domain(
                project_id, service_id, domain_name, new_cert, cert_status)
        except errors.ServiceNotFound:
            pecan.abort(
                404,
                detail='Service {0} could not be found'.format(service_id))
        except (LookupError, ValueError):
            pecan.abort(
                404,
                detail='Domain {0} could not be found'.format(domain_name))

        return pecan.Response(None, 202)
Esempio n. 22
0
class AdminServiceController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AdminServiceController, self).__init__(driver)
        self.__class__.action = OperatorServiceActionController(driver)
        self.__class__.status = ServiceStatusController(driver)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(helpers.is_valid_service_status(),
                                           helpers.abort_with_message,
                                           stoplight_helpers.pecan_getter))
    def get(self):
        services_controller = self._driver.manager.services_controller

        call_args = getattr(pecan.request.context, "call_args")
        status = call_args.pop('status')
        service_projectids = services_controller.get_services_by_status(status)

        return pecan.Response(json_body=service_projectids, status=200)
Esempio n. 23
0
class DomainController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(DomainController, self).__init__(driver)

        self._conf = driver.conf

    @pecan.expose('json')
    @decorators.validate(domain_name=rule.Rule(
        helpers.is_valid_domain_by_name(), helpers.abort_with_message))
    def get_one(self, domain_name):
        services_controller = self._driver.manager.services_controller
        try:
            service_obj = services_controller.get_service_by_domain_name(
                domain_name)
        except LookupError:
            pecan.abort(404, detail='Domain %s cannot be found' % domain_name)
        # convert a service model into a response service model
        return resp_service_model.Model(service_obj, self)
Esempio n. 24
0
class AkamaiSanMappingListController(base.Controller, hooks.HookController):
    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(AkamaiSanMappingListController, self).__init__(driver)

        self.manager = self._driver.manager

    @pecan.expose('json')
    def get_all(self):
        try:
            return (
                self.manager.background_job_controller.get_san_mapping_list())
        except Exception as e:
            pecan.abort(404, str(e))

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            ssl_certificate.SSLCertificateSchema.get_schema(
                "san_mapping_list", "PUT")), helpers.abort_with_message,
        stoplight_helpers.pecan_getter))
    def put(self):
        """The input of the queue data must be a list of dictionaries:

        (after json loaded)
        [
          { "domain_name": <domain_name>,
            "san_cert_name": <san_cert_name>
          }
        ]
        """
        try:
            san_mapping_list = json.loads(pecan.request.body.decode('utf-8'))
            res, deleted = (self.manager.background_job_controller.
                            put_san_mapping_list(san_mapping_list))
            # queue is the new queue, and deleted is deleted items
            return {"queue": res, "deleted": deleted}
        except Exception as e:
            pecan.abort(400, str(e))
Esempio n. 25
0
class StorageHealthController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    """Storage Health Controller."""

    @pecan.expose('json')
    def get(self, storage_name):
        """GET.

        Returns the health of storage

        :param storage_name
        :returns JSON storage model or HTTP 404
        """

        health_controller = self._driver.manager.health_controller

        try:
            is_alive = health_controller.is_storage_alive(storage_name)
            return health_response.StorageModel(is_alive)
        except KeyError:
            pecan.response.status = 404
Esempio n. 26
0
class DistributedTaskHealthController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    """Distributed Task Health Controller."""

    @pecan.expose('json')
    def get(self, distributed_task_name):
        """GET.

        Returns the health of distributed task manager

        :param distributed_task_name
        :returns JSON storage model or HTTP 404
        """

        health_controller = self._driver.manager.health_controller

        try:
            is_alive = health_controller.is_distributed_task_alive(
                distributed_task_name)
            return health_response.DistributedTaskModel(is_alive)
        except KeyError:
            pecan.response.status = 404
Esempio n. 27
0
class ServicesController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    def __init__(self, driver):
        super(ServicesController, self).__init__(driver)

        self._conf = driver.conf
        self._conf.register_opts(LIMITS_OPTIONS, group=LIMITS_GROUP)
        self.limits_conf = self._conf[LIMITS_GROUP]
        self.max_services_per_page = self.limits_conf.max_services_per_page
        # Add assets controller here
        # need to initialize a nested controller with a parameter driver,
        # so added it in __init__ method.
        # see more in: http://pecan.readthedocs.org/en/latest/rest.html
        self.__class__.assets = ServiceAssetsController(driver)
        self.__class__.analytics = ServicesAnalyticsController(driver)

    @pecan.expose('json')
    def get_all(self):
        marker = pecan.request.GET.get('marker', None)
        limit = pecan.request.GET.get('limit', 10)
        try:
            limit = int(limit)
            if limit <= 0:
                pecan.abort(400, detail=u'Limit should be greater than 0')
            if limit > self.max_services_per_page:
                error = u'Limit should be less than or equal to {0}'.format(
                    self.max_services_per_page)
                pecan.abort(400, detail=error)
        except ValueError:
            error = (u'Limit should be an integer greater than 0 and less'
                     u' or equal to {0}'.format(self.max_services_per_page))
            pecan.abort(400, detail=error)

        try:
            if marker is not None:
                marker = str(uuid.UUID(marker))
        except ValueError:
            pecan.abort(400, detail="Marker must be a valid UUID")

        services_controller = self._driver.manager.services_controller
        service_resultset = services_controller.list(self.project_id, marker,
                                                     limit)
        results = [
            resp_service_model.Model(s, self) for s in service_resultset
        ]

        links = []
        if len(results) >= limit:
            links.append(
                link.Model(
                    u'{0}/services?marker={1}&limit={2}'.format(
                        self.base_url, results[-1]['id'], limit), 'next'))

        return {'links': links, 'services': results}

    @pecan.expose('json')
    @decorators.validate(service_id=rule.Rule(helpers.is_valid_service_id(),
                                              helpers.abort_with_message))
    def get_one(self, service_id):
        services_controller = self._driver.manager.services_controller
        try:
            service_obj = services_controller.get(self.project_id, service_id)
        except ValueError:
            pecan.abort(404,
                        detail='service %s could not be found' % service_id)
        # convert a service model into a response service model
        return resp_service_model.Model(service_obj, self)

    @pecan.expose('json')
    @decorators.validate(request=rule.Rule(
        helpers.json_matches_service_schema(
            service.ServiceSchema.get_schema("service", "POST")),
        helpers.abort_with_message, stoplight_helpers.pecan_getter))
    def post(self):
        services_controller = self._driver.manager.services_controller
        service_json_dict = json.loads(pecan.request.body.decode('utf-8'))
        service_id = None
        try:
            service_obj = services_controller.create(self.project_id,
                                                     self.auth_token,
                                                     service_json_dict)
            service_id = service_obj.service_id
        except errors.SharedShardsExhausted as e:
            # domain - shared domains exhausted
            pecan.abort(400, detail=str(e))
        except LookupError as e:  # error handler for no flavor
            pecan.abort(400, detail=str(e))
        except ValueError as e:  # error handler for existing service name
            pecan.abort(400, detail=str(e))
        except errors.ServicesOverLimit as e:
            # error handler for services count exceeding limit
            pecan.abort(403, detail=str(e))
        service_url = str(
            uri.encode(u'{0}/v1.0/services/{1}'.format(pecan.request.host_url,
                                                       service_id)))

        return pecan.Response(None, 202, headers={"Location": service_url})

    @pecan.expose('json')
    @decorators.validate(service_id=rule.Rule(helpers.is_valid_service_id(),
                                              helpers.abort_with_message))
    def delete(self, service_id):
        services_controller = self._driver.manager.services_controller

        try:
            services_controller.delete(self.project_id, service_id)
        except LookupError as e:
            pecan.abort(404, detail=str(e))
        except ValueError as e:
            pecan.abort(404, detail=str(e))

        return pecan.Response(None, 202)

    @pecan.expose('json')
    @decorators.validate(service_id=rule.Rule(helpers.is_valid_service_id(),
                                              helpers.abort_with_message),
                         request=rule.Rule(
                             helpers.json_matches_service_schema(
                                 service.ServiceSchema.get_schema(
                                     "service",
                                     "PATCH")), helpers.abort_with_message,
                             stoplight_helpers.pecan_getter))
    def patch_one(self, service_id):
        service_updates = json.loads(pecan.request.body.decode('utf-8'))

        services_controller = self._driver.manager.services_controller

        try:
            services_controller.update(self.project_id, service_id,
                                       self.auth_token, service_updates)
        except exceptions.ValidationFailed as e:
            pecan.abort(400, detail=u'{0}'.format(e))
        except LookupError as e:  # error handler for no flavor
            pecan.abort(400, detail=str(e))
        except ValueError as e:  # error handler for existing service name
            pecan.abort(400, detail=str(e))
        except errors.ServiceNotFound as e:
            pecan.abort(404, detail=str(e))
        except errors.ServiceStatusNeitherDeployedNorFailed as e:
            pecan.abort(400, detail=str(e))
        except errors.SharedShardsExhausted as e:
            # domain - shared domains exhausted
            pecan.abort(400, detail=str(e))
        except Exception as e:
            pecan.abort(400, detail=util.help_escape(str(e)))

        service_url = str(
            uri.encode(u'{0}/v1.0/services/{1}'.format(pecan.request.host_url,
                                                       service_id)))

        return pecan.Response(None, 202, headers={"Location": service_url})
Esempio n. 28
0
class SSLCertificateController(base.Controller, hooks.HookController):

    __hooks__ = [poppy_hooks.Context(), poppy_hooks.Error()]

    @pecan.expose('json')
    @decorators.validate(
        request=rule.Rule(
            helpers.json_matches_service_schema(
                ssl_certificate_validation.SSLCertificateSchema.get_schema(
                    "ssl_certificate",
                    "POST")),
            helpers.abort_with_message,
            stoplight_helpers.pecan_getter))
    def post(self):
        ssl_certificate_controller = (
            self._driver.manager.ssl_certificate_controller)

        certificate_info_dict = json.loads(pecan.request.body.decode('utf-8'))

        try:
            project_id = certificate_info_dict.get('project_id')
            cert_obj = ssl_certificate.load_from_json(certificate_info_dict)
            cert_obj.project_id = project_id
            ssl_certificate_controller.create_ssl_certificate(project_id,
                                                              cert_obj)
        except LookupError as e:
            pecan.abort(400, detail='Provisioning ssl certificate failed. '
                        'Reason: %s' % str(e))
        except ValueError as e:
            pecan.abort(400, detail='Provisioning ssl certificate failed. '
                        'Reason: %s' % str(e))

        return pecan.Response(None, 202)

    @pecan.expose('json')
    @decorators.validate(
        domain_name=rule.Rule(
            helpers.is_valid_domain_by_name(),
            helpers.abort_with_message)
    )
    def delete(self, domain_name):
        # For now we only support 'san' cert type
        cert_type = pecan.request.GET.get('cert_type', 'san')

        certificate_controller = \
            self._driver.manager.ssl_certificate_controller
        try:
            certificate_controller.delete_ssl_certificate(
                self.project_id, domain_name, cert_type
            )
        except ValueError as e:
            pecan.abort(400, detail='Delete ssl certificate failed. '
                        'Reason: %s' % str(e))

        return pecan.Response(None, 202)

    @pecan.expose('json')
    @decorators.validate(
        domain_name=rule.Rule(
            helpers.is_valid_domain_by_name(),
            helpers.abort_with_message)
    )
    def get_one(self, domain_name):

        certificate_controller = \
            self._driver.manager.ssl_certificate_controller
        total_cert_info = []

        try:
            # NOTE(TheSriram): we can also enforce project_id constraints
            certs_info = certificate_controller.get_certs_info_by_domain(
                domain_name=domain_name,
                project_id=None)
        except ValueError:
            pecan.abort(404, detail='certificate '
                                    'could not be found '
                                    'for domain : %s' %
                        domain_name)
        else:
            # convert a cert model into a response cert model
            try:
                if iter(certs_info):
                    for cert in certs_info:
                        total_cert_info.append(ssl_cert_model.Model(cert))
                    return total_cert_info
            except TypeError:
                return ssl_cert_model.Model(certs_info)