/
base.py
175 lines (129 loc) · 4.6 KB
/
base.py
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
"""
nydus.db.base
~~~~~~~~~~~~~
:copyright: (c) 2011 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
import time
from itertools import cycle
__all__ = ('BaseRouter', 'RoundRobinRouter')
class BaseRouter(object):
"""
Handles routing requests to a specific connection in a single cluster.
"""
retryable = False
class UnableToSetupRouter(Exception):
pass
def __init__(self, *args, **kwargs):
self._ready = False
def get_dbs(self, cluster, attr, key=None, *args, **kwargs):
"""
Perform setup and routing
Always return an iterable
Do not overload this method
"""
if not self._ready:
if not self.setup_router(cluster, *args, **kwargs):
raise self.UnableToSetupRouter()
key = self._pre_routing(cluster, attr, key, *args, **kwargs)
if not key:
return cluster.hosts.keys()
try:
db_nums = self._route(cluster, attr, key, *args, **kwargs)
except Exception, e:
self._handle_exception(e)
db_nums = []
return self._post_routing(cluster, attr, key, db_nums, *args, **kwargs)
# Backwards compatibilty
get_db = get_dbs
def setup_router(self, cluster, *args, **kwargs):
"""
Call method to perform any setup
"""
self._ready = self._setup_router(cluster, *args, **kwargs)
return self._ready
def _setup_router(self, cluster, *args, **kwargs):
"""
Perform any initialization for the router
Returns False if setup could not be completed
"""
return True
def _pre_routing(self, cluster, attr, key, *args, **kwargs):
"""
Perform any prerouting with this method and return the key
"""
return key
def _route(self, cluster, attr, key, *args, **kwargs):
"""
Perform routing and return db_nums
"""
return cluster.hosts.keys()
def _post_routing(self, cluster, attr, key, db_nums, *args, **kwargs):
"""
Perform any postrouting actions and return db_nums
"""
return db_nums
def _handle_exception(self, e):
"""
Handle/transform exceptions and return it
"""
raise e
class RoundRobinRouter(BaseRouter):
"""
Basic retry router that performs round robin
"""
# Raised if all hosts in the hash have been marked as down
class HostListExhausted(Exception):
pass
class InvalidDBNum(Exception):
pass
# If this router can be retried on if a particular db index it gave out did
# not work
retryable = True
# How many requests to serve in a situation when a host is down before
# the down hosts are retried
attempt_reconnect_threshold = 100000
# Retry a down connection after this timeout
retry_timeout = 30
def __init__(self, *args, **kwargs):
self._get_db_attempts = 0
self._down_connections = {}
super(RoundRobinRouter,self).__init__(*args, **kwargs)
@classmethod
def ensure_db_num(cls, db_num):
try:
return int(db_num)
except ValueError:
raise cls.InvalidDBNum()
def flush_down_connections(self):
self._get_db_attempts = 0
self._down_connections = {}
def mark_connection_down(self, db_num):
db_num = self.ensure_db_num(db_num)
self._down_connections[db_num] = time.time()
def mark_connection_up(self, db_num):
db_num = self.ensure_db_num(db_num)
self._down_connections.pop(db_num, None)
def _setup_router(self, cluster, *args, **kwargs):
self._hosts_cycler = cycle(cluster.hosts.keys())
return True
def _pre_routing(self, cluster, attr, key, *args, **kwargs):
self._get_db_attempts += 1
if self._get_db_attempts > self.attempt_reconnect_threshold:
self.flush_down_connections()
if 'retry_for' in kwargs:
self.mark_connection_down(kwargs['retry_for'])
return key
def _route(self, cluster, attr, key, *args, **kwargs):
now = time.time()
for i in xrange(len(cluster)):
db_num = self._hosts_cycler.next()
marked_down_at = self._down_connections.get(db_num, False)
if not marked_down_at or (marked_down_at + self.retry_timeout <= now):
return [db_num]
else:
raise self.HostListExhausted()
def _post_routing(self, cluster, attr, key, db_nums, *args, **kwargs):
if db_nums:
self.mark_connection_up(db_nums[0])
return db_nums