1 # Copyright 2017 ZTE Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
19 from lcm.pub.config.config import REDIS_HOST, REDIS_PORT, REDIS_PASSWD
23 def __init__(self, lock_key, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWD, db=9, lock_timeout=5 * 60):
24 self.lock_key = lock_key
25 self.lock_timeout = lock_timeout
26 self.redis = redis.Redis(host=host, port=port, db=db, password=password)
27 self.acquire_time = -1
30 begin = now = int(time.time())
31 while (now - begin) < self.lock_timeout:
33 result = self.redis.setnx(self.lock_key, now + self.lock_timeout + 1)
34 if result == 1 or result is True:
35 self.acquire_time = now
38 current_lock_timestamp = self.redis.get(self.lock_key)
39 if not current_lock_timestamp:
43 current_lock_timestamp = int(current_lock_timestamp)
45 if now > current_lock_timestamp:
46 next_lock_timestamp = self.redis.getset(self.lock_key, now + self.lock_timeout + 1)
47 if not next_lock_timestamp:
50 next_lock_timestamp = int(next_lock_timestamp)
52 if next_lock_timestamp == current_lock_timestamp:
53 self.acquire_time = now
61 now = int(time.time())
62 if now > self.acquire_time + self.lock_timeout:
63 # key expired, do nothing and let other clients handle it
65 self.acquire_time = None
66 self.redis.delete(self.lock_key)
69 def do_biz_with_share_lock(lock_name, callback):
70 lock = SharedLock(lock_name)
72 if not lock.acquire():
73 raise Exception(lock_name + " timeout")
75 except Exception as e: