Path: blob/main/resources/create_test_cluster.py
469 views
#!/usr/bin/env python1# type: ignore2from __future__ import annotations34import os5import random6import re7import secrets8import subprocess9import sys10import time11import uuid12from optparse import OptionParser1314import singlestoredb as s2151617# Handle command-line options18usage = 'usage: %prog [options] workspace-name'19parser = OptionParser(usage=usage)20parser.add_option(21'-r', '--region',22default='AWS::*US East 1*',23help='region pattern or ID',24)25parser.add_option(26'-p', '--password',27default=secrets.token_urlsafe(20) + '-x&$',28help='admin password',29)30parser.add_option(31'-e', '--expires',32default='4h',33help='timestamp when workspace should expire (4h)',34)35parser.add_option(36'-s', '--size',37default='S-00',38help='size of the workspace (S-00)',39)40parser.add_option(41'-t', '--token',42help='API key for the workspace management API',43)44parser.add_option(45'--http-port', type='int',46help='enable HTTP API on given port',47)48parser.add_option(49'-i', '--init-sql',50help='initialize database with given SQL file',51)52parser.add_option(53'-o', '--output',54default='env', choices=['env', 'github', 'json'],55help='report workspace information in the requested format: github, env, json',56)57parser.add_option(58'-d', '--database',59help='database name to create',60)6162(options, args) = parser.parse_args()6364if len(args) != 1:65parser.print_help()66sys.exit(1)6768if options.init_sql and not os.path.isfile(options.init_sql):69print('ERROR: Could not locate SQL file: {options.init_sql}', file=sys.stderr)70sys.exit(1)717273# Connect to workspace74wm = s2.manage_workspaces(options.token or None)7576# Find matching region77if '::' in options.region:78pattern = options.region.replace('*', '.*')79regions = wm.regions80for item in random.sample(regions, k=len(regions)):81region_name = '{}::{}'.format(item.provider, item.name)82if re.match(pattern, region_name):83options.region = item.id84break8586if '::' in options.region:87print(88'ERROR: Could not find a region mating the pattern: '89'{options.region}', file=sys.stderr,90)91sys.exit(1)929394# Create workspace group95wg_name = 'Python Client Testing'9697wgs = [x for x in wm.workspace_groups if x.name == wg_name]98if len(wgs) > 1:99print('ERROR: There is more than one workspace group with the specified name.')100sys.exit(1)101elif len(wgs) == 1:102wg = wgs[0]103else:104wg = wm.create_workspace_group(105wg_name,106region=options.region,107admin_password=options.password,108# firewall_ranges=requests.get('https://api.github.com/meta').json()['actions'],109firewall_ranges=['0.0.0.0/0'],110allow_all_traffic=True,111)112113# Make sure the workspace group exists before continuing114timeout = 300115while timeout > 0 and not [x for x in wm.workspace_groups if x.name == wg_name]:116time.sleep(10)117timeout -= 10118119ws_name = re.sub(r'^-|-$', r'', re.sub(r'-+', r'-', re.sub(r'\s+', '-', args[0].lower())))120121ws = wg.create_workspace(122ws_name,123size=options.size,124wait_on_active=True,125)126127# Make sure the endpoint exists before continuing128timeout = 300129while timeout > 0 and not ws.endpoint:130time.sleep(10)131ws.refresh()132timeout -= 10133134if not ws.endpoint:135print('ERROR: Endpoint was never activated.')136sys.exit(1)137138139# Extra pause for server to become available140time.sleep(10)141142database = options.database143if not database:144database = 'TEMP_{}'.format(uuid.uuid4()).replace('-', '_')145146host = ws.endpoint147if ':' in host:148host, port = host.split(':', 1)149port = int(port)150else:151port = 3306152153# Print workspace information154if options.output == 'env':155print(f'CLUSTER_ID={ws.id}')156print(f'CLUSTER_HOST={host}')157print(f'CLUSTER_PORT={port}')158print(f'CLUSTER_DATABASE={database}')159elif options.output == 'github':160with open(os.environ['GITHUB_OUTPUT'], 'a') as output:161print(f'cluster-id={ws.id}', file=output)162print(f'cluster-host={host}', file=output)163print(f'cluster-port={port}', file=output)164print(f'cluster-database={database}', file=output)165elif options.output == 'json':166print('{')167print(f' "cluster-id": "{ws.id}",')168print(f' "cluster-host": "{host}",')169print(f' "cluster-port": {port}')170print(f' "cluster-database": {database}')171print('}')172173# Initialize the database174if options.init_sql:175init_db = [176os.path.join(os.path.dirname(__file__), 'init_db.py'),177'--host', str(host), '--port', str(port),178'--user', 'admin', '--password', options.password,179'--database', database,180]181182if options.http_port:183init_db += ['--http-port', str(options.http_port)]184185init_db.append(options.init_sql)186187subprocess.check_call(init_db)188189190