Elffuss BraidHub

kikocis/falkordb-omnistrate public

Merge pull request #101 from FalkorDB/89-cluster-test-addremove-cluster-replicas

89 cluster test addremove cluster replicas
Changeset82562fb24d6ccd5d8391a47d046c8c9045287494cb3d4261b444f0bfb5c38485
AuthorDudi <16744955+dudizimber@users.noreply.github.com> · 2024-08-26 16:46 +03:00
CommitterGitHub <noreply@github.com> · 2024-08-26 16:46 +03:00
Parents355cc9c1a123, f15a31e25d87

Browse the files at this changeset

16 files changed

modified .github/workflows/build-test-image.yaml +22 −2
@@ -298,7 +298,7 @@
298298 subscriptionId: sub-GJPV3NoNC0
299299 serviceId: ${{ vars.OMNISTRATE_INTERNAL_SERVICE_ID }}
300300 environmentId: ${{ vars.OMNISTRATE_INTERNAL_DEV_ENVIRONMENT}}
301- extraParams: "--resource-key 'cluster-Single-Zone' --replica-id 'cluster-sz-0' --instance-name 'test-cluster-sz-shards' --instance-description 'test-cluster-sz-shards' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1'"
301+ extraParams: "--resource-key 'cluster-Single-Zone' --instance-name 'test-cluster-sz-shards' --instance-description 'test-cluster-sz-shards' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1'"
302302 - name: PRO/ClusterMultiZone - GCP/us-central1 - Add/Remove Shards
303303 if: "true"
304304 testFile: test_cluster_shards.py
@@ -308,7 +308,27 @@
308308 subscriptionId: sub-GJPV3NoNC0
309309 serviceId: ${{ vars.OMNISTRATE_INTERNAL_SERVICE_ID }}
310310 environmentId: ${{ vars.OMNISTRATE_INTERNAL_DEV_ENVIRONMENT}}
311- extraParams: "--resource-key 'cluster-Multi-Zone' --replica-id 'cluster-mz-0' --instance-name 'test-cluster-mz-shards' --instance-description 'test-cluster-mz-shards' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1' --ensure-mz-distribution"
311+ extraParams: "--resource-key 'cluster-Multi-Zone' --instance-name 'test-cluster-mz-shards' --instance-description 'test-cluster-mz-shards' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1' --ensure-mz-distribution"
312+ - name: PRO/ClusterSingleZone - GCP/us-central1 - Add/Remove Replicas
313+ if: "true"
314+ testFile: test_cluster_replicas.py
315+ tierName: pro-${{ contains(github.ref, 'refs/tags/v') && 'main' || github.ref_name }}
316+ cloudProvider: gcp
317+ cloudRegion: us-central1
318+ subscriptionId: sub-GJPV3NoNC0
319+ serviceId: ${{ vars.OMNISTRATE_INTERNAL_SERVICE_ID }}
320+ environmentId: ${{ vars.OMNISTRATE_INTERNAL_DEV_ENVIRONMENT}}
321+ extraParams: "--resource-key 'cluster-Single-Zone' --instance-name 'test-cluster-sz-replicas' --instance-description 'test-cluster-sz-replicas' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1' --shards '3'"
322+ - name: PRO/ClusterMultiZone - GCP/us-central1 - Add/Remove Replicas
323+ if: "true"
324+ testFile: test_cluster_replicas.py
325+ tierName: pro-${{ contains(github.ref, 'refs/tags/v') && 'main' || github.ref_name }}
326+ cloudProvider: gcp
327+ cloudRegion: us-central1
328+ subscriptionId: sub-GJPV3NoNC0
329+ serviceId: ${{ vars.OMNISTRATE_INTERNAL_SERVICE_ID }}
330+ environmentId: ${{ vars.OMNISTRATE_INTERNAL_DEV_ENVIRONMENT}}
331+ extraParams: "--resource-key 'cluster-Multi-Zone' --instance-name 'test-cluster-mz-replicas' --instance-description 'test-cluster-mz-replicas' --instance-type 'e2-custom-4-8192' --storage-size '30' --rdb-config 'medium' --aof-config 'always' --host-count '6' --cluster-replicas '1' --shards '3' --ensure-mz-distribution"
312332
313333 steps:
314334 - name: Checkout
modified falkordb-cluster-rebalance/src/falkordb_cluster.py +32 −12
@@ -2,6 +2,7 @@
22 from time import sleep, time
33 import subprocess
44 from datetime import datetime
5+import logging
56
67
78 class FalkorDBClusterNode:
@@ -58,6 +59,14 @@
5859 else None
5960 )
6061
62+ @property
63+ def is_master(self) -> bool:
64+ return self.mode == "master"
65+
66+ @property
67+ def is_slave(self) -> bool:
68+ return self.mode == "slave"
69+
6170 @staticmethod
6271 def from_dict(key: str, val: dict) -> "FalkorDBClusterNode":
6372 return FalkorDBClusterNode(
@@ -94,9 +103,15 @@
94103 for key, val in self.client.cluster_nodes().items()
95104 ]
96105 self.sort()
97- print(f"{datetime.now()}: Cluster refreshed: {self}")
106+ logging.info(f"{datetime.now()}: Cluster refreshed: {self}")
98107 return self
99108
109+ def is_ready(self) -> bool:
110+ # Check cluster status
111+ cluster_state = self.client.cluster_info()["cluster_state"]
112+ logging.info(f"{datetime.now()}: Cluster state: {cluster_state}")
113+ return cluster_state == "ok"
114+
100115 def is_connected(self) -> bool:
101116 return all(node.connected for node in self.nodes)
102117
@@ -108,7 +123,7 @@
108123 text = "FalkorDBCluster:\n"
109124
110125 for node in self.nodes:
111- if node.mode == "master":
126+ if node.is_master:
112127 text += f"Master: {node.idx} - {node.id} - {node.slots}\n"
113128 text += "Slaves:\n" + "\n".join(
114129 f" {slave.idx} - {slave.id}"
@@ -135,11 +150,11 @@
135150 return [
136151 node
137152 for node in self.nodes
138- if node.mode == "slave" and self.get_node_by_id(node.master_id) is None
153+ if node.is_slave and self.get_node_by_id(node.master_id) is None
139154 ]
140155
141156 def get_masters(self) -> list[FalkorDBClusterNode]:
142- return [node for node in self.nodes if node.mode == "master"]
157+ return [node for node in self.nodes if node.is_master]
143158
144159 def get_slaves_from_master(self, master_id: str) -> list[FalkorDBClusterNode]:
145160 return [node for node in self.nodes if node.master_id == master_id]
@@ -167,12 +182,12 @@
167182 new_master_node.to_cluster_node(), old_master_id
168183 )
169184
170- print(
185+ logging.info(
171186 f"{datetime.now()}: Replicate {new_master_node} to {old_master_node} at: {res}"
172187 )
173188
174189 self._wait_for_condition(
175- lambda: self.get_node_by_id(new_master_id).mode == "slave"
190+ lambda: self.get_node_by_id(new_master_id).is_slave
176191 and self.get_node_by_id(new_master_id).master_id == old_master_id,
177192 timeout,
178193 "Timed out waiting for the new master to become a slave",
@@ -182,10 +197,10 @@
182197
183198 res = self.client.cluster_failover(new_master_node.to_cluster_node())
184199
185- print(f"{datetime.now()}: Failover {old_master_node}: {res}")
200+ logging.info(f"{datetime.now()}: Failover {old_master_node}: {res}")
186201
187202 self._wait_for_condition(
188- lambda: self.get_node_by_id(old_master_id).mode == "slave"
203+ lambda: self.get_node_by_id(old_master_id).is_slave
189204 and self.get_node_by_id(old_master_id).master_id == new_master_id,
190205 timeout,
191206 "Timed out waiting for the old master to become a slave",
@@ -213,10 +228,12 @@
213228
214229 res = self.client.cluster_replicate(slave_node.to_cluster_node(), new_master_id)
215230
216- print(f"{datetime.now()}: Replicate {slave_node} to {new_master_node}: {res}")
231+ logging.info(
232+ f"{datetime.now()}: Replicate {slave_node} to {new_master_node}: {res}"
233+ )
217234
218235 self._wait_for_condition(
219- lambda: self.get_node_by_id(slave_id).mode == "slave"
236+ lambda: self.get_node_by_id(slave_id).is_slave
220237 and self.get_node_by_id(slave_id).master_id == new_master_id,
221238 180,
222239 "Timed out waiting for the slave to become a slave",
@@ -226,7 +243,7 @@
226243
227244 slot_count = 16384 // shards
228245
229- print(f"Reshard to {slot_count} slots. New node: {new_node.id}")
246+ logging.info(f"Reshard to {slot_count} slots. New node: {new_node.id}")
230247 res = subprocess.call(
231248 [
232249 "redis-cli",
@@ -248,10 +265,13 @@
248265 ]
249266 )
250267
251- print(f"Reshard result: {res}")
268+ logging.info(f"Reshard result: {res}")
252269
253270 self._wait_for_condition(
254271 lambda: all(len(node.slots) > 0 for node in self.get_masters()),
255272 180,
256273 "Timed out waiting for all nodes to have the correct number of slots",
257274 )
275+
276+ def forget_node(self, node_id: str):
277+ self.client.execute_command("CLUSTER FORGET", node_id)
modified falkordb-cluster-rebalance/src/main.py +108 −43
@@ -5,6 +5,7 @@
55 import redis
66 import threading
77 from simple_http_server import route, server, HttpError
8+import logging
89
910
1011 def _get_admin_pass():
@@ -12,16 +13,17 @@
1213 Check if the password exists in the adminpassword file,\n
1314 if it does not, take the pass from the ADMIN_PASSWORD variable.
1415 """
15- admin_password = os.getenv('ADMIN_PASSWORD')
16+ admin_password = os.getenv("ADMIN_PASSWORD")
1617 if admin_password:
1718 return admin_password
18- secret_path = '/run/secrets/adminpassword'
19+ secret_path = "/run/secrets/adminpassword"
1920 try:
2021 with open(secret_path) as f:
2122 return f.read().strip() # Strip any extra whitespace or newlines
2223 except FileNotFoundError:
2324 raise FileNotFoundError(f"Secret file '{secret_path}' does not exist.")
2425
26+
2527 HEALTHCHECK_PORT = os.getenv("HEALTHCHECK_PORT", "8081")
2628 ADMIN_PASSWORD = _get_admin_pass()
2729 TLS = os.getenv("TLS", "false") == "true"
@@ -31,6 +33,8 @@
3133 IS_MULTI_ZONE = os.getenv("IS_MULTI_ZONE", "0") == "1"
3234 EXTERNAL_DNS_SUFFIX = os.getenv("EXTERNAL_DNS_SUFFIX")
3335
36+logging.basicConfig(level=logging.DEBUG if DEBUG else logging.INFO)
37+
3438 MIN_HOST_COUNT = 6
3539 MIN_MASTER_COUNT = 3
3640 MIN_SLAVE_COUNT = 3
@@ -41,25 +45,61 @@
4145 healthcheck_ok = False
4246
4347
44-def _handle_too_many_masters(cluster: FalkorDBCluster):
48+def _handle_too_many_masters(cluster: FalkorDBCluster, expected_masters: int):
4549 # Choose one master to become slave from another master that doesn't have enough slaves
46- extra_masters = [
47- master
48- for master in cluster.get_masters()
49- if len(cluster.get_slaves_from_master(master.id)) < CLUSTER_REPLICAS
50+ sorted_masters: list[tuple[FalkorDBClusterNode, int]] = []
51+ for extra_master in cluster.get_masters():
52+ if len(extra_master.slots) > 0:
53+ continue
54+ sorted_masters.append(
55+ (extra_master, cluster.get_slaves_from_master(extra_master.id))
56+ )
57+
58+ print(
59+ f"Too many masters: expected_masters: {expected_masters}\nsorted_masters: {sorted_masters}"
60+ )
61+ sorted_masters = sorted(sorted_masters, key=lambda x: len(x[1]))
62+
63+ # Select the masters with the least slaves
64+ extra_masters: list[tuple[FalkorDBClusterNode, int]] = sorted_masters[
65+ : int(len(sorted_masters) - expected_masters)
5066 ]
5167
5268 if len(extra_masters) == 0:
53- print("No extra masters to relocate")
69+ logging.info("No extra masters to handle")
5470 return
5571
5672 if len(extra_masters) == 1:
57- print("Only one extra master to relocate. Skipping...")
73+ logging.info("Only one extra master to handle. Skipping...")
5874 return
5975
6076 if len(extra_masters) > 1:
61- print(f"{len(extra_masters)} extra masters to relocate.")
62- cluster.relocate_slave(extra_masters[1].id, extra_masters[0].id)
77+ logging.info(f"{len(extra_masters)} extra masters to handle.")
78+ groups = cluster.groups(CLUSTER_REPLICAS)
79+ extra_master = extra_masters[0][0]
80+ logging.info(f"Extra master: {extra_master}")
81+ extra_master_group = next(
82+ (group for group in groups if extra_master in group),
83+ None,
84+ )
85+ group_master = next(
86+ (node for node in extra_master_group if node.is_master),
87+ None,
88+ )
89+ if group_master is None:
90+ logging.info(f"Group has no master. Finding another group...")
91+ for group in groups:
92+ if (
93+ len([node for node in group if node.is_slave]) < CLUSTER_REPLICAS
94+ and next((node for node in group if node.is_master), None)
95+ is not None
96+ ):
97+ group_master = next(
98+ (node for node in group if node.is_master),
99+ )
100+ logging.info(f"Found group master: {group_master}")
101+ break
102+ cluster.relocate_slave(extra_master.id, group_master.id)
63103 return main()
64104
65105
@@ -73,20 +113,20 @@
73113
74114 for i, group in enumerate(groups):
75115 if node in group:
76- print(f"Skipping group {i}. Node {node.id} is already in this group")
116+ logging.info(f"Skipping group {i}. Node {node.id} is already in this group")
77117 continue
78- if not any(n.mode == "master" for n in group):
118+ if not any(n.is_master for n in group):
79119 suitable_relocation_node = group[0]
80120 break
81121 else:
82- print(f"Cannot relocate master {node}, no suitable node found")
122+ logging.info(f"Cannot relocate master {node}, no suitable node found")
83123 return
84124
85- print(f"Relocating master {node} to {suitable_relocation_node} in group {i}")
125+ logging.info(f"Relocating master {node} to {suitable_relocation_node} in group {i}")
86126
87127 cluster.relocate_master(node.id, suitable_relocation_node.id)
88128
89- print(f"Master {node} relocated to {suitable_relocation_node}")
129+ logging.info(f"Master {node} relocated to {suitable_relocation_node}")
90130
91131 return main()
92132
@@ -99,14 +139,33 @@
99139 group_slaves: list[FalkorDBClusterNode],
100140 ):
101141
102- print(f"Slave {slave} has master from different group: {slave_master}")
142+ logging.info(f"Slave {slave} has master from different group: {slave_master}")
103143 # If there's a master in the same group with less replicas than expected, relocate the slave to that master
104144 if len(group_slaves) < CLUSTER_REPLICAS:
105145 cluster.relocate_slave(slave.id, group_master.id)
106- print(f"Slave {slave} relocated to {group_master}")
146+ logging.info(f"Slave {slave} relocated to {group_master}")
107147 return main()
108148
109149
150+def _handle_cluster_not_fully_connected(cluster: FalkorDBCluster):
151+ # If:
152+ # 1. the nodes that are not connected are all masters
153+ # 2. they don't have slots assigned
154+ # 3. and their index is > 6
155+ # Then delete them
156+ for node in cluster.nodes:
157+ if (
158+ not node.connected
159+ and node.idx > 6
160+ and node.is_master
161+ and len(node.slots) == 0
162+ ):
163+ logging.info(f"Deleting master {node}")
164+ cluster.forget_node(node.id)
165+
166+ return main()
167+
168+
110169 def main():
111170 cluster = FalkorDBCluster(
112171 host=NODE_0_HOST,
@@ -116,33 +175,37 @@
116175 )
117176 # slots = client.cluster_slots()
118177 if len(cluster) < MIN_HOST_COUNT:
119- print("Not enough hosts to rebalance")
178+ logging.info("Not enough hosts to rebalance")
120179 return
121180
122- if not cluster.is_connected():
123- print("Cluster is not fully connected")
124- return
181+ if not cluster.is_connected() and not cluster.is_ready():
182+ logging.info("Cluster is not fully connected")
183+ return _handle_cluster_not_fully_connected(cluster)
125184
126185 expected_shards = len(cluster) / (CLUSTER_REPLICAS + 1)
127186 if expected_shards % 1 != 0:
128- print(f"Cannot rebalance, expected shards is not an integer: {expected_shards}")
187+ logging.info(
188+ f"Cannot rebalance, expected shards is not an integer: {expected_shards}"
189+ )
129190 return
130191
192+ expected_shards = int(expected_shards)
193+
131194 if len(cluster) % (CLUSTER_REPLICAS + 1) != 0:
132- print(
195+ logging.info(
133196 f"Cannot rebalance, number of nodes does not match the shards. Nodes: {len(cluster)}, expected_shards: {expected_shards}"
134197 )
135198 return
136199
137200 invalid_slaves = cluster.get_slaves_with_invalid_masters()
138201 if len(invalid_slaves) > 0:
139- print(f"Invalid slaves: {invalid_slaves}")
202+ logging.info(f"Invalid slaves: {invalid_slaves}")
140203
141204 expected_masters = expected_shards
142205
143206 if len(cluster.get_masters()) > expected_masters:
144- print(f"Too many masters: {len(cluster.get_masters())}")
145- return _handle_too_many_masters(cluster)
207+ logging.info(f"Too many masters: {len(cluster.get_masters())}")
208+ return _handle_too_many_masters(cluster, expected_masters)
146209
147210 for s in range(0, int(expected_shards)):
148211 group_start_idx = s * (CLUSTER_REPLICAS + 1)
@@ -152,40 +215,42 @@
152215 (
153216 node
154217 for node in cluster.nodes[group_start_idx:group_end_idx]
155- if node.mode == "master"
218+ if node.is_master
156219 ),
157220 None,
158221 )
159222
160223 if group_master is None:
161- print(f"Group {s} has no master")
224+ logging.info(f"Group {s} has no master")
162225 continue
163226
164227 group_slaves: list[FalkorDBClusterNode] = [
165228 node
166229 for node in cluster.nodes[group_start_idx:group_end_idx]
167- if node.mode == "slave" and node.master_id == group_master.id
230+ if node.is_slave and node.master_id == group_master.id
168231 ]
169232
170233 for i in range(group_start_idx, group_end_idx):
171234 node = cluster.nodes[i]
172235
173- if node.mode == "master":
236+ if node.is_master:
174237 if group_master is None or group_master == node:
175238 group_master = node
176239 if len(group_master.slots) == 0:
177- print(f"Master {group_master} has no slots")
240+ logging.info(f"Master {group_master} has no slots")
178241 cluster.rebalance_slots(group_master, expected_shards)
179242 return main()
180243 elif IS_MULTI_ZONE:
181- print(f"Group {s} has more than 1 master: {group_master}, {node}")
244+ logging.info(
245+ f"Group {s} has more than 1 master: {group_master}, {node}"
246+ )
182247 return _relocate_master(cluster, node)
183248 else:
184249 slave_master = cluster.get_node_by_id(node.master_id)
185250 if slave_master is None:
186- print(f"Slave {node} has no master")
251+ logging.info(f"Slave {node} has no master")
187252 if slave_master.mode != "master":
188- print(f"Slave {node} has invalid master: {slave_master}")
253+ logging.info(f"Slave {node} has invalid master: {slave_master}")
189254
190255 # Check if master belongs to the same group as slave
191256 if IS_MULTI_ZONE and (
@@ -196,20 +261,20 @@
196261 cluster, node, slave_master, group_master, group_slaves
197262 )
198263
199- if IS_MULTI_ZONE and len(group_slaves) != CLUSTER_REPLICAS:
200- print(f"Group {s} has invalid number of slaves: {group_slaves}")
264+ if len(group_slaves) != CLUSTER_REPLICAS:
265+ logging.info(f"Group {s} has invalid number of slaves: {group_slaves}")
201266
202- print(f"Cluster after: {cluster}")
267+ logging.info(f"Cluster after: {cluster}")
203268
204269
205270 def _node_resolved():
206- print(f"Checking node connection: {NODE_0_HOST}:{NODE_PORT}")
271+ logging.info(f"Checking node connection: {NODE_0_HOST}:{NODE_PORT}")
207272 # Resolve hostnames to IPs
208273 try:
209274 socket.gethostbyname(NODE_0_HOST)
210275 except Exception as e:
211276 if DEBUG:
212- print(f"Error resolving host: {e}")
277+ logging.error(f"Error resolving host: {e}")
213278 return False
214279
215280 # ping node
@@ -221,7 +286,7 @@
221286 return True
222287 except Exception as e:
223288 if DEBUG:
224- print(f"Error pinging node: {e}")
289+ logging.error(f"Error pinging node: {e}")
225290 return False
226291
227292
@@ -238,7 +303,7 @@
238303 main()
239304 healthcheck_ok = True
240305 except Exception as e:
241- print(f"Error: {e}")
306+ logging.exception(f"Error: {e}")
242307 healthcheck_ok = False
243308
244309
@@ -254,4 +319,4 @@
254319
255320 server.start(port=int(HEALTHCHECK_PORT))
256321
257- print("Server started")
322+ logging.info("Server started")
modified falkordb-cluster/cluster-entrypoint.sh +8 −2
@@ -197,7 +197,13 @@
197197
198198 redis-cli --cluster add-node $NODE_HOST:$NODE_PORT $cluster_host:$NODE_PORT $AUTH_CONNECTION_STRING $TLS_CONNECTION_STRING
199199
200- touch /data/cluster_initialized
200+ # If it was not successful, retry after 10 seconds
201+ if [[ $? -ne 0 ]]; then
202+ echo "Failed to join cluster. Retrying in 10 seconds"
203+ sleep 10
204+ join_cluster
205+ fi
206+
201207 }
202208
203209 run_node() {
@@ -253,7 +259,7 @@
253259 # Create cluster
254260 echo "Creating cluster"
255261 create_cluster
256-elif [[ $NODE_INDEX -gt $CLUSTER_REPLICAS && ! -f "/data/cluster_initialized" ]]; then
262+elif [[ $NODE_INDEX -gt 5 ]]; then
257263 # Join cluster
258264 echo "Joining cluster"
259265 join_cluster
modified omnistrate.free.yaml +14 −8
@@ -1,19 +1,25 @@
11 version: "3.9"
22
33 x-omnistrate-service-plan:
4- name: 'FalkorDB Free'
5- tenancyType: 'OMNISTRATE_MULTI_TENANCY'
4+ name: "FalkorDB Free"
5+ tenancyType: "OMNISTRATE_MULTI_TENANCY"
66 deployment:
77 hostedDeployment:
8- GcpProjectId: '$GcpProjectId'
9- GcpProjectNumber: '$GcpProjectNumber'
10- GcpServiceAccountEmail: '$GcpServiceAccountEmail'
8+ GcpProjectId: "$GcpProjectId"
9+ GcpProjectNumber: "$GcpProjectNumber"
10+ GcpServiceAccountEmail: "$GcpServiceAccountEmail"
11+
12+x-internal-integrations:
13+ logs:
14+ provider: native
15+ metrics:
16+ provider: native
1117
1218 x-omnistrate-integrations:
1319 - omnistrateMetrics:
1420
1521 services:
16-# Free
22+ # Free
1723 Free:
1824 x-omnistrate-mode-internal: false
1925 image: omnistrate/noop
@@ -159,10 +165,10 @@
159165 deploy:
160166 resources:
161167 limits:
162- cpus: '0.5'
168+ cpus: "0.5"
163169 memory: 100M
164170 reservations:
165- cpus: '0.1'
171+ cpus: "0.1"
166172 memory: 100M
167173
168174 secrets:
modified omnistrate.pro.yaml +7 −7
@@ -29,6 +29,12 @@
2929 ingressPort: 26379
3030 backendPort: 26379
3131
32+x-internal-integrations:
33+ logs:
34+ provider: native
35+ metrics:
36+ provider: native
37+
3238 x-redisMetrics: &metrics
3339 prometheusEndpoint: "http://localhost:9121/metrics"
3440 metrics:
@@ -210,10 +216,6 @@
210216 cluster-mz:
211217 <<: *metrics
212218
213-
214-
215-
216-
217219 x-rebalanceparam: &rebalanceparam
218220 x-omnistrate-api-params:
219221 - key: clusterReplicas
@@ -235,7 +237,6 @@
235237 export: true
236238 defaultValue: "false"
237239
238-
239240 x-clusterparam: &clusterparam
240241 x-omnistrate-api-params:
241242 - key: hostCount
@@ -317,7 +318,6 @@
317318 - "everysec"
318319 - "always"
319320
320-
321321 services:
322322 # Standalone
323323
@@ -2100,4 +2100,4 @@
21002100 adminpasspath:
21012101 file: ./secrets/adminpassword
21022102 falkordbpasspath:
2103- file: ./secrets/falkordbpassword
No newline at the end of the file
2103+ file: ./secrets/falkordbpassword
modified omnistrate_tests/classes/falkordb_cluster.py +24 −12
@@ -3,6 +3,10 @@
33 import subprocess
44 from datetime import datetime
55
6+import logging
7+
8+logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
9+
610
711 class FalkorDBClusterNode:
812
@@ -58,6 +62,14 @@
5862 else None
5963 )
6064
65+ @property
66+ def is_master(self) -> bool:
67+ return self.mode == "master"
68+
69+ @property
70+ def is_slave(self) -> bool:
71+ return self.mode == "slave"
72+
6173 @staticmethod
6274 def from_dict(key: str, val: dict) -> "FalkorDBClusterNode":
6375 return FalkorDBClusterNode(
@@ -99,7 +111,7 @@
99111 for key, val in self.client.cluster_nodes().items()
100112 ]
101113 self.sort()
102- print(f"{datetime.now()}: Cluster refreshed: {self}")
114+ logging.info(f"{datetime.now()}: Cluster refreshed: {self}")
103115 return self
104116
105117 def is_connected(self) -> bool:
@@ -113,7 +125,7 @@
113125 text = "FalkorDBCluster:\n"
114126
115127 for node in self.nodes:
116- if node.mode == "master":
128+ if node.is_master:
117129 text += f"Master: {node.idx} - {node.id} - {node.slots}\n"
118130 text += "Slaves:\n" + "\n".join(
119131 f" {slave.idx} - {slave.id}"
@@ -140,11 +152,11 @@
140152 return [
141153 node
142154 for node in self.nodes
143- if node.mode == "slave" and self.get_node_by_id(node.master_id) is None
155+ if node.is_slave and self.get_node_by_id(node.master_id) is None
144156 ]
145157
146158 def get_masters(self) -> list[FalkorDBClusterNode]:
147- return [node for node in self.nodes if node.mode == "master"]
159+ return [node for node in self.nodes if node.is_master]
148160
149161 def get_slaves_from_master(self, master_id: str) -> list[FalkorDBClusterNode]:
150162 return [node for node in self.nodes if node.master_id == master_id]
@@ -172,12 +184,12 @@
172184 new_master_node.to_cluster_node(), old_master_id
173185 )
174186
175- print(
187+ logging.info(
176188 f"{datetime.now()}: Replicate {new_master_node} to {old_master_node} at: {res}"
177189 )
178190
179191 self._wait_for_condition(
180- lambda: self.get_node_by_id(new_master_id).mode == "slave"
192+ lambda: self.get_node_by_id(new_master_id).is_slave
181193 and self.get_node_by_id(new_master_id).master_id == old_master_id,
182194 timeout,
183195 "Timed out waiting for the new master to become a slave",
@@ -187,10 +199,10 @@
187199
188200 res = self.client.cluster_failover(new_master_node.to_cluster_node())
189201
190- print(f"{datetime.now()}: Failover {old_master_node}: {res}")
202+ logging.info(f"{datetime.now()}: Failover {old_master_node}: {res}")
191203
192204 self._wait_for_condition(
193- lambda: self.get_node_by_id(old_master_id).mode == "slave"
205+ lambda: self.get_node_by_id(old_master_id).is_slave
194206 and self.get_node_by_id(old_master_id).master_id == new_master_id,
195207 timeout,
196208 "Timed out waiting for the old master to become a slave",
@@ -218,10 +230,10 @@
218230
219231 res = self.client.cluster_replicate(slave_node.to_cluster_node(), new_master_id)
220232
221- print(f"{datetime.now()}: Replicate {slave_node} to {new_master_node}: {res}")
233+ logging.info(f"{datetime.now()}: Replicate {slave_node} to {new_master_node}: {res}")
222234
223235 self._wait_for_condition(
224- lambda: self.get_node_by_id(slave_id).mode == "slave"
236+ lambda: self.get_node_by_id(slave_id).is_slave
225237 and self.get_node_by_id(slave_id).master_id == new_master_id,
226238 180,
227239 "Timed out waiting for the slave to become a slave",
@@ -231,7 +243,7 @@
231243
232244 slot_count = 16384 // shards
233245
234- print(f"Reshard to {slot_count} slots. New node: {new_node.id}")
246+ logging.info(f"Reshard to {slot_count} slots. New node: {new_node.id}")
235247 res = subprocess.call(
236248 [
237249 "redis-cli",
@@ -253,7 +265,7 @@
253265 ]
254266 )
255267
256- print(f"Reshard result: {res}")
268+ logging.info(f"Reshard result: {res}")
257269
258270 self._wait_for_condition(
259271 lambda: all(len(node.slots) > 0 for node in self.get_masters()),
modified omnistrate_tests/classes/omnistrate_fleet_api.py +10 −4
@@ -7,6 +7,10 @@
77 OmnistrateTierVersion,
88 )
99
10+import logging
11+
12+logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
13+
1014
1115 class OmnistrateFleetAPI:
1216
@@ -19,7 +23,7 @@
1923
2024 def handle_response(self, response, message):
2125 if response.status_code >= 300 or response.status_code < 200:
22- print(f"{message}: {response.text}")
26+ logging.error(f"{message}: {response.text}")
2327 raise Exception(f"{message}")
2428
2529 def get_token(self):
@@ -131,10 +135,15 @@
131135 deployment_create_timeout_seconds: int = None,
132136 deployment_delete_timeout_seconds: int = None,
133137 deployment_failover_timeout_seconds: int = None,
138+ deployment_update_timeout_seconds: int = None,
134139 ):
135140 return (
136141 omnistrate_tests.classes.omnistrate_fleet_instance.OmnistrateFleetInstance(
137142 self,
143+ deployment_create_timeout_seconds,
144+ deployment_delete_timeout_seconds,
145+ deployment_failover_timeout_seconds,
146+ deployment_update_timeout_seconds,
138147 service_id,
139148 service_provider_id,
140149 service_key,
@@ -145,8 +154,5 @@
145154 product_tier_key,
146155 resource_key,
147156 subscription_id,
148- deployment_create_timeout_seconds,
149- deployment_delete_timeout_seconds,
150- deployment_failover_timeout_seconds,
151157 )
152158 )
modified omnistrate_tests/classes/omnistrate_fleet_instance.py +70 −45
@@ -1,6 +1,10 @@
11 from falkordb import FalkorDB
22 import json
33 import os
4+import logging
5+
6+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
7+
48 import time
59 import random
610 import string
@@ -26,6 +30,10 @@
2630 def __init__(
2731 self,
2832 fleet_api: omnistrate_tests.classes.omnistrate_fleet_api.OmnistrateFleetAPI,
33+ deployment_create_timeout_seconds: int | None,
34+ deployment_delete_timeout_seconds: int | None,
35+ deployment_failover_timeout_seconds: int | None,
36+ deployment_update_timeout_seconds: int | None,
2937 service_id: str = os.getenv("SERVICE_ID"),
3038 service_provider_id: str = os.getenv("SERVICE_PROVIDER_ID"),
3139 service_key: str = os.getenv("SERVICE_KEY"),
@@ -36,15 +44,6 @@
3644 product_tier_key: str = os.getenv("PRODUCT_TIER_KEY"),
3745 resource_key: str = os.getenv("RESOURCE_KEY"),
3846 subscription_id: str = os.getenv("SUBSCRIPTION_ID"),
39- deployment_create_timeout_seconds: int = int(
40- os.getenv("DEPLOYMENT_CREATE_TIMEOUT_SECONDS", "1200")
41- ),
42- deployment_delete_timeout_seconds: int = int(
43- os.getenv("DEPLOYMENT_DELETE_TIMEOUT_SECONDS", "1200")
44- ),
45- deployment_failover_timeout_seconds: int = int(
46- os.getenv("DEPLOYMENT_FAILOVER_TIMEOUT_SECONDS", "1500")
47- ),
4847 ):
4948 assert (
5049 service_provider_id is not None
@@ -83,9 +82,22 @@
8382 self.resource_key = resource_key
8483 self.subscription_id = subscription_id
8584
86- self.deployment_create_timeout_seconds = deployment_create_timeout_seconds
87- self.deployment_delete_timeout_seconds = deployment_delete_timeout_seconds
88- self.deployment_failover_timeout_seconds = deployment_failover_timeout_seconds
85+ self.deployment_create_timeout_seconds = (
86+ deployment_create_timeout_seconds
87+ or int(os.getenv("DEPLOYMENT_CREATE_TIMEOUT_SECONDS", "2400"))
88+ )
89+ self.deployment_delete_timeout_seconds = (
90+ deployment_delete_timeout_seconds
91+ or int(os.getenv("DEPLOYMENT_DELETE_TIMEOUT_SECONDS", "1200"))
92+ )
93+ self.deployment_failover_timeout_seconds = (
94+ deployment_failover_timeout_seconds
95+ or int(os.getenv("DEPLOYMENT_FAILOVER_TIMEOUT_SECONDS", "1500"))
96+ )
97+ self.deployment_update_timeout_seconds = (
98+ deployment_update_timeout_seconds
99+ or int(os.getenv("DEPLOYMENT_UPDATE_TIMEOUT_SECONDS", "2400"))
100+ )
89101
90102 def create(
91103 self,
@@ -114,7 +126,7 @@
114126 "productTierVersion": product_tier_version,
115127 }
116128
117- print(f"Creating instance {name}")
129+ logging.info(f"Creating instance {name}")
118130
119131 response = self._fleet_api.client().post(
120132 f"{self._fleet_api.base_url}/fleet/resource-instance/{self.service_provider_id}/{self.service_key}/{self.service_api_version}/{self.service_environment_key}/{self.service_model_key}/{self.product_tier_key}/{self.resource_key}?subscriptionId={self.subscription_id}",
@@ -126,7 +138,7 @@
126138
127139 self.instance_id = response.json()["id"]
128140
129- print(f"Instance {name} created: {self.instance_id}")
141+ logging.info(f"Instance {name} created: {self.instance_id}")
130142
131143 if not wait_for_ready:
132144 return
@@ -139,9 +151,12 @@
139151 raise Exception(f"Failed to create instance {name}")
140152
141153 def wait_for_instance_status(
142- self, requested_status="RUNNING", timeout_seconds: int = 1200
154+ self,
155+ timeout_seconds: int,
156+ requested_status="RUNNING",
143157 ):
144158 """Wait for the instance to be ready."""
159+ print(f"Waiting for instance to be ready. Timeout: {timeout_seconds} seconds")
145160 timeout_timer = time.time() + int(timeout_seconds or 1200)
146161
147162 while True:
@@ -150,13 +165,13 @@
150165
151166 status = self.get_instance_details()["status"]
152167 if status == requested_status:
153- print(f"Instance is {requested_status}")
168+ logging.info(f"Instance is {requested_status}")
154169 break
155170 elif status == "FAILED":
156- print("Instance is in error state")
171+ logging.info("Instance is in error state")
157172 raise Exception("Instance is in error state")
158173 else:
159- print("Instance is in " + status + " state")
174+ logging.info("Instance is in " + status + " state")
160175 time.sleep(5)
161176
162177 def get_instance_details(self, retries=5):
@@ -231,7 +246,7 @@
231246 if e.args[0] == "Timeout":
232247 raise Exception(f"Failed to delete instance {self.instance_id}")
233248
234- def stop(self, wait_for_ready: bool, retry=5):
249+ def stop(self, wait_for_ready: bool, retry=10):
235250 """Stop the instance. Optionally wait for the instance to be ready."""
236251
237252 response = self._fleet_api.client().post(
@@ -241,7 +256,7 @@
241256 )
242257
243258 if "another operation is already in progress" in response.text and retry > 0:
244- time.sleep(60)
259+ time.sleep(90)
245260 return self.stop(wait_for_ready, retry - 1)
246261
247262 self._fleet_api.handle_response(
@@ -256,7 +271,7 @@
256271 timeout_seconds=self.deployment_failover_timeout_seconds,
257272 )
258273
259- def start(self, wait_for_ready: bool, retry=5):
274+ def start(self, wait_for_ready: bool, retry=10):
260275 """Start the instance. Optionally wait for the instance to be ready."""
261276
262277 response = self._fleet_api.client().post(
@@ -266,7 +281,7 @@
266281 )
267282
268283 if "another operation is already in progress" in response.text and retry > 0:
269- time.sleep(60)
284+ time.sleep(90)
270285 return self.start(wait_for_ready, retry - 1)
271286
272287 self._fleet_api.handle_response(
@@ -281,10 +296,10 @@
281296 )
282297
283298 def trigger_failover(
284- self, replica_id: str, wait_for_ready: bool, resource_id: str = None, retry=5
299+ self, replica_id: str, wait_for_ready: bool, resource_id: str = None, retry=10
285300 ):
286301 """Trigger failover for the instance. Optionally wait for the instance to be ready."""
287- print(f"Triggering failover for instance {self.instance_id}")
302+ logging.info(f"Triggering failover for instance {self.instance_id}")
288303
289304 data = {
290305 "failedReplicaID": replica_id,
@@ -299,7 +314,7 @@
299314 )
300315
301316 if "another operation is already in progress" in response.text and retry > 0:
302- time.sleep(60)
317+ time.sleep(90)
303318 return self.trigger_failover(
304319 replica_id, wait_for_ready, resource_id, retry - 1
305320 )
@@ -326,12 +341,12 @@
326341
327342 return self.update_params(wait_until_ready, retry, **data)
328343
329- def update_params(self, wait_until_ready: bool = True, retry=5, **kwargs):
344+ def update_params(self, wait_until_ready: bool = True, retry=10, **kwargs):
330345 """Update the instance parameters."""
331346
332- self.wait_for_instance_status()
347+ self.wait_for_instance_status(timeout_seconds=1200)
333348
334- data = kwargs
349+ data = {"requestParams": kwargs}
335350
336351 response = self._fleet_api.client().patch(
337352 f"{self._fleet_api.base_url}/resource-instance/{self.service_provider_id}/{self.service_key}/{self.service_api_version}/{self.service_environment_key}/{self.service_model_key}/{self.product_tier_key}/{self.resource_key}/{self.instance_id}",
@@ -339,12 +354,8 @@
339354 timeout=15,
340355 )
341356
342- if "another operation is already in progress" in str(response.text):
343- if retry == 0:
344- raise Exception(
345- f"Failed to update instance type {self.instance_id} after {retry} retries"
346- )
347- time.sleep(60)
357+ if "another operation is already in progress" in response.text and retry > 0:
358+ time.sleep(90)
348359 return self.update_params(wait_until_ready, retry - 1, **kwargs)
349360
350361 self._fleet_api.handle_response(
@@ -355,7 +366,7 @@
355366 return
356367
357368 self.wait_for_instance_status(
358- timeout_seconds=self.deployment_failover_timeout_seconds
369+ timeout_seconds=self.deployment_update_timeout_seconds
359370 )
360371
361372 def upgrade(
@@ -397,6 +408,7 @@
397408 upgrade_timeout: int = 1200,
398409 ):
399410 right_now = time.time()
411+ skipped_running = False
400412 while True:
401413 response = self._fleet_api.client().get(
402414 f"{self._fleet_api.base_url}/fleet/service/{service_id}/productTier/{product_tier_id}/upgrade-path/{upgrade_id}",
@@ -407,12 +419,23 @@
407419
408420 status = response.json()["status"]
409421
422+ if (
423+ status == "RUNNING"
424+ and not skipped_running
425+ and time.time() - right_now < upgrade_timeout
426+ ):
427+ logging.info("Skipping first running status")
428+ time.sleep(5)
429+ continue
430+
431+ skipped_running = True
432+
410433 if status == "IN_PROGRESS":
411- print("Upgrade in progress")
434+ logging.info("Upgrade in progress")
412435 time.sleep(10)
413- print("Waiting for instance to be ready")
436+ logging.info("Waiting for instance to be ready")
414437 elif status == "COMPLETE":
415- print("Upgrade completed")
438+ logging.info("Upgrade completed")
416439 break
417440 else:
418441 raise Exception(f"Upgrade failed: {status}")
@@ -420,9 +443,9 @@
420443 if time.time() - right_now > upgrade_timeout:
421444 raise Exception("Upgrade timed out")
422445
423- def get_network_topology(self):
446+ def get_network_topology(self, force_refresh=False):
424447
425- if self._network_topology is not None:
448+ if self._network_topology is not None and not force_refresh:
426449 return self._network_topology
427450
428451 self._network_topology = self.get_instance_details()["detailedNetworkTopology"]
@@ -464,7 +487,7 @@
464487 and len(resources[key]["clusterEndpoint"]) > 0
465488 and "streamer." not in resources[key]["clusterEndpoint"]
466489 and "clusterPorts" in resources[key]
467- and resources[key]['networkingType'] != "INTERNAL"
490+ and resources[key]["networkingType"] != "INTERNAL"
468491 ):
469492 return {
470493 "endpoint": resources[key]["clusterEndpoint"],
@@ -483,7 +506,9 @@
483506 # Connect to the master node
484507 while retries > 0:
485508 try:
486- print(f"Connecting to {endpoint['endpoint']}:{endpoint['ports'][0]}")
509+ logging.info(
510+ f"Connecting to {endpoint['endpoint']}:{endpoint['ports'][0]}"
511+ )
487512 self._connection = FalkorDB(
488513 host=endpoint["endpoint"],
489514 port=endpoint["ports"][0],
@@ -493,7 +518,7 @@
493518 )
494519 break
495520 except Exception as e:
496- print(f"Failed to connect to the master node: {e}")
521+ logging.error(f"Failed to connect to the master node: {e}")
497522 retries -= 1
498523 time.sleep(60)
499524
@@ -507,7 +532,7 @@
507532
508533 db = self.create_connection()
509534
510- print("Generating data")
535+ logging.info("Generating data")
511536 for i in range(0, graph_count):
512537
513538 name = rand_string()
@@ -520,4 +545,4 @@
520545 CREATE (a:L {v:x})-[:R]->(b:X {v: tostring(x)}), (a)-[:Z]->(:Y {v:tostring(x)})""",
521546 {"node_count": node_count},
522547 )
523- print("Data generated")
548+ logging.info("Data generated")
modified omnistrate_tests/test_cluster.py +18 −13
@@ -12,6 +12,9 @@
1212 with suppress(ValueError):
1313 sys.path.remove(str(parent))
1414
15+import logging
16+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
17+
1518 import time
1619 import os
1720 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -79,7 +82,7 @@
7982 args.service_id, product_tier.service_model_id
8083 )
8184
82- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
85+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
8386
8487 instance = omnistrate.instance(
8588 service_id=args.service_id,
@@ -121,20 +124,21 @@
121124 # Test stop and start instance
122125 test_stop_start(instance)
123126 except Exception as e:
124- instance.delete(True)
127+ logging.exception(e)
128+ instance.delete(False)
125129 raise e
126130
127131 # Delete instance
128- instance.delete(True)
132+ instance.delete(False)
129133
130- print("Test passed")
134+ logging.info("Test passed")
131135
132136
133137 def test_ensure_mz_distribution(instance: OmnistrateFleetInstance):
134138 """This function should ensure that each shard is distributed across multiple availability zones"""
135139
136140 instance_details = instance.get_instance_details()
137- network_topology: dict = instance.get_network_topology()
141+ network_topology: dict = instance.get_network_topology(force_refresh=True)
138142
139143 params = (
140144 instance_details["result_params"]
@@ -170,7 +174,7 @@
170174 raise Exception("No nodes found in network topology")
171175
172176 if len(nodes) != host_count:
173- raise Exception("Host count does not match number of nodes")
177+ raise Exception(f"Host count does not match number of nodes. Current host count: {host_count}; Number of nodes: {len(nodes)}")
174178
175179 cluster = FalkorDBCluster(
176180 host=resource["clusterEndpoint"],
@@ -189,7 +193,8 @@
189193 (n for n in nodes if n["endpoint"] == node.hostname), None
190194 )
191195 if not omnistrateNode:
192- raise Exception(f"Node {node.hostname} not found in network topology")
196+ logging.warning(f"Node {node.hostname} not found in network topology")
197+ continue
193198
194199 group_azs.add(omnistrateNode["availabilityZone"])
195200
@@ -198,9 +203,9 @@
198203 "Group is not distributed across multiple availability zones"
199204 )
200205
201- print(f"Group {group} is distributed across availability zones {group_azs}")
206+ logging.info(f"Group {group} is distributed across availability zones {group_azs}")
202207
203- print("Shards are distributed across multiple availability zones")
208+ logging.info("Shards are distributed across multiple availability zones")
204209
205210
206211 def test_failover(instance: OmnistrateFleetInstance):
@@ -231,7 +236,7 @@
231236 if len(result.result_set) == 0:
232237 raise Exception("Data lost after failover")
233238
234- print("Data persisted after failover")
239+ logging.info("Data persisted after failover")
235240
236241 graph.delete()
237242
@@ -249,11 +254,11 @@
249254 # Write some data to the DB
250255 graph.query("CREATE (n:Person {name: 'Alice'})")
251256
252- print("Stopping instance")
257+ logging.info("Stopping instance")
253258
254259 instance.stop(wait_for_ready=True)
255260
256- print("Instance stopped")
261+ logging.info("Instance stopped")
257262
258263 instance.start(wait_for_ready=True)
259264
@@ -264,7 +269,7 @@
264269 if len(result.result_set) == 0:
265270 raise Exception("Data lost after stop/start")
266271
267- print("Instance started")
272+ logging.info("Instance started")
268273
269274
270275 if __name__ == "__main__":
added omnistrate_tests/test_cluster_replicas.py +294 −0
@@ -0,0 +1,294 @@
1+import sys
2+import signal
3+from pathlib import Path
4+
5+file = Path(__file__).resolve()
6+parent, root = file.parent, file.parents[1]
7+sys.path.append(str(root))
8+
9+# Additionally remove the current file's directory from sys.path
10+from contextlib import suppress
11+
12+with suppress(ValueError):
13+ sys.path.remove(str(parent))
14+
15+import logging
16+
17+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
18+
19+import time
20+import os
21+from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
22+from omnistrate_tests.classes.omnistrate_fleet_api import OmnistrateFleetAPI
23+from omnistrate_tests.classes.falkordb_cluster import FalkorDBCluster
24+import argparse
25+
26+parser = argparse.ArgumentParser()
27+parser.add_argument("omnistrate_user")
28+parser.add_argument("omnistrate_password")
29+parser.add_argument("cloud_provider", choices=["aws", "gcp"])
30+parser.add_argument("region")
31+
32+parser.add_argument(
33+ "--subscription-id", required=False, default=os.getenv("SUBSCRIPTION_ID")
34+)
35+parser.add_argument("--ref-name", required=False, default=os.getenv("REF_NAME"))
36+parser.add_argument("--service-id", required=True)
37+parser.add_argument("--environment-id", required=True)
38+parser.add_argument("--resource-key", required=True)
39+
40+parser.add_argument("--instance-name", required=True)
41+parser.add_argument("--instance-description", required=False, default="test-standalone")
42+parser.add_argument("--instance-type", required=True)
43+parser.add_argument("--storage-size", required=False, default="30")
44+parser.add_argument("--tls", action="store_true")
45+parser.add_argument("--rdb-config", required=False, default="medium")
46+parser.add_argument("--aof-config", required=False, default="always")
47+parser.add_argument("--host-count", required=False, default="6")
48+parser.add_argument("--cluster-replicas", required=False, default="1")
49+parser.add_argument("--shards", required=False, default="3")
50+
51+parser.add_argument("--ensure-mz-distribution", action="store_true")
52+
53+parser.set_defaults(tls=False)
54+args = parser.parse_args()
55+
56+instance: OmnistrateFleetInstance = None
57+
58+
59+# Intercept exit signals so we can delete the instance before exiting
60+def signal_handler(sig, frame):
61+ if instance:
62+ instance.delete(False)
63+ sys.exit(0)
64+
65+
66+signal.signal(signal.SIGINT, signal_handler)
67+signal.signal(signal.SIGTERM, signal_handler)
68+
69+current_host_count = int(args.host_count)
70+current_replicas_count = int(args.cluster_replicas)
71+
72+
73+def test_cluster_replicas():
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+ )
105+
106+ try:
107+ instance.create(
108+ wait_for_ready=True,
109+ deployment_cloud_provider=args.cloud_provider,
110+ deployment_region=args.region,
111+ name=args.instance_name,
112+ description=args.instance_description,
113+ falkordb_user="falkordb",
114+ falkordb_password="falkordb",
115+ nodeInstanceType=args.instance_type,
116+ storageSize=args.storage_size,
117+ enableTLS=args.tls,
118+ RDBPersistenceConfig=args.rdb_config,
119+ AOFPersistenceConfig=args.aof_config,
120+ hostCount=args.host_count,
121+ clusterReplicas=args.cluster_replicas,
122+ )
123+
124+ add_data(instance)
125+
126+ change_replica_count(instance, int(args.cluster_replicas) + 1)
127+
128+ if args.ensure_mz_distribution:
129+ test_ensure_mz_distribution(instance)
130+
131+ check_data(instance)
132+
133+ change_replica_count(instance, int(args.cluster_replicas))
134+
135+ check_data(instance)
136+ except Exception as e:
137+ logging.exception(e)
138+ instance.delete(False)
139+ raise e
140+
141+ # Delete instance
142+ instance.delete(False)
143+
144+ logging.info("Test passed")
145+
146+
147+def change_replica_count(instance: OmnistrateFleetInstance, new_replicas_count: int):
148+ global current_replicas_count, current_host_count
149+
150+ diff = new_replicas_count - current_replicas_count
151+
152+ new_host_count = int(current_host_count) + (diff * int(args.shards))
153+
154+ logging.info(
155+ f"Changing clusterReplicas to {new_replicas_count} and hostCount to {new_host_count}"
156+ )
157+ instance.update_params(
158+ hostCount=f"{new_host_count}",
159+ clusterReplicas=f"{new_replicas_count}",
160+ wait_for_ready=True,
161+ )
162+ current_host_count = new_host_count
163+ current_replicas_count = new_replicas_count
164+
165+ instance_details = instance.get_instance_details()
166+
167+ params = (
168+ instance_details["result_params"]
169+ if "result_params" in instance_details
170+ else None
171+ )
172+
173+ if not params:
174+ raise Exception("No result_params found in instance details")
175+
176+ host_count = int(params["hostCount"]) if "hostCount" in params else None
177+
178+ if not host_count:
179+ raise Exception("No hostCount found in instance details")
180+
181+ if host_count != current_host_count:
182+ raise Exception("Host count does not match new host count")
183+
184+ cluster_replicas = (
185+ int(params["clusterReplicas"]) if "clusterReplicas" in params else None
186+ )
187+
188+ if not cluster_replicas:
189+ raise Exception("No clusterReplicas found in instance details")
190+
191+ if cluster_replicas != current_replicas_count:
192+ raise Exception("Cluster replicas count does not match new replicas count")
193+
194+
195+def test_ensure_mz_distribution(instance: OmnistrateFleetInstance):
196+ """This function should ensure that each shard is distributed across multiple availability zones"""
197+
198+ network_topology: dict = instance.get_network_topology(force_refresh=True)
199+ instance_details = instance.get_instance_details()
200+
201+ params = (
202+ instance_details["result_params"]
203+ if "result_params" in instance_details
204+ else None
205+ )
206+
207+ if not params:
208+ raise Exception("No result_params found in instance details")
209+
210+ resource_key = next(
211+ (k for [k, v] in network_topology.items() if v["resourceName"] == "cluster-mz"),
212+ None,
213+ )
214+
215+ resource = network_topology[resource_key]
216+
217+ nodes = resource["nodes"]
218+
219+ if len(nodes) == 0:
220+ raise Exception("No nodes found in network topology")
221+
222+ if len(nodes) != current_host_count:
223+ raise Exception(f"Host count does not match number of nodes. Current host count: {current_host_count}; Number of nodes: {len(nodes)}")
224+
225+ cluster = FalkorDBCluster(
226+ host=resource["clusterEndpoint"],
227+ port=resource["clusterPorts"][0],
228+ username="falkordb",
229+ password="falkordb",
230+ ssl=params["enableTLS"] == "true" if "enableTLS" in params else False,
231+ )
232+
233+ groups = cluster.groups(current_replicas_count)
234+
235+ for group in groups:
236+ group_azs = set()
237+ for node in group:
238+ omnistrateNode = next(
239+ (n for n in nodes if n["endpoint"] == node.hostname), None
240+ )
241+ if not omnistrateNode:
242+ logging.warning(f"Node {node.hostname} not found in network topology")
243+ continue
244+
245+ group_azs.add(omnistrateNode["availabilityZone"])
246+
247+ if len(group_azs) == 1:
248+ raise Exception(
249+ "Group is not distributed across multiple availability zones"
250+ )
251+
252+ logging.info(
253+ f"Group {group} is distributed across availability zones {group_azs}"
254+ )
255+
256+ logging.info("Shards are distributed across multiple availability zones")
257+
258+
259+def add_data(instance: OmnistrateFleetInstance):
260+ """This function should retrieve the instance host and port for connection, write some data to the DB, then check that the data is there"""
261+
262+ # Get instance host and port
263+ db = instance.create_connection(
264+ ssl=args.tls,
265+ )
266+
267+ graph = db.select_graph("test")
268+
269+ # Write some data to the DB
270+ graph.query("CREATE (n:Person {name: 'Alice'})")
271+
272+ result = graph.query("MATCH (n:Person) RETURN n")
273+
274+ if len(result.result_set) == 0:
275+ raise Exception("Data not found after write")
276+
277+
278+def check_data(instance: OmnistrateFleetInstance):
279+
280+ # Get instance host and port
281+ db = instance.create_connection(
282+ ssl=args.tls,
283+ )
284+
285+ graph = db.select_graph("test")
286+
287+ result = graph.query("MATCH (n:Person) RETURN n")
288+
289+ if len(result.result_set) == 0:
290+ raise Exception("Data did not persist after host count change")
291+
292+
293+if __name__ == "__main__":
294+ test_cluster_replicas()
modified omnistrate_tests/test_cluster_shards.py +49 −17
@@ -12,6 +12,10 @@
1212 with suppress(ValueError):
1313 sys.path.remove(str(parent))
1414
15+import logging
16+
17+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
18+
1519 import time
1620 import os
1721 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -32,8 +36,6 @@
3236 parser.add_argument("--service-id", required=True)
3337 parser.add_argument("--environment-id", required=True)
3438 parser.add_argument("--resource-key", required=True)
35-parser.add_argument("--replica-id", required=True)
36-
3739
3840 parser.add_argument("--instance-name", required=True)
3941 parser.add_argument("--instance-description", required=False, default="test-standalone")
@@ -52,11 +54,16 @@
5254
5355 instance: OmnistrateFleetInstance = None
5456
57+current_host_count = int(args.host_count)
58+
59+
5560 # Intercept exit signals so we can delete the instance before exiting
5661 def signal_handler(sig, frame):
5762 if instance:
5863 instance.delete(False)
5964 sys.exit(0)
65+
66+
6067 signal.signal(signal.SIGINT, signal_handler)
6168 signal.signal(signal.SIGTERM, signal_handler)
6269
@@ -79,7 +86,7 @@
7986 args.service_id, product_tier.service_model_id
8087 )
8188
82- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
89+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
8390
8491 instance = omnistrate.instance(
8592 service_id=args.service_id,
@@ -123,31 +130,32 @@
123130
124131 change_host_count(instance, int(args.host_count))
125132
133+ if args.ensure_mz_distribution:
134+ test_ensure_mz_distribution(instance)
135+
126136 check_data(instance)
127137 except Exception as e:
128- instance.delete(True)
138+ logging.exception(e)
139+ instance.delete(False)
129140 raise e
130141
131142 # Delete instance
132- instance.delete(True)
143+ instance.delete(False)
133144
134- print("Test passed")
145+ logging.info("Test passed")
135146
136147
137148 def change_host_count(instance: OmnistrateFleetInstance, new_host_count: int):
149+ global current_host_count
138150
139- print(f"Changing host count to {new_host_count}")
151+ logging.info(f"Changing host count to {new_host_count}")
140152 instance.update_params(
141153 hostCount=f"{new_host_count}",
142154 wait_for_ready=True,
143155 )
144-
145-
146-def test_ensure_mz_distribution(instance: OmnistrateFleetInstance):
147- """This function should ensure that each shard is distributed across multiple availability zones"""
156+ current_host_count = new_host_count
148157
149158 instance_details = instance.get_instance_details()
150- network_topology: dict = instance.get_network_topology()
151159
152160 params = (
153161 instance_details["result_params"]
@@ -163,6 +171,25 @@
163171 if not host_count:
164172 raise Exception("No hostCount found in instance details")
165173
174+ if host_count != current_host_count:
175+ raise Exception("Host count does not match new host count")
176+
177+
178+def test_ensure_mz_distribution(instance: OmnistrateFleetInstance):
179+ """This function should ensure that each shard is distributed across multiple availability zones"""
180+
181+ instance_details = instance.get_instance_details()
182+ network_topology: dict = instance.get_network_topology(force_refresh=True)
183+
184+ params = (
185+ instance_details["result_params"]
186+ if "result_params" in instance_details
187+ else None
188+ )
189+
190+ if not params:
191+ raise Exception("No result_params found in instance details")
192+
166193 cluster_replicas = (
167194 int(params["clusterReplicas"]) if "clusterReplicas" in params else None
168195 )
@@ -179,11 +206,13 @@
179206
180207 nodes = resource["nodes"]
181208
209+ logging.debug(f"Nodes: {nodes}")
210+
182211 if len(nodes) == 0:
183212 raise Exception("No nodes found in network topology")
184213
185- if len(nodes) != host_count:
186- raise Exception("Host count does not match number of nodes")
214+ if len(nodes) != current_host_count:
215+ raise Exception(f"Host count does not match number of nodes. Current host count: {current_host_count}; Number of nodes: {len(nodes)}")
187216
188217 cluster = FalkorDBCluster(
189218 host=resource["clusterEndpoint"],
@@ -202,7 +231,8 @@
202231 (n for n in nodes if n["endpoint"] == node.hostname), None
203232 )
204233 if not omnistrateNode:
205- raise Exception(f"Node {node.hostname} not found in network topology")
234+ logging.warning(f"Node {node.hostname} not found in network topology")
235+ continue
206236
207237 group_azs.add(omnistrateNode["availabilityZone"])
208238
@@ -211,9 +241,11 @@
211241 "Group is not distributed across multiple availability zones"
212242 )
213243
214- print(f"Group {group} is distributed across availability zones {group_azs}")
244+ logging.info(
245+ f"Group {group} is distributed across availability zones {group_azs}"
246+ )
215247
216- print("Shards are distributed across multiple availability zones")
248+ logging.info("Shards are distributed across multiple availability zones")
217249
218250
219251 def add_data(instance: OmnistrateFleetInstance):
modified omnistrate_tests/test_replication.py +23 −19
@@ -12,6 +12,9 @@
1212 except ValueError: # Already removed
1313 pass
1414
15+import logging
16+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
17+
1518 import time
1619 import os
1720 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -81,7 +84,7 @@
8184 args.service_id, product_tier.service_model_id
8285 )
8386
84- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
87+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
8588
8689 instance = omnistrate.instance(
8790 service_id=args.service_id,
@@ -118,13 +121,14 @@
118121 # Test stop and start instance
119122 test_stop_start(instance)
120123 except Exception as e:
121- instance.delete(True)
124+ logging.exception(e)
125+ instance.delete(False)
122126 raise e
123127
124128 # Delete instance
125- instance.delete(True)
129+ instance.delete(False)
126130
127- print("Test passed")
131+ logging.info("Test passed")
128132
129133
130134 def test_failover(instance: OmnistrateFleetInstance):
@@ -209,7 +213,7 @@
209213
210214 id_key = "sz" if args.resource_key == "single-Zone" else "mz"
211215
212- print(f"Triggering failover for node-{id_key}-0")
216+ logging.info(f"Triggering failover for node-{id_key}-0")
213217 # Trigger failover
214218 instance.trigger_failover(
215219 replica_id=f"node-{id_key}-0",
@@ -225,10 +229,10 @@
225229 promotion_completed = True
226230 time.sleep(5)
227231 except Exception as e:
228- print("Promotion not completed yet")
232+ logging.info("Promotion not completed yet")
229233 time.sleep(5)
230234
231- print("Promotion completed")
235+ logging.info("Promotion completed")
232236
233237 # Check if data is still there
234238 graph_1 = db_1.select_graph("test")
@@ -238,18 +242,18 @@
238242 if len(result.result_set) == 0:
239243 raise Exception("Data lost after first failover")
240244
241- print("Data persisted after first failover")
245+ logging.info("Data persisted after first failover")
242246
243247 graph_1.query("CREATE (n:Person {name: 'Bob'})")
244248
245249 result = graph_1.query("MATCH (n:Person) RETURN n")
246250
247- print("result after bob", result.result_set)
251+ logging.info(f"result after bob: {result.result_set}")
248252
249253 # wait until the node 0 is ready
250254 instance.wait_for_instance_status(timeout_seconds=600)
251255
252- print(f"Triggering failover for sentinel-{id_key}-0")
256+ logging.info(f"Triggering failover for sentinel-{id_key}-0")
253257 # Trigger sentinel failover
254258 instance.trigger_failover(
255259 replica_id=f"sentinel-{id_key}-0",
@@ -264,12 +268,12 @@
264268 if len(result.result_set) < 2:
265269 raise Exception("Data lost after second failover")
266270
267- print("Data persisted after second failover")
271+ logging.info("Data persisted after second failover")
268272
269273 # wait until the node 0 is ready
270274 instance.wait_for_instance_status(timeout_seconds=600)
271275
272- print(f"Triggering failover for node-{id_key}-1")
276+ logging.info(f"Triggering failover for node-{id_key}-1")
273277 # Trigger failover
274278 instance.trigger_failover(
275279 replica_id=f"node-{id_key}-1",
@@ -285,10 +289,10 @@
285289 promotion_completed = True
286290 time.sleep(5)
287291 except Exception as e:
288- print("Promotion not completed yet")
292+ logging.info("Promotion not completed yet")
289293 time.sleep(5)
290294
291- print("Promotion completed")
295+ logging.info("Promotion completed")
292296
293297 # Check if data is still there
294298 graph_0 = db_0.select_graph("test")
@@ -296,10 +300,10 @@
296300 result = graph_0.query("MATCH (n:Person) RETURN n")
297301
298302 if len(result.result_set) < 2:
299- print(result.result_set)
303+ logging.info(result.result_set)
300304 raise Exception("Data lost after third failover")
301305
302- print("Data persisted after third failover")
306+ logging.info("Data persisted after third failover")
303307
304308
305309 def test_stop_start(instance: OmnistrateFleetInstance):
@@ -332,11 +336,11 @@
332336 # Write some data to the DB
333337 graph.query("CREATE (n:Person {name: 'Alice'})")
334338
335- print("Stopping node")
339+ logging.info("Stopping node")
336340
337341 instance.stop(wait_for_ready=True)
338342
339- print("Instance stopped")
343+ logging.info("Instance stopped")
340344
341345 instance.start(wait_for_ready=True)
342346
@@ -347,7 +351,7 @@
347351 if len(result.result_set) == 0:
348352 raise Exception("Data lost after stop/start")
349353
350- print("Instance started")
354+ logging.info("Instance started")
351355
352356
353357 if __name__ == "__main__":
modified omnistrate_tests/test_standalone.py +12 −8
@@ -12,6 +12,9 @@
1212 with suppress(ValueError):
1313 sys.path.remove(str(parent))
1414
15+import logging
16+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
17+
1518 import time
1619 import os
1720 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -73,7 +76,7 @@
7376 args.service_id, product_tier.service_model_id
7477 )
7578
76- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
79+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
7780
7881 instance = omnistrate.instance(
7982 service_id=args.service_id,
@@ -110,13 +113,14 @@
110113 # Test stop and start instance
111114 test_stop_start(instance)
112115 except Exception as e:
113- instance.delete(True)
116+ logging.exception(e)
117+ instance.delete(False)
114118 raise e
115119
116120 # Delete instance
117- instance.delete(True)
121+ instance.delete(False)
118122
119- print("Test passed")
123+ logging.info("Test passed")
120124
121125
122126 def test_failover(instance: OmnistrateFleetInstance):
@@ -147,7 +151,7 @@
147151 if len(result.result_set) == 0:
148152 raise Exception("Data lost after failover")
149153
150- print("Data persisted after failover")
154+ logging.info("Data persisted after failover")
151155
152156 graph.delete()
153157
@@ -165,11 +169,11 @@
165169 # Write some data to the DB
166170 graph.query("CREATE (n:Person {name: 'Alice'})")
167171
168- print("Stopping instance")
172+ logging.info("Stopping instance")
169173
170174 instance.stop(wait_for_ready=True)
171175
172- print("Instance stopped")
176+ logging.info("Instance stopped")
173177
174178 instance.start(wait_for_ready=True)
175179
@@ -180,7 +184,7 @@
180184 if len(result.result_set) == 0:
181185 raise Exception("Data lost after stop/start")
182186
183- print("Instance started")
187+ logging.info("Instance started")
184188
185189
186190 if __name__ == "__main__":
modified omnistrate_tests/test_update_memory.py +8 −4
@@ -12,6 +12,9 @@
1212 with suppress(ValueError):
1313 sys.path.remove(str(parent))
1414
15+import logging
16+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
17+
1518 import time
1619 import os
1720 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -78,7 +81,7 @@
7881 args.service_id, product_tier.service_model_id
7982 )
8083
81- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
84+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
8285
8386 instance = omnistrate.instance(
8487 service_id=args.service_id,
@@ -119,13 +122,14 @@
119122 query_data(instance)
120123
121124 except Exception as e:
122- instance.delete(True)
125+ logging.exception(e)
126+ instance.delete(False)
123127 raise e
124128
125129 # Delete instance
126- instance.delete(True)
130+ instance.delete(False)
127131
128- print("Update memory size test passed")
132+ logging.info("Update memory size test passed")
129133
130134
131135 def add_data(instance: OmnistrateFleetInstance):
modified omnistrate_tests/test_upgrade_version.py +11 −8
@@ -12,6 +12,9 @@
1212 with suppress(ValueError):
1313 sys.path.remove(str(parent))
1414
15+import logging
16+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
17+
1518 import time
1619 import os
1720 from omnistrate_tests.classes.omnistrate_fleet_instance import OmnistrateFleetInstance
@@ -76,7 +79,7 @@
7679 args.service_id, product_tier.service_model_id
7780 )
7881
79- print(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
82+ logging.info(f"Product tier id: {product_tier.product_tier_id} for {args.ref_name}")
8083
8184 # 1. List product tier versions
8285 tiers = omnistrate.list_tier_versions(
@@ -96,8 +99,8 @@
9699 if last_tier is None:
97100 raise ValueError("No last tier found")
98101
99- print(f"Preferred tier: {preferred_tier.version}")
100- print(f"Last tier: {last_tier.version}")
102+ logging.info(f"Preferred tier: {preferred_tier.version}")
103+ logging.info(f"Last tier: {last_tier.version}")
101104
102105 # 2. Create omnistrate instance with previous version
103106 instance = omnistrate.instance(
@@ -142,19 +145,19 @@
142145 wait_until_ready=True,
143146 )
144147
145- print(f"Upgrade time: {(time.time() - upgrade_timer):.2f}s")
148+ logging.info(f"Upgrade time: {(time.time() - upgrade_timer):.2f}s")
146149
147150 # 6. Verify the upgrade was successful
148151 query_data(instance)
149152 except Exception as e:
150- print("Error " + str(e))
151- instance.delete(True)
153+ logging.exception(e)
154+ instance.delete(False)
152155 raise e
153156
154157 # 7. Delete the instance
155- instance.delete(True)
158+ instance.delete(False)
156159
157- print("Upgrade version test passed")
160+ logging.info("Upgrade version test passed")
158161
159162
160163 def add_data(instance: OmnistrateFleetInstance):