Beispiel #1
0
    def POST(self, req, *parts):
        """
        Handle Machine operations
        """
        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        request_data = request_data.get('body', {})
        if request_data.get('Action'):
            request_data = request_data.get('Action')
        action = request_data.get('action', 'notexist')
        method = self.actions.get(action)
        if method:
            resp = getattr(self, '_' + method)(req, request_data, *parts)
        else:
            resp = get_err_response('NotImplemented')

        return resp
Beispiel #2
0
    def POST(self, req, *parts):
        """
        Handle Machine operations
        """
        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        request_data = request_data.get('body', {})
        if request_data.get('Action'):
            request_data = request_data.get('Action')
        action = request_data.get('action', 'notexist')
        resp = None
        if action in Consts.MACHINE_ACTIONS:
            # Need to get the current machine state
            env = self._fresh_env(req)
            env['SCRIPT_NAME'] = '/v2'
            env['CONTENT_LENGTH'] = 0

            action = action.split('/')[-1]
            access_path = '/'.join(['/v2', self.tenant_id, 'servers',
                                    parts[0]])
            status, headers, body, status_code = access_resource(env, 'GET',
                access_path, True, None, None)
            if status:
                body = json.loads(body)
                key = ''.join([body['server']['status'].lower(), '_', action])
                method = Consts.MACHINE_ACTION_MAPS.get(key)
                if method:
                    resp = self._run_method(req, request_data, method, *parts)
            else:
                resp = get_err_response('NotFound')

        if resp:
            return resp
        else:
            return get_err_response('NotImplemented')
Beispiel #3
0
    def DELETE(self, req, *parts):
        """
        handle volume detach operation
        """
        #parts is /server_id/attach_id

        if len(parts) < 2:
            return get_err_response('BadRequest')

        env = self._fresh_env(req)
        env['PATH_INFO'] = concat(self.os_path, '/', parts[0],
                                  '/os-volume_attachments/', parts[1])
        env['CONTENT_TYPE'] = 'application/json'
        new_req = Request(env)
        res = new_req.get_response(self.app)

        return res
Beispiel #4
0
    def POST(self, req, *parts):
        """
        Handle POST machineVolumeCollection request which will attach an volume
        """
        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        if request_data:
            data = request_data.get('body').get('MachineVolume')
            if not data:
                data = request_data.get('body')
            if data:

                volume_url = data.get('volume', {}).get('href')
                if volume_url:
                    volume_id = volume_url.strip('/').split('/')[-1]
                else:
                    return get_err_response('MalformedBody')

                device = data.get('initialLocation')
                if not device:
                    return get_err_response('MalformedBody')

                reqdata = {}
                reqdata['volumeAttachment'] = {'volumeId': volume_id,
                                            'device': device}
                env = self._fresh_env(req)
                env['PATH_INFO'] = concat(self.os_path, '/', parts[0],
                                          '/os-volume_attachments')
                env['CONTENT_TYPE'] = 'application/json'
                new_req = Request(env)
                new_req.body = json.dumps(reqdata)
                res = new_req.get_response(self.app)
                if res.status_int == 200:
                    data = json.loads(res.body).get('volumeAttachment')
                    attach_id = data.get('id')
                    server_id = data.get('serverId')
                    volume_id = data.get('volumeId')

                    body = {}
                    match_up(body, data, 'initialLocation', 'device')

                    body['id'] = concat(self.tenant_id, '/machinevolume/',
                                        server_id, '/', attach_id)
                    location = '/'.join([self.request_prefix, body['id']])

                    body['volume'] = {'href': concat(self.tenant_id,
                                                    '/volume/', volume_id)}

                    # deal with volume attach operations
                    operations = []
                    operations.append(self._create_op('edit', body['id']))

                    operations.append(self._create_op('delete', body['id']))
                    body['operations'] = operations
                    body['state'] = 'ATTACHING'

                    if self.res_content_type == 'application/xml':
                        response_data = {'MachineVolume': body}
                    else:
                        body['resourceURI'] = concat(self.uri_prefix,
                                                    '/MachineVolume')
                        response_data = body

                    new_content = make_response_data(response_data,
                                                 self.res_content_type,
                                                 self.machine_volume_metadata,
                                                 self.uri_prefix)
                    resp = Response()
                    self._fixup_cimi_header(resp)
                    resp.headers['Content-Type'] = self.res_content_type
                    resp.headers['Location'] = location
                    resp.status = 201
                    resp.body = new_content
                    return resp
                else:
                    return res

            else:
                return get_err_response('BadRequest')
        else:
            return get_err_response('BadRequest')
Beispiel #5
0
    def POST(self, req, *parts):
        """
        Handle POST machine request which will create a machine
        """

        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        if request_data:
            data = request_data.get('body').get('VolumeCreate')
            if not data:
                data = request_data.get('body')
                if data:
                    action = data.get('resourceURI')
                    # this is to ensure that the json format contains
                    # the right indicator for volume create
                    if not action or action != '/'.join([self.uri_prefix,
                                          'VolumeCreate']):
                        data = None
            if data:
                new_body = {}
                match_up(new_body, data, 'display_name', 'name')
                match_up(new_body, data, 'display_description', 'description')
                match_up(new_body, data, 'size',
                         'volumeTemplate/volumeConfig/capacity')
                # map the properties to metadata
                match_up(new_body, data, 'metadata', 'properties')
                # check if there are some extra things
                """
                if has_extra(data, {'resourceURI': None, 'xmlns': None,
                                    'name': None, 'description': None,
                                    'properties': None,
                                    'volumeTemplate': {'volumeConfig':
                                                       {'capacity': None}}}):
                    return get_err_response('BadRequest')
                """
                self.os_path = '/%s/volumes' % (self.tenant_id)
                env = self._fresh_env(req)
                env['SERVER_PORT'] = self.conf.get('volume_endpoint_port')
                env['SCRIPT_NAME'] = '/v1'
                env['HTTP_HOST'] = '%s:%s' % \
                    (self.conf.get('volume_endpoint_host'),
                     self.conf.get('volume_endpoint_port'))
                new_body_json = json.dumps({'volume': new_body})
                env['CONTENT_LENGTH'] = len(new_body_json)

                status, headers, body, status_code = access_resource(env,
                    'POST', '/v1' + self.os_path, True, None, new_body_json)

                if status:
                    # resource created successfully, we redirect the request
                    # to query machine
                    resp_data = json.loads(body)
                    data = resp_data.get('volume')
                    resp_data = {}
                    match_up(resp_data, data, 'name', 'display_name')
                    match_up(resp_data, data, 'description',
                             'display_description')
                    match_up(resp_data, data, 'capacity', 'size')
                    match_up(resp_data, data, 'created', 'created_at')
                    resp_data['id'] = ''.join([self.tenant_id,
                                               '/volume/',
                                               data.get('id')])
                    location = resp_data['id']
                    if self.res_content_type == 'application/xml':
                        response_data = {'Volume': resp_data}
                    else:
                        resp_data['resourceURI'] = '/'.join([self.uri_prefix,
                                                            'Volume'])
                        response_data = resp_data

                    new_content = make_response_data(response_data,
                                             self.res_content_type,
                                             self.volume_metadata,
                                             self.uri_prefix)
                    resp = Response()
                    self._fixup_cimi_header(resp)
                    resp.headers['Content-Type'] = self.res_content_type
                    resp.headers['Location'] = \
                        '/'.join([self.request_prefix,
                                  location])
                    resp.status = 201
                    resp.body = new_content
                    return resp
                else:
                    return get_err_response('BadRequest')
            else:
                return get_err_response('BadRequest')
        else:
            return get_err_response('BadRequest')
Beispiel #6
0
    def POST(self, req, *parts):
        """
        Handle POST machine request which will create a machine
        """

        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        if request_data:
            data = request_data.get('body').get('MachineCreate')
            if not data:
                data = request_data.get('body')
            if data:
                new_body = {}
                match_up(new_body, data, 'name', 'name')

                if (data.get('machineTemplate') is None or
                    data.get('machineTemplate').get('machineImage') is None or
                    data.get('machineTemplate').get('machineConfig') is None):
                    return get_err_response('BadRequest')

                match_up(new_body, data, 'imageRef',
                         'machineTemplate/machineImage/href')

                match_up(new_body, data, 'flavorRef',
                         'machineTemplate/machineConfig/href')

                if (new_body.get('flavorRef') is None or
                    new_body.get('imageRef') is None):
                    return get_err_response('BadRequest')

                new_body['imageRef'] = new_body.get('imageRef').split('/')[-1]
                new_body['flavorRef'] = \
                    new_body.get('flavorRef').split('/')[-1]

                adminPass = data.get('credentials', {}).get('password')
                if adminPass:
                    new_body['adminPass'] = adminPass

                self.os_path = '/%s/servers' % (self.tenant_id)
                new_req = self._fresh_request(req)

                new_req.body = json.dumps({'server': new_body})
                resp = new_req.get_response(self.app)
                if resp.status_int == 201:
                    # resource created successfully, we redirect the request
                    # to query machine
                    resp_data = json.loads(resp.body)
                    id = resp_data.get('server').get('id')
                    env = self._fresh_env(req)
                    env['PATH_INFO'] = concat(self.request_prefix,
                                              '/', self.tenant_id,
                                              '/servers/', id)
                    env['REQUEST_METHOD'] = 'GET'
                    new_req = Request(env)
                    resp = new_req.get_response(self.app)
                    resp_data = {}
                    resp.headers['Location'] = \
                        '/'.join([self.request_prefix, self.tenant_id,
                                  'Machine', id])
                    resp.status = 201
                elif resp.status_int == 202:
                    resp_body_data = json.loads(resp.body).get('server')
                    id = resp_body_data.get('id')
                    resp_data = {}
                    resp_data['resourceURI'] = '/'.join([self.uri_prefix,
                                            'Machine'])
                    match_up(resp_data, data, 'name', 'name')
                    resp_data['id'] = concat(self.tenant_id, '/Machine/', id)
                    resp_data['credentials'] = {'userName': '******',
                        'password': resp_body_data.get('adminPass')}
                    if self.res_content_type == 'application/xml':
                        response_data = {'Machine': resp_data}
                        remove_member(response_data, 'resourceURI')
                    else:
                        response_data = resp_data

                    new_content = make_response_data(response_data,
                                             self.res_content_type,
                                             self.machine_metadata,
                                             self.uri_prefix)
                    resp = Response()
                    self._fixup_cimi_header(resp)
                    resp.headers['Content-Type'] = self.res_content_type
                    resp.headers['Location'] = \
                        '/'.join([self.request_prefix, self.tenant_id,
                                  'Machine', id])
                    resp.status = 202
                    resp.body = new_content
                return resp
            else:
                return get_err_response('BadRequest')
        else:
            return get_err_response('BadRequest')