Elffuss BraidHub

kikocis/falkordb-omnistrate public

main · 12.4 KiBRawPermalink
1import sys
2import signal
3from random import randbytes
4from pathlib import Path
5import threading
6from redis.retry import Retry
7from redis.backoff import ExponentialBackoff
8from redis.exceptions import (
9 TimeoutError,
10 ConnectionError,
11 BusyLoadingError
12)
13
14file = Path(__file__).resolve()
15parent, root = file.parent, file.parents[1]
16sys.path.append(str(root))
17
18# Additionally remove the current file's directory from sys.path
19try:
20 sys.path.remove(str(parent))
21except ValueError: # Already removed
22 pass
23
24import logging
25logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
26
27import time
28import os
29from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
30from omnistrate_tests.classes.omnistrate_fleet_api import OmnistrateFleetAPI
31import argparse
32from falkordb import FalkorDB
33from redis import Sentinel
34import random
35
36
37parser = argparse.ArgumentParser()
38parser.add_argument("omnistrate_user")
39parser.add_argument("omnistrate_password")
40parser.add_argument("cloud_provider", choices=["aws", "gcp"])
41parser.add_argument("region")
42
43parser.add_argument(
44 "--subscription-id", required=False, default=os.getenv("SUBSCRIPTION_ID")
45)
46parser.add_argument("--ref-name", required=False, default=os.getenv("REF_NAME"))
47parser.add_argument("--service-id", required=True)
48parser.add_argument("--environment-id", required=True)
49parser.add_argument(
50 "--resource-key", required=True, choices=["single-Zone", "multi-Zone"]
51)
52
53
54parser.add_argument("--instance-name", required=True)
55parser.add_argument(
56 "--instance-description", required=False, default="test-replication"
57)
58parser.add_argument("--instance-type", required=True)
59parser.add_argument("--storage-size", required=False, default="30")
60parser.add_argument("--tls", action="store_true")
61parser.add_argument("--rdb-config", required=False, default="medium")
62parser.add_argument("--aof-config", required=False, default="always")
63
64parser.set_defaults(tls=False)
65args = parser.parse_args()
66
67instance: OmnistrateFleetInstance = None
68
69# Intercept exit signals so we can delete the instance before exiting
70def signal_handler(sig, frame):
71 if instance:
72 instance.delete(False)
73 sys.exit(0)
74signal.signal(signal.SIGINT, signal_handler)
75signal.signal(signal.SIGTERM, signal_handler)
76
77
78def test_replication():
79 global instance
80
81 omnistrate = OmnistrateFleetAPI(
82 email=args.omnistrate_user,
83 password=args.omnistrate_password,
84 )
85
86 service = omnistrate.get_service(args.service_id)
87 product_tier = omnistrate.get_product_tier(
88 service_id=args.service_id,
89 environment_id=args.environment_id,
90 tier_name=args.ref_name,
91 )
92 service_model = omnistrate.get_service_model(
93 args.service_id, product_tier.service_model_id
94 )
95
96 logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
97
98 instance = omnistrate.instance(
99 service_id=args.service_id,
100 service_provider_id=service.service_provider_id,
101 service_key=service.key,
102 service_environment_id=args.environment_id,
103 service_environment_key=service.get_environment(args.environment_id).key,
104 service_model_key=service_model.key,
105 service_api_version="v1",
106 product_tier_key=product_tier.product_tier_key,
107 resource_key=args.resource_key,
108 subscription_id=args.subscription_id,
109 deployment_create_timeout_seconds=2400,
110 deployment_delete_timeout_seconds=2400,
111 deployment_failover_timeout_seconds=2400
112 )
113
114 try:
115 password = randbytes(16).hex()
116 instance.create(
117 wait_for_ready=True,
118 deployment_cloud_provider=args.cloud_provider,
119 deployment_region=args.region,
120 name=args.instance_name,
121 description=args.instance_description,
122 falkordb_user="falkordb",
123 falkordb_password=password,
124 nodeInstanceType=args.instance_type,
125 storageSize=args.storage_size,
126 enableTLS=args.tls,
127 RDBPersistenceConfig=args.rdb_config,
128 AOFPersistenceConfig=args.aof_config,
129 )
130
131 thread_signal = threading.Event()
132 error_signal = threading.Event()
133 thread = threading.Thread(
134 target=test_zero_downtime, args=(thread_signal, error_signal, instance, args.tls)
135 )
136 thread.start()
137
138 # Test failover and data loss
139 test_failover(instance, password)
140
141 # Wait for the zero_downtime
142 thread_signal.set()
143 thread.join()
144
145 # Test stop and start instance
146 test_stop_start(instance, password)
147 except Exception as e:
148 logging.exception(e)
149 instance.delete(False)
150 raise e
151
152 # Delete instance
153 instance.delete(False)
154
155 if error_signal.is_set():
156 raise ValueError("Test failed")
157 else:
158 logging.info("Test passed")
159
160
161def test_failover(instance: OmnistrateFleetInstance, password: str):
162 """
163 Single Zone tests are the following:
164 1. Create a single zone instance
165 2. Write some data to the master node
166 3. Trigger a failover for the master node
167 4. Wait until the sentinels promote a new master
168 5. Check if the data is still there
169 6. Write more data to the new master
170 7. Trigger a failover for one of the sentinels
171 8. Make sure we can still connect and read the data
172 9. Trigger a failover for the new master
173 10. Wait until the sentinels promote a new master
174 11. Make sure we still have the both writes in the new master and slave
175 12. Delete the instance
176 """
177
178 resources = instance.get_connection_endpoints()
179 db_resource = list(
180 filter(lambda resource: resource["id"].startswith("node-"), resources)
181 )
182 db_resource.sort(key=lambda resource: resource["id"])
183 sentinel_resource = next(
184 (resource for resource in resources if resource["id"].startswith("sentinel-")),
185 None,
186 )
187 db_0 = FalkorDB(
188 host=db_resource[0]["endpoint"],
189 port=db_resource[0]["ports"][0],
190 username="falkordb",
191 password=password,
192 ssl=args.tls,
193 )
194 db_1 = FalkorDB(
195 host=db_resource[1]["endpoint"],
196 port=db_resource[1]["ports"][0],
197 username="falkordb",
198 password=password,
199 ssl=args.tls,
200 )
201
202 retry = Retry(ExponentialBackoff(base=3),20,supported_errors=(
203 TimeoutError,
204 ConnectionError,
205 ConnectionRefusedError
206 ))
207
208 sentinels = Sentinel(
209 sentinels=[
210 (sentinel_resource["endpoint"], sentinel_resource["ports"][0]),
211 (db_resource[0]["endpoint"], db_resource[0]["ports"][1]),
212 (db_resource[1]["endpoint"], db_resource[1]["ports"][1]),
213 ],
214 sentinel_kwargs={
215 "username": "falkordb",
216 "password": password,
217 "ssl": args.tls,
218 },
219 connection_kwargs={
220 "username": "falkordb",
221 "password": password,
222 "ssl": args.tls,
223 "retry": retry
224 },
225 )
226
227 sentinels_list = random.choice(sentinels.sentinels).execute_command(
228 "sentinel sentinels master"
229 )
230
231 if len(sentinels_list) != 2:
232 raise Exception(
233 f"Sentinel list not correct. Expected 2, got {len(sentinels_list)}"
234 )
235
236 graph_0 = db_0.select_graph("test")
237
238 # Write some data to the DB
239 graph_0.query("CREATE (n:Person {name: 'Alice'})")
240
241 # Check if data was replicated
242 graph_1 = db_1.select_graph("test")
243
244 result = graph_1.ro_query("MATCH (n:Person) RETURN n")
245
246 if len(result.result_set) == 0:
247 raise Exception("Data was not replicated to the slave")
248
249 id_key = "sz" if args.resource_key == "single-Zone" else "mz"
250
251 logging.info(f"Triggering failover for node-{id_key}-0")
252 # Trigger failover
253 instance.trigger_failover(
254 replica_id=f"node-{id_key}-0",
255 wait_for_ready=False,
256 resource_id=instance.get_resource_id(f"node-{id_key}"),
257 )
258
259 promotion_completed = False
260 while not promotion_completed:
261 try:
262 graph = db_1.execute_command("info replication")
263 if "role:master" in graph:
264 promotion_completed = True
265 time.sleep(5)
266 except Exception as e:
267 logging.info("Promotion not completed yet")
268 time.sleep(5)
269
270 logging.info("Promotion completed")
271
272 # Check if data is still there
273 graph_1 = db_1.select_graph("test")
274
275 result = graph_1.query("MATCH (n:Person) RETURN n")
276
277 if len(result.result_set) == 0:
278 raise Exception("Data lost after first failover")
279
280 logging.info("Data persisted after first failover")
281
282 graph_1.query("CREATE (n:Person {name: 'Bob'})")
283
284 result = graph_1.query("MATCH (n:Person) RETURN n")
285
286 logging.info(f"result after bob: {result.result_set}")
287
288 # wait until the node 0 is ready
289 instance.wait_for_instance_status(timeout_seconds=600)
290
291 logging.info(f"Triggering failover for sentinel-{id_key}-0")
292 # Trigger sentinel failover
293 instance.trigger_failover(
294 replica_id=f"sentinel-{id_key}-0",
295 wait_for_ready=False,
296 resource_id=instance.get_resource_id(f"sentinel-{id_key}"),
297 )
298
299 graph_1 = db_1.select_graph("test")
300
301 result = graph_1.query("MATCH (n:Person) RETURN n")
302
303 if len(result.result_set) < 2:
304 raise Exception("Data lost after second failover")
305
306 logging.info("Data persisted after second failover")
307
308 # wait until the node 0 is ready
309 instance.wait_for_instance_status(timeout_seconds=600)
310
311 logging.info(f"Triggering failover for node-{id_key}-1")
312 # Trigger failover
313 instance.trigger_failover(
314 replica_id=f"node-{id_key}-1",
315 wait_for_ready=False,
316 resource_id=instance.get_resource_id(f"node-{id_key}"),
317 )
318
319 promotion_completed = False
320 while not promotion_completed:
321 try:
322 graph = db_0.execute_command("info replication")
323 if "role:master" in graph:
324 promotion_completed = True
325 time.sleep(5)
326 except Exception as e:
327 logging.info("Promotion not completed yet")
328 time.sleep(5)
329
330 logging.info("Promotion completed")
331
332 # Check if data is still there
333 graph_0 = db_0.select_graph("test")
334
335 result = graph_0.query("MATCH (n:Person) RETURN n")
336
337 if len(result.result_set) < 2:
338 logging.info(result.result_set)
339 raise Exception("Data lost after third failover")
340
341 logging.info("Data persisted after third failover")
342
343
344def test_stop_start(instance: OmnistrateFleetInstance, password: str):
345 """
346 Single Zone tests are the following:
347 1. Create a single zone instance
348 2. Write some data to the master node
349 3. Stop the master node
350 4. Make sure we can still connect and read the data
351 5. Start the master node
352 6. Make sure we can still connect and read the data
353 7. Delete the instance
354 """
355
356 resources = instance.get_connection_endpoints()
357 sentinel_resource = next(
358 (resource for resource in resources if resource["id"].startswith("sentinel-")),
359 None,
360 )
361 db = FalkorDB(
362 host=sentinel_resource["endpoint"],
363 port=sentinel_resource["ports"][0],
364 username="falkordb",
365 password=password,
366 ssl=args.tls,
367 )
368
369 graph = db.select_graph("test")
370
371 # Write some data to the DB
372 graph.query("CREATE (n:Person {name: 'Alice'})")
373
374 logging.info("Stopping node")
375
376 instance.stop(wait_for_ready=True)
377
378 logging.info("Instance stopped")
379
380 instance.start(wait_for_ready=True)
381
382 graph = db.select_graph("test")
383
384 result = graph.query("MATCH (n:Person) RETURN n")
385
386 if len(result.result_set) == 0:
387 raise Exception("Data lost after stop/start")
388
389 logging.info("Instance started")
390
391
392def test_zero_downtime(
393 thread_signal: threading.Event,
394 error_signal: threading.Event,
395 instance: OmnistrateFleetInstance,
396 ssl=False,
397):
398 """This function should test the ability to read and write while a memory update happens"""
399 try:
400 db = instance.create_connection(ssl=ssl, force_reconnect=True)
401
402 graph = db.select_graph("test_zero_downtime")
403
404 while not thread_signal.is_set():
405 # Write some data to the DB
406 graph.query("CREATE (n:Person {name: 'Alice'})")
407 graph.ro_query("MATCH (n:Person {name: 'Alice'}) RETURN n")
408
409 time.sleep(3)
410 except Exception as e:
411 logging.exception(e)
412 error_signal.set()
413 raise e
414
415
416if __name__ == "__main__":
417 test_replication()