def _update_state(self, services, state):
        # Services are items (not obj)
        # import pdb;pdb.set_trace()
        code = get_status(state)
        for sproject in services:
            item = self.spres._find_item(unicode(sproject.pk))
            instance = find_instance(unicode(item['_id']))
            if instance:
                if state == 'DISABLED':
                    ok = self.orch.instance_delete(instance['instance_id'])
                    if not ok:
                        return "Error instance '%s' delete." % instance[
                            'instance_id']
                    else:
                        sproject.instance_id = None
                        sproject.status = DISABLED
                        sproject.save()

                else:
                    response = self.orch.instance_set_state(
                        instance['instance_id'], state)
                    code = None
                    if 'state' in response['response']:
                        code = get_status(response['response']['state'])
                        update_status_project(sproject.id, code)
                    if response['status_code'] not in (200, 201):
                        error_code = 'ORQUESTRATOR_STATE'
                        if 'code' in response['response']:
                            error_code = response['response']['code']
                        return create_message_error(response['status_code'],
                                                    error_code, code)
            elif code in (1, 3, 8):
                update_status_project(sproject.id, code)
            else:
                return create_message_error(404, 'NOT_UPDATE_STATE')
    def _get_state(self, services):
        # Services are items (not obj)
        # import pdb;pdb.set_trace()
        project_status = None
        data = None
        for sproject in services:
            service_id = unicode(sproject.pk)
            item = self.spres._find_item(unicode(service_id))
            instance = find_instance(unicode(item['_id']))
            if sproject.status == DISABLED:
                project_status = DISABLED
                break
            if instance:
                data = self.orch.instance_get_state(instance['instance_id'])
                if self.orch.req.status_code not in (200, 201):
                    code = None
                    response = json.loads(self.orch.req.text)
                    if 'state' in response:
                        code = get_status(response['state'])
                        update_status_project(sproject.pk, code)
                        error_code = 'ORQUESTRATOR_STATE'
                    if 'code' in response:
                        error_code = response['code']
                    return create_message_error(self.orch.req.status_code,
                                                error_code, code)
                state = data['state']
                if state:
                    status = STATES.index(state)
                    # 20160719 Cache status in db
                    sproject.status = status
                    sproject.runtime_params = dict(
                        runtime_params=data['runtime_params'])
                    sproject.save()
                    if project_status is None or status < project_status:
                        project_status = status
                    continue
                else:
                    code = get_status('FAILED')
                    update_status_project(sproject.pk, code)
                    return create_message_error(
                        404, _cfg.errors__orchestrator_state, code)
                    # some error
                    # break

        if (project_status is None) or (data is None):
            return create_message_error(404, _cfg.errors__orchestrator_state,
                                        '')
        else:
            return dict(status_code=self.orch.req.status_code,
                        status=project_status,
                        state=STATES[project_status],
                        runtime_params=data['runtime_params'])
 def put(self, id):
     data = get_json()
     user = self.get_user(id)
     if user is None:
         return create_response(
             404, create_message_error(404, 'USER_NOT_ACTIVATED'))
     response = self.keystone.change_password(user['keystone_user_id'],
                                              data)
     if response.status_code is not 204:
         self.status_code = response.status_code
         self.item = create_message_error(self.status_code,
                                          json.loads(response.text))
     else:
         self.u.update(id, {"password": False})
     return create_response(self.status_code, self.item)
 def __init__(self):
     self.path = get_cfg('keystone__url')
     self.user = None
     self.keystone = Keystone()
     self.response_msg = create_message_error(409, 'USER_DUPLICATED')
     self.smm = ServiceManagerMailer()
     self.session = Session()
    def get(self, id):
        user = self.get_user(id)
        if user is None:
            return create_response(
                404, create_message_error(404, 'USER_NOT_ACTIVATED'))
        new_password = generate_password()
        response = self.keystone.patch_user(user['keystone_user_id'],
                                            new_password)
        if response.status_code == 200:
            self.smm.change_password(user['email'], new_password)
            self.u.update(id, {"password": True})
        else:
            self.status_code = response.status_code
            self.item = create_message_error(self.status_code,
                                             json.loads(response.text))

        return create_response(self.status_code, self.item)
 def decorated_view(*args, **kwargs):
     jwt_token = get_token()
     if jwt_token:
         try:
             jwt.decode(jwt_token, 'secret', algorithms=['HS256'])
         except (jwt.DecodeError, jwt.ExpiredSignatureError):
             return respond_json(create_message_error(403, 'TOKEN_EXPIRED'),
                                 status=403)
     return fn(*args, **kwargs)
    def post(self):
        data = get_json()
        user = self.u.get_by_field('email', data['email'])
        if user is None:
            self.item = create_message_error(404, '')
            return create_response(404, self.item)
        new_password = generate_password()
        response = self.keystone.patch_user(user['keystone_user_id'],
                                            new_password)
        if response.status_code == 200:
            self.smm.change_password(user['email'], new_password)
            self.u.update(str(user['_id']), {"password": True})
        else:
            self.status_code = response.status_code
            self.item = create_message_error(self.status_code,
                                             json.loads(response.text))

        return create_response(self.status_code, self.item)
    def get(self, id):
        self.project = find_one_in_collection('projects',
                                              {"_id": ObjectId(id)})
        sproject = find_one_in_collection('sprojects',
                                          {"project": self.project['_id']})
        instance = find_one_in_collection('instances',
                                          {"sproject": sproject["_id"]})
        if instance is not None:
            item = self.create_data(str(instance["instance_id"]))
            if item is None:
                return respond_json(create_message_error(400, "BAD_URL"), 400)
            data = self.orch.get_billing(item)
            status_code = data.status_code
            response = data.text
        else:
            response = create_message_error(404, "NO_INSTANCES")
            status_code = 404

        return respond_json(response, status=status_code)
Beispiel #9
0
 def delete(self, id):
     self.u.update(id, self.data_delete)
     user = self.u.get(id)
     response = self.keystone.patch_user(user['keystone_user_id'], False)
     if response.status_code == 200:
         status_code = 204
         item = None
     else:
         status_code = 404
         item = create_message_error(404, "USER_NOT_FOUND")
     return create_response(status_code, item)
 def save_keystone(self, data):
     #primero comprobamos que el usuario ha de ser o proveedor o cliente
     if not data['client_role'] and not data['provider_role']:
         return respond_json(create_message_error(400, 'PROVIDER_CLIENT'),
                             400)
     # login
     response = self.keystone.get_login()
     if response.status_code == 201:
         token = get_keystone_token(response)
         json_data, entity_id, entity = self.keystone.get_project(
             get_cfg('keystone__project_name'), data)
         url = self.path + get_cfg('keystone__create_user')
         response = post(self.session, url, put_headers_keystone(token),
                         json_data)
         if response.status_code == 201:
             user_id = json.loads(response.text)['user']['id']
             # grabamos la info en mongo
             if data['provider_role']:
                 self.user = Provider()
             else:
                 self.user = Client()
             try:
                 self.dict_to_mongo_user(data, user_id, entity_id,
                                         str(entity['_id']))
                 self.response_msg = dict(status_code=204)
             except Exception as e:
                 '''
                 Cualquier error que se produzca al intentar grabar en BBDD. 
                 Hemos de borrar el usuario de Keystone
                 '''
                 print e
                 url = url + "/" + user_id
                 delete(self.session, url, put_headers_keystone(token))
                 self.response_msg = create_message_error(400)
             if self.response_msg['status_code'] == 204:
                 self.smm.notify(self.user.email)
         return respond_json(self.response_msg,
                             self.response_msg['status_code'])
Beispiel #11
0
    def user_login(self, email, password):
        self.keystone.keystone_admin = email
        self.keystone.keystone_admin_pass = password
        response = self.keystone.get_login()

        if response.status_code == 201:
            # Encontrado el usuario en Keystone. Lo buscamos en mongo
            data = find_one_in_collection(
                'users', {
                    'keystone_user_id':
                    json.loads(response.text)['token']['user']['id']
                })
            if data is not None:
                self.create_role_user(data)
                response.status_code = 200
            else:
                response.status_code = 404
                self.item = create_message_error(response.status_code,
                                                 "USER_NOT_FOUND")
        return create_response(response.status_code, self.item)
Beispiel #12
0
 def put(self, id):
     data = get_json()
     user = find_one_in_collection(self.collection, {"_id": ObjectId(id)})
     if 'activated' in data:
         response = self.keystone.patch_user(user['keystone_user_id'],
                                             data['activated'])
         if response.status_code == 200:
             if user['activated'] and not data['activated']:
                 self.smm.ban(user['email'])
             if data['activated'] and not user['activated']:
                 self.smm.welcome(user['email'])
     if '_id' in data:
         del data['_id']
     try:
         self.u.update(id, data)
         status_code = 204
     except Exception as e:
         print e
         status_code = 400
         self.item = create_message_error(status_code, "USER_NOT_FOUND")
         if 'activated' in data:
             self.keystone.patch_user(user['keystone_user_id'],
                                      not (data['activated']))
     return create_response(status_code, self.item)
def return_error_response(status_code, msg):
    return respond_json(create_message_error(status_code, msg),
                        status=status_code)
Beispiel #14
0
 def __init__(self):
     self.session = Session()
     self.user = None
     self.item = create_message_error(401, "USER_NOT_ACTIVATED")
     self.keystone = Keystone()
     self.time_token = Token().get()
Beispiel #15
0
def update_project(project, item, is_new=False):
    # import pdb;pdb.set_trace()
    _status = SAVED
    status_code = 200
    if is_new: status_code = 201
    try:
        resp = regex_name(item)
        if resp is not None: return resp
        if 'name' not in item:
            item['name'] = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
        client = None
        client_id = item.pop('client', None)
        if client_id:
            is_provider = get_type_user(client_id)
            if is_provider:
                client = Provider.objects.get(id=client_id)
                _status = CONFIRMED
            else:
                client = Client.objects.get(id=client_id)
        if project.client:
            if client and project.client != client:
                return error_api(
                    msg='Error: Client project can not be changed.',
                    status=400)
        elif client is None:
            return error_api("Client not defined.", status=400)
        else:
            project.client = client

        services = project.services
        if services:
            for sproject in list(services):
                sproject.delete()
                project.services.remove(sproject)

        sitems = item.pop('services')

        for name in ['name', 'description', 'summary']:
            if name in item:
                setattr(project, name, item[name])
        try:
            project.save()
        except NotUniqueError:
            error_response = create_message_error(409,
                                                  'NOT_UNIQUE_PROJECT_NAME')
            return respond_json(error_response, status=409)

        services = []
        if not sitems:
            project.delete()
            return error_api("No services.", status=400)
        try:
            for sitem in sitems:
                service_id = sitem['service']
                # service = ServiceDescription.objects.get(id=service_id)
                service = get_db(_cfg.database__database_name)['services']. \
                    find_one({'_id': ObjectId(service_id)})
                if service is None:
                    project.delete()
                    return error_api("Service '%s' doesn't exist." %
                                     service_id,
                                     status=400)
                services.append(service)
        except Exception, err:
            project.delete()
            return error_api(msg="Error in project '%s'." % err, status=400)
        try:
            for sitem, service in zip(sitems, services):
                # context_type=sitem.get('context_type', '')
                provider = service['provider']
                sproject = SProject(service=service['_id'],
                                    project=project,
                                    provider=provider,
                                    status=_status)
                sproject.save()
                project.services.append(sproject)
            project.save()
        except Exception, err:
            if project.services:
                for sproject in project.services:
                    sproject.delete()
                project.delete()
                return error_api(msg="Error: updating project '%s'." % err,
                                 status=400)
Beispiel #16
0
    def _set_state(self, services, state):
        # Services are items (not obj)
        # import pdb;pdb.set_trace()
        for sproject in services:
            item = self.spres._find_item(unicode(sproject.pk))
            # Save consumer params in SProjects
            sproject.consumer_params = dict(
                consumer_params=self.consumer_params)
            sproject.save()
            instance = find_instance(unicode(item['_id']))
            if instance:
                if state == 'DISABLED':
                    ok = self.orch.instance_delete(instance['instance_id'])
                    if not ok:
                        return "Error instance '%s' delete." % instance[
                            'instance_id']
                    else:
                        sproject.instance_id = None
                        sproject.status = DISABLED
                        sproject.save()

                else:
                    response = self.orch.instance_set_state(
                        instance['instance_id'], state)
                    code = None
                    if 'state' in response['response']:
                        code = get_status(response['response']['state'])
                        update_status_project(sproject.id, code)
                    if response['status_code'] not in (200, 201):
                        error_code = 'ORQUESTRATOR_STATE'
                        if 'code' in response['response']:
                            error_code = response['response']['code']
                        return create_message_error(response['status_code'],
                                                    error_code, code)

            else:
                # context para el orquestrador
                service = get_service(item['service'])
                context = service['context']
                # name_image = context['name_image']
                # Primero miramos si está la imagen cacheada en el orquestrador
                if (context['vm_image_format']
                        == 'openstack_id') or (self.exists_image(context)):
                    if context['vm_image_format'] == 'openstack_id':
                        context['vm_image'] = context['name_image']
                    else:
                        context['vm_image'] = _cfg.repository__ip + context[
                            'name_image']
                else:
                    # Si no lo está. Guardamos la imagen en local
                    context['vm_image'] = save_image_to_local(
                        context['vm_image'], context['name_image'])
                # guardada la imagen. Seguimos
                context['consumer_params'] = self.consumer_params
                context = dict(context=context)
                resp = self.orch.instance_create(context)
                if resp.status_code in (200, 201):
                    data = json.loads(resp.text)
                    instance_id = data['service_instance_id']
                    instance = Instance(sproject=sproject,
                                        instance_id=instance_id)
                    instance.save()
                    # delete local image
                    # path_file = "{0}{1}".format(_cfg.repository__path, name_image)
                    # os.remove(path_file)
                else:
                    resp_text = ''
                    json_load = json.loads(resp.text)
                    if 'code' in json_load:
                        resp_text = json_load['code']
                    return create_message_error(resp.status_code, resp_text,
                                                '')

        error = self._get_state(services)
        if error['status_code'] not in (200, 201):
            return create_message_error(self.orch.req.status_code,
                                        json.loads(self.orch.req.text)['code'],
                                        '')