Update parse nsd package logic
[vfc/nfvo/lcm.git] / lcm / pub / utils / share_lock.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Copyright 2016 ZTE Corporation.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #         http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import time
18
19 import redis
20
21 from lcm.pub.config.config import REDIS_HOST, REDIS_PORT, REDIS_PASSWD
22
23
24 class SharedLock:
25     def __init__(self, lock_key, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWD, db=9, lock_timeout=5 * 60):
26         self.lock_key = lock_key
27         self.lock_timeout = lock_timeout
28         self.redis = redis.Redis(host=host, port=port, db=db, password=password)
29         self.acquire_time = -1
30
31     def acquire(self):
32         begin = now = int(time.time())
33         while (now - begin) < self.lock_timeout:
34
35             result = self.redis.setnx(self.lock_key, now + self.lock_timeout + 1)
36             if result == 1 or result is True:
37                 self.acquire_time = now
38                 return True
39
40             current_lock_timestamp = self.redis.get(self.lock_key)
41             if not current_lock_timestamp:
42                 time.sleep(1)
43                 continue
44
45             current_lock_timestamp = int(current_lock_timestamp)
46
47             if now > current_lock_timestamp:
48                 next_lock_timestamp = self.redis.getset(self.lock_key, now + self.lock_timeout + 1)
49                 if not next_lock_timestamp:
50                     time.sleep(1)
51                     continue
52                 next_lock_timestamp = int(next_lock_timestamp)
53
54                 if next_lock_timestamp == current_lock_timestamp:
55                     self.acquire_time = now
56                     return True
57             else:
58                 time.sleep(1)
59                 continue
60         return False
61
62     def release(self):
63         now = int(time.time())
64         if now > self.acquire_time + self.lock_timeout:
65             # key expired, do nothing and let other clients handle it
66             return
67         self.acquire_time = None
68         self.redis.delete(self.lock_key)
69
70
71 def do_biz_with_share_lock(lock_name, callback):
72     lock = SharedLock(lock_name)
73     try:
74         if not lock.acquire():
75             raise Exception(lock_name + " timeout")
76         callback()
77     except Exception as e:
78         raise e
79     finally:
80         lock.release()