|
| 1 | +# system imports |
| 2 | +from http import HTTPStatus |
| 3 | + |
| 4 | +# web imports |
| 5 | +from flask import request, jsonify, make_response |
| 6 | +from flask.views import MethodView |
| 7 | + |
| 8 | +# lib imports |
| 9 | +from .classes import JobExecutor, ReportStore, RequestParser |
| 10 | + |
| 11 | + |
| 12 | +class shell2httpAPI(MethodView): |
| 13 | + command_name: str |
| 14 | + executor: JobExecutor |
| 15 | + store: ReportStore |
| 16 | + request_parser: RequestParser |
| 17 | + |
| 18 | + def get(self): |
| 19 | + try: |
| 20 | + md5: str = request.args.get("key") |
| 21 | + if not md5: |
| 22 | + raise Exception("No key provided in arguments.") |
| 23 | + # check if job has been finished |
| 24 | + future = self.executor.get_job(md5) |
| 25 | + if future: |
| 26 | + if not future.done: |
| 27 | + return make_response(jsonify(status="running", md5=md5), 200) |
| 28 | + |
| 29 | + # pop future object since it has been finished |
| 30 | + self.executor.pop_job(md5) |
| 31 | + |
| 32 | + # if yes, get result from store |
| 33 | + report = self.store.get_one(md5) |
| 34 | + if not report: |
| 35 | + raise Exception(f"Report does not exist for key:{md5}") |
| 36 | + |
| 37 | + return make_response(report.to_json(), HTTPStatus.OK) |
| 38 | + |
| 39 | + except Exception as e: |
| 40 | + return make_response(jsonify(error=str(e)), HTTPStatus.NOT_FOUND) |
| 41 | + |
| 42 | + def post(self): |
| 43 | + try: |
| 44 | + # Check if command is correct and parse it |
| 45 | + cmd, md5 = self.request_parser.parse_req(request) |
| 46 | + |
| 47 | + # run executor job in background |
| 48 | + job_key = JobExecutor.make_key(md5) |
| 49 | + future = self.executor.new_job( |
| 50 | + future_key=job_key, fn=self.executor.run_command, cmd=cmd, md5=md5 |
| 51 | + ) |
| 52 | + # callback that adds result to store |
| 53 | + future.add_done_callback(self.store.save_result) |
| 54 | + # callback that removes the temporary directory |
| 55 | + future.add_done_callback(self.request_parser.cleanup_temp_dir) |
| 56 | + |
| 57 | + return make_response( |
| 58 | + jsonify(status="running", key=md5), HTTPStatus.ACCEPTED, |
| 59 | + ) |
| 60 | + |
| 61 | + except Exception as e: |
| 62 | + return make_response(jsonify(error=str(e)), HTTPStatus.BAD_REQUEST) |
| 63 | + |
| 64 | + def __init__(self, command_name, executor): |
| 65 | + self.command_name = command_name |
| 66 | + self.executor = JobExecutor(executor) |
| 67 | + self.store = ReportStore() |
| 68 | + self.request_parser = RequestParser(command_name) |
0 commit comments