From c1f174294845db115743296e922d495b56a65e93 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sat, 22 Apr 2023 22:27:30 -0500 Subject: [PATCH] Interim headless docker commit \o/ --- api/.dockerignore | 9 +++ api/Dockerfile | 33 ++++++++++ api/requirements.txt | 1 + api/src/__api__.py | 66 ++++++++++++++++++++ api/src/__main__.py | 125 ++++++++++++++++++++----------------- api/src/job_processor.py | 80 ------------------------ api/src/netio_processor.py | 8 ++- 7 files changed, 182 insertions(+), 140 deletions(-) create mode 100644 api/.dockerignore create mode 100644 api/Dockerfile create mode 100644 api/src/__api__.py delete mode 100644 api/src/job_processor.py diff --git a/api/.dockerignore b/api/.dockerignore new file mode 100644 index 0000000..c017e38 --- /dev/null +++ b/api/.dockerignore @@ -0,0 +1,9 @@ +/out/ +/lib/ +/lib64 +/bin/ + +state.dat +filekey.key +__pycache__ +.envrc \ No newline at end of file diff --git a/api/Dockerfile b/api/Dockerfile new file mode 100644 index 0000000..7f3073f --- /dev/null +++ b/api/Dockerfile @@ -0,0 +1,33 @@ +FROM python:3.10-buster + +RUN apt-get update && apt-get upgrade -y +RUN apt-get install -y libasound2 \ + libnspr4 \ + libnss3 \ + libxss1 \ + xdg-utils \ + unzip \ + libappindicator1 \ + fonts-liberation \ + xvfb \ + libatk-bridge2.0-0 \ + libatspi2.0-0 \ + libgbm1 \ + libgtk-3-0 \ + libu2f-udev \ + libvulkan1 \ + libxkbcommon0 +RUN apt-get -f install +RUN wget http://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb +RUN dpkg -i google-chrome*.deb && rm google-chrome*.deb + +# Patch to make XVFB actually work +RUN mkdir /tmp/.X11-unix +RUN chmod 1777 /tmp/.X11-unix +RUN chown root /tmp/.X11-unix/ + +COPY . . + +RUN pip install -r requirements.txt + +CMD ["python", "src/__main__.py"] \ No newline at end of file diff --git a/api/requirements.txt b/api/requirements.txt index c0dfd7b..ebf9767 100644 --- a/api/requirements.txt +++ b/api/requirements.txt @@ -38,6 +38,7 @@ pymongo==4.3.3 PySocks==1.7.1 python-dotenv==1.0.0 pytoolconfig==1.2.5 +PyVirtualDisplay==3.0 requests==2.28.2 rope==1.7.0 selenium==4.8.3 diff --git a/api/src/__api__.py b/api/src/__api__.py new file mode 100644 index 0000000..64c6d9d --- /dev/null +++ b/api/src/__api__.py @@ -0,0 +1,66 @@ +""" +The API endpoints for the proessor +Author: oitsjustjose @ modrinth/curseforge/twitter +""" + +import json +from dataclasses import asdict +from multiprocessing import Process +from os import environ as env + +from flask import Flask, request + +from data import Status +from job_database import Job, JobDb, Status + +app = Flask(__name__) + +db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) + + +@app.route("/jobs/status/", methods=["GET", "POST"]) +def get_job_status(job_id: str) -> str: + "Gets the queue status for a given job" + + 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.COMPLETE: + return logs, 200 + return "Failed to find job", 404 + + +@app.route("/jobs/info/", methods=["GET", "POST"]) +def get_job_info(job_id: str): + """Gets the job info for a given uuid""" + 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"]) +def new_job(): + """Creates a new job""" + try: + data = json.loads(request.data) + jobe = Job( + github_pat=data["githubPat"], + curseforge_slug=data["slug"], + modrinth_id=data["projId"], + delimiter=data["delimiter"] if "delimiter" in data else "-", + ) + + # 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 + + +app.run("0.0.0.0", env["PORT"] if "PORT" in env else 3000) diff --git a/api/src/__main__.py b/api/src/__main__.py index c4cfe88..e1bd073 100644 --- a/api/src/__main__.py +++ b/api/src/__main__.py @@ -1,72 +1,79 @@ """ -The API endpoints for the proessor +Does the actual work behind the scenes Author: oitsjustjose @ modrinth/curseforge/twitter """ - -import json -from dataclasses import asdict -from multiprocessing import Process from os import environ as env +from time import sleep -from flask import Flask, request - -from data import Status -from job_database import Job, JobDb, Status -from job_processor import worker - -app = Flask(__name__) - -db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) +from data import Job, Status +from job_database import JobDb +from netio_processor import download, upload -@app.route("/jobs/status/", methods=["GET", "POST"]) -def get_job_status(job_id: str) -> str: - "Gets the queue status for a given job" +def _resume(job_db: JobDb): + """Resumes processing jobs on server restart""" + print("Resuming jobs from last run") - 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.COMPLETE: - return logs, 200 - return "Failed to find job", 404 - - -@app.route("/jobs/info/", methods=["GET", "POST"]) -def get_job_info(job_id: str): - """Gets the job info for a given uuid""" - 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"]) -def new_job(): - """Creates a new job""" - try: - data = json.loads(request.data) - jobe = Job( - github_pat=data["githubPat"], - curseforge_slug=data["slug"], - modrinth_id=data["projId"], - delimiter=data["delimiter"] if "delimiter" in data else "-", + for job in job_db.get_active_jobs(): + print(f"Resuming job {job.job_id}") + job_db.update_job_status(job.job_id, Status.PROCESSING) + dl_status, dl_logs = download(job.curseforge_slug) + if dl_status == Status.FAIL: # Failed - early exit, update DB for user + job_db.update_job_status( + job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs) + ) + continue + # Didn't fail, update DB with latest logs and same status + job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs)) + ul_status, ul_logs = upload( + job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter + ) + # Take the higher severity - it would only be + text_status = Status(max(dl_status.value, ul_status.value)).name + job_db.update_job_status( + job.job_id, + Status.COMPLETE, + "\n".join([f"**{text_status}**"] + ul_logs + dl_logs), ) - # 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 + +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) + dl_status, dl_logs = download(job.curseforge_slug) + if dl_status == Status.FAIL: # Failed - early exit, update DB for user + job_db.update_job_status( + job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs) + ) + return True + # Didn't fail, update DB with latest logs and same status + job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs)) + ul_status, ul_logs = upload( + job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter + ) + # Take the higher severity - it would only be + text_status = Status(max(dl_status.value, ul_status.value)).name + job_db.update_job_status( + job.job_id, + Status.COMPLETE, + "\n".join([f"**{text_status}**"] + ul_logs + dl_logs), + ) + return True 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] + 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/src/job_processor.py b/api/src/job_processor.py deleted file mode 100644 index ae27c82..0000000 --- a/api/src/job_processor.py +++ /dev/null @@ -1,80 +0,0 @@ -""" -Does the actual work behind the scenes -Author: oitsjustjose @ modrinth/curseforge/twitter -""" -from os import environ as env -from time import sleep - -from data import Job, Status -from job_database import JobDb -from netio_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(): - print(f"Resuming job {job.job_id}") - job_db.update_job_status(job.job_id, Status.PROCESSING) - dl_status, dl_logs = download(job.curseforge_slug) - if dl_status == Status.FAIL: # Failed - early exit, update DB for user - job_db.update_job_status( - job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs) - ) - continue - # Didn't fail, update DB with latest logs and same status - job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs)) - ul_status, ul_logs = upload( - job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter - ) - # Take the higher severity - it would only be - text_status = Status(max(dl_status.value, ul_status.value)).name - job_db.update_job_status( - job.job_id, - Status.COMPLETE, - "\n".join([f"**{text_status}**"] + ul_logs + dl_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) - dl_status, dl_logs = download(job.curseforge_slug) - if dl_status == Status.FAIL: # Failed - early exit, update DB for user - job_db.update_job_status( - job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs) - ) - return True - # Didn't fail, update DB with latest logs and same status - job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs)) - ul_status, ul_logs = upload( - job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter - ) - # Take the higher severity - it would only be - text_status = Status(max(dl_status.value, ul_status.value)).name - job_db.update_job_status( - job.job_id, - Status.COMPLETE, - "\n".join([f"**{text_status}**"] + ul_logs + dl_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/src/netio_processor.py b/api/src/netio_processor.py index c502272..7b89089 100644 --- a/api/src/netio_processor.py +++ b/api/src/netio_processor.py @@ -15,7 +15,7 @@ from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager - +from pyvirtualdisplay import Display from data import ModInfo, Status @@ -239,7 +239,11 @@ def download(slug: str) -> Tuple[Status, List[str]]: os.makedirs(f"./out/{slug}", exist_ok=True) # REGION CHROME DRIVER AND OPTIONS + display = Display(visible=0, size=(1366, 768)) + display.start() + options = Options() + options.add_argument("--no-sandbox") options.add_argument("--ignore-ssl-errors=yes") options.add_argument("--ignore-certificate-errors") options.add_experimental_option("excludeSwitches", ["enable-logging"]) @@ -276,4 +280,6 @@ def download(slug: str) -> Tuple[Status, List[str]]: else Status.FAIL ) + display.stop() + driver.close() return status, logs