| 1 | from falkordb import FalkorDB |
| 2 | import json |
| 3 | import os |
| 4 | import logging |
| 5 | import socket |
| 6 | from redis import retry, backoff, exceptions as redis_exceptions |
| 7 | |
| 8 | logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s") |
| 9 | |
| 10 | import time |
| 11 | import random |
| 12 | import string |
| 13 | from requests import exceptions |
| 14 | import omnistrate_tests.classes.omnistrate_fleet_api |
| 15 | |
| 16 | |
| 17 | def rand_range(a, b): |
| 18 | return random.randint(a, b) |
| 19 | |
| 20 | |
| 21 | def rand_string(l=12): |
| 22 | letters = string.ascii_letters |
| 23 | return "".join(random.choice(letters) for _ in range(l)) |
| 24 | |
| 25 | |
| 26 | class OmnistrateFleetInstance: |
| 27 | |
| 28 | instance_id: str = None |
| 29 | _network_topology = None |
| 30 | _connection: FalkorDB = None |
| 31 | |
| 32 | falkordb_password: str = None |
| 33 | |
| 34 | def __init__( |
| 35 | self, |
| 36 | fleet_api: omnistrate_tests.classes.omnistrate_fleet_api.OmnistrateFleetAPI, |
| 37 | deployment_create_timeout_seconds: int | None, |
| 38 | deployment_delete_timeout_seconds: int | None, |
| 39 | deployment_failover_timeout_seconds: int | None, |
| 40 | deployment_update_timeout_seconds: int | None, |
| 41 | service_id: str = os.getenv("SERVICE_ID"), |
| 42 | service_provider_id: str = os.getenv("SERVICE_PROVIDER_ID"), |
| 43 | service_key: str = os.getenv("SERVICE_KEY"), |
| 44 | service_api_version: str = os.getenv("SERVICE_API_VERSION"), |
| 45 | service_environment_key: str = os.getenv("SERVICE_ENVIRONMENT_KEY"), |
| 46 | service_environment_id: str = os.getenv("SERVICE_ENVIRONMENT_ID"), |
| 47 | service_model_key: str = os.getenv("SERVICE_MODEL_KEY"), |
| 48 | product_tier_key: str = os.getenv("PRODUCT_TIER_KEY"), |
| 49 | resource_key: str = os.getenv("RESOURCE_KEY"), |
| 50 | subscription_id: str = os.getenv("SUBSCRIPTION_ID"), |
| 51 | ): |
| 52 | assert ( |
| 53 | service_provider_id is not None |
| 54 | ), "Missing service_provider_id or SERVICE_PROVIDER_ID environment variable" |
| 55 | assert ( |
| 56 | service_key is not None |
| 57 | ), "Missing service_key or SERVICE_KEY environment variable" |
| 58 | assert ( |
| 59 | service_api_version is not None |
| 60 | ), "Missing service_api_version or SERVICE_API_VERSION environment variable" |
| 61 | assert ( |
| 62 | service_environment_key is not None |
| 63 | ), "Missing service_environment_key or SERVICE_ENVIRONMENT_KEY environment variable" |
| 64 | assert ( |
| 65 | service_environment_id is not None |
| 66 | ), "Missing service_environment_id or SERVICE_ENVIRONMENT_ID environment variable" |
| 67 | assert ( |
| 68 | service_model_key is not None |
| 69 | ), "Missing service_model_key or SERVICE_MODEL_KEY environment variable" |
| 70 | assert ( |
| 71 | product_tier_key is not None |
| 72 | ), "Missing product_tier_key or PRODUCT_TIER_KEY environment variable" |
| 73 | assert ( |
| 74 | resource_key is not None |
| 75 | ), "Missing resource_key or RESOURCE_KEY environment variable" |
| 76 | |
| 77 | self._fleet_api = fleet_api |
| 78 | self.service_id = service_id |
| 79 | self.service_provider_id = service_provider_id |
| 80 | self.service_key = service_key |
| 81 | self.service_api_version = service_api_version |
| 82 | self.service_environment_key = service_environment_key |
| 83 | self.service_environment_id = service_environment_id |
| 84 | self.service_model_key = service_model_key |
| 85 | self.product_tier_key = product_tier_key |
| 86 | self.resource_key = resource_key |
| 87 | self.subscription_id = subscription_id |
| 88 | |
| 89 | self.deployment_create_timeout_seconds = ( |
| 90 | deployment_create_timeout_seconds |
| 91 | or int(os.getenv("DEPLOYMENT_CREATE_TIMEOUT_SECONDS", "2400")) |
| 92 | ) |
| 93 | self.deployment_delete_timeout_seconds = ( |
| 94 | deployment_delete_timeout_seconds |
| 95 | or int(os.getenv("DEPLOYMENT_DELETE_TIMEOUT_SECONDS", "1200")) |
| 96 | ) |
| 97 | self.deployment_failover_timeout_seconds = ( |
| 98 | deployment_failover_timeout_seconds |
| 99 | or int(os.getenv("DEPLOYMENT_FAILOVER_TIMEOUT_SECONDS", "1500")) |
| 100 | ) |
| 101 | self.deployment_update_timeout_seconds = ( |
| 102 | deployment_update_timeout_seconds |
| 103 | or int(os.getenv("DEPLOYMENT_UPDATE_TIMEOUT_SECONDS", "2400")) |
| 104 | ) |
| 105 | |
| 106 | def create( |
| 107 | self, |
| 108 | wait_for_ready: bool, |
| 109 | deployment_cloud_provider: str, |
| 110 | deployment_region: str, |
| 111 | name: str, |
| 112 | description: str, |
| 113 | falkordb_user: str, |
| 114 | falkordb_password: str, |
| 115 | product_tier_version: str | None = None, |
| 116 | **kwargs, |
| 117 | ) -> str: |
| 118 | """Create an instance with the specified parameters. Optionally wait for the instance to be ready.""" |
| 119 | |
| 120 | self.falkordb_password = falkordb_password |
| 121 | |
| 122 | data = { |
| 123 | "cloud_provider": deployment_cloud_provider, |
| 124 | "region": deployment_region, |
| 125 | "requestParams": { |
| 126 | "name": name, |
| 127 | "description": description, |
| 128 | "falkordbUser": falkordb_user, |
| 129 | "falkordbPassword": falkordb_password, |
| 130 | **kwargs, |
| 131 | }, |
| 132 | "productTierVersion": product_tier_version, |
| 133 | } |
| 134 | |
| 135 | logging.info(f"Creating instance {name}") |
| 136 | |
| 137 | response = self._fleet_api.client().post( |
| 138 | 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}", |
| 139 | data=json.dumps(data), |
| 140 | timeout=60, |
| 141 | ) |
| 142 | |
| 143 | self._fleet_api.handle_response(response, f"Failed to create instance {name}") |
| 144 | |
| 145 | self.instance_id = response.json()["id"] |
| 146 | |
| 147 | logging.info(f"Instance {name} created: {self.instance_id}") |
| 148 | |
| 149 | if not wait_for_ready: |
| 150 | return |
| 151 | |
| 152 | try: |
| 153 | self.wait_for_instance_status( |
| 154 | timeout_seconds=self.deployment_create_timeout_seconds |
| 155 | ) |
| 156 | except Exception: |
| 157 | raise Exception(f"Failed to create instance {name}") |
| 158 | |
| 159 | def wait_for_instance_status( |
| 160 | self, |
| 161 | timeout_seconds: int, |
| 162 | requested_status="RUNNING", |
| 163 | ): |
| 164 | """Wait for the instance to be ready.""" |
| 165 | print(f"Waiting for instance to be ready. Timeout: {timeout_seconds} seconds") |
| 166 | timeout_timer = time.time() + int(timeout_seconds or 1200) |
| 167 | |
| 168 | while True: |
| 169 | if time.time() > timeout_timer: |
| 170 | raise Exception("Timeout") |
| 171 | |
| 172 | status = self.get_instance_details()["status"] |
| 173 | if status == requested_status: |
| 174 | logging.info(f"Instance is {requested_status}") |
| 175 | break |
| 176 | elif status == "FAILED": |
| 177 | logging.info("Instance is in error state") |
| 178 | raise Exception("Instance is in error state") |
| 179 | else: |
| 180 | logging.info("Instance is in " + status + " state") |
| 181 | time.sleep(5) |
| 182 | |
| 183 | def get_instance_details(self, retries=5): |
| 184 | """Get the details of the instance.""" |
| 185 | |
| 186 | while retries > 0: |
| 187 | |
| 188 | try: |
| 189 | |
| 190 | response = self._fleet_api.client().get( |
| 191 | f"{self._fleet_api.base_url}/fleet/service/{self.service_id}/environment/{self.service_environment_id}/instance/{self.instance_id}", |
| 192 | timeout=60, |
| 193 | ) |
| 194 | |
| 195 | except exceptions.ReadTimeout as e: |
| 196 | retries -= 1 |
| 197 | time.sleep(3) |
| 198 | continue |
| 199 | |
| 200 | if response.status_code >= 500: |
| 201 | retries -= 1 |
| 202 | time.sleep(3) |
| 203 | continue |
| 204 | else: |
| 205 | break |
| 206 | |
| 207 | self._fleet_api.handle_response( |
| 208 | response, f"Failed to get instance state {self.instance_id}" |
| 209 | ) |
| 210 | |
| 211 | return response.json()["consumptionResourceInstanceResult"] |
| 212 | |
| 213 | def get_resource_id(self, resource_key: str = None) -> str | None: |
| 214 | """Get the resource ID of the instance.""" |
| 215 | |
| 216 | network_topology = self.get_network_topology() |
| 217 | |
| 218 | # find key for object with the correct resourceKey |
| 219 | |
| 220 | for key in network_topology.keys(): |
| 221 | if network_topology[key]["resourceKey"] == ( |
| 222 | resource_key or self.resource_key |
| 223 | ): |
| 224 | return key |
| 225 | |
| 226 | def delete(self, wait_for_delete: bool): |
| 227 | """Delete the instance. Optionally wait for the instance to be deleted.""" |
| 228 | |
| 229 | resource_id = self.get_resource_id() |
| 230 | |
| 231 | if resource_id is None: |
| 232 | raise Exception(f"Resource ID not found for instance {self.instance_id}") |
| 233 | |
| 234 | response = self._fleet_api.client().delete( |
| 235 | f"{self._fleet_api.base_url}/fleet/service/{self.service_id}/environment/{self.service_environment_id}/instance/{self.instance_id}", |
| 236 | timeout=60, |
| 237 | data=json.dumps({"resourceId": resource_id}), |
| 238 | ) |
| 239 | |
| 240 | self._fleet_api.handle_response( |
| 241 | response, f"Failed to delete instance {self.instance_id}" |
| 242 | ) |
| 243 | |
| 244 | if not wait_for_delete: |
| 245 | return |
| 246 | |
| 247 | try: |
| 248 | self.wait_for_instance_status( |
| 249 | timeout_seconds=self.deployment_delete_timeout_seconds |
| 250 | ) |
| 251 | except Exception as e: |
| 252 | if e.args[0] == "Timeout": |
| 253 | raise Exception(f"Failed to delete instance {self.instance_id}") |
| 254 | |
| 255 | def stop(self, wait_for_ready: bool, retry=10): |
| 256 | """Stop the instance. Optionally wait for the instance to be ready.""" |
| 257 | |
| 258 | response = self._fleet_api.client().post( |
| 259 | f"{self._fleet_api.base_url}/fleet/service/{self.service_id}/environment/{self.service_environment_id}/instance/{self.instance_id}/stop", |
| 260 | timeout=60, |
| 261 | data=json.dumps({"resourceId": self.get_resource_id()}), |
| 262 | ) |
| 263 | |
| 264 | if "operation is already in progress" in response.text and retry > 0: |
| 265 | time.sleep(90) |
| 266 | return self.stop(wait_for_ready, retry - 1) |
| 267 | |
| 268 | self._fleet_api.handle_response( |
| 269 | response, f"Failed to stop instance {self.instance_id}" |
| 270 | ) |
| 271 | |
| 272 | if not wait_for_ready: |
| 273 | return |
| 274 | |
| 275 | self.wait_for_instance_status( |
| 276 | requested_status="STOPPED", |
| 277 | timeout_seconds=self.deployment_failover_timeout_seconds, |
| 278 | ) |
| 279 | |
| 280 | def start(self, wait_for_ready: bool, retry=10): |
| 281 | """Start the instance. Optionally wait for the instance to be ready.""" |
| 282 | |
| 283 | response = self._fleet_api.client().post( |
| 284 | f"{self._fleet_api.base_url}/fleet/service/{self.service_id}/environment/{self.service_environment_id}/instance/{self.instance_id}/start", |
| 285 | timeout=60, |
| 286 | data=json.dumps({"resourceId": self.get_resource_id()}), |
| 287 | ) |
| 288 | |
| 289 | if "operation is already in progress" in response.text and retry > 0: |
| 290 | time.sleep(90) |
| 291 | return self.start(wait_for_ready, retry - 1) |
| 292 | |
| 293 | self._fleet_api.handle_response( |
| 294 | response, f"Failed to start instance {self.instance_id}" |
| 295 | ) |
| 296 | |
| 297 | if not wait_for_ready: |
| 298 | return |
| 299 | |
| 300 | self.wait_for_instance_status( |
| 301 | timeout_seconds=self.deployment_failover_timeout_seconds |
| 302 | ) |
| 303 | |
| 304 | def trigger_failover( |
| 305 | self, replica_id: str, wait_for_ready: bool, resource_id: str = None, retry=10 |
| 306 | ): |
| 307 | """Trigger failover for the instance. Optionally wait for the instance to be ready.""" |
| 308 | logging.info(f"Triggering failover for instance {self.instance_id}") |
| 309 | |
| 310 | data = { |
| 311 | "failedReplicaID": replica_id, |
| 312 | "failedReplicaAction": "FAILOVER_AND_RESTART", |
| 313 | "resourceId": resource_id or self.get_resource_id(), |
| 314 | } |
| 315 | |
| 316 | response = self._fleet_api.client().post( |
| 317 | f"{self._fleet_api.base_url}/fleet/service/{self.service_id}/environment/{self.service_environment_id}/instance/{self.instance_id}/failover", |
| 318 | data=json.dumps(data), |
| 319 | timeout=60, |
| 320 | ) |
| 321 | |
| 322 | if "operation is already in progress" in response.text and retry > 0: |
| 323 | time.sleep(90) |
| 324 | return self.trigger_failover( |
| 325 | replica_id, wait_for_ready, resource_id, retry - 1 |
| 326 | ) |
| 327 | |
| 328 | self._fleet_api.handle_response( |
| 329 | response, f"Failed to trigger failover for instance {self.instance_id}" |
| 330 | ) |
| 331 | |
| 332 | if not wait_for_ready: |
| 333 | return |
| 334 | |
| 335 | self.wait_for_instance_status( |
| 336 | timeout_seconds=self.deployment_failover_timeout_seconds |
| 337 | ) |
| 338 | |
| 339 | def update_instance_type( |
| 340 | self, new_instance_type: str, wait_until_ready: bool = True, retry=5 |
| 341 | ): |
| 342 | """Update the instance type.""" |
| 343 | |
| 344 | data = { |
| 345 | "nodeInstanceType": new_instance_type, |
| 346 | } |
| 347 | |
| 348 | return self.update_params(wait_until_ready, retry, **data) |
| 349 | |
| 350 | def update_params(self, wait_until_ready: bool = True, retry=10, **kwargs): |
| 351 | """Update the instance parameters.""" |
| 352 | |
| 353 | self.wait_for_instance_status(timeout_seconds=1200) |
| 354 | |
| 355 | data = {"requestParams": kwargs} |
| 356 | |
| 357 | response = self._fleet_api.client().patch( |
| 358 | 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}", |
| 359 | data=json.dumps(data), |
| 360 | timeout=60, |
| 361 | ) |
| 362 | |
| 363 | if "operation is already in progress" in response.text and retry > 0: |
| 364 | time.sleep(90) |
| 365 | return self.update_params(wait_until_ready, retry - 1, **kwargs) |
| 366 | |
| 367 | self._fleet_api.handle_response( |
| 368 | response, f"Failed to update instance type {self.instance_id}" |
| 369 | ) |
| 370 | |
| 371 | if not wait_until_ready: |
| 372 | return |
| 373 | |
| 374 | self.wait_for_instance_status( |
| 375 | timeout_seconds=self.deployment_update_timeout_seconds |
| 376 | ) |
| 377 | |
| 378 | def upgrade( |
| 379 | self, |
| 380 | service_id: str, |
| 381 | product_tier_id: str, |
| 382 | source_version: str, |
| 383 | target_version: str, |
| 384 | wait_until_ready: bool = False, |
| 385 | upgrade_timeout: int = 1200, |
| 386 | ): |
| 387 | |
| 388 | data = { |
| 389 | "sourceVersion": source_version, |
| 390 | "targetVersion": target_version, |
| 391 | "upgradeFilters": {"INSTANCE_IDS": [self.instance_id]}, |
| 392 | } |
| 393 | |
| 394 | response = self._fleet_api.client().post( |
| 395 | f"{self._fleet_api.base_url}/fleet/service/{service_id}/productTier/{product_tier_id}/upgrade-path", |
| 396 | json=data, |
| 397 | timeout=60, |
| 398 | ) |
| 399 | |
| 400 | self._fleet_api.handle_response(response, "Failed to upgrade instance") |
| 401 | |
| 402 | upgrade_id = response.json()["upgradePathId"] |
| 403 | |
| 404 | if wait_until_ready: |
| 405 | self._wait_until_upgrade_ready( |
| 406 | service_id, product_tier_id, upgrade_id, upgrade_timeout |
| 407 | ) |
| 408 | |
| 409 | def _wait_until_upgrade_ready( |
| 410 | self, |
| 411 | service_id: str, |
| 412 | product_tier_id: str, |
| 413 | upgrade_id: str, |
| 414 | upgrade_timeout: int = 1200, |
| 415 | ): |
| 416 | right_now = time.time() |
| 417 | skipped_running = False |
| 418 | while True: |
| 419 | response = self._fleet_api.client().get( |
| 420 | f"{self._fleet_api.base_url}/fleet/service/{service_id}/productTier/{product_tier_id}/upgrade-path/{upgrade_id}", |
| 421 | timeout=60, |
| 422 | ) |
| 423 | |
| 424 | self._fleet_api.handle_response(response, "Failed to get upgrade status") |
| 425 | |
| 426 | status = response.json()["status"] |
| 427 | |
| 428 | if ( |
| 429 | status == "RUNNING" |
| 430 | and not skipped_running |
| 431 | and time.time() - right_now < upgrade_timeout |
| 432 | ): |
| 433 | logging.info("Skipping first running status") |
| 434 | time.sleep(5) |
| 435 | continue |
| 436 | |
| 437 | skipped_running = True |
| 438 | |
| 439 | if status == "PENDING": |
| 440 | logging.info("Upgrade pending") |
| 441 | time.sleep(10) |
| 442 | logging.info("Waiting for instance to be ready") |
| 443 | if status == "IN_PROGRESS": |
| 444 | logging.info("Upgrade in progress") |
| 445 | time.sleep(10) |
| 446 | logging.info("Waiting for instance to be ready") |
| 447 | elif status == "COMPLETE": |
| 448 | logging.info("Upgrade completed") |
| 449 | break |
| 450 | else: |
| 451 | raise Exception(f"Upgrade failed: {status}") |
| 452 | |
| 453 | if time.time() - right_now > upgrade_timeout: |
| 454 | raise Exception("Upgrade timed out") |
| 455 | |
| 456 | def get_network_topology(self, force_refresh=False): |
| 457 | |
| 458 | if self._network_topology is not None and not force_refresh: |
| 459 | return self._network_topology |
| 460 | |
| 461 | self._network_topology = self.get_instance_details()["detailedNetworkTopology"] |
| 462 | |
| 463 | return self._network_topology |
| 464 | |
| 465 | def get_connection_endpoints(self): |
| 466 | """Get the connection endpoints for the instance.""" |
| 467 | |
| 468 | resources = self.get_network_topology() |
| 469 | |
| 470 | resources_keys = resources.keys() |
| 471 | |
| 472 | endpoints = [] |
| 473 | for key in resources_keys: |
| 474 | if "nodes" in resources[key] and len(resources[key]["nodes"]) > 0: |
| 475 | for node in resources[key]["nodes"]: |
| 476 | endpoints.append( |
| 477 | { |
| 478 | "id": node["id"], |
| 479 | "endpoint": node["endpoint"], |
| 480 | "ports": node["ports"], |
| 481 | } |
| 482 | ) |
| 483 | |
| 484 | if len(endpoints) == 0: |
| 485 | raise Exception("No endpoints found") |
| 486 | |
| 487 | return endpoints |
| 488 | |
| 489 | def get_cluster_endpoint(self): |
| 490 | resources = self.get_network_topology() |
| 491 | |
| 492 | resources_keys = resources.keys() |
| 493 | |
| 494 | for key in resources_keys: |
| 495 | if ( |
| 496 | "clusterEndpoint" in resources[key] |
| 497 | and len(resources[key]["clusterEndpoint"]) > 0 |
| 498 | and "streamer." not in resources[key]["clusterEndpoint"] |
| 499 | and "clusterPorts" in resources[key] |
| 500 | and resources[key]["networkingType"] != "INTERNAL" |
| 501 | ): |
| 502 | return { |
| 503 | "endpoint": resources[key]["clusterEndpoint"], |
| 504 | "ports": resources[key]["clusterPorts"], |
| 505 | } |
| 506 | |
| 507 | def create_connection( |
| 508 | self, ssl: bool = False, force_reconnect: bool = False, retries=5 |
| 509 | ): |
| 510 | |
| 511 | if self._connection is not None and not force_reconnect: |
| 512 | return self._connection |
| 513 | |
| 514 | endpoint = self.get_cluster_endpoint() |
| 515 | |
| 516 | # Connect to the master node |
| 517 | while retries > 0: |
| 518 | try: |
| 519 | logging.info( |
| 520 | f"Connecting to {endpoint['endpoint']}:{endpoint['ports'][0]}" |
| 521 | ) |
| 522 | self._connection = FalkorDB( |
| 523 | host=endpoint["endpoint"], |
| 524 | port=endpoint["ports"][0], |
| 525 | username="falkordb", |
| 526 | password=self.falkordb_password, |
| 527 | ssl=ssl, |
| 528 | cluster_error_retry_attempts=20, |
| 529 | retry=retry.Retry( |
| 530 | retries=20, |
| 531 | backoff=backoff.ExponentialBackoff(base=3), |
| 532 | supported_errors=( |
| 533 | ConnectionRefusedError, |
| 534 | ConnectionError, |
| 535 | TimeoutError, |
| 536 | socket.timeout, |
| 537 | redis_exceptions.ConnectionError |
| 538 | ), |
| 539 | ), |
| 540 | ) |
| 541 | break |
| 542 | except Exception as e: |
| 543 | logging.error(f"Failed to connect to the master node: {e}") |
| 544 | retries -= 1 |
| 545 | time.sleep(60) |
| 546 | |
| 547 | if self._connection is None: |
| 548 | raise Exception("Failed to connect to the master node") |
| 549 | |
| 550 | return self._connection |
| 551 | |
| 552 | def generate_data(self, graph_count: int): |
| 553 | """Generate data for the instance.""" |
| 554 | |
| 555 | db = self.create_connection() |
| 556 | |
| 557 | logging.info("Generating data") |
| 558 | for i in range(0, graph_count): |
| 559 | |
| 560 | name = rand_string() |
| 561 | g = db.select_graph(name) |
| 562 | |
| 563 | node_count = rand_range(2000, 1000000) |
| 564 | node_count = rand_range(200, 1000) |
| 565 | g.query( |
| 566 | """UNWIND range (0, $node_count) as x |
| 567 | CREATE (a:L {v:x})-[:R]->(b:X {v: tostring(x)}), (a)-[:Z]->(:Y {v:tostring(x)})""", |
| 568 | {"node_count": node_count}, |
| 569 | ) |
| 570 | logging.info("Data generated") |