forked from apache/cassandra-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent.py
More file actions
299 lines (245 loc) · 12 KB
/
concurrent.py
File metadata and controls
299 lines (245 loc) · 12 KB
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
# Copyright 2013-2017 DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
from heapq import heappush, heappop
from itertools import cycle
import six
from six.moves import xrange, zip
from threading import Condition
import sys
from collections import defaultdict
from cassandra.cluster import ResultSet
from cassandra.pool import HostDistance
from cassandra.cqltypes import _cqltypes
import logging
log = logging.getLogger(__name__)
ExecutionResult = namedtuple('ExecutionResult', ['success', 'result_or_exc'])
def execute_concurrent(session, statements_and_parameters, concurrency=100, raise_on_first_error=True, results_generator=False):
"""
Executes a sequence of (statement, parameters) tuples concurrently. Each
``parameters`` item must be a sequence or :const:`None`.
The `concurrency` parameter controls how many statements will be executed
concurrently. When :attr:`.Cluster.protocol_version` is set to 1 or 2,
it is recommended that this be kept below 100 times the number of
core connections per host times the number of connected hosts (see
:meth:`.Cluster.set_core_connections_per_host`). If that amount is exceeded,
the event loop thread may attempt to block on new connection creation,
substantially impacting throughput. If :attr:`~.Cluster.protocol_version`
is 3 or higher, you can safely experiment with higher levels of concurrency.
If `raise_on_first_error` is left as :const:`True`, execution will stop
after the first failed statement and the corresponding exception will be
raised.
`results_generator` controls how the results are returned.
If :const:`False`, the results are returned only after all requests have completed.
If :const:`True`, a generator expression is returned. Using a generator results in a constrained
memory footprint when the results set will be large -- results are yielded
as they return instead of materializing the entire list at once. The trade for lower memory
footprint is marginal CPU overhead (more thread coordination and sorting out-of-order results
on-the-fly).
A sequence of ``ExecutionResult(success, result_or_exc)`` namedtuples is returned
in the same order that the statements were passed in. If ``success`` is :const:`False`,
there was an error executing the statement, and ``result_or_exc`` will be
an :class:`Exception`. If ``success`` is :const:`True`, ``result_or_exc``
will be the query result.
Example usage::
select_statement = session.prepare("SELECT * FROM users WHERE id=?")
statements_and_params = []
for user_id in user_ids:
params = (user_id, )
statements_and_params.append((select_statement, params))
results = execute_concurrent(
session, statements_and_params, raise_on_first_error=False)
for (success, result) in results:
if not success:
handle_error(result) # result will be an Exception
else:
process_user(result[0]) # result will be a list of rows
"""
if concurrency <= 0:
raise ValueError("concurrency must be greater than 0")
if not statements_and_parameters:
return []
executor = ConcurrentExecutorGenResults(session, statements_and_parameters) if results_generator else ConcurrentExecutorListResults(session, statements_and_parameters)
return executor.execute(concurrency, raise_on_first_error)
class _ConcurrentExecutor(object):
max_error_recursion = 100
def __init__(self, session, statements_and_params):
self.session = session
self._enum_statements = enumerate(iter(statements_and_params))
self._condition = Condition()
self._fail_fast = False
self._results_queue = []
self._current = 0
self._exec_count = 0
self._exec_depth = 0
def execute(self, concurrency, fail_fast):
self._fail_fast = fail_fast
self._results_queue = []
self._current = 0
self._exec_count = 0
with self._condition:
for n in xrange(concurrency):
if not self._execute_next():
break
return self._results()
def _execute_next(self):
# lock must be held
try:
(idx, (statement, params)) = next(self._enum_statements)
self._exec_count += 1
self._execute(idx, statement, params)
return True
except StopIteration:
pass
def _execute(self, idx, statement, params):
self._exec_depth += 1
try:
future = self.session.execute_async(statement, params, timeout=None)
args = (future, idx)
future.add_callbacks(
callback=self._on_success, callback_args=args,
errback=self._on_error, errback_args=args)
except Exception as exc:
# exc_info with fail_fast to preserve stack trace info when raising on the client thread
# (matches previous behavior -- not sure why we wouldn't want stack trace in the other case)
e = sys.exc_info() if self._fail_fast and six.PY2 else exc
# If we're not failing fast and all executions are raising, there is a chance of recursing
# here as subsequent requests are attempted. If we hit this threshold, schedule this result/retry
# and let the event loop thread return.
if self._exec_depth < self.max_error_recursion:
self._put_result(e, idx, False)
else:
self.session.submit(self._put_result, e, idx, False)
self._exec_depth -= 1
def _on_success(self, result, future, idx):
future.clear_callbacks()
self._put_result(ResultSet(future, result), idx, True)
def _on_error(self, result, future, idx):
self._put_result(result, idx, False)
@staticmethod
def _raise(exc):
if six.PY2 and isinstance(exc, tuple):
(exc_type, value, traceback) = exc
six.reraise(exc_type, value, traceback)
else:
raise exc
class ConcurrentExecutorGenResults(_ConcurrentExecutor):
def _put_result(self, result, idx, success):
with self._condition:
heappush(self._results_queue, (idx, ExecutionResult(success, result)))
self._execute_next()
self._condition.notify()
def _results(self):
with self._condition:
while self._current < self._exec_count:
while not self._results_queue or self._results_queue[0][0] != self._current:
self._condition.wait()
while self._results_queue and self._results_queue[0][0] == self._current:
_, res = heappop(self._results_queue)
try:
self._condition.release()
if self._fail_fast and not res[0]:
self._raise(res[1])
yield res
finally:
self._condition.acquire()
self._current += 1
class ConcurrentExecutorListResults(_ConcurrentExecutor):
_exception = None
def execute(self, concurrency, fail_fast):
self._exception = None
return super(ConcurrentExecutorListResults, self).execute(concurrency, fail_fast)
def _put_result(self, result, idx, success):
self._results_queue.append((idx, ExecutionResult(success, result)))
with self._condition:
self._current += 1
if not success and self._fail_fast:
if not self._exception:
self._exception = result
self._condition.notify()
elif not self._execute_next() and self._current == self._exec_count:
self._condition.notify()
def _results(self):
with self._condition:
while self._current < self._exec_count:
self._condition.wait()
if self._exception and self._fail_fast:
self._raise(self._exception)
if self._exception and self._fail_fast: # raise the exception even if there was no wait
self._raise(self._exception)
return [r[1] for r in sorted(self._results_queue)]
def execute_concurrent_with_args(session, statement, parameters, *args, **kwargs):
"""
Like :meth:`~cassandra.concurrent.execute_concurrent()`, but takes a single
statement and a sequence of parameters. Each item in ``parameters``
should be a sequence or :const:`None`.
Example usage::
statement = session.prepare("INSERT INTO mytable (a, b) VALUES (1, ?)")
parameters = [(x,) for x in range(1000)]
execute_concurrent_with_args(session, statement, parameters, concurrency=50)
"""
return execute_concurrent(session, zip(cycle((statement,)), parameters), *args, **kwargs)
def query_by_keys(session, keyspace, table, select_fields, keys):
"""
Executes a few SELECT statements using the IN clause with several partition keys
and targeted at the replica with those keys. The alternative to this would be several
SELECT statements with the WHERE clause key=value.
The target table can only have one partition key
Example usage::
result = query_per_range(session, "system", "peers",
("peer", "data_center"), ("127.0.0.1", "127.0.0.2"))
"""
select_query = "SELECT " + ",".join(select_fields) + " FROM {}.{} WHERE ".format(keyspace, table)
cluster = session.cluster
partition_keys = cluster.metadata.keyspaces[keyspace].tables[table].partition_key
assert len(partition_keys) == 1
serializer = _cqltypes[partition_keys[0].cql_type]
partition_key_name = partition_keys[0].name
no_valid_replica = object()
keys_per_host = defaultdict(list)
for key in keys:
serialized_key = serializer.serialize(key, cluster.protocol_version)
all_replicas = cluster.metadata.get_replicas(keyspace, serialized_key)
# First check if there are local replicas
valid_replicas = list(host for host in all_replicas if
host.is_up and cluster._default_load_balancing_policy.distance(host) == HostDistance.LOCAL)
if not valid_replicas:
valid_replicas = list(host for host in all_replicas if host.is_up)
if not valid_replicas:
# We will group under this statement all the keys for which
# we haven't found a valid replica
keys_per_host[no_valid_replica].append(key)
else:
for replica in valid_replicas:
if replica in keys_per_host:
keys_per_host[replica].append(key)
break
else:
keys_per_host[valid_replicas.pop()].append(key)
response_futures = []
for host, keys_in_host in six.iteritems(keys_per_host):
primary_keys_query = partition_key_name + " IN "
params_query = "(" + ",".join(["%s"] * len(keys_in_host)) + ")"
statement = select_query + primary_keys_query + params_query
response_future = session._create_response_future(statement, keys_in_host, trace=False,
custom_payload=None, timeout=session.default_timeout)
if host is no_valid_replica:
response_future.send_request()
else:
response_future._query(host)
response_futures.append(response_future)
for response_future in response_futures:
results = response_future.result()
for row in results:
yield row