1
0
Fork 0
onnx-web/api/onnx_web/worker/worker.py

79 lines
2.4 KiB
Python
Raw Normal View History

2023-02-26 05:49:39 +00:00
from logging import getLogger
2023-03-06 03:37:39 +00:00
from os import getpid
2023-03-07 14:02:53 +00:00
from queue import Empty
2023-02-28 04:52:43 +00:00
from sys import exit
2023-02-26 20:15:30 +00:00
2023-02-26 19:09:24 +00:00
from setproctitle import setproctitle
2023-02-26 05:49:39 +00:00
2023-02-26 18:32:48 +00:00
from ..server import ServerContext, apply_patches
2023-02-26 21:21:58 +00:00
from ..torch_before_ort import get_available_providers
2023-02-26 20:15:30 +00:00
from .context import WorkerContext
2023-02-26 05:49:39 +00:00
logger = getLogger(__name__)
2023-03-06 03:37:39 +00:00
EXIT_ERROR = 1
EXIT_INTERRUPT = 0
EXIT_MEMORY = 2
EXIT_REPLACED = 3
EXIT_SUCCESS = 0
2023-02-26 18:32:48 +00:00
def worker_main(context: WorkerContext, server: ServerContext):
2023-02-26 18:32:48 +00:00
apply_patches(server)
2023-02-26 20:15:30 +00:00
setproctitle("onnx-web worker: %s" % (context.device.device))
2023-02-26 18:32:48 +00:00
logger.trace(
"checking in from worker with providers: %s", get_available_providers()
)
# make leaking workers easier to recycle
context.progress.cancel_join_thread()
2023-02-26 05:49:39 +00:00
while True:
2023-02-27 02:09:42 +00:00
try:
if not context.is_active():
2023-03-07 14:02:53 +00:00
logger.warning(
"worker %s has been replaced by %s, exiting",
getpid(),
context.get_active(),
2023-03-07 14:02:53 +00:00
)
2023-03-06 03:37:39 +00:00
exit(EXIT_REPLACED)
# wait briefly for the next job
job = context.pending.get(timeout=1.0)
logger.info("worker %s got job: %s", context.device.device, job.name)
2023-02-28 04:45:29 +00:00
# clear flags and save the job name
context.start(job.name)
logger.info("starting job: %s", job.name)
# reset progress, which does a final check for cancellation
context.set_progress(0)
job.fn(context, *job.args, **job.kwargs)
# confirm completion of the job
logger.info("job succeeded: %s", job.name)
context.finish()
2023-02-28 04:37:43 +00:00
except Empty:
pass
2023-02-28 04:52:43 +00:00
except KeyboardInterrupt:
2023-02-28 05:12:53 +00:00
logger.info("worker got keyboard interrupt")
context.fail()
2023-03-06 03:37:39 +00:00
exit(EXIT_INTERRUPT)
except ValueError:
logger.exception("value error in worker, exiting: %s")
context.fail()
2023-03-06 03:37:39 +00:00
exit(EXIT_ERROR)
2023-02-26 17:16:33 +00:00
except Exception as e:
e_str = str(e)
if "Failed to allocate memory" in e_str or "out of memory" in e_str:
logger.error("detected out-of-memory error, exiting: %s", e)
context.fail()
2023-03-06 03:37:39 +00:00
exit(EXIT_MEMORY)
else:
2023-03-17 03:29:07 +00:00
logger.exception(
"error while running job",
)
context.fail()
# carry on