media-sucker/src/worker.py

56 lines
1.5 KiB
Python
Raw Permalink Normal View History

2022-08-25 10:17:25 -06:00
import threading
import os
import json
2022-08-25 10:17:25 -06:00
import logging
2022-09-02 17:04:07 -06:00
import time
import traceback
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
2022-08-25 10:17:25 -06:00
class Worker(threading.Thread):
def __init__(self, directory, **kwargs):
self.directory = directory
2022-09-02 17:04:07 -06:00
self.loop_delay = 2 * SECOND
self.status = {}
2022-08-25 10:17:25 -06:00
kwargs["daemon"] = True
return super().__init__(**kwargs)
2022-09-02 17:04:07 -06:00
def run(self):
while True:
self.status = {"state": "idle"}
try:
self.once()
except Exception as exc:
self.status["state"] = "error"
for line in traceback.format_exception(exc):
logging.error(line)
time.sleep(30 * SECOND)
time.sleep(self.loop_delay)
2022-08-25 10:17:25 -06:00
def workdir(self, *path):
return os.path.join(self.directory, *path)
def write_state(self, subdir, state):
2022-08-25 10:17:25 -06:00
logging.debug("Writing state: %s" % repr(state))
statefn = self.workdir(subdir, "sucker.json")
newstatefn = statefn + ".new"
with open(newstatefn, "w") as f:
json.dump(state, f)
os.rename(newstatefn, statefn)
2022-08-25 10:17:25 -06:00
def read_state(self, subdir):
2022-09-02 17:04:07 -06:00
try:
with open(self.workdir(subdir, "sucker.json")) as f:
return json.load(f)
except FileNotFoundError:
return {}
2022-08-25 10:17:25 -06:00
def clear_state(self, subdir):
2022-09-02 17:04:07 -06:00
try:
os.unlink(self.workdir(subdir, "sucker.json"))
except FileNotFoundError:
pass