forked from crate/crate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_decommission.py
More file actions
401 lines (337 loc) · 13.5 KB
/
Copy pathtest_decommission.py
File metadata and controls
401 lines (337 loc) · 13.5 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# -*- coding: utf-8; -*-
#
# Licensed to Crate.io GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you 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.
#
# However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.
import unittest
import os
import time
import random
import string
import threading
from cr8.run_crate import CrateNode
from crate.client.http import Client
from crate.client.exceptions import ProgrammingError, ConnectionError
from testutils.paths import crate_path
from testutils.ports import bind_range
def decommission(client, node):
try:
return client.sql('alter cluster decommission ?', (node,))
except ConnectionError:
pass
def retry_sql(client, statement):
""" retry statement on node not found in cluster state errors
sys.shards queries might fail if a node that has shutdown is still
in the cluster state
"""
wait_time = 0
sleep_duration = 0.01
last_error = None
while wait_time < 10.5:
try:
return client.sql(statement)
except ProgrammingError as e:
if ('not found in cluster state' in e.message or
'Node not connected' in e.message):
time.sleep(sleep_duration)
last_error = e
wait_time += sleep_duration
sleep_duration *= 2
continue
raise e
raise last_error
def wait_for_cluster_size(client, expected_size, timeout_in_s=20):
""" retry check (up to timeout_in_s) for expected cluster size
Returns True if the cluster size reaches the expected one, False otherwise
Can raise: Value Error -- for a negative value of expected_size
TimeoutError -- after timeout_in_s
A node can be decommissioned with a delay, this can be
used to check when a node is indeed decommissioned
"""
if expected_size < 0:
raise ValueError('expected_size cannot be negative')
wait_time = 0
sleep_duration = 1
num_nodes = -1
while num_nodes != expected_size:
time.sleep(sleep_duration)
wait_time += sleep_duration
response = client.sql("select * from sys.nodes")
num_nodes = response.get("rowcount", -1)
if num_nodes == -1:
return False
if wait_time > timeout_in_s:
raise TimeoutError('Timeout occurred ({}s) while waiting for cluster size to become {}'
.format(timeout_in_s, expected_size))
return True
class GracefulStopCrateLayer(CrateNode):
MAX_RETRIES = 3
def start(self, retry=0):
if retry >= self.MAX_RETRIES:
raise SystemError('Could not start Crate server. Max retries exceeded!')
try:
super().start()
except Exception:
self.start(retry=retry + 1)
def stop(self):
"""do not care if process already died"""
try:
super().stop()
except OSError:
pass
class GracefulStopTest(unittest.TestCase):
"""
abstract class for starting a cluster of crate instances
and testing against them
"""
DEFAULT_NUM_SERVERS = 1
def __init__(self, *args, **kwargs):
self.num_servers = kwargs.pop("num_servers", getattr(self, "NUM_SERVERS", self.DEFAULT_NUM_SERVERS))
super().__init__(*args, **kwargs)
def setUp(self):
self.crates = []
self.clients = []
self.node_names = []
# auto-discovery with unicast on the same host only works if all nodes are configured with the same port range
transport_port_range = bind_range(range_size=self.num_servers)
for i in range(self.num_servers):
layer = GracefulStopCrateLayer(
crate_dir=crate_path(),
settings={
'cluster.name': self.__class__.__name__,
'node.name': self.node_name(i),
'transport.tcp.port': transport_port_range,
'node.sql.num_temp_error_retries': 15,
},
env={
**os.environ.copy(),
'CRATE_HEAP_SIZE': '256M'
},
version=(4, 0, 0)
)
layer.start()
self.clients.append(Client(layer.http_url))
self.crates.append(layer)
self.node_names.append(self.node_name(i))
client = self.random_client()
num_nodes = 0
# wait until all nodes joined the cluster
while num_nodes < len(self.crates):
response = client.sql("select * from sys.nodes")
num_nodes = response.get("rowcount", 0)
time.sleep(.5)
def tearDown(self):
for client in self.clients:
client.close()
for layer in self.crates:
layer.stop()
def random_client(self):
return random.choice(self.clients)
def node_name(self, i):
return "crate_{0}_{1}".format(self.__class__.__name__, i)
def set_settings(self, settings):
client = self.random_client()
for key, value in settings.items():
client.sql("set global transient {}=?".format(key), (value,))
class TestGracefulStopPrimaries(GracefulStopTest):
NUM_SERVERS = 3
def setUp(self):
super().setUp()
client = self.clients[0]
client.sql("create table t1 (id int, name string) "
"clustered into 4 shards "
"with (number_of_replicas=0)")
client.sql("insert into t1 (id, name) values (?, ?), (?, ?)",
(1, "Ford", 2, "Trillian"))
client.sql("refresh table t1")
def test_graceful_stop_primaries(self):
"""
test min_availability: primaries
"""
client2 = self.clients[1]
self.set_settings({"cluster.graceful_stop.min_availability": "primaries"})
decommission(self.clients[0], self.node_names[0])
self.assertEqual(wait_for_cluster_size(client2, TestGracefulStopPrimaries.NUM_SERVERS - 1), True)
stmt = "select table_name, id from sys.shards where state = 'UNASSIGNED'"
response = retry_sql(client2, stmt)
# assert that all shards are assigned
self.assertEqual(response.get("rowcount", -1), 0)
def tearDown(self):
client = self.clients[1]
client.sql("drop table t1")
super().tearDown()
class TestGracefulStopFull(GracefulStopTest):
NUM_SERVERS = 3
def setUp(self):
super().setUp()
client = self.clients[0]
client.sql("create table t1 (id int, name string) "
"clustered into 4 shards "
"with (number_of_replicas=1)")
client.sql("insert into t1 (id, name) values (?, ?), (?, ?)",
(1, "Ford", 2, "Trillian"))
client.sql("refresh table t1")
def test_graceful_stop_full(self):
"""
min_availability: full moves all shards
"""
node1, node2, node3 = self.node_names
client1, client2, client3 = self.clients
self.set_settings({"cluster.graceful_stop.min_availability": "full"})
decommission(client2, node1)
self.assertEqual(wait_for_cluster_size(client2, TestGracefulStopFull.NUM_SERVERS - 1), True)
stmt = "select table_name, id from sys.shards where state = 'UNASSIGNED'"
response = retry_sql(client2, stmt)
# assert that all shards are assigned
self.assertEqual(response.get("rowcount", -1), 0)
def tearDown(self):
client = self.clients[2]
client.sql("drop table t1")
super().tearDown()
class TestGracefulStopNone(GracefulStopTest):
NUM_SERVERS = 3
def setUp(self):
super().setUp()
client = self.clients[0]
client.sql("create table t1 (id int, name string) "
"clustered into 8 shards "
"with (number_of_replicas=0)")
client.sql("refresh table t1")
names = ("Ford", "Trillian", "Zaphod", "Jeltz")
for i in range(16):
client.sql("insert into t1 (id, name) "
"values (?, ?)",
(i, random.choice(names)))
client.sql("refresh table t1")
def test_graceful_stop_none(self):
"""
test `min_availability: none` will stop the node immediately.
Causes some shard to become unassigned (no replicas)
"""
client2 = self.clients[1]
self.set_settings({"cluster.graceful_stop.min_availability": "none"})
decommission(self.clients[0], self.node_names[0])
self.assertEqual(wait_for_cluster_size(client2, TestGracefulStopNone.NUM_SERVERS - 1), True)
stmt = "select node['id'] as node_id, id, state \
from sys.shards where state='UNASSIGNED'"
resp = retry_sql(client2, stmt)
# since there were no replicas some shards must be missing
unassigned_shards = resp.get("rowcount", -1)
self.assertTrue(
unassigned_shards > 0,
"{0} unassigned shards, expected more than 0".format(unassigned_shards)
)
def tearDown(self):
client = self.clients[1]
client.sql("drop table t1")
super().tearDown()
class TestGracefulStopDuringQueryExecution(GracefulStopTest):
NUM_SERVERS = 3
def setUp(self):
super().setUp()
client = self.clients[0]
client.sql('''
CREATE TABLE t1 (id int primary key, name string)
CLUSTERED INTO 4 SHARDS
WITH (number_of_replicas = 1)
''')
def bulk_params():
for i in range(5000):
chars = list(string.ascii_lowercase[:14])
random.shuffle(chars)
yield (i, ''.join(chars))
bulk_params = list(bulk_params())
client.sql('INSERT INTO t1 (id, name) values (?, ?)', None, bulk_params)
client.sql('REFRESH TABLE t1')
def test_graceful_stop_concurrent_queries(self):
self.set_settings({
"cluster.graceful_stop.min_availability": "full",
"cluster.graceful_stop.force": "false"
})
concurrency = 4
client = self.clients[0]
run_queries = [True]
errors = []
threads_finished_b = threading.Barrier((concurrency * 3) + 1)
func_args = (client, run_queries, errors, threads_finished_b)
for i in range(concurrency):
t = threading.Thread(
target=TestGracefulStopDuringQueryExecution.exec_select_queries,
args=func_args
)
t.start()
t = threading.Thread(
target=TestGracefulStopDuringQueryExecution.exec_insert_queries,
args=func_args
)
t.start()
t = threading.Thread(
target=TestGracefulStopDuringQueryExecution.exec_delete_queries,
args=func_args
)
t.start()
# Ensure we don't hold a connection open to the node getting stopped
self.clients[1].close()
decommission(self.clients[0], self.node_names[1])
try:
self.assertEqual(wait_for_cluster_size(self.clients[0], TestGracefulStopDuringQueryExecution.NUM_SERVERS - 1), True)
except:
# Need to stop threads, otherwise the test would get stuck
run_queries[0] = False
threads_finished_b.wait()
raise
run_queries[0] = False
threads_finished_b.wait()
self.assertEqual(errors, [])
def tearDown(self):
self.clients[0].sql('DROP TABLE t1')
super().tearDown()
@staticmethod
def exec_insert_queries(client, is_active, errors, finished):
while is_active[0]:
try:
chars = list(string.ascii_lowercase[:14])
random.shuffle(chars)
client.sql(
'insert into t1 (id, name) values ($1, $2) on conflict (id) do update set name = $2',
(random.randint(0, 2147483647), ''.join(chars))
)
except Exception as e:
errors.append(e)
finished.wait()
@staticmethod
def exec_delete_queries(client, is_active, errors, finished):
while is_active[0]:
try:
chars = list(string.ascii_lowercase[:14])
random.shuffle(chars)
pattern = ''.join(chars[:3]) + '%'
client.sql(
'delete from t1 where name like ?', (pattern,))
except Exception as e:
if 'RelationUnknown' not in str(e):
errors.append(e)
finished.wait()
@staticmethod
def exec_select_queries(client, is_active, errors, finished):
while is_active[0]:
try:
client.sql('select name, count(*) from t1 group by name')
except Exception as e:
errors.append(e)
finished.wait()