Management API and tools

This commit is contained in:
oitsjustjose 2023-04-24 19:38:35 -05:00
commit 9b81a6cc8b
15 changed files with 222 additions and 149 deletions

View file

@ -8,44 +8,45 @@ from time import sleep
from common import Job, Status
from curse_downloader import CurseDownloader
from job_database import JobDb
from mgmt_tools import MgmtApiHelper
from modrinth_uploader import ModrinthUploader
def _process(job_db: JobDb, job: Job):
def _process(helper: MgmtApiHelper, job: Job):
"""Handles the download and upload process for a single job"""
job_db.update_job_status(job.job_id, Status.PROCESSING)
helper.update_job_status(job.job_id, Status.PROCESSING)
downloader = CurseDownloader(job_db, job)
downloader = CurseDownloader(helper, job)
dls = downloader.download()
if dls == Status.FAIL:
job_db.update_job_status(job.job_id, Status.COMPLETE)
job_db.append_job_log(job.job_id, "***FAILED***")
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, "***FAILED***")
return
uploader = ModrinthUploader(job_db, job)
uploader = ModrinthUploader(helper, job)
uls = uploader.upload()
stat = Status(max(dls.value, uls.value)).name
job_db.update_job_status(job.job_id, Status.COMPLETE)
job_db.append_job_log(job.job_id, f"***{stat}***")
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, f"***{stat}***")
def _resume(job_db: JobDb):
def _resume(helper: MgmtApiHelper):
"""Resumes processing jobs on server restart"""
print("Resuming jobs from last run")
for job in job_db.get_active_jobs():
for job in helper.get_resumable_jobs():
print(f"Resuming job {job.job_id}")
_process(job_db, job)
_process(helper, job)
def _work(job_db: JobDb) -> bool:
def _work(helper: MgmtApiHelper) -> bool:
"""Does the actual lifting"""
job: Job = job_db.get_next_job()
sleep(2) # Sleep to make sure DB processing is done
job: Job = helper.get_next_job()
if not job:
return False
_process(job_db, job)
_process(helper, job)
return True
@ -53,10 +54,7 @@ def main_loop():
"""The main process loop"""
print("Init DB connection")
job_db = JobDb(
env["MONGO_URI"] if "MONGO_URI" in env else "localhost",
int(env["MONGO_PORT"]) if "MONGO_PORT" in env else 27017,
)
helper = MgmtApiHelper()
print("DB Connected")
print("Starting virtual display")
@ -65,10 +63,10 @@ def main_loop():
print("Done initializing VDisplay")
print("Starting the job processor")
_resume(job_db)
_resume(helper)
while True:
try:
if _work(job_db):
if _work(helper):
sleep(1)
else:
sleep(5)

View file

@ -1,5 +1,5 @@
"""
Houses data classes
Houses commonly used dataclasses and Enums
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from dataclasses import dataclass
@ -42,23 +42,3 @@ class ModInfo:
modrinth_name: str
game_version: str # representative game ver
game_versions: List[str] # actual game vers
class DbLogger:
"""
A base class for Upload and Download that indicates how to log
Args:
db (JobDb): the job database
job_id (str): the job id for the given job
"""
def __init__(self, db, job_id: str):
self._db = db
self._job_id = job_id
def logmsg(self, msg: str) -> None:
"""
Logs a message to the database
Args: msg(str): the message to log
"""
self._db.append_job_log(self._job_id, msg)

View file

@ -1,3 +1,7 @@
"""
Downloads mod files from Curse
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import os
from time import sleep
from typing import List
@ -9,22 +13,22 @@ from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from common import DbLogger, Job, Status
from job_database import JobDb
from common import Job, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
class CurseDownloader(DbLogger):
class CurseDownloader(MgmtApiLogger):
"""
The class for handling curse downloads
Args:
db (JobDb): the job database
helper (MgmtApiHelper): the job database
job_id (str): the job id for the given job
"""
def __init__(self, db: JobDb, job: Job):
super().__init__(db, job.job_id)
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, job.job_id)
self._slug = job.curseforge_slug
self._job_db = db
self._helper = helper
self._job_id = job.job_id
# REGION CHROME DRIVER AND OPTIONS
options = Options()
@ -50,7 +54,7 @@ class CurseDownloader(DbLogger):
def download(self) -> Status:
"""
Downloads all mod files for a given slug
Returns: (Tuple[Status, List[str]]): The status and logs, if any
Returns: (Status): The status of the download
"""
root = f"https://legacy.curseforge.com/minecraft/mc-mods/{self._slug}/files/all"
os.makedirs(f"./out/{self._slug}", exist_ok=True)

View file

@ -1,82 +0,0 @@
"""
DB Handling for Jobs
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from os import environ as env
from typing import Dict, List, Union
from cryptography.fernet import Fernet
from pymongo import ASCENDING, MongoClient
from pymongo.collection import Collection
from pymongo.database import Database
from common import Job, Status
class JobDb:
"""A database for the job queue"""
def __init__(self, host: str = "", port: int = 0):
self._client: MongoClient = MongoClient(host or "localhost", port or 27017)
self._db: Database = self._client["ctmmm"]
self._coll: Collection = self._db["jobs"]
self._fernet = Fernet(env["SECRET"])
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": Status.ENQUEUED.value})
.sort("queuePlace", ASCENDING)
.limit(1)
)
if data:
return self._dict_to_job(data[0])
return None
def get_active_jobs(self) -> List[Job]:
"""Gets all active jobs - only used for resuming between restarts"""
data: List[Union[dict, None]] = list(
self._coll.find({"status": Status.PROCESSING.value}).sort(
"queuePlace", ASCENDING
)
)
return [self._dict_to_job(x) for x in data]
def update_job_status(self, job_id: str, status: Status) -> None:
"""Updates the status of a job, and logs, if applicable"""
self._coll.update_one({"jobId": job_id}, {"$set": {"status": status.value}})
def append_job_log(self, job_id: str, newlog: str) -> None:
"""Updates the status of a job, and logs, if applicable"""
job = self._coll.find_one({"jobId": job_id})
self._coll.update_one(
{"jobId": job_id}, {"$set": {"logs": f"{newlog}\n{job['logs']}"}}
)
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,
"curseforgeSlug": slug,
"modrinthId": proj_id,
}
)
print(data)
if not data:
return None
return data["jobId"]
def _dict_to_job(self, data: Dict) -> Job:
"""Converts a dictionary (from mongo) into a Job"""
return Job(
github_pat=self._fernet.decrypt(data["githubPat"]),
curseforge_slug=data["curseforgeSlug"],
modrinth_id=data["modrinthId"],
logs=data["logs"] if "logs" in data else [],
job_id=data["jobId"],
delimiter=data["delimiter"] if "delimiter" in data else "-",
status=data["status"],
queue_place=data["queuePlace"],
)

View file

@ -0,0 +1,93 @@
"""
Houses API Tools when communicating with the RESTful API
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from os import environ as env
from typing import Dict, List, Union
import requests
from cryptography.fernet import Fernet
from common import Job, Status
class MgmtApiHelper:
"""An API Helper for the Job API"""
def __init__(self):
self._mgmt_timeout = 30
self._mgmt_host = env["MGMT_HOST"]
self._mgmt_key = env["MGMT_KEY"]
self._fernet = Fernet(env["SECRET"])
# REGION NON JOB-SPECIFIC METHODS
def get_next_job(self) -> Union[Job, None]:
"""Gets the next job to do, if any"""
resp = requests.get(
f"{self._mgmt_host}/api/v1/mgmt/dequeue?mgmtKey={self._mgmt_key}",
timeout=self._mgmt_timeout,
)
# 404 response is for if there's nothing to dequeue
if resp.status_code == 404:
return None
return self._dict_to_job(resp.json())
def get_resumable_jobs(self) -> List[Job]:
"""Gets all active jobs - only used for resuming between restarts"""
resp = requests.get(
f"{self._mgmt_host}/api/v1/mgmt/resumable?mgmtKey={self._mgmt_key}",
timeout=self._mgmt_timeout,
)
return [self._dict_to_job(x) for x in resp.json()]
def _dict_to_job(self, data: Dict) -> Job:
"""Converts a dictionary (from mongo) into a Job"""
return Job(
github_pat=self._fernet.decrypt(data["githubPat"]),
curseforge_slug=data["curseforgeSlug"],
modrinth_id=data["modrinthId"],
logs=data["logs"] if "logs" in data else [],
job_id=data["jobId"],
delimiter=data["delimiter"] if "delimiter" in data else "-",
status=data["status"],
queue_place=data["queuePlace"],
)
# ENDREGION NON JOB-SPECIFIC METHODS
def update_job_status(self, job_id: str, status: Status) -> None:
"""Updates the status of a job"""
requests.patch(
f"{self._mgmt_host}/api/v1/mgmt/update/{job_id}?mgmtKey={self._mgmt_key}",
timeout=self._mgmt_timeout,
data={"status": status.value},
)
def append_job_log(self, job_id: str, newlog: str) -> None:
"""Appends to the logs for a job"""
requests.patch(
f"{self._mgmt_host}/api/v1/mgmt/update/{job_id}?mgmtKey={self._mgmt_key}",
timeout=self._mgmt_timeout,
data={"log": newlog},
)
class MgmtApiLogger:
"""
A base class for Upload and Download that indicates how to log via API
Args:
helper (MgmtApiHelper): the job api controller
job_id (str): the job id for the given job
"""
def __init__(self, helper: MgmtApiHelper, job_id: str):
self.helper = helper
self._job_id = job_id
def logmsg(self, msg: str) -> None:
"""
Logs a message to the database
Args: msg(str): the message to log
"""
self.helper.append_job_log(self._job_id, msg)

View file

@ -1,5 +1,5 @@
"""
Performs upload/download operations
Uploads mod files to Modrinth
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import json
@ -9,13 +9,20 @@ from typing import List, Union
import requests
from common import DbLogger, Job, ModInfo, Status
from job_database import JobDb
from common import Job, ModInfo, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
class ModrinthUploader(DbLogger):
def __init__(self, job_db: JobDb, job: Job):
super().__init__(job_db, job.job_id)
class ModrinthUploader(MgmtApiLogger):
"""
Handles uploading jar files to Modrinth
Args:
helper (MgmtApiHelper): the current mongo instance for the Job DB
job (Job): the job to process
"""
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, job.job_id)
self._job = job
def __get_versions(self, parts: List[str]) -> List[str]:
@ -81,8 +88,8 @@ class ModrinthUploader(DbLogger):
payload = json.dumps(
{
"name": mod_info.name,
"version_number": mod_info.modrinth_name,
"name": mod_info.modrinth_name,
"version_number": mod_info.mod_version,
"changelog": "Migrated Automagically from CurseForge",
"dependencies": [],
"game_versions": mod_info.game_versions,
@ -114,7 +121,7 @@ class ModrinthUploader(DbLogger):
statuses.append(Status.SUCCESS)
else:
statuses.append(Status.FAIL)
self.logmsg("----- FILE {fpath} -----")
self.logmsg(f"----- FILE {fpath} -----")
self.logmsg(f"API Response from Modrinth FAIL for {fpath}:")
if response.text: # Add text if exists
self.logmsg(response.text)
@ -131,5 +138,5 @@ class ModrinthUploader(DbLogger):
if any_succ and not any_fail
else Status.FAIL
)
rmtree(f"./out/{self._job.github_pat}")
rmtree(f"./out/{self._job.curseforge_slug}")
return status