def on_post(self, req, resp, project_id, session_id): # POST /v2/{project_id}/sessions/{session_id}/action # executes an action on the specified session user_id = req.get_header('X-User-ID') or '' doc = self.json_body(req) try: action, params = next(iter(doc.items())) except Exception: raise freezer_api_exc.BadDataFormat("Bad action request format") session_doc = self.db.get_session(project_id=project_id, user_id=user_id, session_id=session_id) session = Session(session_doc) session.execute_action(action, params) if session.need_update: self.db.update_session(project_id=project_id, user_id=user_id, session_id=session_id, patch_doc=session.doc) resp.status = falcon.HTTP_202 resp.body = { 'result': session.action_result, 'session_tag': session.session_tag }
def on_post(self, req, resp, project_id, job_id): # POST /v1/jobs/{job_id}/event # requests an event on the specified job user_id = req.get_header('X-User-ID') or '' doc = self.json_body(req) try: event, params = next(six.iteritems(doc)) except Exception: raise freezer_api_exc.BadDataFormat("Bad event request format") job_doc = self.db.get_job(project_id=project_id, user_id=user_id, job_id=job_id) job = Job(job_doc) result = job.execute_event(event, params) if job.need_update: self.db.replace_job(project_id=project_id, user_id=user_id, job_id=job_id, doc=job.doc) resp.status = falcon.HTTP_202 resp.body = {'result': result}
def add_backup(user_id, user_name, doc, project_id=None): if CONF.enable_v1_api: metadatadoc = utilsv1.BackupMetadataDoc(user_id, user_name, doc) else: metadatadoc = utilsv2.BackupMetadataDoc(project_id, user_id, user_name, doc) if not metadatadoc.is_valid(): raise freezer_api_exc.BadDataFormat(message='Bad Data Format') backup_id = metadatadoc.backup_id backupjson = metadatadoc.serialize() backup_metadata = backupjson.get('backup_metadata') existing = get_backup(project_id=project_id, user_id=user_id, backup_id=backup_id) if existing: raise freezer_api_exc.DocumentExists( message='Backup already registered with ID' ' {0}'.format(backup_id)) backup = models.Backup() backupvalue = {} backupvalue['project_id'] = project_id backupvalue['id'] = backup_id backupvalue['user_id'] = user_id backupvalue['user_name'] = user_name backupvalue['job_id'] = backup_metadata.get('job_id') # The field backup_metadata is json, including : # hostname , backup_name , container etc backupvalue['backup_metadata'] = json_utils.json_encode(backup_metadata) backup.update(backupvalue) add_tuple(tuple=backup) LOG.info('Backup registered, backup_id: {0}'.format(backup_id)) return backup_id
def set_job_end(self, job_id, result, timestamp): try: job = self.doc['jobs'][job_id] except Exception: raise freezer_api_exc.BadDataFormat('job_id not found in session') job['status'] = 'completed' job['result'] = result job['time_ended'] = timestamp
def set_job_start(self, job_id, timestamp): try: job = self.doc['jobs'][job_id] except Exception: raise freezer_api_exc.BadDataFormat('job_id not found in session') job['status'] = 'running' job['result'] = '' job['time_started'] = timestamp
def on_post(self, req, resp): # POST /v1/sessions Creates session entry doc = self.json_body(req) if not doc: raise freezer_api_exc.BadDataFormat(message='Missing request body') user_id = req.get_header('X-User-ID') session_id = self.db.add_session(user_id=user_id, doc=doc) resp.status = falcon.HTTP_201 resp.body = {'session_id': session_id}
def add_backup(self, project_id, user_id, user_name, doc): # raises if data is malformed (HTTP_400) or already present (HTTP_409) backup_metadata_doc = utils.BackupMetadataDoc(project_id, user_id, user_name, doc) if not backup_metadata_doc.is_valid(): raise freezer_api_exc.BadDataFormat(message='Bad Data Format') backup_id = backup_metadata_doc.backup_id self.backup_manager.insert(backup_metadata_doc.serialize(), backup_id) return backup_id
def expand_default_properties(self): action_defaults = self.doc.pop("action_defaults") if isinstance(action_defaults, dict): for key, val in six.iteritems(action_defaults): for action in self.doc.get("job_actions"): if action["freezer_action"].get(key) is None: action["freezer_action"][key] = val else: raise freezer_api_exc.BadDataFormat( message="action_defaults shouldbe a dictionary")
def on_post(self, req, resp, project_id): # POST /v1/clients Creates client entry doc = self.json_body(req) if not doc: raise freezer_api_exc.BadDataFormat(message='Missing request body') user_id = req.get_header('X-User-ID') client_id = self.db.add_client(project_id=project_id, user_id=user_id, doc=doc) resp.status = falcon.HTTP_201 resp.body = {'client_id': client_id}
def execute_event(self, event, params): handler = self.event_handlers.get(event, None) if not handler: raise freezer_api_exc.BadDataFormat("Bad Action Method") try: self.event_result = handler(params) except freezer_api_exc.BadDataFormat: raise except Exception as e: raise freezer_api_exc.FreezerAPIException(e) return self.event_result
def on_post(self, req, resp, session_id): # PUT /v1/sessions/{session_id} creates/replaces the specified session user_id = req.get_header('X-User-ID') or '' doc = self.json_body(req) if not doc: raise freezer_api_exc.BadDataFormat(message='Missing request body') new_version = self.db.replace_session(user_id=user_id, session_id=session_id, doc=doc) resp.status = falcon.HTTP_201 resp.body = {'session_id': session_id, 'version': new_version}
def add_backup(self, user_id, user_name, data): backup_metadata_doc = BackupMetadataDoc(user_id, user_name, data) if not backup_metadata_doc.is_valid(): raise exceptions.BadDataFormat(message='Bad Data Format') backup_id = backup_metadata_doc.backup_id if (user_id, backup_id) in self._map: raise exceptions.DocumentExists( message='Backup data already existing ({0})'.format(backup_id), resp_body={'backup_id': backup_id}) self._map[(user_id, backup_id)] = backup_metadata_doc.serialize() logging.info('Adding backup data with backup_id {0}'.format(backup_id)) return backup_id
def on_post(self, req, resp): # POST /v1/jobs Creates job entry try: job = Job(self.json_body(req)) except KeyError: raise freezer_api_exc.BadDataFormat(message='Missing request body') user_id = req.get_header('X-User-ID') self.update_actions_in_job(user_id, job.doc) job_id = self.db.add_job(user_id=user_id, doc=job.doc) resp.status = falcon.HTTP_201 resp.body = {'job_id': job_id}
def on_post(self, req, resp): # POST /v1/backups Creates backup entry doc = self.json_body(req) if not doc: raise freezer_api_exc.BadDataFormat(message='Missing request body') user_name = req.get_header('X-User-Name') user_id = req.get_header('X-User-ID') backup_id = self.db.add_backup(user_id=user_id, user_name=user_name, doc=doc) resp.status = falcon.HTTP_201 resp.body = {'backup_id': backup_id}
def json_body(req): if not req.content_length: return {} try: raw_json = req.stream.read() except Exception: raise freezer_api_exc.BadDataFormat('Empty request body. A valid ' 'JSON document is required.') try: json_data = json.loads(raw_json, encoding='utf-8') except ValueError: raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON') return json_data
def on_post(self, req, resp): # POST /v1/backups Creates backup entry try: doc = req.context['doc'] except KeyError: raise exceptions.BadDataFormat( message='Missing request body', resp_body={'error': 'missing request body'}) user_name = req.get_header('X-User-Name') user_id = req.get_header('X-User-ID') backup_id = self.db.add_backup(user_id=user_id, user_name=user_name, data=doc) resp.status = falcon.HTTP_201 req.context['result'] = {'backup_id': backup_id}
def add_backup(self, user_id, user_name, data): # raises if data is malformed (HTTP_400) or already present (HTTP_409) backup_metadata_doc = BackupMetadataDoc(user_id, user_name, data) if not backup_metadata_doc.is_valid(): raise exceptions.BadDataFormat(message='Bad Data Format') backup_id = backup_metadata_doc.backup_id existing_data = self._get_backup(user_id, backup_id) if existing_data: raise exceptions.DocumentExists( message='Backup data already existing ({0})'.format(backup_id), resp_body={'backup_id': backup_id}) if not self._index(backup_metadata_doc.serialize()): # should never happen raise exceptions.StorageEngineError( message='index operation failed', resp_body={'backup_id': backup_id}) logging.info('Backup metadata indexed, backup_id: {0}'. format(backup_id)) return backup_id
def start(self, job_id, job_tag): """ Apply the 'start' action to the session object If the request can be accepted it modifies the relevant fields and sets the need_update member to notify that the stored document needs to be updated """ job_tag = int(job_tag) self.session_tag = int(self.session_tag) now = int(time.time()) time_since_last_start = now - self.doc.get('time_start', 0) if job_tag > self.session_tag: raise freezer_api_exc.BadDataFormat( 'requested tag value too high. Session Tag: {0} ' 'Job Tag: {1}'.format(self.session_tag, job_tag)) if time_since_last_start <= self.doc.get('hold_off', 60): # session has been started not so long ago # tag increments are not allowed during hold_off if job_tag < self.session_tag: self.action_result = 'success' self.set_job_start(job_id, now) self.need_update = True else: self.action_result = 'hold-off' self.need_update = False elif time_since_last_start > self.doc.get('hold_off', 60): # out of hold_off window: # - ok to trigger new action start (job_tag == session_tag) # if job_tag < session_tag client is probably out-of-sync if self.session_tag == job_tag: self.session_tag += 1 self.doc['time_start'] = now self.doc['status'] = 'running' self.doc['result'] = '' self.action_result = 'success' self.set_job_start(job_id, now) self.need_update = True else: self.action_result = 'out-of-sync' self.need_update = False
def test_BadDataFormat(self): e = exceptions.BadDataFormat(message='testing') self.assertRaises(falcon.HTTPBadRequest, e.handle, self.ex, self.mock_req, self.mock_req, None)
def validate(doc): LOG.debug("Debugging Session validate: {0}".format(doc)) try: SessionDoc.session_doc_validator.validate(doc) except Exception as e: raise freezer_api_exc.BadDataFormat(str(e).splitlines()[0])
def validate(doc): try: SessionDoc.session_doc_validator.validate(doc) except Exception as e: raise freezer_api_exc.BadDataFormat(str(e).splitlines()[0])
def validate(doc): try: ClientDoc.client_doc_validator.validate(doc) except Exception as e: raise freezer_api_exc.BadDataFormat(str(e).splitlines()[0])
def validate_patch(doc): try: JobDoc.job_patch_validator.validate(doc) except Exception as e: raise freezer_api_exc.BadDataFormat(str(e).splitlines()[0])