Space#
HPSpace#
- class sagemaker.hyperpod.space.hyperpod_space.HPSpace[source]#
Bases:
BaseModelHyperPod Space on Amazon SageMaker HyperPod clusters.
This class provides methods to create, manage, and monitor spaces on SageMaker HyperPod clusters orchestrated by Amazon EKS. Spaces are interactive workspaces that provide development environments with configurable resources, storage, and access controls.
Attributes:
Attribute
Type
Description
config
SpaceConfig
The space configuration using the space parameter model
raw_resource
Dict[str, Any], optional
The complete Kubernetes resource data including apiVersion, kind, metadata, and status
Usage Examples
>>> # Create a new space >>> from hyperpod_space_template.v1_0.model import SpaceConfig >>> config = SpaceConfig(name="my-space", display_name="My Space") >>> space = HPSpace(config=config) >>> space.create() >>> # List all spaces >>> spaces = HPSpace.list() >>> for space in spaces: ... print(f"Space: {space.config.name}")
- config: SpaceConfig#
- property api_version: str | None#
Get the apiVersion from the Kubernetes resource.
Returns:
str or None: The API version of the Kubernetes resource, or None if raw_resource is not available
Usage Examples
>>> space = HPSpace.get("my-space") >>> print(f"API Version: {space.api_version}")
- property kind: str | None#
Get the kind from the Kubernetes resource.
Returns:
str or None: The kind of the Kubernetes resource, or None if raw_resource is not available
Usage Examples
>>> space = HPSpace.get("my-space") >>> print(f"Resource Kind: {space.kind}")
- property metadata: Dict[str, Any] | None#
Get the metadata from the Kubernetes resource.
Returns:
Dict[str, Any] or None: The metadata section of the Kubernetes resource, or None if raw_resource is not available
Usage Examples
>>> space = HPSpace.get("my-space") >>> print(f"Creation Time: {space.metadata['creationTimestamp']}")
- property status: Dict[str, Any] | None#
Get the status from the Kubernetes resource.
Returns:
Dict[str, Any] or None: The status section of the Kubernetes resource, or None if raw_resource is not available
Usage Examples
>>> space = HPSpace.get("my-space") >>> conditions = space.status.get('conditions', []) >>> for condition in conditions: ... print(f"{condition['type']}: {condition['status']}")
- create(debug: bool = False)[source]#
Create and submit the HyperPod Space to the Kubernetes cluster.
Creates a new space resource in the Kubernetes cluster based on the configuration provided in the space config. Validates MIG profiles if enabled and converts the configuration to the appropriate domain model.
Parameters:
Parameter
Type
Description
debug
bool, optional
Enable debug logging (default: False)
Raises:
RuntimeError: If MIG profile validation fails or unsupported profiles are used Exception: If the space creation fails or Kubernetes API call fails
Usage Examples
>>> # Create a space with debug logging >>> space = HPSpace(config=space_config) >>> space.create(debug=True) >>> # Create a space with default settings >>> space.create()
- classmethod list(namespace: str | None = None) List[HPSpace][source]#
List all HyperPod Spaces in the specified namespace created by the caller.
Retrieves all spaces that were either created by the current caller (based on AWS STS identity) or are marked as ‘Public’ ownership type. Uses pagination to handle large numbers of spaces efficiently.
Parameters:
Parameter
Type
Description
namespace
str, optional
The Kubernetes namespace to list spaces from. If None, uses the default namespace from current context
Returns:
List[HPSpace]: List of HPSpace instances created by the caller or marked as public
Raises:
Exception: If the Kubernetes API call fails or spaces cannot be retrieved
Usage Examples
>>> # List spaces in default namespace >>> spaces = HPSpace.list() >>> print(f"Found {len(spaces)} spaces") >>> # List spaces in specific namespace >>> spaces = HPSpace.list(namespace="my-namespace") >>> for space in spaces: ... print(f"Space: {space.config.name}")
- classmethod get(name: str, namespace: str = None) HPSpace[source]#
Get a specific HyperPod Space by name.
Retrieves a single space resource from the Kubernetes cluster and maps the response to the SpaceConfig model for easy access to configuration and status information.
Parameters:
Parameter
Type
Description
name
str
The name of the space to retrieve
namespace
str, optional
The Kubernetes namespace. If None, uses the default namespace from current context
Returns:
HPSpace: The space instance with configuration and raw Kubernetes resource data
Raises:
Exception: If the space is not found or Kubernetes API call fails
Usage Examples
>>> # Get space from default namespace >>> space = HPSpace.get("my-space") >>> print(f"Space status: {space.status}") >>> # Get space from specific namespace >>> space = HPSpace.get("my-space", namespace="production") >>> print(f"Display name: {space.config.display_name}")
- delete()[source]#
Delete the HyperPod Space from the Kubernetes cluster.
Permanently removes the space resource from the Kubernetes cluster. This operation cannot be undone and will terminate any running workloads associated with the space.
Raises:
Exception: If the deletion fails or Kubernetes API call fails
Usage Examples
>>> # Delete a space >>> space = HPSpace.get("my-space") >>> space.delete()
- update(**kwargs)[source]#
Update the HyperPod Space configuration.
Updates the space configuration with the provided parameters. Validates MIG profiles if resource updates are requested and ensures compatibility with the current node instance type.
Parameters:
Parameter
Type
Description
**kwargs
Any
Configuration fields to update (e.g., desired_status=”Stopped”, display_name=”New Name”)
Raises:
RuntimeError: If MIG profile validation fails or unsupported profiles are used Exception: If the update fails or Kubernetes API call fails
Usage Examples
>>> # Update space status >>> space = HPSpace.get("my-space") >>> space.update(desired_status="Stopped") >>> # Update display name and resources >>> space.update( ... display_name="Updated Space", ... resources={"requests": {"cpu": "2", "memory": "4Gi"}} ... )
- start()[source]#
Start the HyperPod Space by setting desired status to Running.
Convenience method that updates the space’s desired status to “Running”, which will cause the Kubernetes operator to start the space workloads.
Usage Examples
>>> # Start a space >>> space = HPSpace.get("my-space") >>> space.start()
- stop()[source]#
Stop the HyperPod Space by setting desired status to Stopped.
Convenience method that updates the space’s desired status to “Stopped”, which will cause the Kubernetes operator to stop the space workloads.
Usage Examples
>>> # Stop a space >>> space = HPSpace.get("my-space") >>> space.stop()
- list_pods() List[str][source]#
List all pods associated with this space.
Retrieves all Kubernetes pods that are labeled as belonging to this space using the workspace-name label selector.
Returns:
List[str]: List of pod names associated with the space
Raises:
Exception: If the Kubernetes API call fails
Usage Examples
>>> # List pods for a space >>> space = HPSpace.get("my-space") >>> pods = space.list_pods() >>> print(f"Found {len(pods)} pods: {pods}")
- get_logs(pod_name: str | None = None, container: str | None = None) str[source]#
Get logs from a pod associated with this space.
Retrieves logs from a specific pod and container. If no pod is specified, uses the first available pod. If no container is specified, defaults to the “workspace” container.
Parameters:
Parameter
Type
Description
pod_name
str, optional
Name of the pod to get logs from. If None, gets logs from the first available pod
container
str, optional
Name of the container to get logs from. Defaults to “workspace”
Returns:
str: The pod logs as a string
Raises:
RuntimeError: If no pods are found for the space Exception: If the Kubernetes API call fails
Usage Examples
>>> # Get logs from default pod and container >>> space = HPSpace.get("my-space") >>> logs = space.get_logs() >>> print(logs) >>> # Get logs from specific pod and container >>> logs = space.get_logs(pod_name="my-pod", container="sidecar")
- create_space_access(connection_type: str = 'vscode-remote') Dict[str, str][source]#
Create a space access for this space.
Creates a space access resource that provides remote connection capabilities to the space. Supports VS Code remote development and web UI access types.
Parameters:
Parameter
Type
Description
connection_type
str, optional
The IDE type for remote access. Must be “vscode-remote” or “web-ui” (default: “vscode-remote”)
Returns:
Dict[str, str]: Dictionary containing ‘SpaceConnectionType’ and ‘SpaceConnectionUrl’ keys
Raises:
ValueError: If connection_type is not “vscode-remote” or “web-ui” Exception: If the space access creation fails or Kubernetes API call fails
Usage Examples
>>> # Create VS Code remote access >>> space = HPSpace.get("my-space") >>> access = space.create_space_access("vscode-remote") >>> print(f"Connection URL: {access['SpaceConnectionUrl']}") >>> # Create web UI access >>> access = space.create_space_access("web-ui") >>> print(f"Web UI URL: {access['SpaceConnectionUrl']}")
- portforward_space(local_port: str, remote_port: str = DEFAULT_SPACE_PORT)[source]#
Forward local port to the space pod for development access.
Creates a port forwarding connection from a local port to a remote port on the space pod, enabling direct access to services running inside the space.
Parameters:
- Header-rows:
1
- Widths:
20 20 60
Parameter - Type - Description
local_port - str - The local port to forward from
remote_port - str, optional - The remote port on the space pod to forward to (default: DEFAULT_SPACE_PORT)
Raises:
RuntimeError: If no pods are found for the space or if the space is not in Available status KeyboardInterrupt: When the user stops the port forwarding with Ctrl+C Exception: If the port forwarding setup fails or Kubernetes API call fails
Usage Examples
- Open:
>>> # Forward local port 8080 to default remote port >>> space = HPSpace.get("myspace") >>> space.portforward_space("8080") >>> # Forward local port 3000 to remote port 8888 >>> space.portforward_space("3000", "8888") >>> # Access forwarded service (in another terminal) >>> # curl http://localhost:8080
HPSpaceTemplate#
- class sagemaker.hyperpod.space.hyperpod_space_template.HPSpaceTemplate[source]#
Bases:
objectHyperPod Space Template on Amazon SageMaker HyperPod clusters.
This class provides methods to create, manage, and monitor space templates on SageMaker HyperPod clusters orchestrated by Amazon EKS. Space templates define reusable configurations for creating spaces with predefined settings, resources, and constraints.
Attributes:
Attribute
Type
Description
config_data
Dict[str, Any]
Dictionary containing the complete template configuration
name
str
Name of the space template extracted from metadata
namespace
str
Kubernetes namespace of the template extracted from metadata
Usage Examples
>>> # Create template from YAML file >>> template = HPSpaceTemplate(file_path="template.yaml") >>> template.create() >>> # List all templates >>> templates = HPSpaceTemplate.list() >>> for template in templates: ... print(f"Template: {template.name}")
- __init__(*, file_path: str | None = None, config_data: Dict[str, Any] | None = None)[source]#
Initialize space template with config YAML file path or dictionary data.
Creates a new HPSpaceTemplate instance from either a YAML configuration file or a dictionary containing configuration data. Exactly one of the parameters must be provided.
Parameters:
Parameter
Type
Description
file_path
str, optional
Path to YAML configuration file (keyword-only)
config_data
Dict[str, Any], optional
Dictionary containing configuration data (keyword-only)
Raises:
ValueError: If both or neither parameters are provided, or if YAML parsing fails FileNotFoundError: If the specified file path does not exist
Usage Examples
>>> # Initialize from YAML file >>> template = HPSpaceTemplate(file_path="my-template.yaml") >>> # Initialize from dictionary (e.g., from API response) >>> config = {"metadata": {"name": "my-template"}, "spec": {...}} >>> template = HPSpaceTemplate(config_data=config)
- create() HPSpaceTemplate[source]#
Create the space template in the Kubernetes cluster.
Submits the space template configuration to the Kubernetes cluster and creates a new template resource. Updates the instance with the server response including generated metadata.
Returns:
HPSpaceTemplate: Updated HPSpaceTemplate instance with server response data
Raises:
ApiException: If the Kubernetes API call fails Exception: If template creation fails for other reasons
Usage Examples
>>> # Create template from file >>> template = HPSpaceTemplate(file_path="template.yaml") >>> created_template = template.create() >>> print(f"Created template: {created_template.name}")
- classmethod list(namespace: str | None = None) List[HPSpaceTemplate][source]#
List all space templates in the specified namespace.
Retrieves all space template resources from the Kubernetes cluster in the specified namespace. If no namespace is provided, uses the default namespace from the current Kubernetes context.
Parameters:
Parameter
Type
Description
namespace
str, optional
The Kubernetes namespace to list space templates from. If None, uses the default namespace from current context
Returns:
List[HPSpaceTemplate]: List of HPSpaceTemplate instances found in the namespace
Raises:
ApiException: If the Kubernetes API call fails Exception: If template listing fails for other reasons
Usage Examples
>>> # List templates in default namespace >>> templates = HPSpaceTemplate.list() >>> print(f"Found {len(templates)} templates") >>> # List templates in specific namespace >>> templates = HPSpaceTemplate.list(namespace="production") >>> for template in templates: ... print(f"Template: {template.name}")
- classmethod get(name: str, namespace: str | None = None) HPSpaceTemplate[source]#
Get a specific space template by name.
Retrieves a single space template resource from the Kubernetes cluster by name. Removes managedFields from the metadata for cleaner output.
Parameters:
Parameter
Type
Description
name
str
Name of the space template to retrieve
namespace
str, optional
The Kubernetes namespace. If None, uses the default namespace from current context
Returns:
HPSpaceTemplate: The space template instance with configuration data
Raises:
ApiException: If the template is not found or Kubernetes API call fails Exception: If template retrieval fails for other reasons
Usage Examples
>>> # Get template from default namespace >>> template = HPSpaceTemplate.get("my-template") >>> print(f"Template display name: {template.config_data['spec']['displayName']}") >>> # Get template from specific namespace >>> template = HPSpaceTemplate.get("my-template", namespace="production") >>> print(template.to_yaml())
- delete() None[source]#
Delete the space template from the Kubernetes cluster.
Permanently removes the space template resource from the Kubernetes cluster. This operation cannot be undone. Any spaces created from this template will continue to exist but will no longer reference the template.
Raises:
ApiException: If the deletion fails or Kubernetes API call fails Exception: If template deletion fails for other reasons
Usage Examples
>>> # Delete a template >>> template = HPSpaceTemplate.get("my-template") >>> template.delete()
- update(file_path: str) HPSpaceTemplate[source]#
Update the space template from a YAML configuration file.
Updates the existing space template with new configuration from a YAML file. Validates that the template name in the file matches the current template name and removes immutable fields before applying the update.
Parameters:
Parameter
Type
Description
file_path
str
Path to the YAML configuration file containing updated template configuration
Returns:
HPSpaceTemplate: Updated HPSpaceTemplate instance with server response data
Raises:
FileNotFoundError: If the specified file path does not exist ValueError: If YAML parsing fails or template name mismatch occurs ApiException: If the Kubernetes API call fails Exception: If template update fails for other reasons
Usage Examples
>>> # Update template from file >>> template = HPSpaceTemplate.get("my-template") >>> updated_template = template.update("updated-template.yaml") >>> print(f"Updated template: {updated_template.name}")
- to_yaml() str[source]#
Convert the space template to YAML format.
Serializes the template configuration data to a YAML string representation with readable formatting (non-flow style).
Returns:
str: YAML string representation of the template configuration
Usage Examples
>>> # Convert template to YAML >>> template = HPSpaceTemplate.get("my-template") >>> yaml_content = template.to_yaml() >>> print(yaml_content) >>> # Save template to file >>> with open("exported-template.yaml", "w") as f: ... f.write(template.to_yaml())
- to_dict() Dict[str, Any][source]#
Convert the space template to dictionary format.
Returns the template configuration data as a dictionary, which can be used for programmatic access to template properties or serialization to other formats.
Returns:
Dict[str, Any]: Dictionary representation of the template configuration
Usage Examples
>>> # Get template as dictionary >>> template = HPSpaceTemplate.get("my-template") >>> config_dict = template.to_dict() >>> print(f"Template spec: {config_dict['spec']}") >>> # Access specific configuration values >>> display_name = config_dict['spec']['displayName'] >>> default_image = config_dict['spec']['defaultImage']
Space Configs#
- class hyperpod_space_template.v1_0.model.OwnershipType[source]#
-
An enumeration.
- PUBLIC = 'Public'#
- OWNER_ONLY = 'OwnerOnly'#
- __new__(value)#
- class hyperpod_space_template.v1_0.model.DesiredStatus[source]#
-
An enumeration.
- RUNNING = 'Running'#
- STOPPED = 'Stopped'#
- __new__(value)#
- class hyperpod_space_template.v1_0.model.VolumeSpec[source]#
Bases:
BaseModelVolumeSpec defines a volume to mount from an existing PVC
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.ContainerConfig[source]#
Bases:
BaseModelContainerConfig defines container command and args configuration
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.TemplateRef[source]#
Bases:
BaseModelTemplateRef defines a reference to a WorkspaceTemplate
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.IdleDetectionSpec[source]#
Bases:
BaseModelIdleDetectionSpec defines idle detection methods
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.IdleShutdownSpec[source]#
Bases:
BaseModelIdleShutdownSpec defines idle shutdown configuration
- detection: IdleDetectionSpec#
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.StorageSpec[source]#
Bases:
BaseModelStorageSpec defines the storage configuration for Workspace
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.ResourceRequirements[source]#
Bases:
BaseModelResourceRequirements describes the compute resource requirements
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- class hyperpod_space_template.v1_0.model.SpaceConfig[source]#
Bases:
BaseModelSpaceConfig defines the desired state of a Space
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}#
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].
- desired_status: DesiredStatus | None#
- ownership_type: OwnershipType | None#
- resources: ResourceRequirements | None#
- storage: StorageSpec | None#
- volumes: List[VolumeSpec] | None#
- container_config: ContainerConfig | None#
- template_ref: TemplateRef | None#
- idle_shutdown: IdleShutdownSpec | None#