Path: blob/main/singlestoredb/fusion/handlers/utils.py
469 views
#!/usr/bin/env python1import datetime2import os3from typing import Any4from typing import Dict5from typing import Optional6from typing import Union78from ...exceptions import ManagementError9from ...management import files as mgmt_files10from ...management import manage_workspaces11from ...management.files import FilesManager12from ...management.files import FileSpace13from ...management.files import manage_files14from ...management.workspace import StarterWorkspace15from ...management.workspace import Workspace16from ...management.workspace import WorkspaceGroup17from ...management.workspace import WorkspaceManager181920def get_workspace_manager() -> WorkspaceManager:21"""Return a new workspace manager."""22return manage_workspaces()232425def get_files_manager() -> FilesManager:26"""Return a new files manager."""27return manage_files()282930def dt_isoformat(dt: Optional[datetime.datetime]) -> Optional[str]:31"""Convert datetime to string."""32if dt is None:33return None34return dt.isoformat()353637def get_workspace_group(params: Dict[str, Any]) -> WorkspaceGroup:38"""39Find a workspace group matching group_id or group_name.4041This function will get a workspace group or ID from the42following parameters:4344* params['group_name']45* params['group_id']46* params['group']['group_name']47* params['group']['group_id']48* params['in_group']['group_name']49* params['in_group']['group_id']5051Or, from the SINGLESTOREDB_WORKSPACE_GROUP environment variable.5253"""54manager = get_workspace_manager()5556group_name = params.get('group_name') or \57(params.get('in_group') or {}).get('group_name') or \58(params.get('group') or {}).get('group_name')59if group_name:60workspace_groups = [61x for x in manager.workspace_groups62if x.name == group_name63]6465if not workspace_groups:66raise KeyError(67f'no workspace group found with name: {group_name}',68)6970if len(workspace_groups) > 1:71ids = ', '.join(x.id for x in workspace_groups)72raise ValueError(73f'more than one workspace group with given name was found: {ids}',74)7576return workspace_groups[0]7778group_id = params.get('group_id') or \79(params.get('in_group') or {}).get('group_id') or \80(params.get('group') or {}).get('group_id')81if group_id:82try:83return manager.get_workspace_group(group_id)84except ManagementError as exc:85if exc.errno == 404:86raise KeyError(f'no workspace group found with ID: {group_id}')87raise8889if os.environ.get('SINGLESTOREDB_WORKSPACE_GROUP'):90try:91return manager.get_workspace_group(92os.environ['SINGLESTOREDB_WORKSPACE_GROUP'],93)94except ManagementError as exc:95if exc.errno == 404:96raise KeyError(97'no workspace found with ID: '98f'{os.environ["SINGLESTOREDB_WORKSPACE_GROUP"]}',99)100raise101102if os.environ.get('SINGLESTOREDB_CLUSTER'):103raise ValueError('clusters and shared workspaces are not currently supported')104105raise KeyError('no workspace group was specified')106107108def get_workspace(params: Dict[str, Any]) -> Workspace:109"""110Retrieve the specified workspace.111112This function will get a workspace group or ID from the113following parameters:114115* params['workspace_name']116* params['workspace_id']117* params['workspace']['workspace_name']118* params['workspace']['workspace_id']119120Or, from the SINGLESTOREDB_WORKSPACE environment variable.121122"""123manager = get_workspace_manager()124workspace_name = params.get('workspace_name') or \125(params.get('workspace') or {}).get('workspace_name')126if workspace_name:127wg = get_workspace_group(params)128workspaces = [129x for x in wg.workspaces130if x.name == workspace_name131]132133if not workspaces:134raise KeyError(135f'no workspace found with name: {workspace_name}',136)137138if len(workspaces) > 1:139ids = ', '.join(x.id for x in workspaces)140raise ValueError(141f'more than one workspace with given name was found: {ids}',142)143144return workspaces[0]145146workspace_id = params.get('workspace_id') or \147(params.get('workspace') or {}).get('workspace_id')148if workspace_id:149try:150return manager.get_workspace(workspace_id)151except ManagementError as exc:152if exc.errno == 404:153raise KeyError(f'no workspace found with ID: {workspace_id}')154raise155156if os.environ.get('SINGLESTOREDB_WORKSPACE'):157try:158return manager.get_workspace(159os.environ['SINGLESTOREDB_WORKSPACE'],160)161except ManagementError as exc:162if exc.errno == 404:163raise KeyError(164'no workspace found with ID: '165f'{os.environ["SINGLESTOREDB_WORKSPACE"]}',166)167raise168169if os.environ.get('SINGLESTOREDB_CLUSTER'):170raise ValueError('clusters and shared workspaces are not currently supported')171172raise KeyError('no workspace was specified')173174175def get_deployment(176params: Dict[str, Any],177) -> Union[WorkspaceGroup, StarterWorkspace]:178"""179Find a starter workspace matching deployment_id or deployment_name.180181This function will get a starter workspace or ID from the182following parameters:183184* params['deployment_name']185* params['deployment_id']186* params['group']['deployment_name']187* params['group']['deployment_id']188* params['in_deployment']['deployment_name']189* params['in_deployment']['deployment_id']190* params['in']['in_group']['deployment_name']191* params['in']['in_group']['deployment_id']192* params['in']['in_deployment']['deployment_name']193* params['in']['in_deployment']['deployment_id']194195Or, from the SINGLESTOREDB_WORKSPACE_GROUP196or SINGLESTOREDB_CLUSTER environment variables.197198"""199manager = get_workspace_manager()200201#202# Search for deployment by name203#204deployment_name = params.get('deployment_name') or \205(params.get('in_deployment') or {}).get('deployment_name') or \206(params.get('group') or {}).get('deployment_name') or \207((params.get('in') or {}).get('in_group') or {}).get('deployment_name') or \208((params.get('in') or {}).get('in_deployment') or {}).get('deployment_name')209210if deployment_name:211# Standard workspace group212workspace_groups = [213x for x in manager.workspace_groups214if x.name == deployment_name215]216217if len(workspace_groups) == 1:218return workspace_groups[0]219220elif len(workspace_groups) > 1:221ids = ', '.join(x.id for x in workspace_groups)222raise ValueError(223f'more than one workspace group with given name was found: {ids}',224)225226# Starter workspace227starter_workspaces = [228x for x in manager.starter_workspaces229if x.name == deployment_name230]231232if len(starter_workspaces) == 1:233return starter_workspaces[0]234235elif len(starter_workspaces) > 1:236ids = ', '.join(x.id for x in starter_workspaces)237raise ValueError(238f'more than one starter workspace with given name was found: {ids}',239)240241raise KeyError(f'no deployment found with name: {deployment_name}')242243#244# Search for deployment by ID245#246deployment_id = params.get('deployment_id') or \247(params.get('in_deployment') or {}).get('deployment_id') or \248(params.get('group') or {}).get('deployment_id') or \249((params.get('in') or {}).get('in_group') or {}).get('deployment_id') or \250((params.get('in') or {}).get('in_deployment') or {}).get('deployment_id')251252if deployment_id:253try:254# Standard workspace group255return manager.get_workspace_group(deployment_id)256except ManagementError as exc:257if exc.errno == 404:258try:259# Starter workspace260return manager.get_starter_workspace(deployment_id)261except ManagementError as exc:262if exc.errno == 404:263raise KeyError(f'no deployment found with ID: {deployment_id}')264raise265else:266raise267268# Use workspace group from environment269if os.environ.get('SINGLESTOREDB_WORKSPACE_GROUP'):270try:271return manager.get_workspace_group(272os.environ['SINGLESTOREDB_WORKSPACE_GROUP'],273)274except ManagementError as exc:275if exc.errno == 404:276raise KeyError(277'no workspace found with ID: '278f'{os.environ["SINGLESTOREDB_WORKSPACE_GROUP"]}',279)280raise281282# Use cluster from environment283if os.environ.get('SINGLESTOREDB_CLUSTER'):284try:285return manager.get_starter_workspace(286os.environ['SINGLESTOREDB_CLUSTER'],287)288except ManagementError as exc:289if exc.errno == 404:290raise KeyError(291'no starter workspace found with ID: '292f'{os.environ["SINGLESTOREDB_CLUSTER"]}',293)294raise295296raise KeyError('no deployment was specified')297298299def get_file_space(params: Dict[str, Any]) -> FileSpace:300"""301Retrieve the specified file space.302303This function will get a file space from the304following parameters:305306* params['file_location']307"""308manager = get_files_manager()309310file_location = params.get('file_location')311if file_location:312file_location_lower_case = file_location.lower()313314if file_location_lower_case == mgmt_files.PERSONAL_SPACE:315return manager.personal_space316elif file_location_lower_case == mgmt_files.SHARED_SPACE:317return manager.shared_space318elif file_location_lower_case == mgmt_files.MODELS_SPACE:319return manager.models_space320else:321raise ValueError(f'invalid file location: {file_location}')322323raise KeyError('no file space was specified')324325326