Пример #1
0
    def get_last_operation(self, req, instance_id):
        service = db_cf.get_service_for_instance(instance_id)
        # NOTE(freerunner): Prevent code 500 if requested environment
        # already doesn't exist.
        if not service:
            LOG.warning(_LW('Requested service for instance {} is not found'))
            body = {}
            resp = response.Response(status=410, json_body=body)
            return resp
        env_id = service.environment_id
        token = req.headers["X-Auth-Token"]
        m_cli = _get_muranoclient(token, req)

        # NOTE(starodubcevna): we can track only environment status. it's
        # murano API limitation.
        m_environment = m_cli.environments.get(env_id)
        if m_environment.status == 'ready':
            body = {'state': 'succeeded', 'description': 'operation succeed'}
            resp = response.Response(status=200, json_body=body)
        elif m_environment.status in ['pending', 'deleting', 'deploying']:
            body = {
                'state': 'in progress',
                'description': 'operation in progress'
            }
            resp = response.Response(status=202, json_body=body)
        elif m_environment.status in ['deploy failure', 'delete failure']:
            body = {
                'state':
                'failed',
                'description':
                '{0}. Please correct it manually'.format(m_environment.status)
            }
            resp = response.Response(status=200, json_body=body)
        return resp
Пример #2
0
    def bind(self, req, body, instance_id, app_id):
        db_service = db_cf.get_service_for_instance(instance_id)
        if not db_service:
            return {}

        service_id = db_service.service_id
        environment_id = db_service.environment_id
        token = req.headers['X-Auth-Token']
        m_cli = _get_muranoclient(token, req)

        session_id = create_session(m_cli, environment_id)
        env = m_cli.environments.get(environment_id, session_id)
        LOG.debug('Got environment {0}'.format(env))
        service = self._get_service(env, service_id)
        LOG.debug('Got service {0}'.format(service))

        # NOTE(starodubcevna): Here we need to find an action which will return
        # us needed credentials. By default we will looking for getCredentials
        # action.
        result = {}
        try:
            actions = service['?']['_actions']
            for action_id in list(actions):
                if 'getCredentials' in action_id:

                    @retrying.retry(
                        retry_on_exception=lambda e: isinstance(e, TypeError),
                        wait_random_min=1000,
                        wait_random_max=10000,
                        stop_max_delay=30000)
                    def _get_creds(client, task_id, environment_id):
                        result = m_cli.actions.get_result(
                            environment_id, task_id)['result']
                        return result

                    task_id = m_cli.actions.call(environment_id, action_id)
                    result = _get_creds(m_cli, task_id, environment_id)

            if not result:
                LOG.warning(
                    _LW("This application doesn't have action "
                        "getCredentials"))
                return response.Response(status=500)
        except KeyError:
            # NOTE(starodubcevna): In CF service broker API spec return
            # code for failed bind is not present, so we will return 500.
            LOG.warning(_LW("This application doesn't have actions at all"))
            return response.Response(status=500)

        if 'credentials' in list(result):
            return result
        else:
            return {'credentials': result}
Пример #3
0
    def __call__(self, _, request, params):
        filename = request.path_info
        filename = os.path.normpath(
            os.path.join(self.dirname, *filename.split('/')))

        if not filename.startswith(self.dirname +
                                   '/') or not os.path.isfile(filename):
            res = exc.HTTPNotFound()
        else:
            mime, _ = mimetypes.guess_type(filename)
            mime = mime or 'application/octet-stream'

            size = os.path.getsize(filename)
            time = os.path.getmtime(filename)

            res = response.Response(content_type=mime,
                                    content_length=size,
                                    app_iter=self.iter_file(filename),
                                    conditional_response=True)
            res.last_modified = time
            res.etag = '%s-%s-%s' % (time, size, hash(filename))

            if filename.endswith('.gz'):
                res.content_encoding = 'gzip'

        return res
Пример #4
0
    def process_request(self, req):
        if not self._can_apply_middleware(req):
            LOG.debug('%s skipped in role middleware', req.path)
            return None

        is_authenticated = self._is_authenticated(req)
        is_authorized, is_agent = self._is_authorized(req)
        tenant_id = req.headers.get('X-Tenant-Id')

        req.environ[_X_MONASCA_LOG_AGENT] = is_agent

        LOG.debug('%s is authenticated=%s, authorized=%s, log_agent=%s',
                  tenant_id, is_authenticated, is_authorized, is_agent)

        if is_authenticated and is_authorized:
            LOG.debug('%s has been authenticated and authorized', tenant_id)
            return  # do return nothing to enter API internal

        # whoops
        if is_authorized:
            explanation = u'Failed to authenticate request for %s' % tenant_id
        else:
            explanation = (u'Tenant %s is missing a required role to access '
                           u'this service' % tenant_id)

        if explanation is not None:
            LOG.error(explanation)
            json_body = {u'title': u'Unauthorized', u'message': explanation}
            return response.Response(status=401,
                                     json_body=json_body,
                                     content_type='application/json')
Пример #5
0
    def deprovision(self, req, instance_id):
        service = db_cf.get_service_for_instance(instance_id)
        if not service:
            return {}

        service_id = service.service_id
        environment_id = service.environment_id
        token = req.headers['X-Auth-Token']
        m_cli = _get_muranoclient(token, req)

        session_id = create_session(m_cli, environment_id)
        m_cli.services.delete(environment_id, '/' + service_id, session_id)
        m_cli.sessions.deploy(environment_id, session_id)
        return response.Response(status=202, json_body={})
Пример #6
0
def dummy_app(environ, response):
    res = webob_response.Response()
    return res(environ, response)
Пример #7
0
    def provision(self, req, body, instance_id):
        """Here is the example of request body given us from Cloud Foundry:

         {
         "service_id":        "service-guid-here",
         "plan_id":           "plan-guid-here",
         "organization_guid": "org-guid-here",
         "space_guid":        "space-guid-here",
         "parameters": {"param1": "value1",
                        "param2": "value2"}
         }
        """
        data = json.loads(req.body)
        space_guid = data['space_guid']
        org_guid = data['organization_guid']
        plan_id = data['plan_id']
        service_id = data['service_id']
        parameters = data['parameters']
        self.current_session = None

        # Here we'll take an entry for CF org and space from db. If we
        # don't have any entries we will create it from scratch.
        try:
            tenant = db_cf.get_tenant_for_org(org_guid)
        except AttributeError:
            tenant = req.headers['X-Project-Id']
            db_cf.set_tenant_for_org(org_guid, tenant)
            LOG.info(
                _LI("Cloud Foundry {org_id} mapped to tenant "
                    "{tenant_name}").format(org_id=org_guid,
                                            tenant_name=tenant))

        token = req.headers['X-Auth-Token']
        m_cli = _get_muranoclient(token, req)

        def _set_new_environment_for_space(space_guid, log_msg):
            body = {'name': 'my_{uuid}'.format(uuid=uuid.uuid4().hex)}
            env = m_cli.environments.create(body)
            db_cf.set_environment_for_space(space_guid, env.id)
            LOG.info(log_msg.format(space_id=space_guid,
                                    environment_id=env.id))
            return env.id

        try:
            environment_id = db_cf.get_environment_for_space(space_guid)
            # NOTE: Check that environment which was previously linked with
            # CF space still exist, reset a new environment for space.
            try:
                env = m_cli.environments.get(environment_id)
            except exceptions.HTTPNotFound:
                msg = (_LI("Can not find environment_id {environment_id}, "
                           "will create a new one.").format(
                               environment_id=environment_id))
                LOG.info(msg)
                env = {}
            if not env:
                log_msg = (_LI("Cloud Foundry {space_id} remapped to "
                               "{environment_id}"))
                environment_id = _set_new_environment_for_space(
                    space_guid, log_msg)
        except AttributeError:
            log_msg = (_LI("Cloud Foundry {space_id} mapped to "
                           "{environment_id}"))
            environment_id = _set_new_environment_for_space(
                space_guid, log_msg)

        package = m_cli.packages.get(service_id)
        LOG.debug('Adding service {name}'.format(name=package.name))

        service = self._make_service(space_guid, package, plan_id)
        db_cf.set_instance_for_service(instance_id, service['?']['id'],
                                       environment_id, tenant)

        # NOTE(Kezar): Here we are going through JSON and add ids where
        # it's necessary. Before that we need to drop '?' key from parameters
        # dictionary as far it contains murano package related info which is
        # necessary in our scenario
        if '?' in parameters.keys():
            parameters.pop('?', None)
            LOG.warning(
                _LW("Incorrect input parameters. Package related "
                    "parameters shouldn't be passed through Cloud "
                    "Foundry"))
        params = [parameters]
        while params:
            a = params.pop()
            for k, v in six.iteritems(a):
                if isinstance(v, dict):
                    params.append(v)
                    if k == '?':
                        v['id'] = uuid.uuid4().hex
        service.update(parameters)
        # Now we need to obtain session to modify the env
        session_id = create_session(m_cli, environment_id)
        m_cli.services.post(environment_id,
                            path='/',
                            data=service,
                            session_id=session_id)
        m_cli.sessions.deploy(environment_id, session_id)
        self.current_session = session_id
        return response.Response(status=202, json_body={})