|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import os |
| 16 | + |
| 17 | +from google.cloud.tpu_v2 import Node |
| 18 | + |
| 19 | + |
| 20 | +def start_cloud_tpu(project_id: str, zone: str, tpu_name: str = "tpu-name") -> Node: |
| 21 | + """Start a TPU node. |
| 22 | + Args: |
| 23 | + project_id (str): The ID of Google Cloud project. |
| 24 | + zone (str): The zone of the TPU node. |
| 25 | + tpu_name (str): The name of the TPU node to start. |
| 26 | + Returns: |
| 27 | + Node: The started TPU node. |
| 28 | + """ |
| 29 | + # [START tpu_vm_start] |
| 30 | + from google.cloud import tpu_v2 |
| 31 | + |
| 32 | + # TODO(developer): Update and un-comment below lines |
| 33 | + # project_id = "your-project-id" |
| 34 | + # zone = "us-central1-b" |
| 35 | + # tpu_name = "tpu-name" |
| 36 | + |
| 37 | + client = tpu_v2.TpuClient() |
| 38 | + |
| 39 | + request = tpu_v2.StartNodeRequest( |
| 40 | + name=f"projects/{project_id}/locations/{zone}/nodes/{tpu_name}", |
| 41 | + ) |
| 42 | + try: |
| 43 | + operation = client.start_node(request=request) |
| 44 | + print("Waiting for start operation to complete...") |
| 45 | + response = operation.result() |
| 46 | + print(f"TPU {tpu_name} has been started") |
| 47 | + print(response.state) |
| 48 | + # Example response: |
| 49 | + # State.READY |
| 50 | + |
| 51 | + return response |
| 52 | + except Exception as e: |
| 53 | + print(e) |
| 54 | + |
| 55 | + # [END tpu_vm_start] |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") |
| 60 | + ZONE = "us-central1-b" |
| 61 | + start_cloud_tpu(PROJECT_ID, ZONE, "tpu-name") |
0 commit comments