forked from aws/sagemaker-hyperpod-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyperpod_space.py
More file actions
975 lines (739 loc) · 32.1 KB
/
hyperpod_space.py
File metadata and controls
975 lines (739 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
import logging
import yaml
import boto3
from sagemaker.hyperpod.common.utils import create_boto3_client
from typing import List, Optional, ClassVar, Dict, Set, Any
from pydantic import BaseModel, Field, ConfigDict, model_validator
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from kr8s.objects import Pod
from sagemaker.hyperpod.common.config.metadata import Metadata
from hyperpod_space_template.v1_0.model import ResourceRequirements
from sagemaker.hyperpod.common.utils import (
handle_exception,
get_default_namespace,
setup_logging,
verify_kubernetes_version_compatibility,
)
from sagemaker.hyperpod.space.utils import (
map_kubernetes_response_to_model,
validate_space_mig_resources,
validate_mig_profile_in_cluster,
)
from sagemaker.hyperpod.common.telemetry.telemetry_logging import (
_hyperpod_telemetry_emitter,
)
from sagemaker.hyperpod.common.telemetry.constants import Feature
from sagemaker.hyperpod.cli.constants.space_constants import (
SPACE_GROUP,
SPACE_VERSION,
SPACE_PLURAL,
DEFAULT_SPACE_PORT,
)
from sagemaker.hyperpod.cli.constants.space_access_constants import (
SPACE_ACCESS_GROUP,
SPACE_ACCESS_VERSION,
SPACE_ACCESS_PLURAL,
)
from hyperpod_space_template.v1_0.model import SpaceConfig, ResourceRequirements
class HPSpace(BaseModel):
"""HyperPod 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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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}")
"""
is_kubeconfig_loaded: ClassVar[bool] = False
model_config = ConfigDict(extra="forbid")
config: SpaceConfig = Field(
description="The space configuration using the space parameter model"
)
raw_resource: Optional[Dict[str, Any]] = Field(
default=None,
description="The complete Kubernetes resource data including apiVersion, kind, metadata, and status"
)
@classmethod
def get_logger(cls):
"""Get logger for the HPSpace class.
**Returns:**
logging.Logger: Logger instance configured for the HPSpace class
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> logger = HPSpace.get_logger()
>>> logger.info("Space operation completed")
"""
return logging.getLogger(__name__)
@property
def api_version(self) -> Optional[str]:
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> space = HPSpace.get("my-space")
>>> print(f"API Version: {space.api_version}")
"""
return self.raw_resource.get("apiVersion") if self.raw_resource else None
@property
def kind(self) -> Optional[str]:
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> space = HPSpace.get("my-space")
>>> print(f"Resource Kind: {space.kind}")
"""
return self.raw_resource.get("kind") if self.raw_resource else None
@property
def metadata(self) -> Optional[Dict[str, Any]]:
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> space = HPSpace.get("my-space")
>>> print(f"Creation Time: {space.metadata['creationTimestamp']}")
"""
return self.raw_resource.get("metadata") if self.raw_resource else None
@property
def status(self) -> Optional[Dict[str, Any]]:
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> space = HPSpace.get("my-space")
>>> conditions = space.status.get('conditions', [])
>>> for condition in conditions:
... print(f"{condition['type']}: {condition['status']}")
"""
return self.raw_resource.get("status") if self.raw_resource else None
@classmethod
def verify_kube_config(cls):
"""Verify and load Kubernetes configuration.
Loads the Kubernetes configuration from the default kubeconfig location
and verifies compatibility with the cluster. This method is called
automatically by other methods that interact with the Kubernetes API.
**Raises:**
RuntimeError: If the kubeconfig cannot be loaded or is invalid
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # Verify kubeconfig before operations
>>> HPSpace.verify_kube_config()
"""
if not cls.is_kubeconfig_loaded:
try:
config.load_kube_config()
cls.is_kubeconfig_loaded = True
verify_kubernetes_version_compatibility(cls.get_logger())
except Exception as e:
raise RuntimeError(f"Failed to load kubeconfig: {e}")
@staticmethod
def _extract_mig_profiles(resources: Optional[ResourceRequirements]) -> Set[str]:
"""Extract MIG profile resource keys from resources without validation.
**Parameters:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - Parameter
- Type
- Description
* - resources
- ResourceRequirements or None
- The resource requirements to extract MIG profiles from
**Returns:**
set: Set of MIG profile resource keys found in the resources
"""
if not resources:
return set()
mig_profiles = set()
if resources.requests:
mig_profiles.update([
key for key in resources.requests.keys()
if key.startswith("nvidia.com/mig-")
])
if resources.limits:
mig_profiles.update([
key for key in resources.limits.keys()
if key.startswith("nvidia.com/mig-")
])
return mig_profiles
def _validate_and_extract_mig_profiles(self, resources: Optional[ResourceRequirements]) -> Set[str]:
"""Validate MIG resources and extract MIG profiles.
**Parameters:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - Parameter
- Type
- Description
* - resources
- ResourceRequirements or None
- The resource requirements to validate
**Returns:**
set: Set of MIG profile resource keys found in the resources
**Raises:**
RuntimeError: If MIG validation fails or profiles are invalid
"""
if not resources:
return set()
# Validate requests
if resources.requests:
valid, err = validate_space_mig_resources(resources.requests)
if not valid:
raise RuntimeError(err)
# Validate limits
if resources.limits:
valid, err = validate_space_mig_resources(resources.limits)
if not valid:
raise RuntimeError(err)
# Extract MIG profiles
mig_profiles = self._extract_mig_profiles(resources)
# Validate that requests and limits use the same MIG profile
if len(mig_profiles) > 1:
raise RuntimeError(
"MIG profile mismatch: requests and limits must use the same MIG profile. "
f"Found: {', '.join(mig_profiles)}"
)
# Validate MIG profile exists in cluster
if mig_profiles:
mig_profile = list(mig_profiles)[0]
valid, err = validate_mig_profile_in_cluster(mig_profile)
if not valid:
raise RuntimeError(err)
return mig_profiles
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "create_space")
def create(self, debug: bool = False):
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # Create a space with debug logging
>>> space = HPSpace(config=space_config)
>>> space.create(debug=True)
>>> # Create a space with default settings
>>> space.create()
"""
self.verify_kube_config()
logger = self.get_logger()
logger = setup_logging(logger, debug)
# Validate and extract MIG profiles
self._validate_and_extract_mig_profiles(self.config.resources)
# Convert config to domain model
domain_config = self.config.to_domain()
config_body = domain_config["space_spec"]
logger.debug(
"Creating HyperPod Space with config:\n%s",
yaml.dump(config_body),
)
custom_api = client.CustomObjectsApi()
try:
custom_api.create_namespaced_custom_object(
group=SPACE_GROUP,
version=SPACE_VERSION,
namespace=self.config.namespace,
plural=SPACE_PLURAL,
body=config_body,
)
logger.debug(f"Successfully created HyperPod Space '{self.config.name}'!")
except Exception as e:
logger.error(f"Failed to create HyperPod Space {self.config.name}!")
handle_exception(e, self.config.name, self.config.namespace, debug=debug)
@classmethod
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "list_spaces")
def list(cls, namespace: Optional[str] = None) -> List["HPSpace"]:
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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}")
"""
cls.verify_kube_config()
if not namespace:
namespace = get_default_namespace()
# Get caller identity
sts_client = create_boto3_client('sts')
caller_identity = sts_client.get_caller_identity()
caller_arn = caller_identity['Arn']
custom_api = client.CustomObjectsApi()
spaces = []
continue_token = None
try:
while True:
response = custom_api.list_namespaced_custom_object(
group=SPACE_GROUP,
version=SPACE_VERSION,
namespace=namespace,
plural=SPACE_PLURAL,
_continue=continue_token
)
for item in response.get("items", []):
# Check if space was created by the caller or it's set as 'Public'
created_by = item.get('metadata', {}).get('annotations', {}).get('workspace.jupyter.org/created-by')
ownership_type = item.get('spec', {}).get('ownershipType', '')
if created_by == caller_arn or ownership_type == "Public":
config_data = map_kubernetes_response_to_model(item, SpaceConfig)
space_config = SpaceConfig(**config_data)
space = cls(
config=space_config,
raw_resource=item
)
spaces.append(space)
# Check if there are more pages
continue_token = response.get('metadata', {}).get('continue')
if not continue_token:
break
return spaces
except Exception as e:
handle_exception(e, "list", namespace)
@classmethod
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "get_space")
def get(cls, name: str, namespace: str = None) -> "HPSpace":
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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}")
"""
cls.verify_kube_config()
if not namespace:
namespace = get_default_namespace()
custom_api = client.CustomObjectsApi()
try:
response = custom_api.get_namespaced_custom_object(
group=SPACE_GROUP,
version=SPACE_VERSION,
namespace=namespace,
plural=SPACE_PLURAL,
name=name
)
# Use dynamic mapping based on SpaceConfig model
config_data = map_kubernetes_response_to_model(response, SpaceConfig)
space_config = SpaceConfig(**config_data)
return cls(
config=space_config,
raw_resource=response
)
except Exception as e:
handle_exception(e, name, namespace)
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "delete_space")
def delete(self):
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # Delete a space
>>> space = HPSpace.get("my-space")
>>> space.delete()
"""
self.verify_kube_config()
logger = self.get_logger()
custom_api = client.CustomObjectsApi()
try:
custom_api.delete_namespaced_custom_object(
group=SPACE_GROUP,
version=SPACE_VERSION,
namespace=self.config.namespace,
plural=SPACE_PLURAL,
name=self.config.name
)
logger.debug(f"Successfully deleted HyperPod Space '{self.config.name}'!")
except Exception as e:
logger.error(f"Failed to delete HyperPod Space {self.config.name}!")
handle_exception(e, self.config.name, self.config.namespace)
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "update_space")
def update(self, **kwargs):
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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"}}
... )
"""
self.verify_kube_config()
logger = self.get_logger()
# Validate MIG profile configuration
if "resources" in kwargs:
resources = kwargs["resources"]
if isinstance(resources, dict):
resources = ResourceRequirements(**resources)
# Validate and extract MIG profiles
mig_profiles = self._validate_and_extract_mig_profiles(resources)
# Remove existing MIG profiles if changing to a different one
if mig_profiles:
mig_profile = list(mig_profiles)[0]
existing_config = HPSpace.get(self.config.name, self.config.namespace).config
existing_mig_profiles = self._extract_mig_profiles(existing_config.resources)
if existing_mig_profiles and mig_profile not in existing_mig_profiles:
# Remove existing MIG profiles by setting to None
for existing_profile in existing_mig_profiles:
if existing_profile != mig_profile:
kwargs["resources"].setdefault("requests", {})[existing_profile] = None
kwargs["resources"].setdefault("limits", {})[existing_profile] = None
custom_api = client.CustomObjectsApi()
# Update space config with the input config
current_config = self.config.model_dump(by_alias=True)
current_config.update(kwargs)
self.config = SpaceConfig(**current_config)
# Convert to domain model and extract spec
domain_config = self.config.to_domain()
spec_updates = domain_config["space_spec"]["spec"]
try:
custom_api.patch_namespaced_custom_object(
group=SPACE_GROUP,
version=SPACE_VERSION,
namespace=self.config.namespace,
plural=SPACE_PLURAL,
name=self.config.name,
body={"spec": spec_updates}
)
logger.debug(f"Successfully updated HyperPod Space '{self.config.name}'!")
except Exception as e:
logger.error(f"Failed to update HyperPod Space {self.config.name}!")
handle_exception(e, self.config.name, self.config.namespace)
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "start_space")
def start(self):
"""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.
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # Start a space
>>> space = HPSpace.get("my-space")
>>> space.start()
"""
self.update(desired_status="Running")
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "stop_space")
def stop(self):
"""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.
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # Stop a space
>>> space = HPSpace.get("my-space")
>>> space.stop()
"""
self.update(desired_status="Stopped")
def list_pods(self) -> List[str]:
"""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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # List pods for a space
>>> space = HPSpace.get("my-space")
>>> pods = space.list_pods()
>>> print(f"Found {len(pods)} pods: {pods}")
"""
self.verify_kube_config()
logger = self.get_logger()
v1 = client.CoreV1Api()
try:
pods = v1.list_namespaced_pod(
namespace=self.config.namespace,
label_selector=f"{SPACE_GROUP}/workspace-name={self.config.name}"
)
return [pod.metadata.name for pod in pods.items]
except Exception as e:
handle_exception(e, self.config.name, self.config.namespace)
def get_logs(self, pod_name: Optional[str] = None, container: Optional[str] = None) -> str:
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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")
"""
self.verify_kube_config()
logger = self.get_logger()
if not pod_name:
pods = self.list_pods()
if not pods:
raise RuntimeError(f"No pods found for space '{self.config.name}'")
pod_name = pods[0]
if not container:
container = "workspace"
v1 = client.CoreV1Api()
try:
return v1.read_namespaced_pod_log(
name=pod_name,
namespace=self.config.namespace,
container=container
)
except Exception as e:
handle_exception(e, pod_name, self.config.namespace)
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "create_space_access")
def create_space_access(self, connection_type: str = "vscode-remote") -> Dict[str, str]:
"""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:**
.. list-table::
:header-rows: 1
:widths: 20 20 60
* - 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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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']}")
"""
self.verify_kube_config()
logger = self.get_logger()
if connection_type not in {"vscode-remote", "web-ui"}:
raise ValueError("--connection-type must be 'vscode-remote' or 'web-ui'.")
config = {
"metadata": {
"namespace": self.config.namespace,
},
"spec": {
"workspaceName": self.config.name,
"workspaceConnectionType": connection_type,
}
}
custom_api = client.CustomObjectsApi()
try:
response = custom_api.create_namespaced_custom_object(
group=SPACE_ACCESS_GROUP,
version=SPACE_ACCESS_VERSION,
namespace=self.config.namespace,
plural=SPACE_ACCESS_PLURAL,
body=config
)
logger.debug(f"Successfully created space access for '{self.config.name}'!")
return {
"SpaceConnectionType": connection_type,
"SpaceConnectionUrl": response["status"]["workspaceConnectionUrl"]
}
except Exception as e:
logger.error(f"Failed to create space access for {self.config.name}!")
handle_exception(e, self.config.name, self.config.namespace)
@_hyperpod_telemetry_emitter(Feature.HYPERPOD, "portforward_space")
def portforward_space(self, local_port: str, remote_port: str = DEFAULT_SPACE_PORT):
"""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:**
.. list-table::
: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
.. dropdown:: Usage Examples
:open:
.. code-block:: python
>>> # 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
"""
self.verify_kube_config()
logger = self.get_logger()
# Check if space is in Available status
if self.status and self.status.get("conditions"):
is_available = False
for condition in self.status["conditions"]:
if condition.get("type") == "Available" and condition.get("status") == "True":
is_available = True
break
if not is_available:
raise RuntimeError(f"Space '{self.config.name}' is not in Available status. Port forwarding is only allowed for available spaces.")
pods = self.list_pods()
if not pods:
raise RuntimeError(f"No pods found for space '{self.config.name}'")
pod_name = pods[0]
pod = Pod.get(name=pod_name, namespace=self.config.namespace)
pf = pod.portforward(remote_port=int(remote_port), local_port=int(local_port))
logger.debug(f"Forwarding from local port {local_port} to space pod: {pod_name}.")
try:
pf.run_forever()
except KeyboardInterrupt:
logger.debug("Stopping space port forward...")
finally:
pf.stop()