Created
February 18, 2016 08:23
-
-
Save ranedk/e4c82e700de2eb21c14d to your computer and use it in GitHub Desktop.
Managing locks using pg_advisory_locks in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def lock_name_to_int(lock_name): | |
"""converts lock_name into integer | |
This is needed to create a pg_advisory_lock | |
Can return negative values, but is acceptable | |
""" | |
return lock_name.__hash__() | |
def acquire_exclusive_lock(lock_name, log_after_seconds=1): | |
cursor = connection.cursor() | |
lock_id = lock_name_to_int(lock_name) | |
command = "select pg_advisory_lock(%d)" % lock_id | |
start = time.time() | |
cursor.execute(command) | |
acquire = cursor.fetchone()[0] | |
time_taken = time.time() - start | |
if time_taken > log_after_seconds: | |
extlogger.info("ERROR: lock %s - %s getting released in %s seconds (more than %s seconds)" % ( | |
lock_name, lock_id, time_taken, log_after_seconds | |
)) | |
print "ERROR: lock %s - %s getting released in %s seconds (more than %s seconds)" % ( | |
lock_name, lock_id, time_taken, log_after_seconds | |
) | |
return acquire | |
def release_exclusive_lock(lock_name): | |
cursor = connection.cursor() | |
lock_id = lock_name_to_int(lock_name) | |
command = "select pg_advisory_unlock(%d)" % lock_id | |
cursor.execute(command) | |
release = cursor.fetchone()[0] | |
if not release: | |
raise Exception("Not able to release lock %s - %s" % (lock_name, lock_id)) | |
return release |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment