Implement vnflcm call_req_aai function
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / utils / share_lock.py
1 # Copyright 2017 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import time
16
17 import redis
18
19 from lcm.pub.config.config import REDIS_HOST, REDIS_PORT, REDIS_PASSWD
20
21
22 class SharedLock:
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
28
29     def acquire(self):
30         begin = now = int(time.time())
31         while (now - begin) < self.lock_timeout:
32
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
36                 return True
37
38             current_lock_timestamp = self.redis.get(self.lock_key)
39             if not current_lock_timestamp:
40                 time.sleep(1)
41                 continue
42
43             current_lock_timestamp = int(current_lock_timestamp)
44
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:
48                     time.sleep(1)
49                     continue
50                 next_lock_timestamp = int(next_lock_timestamp)
51
52                 if next_lock_timestamp == current_lock_timestamp:
53                     self.acquire_time = now
54                     return True
55             else:
56                 time.sleep(1)
57                 continue
58         return False
59
60     def release(self):
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
64             return
65         self.acquire_time = None
66         self.redis.delete(self.lock_key)
67
68
69 def do_biz_with_share_lock(lock_name, callback):
70     lock = SharedLock(lock_name)
71     try:
72         if not lock.acquire():
73             raise Exception(lock_name + " timeout")
74         callback()
75     except Exception as e:
76         raise e
77     finally:
78         lock.release()