Path: blob/main/singlestoredb/fusion/handlers/utils.py
801 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.inference_api import InferenceAPIInfo15from ...management.inference_api import InferenceAPIManager16from ...management.workspace import StarterWorkspace17from ...management.workspace import Workspace18from ...management.workspace import WorkspaceGroup19from ...management.workspace import WorkspaceManager202122def get_workspace_manager() -> WorkspaceManager:23"""Return a new workspace manager."""24return manage_workspaces()252627def get_files_manager() -> FilesManager:28"""Return a new files manager."""29return manage_files()303132def dt_isoformat(dt: Optional[datetime.datetime]) -> Optional[str]:33"""Convert datetime to string."""34if dt is None:35return None36return dt.isoformat()373839def get_workspace_group(params: Dict[str, Any]) -> WorkspaceGroup:40"""41Find a workspace group matching group_id or group_name.4243This function will get a workspace group or ID from the44following parameters:4546* params['group_name']47* params['group_id']48* params['group']['group_name']49* params['group']['group_id']50* params['in_group']['group_name']51* params['in_group']['group_id']5253Or, from the SINGLESTOREDB_WORKSPACE_GROUP environment variable.5455"""56manager = get_workspace_manager()5758group_name = params.get('group_name') or \59(params.get('in_group') or {}).get('group_name') or \60(params.get('group') or {}).get('group_name')61if group_name:62workspace_groups = [63x for x in manager.workspace_groups64if x.name == group_name65]6667if not workspace_groups:68raise KeyError(69f'no workspace group found with name: {group_name}',70)7172if len(workspace_groups) > 1:73ids = ', '.join(x.id for x in workspace_groups)74raise ValueError(75f'more than one workspace group with given name was found: {ids}',76)7778return workspace_groups[0]7980group_id = params.get('group_id') or \81(params.get('in_group') or {}).get('group_id') or \82(params.get('group') or {}).get('group_id')83if group_id:84try:85return manager.get_workspace_group(group_id)86except ManagementError as exc:87if exc.errno == 404:88raise KeyError(f'no workspace group found with ID: {group_id}')89raise9091if os.environ.get('SINGLESTOREDB_WORKSPACE_GROUP'):92try:93return manager.get_workspace_group(94os.environ['SINGLESTOREDB_WORKSPACE_GROUP'],95)96except ManagementError as exc:97if exc.errno == 404:98raise KeyError(99'no workspace found with ID: '100f'{os.environ["SINGLESTOREDB_WORKSPACE_GROUP"]}',101)102raise103104if os.environ.get('SINGLESTOREDB_CLUSTER'):105raise ValueError('clusters and shared workspaces are not currently supported')106107raise KeyError('no workspace group was specified')108109110def get_workspace(params: Dict[str, Any]) -> Workspace:111"""112Retrieve the specified workspace.113114This function will get a workspace group or ID from the115following parameters:116117* params['workspace_name']118* params['workspace_id']119* params['workspace']['workspace_name']120* params['workspace']['workspace_id']121122Or, from the SINGLESTOREDB_WORKSPACE environment variable.123124"""125manager = get_workspace_manager()126workspace_name = params.get('workspace_name') or \127(params.get('workspace') or {}).get('workspace_name')128if workspace_name:129wg = get_workspace_group(params)130workspaces = [131x for x in wg.workspaces132if x.name == workspace_name133]134135if not workspaces:136raise KeyError(137f'no workspace found with name: {workspace_name}',138)139140if len(workspaces) > 1:141ids = ', '.join(x.id for x in workspaces)142raise ValueError(143f'more than one workspace with given name was found: {ids}',144)145146return workspaces[0]147148workspace_id = params.get('workspace_id') or \149(params.get('workspace') or {}).get('workspace_id')150if workspace_id:151try:152return manager.get_workspace(workspace_id)153except ManagementError as exc:154if exc.errno == 404:155raise KeyError(f'no workspace found with ID: {workspace_id}')156raise157158if os.environ.get('SINGLESTOREDB_WORKSPACE'):159try:160return manager.get_workspace(161os.environ['SINGLESTOREDB_WORKSPACE'],162)163except ManagementError as exc:164if exc.errno == 404:165raise KeyError(166'no workspace found with ID: '167f'{os.environ["SINGLESTOREDB_WORKSPACE"]}',168)169raise170171if os.environ.get('SINGLESTOREDB_CLUSTER'):172raise ValueError('clusters and shared workspaces are not currently supported')173174raise KeyError('no workspace was specified')175176177def get_deployment(178params: Dict[str, Any],179) -> Union[WorkspaceGroup, StarterWorkspace]:180"""181Find a starter workspace matching deployment_id or deployment_name.182183This function will get a starter workspace or ID from the184following parameters:185186* params['deployment_name']187* params['deployment_id']188* params['group']['deployment_name']189* params['group']['deployment_id']190* params['in_deployment']['deployment_name']191* params['in_deployment']['deployment_id']192* params['in']['in_group']['deployment_name']193* params['in']['in_group']['deployment_id']194* params['in']['in_deployment']['deployment_name']195* params['in']['in_deployment']['deployment_id']196197Or, from the SINGLESTOREDB_WORKSPACE_GROUP198or SINGLESTOREDB_CLUSTER environment variables.199200"""201manager = get_workspace_manager()202203#204# Search for deployment by name205#206deployment_name = params.get('deployment_name') or \207(params.get('in_deployment') or {}).get('deployment_name') or \208(params.get('group') or {}).get('deployment_name') or \209((params.get('in') or {}).get('in_group') or {}).get('deployment_name') or \210((params.get('in') or {}).get('in_deployment') or {}).get('deployment_name')211212if deployment_name:213# Standard workspace group214workspace_groups = [215x for x in manager.workspace_groups216if x.name == deployment_name217]218219if len(workspace_groups) == 1:220return workspace_groups[0]221222elif len(workspace_groups) > 1:223ids = ', '.join(x.id for x in workspace_groups)224raise ValueError(225f'more than one workspace group with given name was found: {ids}',226)227228# Starter workspace229starter_workspaces = [230x for x in manager.starter_workspaces231if x.name == deployment_name232]233234if len(starter_workspaces) == 1:235return starter_workspaces[0]236237elif len(starter_workspaces) > 1:238ids = ', '.join(x.id for x in starter_workspaces)239raise ValueError(240f'more than one starter workspace with given name was found: {ids}',241)242243raise KeyError(f'no deployment found with name: {deployment_name}')244245#246# Search for deployment by ID247#248deployment_id = params.get('deployment_id') or \249(params.get('in_deployment') or {}).get('deployment_id') or \250(params.get('group') or {}).get('deployment_id') or \251((params.get('in') or {}).get('in_group') or {}).get('deployment_id') or \252((params.get('in') or {}).get('in_deployment') or {}).get('deployment_id')253254if deployment_id:255try:256# Standard workspace group257return manager.get_workspace_group(deployment_id)258except ManagementError as exc:259if exc.errno == 404:260try:261# Starter workspace262return manager.get_starter_workspace(deployment_id)263except ManagementError as exc:264if exc.errno == 404:265raise KeyError(f'no deployment found with ID: {deployment_id}')266raise267else:268raise269270# Use workspace group from environment271if os.environ.get('SINGLESTOREDB_WORKSPACE_GROUP'):272try:273return manager.get_workspace_group(274os.environ['SINGLESTOREDB_WORKSPACE_GROUP'],275)276except ManagementError as exc:277if exc.errno == 404:278raise KeyError(279'no workspace found with ID: '280f'{os.environ["SINGLESTOREDB_WORKSPACE_GROUP"]}',281)282raise283284# Use cluster from environment285if os.environ.get('SINGLESTOREDB_CLUSTER'):286try:287return manager.get_starter_workspace(288os.environ['SINGLESTOREDB_CLUSTER'],289)290except ManagementError as exc:291if exc.errno == 404:292raise KeyError(293'no starter workspace found with ID: '294f'{os.environ["SINGLESTOREDB_CLUSTER"]}',295)296raise297298raise KeyError('no deployment was specified')299300301def get_file_space(params: Dict[str, Any]) -> FileSpace:302"""303Retrieve the specified file space.304305This function will get a file space from the306following parameters:307308* params['file_location']309"""310manager = get_files_manager()311312file_location = params.get('file_location')313if file_location:314file_location_lower_case = file_location.lower()315316if file_location_lower_case == mgmt_files.PERSONAL_SPACE:317return manager.personal_space318elif file_location_lower_case == mgmt_files.SHARED_SPACE:319return manager.shared_space320elif file_location_lower_case == mgmt_files.MODELS_SPACE:321return manager.models_space322else:323raise ValueError(f'invalid file location: {file_location}')324325raise KeyError('no file space was specified')326327328def get_inference_api_manager() -> InferenceAPIManager:329"""Return the inference API manager for the current project."""330wm = get_workspace_manager()331return wm.organization.inference_apis332333334def get_inference_api(params: Dict[str, Any]) -> InferenceAPIInfo:335"""Return an inference API based on model name in params."""336inference_apis = get_inference_api_manager()337model_name = params['model_name']338return inference_apis.get(model_name)339340341