""" Task lock ========= This is an implementation of cache locking for tasks that need to be run in blocking fashion. Ex: As a cron that should not start again while still running. """ from dogpile.cache.api import NO_VALUE from hashlib import md5 from labelaudit import config from labelaudit.connectors import cache class TaskLock: def __init__(self, task_name): task_hexdigest = md5(task_name.encode('utf-8')).hexdigest() # The cache key consists of the fully qualified task name and the # MD5 digest of the task name. self.lock_id = '{}-{}-lock-{}'.format( config.ENVIRONMENT, task_name, task_hexdigest) def acquire_task(self): """See if task can be acquired, or if it's already locked. If task is available, lock it, and return True. Return: boolean (True if task is available and False if it is not.) """ if cache.region.get(self.lock_id) == NO_VALUE: cache.region.set(self.lock_id, 'locked') return True return False def delete(self): """Delete the cache lock. This operation is idempotent (can be called multiple times, or on a non-existent key, safely). """ return cache.region.delete(self.lock_id)