From d9411642b6c86aa4cfb187f66bc0624ecf7c3558 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Fri, 21 Apr 2023 14:53:00 -0500 Subject: [PATCH] DB --- api/api.py | 168 +++++++++---------------------------------- api/db.py | 127 ++++++++++++++++++++++++++++++++ api/job_processor.py | 61 ++++++++++++++++ api/requirements.txt | 2 + 4 files changed, 223 insertions(+), 135 deletions(-) create mode 100644 api/db.py create mode 100644 api/job_processor.py diff --git a/api/api.py b/api/api.py index 8f0c8c7..5953727 100644 --- a/api/api.py +++ b/api/api.py @@ -4,137 +4,43 @@ Author: oitsjustjose @ modrinth/curseforge/twitter """ import json -from dataclasses import asdict, dataclass -from multiprocessing import Manager, Process +from dataclasses import asdict +from multiprocessing import Process from os import environ as env -from os.path import exists -from time import sleep -from typing import List -from cryptography.fernet import Fernet from flask import Flask, request -from shortuuid import ShortUUID -from processor import download, upload - - -@dataclass -class Job: - """A single job""" - - github_pat: str - curseforge_slug: str - modrinth_id: str - logs = [] - job_id: str = ShortUUID().random(length=8) - delimiter: str = "-" +from db import Job, JobDb, Status +from job_processor import worker app = Flask(__name__) -fer = Fernet(env["SECRET"]) + +db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) -manager = Manager() -active_jobs: List[Job] = manager.list() -jobs: List[Job] = manager.list() -completed: List[Job] = manager.list() - - -def job_processor(): - print("Starting the job processor") - while True: - try: - sleep(1) - if not jobs: - continue - active_job = jobs[0] - active_jobs.append(active_job) - - active_job.logs += download(active_job.curseforge_slug) - active_job.logs += upload( - active_job.github_pat, - active_job.curseforge_slug, - active_job.modrinth_id, - active_job.delimiter, - ) - - active_job.github_pat = "" - completed.append(active_job) - - for idx, obj in enumerate(active_jobs): - if obj.job_id == active_job.job_id: - del active_jobs[idx] - for idx, obj in enumerate(jobs): - if obj.job_id == active_job.job_id: - del jobs[idx] - - except KeyboardInterrupt: - break - - -def save(): - """Saves the current application state to an encrypted file""" - - data = { - "jobs": [asdict(x) for x in jobs], - "completed": dict(completed), - } - with open("./state.dat", "wb") as handle: - handle.write(fer.encrypt(json.dumps(data).encode())) - - -def load(): - """Loads the current application state from encrypted file""" - global active_job, jobs, completed - if not exists("./state.dat"): - return - with open("./state.dat", "rb") as handle: - data = json.loads(fer.decrypt(handle.read().decode())) - if "jobs" in data: - for job in data["jobs"]: - jobs.append( - Job( - github_pat=job["github_pat"], - curseforge_slug=job["curseforge_slug"], - modrinth_id=job["modrinth_id"], - job_id=job["job_id"], - delimiter=job["delimiter"], - ) - ) - - if "completed" in data: - completed = data["completed"] - print(completed, jobs) - - -@app.route("/jobs/status/", methods=["GET", "POST"]) -def get_job_status(uuid: str) -> str: +@app.route("/jobs/status/", methods=["GET", "POST"]) +def get_job_status(job_id: str) -> str: "Gets the queue status for a given job" - for job in active_jobs: - if job.job_id == uuid: - return "Currently Processing", 200 - - for job in completed: - if job.job_id == uuid: - logs = "\\n".join(job.logs) - return f"Completed!\n{logs}", 200 - - for idx, job in enumerate(jobs): - if job.job_id == uuid: - return f"Enqueued: {idx+1} Job(s) Ahead In Queue", 200 + status, logs, queue = db.get_job_status(job_id) + if status == Status.ENQUEUED: + return f"Enqueued: {queue} Job(s) Ahead In Queue", 200 + if status == Status.PROCESSING: + return f"Currently Processing!\n{logs}", 200 + if status == Status.COMPLETED: + return f"Completed!\n{logs}", 200 return "Failed to find job", 404 -@app.route("/jobs/info/", methods=["GET", "POST"]) -def get_job_info(uuid: str): +@app.route("/jobs/info/", methods=["GET", "POST"]) +def get_job_info(job_id: str): """Gets the job info for a given uuid""" - for job in jobs: - if job.job_id == uuid: - data = asdict(job) - data.pop("github_pat") - return json.dumps(data), 200 - return "Failed to find job", 404 + job = db.get_job(job_id) + if not job: + return "Failed to find job", 404 + job.github_pat = "" + return json.dumps(asdict(job), indent=2), 200 @app.route("/jobs/new", methods=["POST"]) @@ -149,26 +55,18 @@ def new_job(): delimiter=data["delimiter"] if "delimiter" in data else "-", ) - # Don't enqueue a task that already exists - for job in jobs: - if ( - job.github_pat == jobe.github_pat - and job.curseforge_slug == jobe.curseforge_slug - and job.modrinth_id == jobe.modrinth_id - and job.delimiter == jobe.delimiter - ): - return job.job_id, 200 - - jobs.append(jobe) - return jobe.job_id, 200 + # Job already exists in queue, give it back + existing = db.get_existing_queued_job(jobe.curseforge_slug, jobe.modrinth_id) + if existing: + return existing, 200 + return db.enqueue_job(jobe), 200 except: return "Internal Server Error", 500 -load() -proc = Process(target=job_processor) -proc.start() - -app.run("0.0.0.0", env["PORT"] if "PORT" in env else 3000) -proc.join() -save() +if __name__ == "__main__": + proc_cnt: int = int(env["PROCS"]) if "PROCS" in env else 1 + processes = [Process(target=worker) for _ in range(proc_cnt)] + _ = [p.start() for p in processes] + app.run("0.0.0.0", env["PORT"] if "PORT" in env else 3000) + _ = [p.join() for p in processes] diff --git a/api/db.py b/api/db.py new file mode 100644 index 0000000..844f9c5 --- /dev/null +++ b/api/db.py @@ -0,0 +1,127 @@ +"""DB Handling for Jobs""" + +from dataclasses import asdict, dataclass +from enum import Enum +from os import environ as env +from typing import Dict, List, Tuple, Union + +from cryptography.fernet import Fernet +from pymongo import ASCENDING, DESCENDING, MongoClient +from pymongo.collection import Collection +from pymongo.database import Database +from shortuuid import ShortUUID + + +class Status(Enum): + """Job Status""" + + ENQUEUED = 0 + PROCESSING = 1 + COMPLETED = 2 + NOTFOUND = -1 + + +@dataclass +class Job: + """A single job""" + + github_pat: str + curseforge_slug: str + modrinth_id: str + job_id: str = ShortUUID().random(length=8) + delimiter: str = "-" + logs: str = "" + status: Status = Status.ENQUEUED + queue_place: int = 0 + + +class JobDb: + """A database for the job queue""" + + def __init__(self, host: str, port: int): + self._client: MongoClient = MongoClient(host, port) + self._db: Database = self._client["ctmmm"] + self._coll: Collection = self._db["jobs"] + self._fernet = Fernet(env["SECRET"]) + + def get_job(self, job_id: str) -> Union[Job, None]: + """Gets a job by the job's short ID""" + data: Union[dict, None] = self._coll.find_one({"job_id": job_id}) + if not data: + return None + return self._dict_to_job(data) + + def get_next_job(self) -> Union[Job, None]: + """Gets the next job to do, if any""" + data: List[Union[dict, None]] = list( + self._coll.find({"status": 0}).sort("queue_place", ASCENDING).limit(1) + ) + if data: + return self._dict_to_job(data[0]) + return None + + def get_active_jobs(self) -> List[Job]: + data: List[Union[dict, None]] = list( + self._coll.find({"status": 0}).sort("queue_place", ASCENDING).limit(1) + ) + return data + + def enqueue_job(self, job: Job) -> str: + """Inserts the job, with corrected Queue Place and encrypted PAT""" + queue_place = 0 + data: List[Union[dict, None]] = list( + self._coll.find({"status": 0}).sort("queue_place", DESCENDING).limit(1) + ) + if data: + queue_place = data[0]["queue_place"] + 1 + job.queue_place = queue_place + job.github_pat = self._fernet.encrypt(job.github_pat.encode()) + job.status = job.status.value + self._coll.insert_one(asdict(job)) + return job.job_id + + def update_job_status( + self, job_id: str, status: Status, logs: Union[str, None] = None + ) -> None: + """Updates the status of a job, and logs, if applicable""" + update = {"status": status.value} + if logs: + update["logs"] = logs + self._coll.update_one({"job_id": job_id}, {"$set": update}) + + def get_job_status(self, job_id: str) -> Tuple[Status, str, int]: + """Gets the status of a job, including queue place and logs""" + data: Union[dict, None] = self._coll.find_one({"job_id": job_id}) + if not data: + return (Status.NOTFOUND, [], -1) + return ( + Status(data["status"]), + data["logs"], + data["queue_place"], + ) + + def get_existing_queued_job(self, slug: str, proj_id: str) -> Union[str, None]: + """Gets the existing job ID if it exists""" + data: Union[dict, None] = self._coll.find_one( + { + "status": Status.ENQUEUED.value, + "curseforge_slug": slug, + "modrinth_id": proj_id, + } + ) + if not data: + return None + return data["job_id"] + + def _dict_to_job(self, data: Dict) -> Job: + """Converts a dictionary (from mongo) into a Job""" + return Job( + github_pat=self._fernet.decrypt(data["github_pat"].decode()), + curseforge_slug=data["curseforge_slug"], + modrinth_id=data["modrinth_id"], + logs=data["logs"] if "logs" in data else [], + job_id=data["job_id"], + delimiter=data["delimiter"] if "delimiter" in data else "-", + status=data["status"], + queue_place=data["queue_place"], + ) diff --git a/api/job_processor.py b/api/job_processor.py new file mode 100644 index 0000000..d99a828 --- /dev/null +++ b/api/job_processor.py @@ -0,0 +1,61 @@ +"""Does the actual work behind the scenes""" +from os import environ as env +from time import sleep + +from db import Job, JobDb, Status +from processor import download, upload + + +def resume(job_db: JobDb): + """Resumes processing jobs on server restart""" + print("Resuming jobs from last run") + + for job in job_db.get_active_jobs(): + sleep(1) + job: Job = job_db.get_next_job() + if not job: + sleep(5) + continue + job_db.update_job_status(job.job_id, Status.PROCESSING) + logs = download(job.curseforge_slug) + job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(logs)) + logs += upload( + job.github_pat, + job.curseforge_slug, + job.modrinth_id, + job.delimiter, + ) + job_db.update_job_status(job.job_id, Status.COMPLETED, "\n".join(logs)) + + +def work(job_db: JobDb) -> bool: + """Does the actual lifting""" + job: Job = job_db.get_next_job() + if not job: + return False + job_db.update_job_status(job.job_id, Status.PROCESSING) + logs = download(job.curseforge_slug) + job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(logs)) + logs += upload( + job.github_pat, + job.curseforge_slug, + job.modrinth_id, + job.delimiter, + ) + job_db.update_job_status(job.job_id, Status.COMPLETED, "\n".join(logs)) + return True + + +def worker(): + """A worker thread function for processing jobs in the job db""" + print("Starting the job processor") + job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) + resume(job_db) + while True: + try: + if work(job_db): + sleep(1) + else: + sleep(5) + except KeyboardInterrupt: + break diff --git a/api/requirements.txt b/api/requirements.txt index a8567e3..c0dfd7b 100644 --- a/api/requirements.txt +++ b/api/requirements.txt @@ -12,6 +12,7 @@ crontab==1.0.1 cryptography==40.0.2 decorator==5.1.1 dill==0.3.6 +dnspython==2.3.0 exceptiongroup==1.1.1 fire==0.5.0 Flask==2.2.3 @@ -33,6 +34,7 @@ platformdirs==3.2.0 progress==1.6 pycparser==2.21 pylint==2.17.2 +pymongo==4.3.3 PySocks==1.7.1 python-dotenv==1.0.0 pytoolconfig==1.2.5