2018-02-05 14:58:02 +00:00
|
|
|
import time
|
|
|
|
|
|
2017-08-31 12:52:06 +01:00
|
|
|
from celery import Celery, Task
|
2018-07-12 15:09:38 +01:00
|
|
|
from celery.signals import worker_process_shutdown
|
|
|
|
|
from flask import current_app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@worker_process_shutdown.connect
|
|
|
|
|
def worker_process_shutdown(sender, signal, pid, exitcode, **kwargs):
|
|
|
|
|
current_app.logger.info('worker shutdown: PID: {} Exitcode: {}'.format(pid, exitcode))
|
2017-08-31 12:52:06 +01:00
|
|
|
|
|
|
|
|
|
2018-02-12 15:29:03 +00:00
|
|
|
def make_task(app):
|
|
|
|
|
class NotifyTask(Task):
|
|
|
|
|
abstract = True
|
|
|
|
|
start = None
|
2018-02-05 14:58:02 +00:00
|
|
|
|
2018-02-12 15:29:03 +00:00
|
|
|
def on_success(self, retval, task_id, args, kwargs):
|
|
|
|
|
elapsed_time = time.time() - self.start
|
|
|
|
|
app.logger.info(
|
|
|
|
|
"{task_name} took {time}".format(
|
|
|
|
|
task_name=self.name, time="{0:.4f}".format(elapsed_time)
|
|
|
|
|
)
|
2018-02-05 14:58:02 +00:00
|
|
|
)
|
2017-08-31 12:52:06 +01:00
|
|
|
|
2018-02-12 15:29:03 +00:00
|
|
|
def on_failure(self, exc, task_id, args, kwargs, einfo):
|
|
|
|
|
# ensure task will log exceptions to correct handlers
|
2018-02-22 15:05:37 +00:00
|
|
|
app.logger.exception('Celery task: {} failed'.format(self.name))
|
2018-02-12 15:29:03 +00:00
|
|
|
super().on_failure(exc, task_id, args, kwargs, einfo)
|
|
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
|
# ensure task has flask context to access config, logger, etc
|
|
|
|
|
with app.app_context():
|
|
|
|
|
self.start = time.time()
|
|
|
|
|
return super().__call__(*args, **kwargs)
|
2017-08-31 12:52:06 +01:00
|
|
|
|
2018-02-12 15:29:03 +00:00
|
|
|
return NotifyTask
|
2017-06-01 14:32:19 +01:00
|
|
|
|
2016-02-09 13:31:45 +00:00
|
|
|
|
|
|
|
|
class NotifyCelery(Celery):
|
2017-06-09 16:20:02 +01:00
|
|
|
|
2017-07-19 13:50:29 +01:00
|
|
|
def init_app(self, app):
|
2017-08-31 12:52:06 +01:00
|
|
|
super().__init__(
|
|
|
|
|
app.import_name,
|
|
|
|
|
broker=app.config['BROKER_URL'],
|
2018-02-12 15:29:03 +00:00
|
|
|
task_cls=make_task(app),
|
2017-08-31 12:52:06 +01:00
|
|
|
)
|
2016-02-09 13:31:45 +00:00
|
|
|
|
2017-08-31 12:52:06 +01:00
|
|
|
self.conf.update(app.config)
|