1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
|
"""
lock
~~~~
A generic lock.
"""
from __future__ import annotations
import datetime
import importlib
import json
import pathlib
import re
import time
import typing
import uuid
if typing.TYPE_CHECKING:
import etcd
import filelock
import kubernetes
__all__ = [
"Lock",
"LockException",
"LockTimeoutException",
"RedisLock",
"EtcdLock",
"MCLock",
"KubernetesLock",
"FileLock",
]
class LockException(Exception):
"""
Generic exception for Locks.
"""
pass
class LockTimeoutException(Exception):
"""
Raised whenever timeout occurs while trying to acquire lock.
"""
pass
class BaseLock(object):
"""
Interface for implementing custom Lock implementations. This class must be
sub-classed in order to implement a custom Lock with custom logic or
different backend or both.
Basic Usage (an example of our imaginary datastore)
>>> class MyLock(BaseLock):
... def __init__(self, lock_name, **kwargs):
... super(MyLock, self).__init__(lock_name, **kwargs)
... if self.client is None:
... self.client = mybackend.Client(host='localhost', port=1234)
... self._owner = None
...
... def _acquire(self):
... if self.client.get(self.lock_name) is not None:
... owner = str(uuid.uuid4()) # or anythin you want
... self.client.set(self.lock_name, owner)
... self._owner = owner
... if self.expire is not None:
... self.client.expire(self.lock_name, self.expire)
... return True
... return False
...
... def _release(self):
... if self._owner is not None:
... lock_val = self.client.get(self.lock_name)
... if lock_val == self._owner:
... self.client.delete(self.lock_name)
...
... def _locked(self):
... if self.client.get(self.lock_name) is not None:
... return True
... return False
"""
def __init__(self, lock_name, **kwargs):
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Optional namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
# Lazy to avoid circular
from . import _configuration
self.lock_name = lock_name
if kwargs.get("namespace"):
self.namespace = kwargs["namespace"]
else:
self.namespace = _configuration.namespace
if "expire" in kwargs:
self.expire = kwargs["expire"]
else:
self.expire = _configuration.expire
if "timeout" in kwargs:
self.timeout = kwargs["timeout"]
else:
self.timeout = _configuration.timeout
if "retry_interval" in kwargs:
self.retry_interval = kwargs["retry_interval"]
else:
self.retry_interval = _configuration.retry_interval
if kwargs.get("client"):
self.client = kwargs["client"]
else:
self.client = None
@property
def _locked(self):
"""
Implementation of method to check if lock has been acquired. Must be
implemented in the sub-class.
:returns: if the lock is acquired or not
:rtype: bool
"""
raise NotImplementedError("Must be implemented in the sub-class.")
def locked(self):
"""
Return if the lock has been acquired or not.
:returns: True indicating that a lock has been acquired ot a
shared resource is locked.
:rtype: bool
"""
return self._locked
def _acquire(self):
"""
Implementation of acquiring a lock in a non-blocking fashion. Must be
implemented in the sub-class. :meth:`acquire` makes use of this
implementation to provide blocking and non-blocking implementations.
:returns: if the lock was successfully acquired or not
:rtype: bool
"""
raise NotImplementedError("Must be implemented in the sub-class.")
def acquire(self, blocking=True):
"""
Acquire a lock, blocking or non-blocking.
:param bool blocking: acquire a lock in a blocking or non-blocking
fashion. Defaults to True.
:returns: if the lock was successfully acquired or not
:rtype: bool
"""
if blocking is True:
timeout = self.timeout
while timeout >= 0:
if self._acquire() is not True:
timeout -= self.retry_interval
if timeout > 0:
time.sleep(self.retry_interval)
else:
return True
raise LockTimeoutException(
"Timeout elapsed after %s seconds "
"while trying to acquiring "
"lock." % self.timeout
)
else:
return self._acquire()
def _release(self):
"""
Implementation of releasing an acquired lock. Must be implemented in
the sub-class.
"""
raise NotImplementedError("Must be implemented in the sub-class.")
def release(self):
"""
Release a lock.
"""
return self._release()
def _renew(self) -> bool:
"""
Implementation of renewing an acquired lock. Must be implemented in
the sub-class.
"""
raise NotImplementedError("Must be implemented in the sub-class")
def renew(self) -> bool:
"""
Renew a lock that is already acquired.
"""
return self._renew()
def __enter__(self):
self.acquire()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.release()
def __del__(self):
try:
self.release()
except LockException:
pass
class Lock(BaseLock):
"""
A general lock that inherits global coniguration and provides locks with
the configured backend.
.. note:: to use :class:`Lock` class, you must configure the global backend
to use a particular backend. If the global backend is not set,
calling any method on instances of :class:`Lock` will throw
exceptions.
Basic Usage:
>>> import sherlock
>>> from sherlock import Lock
>>>
>>> sherlock.configure(sherlock.backends.REDIS)
>>>
>>> # Create a lock instance
>>> lock = Lock('my_lock')
>>>
>>> # Acquire a lock in Redis running on localhost
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> import redis
>>> redis_client = redis.StrictRedis(host='X.X.X.X', port=6379, db=2)
>>> sherlock.configure(client=redis_client)
>>>
>>> # Acquire a lock in Redis running on X.X.X.X:6379
>>> lock.acquire()
>>>
>>> lock.locked()
True
>>>
>>> # Acquire a lock using the with_statement
>>> with Lock('my_lock') as lock:
... # do some stuff with your acquired resource
... pass
"""
def __init__(self, lock_name, **kwargs):
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Optional namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
.. Note:: this Lock object does not accept a custom lock backend store
client object. It instead uses the global custom client
object.
"""
# Lazy to avoid circular
from . import _configuration
# Raise exception if client keyword argument is found
if "client" in kwargs:
raise TypeError("Lock object does not accept a custom client " "object")
super(Lock, self).__init__(lock_name, **kwargs)
try:
self.client = _configuration.client
except ValueError:
pass
if self.client is None:
self._lock_proxy = None
else:
kwargs.update(client=_configuration.client)
try:
self._lock_proxy = globals()[_configuration.backend["lock_class"]](
lock_name, **kwargs
)
except KeyError:
self._lock_proxy = _configuration.backend["lock_class"](
lock_name, **kwargs
)
def _acquire(self):
if self._lock_proxy is None:
raise LockException(
"Lock backend has not been configured and "
"lock cannot be acquired or released. "
"Configure lock backend first."
)
return self._lock_proxy.acquire(False)
def _release(self):
if self._lock_proxy is None:
raise LockException(
"Lock backend has not been configured and "
"lock cannot be acquired or released. "
"Configure lock backend first."
)
return self._lock_proxy.release()
def _renew(self) -> bool:
if self._lock_proxy is None:
raise LockException(
"Lock backend has not been configured and "
"lock cannot be acquired or released. "
"Configure lock backend first."
)
return self._lock_proxy.renew()
@property
def _locked(self):
if self._lock_proxy is None:
raise LockException(
"Lock backend has not been configured and "
"lock cannot be acquired or released. "
"Configure lock backend first."
)
return self._lock_proxy.locked()
class RedisLock(BaseLock):
"""
Implementation of lock with Redis as the backend for synchronization.
Basic Usage:
>>> import redis
>>> import sherlock
>>> from sherlock import RedisLock
>>>
>>> # Global configuration of defaults
>>> sherlock.configure(expire=120, timeout=20)
>>>
>>> # Create a lock instance
>>> lock = RedisLock('my_lock')
>>>
>>> # Acquire a lock in Redis, global backend and client configuration need
>>> # not be configured since we are using a backend specific lock.
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> # Use this client object
>>> client = redis.StrictRedis()
>>>
>>> # Create a lock instance with custom client object
>>> lock = RedisLock('my_lock', client=client)
>>>
>>> # To override the defaults, just past the configurations as parameters
>>> lock = RedisLock('my_lock', client=client, expire=1, timeout=5)
>>>
>>> # Acquire a lock using the with_statement
>>> with RedisLock('my_lock') as lock:
... # do some stuff with your acquired resource
... pass
"""
_acquire_script = """
local result = redis.call('SETNX', KEYS[1], ARGV[1])
if result == 1 and ARGV[2] ~= -1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
return result
"""
_release_script = """
local result = 0
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('DEL', KEYS[1])
result = 1
end
return result
"""
_renew_script = """
local result = 0
if redis.call('GET', KEYS[1]) == ARGV[1] then
if ARGV[2] ~= -1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
else
redis.call('PERSIST', KEYS[1])
end
result = 1
end
return result
"""
def __init__(self, lock_name, **kwargs):
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Optional namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
try:
import redis
except ImportError as exc:
raise ImportError("Please install `sherlock` with `redis` extras.") from exc
super(RedisLock, self).__init__(lock_name, **kwargs)
if self.client is None:
self.client = redis.StrictRedis(host="localhost", port=6379, db=0)
self._owner = None
# Register Lua script
self._acquire_func = self.client.register_script(self._acquire_script)
self._release_func = self.client.register_script(self._release_script)
self._renew_func = self.client.register_script(self._renew_script)
@property
def _key_name(self):
if self.namespace is not None:
key = "%s_%s" % (self.namespace, self.lock_name)
else:
key = self.lock_name
return key
def _acquire(self):
owner = str(uuid.uuid4())
if self.expire is None:
expire = -1
else:
expire = self.expire
if self._acquire_func(keys=[self._key_name], args=[owner, expire]) != 1:
return False
self._owner = owner
return True
def _release(self):
if self._owner is None:
raise LockException("Lock was not set by this process.")
if self._release_func(keys=[self._key_name], args=[self._owner]) != 1:
raise LockException(
"Lock could not be released because it was "
"not acquired by this instance."
)
self._owner = None
def _renew(self) -> bool:
if self._owner is None:
raise LockException("Lock was not set by this process.")
if (
self._renew_func(keys=[self._key_name], args=[self._owner, self.expire])
!= 1
):
return False
return True
@property
def _locked(self):
if self.client.get(self._key_name) is None:
return False
return True
class EtcdLock(BaseLock):
"""
Implementation of lock with Etcd as the backend for synchronization.
Basic Usage:
>>> import etcd
>>> import sherlock
>>> from sherlock import EtcdLock
>>>
>>> # Global configuration of defaults
>>> sherlock.configure(expire=120, timeout=20)
>>>
>>> # Create a lock instance
>>> lock = EtcdLock('my_lock')
>>>
>>> # Acquire a lock in Etcd, global backend and client configuration need
>>> # not be configured since we are using a backend specific lock.
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> # Use this client object
>>> client = etcd.Client()
>>>
>>> # Create a lock instance with custom client object
>>> lock = EtcdLock('my_lock', client=client)
>>>
>>> # To override the defaults, just past the configurations as parameters
>>> lock = EtcdLock('my_lock', client=client, expire=1, timeout=5)
>>>
>>> # Acquire a lock using the with_statement
>>> with EtcdLock('my_lock') as lock:
... # do some stuff with your acquired resource
... pass
"""
def __init__(self, lock_name, **kwargs):
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Optional namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
try:
globals()["etcd"] = importlib.import_module("etcd")
except ImportError as exc:
raise ImportError("Please install `sherlock` with `etcd` extras.") from exc
super(EtcdLock, self).__init__(lock_name, **kwargs)
if self.client is None:
self.client = etcd.Client()
self._owner = None
@property
def _key_name(self):
if self.namespace is not None:
return "/%s/%s" % (self.namespace, self.lock_name)
else:
return "/%s" % self.lock_name
def _acquire(self):
owner = str(uuid.uuid4())
try:
self.client.write(self._key_name, owner, prevExist=False, ttl=self.expire)
self._owner = owner
except etcd.EtcdAlreadyExist:
return False
else:
return True
def _release(self):
if self._owner is None:
raise LockException("Lock was not set by this process.")
try:
self.client.delete(self._key_name, prevValue=self._owner)
self._owner = None
except ValueError:
raise LockException(
"Lock could not be released because it "
"was not acquired by this instance."
)
except etcd.EtcdKeyNotFound:
raise LockException(
"Lock could not be released as it has not been acquired"
)
def _renew(self) -> bool:
if self._owner is None:
raise LockException("Lock was not set by this process.")
try:
self.client.write(
self._key_name,
None,
ttl=self.expire,
prevValue=self._owner,
prevExist=True,
refresh=True,
)
return True
except (etcd.EtcdCompareFailed, etcd.EtcdKeyNotFound):
return False
@property
def _locked(self):
try:
self.client.get(self._key_name)
return True
except etcd.EtcdKeyNotFound:
return False
class MCLock(BaseLock):
"""
Implementation of lock with Memcached as the backend for synchronization.
Basic Usage:
>>> import pylibmc
>>> import sherlock
>>> from sherlock import MCLock
>>>
>>> # Global configuration of defaults
>>> sherlock.configure(expire=120, timeout=20)
>>>
>>> # Create a lock instance
>>> lock = MCLock('my_lock')
>>>
>>> # Acquire a lock in Memcached, global backend and client configuration
>>> # need not be configured since we are using a backend specific lock.
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> # Use this client object
>>> client = pylibmc.Client(['X.X.X.X'], binary=True)
>>>
>>> # Create a lock instance with custom client object
>>> lock = MCLock('my_lock', client=client)
>>>
>>> # To override the defaults, just past the configurations as parameters
>>> lock = MCLock('my_lock', client=client, expire=1, timeout=5)
>>>
>>> # Acquire a lock using the with_statement
>>> with MCLock('my_lock') as lock:
... # do some stuff with your acquired resource
... pass
"""
def __init__(self, lock_name, **kwargs):
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Optional namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
try:
import pylibmc
except ImportError as exc:
raise ImportError(
"Please install `sherlock` with `memcached` extras."
) from exc
super(MCLock, self).__init__(lock_name, **kwargs)
if self.client is None:
self.client = pylibmc.Client(["localhost"], binary=True)
self._owner = None
@property
def _key_name(self):
if self.namespace is not None:
key = "%s_%s" % (self.namespace, self.lock_name)
else:
key = self.lock_name
return key
def _acquire(self):
owner = str(uuid.uuid4())
_args = [self._key_name, str(owner)]
if self.expire is not None:
_args.append(self.expire)
# Set key only if it does not exist
if self.client.add(*_args) is True:
self._owner = owner
return True
else:
return False
def _release(self):
if self._owner is None:
raise LockException("Lock was not set by this process.")
resp = self.client.get(self._key_name)
if resp is not None:
if resp == str(self._owner):
self.client.delete(self._key_name)
self._owner = None
else:
raise LockException(
"Lock could not be released because it "
"was been acquired by this instance."
)
else:
raise LockException(
"Lock could not be released as it has not " "been acquired"
)
def _renew(self) -> bool:
if self._owner is None:
raise LockException("Lock was not set by this process.")
resp = self.client.get(self._key_name)
if resp is not None:
if resp == str(self._owner):
_args = [self._key_name, self._owner]
if self.expire is not None:
_args.append(self.expire)
# Update key with new TTL
self.client.set(*_args)
return True
return False
@property
def _locked(self):
return True if self.client.get(self._key_name) is not None else False
class KubernetesLock(BaseLock):
"""
Implementation of lock with Kubernetes resource as the backend for synchronization.
Basic Usage:
>>> import sherlock
>>> from sherlock import KubernetesLock
>>>
>>> # Global configuration of defaults
>>> sherlock.configure(expire=120, timeout=20)
>>>
>>> # Create a lock instance
>>> lock = KubernetesLock('my_lock', 'my_namespace')
>>>
>>> # To acquire a lock in Kubernetes, global backend and client configuration need
>>> # not be configured since we are using a backend specific lock.
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> # To override the defaults, just past the configurations as parameters
>>> lock = KubernetesLock(
... 'my_lock', 'my_namespace', expire=1, timeout=5,
... )
>>>
>>> # Acquire a lock using the with_statement
>>> with KubernetesLock('my_lock', 'my_namespace') as lock:
... # do some stuff with your acquired resource
... pass
"""
def __init__(
self,
lock_name: str,
k8s_namespace: str,
**kwargs,
) -> None:
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str k8s_namespace: Kubernetes namespace to store the lock in.
:param str namespace: Namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
try:
globals()["kubernetes"] = importlib.import_module("kubernetes")
except ImportError as exc:
raise ImportError(
"Please install `sherlock` with `kubernetes` extras."
) from exc
super().__init__(lock_name, **kwargs)
self.k8s_namespace = k8s_namespace
# Verify that all names are compatible with Kubernetes.
rfc_1123_dns_label = re.compile("^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,63}(?<!-)$")
err_msg = (
"{} must conform to RFC1123's definition of a DNS label for KubernetesLock"
)
for attr in ("lock_name", "k8s_namespace", "namespace"):
value = getattr(self, attr)
if value is not None:
if rfc_1123_dns_label.match(getattr(self, attr)) is None:
raise ValueError(err_msg.format(attr))
if self.client is None:
kubernetes.config.load_config()
self.client = kubernetes.client.CoordinationV1Api()
self._owner: typing.Optional[str] = None
@property
def _key_name(self):
if self.namespace is not None:
key = "%s-%s" % (self.namespace, self.lock_name)
else:
key = self.lock_name
return key
def _expiry_time(self, lease: kubernetes.client.V1Lease) -> datetime.datetime:
expiry_time = datetime.datetime.min
if (
lease.spec.renew_time is not None
and lease.spec.lease_duration_seconds is not None
):
expiry_time = lease.spec.renew_time + datetime.timedelta(
seconds=lease.spec.lease_duration_seconds
)
elif lease.spec.lease_duration_seconds is None:
expiry_time = datetime.datetime.max
return expiry_time.astimezone(tz=datetime.timezone.utc)
def _has_expired(
self, lease: kubernetes.client.V1Lease, now: datetime.datetime
) -> bool:
# Determine whether the Lease has expired.
return now > self._expiry_time(lease)
def _create_lease(
self,
owner: str,
) -> typing.Optional[kubernetes.client.V1Lease]:
now = self._now()
try:
return self.client.create_namespaced_lease(
namespace=self.k8s_namespace,
body=kubernetes.client.V1Lease(
metadata=kubernetes.client.V1ObjectMeta(
name=self._key_name,
),
spec=kubernetes.client.V1LeaseSpec(
holder_identity=owner,
acquire_time=now,
renew_time=now,
lease_duration_seconds=self.expire,
),
),
)
except kubernetes.client.exceptions.ApiException as exc:
if exc.reason == "Conflict":
# Someone has created the Lease before we did.
return None
raise LockException("Failed to create Lock.") from exc
def _get_lease(self) -> typing.Optional[kubernetes.client.V1Lease]:
try:
return self.client.read_namespaced_lease(
name=self._key_name,
namespace=self.k8s_namespace,
)
except kubernetes.client.exceptions.ApiException as exc:
if exc.reason == "Not Found":
# Lease did not exist.
return None
raise LockException("Failed to read Lock.") from exc
def _replace_lease(
self,
lease: kubernetes.client.V1Lease,
) -> typing.Optional[kubernetes.client.V1Lease]:
try:
return self.client.replace_namespaced_lease(
name=self._key_name,
namespace=self.k8s_namespace,
body=lease,
)
except kubernetes.client.exceptions.ApiException as exc:
if exc.reason == "Conflict":
return None
raise LockException("Failed to update Lock.") from exc
def _delete_lease(self, lease: kubernetes.client.V1Lease) -> None:
try:
self.client.delete_namespaced_lease(
name=self._key_name,
namespace=self.k8s_namespace,
body=kubernetes.client.V1DeleteOptions(
preconditions=kubernetes.client.V1Preconditions(
resource_version=lease.metadata.resource_version
)
),
)
except kubernetes.client.exceptions.ApiException as exc:
if exc.reason == "Not Found":
# The Lease has already been acquired by another
# instance which is fine.
return None
raise LockException("Failed to release Lock.") from exc
def _now(self) -> datetime.datetime:
return datetime.datetime.now(tz=datetime.timezone.utc)
def _acquire(self) -> bool:
owner = str(uuid.uuid4())
# The Lease object contains a `.metadata.resource_version` which
# protects us from race conditions in updating the Lease as described:
# https://blog.atomist.com/kubernetes-apply-replace-patch/.
lease = self._get_lease()
if lease is None:
# Lease does not exist so let's create it in our name.
if self._create_lease(owner) is not None:
# We created the Lease and so hold the Lock.
self._owner = owner
return True
else:
# We failed to create the Lease before someone else.
return False
now = self._now()
has_expired = self._has_expired(lease, now)
if owner != lease.spec.holder_identity:
if not has_expired:
# Someone else holds the lock.
return False
else:
# Lock is available for us to take.
lease.spec.holder_identity = owner
lease.spec.acquire_time = now
lease.spec.renew_time = now
lease.spec.lease_duration_seconds = self.expire
else:
# Same owner so do not set or modify Lease.
return False
# The Lease object contains a `.metadata.resource_version` which
# protects us from race conditions in updating the Lease as described:
# https://blog.atomist.com/kubernetes-apply-replace-patch/.
if self._replace_lease(lease) is None:
# Someone else has modified the Lease so we can't acquire the Lock
# safely.
return False
# We succeeded in replacing the Lease so we now hold the lock.
self._owner = owner
return True
def _release(self) -> None:
if self._owner is None:
raise LockException("Lock was not set by this process.")
lease = self._get_lease()
if lease is not None and self._owner == lease.spec.holder_identity:
# The Lease object contains a `.metadata.resource_version` which
# protects us from race conditions in deleting the Lease.
self._delete_lease(lease)
def _renew(self) -> bool:
if self._owner is None:
raise LockException("Lock was not set by this process.")
lease = self._get_lease()
if lease is not None and self._owner == lease.spec.holder_identity:
now = self._now()
has_expired = self._has_expired(lease, now)
if has_expired:
return False
lease.spec.acquire_time = now
lease.spec.renew_time = now
lease.spec.lease_duration_seconds = self.expire
# The Lease object contains a `.metadata.resource_version` which
# protects us from race conditions in updating the Lease as described:
# https://blog.atomist.com/kubernetes-apply-replace-patch/.
if self._replace_lease(lease) is None:
# Someone else has modified the Lease before we renewed it so it
# must've expired.
raise False
return True
return False
@property
def _locked(self):
lease = self._get_lease()
if lease is None:
# Lease doesn't exist so can't be locked.
return False
if self._has_expired(lease, self._now()):
# Lease exists but has expired.
return False
# Lease exists and has not expired.
return True
class FileLock(BaseLock):
"""
Implementation of lock with the file system as the backend for synchronization.
Basic Usage:
>>> import sherlock
>>> from sherlock import FileLock
>>>
>>> # Global configuration of defaults
>>> sherlock.configure(expire=120, timeout=20)
>>>
>>> # Create a lock instance
>>> lock = FileLock('my_lock')
>>>
>>> # To acquire a lock global backend and client configuration need
>>> # not be configured since we are using a backend specific lock.
>>> lock.acquire()
True
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
True
>>>
>>> # Release the acquired lock
>>> lock.release()
>>>
>>> # Check if the lock has been acquired
>>> lock.locked()
False
>>>
>>> # To override the defaults, just past the configurations as parameters
>>> lock = FileLock(
... 'my_lock', expire=1, timeout=5,
... )
>>>
>>> # Acquire a lock using the with_statement
>>> with FileLock('my_lock') as lock:
... # do some stuff with your acquired resource
... pass
"""
def __init__(self, lock_name: str, **kwargs) -> None:
"""
:param str lock_name: name of the lock to uniquely identify the lock
between processes.
:param str namespace: Namespace to namespace lock keys for
your application in order to avoid conflicts.
:param float expire: set lock expiry time. If explicitly set to `None`,
lock will not expire.
:param float timeout: set timeout to acquire lock
:param float retry_interval: set interval for trying acquiring lock
after the timeout interval has elapsed.
:param client: supported client object for the backend of your choice.
"""
try:
globals()["filelock"] = importlib.import_module("filelock")
except ImportError as exc:
raise ImportError(
"Please install `sherlock` with `filelock` extras."
) from exc
super().__init__(lock_name, **kwargs)
if self.client is None:
self.client = pathlib.Path("/tmp/sherlock")
self.client.mkdir(parents=True, exist_ok=True)
self._owner: typing.Optional[str] = None
self._data_file = (self.client / self._key_name).with_suffix(".json")
self._lock_file = filelock.FileLock(
(self.client / self._key_name).with_suffix(".lock")
)
@property
def _key_name(self):
if self.namespace is not None:
key = "%s_%s" % (self.namespace, self.lock_name)
else:
key = self.lock_name
return key
def _now(self) -> datetime.datetime:
return datetime.datetime.now(tz=datetime.timezone.utc)
def _expiry_time(self) -> str:
expiry_time = datetime.datetime.max.astimezone(datetime.timezone.utc)
if self.expire is not None:
expiry_time = self._now() + datetime.timedelta(seconds=self.expire)
return expiry_time.isoformat()
def _has_expired(self, data: dict, now: datetime.datetime) -> bool:
expiry_time = datetime.datetime.fromisoformat(data["expiry_time"])
return now > expiry_time.astimezone(tz=datetime.timezone.utc)
def _acquire(self) -> bool:
owner = str(uuid.uuid4())
# Make sure we have unique lock on the file.
with self._lock_file:
if self._data_file.exists():
data = json.loads(self._data_file.read_text())
now = self._now()
has_expired = self._has_expired(data, now)
if owner != data["owner"]:
if not has_expired:
# Someone else holds the lock.
return False
else:
# Lock is available for us to take.
data = {"owner": owner, "expiry_time": self._expiry_time()}
else:
# Same owner so do not set or modify Lease.
return False
else:
data = {"owner": owner, "expiry_time": self._expiry_time()}
# Write new data back to file.
self._data_file.touch()
self._data_file.write_text(json.dumps(data))
# We succeeded in writing to the file so we now hold the lock.
self._owner = owner
return True
def _release(self) -> None:
if self._owner is None:
raise LockException("Lock was not set by this process.")
if self._data_file.exists():
with self._lock_file:
data = json.loads(self._data_file.read_text())
if self._owner == data["owner"]:
self._data_file.unlink()
def _renew(self) -> bool:
if self._owner is None:
raise LockException("Lock was not set by this process.")
if self._data_file.exists():
with self._lock_file:
data = json.loads(self._data_file.read_text())
now = self._now()
has_expired = self._has_expired(data, now)
if self._owner == data["owner"]:
if has_expired:
return False
# Refresh expiry time.
data["expiry_time"] = self._expiry_time()
self._data_file.write_text(json.dumps(data))
return True
return False
@property
def _locked(self):
if not self._data_file.exists():
# File doesn't exist so can't be locked.
return False
with self._lock_file:
data = json.loads(self._data_file.read_text())
if self._has_expired(data, self._now()):
# File exists but has expired.
return False
# Lease exists and has not expired.
return True
|