"""Handle jobs""" import os import shlex import subprocess from uuid import uuid4 from datetime import timedelta from redis import Redis def error_filename(job_id, error_dir): "Compute the path of the file where errors will be dumped." return f"{error_dir}/job_{job_id}.error" def build_file_verification_job( redis_conn: Redis, filepath: str, filetype: str, redisurl: str, ttl_seconds: int): "Build a file verification job" job_id = str(uuid4()) command = [ "python3", "-m", "scripts.validate_file", filetype, filepath, redisurl, job_id ] the_job = { "job_id": job_id, "command": shlex.join(command), "status": "pending", "filename": os.path.basename(filepath), "percent": 0, "filetype": filetype, "job-type": "file-verification" } redis_conn.hset(name=the_job["job_id"], mapping=the_job) redis_conn.expire(name=the_job["job_id"], time=timedelta(seconds=ttl_seconds)) return the_job def launch_job(the_job: dict, redisurl: str, error_dir): """Launch a job in the background""" if not os.path.exists(error_dir): os.mkdir(error_dir) job_id = the_job["job_id"] with open(error_filename(job_id, error_dir), "w", encoding="utf-8") as errorfile: subprocess.Popen( # pylint: disable=[consider-using-with] ["python3", "-m", "scripts.worker", redisurl, job_id], stderr=errorfile) return the_job def job(redis_conn, job_id: str): "Retrieve the job" return redis_conn.hgetall(job_id)