Elffuss BraidHub

kikocis/falkordb-omnistrate public

main · 10.1 KiBRawPermalink
1import sys
2import signal
3from random import randbytes
4from pathlib import Path
5import threading
6
7
8file = Path(__file__).resolve()
9parent, root = file.parent, file.parents[1]
10sys.path.append(str(root))
11
12# Additionally remove the current file's directory from sys.path
13from contextlib import suppress
14
15with suppress(ValueError):
16 sys.path.remove(str(parent))
17
18import logging
19
20logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
21
22import time
23import os
24from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
25from omnistrate_tests.classes.omnistrate_fleet_api import OmnistrateFleetAPI
26from omnistrate_tests.classes.falkordb_cluster import FalkorDBCluster
27import argparse
28
29parser = argparse.ArgumentParser()
30parser.add_argument("omnistrate_user")
31parser.add_argument("omnistrate_password")
32parser.add_argument("cloud_provider", choices=["aws", "gcp"])
33parser.add_argument("region")
34
35parser.add_argument(
36 "--subscription-id", required=False, default=os.getenv("SUBSCRIPTION_ID")
37)
38parser.add_argument("--ref-name", required=False, default=os.getenv("REF_NAME"))
39parser.add_argument("--service-id", required=True)
40parser.add_argument("--environment-id", required=True)
41parser.add_argument("--resource-key", required=True)
42
43parser.add_argument("--instance-name", required=True)
44parser.add_argument("--instance-description", required=False, default="test-standalone")
45parser.add_argument("--instance-type", required=True)
46parser.add_argument("--storage-size", required=False, default="30")
47parser.add_argument("--tls", action="store_true")
48parser.add_argument("--rdb-config", required=False, default="medium")
49parser.add_argument("--aof-config", required=False, default="always")
50parser.add_argument("--host-count", required=False, default="6")
51parser.add_argument("--cluster-replicas", required=False, default="1")
52
53parser.add_argument("--ensure-mz-distribution", action="store_true")
54
55parser.set_defaults(tls=False)
56args = parser.parse_args()
57
58instance: OmnistrateFleetInstance = None
59
60current_host_count = int(args.host_count)
61
62
63# Intercept exit signals so we can delete the instance before exiting
64def signal_handler(sig, frame):
65 if instance:
66 instance.delete(False)
67 sys.exit(0)
68
69
70signal.signal(signal.SIGINT, signal_handler)
71signal.signal(signal.SIGTERM, signal_handler)
72
73
74def test_cluster_shards():
75 global instance
76
77 omnistrate = OmnistrateFleetAPI(
78 email=args.omnistrate_user,
79 password=args.omnistrate_password,
80 )
81
82 service = omnistrate.get_service(args.service_id)
83 product_tier = omnistrate.get_product_tier(
84 service_id=args.service_id,
85 environment_id=args.environment_id,
86 tier_name=args.ref_name,
87 )
88 service_model = omnistrate.get_service_model(
89 args.service_id, product_tier.service_model_id
90 )
91
92 logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
93
94 instance = omnistrate.instance(
95 service_id=args.service_id,
96 service_provider_id=service.service_provider_id,
97 service_key=service.key,
98 service_environment_id=args.environment_id,
99 service_environment_key=service.get_environment(args.environment_id).key,
100 service_model_key=service_model.key,
101 service_api_version="v1",
102 product_tier_key=product_tier.product_tier_key,
103 resource_key=args.resource_key,
104 subscription_id=args.subscription_id,
105 deployment_create_timeout_seconds=2400,
106 deployment_delete_timeout_seconds=2400,
107 deployment_failover_timeout_seconds=2400
108 )
109
110 try:
111 password = randbytes(16).hex()
112 instance.create(
113 wait_for_ready=True,
114 deployment_cloud_provider=args.cloud_provider,
115 deployment_region=args.region,
116 name=args.instance_name,
117 description=args.instance_description,
118 falkordb_user="falkordb",
119 falkordb_password=password,
120 nodeInstanceType=args.instance_type,
121 storageSize=args.storage_size,
122 enableTLS=args.tls,
123 RDBPersistenceConfig=args.rdb_config,
124 AOFPersistenceConfig=args.aof_config,
125 hostCount=args.host_count,
126 clusterReplicas=args.cluster_replicas,
127 )
128
129 add_data(instance)
130
131 # Start a new thread and signal for zero_downtime test
132 thread_signal = threading.Event()
133 error_signal = threading.Event()
134 thread = threading.Thread(
135 target=test_zero_downtime, args=(thread_signal, error_signal, instance, args.tls)
136 )
137 thread.start()
138
139 change_host_count(instance, int(args.host_count) + 2)
140
141 if args.ensure_mz_distribution:
142 test_ensure_mz_distribution(instance, password)
143
144 check_data(instance)
145
146 change_host_count(instance, int(args.host_count))
147
148 if args.ensure_mz_distribution:
149 test_ensure_mz_distribution(instance, password)
150
151 # Wait for the zero_downtime
152 thread_signal.set()
153 thread.join()
154
155 check_data(instance)
156 except Exception as e:
157 logging.exception(e)
158 instance.delete(False)
159 raise e
160
161 # Delete instance
162 instance.delete(False)
163
164 if error_signal.is_set():
165 raise ValueError("Test failed")
166 else:
167 logging.info("Test passed")
168
169
170def change_host_count(instance: OmnistrateFleetInstance, new_host_count: int):
171 global current_host_count
172
173 logging.info(f"Changing host count to {new_host_count}")
174 instance.update_params(
175 hostCount=new_host_count,
176 wait_for_ready=True,
177 )
178
179 current_host_count = new_host_count
180
181 instance_details = instance.get_instance_details()
182
183 params = (
184 instance_details["result_params"]
185 if "result_params" in instance_details
186 else None
187 )
188
189 if not params:
190 raise Exception("No result_params found in instance details")
191
192 host_count = int(params["hostCount"]) if "hostCount" in params else None
193
194 if not host_count:
195 raise Exception("No hostCount found in instance details")
196
197 if host_count != current_host_count:
198 raise Exception("Host count does not match new host count")
199
200
201def test_ensure_mz_distribution(instance: OmnistrateFleetInstance, password: str):
202 """This function should ensure that each shard is distributed across multiple availability zones"""
203
204 instance_details = instance.get_instance_details()
205 network_topology: dict = instance.get_network_topology(force_refresh=True)
206
207 params = (
208 instance_details["result_params"]
209 if "result_params" in instance_details
210 else None
211 )
212
213 if not params:
214 raise Exception("No result_params found in instance details")
215
216 cluster_replicas = (
217 int(params["clusterReplicas"]) if "clusterReplicas" in params else None
218 )
219
220 if not cluster_replicas:
221 raise Exception("No clusterReplicas found in instance details")
222
223 resource_key = next(
224 (k for [k, v] in network_topology.items() if v["resourceName"] == "cluster-mz"),
225 None,
226 )
227
228 resource = network_topology[resource_key]
229
230 nodes = resource["nodes"]
231
232 logging.debug(f"Nodes: {nodes}")
233
234 if len(nodes) == 0:
235 raise Exception("No nodes found in network topology")
236
237 if len(nodes) != current_host_count:
238 raise Exception(f"Host count does not match number of nodes. Current host count: {current_host_count}; Number of nodes: {len(nodes)}")
239
240 cluster = FalkorDBCluster(
241 host=resource["clusterEndpoint"],
242 port=resource["clusterPorts"][0],
243 username="falkordb",
244 password=password,
245 ssl=params["enableTLS"] == "true" if "enableTLS" in params else False,
246 )
247
248 groups = cluster.groups(cluster_replicas)
249
250 for group in groups:
251 group_azs = set()
252 for node in group:
253 omnistrateNode = next(
254 (n for n in nodes if n["endpoint"] == node.hostname), None
255 )
256 if not omnistrateNode:
257 logging.warning(f"Node {node.hostname} not found in network topology")
258 continue
259
260 group_azs.add(omnistrateNode["availabilityZone"])
261
262 if len(group_azs) == 1:
263 raise Exception(
264 "Group is not distributed across multiple availability zones"
265 )
266
267 logging.info(
268 f"Group {group} is distributed across availability zones {group_azs}"
269 )
270
271 logging.info("Shards are distributed across multiple availability zones")
272
273
274def add_data(instance: OmnistrateFleetInstance):
275 """This function should retrieve the instance host and port for connection, write some data to the DB, then check that the data is there"""
276
277 # Get instance host and port
278 db = instance.create_connection(
279 ssl=args.tls,
280 )
281
282 graph = db.select_graph("test")
283
284 # Write some data to the DB
285 graph.query("CREATE (n:Person {name: 'Alice'})")
286
287 result = graph.query("MATCH (n:Person) RETURN n")
288
289 if len(result.result_set) == 0:
290 raise Exception("Data not found after write")
291
292
293def check_data(instance: OmnistrateFleetInstance):
294
295 # Get instance host and port
296 db = instance.create_connection(
297 ssl=args.tls,
298 )
299
300 graph = db.select_graph("test")
301
302 result = graph.query("MATCH (n:Person) RETURN n")
303
304 if len(result.result_set) == 0:
305 raise Exception("Data did not persist after host count change")
306
307
308def test_zero_downtime(
309 thread_signal: threading.Event,
310 error_signal: threading.Event,
311 instance: OmnistrateFleetInstance,
312 ssl=False,
313):
314 """This function should test the ability to read and write while a memory update happens"""
315 try:
316 db = instance.create_connection(ssl=ssl, force_reconnect=True)
317
318 graph = db.select_graph("test")
319
320 while not thread_signal.is_set():
321 # Write some data to the DB
322 graph.query("CREATE (n:Person {name: 'Alice'})")
323 graph.ro_query("MATCH (n:Person {name: 'Alice'}) RETURN n")
324
325 time.sleep(3)
326 except Exception as e:
327 logging.exception(e)
328 error_signal.set()
329 raise e
330
331
332if __name__ == "__main__":
333 test_cluster_shards()