Elffuss BraidHub

kikocis/falkordb-omnistrate public

main · 8.1 KiBRawPermalink
1import sys
2import signal
3from pathlib import Path
4from random import randbytes
5from redis import Redis
6from redis.backoff import ExponentialBackoff
7from redis.retry import Retry
8from redis.exceptions import (
9 ConnectionError,
10 TimeoutError
11)
12import threading
13
14
15
16file = Path(__file__).resolve()
17parent, root = file.parent, file.parents[1]
18sys.path.append(str(root))
19
20# Additionally remove the current file's directory from sys.path
21from contextlib import suppress
22
23with suppress(ValueError):
24 sys.path.remove(str(parent))
25
26import logging
27import time
28import os
29from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
30from omnistrate_tests.classes.omnistrate_fleet_api import OmnistrateFleetAPI
31import argparse
32
33parser = argparse.ArgumentParser()
34parser.add_argument("omnistrate_user")
35parser.add_argument("omnistrate_password")
36parser.add_argument("cloud_provider", choices=["aws", "gcp"])
37parser.add_argument("region")
38
39parser.add_argument(
40 "--subscription-id", required=False, default=os.getenv("SUBSCRIPTION_ID")
41)
42parser.add_argument("--ref-name", required=False, default=os.getenv("REF_NAME"))
43parser.add_argument("--service-id", required=True)
44parser.add_argument("--environment-id", required=True)
45parser.add_argument("--resource-key", required=True)
46parser.add_argument("--replica-id", required=True)
47
48
49parser.add_argument("--instance-name", required=True)
50parser.add_argument("--instance-description", required=False, default="test-standalone")
51parser.add_argument("--instance-type", required=True)
52parser.add_argument("--storage-size", required=False, default="30")
53parser.add_argument("--tls", action="store_true")
54parser.add_argument("--rdb-config", required=False, default="medium")
55parser.add_argument("--aof-config", required=False, default="always")
56parser.add_argument("--replica-count", required=False, default="2")
57
58
59parser.set_defaults(tls=False)
60args = parser.parse_args()
61
62instance: OmnistrateFleetInstance = None
63
64# Intercept exit signals so we can delete the instance before exiting
65def signal_handler(sig, frame):
66 if instance:
67 instance.delete(False)
68 sys.exit(0)
69signal.signal(signal.SIGINT, signal_handler)
70signal.signal(signal.SIGTERM, signal_handler)
71
72
73def test_add_remove_replica():
74 global instance
75
76 omnistrate = OmnistrateFleetAPI(
77 email=args.omnistrate_user,
78 password=args.omnistrate_password,
79 )
80
81 service = omnistrate.get_service(args.service_id)
82 product_tier = omnistrate.get_product_tier(
83 service_id=args.service_id,
84 environment_id=args.environment_id,
85 tier_name=args.ref_name,
86 )
87 service_model = omnistrate.get_service_model(
88 args.service_id, product_tier.service_model_id
89 )
90
91 logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
92
93 instance = omnistrate.instance(
94 service_id=args.service_id,
95 service_provider_id=service.service_provider_id,
96 service_key=service.key,
97 service_environment_id=args.environment_id,
98 service_environment_key=service.get_environment(args.environment_id).key,
99 service_model_key=service_model.key,
100 service_api_version="v1",
101 product_tier_key=product_tier.product_tier_key,
102 resource_key=args.resource_key,
103 subscription_id=args.subscription_id,
104 deployment_create_timeout_seconds=2400,
105 deployment_delete_timeout_seconds=2400,
106 deployment_failover_timeout_seconds=2400
107 )
108
109 try:
110 password = randbytes(16).hex()
111 instance.create(
112 wait_for_ready=True,
113 deployment_cloud_provider=args.cloud_provider,
114 deployment_region=args.region,
115 name=args.instance_name,
116 description=args.instance_description,
117 falkordb_user="falkordb",
118 falkordb_password=password,
119 nodeInstanceType=args.instance_type,
120 storageSize=args.storage_size,
121 enableTLS=args.tls,
122 RDBPersistenceConfig=args.rdb_config,
123 AOFPersistenceConfig=args.aof_config,
124 )
125
126 add_data(instance)
127
128 thread_signal = threading.Event()
129 error_signal = threading.Event()
130 thread = threading.Thread(
131 target=test_zero_downtime, args=(thread_signal, error_signal, instance, args.tls)
132 )
133
134 thread.start()
135
136 check_data(instance)
137
138 change_replica_count(instance, int(args.replica_count) + 1)
139
140 test_fail_over(instance)
141
142 change_replica_count(instance,int(args.replica_count))
143
144 check_data(instance)
145
146 thread_signal.set()
147 thread.join()
148
149 except Exception as e:
150 logging.exception(e)
151 instance.delete(False)
152 raise e
153
154 # Delete instance
155 instance.delete(False)
156
157 if error_signal.is_set():
158 raise ValueError("Test failed")
159 else:
160 logging.info("Test passed")
161
162
163def change_replica_count(instance: OmnistrateFleetInstance, new_replica_count: int):
164
165 logging.info(f"Changing replica count to {new_replica_count}")
166 instance.update_params(
167 numReplicas=new_replica_count,
168 wait_for_ready=True,
169 )
170
171def test_fail_over(instance: OmnistrateFleetInstance):
172 logging.info("Testing failover to the newly created replica")
173
174 endpoint = instance.get_cluster_endpoint()
175 password = instance.falkordb_password
176 id_key = "sz" if args.resource_key == "single-Zone" else "mz"
177 retry = Retry(ExponentialBackoff(base=3), retries=20)
178 try:
179 client = Redis(
180 host=f"{endpoint["endpoint"]}", port=endpoint['ports'][0],
181 username="falkordb",
182 password=password,
183 decode_responses=True,
184 ssl=args.tls,
185 retry=retry,
186 retry_on_error=[TimeoutError,ConnectionError,ConnectionRefusedError]
187 )
188 except Exception as e:
189 logging.exception("Failed to connect to Sentinel!")
190 logging.info(e)
191
192 tout = time.time() + 600
193 while True:
194 if time.time() > tout:
195 raise Exception(f"Failed to failover to node-{id_key}-2")
196 try:
197 time.sleep(5)
198 print(client.execute_command('SENTINEL FAILOVER master'))
199 time.sleep(5)
200 master = client.execute_command('SENTINEL MASTER master')[3]
201 if master.startswith(f"node-{id_key}-2"):
202 break
203 except Exception as e:
204 logging.info(e)
205 continue
206 time.sleep(15)
207 check_data(instance)
208
209def add_data(instance: OmnistrateFleetInstance):
210 """This function should retrieve the instance host and port for connection, write some data to the DB, then check that the data is there"""
211 logging.info('Added data ....')
212 # Get instance host and port
213 db = instance.create_connection(
214 ssl=args.tls,
215 )
216
217 graph = db.select_graph("test")
218
219 # Write some data to the DB
220 graph.query("CREATE (n:Person {name: 'Alice'})")
221
222 result = graph.query("MATCH (n:Person) RETURN n")
223
224 if len(result.result_set) == 0:
225 raise Exception("Data not found after write")
226
227
228def check_data(instance: OmnistrateFleetInstance):
229 print('Retrieving data ....')
230 # Get instance host and port
231 db = instance.create_connection(
232 ssl=args.tls,
233 force_reconnect=True,
234 retries=10
235 )
236
237 graph = db.select_graph("test")
238
239 result = graph.query("MATCH (n:Person) RETURN n")
240
241 if len(result.result_set) == 0:
242 raise Exception("Data did not persist after host count change")
243
244def test_zero_downtime(
245 thread_signal: threading.Event,
246 error_signal: threading.Event,
247 instance: OmnistrateFleetInstance,
248 ssl=False,
249):
250 """This function should test the ability to read and write while a memory update happens"""
251 try:
252 db = instance.create_connection(ssl=ssl, force_reconnect=True)
253
254 graph = db.select_graph("test")
255
256 while not thread_signal.is_set():
257 # Write some data to the DB
258 graph.query("CREATE (n:Person {name: 'Alice'})")
259 graph.ro_query("MATCH (n:Person {name: 'Alice'}) RETURN n")
260
261 time.sleep(3)
262 except Exception as e:
263 logging.exception(e)
264 error_signal.set()
265 raise e
266
267if __name__ == "__main__":
268 test_add_remove_replica()