|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +from gitpod import Gitpod |
| 4 | +from gitpod.types.environments.class_list_response import ClassListResponse |
| 5 | + |
| 6 | +def find_most_used_environment_class(client: Gitpod) -> Optional[ClassListResponse]: |
| 7 | + """ |
| 8 | + Find the most used environment class. |
| 9 | + """ |
| 10 | + user = client.users.get_authenticated_user(body={}).user |
| 11 | + |
| 12 | + class_usage = {} |
| 13 | + page = client.environments.list(organization_id=user.organization_id) |
| 14 | + while page: |
| 15 | + for env in page.environments: |
| 16 | + env_class = env.spec.machine.class_ |
| 17 | + if env_class not in class_usage: |
| 18 | + class_usage[env_class] = 0 |
| 19 | + class_usage[env_class] += 1 |
| 20 | + if page.pagination and page.pagination.next_token: |
| 21 | + page = client.environments.list(token=page.pagination.next_token, organization_id=user.organization_id) |
| 22 | + else: |
| 23 | + break |
| 24 | + |
| 25 | + sorted_classes = sorted(class_usage.items(), key=lambda item: -item[1]) |
| 26 | + environment_class_id = sorted_classes[0][0] if sorted_classes else None |
| 27 | + if not environment_class_id: |
| 28 | + return None |
| 29 | + |
| 30 | + page = client.environments.classes.list(filter={"enabled": True}) |
| 31 | + while page: |
| 32 | + for cls in page.environment_classes: |
| 33 | + if cls.id == environment_class_id: |
| 34 | + return cls |
| 35 | + if page.pagination and page.pagination.next_token: |
| 36 | + page = client.environments.classes.list(token=page.pagination.next_token) |
| 37 | + else: |
| 38 | + break |
| 39 | + return None |
| 40 | + |
| 41 | + |
| 42 | +def wait_for_environment_ready(client: Gitpod, environment_id: str) -> None: |
| 43 | + def is_ready() -> bool: |
| 44 | + environment = client.environments.retrieve(environment_id=environment_id).environment |
| 45 | + if environment.status.phase in [ |
| 46 | + "ENVIRONMENT_PHASE_STOPPING", |
| 47 | + "ENVIRONMENT_PHASE_STOPPED", |
| 48 | + "ENVIRONMENT_PHASE_DELETING", |
| 49 | + "ENVIRONMENT_PHASE_DELETED", |
| 50 | + ]: |
| 51 | + raise RuntimeError(f"Environment {environment_id} is in an unexpected phase: {environment.status.phase}") |
| 52 | + elif environment.status.failure_message and len(environment.status.failure_message) > 0: |
| 53 | + raise RuntimeError(f"Environment {environment_id} failed: {'; '.join(environment.status.failure_message)}") |
| 54 | + return environment.status.phase == "ENVIRONMENT_PHASE_RUNNING" |
| 55 | + |
| 56 | + event_stream = client.events.watch(environment_id=environment_id, timeout=None) |
| 57 | + try: |
| 58 | + if is_ready(): |
| 59 | + return |
| 60 | + |
| 61 | + for event in event_stream: |
| 62 | + if event.resource_type == "RESOURCE_TYPE_ENVIRONMENT" and event.resource_id == environment_id: |
| 63 | + if is_ready(): |
| 64 | + return |
| 65 | + finally: |
| 66 | + event_stream.http_response.close() |
| 67 | + |
0 commit comments