From b9519973ddbe0d221fa80408f11904403bfe674f Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Tue, 15 Oct 2024 22:09:28 +0200 Subject: [PATCH 01/12] Changed package, added information to CODEOWNERS --- tpu/pom.xml | 98 ++++++++++++++ tpu/src/main/java/tpu/CreateTpuVm.java | 67 +++++++++ tpu/src/main/java/tpu/DeleteTpuVm.java | 54 ++++++++ tpu/src/main/java/tpu/GetTpuVm.java | 53 ++++++++ tpu/src/main/java/tpu/ListTpuVms.java | 51 +++++++ tpu/src/main/java/tpu/StartTpuVm.java | 55 ++++++++ tpu/src/main/java/tpu/StopTpuVm.java | 55 ++++++++ tpu/src/test/java/tpu/TpuVmIT.java | 179 +++++++++++++++++++++++++ 8 files changed, 612 insertions(+) create mode 100644 tpu/pom.xml create mode 100644 tpu/src/main/java/tpu/CreateTpuVm.java create mode 100644 tpu/src/main/java/tpu/DeleteTpuVm.java create mode 100644 tpu/src/main/java/tpu/GetTpuVm.java create mode 100644 tpu/src/main/java/tpu/ListTpuVms.java create mode 100644 tpu/src/main/java/tpu/StartTpuVm.java create mode 100644 tpu/src/main/java/tpu/StopTpuVm.java create mode 100644 tpu/src/test/java/tpu/TpuVmIT.java diff --git a/tpu/pom.xml b/tpu/pom.xml new file mode 100644 index 00000000000..a70da7fd766 --- /dev/null +++ b/tpu/pom.xml @@ -0,0 +1,98 @@ + + + + 4.0.0 + com.example.tpu + gce-diregapic-samples + 1.0-SNAPSHOT + + + + shared-configuration + com.google.cloud.samples + 1.2.0 + + + + 11 + 11 + + + + + com.google.cloud + google-cloud-tpu + 2.52.0 + + + + com.google.api + gax + + + + + google-cloud-storage + com.google.cloud + test + + + + truth + com.google.truth + test + 1.4.0 + + + junit + junit + test + 4.13.2 + + + + + org.junit.jupiter + junit-jupiter-engine + 5.10.2 + test + + + + + + + libraries-bom + com.google.cloud + import + pom + 26.40.0 + + + + + diff --git a/tpu/src/main/java/tpu/CreateTpuVm.java b/tpu/src/main/java/tpu/CreateTpuVm.java new file mode 100644 index 00000000000..178ade37e4a --- /dev/null +++ b/tpu/src/main/java/tpu/CreateTpuVm.java @@ -0,0 +1,67 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_create] + +import com.google.cloud.tpu.v2.CreateNodeRequest; +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.TpuClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class CreateTpuVm { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + String tpuVmName = "YOUR_TPU_NAME"; + String acceleratorType = "v2-8"; + String version = "tpu-vm-tf-2.14.1"; + + createTpuVm(projectId, zone, tpuVmName, acceleratorType, version); + } + + // Creates a TPU VM with the specified name, zone, accelerator type, and version. + public static void createTpuVm( + String projectId, String zone, String tpuVmName, String acceleratorType, String version) + throws IOException, ExecutionException, InterruptedException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String parent = String.format("projects/%s/locations/%s", projectId, zone); + + Node tpuVm = Node.newBuilder() + .setName(tpuVmName) + .setAcceleratorType(acceleratorType) + .setRuntimeVersion(version) + .build(); + + CreateNodeRequest request = CreateNodeRequest.newBuilder() + .setParent(parent) + .setNodeId(tpuVmName) + .setNode(tpuVm) + .build(); + + Node response = tpuClient.createNodeAsync(request).get(); + System.out.printf("TPU VM created: %s\n", response.getName()); + } + } +} +//[END tpu_vm_create] diff --git a/tpu/src/main/java/tpu/DeleteTpuVm.java b/tpu/src/main/java/tpu/DeleteTpuVm.java new file mode 100644 index 00000000000..70dda8eb0ce --- /dev/null +++ b/tpu/src/main/java/tpu/DeleteTpuVm.java @@ -0,0 +1,54 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_delete] + +import com.google.cloud.tpu.v2.DeleteNodeRequest; +import com.google.cloud.tpu.v2.NodeName; +import com.google.cloud.tpu.v2.TpuClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class DeleteTpuVm { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + String tpuVmName = "YOUR_TPU_NAME"; + + deleteTpuVm(projectId, zone, tpuVmName); + } + + // Deletes a TPU VM with the specified name in the given project and zone. + public static void deleteTpuVm(String projectId, String zone, String tpuVmName) + throws IOException, ExecutionException, InterruptedException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + + DeleteNodeRequest request = DeleteNodeRequest.newBuilder().setName(nodeName).build(); + tpuClient.deleteNodeAsync(request).get(); + + System.out.println("TPU VM deleted"); + } + } +} +//[END tpu_vm_delete] diff --git a/tpu/src/main/java/tpu/GetTpuVm.java b/tpu/src/main/java/tpu/GetTpuVm.java new file mode 100644 index 00000000000..0addfe1b323 --- /dev/null +++ b/tpu/src/main/java/tpu/GetTpuVm.java @@ -0,0 +1,53 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_get] + +import com.google.cloud.tpu.v2.GetNodeRequest; +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.NodeName; +import com.google.cloud.tpu.v2.TpuClient; +import java.io.IOException; + +public class GetTpuVm { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + String tpuVmName = "YOUR_TPU_NAME"; + + getTpuVm(projectId, zone, tpuVmName); + } + + // Describes a TPU VM with the specified name in the given project and zone. + public static Node getTpuVm(String projectId, String zone, String tpuVmName) + throws IOException { + Node node; + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + + GetNodeRequest request = GetNodeRequest.newBuilder().setName(nodeName).build(); + node = tpuClient.getNode(request); + } + return node; + } +} +//[END tpu_vm_get] diff --git a/tpu/src/main/java/tpu/ListTpuVms.java b/tpu/src/main/java/tpu/ListTpuVms.java new file mode 100644 index 00000000000..edcccd98802 --- /dev/null +++ b/tpu/src/main/java/tpu/ListTpuVms.java @@ -0,0 +1,51 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_list] + +import com.google.cloud.tpu.v2.ListNodesRequest; +import com.google.cloud.tpu.v2.TpuClient; +import com.google.cloud.tpu.v2.TpuClient.ListNodesPagedResponse; +import java.io.IOException; + +public class ListTpuVms { + + public static void main(String[] args) throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + + listTpuVms(projectId, zone); + } + + // Lists TPU VMs in the specified zone. + public static ListNodesPagedResponse listTpuVms(String projectId, String zone) + throws IOException { + ListNodesPagedResponse response; + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String parent = String.format("projects/%s/locations/%s", projectId, zone); + + ListNodesRequest request = ListNodesRequest.newBuilder().setParent(parent).build(); + response = tpuClient.listNodes(request); + } + return response; + } +} +//[END tpu_vm_list] diff --git a/tpu/src/main/java/tpu/StartTpuVm.java b/tpu/src/main/java/tpu/StartTpuVm.java new file mode 100644 index 00000000000..b8be446dde4 --- /dev/null +++ b/tpu/src/main/java/tpu/StartTpuVm.java @@ -0,0 +1,55 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_start] + +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.NodeName; +import com.google.cloud.tpu.v2.StartNodeRequest; +import com.google.cloud.tpu.v2.TpuClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class StartTpuVm { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + String tpuVmName = "YOUR_TPU_NAME"; + + startTpuVm(projectId, zone, tpuVmName); + } + + // Starts a TPU VM with the specified name in the given project and zone. + public static void startTpuVm(String projectId, String zone, String tpuVmName) + throws IOException, ExecutionException, InterruptedException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + + StartNodeRequest request = StartNodeRequest.newBuilder().setName(nodeName).build(); + Node response = tpuClient.startNodeAsync(request).get(); + + System.out.printf("TPU VM started: %s\n", response.getName()); + } + } +} +//[END tpu_vm_start] diff --git a/tpu/src/main/java/tpu/StopTpuVm.java b/tpu/src/main/java/tpu/StopTpuVm.java new file mode 100644 index 00000000000..6b7800045fc --- /dev/null +++ b/tpu/src/main/java/tpu/StopTpuVm.java @@ -0,0 +1,55 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +//[START tpu_vm_stop] + +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.NodeName; +import com.google.cloud.tpu.v2.StopNodeRequest; +import com.google.cloud.tpu.v2.TpuClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class StopTpuVm { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR_PROJECT_ID"; + String zone = "europe-west4-a"; + String tpuVmName = "YOUR_TPU_NAME"; + + stopTpuVm(projectId, zone, tpuVmName); + } + + // Stops a TPU VM with the specified name in the given project and zone. + public static void stopTpuVm(String projectId, String zone, String tpuVmName) + throws IOException, ExecutionException, InterruptedException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create()) { + String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + + StopNodeRequest request = StopNodeRequest.newBuilder().setName(nodeName).build(); + Node response = tpuClient.stopNodeAsync(request).get(); + + System.out.printf("TPU VM stopped: %s\n", response.getName()); + } + } +} +//[END tpu_vm_stop] diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java new file mode 100644 index 00000000000..a2e337b2a60 --- /dev/null +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -0,0 +1,179 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +import static com.google.cloud.tpu.v2.Node.State.READY; +import static com.google.cloud.tpu.v2.Node.State.STOPPED; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static org.junit.Assert.assertNotNull; + +import com.google.api.gax.rpc.NotFoundException; +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.TpuClient; +import com.google.protobuf.Timestamp; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import org.junit.Assert; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@Timeout(value = 25, unit = TimeUnit.MINUTES) +@TestMethodOrder(MethodOrderer. OrderAnnotation. class) +public class TpuVmIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String ZONE = "europe-west4-b"; + static String javaVersion = System.getProperty("java.version").substring(0, 2); + private static final String TPU_VM_NAME = "test-tpu-" + javaVersion + "-" + + UUID.randomUUID().toString().substring(0, 8); + private static final String ACCELERATOR_TYPE = "v5litepod-1"; + private static final String VERSION = "tpu-vm-cos-stable"; + private static final String TPU_VM_PATH_NAME = + String.format("projects/%s/locations/%s/nodes/%s", PROJECT_ID, ZONE, TPU_VM_NAME); + + public static void requireEnvVar(String envVarName) { + assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) + .that(System.getenv(envVarName)).isNotEmpty(); + } + + @BeforeAll + public static void setUp() + throws IOException, ExecutionException, InterruptedException { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + + // Cleanup existing stale resources. + cleanUpExistingTpu("test-tpu-" + javaVersion, PROJECT_ID, ZONE); + } + + @AfterAll + public static void cleanup() throws Exception { + DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + TimeUnit.MINUTES.sleep(5); + + // Test that TPUs is deleted + Assertions.assertThrows( + NotFoundException.class, + () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME)); + } + + @Test + @Order(1) + public void testCreateTpuVm() throws IOException, ExecutionException, InterruptedException { + final PrintStream out = System.out; + ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME, ACCELERATOR_TYPE, VERSION); + + assertThat(stdOut.toString()).contains("TPU VM created: " + TPU_VM_PATH_NAME); + stdOut.close(); + System.setOut(out); + } + + @Test + @Order(2) + public void testGetTpuVm() throws IOException { + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertNotNull(node); + assertThat(node.getName()).isEqualTo(TPU_VM_PATH_NAME); + } + + @Test + @Order(2) + public void testListTpuVm() throws IOException { + TpuClient.ListNodesPagedResponse nodesList = ListTpuVms.listTpuVms(PROJECT_ID, ZONE); + assertNotNull(nodesList); + for (Node node : nodesList.iterateAll()) { + Assert.assertTrue(node.getName().contains("test-tpu")); + } + } + + @Test + @Order(2) + public void testStopTpuVm() throws IOException, ExecutionException, InterruptedException { + StopTpuVm.stopTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertThat(node.getState()).isEqualTo(STOPPED); + } + + @Test + @Order(3) + public void testStartTpuVm() throws IOException, ExecutionException, InterruptedException { + StartTpuVm.startTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertThat(node.getState()).isEqualTo(READY); + } + + public static void cleanUpExistingTpu(String prefixToDelete, String projectId, String zone) + throws IOException, ExecutionException, InterruptedException { + try (TpuClient tpuClient = TpuClient.create()) { + String parent = String.format("projects/%s/locations/%s", projectId, zone); + for (Node node : tpuClient.listNodes(parent).iterateAll()) { + String creationTime = formatTimestamp(node.getCreateTime()); + String name = node.getName().substring(node.getName().lastIndexOf("/") + 1); + if (containPrefixToDeleteAndZone(node, prefixToDelete, zone) + && isCreatedBeforeThresholdTime(creationTime)) { + DeleteTpuVm.deleteTpuVm(projectId, zone, name); + } + } + } + } + + public static boolean containPrefixToDeleteAndZone( + Node node, String prefixToDelete, String zone) { + boolean containPrefixAndZone = false; + try { + containPrefixAndZone = node.getName().contains(prefixToDelete) + && node.getName().split("/")[3].contains(zone); + + } catch (NullPointerException e) { + System.out.println("Resource not found, skipping deletion:"); + } + return containPrefixAndZone; + } + + public static boolean isCreatedBeforeThresholdTime(String timestamp) { + return OffsetDateTime.parse(timestamp).toInstant() + .isBefore(Instant.now().minus(5, ChronoUnit.MINUTES)); + } + + private static String formatTimestamp(Timestamp timestamp) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant( + Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), + ZoneOffset.UTC); + return formatter.format(offsetDateTime); + } +} \ No newline at end of file From 9ee20d7f1aed6ff67d34728aa8f72a3c67210d22 Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Tue, 15 Oct 2024 22:13:04 +0200 Subject: [PATCH 02/12] Added information to CODEOWNERS --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ca79aba529f..f21afe0f659 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -44,6 +44,7 @@ /security-command-center @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/dee-infra @GoogleCloudPlatform/gcp-security-command-center /servicedirectory @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/dee-infra /webrisk @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/dee-infra +/tpu @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/dee-infra # DEE Platform Ops (DEEPO) /errorreporting @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers From f0b8314afe22f38cb35860e172a4cccc79cff362 Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Wed, 16 Oct 2024 14:51:39 +0200 Subject: [PATCH 03/12] Added timeout --- tpu/src/test/java/tpu/TpuVmIT.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index a2e337b2a60..0c2014feacd 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -96,6 +96,7 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME, ACCELERATOR_TYPE, VERSION); + TimeUnit.MINUTES.sleep(3); assertThat(stdOut.toString()).contains("TPU VM created: " + TPU_VM_PATH_NAME); stdOut.close(); @@ -106,6 +107,7 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte @Order(2) public void testGetTpuVm() throws IOException { Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertNotNull(node); assertThat(node.getName()).isEqualTo(TPU_VM_PATH_NAME); } @@ -114,6 +116,7 @@ public void testGetTpuVm() throws IOException { @Order(2) public void testListTpuVm() throws IOException { TpuClient.ListNodesPagedResponse nodesList = ListTpuVms.listTpuVms(PROJECT_ID, ZONE); + assertNotNull(nodesList); for (Node node : nodesList.iterateAll()) { Assert.assertTrue(node.getName().contains("test-tpu")); @@ -125,6 +128,7 @@ public void testListTpuVm() throws IOException { public void testStopTpuVm() throws IOException, ExecutionException, InterruptedException { StopTpuVm.stopTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertThat(node.getState()).isEqualTo(STOPPED); } @@ -133,6 +137,7 @@ public void testStopTpuVm() throws IOException, ExecutionException, InterruptedE public void testStartTpuVm() throws IOException, ExecutionException, InterruptedException { StartTpuVm.startTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + assertThat(node.getState()).isEqualTo(READY); } From d3e1dee1513658b0e44108697b4bb65fec8aacfb Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Wed, 16 Oct 2024 17:15:08 +0200 Subject: [PATCH 04/12] Fixed parameters for test --- tpu/src/test/java/tpu/TpuVmIT.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index 0c2014feacd..0798d8dd56e 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -54,12 +54,12 @@ @TestMethodOrder(MethodOrderer. OrderAnnotation. class) public class TpuVmIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String ZONE = "europe-west4-b"; + private static final String ZONE = "europe-west4-a"; static String javaVersion = System.getProperty("java.version").substring(0, 2); private static final String TPU_VM_NAME = "test-tpu-" + javaVersion + "-" + UUID.randomUUID().toString().substring(0, 8); - private static final String ACCELERATOR_TYPE = "v5litepod-1"; - private static final String VERSION = "tpu-vm-cos-stable"; + private static final String ACCELERATOR_TYPE = "v2-8"; + private static final String VERSION = "tpu-vm-tf-2.14.1"; private static final String TPU_VM_PATH_NAME = String.format("projects/%s/locations/%s/nodes/%s", PROJECT_ID, ZONE, TPU_VM_NAME); @@ -171,7 +171,7 @@ public static boolean containPrefixToDeleteAndZone( public static boolean isCreatedBeforeThresholdTime(String timestamp) { return OffsetDateTime.parse(timestamp).toInstant() - .isBefore(Instant.now().minus(5, ChronoUnit.MINUTES)); + .isBefore(Instant.now().minus(30, ChronoUnit.MINUTES)); } private static String formatTimestamp(Timestamp timestamp) { From 2253b54da9fa17159c82f947f6c6e2a0419471d9 Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Thu, 17 Oct 2024 20:50:06 +0200 Subject: [PATCH 05/12] Fixed DeleteTpuVm and naming --- tpu/src/main/java/tpu/CreateTpuVm.java | 28 ++++++++++++------ tpu/src/main/java/tpu/DeleteTpuVm.java | 41 +++++++++++++++++++++----- tpu/src/main/java/tpu/GetTpuVm.java | 15 ++++++---- tpu/src/main/java/tpu/ListTpuVms.java | 4 +++ tpu/src/main/java/tpu/StartTpuVm.java | 15 ++++++---- tpu/src/main/java/tpu/StopTpuVm.java | 15 ++++++---- 6 files changed, 86 insertions(+), 32 deletions(-) diff --git a/tpu/src/main/java/tpu/CreateTpuVm.java b/tpu/src/main/java/tpu/CreateTpuVm.java index 178ade37e4a..8ce44fa4dc5 100644 --- a/tpu/src/main/java/tpu/CreateTpuVm.java +++ b/tpu/src/main/java/tpu/CreateTpuVm.java @@ -29,18 +29,28 @@ public class CreateTpuVm { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; - String tpuVmName = "YOUR_TPU_NAME"; - String acceleratorType = "v2-8"; - String version = "tpu-vm-tf-2.14.1"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; + // The accelerator type that specifies the version and size of the Cloud TPU you want to create. + // For more information about supported accelerator types for each TPU version, + // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions. + String tpuType = "v2-8"; + // Software version that specifies the version of the TPU runtime to install. + // For more information see https://cloud.google.com/tpu/docs/runtimes + String tpuSoftwareVersion = "tpu-vm-tf-2.14.1"; - createTpuVm(projectId, zone, tpuVmName, acceleratorType, version); + createTpuVm(projectId, zone, nodeName, tpuType, tpuSoftwareVersion); } // Creates a TPU VM with the specified name, zone, accelerator type, and version. public static void createTpuVm( - String projectId, String zone, String tpuVmName, String acceleratorType, String version) + String projectId, String zone, String nodeName, String tpuType, String tpuSoftwareVersion) throws IOException, ExecutionException, InterruptedException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. @@ -48,14 +58,14 @@ public static void createTpuVm( String parent = String.format("projects/%s/locations/%s", projectId, zone); Node tpuVm = Node.newBuilder() - .setName(tpuVmName) - .setAcceleratorType(acceleratorType) - .setRuntimeVersion(version) + .setName(nodeName) + .setAcceleratorType(tpuType) + .setRuntimeVersion(tpuSoftwareVersion) .build(); CreateNodeRequest request = CreateNodeRequest.newBuilder() .setParent(parent) - .setNodeId(tpuVmName) + .setNodeId(nodeName) .setNode(tpuVm) .build(); diff --git a/tpu/src/main/java/tpu/DeleteTpuVm.java b/tpu/src/main/java/tpu/DeleteTpuVm.java index 70dda8eb0ce..3c5200e8e77 100644 --- a/tpu/src/main/java/tpu/DeleteTpuVm.java +++ b/tpu/src/main/java/tpu/DeleteTpuVm.java @@ -18,37 +18,62 @@ //[START tpu_vm_delete] +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; import com.google.cloud.tpu.v2.DeleteNodeRequest; import com.google.cloud.tpu.v2.NodeName; import com.google.cloud.tpu.v2.TpuClient; +import com.google.cloud.tpu.v2.TpuSettings; import java.io.IOException; import java.util.concurrent.ExecutionException; +import org.threeten.bp.Duration; public class DeleteTpuVm { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; - String tpuVmName = "YOUR_TPU_NAME"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; - deleteTpuVm(projectId, zone, tpuVmName); + deleteTpuVm(projectId, zone, nodeName); } // Deletes a TPU VM with the specified name in the given project and zone. - public static void deleteTpuVm(String projectId, String zone, String tpuVmName) + public static void deleteTpuVm(String projectId, String zone, String nodeName) throws IOException, ExecutionException, InterruptedException { + TpuSettings.Builder clientSettings = + TpuSettings.newBuilder(); + clientSettings + .deleteNodeOperationSettings() + .setPollingAlgorithm( + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(5000L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(45000L)) + .setInitialRpcTimeout(Duration.ZERO) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ZERO) + .setTotalTimeout(Duration.ofHours(24L)) + .build())); + // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. - try (TpuClient tpuClient = TpuClient.create()) { - String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + try (TpuClient tpuClient = TpuClient.create(clientSettings.build())) { + String name = NodeName.of(projectId, zone, nodeName).toString(); - DeleteNodeRequest request = DeleteNodeRequest.newBuilder().setName(nodeName).build(); - tpuClient.deleteNodeAsync(request).get(); + DeleteNodeRequest request = DeleteNodeRequest.newBuilder().setName(name).build(); + tpuClient.deleteNodeAsync(request).get(); System.out.println("TPU VM deleted"); } } } -//[END tpu_vm_delete] +//[END tpu_vm_delete] \ No newline at end of file diff --git a/tpu/src/main/java/tpu/GetTpuVm.java b/tpu/src/main/java/tpu/GetTpuVm.java index 0addfe1b323..22f2b6d2c0f 100644 --- a/tpu/src/main/java/tpu/GetTpuVm.java +++ b/tpu/src/main/java/tpu/GetTpuVm.java @@ -28,23 +28,28 @@ public class GetTpuVm { public static void main(String[] args) throws IOException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; - String tpuVmName = "YOUR_TPU_NAME"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; - getTpuVm(projectId, zone, tpuVmName); + getTpuVm(projectId, zone, nodeName); } // Describes a TPU VM with the specified name in the given project and zone. - public static Node getTpuVm(String projectId, String zone, String tpuVmName) + public static Node getTpuVm(String projectId, String zone, String nodeName) throws IOException { Node node; // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (TpuClient tpuClient = TpuClient.create()) { - String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + String name = NodeName.of(projectId, zone, nodeName).toString(); - GetNodeRequest request = GetNodeRequest.newBuilder().setName(nodeName).build(); + GetNodeRequest request = GetNodeRequest.newBuilder().setName(name).build(); node = tpuClient.getNode(request); } return node; diff --git a/tpu/src/main/java/tpu/ListTpuVms.java b/tpu/src/main/java/tpu/ListTpuVms.java index edcccd98802..7f2124d4a03 100644 --- a/tpu/src/main/java/tpu/ListTpuVms.java +++ b/tpu/src/main/java/tpu/ListTpuVms.java @@ -27,7 +27,11 @@ public class ListTpuVms { public static void main(String[] args) throws IOException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; listTpuVms(projectId, zone); diff --git a/tpu/src/main/java/tpu/StartTpuVm.java b/tpu/src/main/java/tpu/StartTpuVm.java index b8be446dde4..d3421a8cc31 100644 --- a/tpu/src/main/java/tpu/StartTpuVm.java +++ b/tpu/src/main/java/tpu/StartTpuVm.java @@ -30,22 +30,27 @@ public class StartTpuVm { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; - String tpuVmName = "YOUR_TPU_NAME"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; - startTpuVm(projectId, zone, tpuVmName); + startTpuVm(projectId, zone, nodeName); } // Starts a TPU VM with the specified name in the given project and zone. - public static void startTpuVm(String projectId, String zone, String tpuVmName) + public static void startTpuVm(String projectId, String zone, String nodeName) throws IOException, ExecutionException, InterruptedException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (TpuClient tpuClient = TpuClient.create()) { - String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + String name = NodeName.of(projectId, zone, nodeName).toString(); - StartNodeRequest request = StartNodeRequest.newBuilder().setName(nodeName).build(); + StartNodeRequest request = StartNodeRequest.newBuilder().setName(name).build(); Node response = tpuClient.startNodeAsync(request).get(); System.out.printf("TPU VM started: %s\n", response.getName()); diff --git a/tpu/src/main/java/tpu/StopTpuVm.java b/tpu/src/main/java/tpu/StopTpuVm.java index 6b7800045fc..6e3e5bfb646 100644 --- a/tpu/src/main/java/tpu/StopTpuVm.java +++ b/tpu/src/main/java/tpu/StopTpuVm.java @@ -30,22 +30,27 @@ public class StopTpuVm { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; - String tpuVmName = "YOUR_TPU_NAME"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; - stopTpuVm(projectId, zone, tpuVmName); + stopTpuVm(projectId, zone, nodeName); } // Stops a TPU VM with the specified name in the given project and zone. - public static void stopTpuVm(String projectId, String zone, String tpuVmName) + public static void stopTpuVm(String projectId, String zone, String nodeName) throws IOException, ExecutionException, InterruptedException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (TpuClient tpuClient = TpuClient.create()) { - String nodeName = NodeName.of(projectId, zone, tpuVmName).toString(); + String name = NodeName.of(projectId, zone, nodeName).toString(); - StopNodeRequest request = StopNodeRequest.newBuilder().setName(nodeName).build(); + StopNodeRequest request = StopNodeRequest.newBuilder().setName(name).build(); Node response = tpuClient.stopNodeAsync(request).get(); System.out.printf("TPU VM stopped: %s\n", response.getName()); From d29a6b5d85bd42531a3b8a28fd17fe99fc8f12bf Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Fri, 18 Oct 2024 13:16:26 +0200 Subject: [PATCH 06/12] Added comment, created Util class --- tpu/src/main/java/tpu/DeleteTpuVm.java | 2 + tpu/src/test/java/tpu/TpuVmIT.java | 51 +----------------- tpu/src/test/java/tpu/Util.java | 75 ++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 50 deletions(-) create mode 100644 tpu/src/test/java/tpu/Util.java diff --git a/tpu/src/main/java/tpu/DeleteTpuVm.java b/tpu/src/main/java/tpu/DeleteTpuVm.java index 3c5200e8e77..bd77ced58cd 100644 --- a/tpu/src/main/java/tpu/DeleteTpuVm.java +++ b/tpu/src/main/java/tpu/DeleteTpuVm.java @@ -48,6 +48,8 @@ public static void main(String[] args) // Deletes a TPU VM with the specified name in the given project and zone. public static void deleteTpuVm(String projectId, String zone, String nodeName) throws IOException, ExecutionException, InterruptedException { + // With these settings the client library handles the Operation's polling mechanism + // and prevent CancellationException error TpuSettings.Builder clientSettings = TpuSettings.newBuilder(); clientSettings diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index 0798d8dd56e..8ecbbb8acba 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -25,15 +25,9 @@ import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.tpu.v2.Node; import com.google.cloud.tpu.v2.TpuClient; -import com.google.protobuf.Timestamp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -75,13 +69,12 @@ public static void setUp() requireEnvVar("GOOGLE_CLOUD_PROJECT"); // Cleanup existing stale resources. - cleanUpExistingTpu("test-tpu-" + javaVersion, PROJECT_ID, ZONE); + Util.cleanUpExistingTpu("test-tpu-" + javaVersion, PROJECT_ID, ZONE); } @AfterAll public static void cleanup() throws Exception { DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); - TimeUnit.MINUTES.sleep(5); // Test that TPUs is deleted Assertions.assertThrows( @@ -96,7 +89,6 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME, ACCELERATOR_TYPE, VERSION); - TimeUnit.MINUTES.sleep(3); assertThat(stdOut.toString()).contains("TPU VM created: " + TPU_VM_PATH_NAME); stdOut.close(); @@ -140,45 +132,4 @@ public void testStartTpuVm() throws IOException, ExecutionException, Interrupted assertThat(node.getState()).isEqualTo(READY); } - - public static void cleanUpExistingTpu(String prefixToDelete, String projectId, String zone) - throws IOException, ExecutionException, InterruptedException { - try (TpuClient tpuClient = TpuClient.create()) { - String parent = String.format("projects/%s/locations/%s", projectId, zone); - for (Node node : tpuClient.listNodes(parent).iterateAll()) { - String creationTime = formatTimestamp(node.getCreateTime()); - String name = node.getName().substring(node.getName().lastIndexOf("/") + 1); - if (containPrefixToDeleteAndZone(node, prefixToDelete, zone) - && isCreatedBeforeThresholdTime(creationTime)) { - DeleteTpuVm.deleteTpuVm(projectId, zone, name); - } - } - } - } - - public static boolean containPrefixToDeleteAndZone( - Node node, String prefixToDelete, String zone) { - boolean containPrefixAndZone = false; - try { - containPrefixAndZone = node.getName().contains(prefixToDelete) - && node.getName().split("/")[3].contains(zone); - - } catch (NullPointerException e) { - System.out.println("Resource not found, skipping deletion:"); - } - return containPrefixAndZone; - } - - public static boolean isCreatedBeforeThresholdTime(String timestamp) { - return OffsetDateTime.parse(timestamp).toInstant() - .isBefore(Instant.now().minus(30, ChronoUnit.MINUTES)); - } - - private static String formatTimestamp(Timestamp timestamp) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant( - Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), - ZoneOffset.UTC); - return formatter.format(offsetDateTime); - } } \ No newline at end of file diff --git a/tpu/src/test/java/tpu/Util.java b/tpu/src/test/java/tpu/Util.java new file mode 100644 index 00000000000..178d7783a81 --- /dev/null +++ b/tpu/src/test/java/tpu/Util.java @@ -0,0 +1,75 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.TpuClient; +import com.google.protobuf.Timestamp; +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.concurrent.ExecutionException; + +public class Util { + private static final int DELETION_THRESHOLD_TIME_MINUTES = 30; + + // Delete TPU VMs which starts with the given prefixToDelete and + // has creation timestamp >30 minutes. + public static void cleanUpExistingTpu(String prefixToDelete, String projectId, String zone) + throws IOException, ExecutionException, InterruptedException { + try (TpuClient tpuClient = TpuClient.create()) { + String parent = String.format("projects/%s/locations/%s", projectId, zone); + for (Node node : tpuClient.listNodes(parent).iterateAll()) { + String creationTime = formatTimestamp(node.getCreateTime()); + String name = node.getName().substring(node.getName().lastIndexOf("/") + 1); + if (containPrefixToDeleteAndZone(node, prefixToDelete, zone) + && isCreatedBeforeThresholdTime(creationTime)) { + DeleteTpuVm.deleteTpuVm(projectId, zone, name); + } + } + } + } + + public static boolean containPrefixToDeleteAndZone( + Node node, String prefixToDelete, String zone) { + boolean containPrefixAndZone = false; + try { + containPrefixAndZone = node.getName().contains(prefixToDelete) + && node.getName().split("/")[3].contains(zone); + + } catch (NullPointerException e) { + System.out.println("Resource not found, skipping deletion:"); + } + return containPrefixAndZone; + } + + public static boolean isCreatedBeforeThresholdTime(String timestamp) { + return OffsetDateTime.parse(timestamp).toInstant() + .isBefore(Instant.now().minus(DELETION_THRESHOLD_TIME_MINUTES, ChronoUnit.MINUTES)); + } + + private static String formatTimestamp(Timestamp timestamp) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant( + Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), + ZoneOffset.UTC); + return formatter.format(offsetDateTime); + } +} From 69568520ec2d40a6c70bf34a0c5d3aabe586369b Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Wed, 23 Oct 2024 10:30:28 +0200 Subject: [PATCH 07/12] Fixed naming --- tpu/src/main/java/tpu/GetTpuVm.java | 5 ++--- tpu/src/main/java/tpu/ListTpuVms.java | 4 +--- tpu/src/test/java/tpu/TpuVmIT.java | 30 +++++++++++++-------------- 3 files changed, 18 insertions(+), 21 deletions(-) diff --git a/tpu/src/main/java/tpu/GetTpuVm.java b/tpu/src/main/java/tpu/GetTpuVm.java index 22f2b6d2c0f..cb1e335bf4a 100644 --- a/tpu/src/main/java/tpu/GetTpuVm.java +++ b/tpu/src/main/java/tpu/GetTpuVm.java @@ -43,16 +43,15 @@ public static void main(String[] args) throws IOException { // Describes a TPU VM with the specified name in the given project and zone. public static Node getTpuVm(String projectId, String zone, String nodeName) throws IOException { - Node node; // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (TpuClient tpuClient = TpuClient.create()) { String name = NodeName.of(projectId, zone, nodeName).toString(); GetNodeRequest request = GetNodeRequest.newBuilder().setName(name).build(); - node = tpuClient.getNode(request); + + return tpuClient.getNode(request); } - return node; } } //[END tpu_vm_get] diff --git a/tpu/src/main/java/tpu/ListTpuVms.java b/tpu/src/main/java/tpu/ListTpuVms.java index 7f2124d4a03..a0f5ad33b7e 100644 --- a/tpu/src/main/java/tpu/ListTpuVms.java +++ b/tpu/src/main/java/tpu/ListTpuVms.java @@ -40,16 +40,14 @@ public static void main(String[] args) throws IOException { // Lists TPU VMs in the specified zone. public static ListNodesPagedResponse listTpuVms(String projectId, String zone) throws IOException { - ListNodesPagedResponse response; // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (TpuClient tpuClient = TpuClient.create()) { String parent = String.format("projects/%s/locations/%s", projectId, zone); ListNodesRequest request = ListNodesRequest.newBuilder().setParent(parent).build(); - response = tpuClient.listNodes(request); + return tpuClient.listNodes(request); } - return response; } } //[END tpu_vm_list] diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index 8ecbbb8acba..b5767e8495c 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -50,12 +50,12 @@ public class TpuVmIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String ZONE = "europe-west4-a"; static String javaVersion = System.getProperty("java.version").substring(0, 2); - private static final String TPU_VM_NAME = "test-tpu-" + javaVersion + "-" + private static final String NODE_NAME = "test-tpu-" + javaVersion + "-" + UUID.randomUUID().toString().substring(0, 8); - private static final String ACCELERATOR_TYPE = "v2-8"; - private static final String VERSION = "tpu-vm-tf-2.14.1"; - private static final String TPU_VM_PATH_NAME = - String.format("projects/%s/locations/%s/nodes/%s", PROJECT_ID, ZONE, TPU_VM_NAME); + private static final String TPU_TYPE = "v2-8"; + private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; + private static final String NODE_PATH_NAME = + String.format("projects/%s/locations/%s/nodes/%s", PROJECT_ID, ZONE, NODE_NAME); public static void requireEnvVar(String envVarName) { assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) @@ -74,12 +74,12 @@ public static void setUp() @AfterAll public static void cleanup() throws Exception { - DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, NODE_NAME); // Test that TPUs is deleted Assertions.assertThrows( NotFoundException.class, - () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME)); + () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME)); } @Test @@ -88,9 +88,9 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte final PrintStream out = System.out; ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); - CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME, ACCELERATOR_TYPE, VERSION); + CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE , TPU_SOFTWARE_VERSION); - assertThat(stdOut.toString()).contains("TPU VM created: " + TPU_VM_PATH_NAME); + assertThat(stdOut.toString()).contains("TPU VM created: " + NODE_PATH_NAME); stdOut.close(); System.setOut(out); } @@ -98,10 +98,10 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte @Test @Order(2) public void testGetTpuVm() throws IOException { - Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME); assertNotNull(node); - assertThat(node.getName()).isEqualTo(TPU_VM_PATH_NAME); + assertThat(node.getName()).isEqualTo(NODE_PATH_NAME); } @Test @@ -118,8 +118,8 @@ public void testListTpuVm() throws IOException { @Test @Order(2) public void testStopTpuVm() throws IOException, ExecutionException, InterruptedException { - StopTpuVm.stopTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); - Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + StopTpuVm.stopTpuVm(PROJECT_ID, ZONE, NODE_NAME); + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME); assertThat(node.getState()).isEqualTo(STOPPED); } @@ -127,8 +127,8 @@ public void testStopTpuVm() throws IOException, ExecutionException, InterruptedE @Test @Order(3) public void testStartTpuVm() throws IOException, ExecutionException, InterruptedException { - StartTpuVm.startTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); - Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, TPU_VM_NAME); + StartTpuVm.startTpuVm(PROJECT_ID, ZONE, NODE_NAME); + Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME); assertThat(node.getState()).isEqualTo(READY); } From 478beaa3fb09a4fb8ee6ffe94bbf298c728d0a5f Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Wed, 23 Oct 2024 11:05:56 +0200 Subject: [PATCH 08/12] Fixed whitespace --- tpu/src/test/java/tpu/TpuVmIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index b5767e8495c..d0a5aeece9b 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -88,7 +88,7 @@ public void testCreateTpuVm() throws IOException, ExecutionException, Interrupte final PrintStream out = System.out; ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); - CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE , TPU_SOFTWARE_VERSION); + CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION); assertThat(stdOut.toString()).contains("TPU VM created: " + NODE_PATH_NAME); stdOut.close(); From ec13f4d34f3855f46c17090e5edb0879a5ee3e70 Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Tue, 29 Oct 2024 11:13:49 +0100 Subject: [PATCH 09/12] Split PR into smaller, deleted redundant code --- tpu/src/main/java/tpu/CreateTpuVm.java | 28 ++++++++++-- tpu/src/main/java/tpu/DeleteTpuVm.java | 1 - tpu/src/main/java/tpu/GetTpuVm.java | 1 - tpu/src/main/java/tpu/ListTpuVms.java | 53 ----------------------- tpu/src/main/java/tpu/StartTpuVm.java | 60 -------------------------- tpu/src/main/java/tpu/StopTpuVm.java | 60 -------------------------- tpu/src/test/java/tpu/TpuVmIT.java | 54 ++++------------------- 7 files changed, 34 insertions(+), 223 deletions(-) delete mode 100644 tpu/src/main/java/tpu/ListTpuVms.java delete mode 100644 tpu/src/main/java/tpu/StartTpuVm.java delete mode 100644 tpu/src/main/java/tpu/StopTpuVm.java diff --git a/tpu/src/main/java/tpu/CreateTpuVm.java b/tpu/src/main/java/tpu/CreateTpuVm.java index 8ce44fa4dc5..5daefabb6d2 100644 --- a/tpu/src/main/java/tpu/CreateTpuVm.java +++ b/tpu/src/main/java/tpu/CreateTpuVm.java @@ -17,12 +17,15 @@ package tpu; //[START tpu_vm_create] - +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; import com.google.cloud.tpu.v2.CreateNodeRequest; import com.google.cloud.tpu.v2.Node; import com.google.cloud.tpu.v2.TpuClient; +import com.google.cloud.tpu.v2.TpuSettings; import java.io.IOException; import java.util.concurrent.ExecutionException; +import org.threeten.bp.Duration; public class CreateTpuVm { @@ -49,12 +52,30 @@ public static void main(String[] args) } // Creates a TPU VM with the specified name, zone, accelerator type, and version. - public static void createTpuVm( + public static Node createTpuVm( String projectId, String zone, String nodeName, String tpuType, String tpuSoftwareVersion) throws IOException, ExecutionException, InterruptedException { + // With these settings the client library handles the Operation's polling mechanism + // and prevent CancellationException error + TpuSettings.Builder clientSettings = + TpuSettings.newBuilder(); + clientSettings + .createNodeOperationSettings() + .setPollingAlgorithm( + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(5000L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(45000L)) + .setInitialRpcTimeout(Duration.ZERO) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ZERO) + .setTotalTimeout(Duration.ofHours(24L)) + .build())); + // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. - try (TpuClient tpuClient = TpuClient.create()) { + try (TpuClient tpuClient = TpuClient.create(clientSettings.build())) { String parent = String.format("projects/%s/locations/%s", projectId, zone); Node tpuVm = Node.newBuilder() @@ -71,6 +92,7 @@ public static void createTpuVm( Node response = tpuClient.createNodeAsync(request).get(); System.out.printf("TPU VM created: %s\n", response.getName()); + return response; } } } diff --git a/tpu/src/main/java/tpu/DeleteTpuVm.java b/tpu/src/main/java/tpu/DeleteTpuVm.java index bd77ced58cd..a63af99bf23 100644 --- a/tpu/src/main/java/tpu/DeleteTpuVm.java +++ b/tpu/src/main/java/tpu/DeleteTpuVm.java @@ -17,7 +17,6 @@ package tpu; //[START tpu_vm_delete] - import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.cloud.tpu.v2.DeleteNodeRequest; diff --git a/tpu/src/main/java/tpu/GetTpuVm.java b/tpu/src/main/java/tpu/GetTpuVm.java index cb1e335bf4a..4a4ec43db2c 100644 --- a/tpu/src/main/java/tpu/GetTpuVm.java +++ b/tpu/src/main/java/tpu/GetTpuVm.java @@ -17,7 +17,6 @@ package tpu; //[START tpu_vm_get] - import com.google.cloud.tpu.v2.GetNodeRequest; import com.google.cloud.tpu.v2.Node; import com.google.cloud.tpu.v2.NodeName; diff --git a/tpu/src/main/java/tpu/ListTpuVms.java b/tpu/src/main/java/tpu/ListTpuVms.java deleted file mode 100644 index a0f5ad33b7e..00000000000 --- a/tpu/src/main/java/tpu/ListTpuVms.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package tpu; - -//[START tpu_vm_list] - -import com.google.cloud.tpu.v2.ListNodesRequest; -import com.google.cloud.tpu.v2.TpuClient; -import com.google.cloud.tpu.v2.TpuClient.ListNodesPagedResponse; -import java.io.IOException; - -public class ListTpuVms { - - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - // Project ID or project number of the Google Cloud project you want to create a node. - String projectId = "YOUR_PROJECT_ID"; - // The zone in which to create the TPU. - // For more information about supported TPU types for specific zones, - // see https://cloud.google.com/tpu/docs/regions-zones - String zone = "europe-west4-a"; - - listTpuVms(projectId, zone); - } - - // Lists TPU VMs in the specified zone. - public static ListNodesPagedResponse listTpuVms(String projectId, String zone) - throws IOException { - // Initialize client that will be used to send requests. This client only needs to be created - // once, and can be reused for multiple requests. - try (TpuClient tpuClient = TpuClient.create()) { - String parent = String.format("projects/%s/locations/%s", projectId, zone); - - ListNodesRequest request = ListNodesRequest.newBuilder().setParent(parent).build(); - return tpuClient.listNodes(request); - } - } -} -//[END tpu_vm_list] diff --git a/tpu/src/main/java/tpu/StartTpuVm.java b/tpu/src/main/java/tpu/StartTpuVm.java deleted file mode 100644 index d3421a8cc31..00000000000 --- a/tpu/src/main/java/tpu/StartTpuVm.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package tpu; - -//[START tpu_vm_start] - -import com.google.cloud.tpu.v2.Node; -import com.google.cloud.tpu.v2.NodeName; -import com.google.cloud.tpu.v2.StartNodeRequest; -import com.google.cloud.tpu.v2.TpuClient; -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -public class StartTpuVm { - - public static void main(String[] args) - throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. - // Project ID or project number of the Google Cloud project you want to create a node. - String projectId = "YOUR_PROJECT_ID"; - // The zone in which to create the TPU. - // For more information about supported TPU types for specific zones, - // see https://cloud.google.com/tpu/docs/regions-zones - String zone = "europe-west4-a"; - // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; - - startTpuVm(projectId, zone, nodeName); - } - - // Starts a TPU VM with the specified name in the given project and zone. - public static void startTpuVm(String projectId, String zone, String nodeName) - throws IOException, ExecutionException, InterruptedException { - // Initialize client that will be used to send requests. This client only needs to be created - // once, and can be reused for multiple requests. - try (TpuClient tpuClient = TpuClient.create()) { - String name = NodeName.of(projectId, zone, nodeName).toString(); - - StartNodeRequest request = StartNodeRequest.newBuilder().setName(name).build(); - Node response = tpuClient.startNodeAsync(request).get(); - - System.out.printf("TPU VM started: %s\n", response.getName()); - } - } -} -//[END tpu_vm_start] diff --git a/tpu/src/main/java/tpu/StopTpuVm.java b/tpu/src/main/java/tpu/StopTpuVm.java deleted file mode 100644 index 6e3e5bfb646..00000000000 --- a/tpu/src/main/java/tpu/StopTpuVm.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package tpu; - -//[START tpu_vm_stop] - -import com.google.cloud.tpu.v2.Node; -import com.google.cloud.tpu.v2.NodeName; -import com.google.cloud.tpu.v2.StopNodeRequest; -import com.google.cloud.tpu.v2.TpuClient; -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -public class StopTpuVm { - - public static void main(String[] args) - throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. - // Project ID or project number of the Google Cloud project you want to create a node. - String projectId = "YOUR_PROJECT_ID"; - // The zone in which to create the TPU. - // For more information about supported TPU types for specific zones, - // see https://cloud.google.com/tpu/docs/regions-zones - String zone = "europe-west4-a"; - // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; - - stopTpuVm(projectId, zone, nodeName); - } - - // Stops a TPU VM with the specified name in the given project and zone. - public static void stopTpuVm(String projectId, String zone, String nodeName) - throws IOException, ExecutionException, InterruptedException { - // Initialize client that will be used to send requests. This client only needs to be created - // once, and can be reused for multiple requests. - try (TpuClient tpuClient = TpuClient.create()) { - String name = NodeName.of(projectId, zone, nodeName).toString(); - - StopNodeRequest request = StopNodeRequest.newBuilder().setName(name).build(); - Node response = tpuClient.stopNodeAsync(request).get(); - - System.out.printf("TPU VM stopped: %s\n", response.getName()); - } - } -} -//[END tpu_vm_stop] diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index d0a5aeece9b..e2b9f54fdbe 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -16,22 +16,16 @@ package tpu; -import static com.google.cloud.tpu.v2.Node.State.READY; -import static com.google.cloud.tpu.v2.Node.State.STOPPED; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertNotNull; import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.tpu.v2.Node; -import com.google.cloud.tpu.v2.TpuClient; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.PrintStream; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import org.junit.Assert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -44,15 +38,15 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -@Timeout(value = 25, unit = TimeUnit.MINUTES) +@Timeout(value = 15, unit = TimeUnit.MINUTES) @TestMethodOrder(MethodOrderer. OrderAnnotation. class) public class TpuVmIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String ZONE = "europe-west4-a"; + private static final String ZONE = "us-central1-a"; static String javaVersion = System.getProperty("java.version").substring(0, 2); private static final String NODE_NAME = "test-tpu-" + javaVersion + "-" + UUID.randomUUID().toString().substring(0, 8); - private static final String TPU_TYPE = "v2-8"; + private static final String TPU_TYPE = "v3-8"; private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; private static final String NODE_PATH_NAME = String.format("projects/%s/locations/%s/nodes/%s", PROJECT_ID, ZONE, NODE_NAME); @@ -85,14 +79,13 @@ public static void cleanup() throws Exception { @Test @Order(1) public void testCreateTpuVm() throws IOException, ExecutionException, InterruptedException { - final PrintStream out = System.out; - ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); - System.setOut(new PrintStream(stdOut)); - CreateTpuVm.createTpuVm(PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION); - assertThat(stdOut.toString()).contains("TPU VM created: " + NODE_PATH_NAME); - stdOut.close(); - System.setOut(out); + Node node = CreateTpuVm.createTpuVm( + PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION); + + assertNotNull(node); + assertThat(node.getName().equals(NODE_NAME)); + assertThat(node.getAcceleratorType().equals(TPU_TYPE)); } @Test @@ -103,33 +96,4 @@ public void testGetTpuVm() throws IOException { assertNotNull(node); assertThat(node.getName()).isEqualTo(NODE_PATH_NAME); } - - @Test - @Order(2) - public void testListTpuVm() throws IOException { - TpuClient.ListNodesPagedResponse nodesList = ListTpuVms.listTpuVms(PROJECT_ID, ZONE); - - assertNotNull(nodesList); - for (Node node : nodesList.iterateAll()) { - Assert.assertTrue(node.getName().contains("test-tpu")); - } - } - - @Test - @Order(2) - public void testStopTpuVm() throws IOException, ExecutionException, InterruptedException { - StopTpuVm.stopTpuVm(PROJECT_ID, ZONE, NODE_NAME); - Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME); - - assertThat(node.getState()).isEqualTo(STOPPED); - } - - @Test - @Order(3) - public void testStartTpuVm() throws IOException, ExecutionException, InterruptedException { - StartTpuVm.startTpuVm(PROJECT_ID, ZONE, NODE_NAME); - Node node = GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME); - - assertThat(node.getState()).isEqualTo(READY); - } } \ No newline at end of file From b6b69e783430da2b232bcd0eb8fb37acc70388fd Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Tue, 29 Oct 2024 14:29:38 +0100 Subject: [PATCH 10/12] Implemented tpu_vm_create_startup_script sample, created test --- .../tpu/CreateTpuVmWithStartupScript.java | 108 ++++++++++++++++++ .../tpu/CreateTpuVmWithStartupScriptIT.java | 86 ++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java create mode 100644 tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java diff --git a/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java b/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java new file mode 100644 index 00000000000..d16c50dcc6a --- /dev/null +++ b/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java @@ -0,0 +1,108 @@ +/* +* Copyright 2024 Google LLC +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package tpu; + +//[START tpu_vm_create_startup_script] +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; +import com.google.cloud.tpu.v2.CreateNodeRequest; +import com.google.cloud.tpu.v2.Node; +import com.google.cloud.tpu.v2.TpuClient; +import com.google.cloud.tpu.v2.TpuSettings; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import org.threeten.bp.Duration; + +public class CreateTpuVmWithStartupScript { + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException { + // TODO(developer): Replace these variables before running the sample. + // Project ID or project number of the Google Cloud project you want to create a node. + String projectId = "YOUR_PROJECT_ID"; + // The zone in which to create the TPU. + // For more information about supported TPU types for specific zones, + // see https://cloud.google.com/tpu/docs/regions-zones + String zone = "europe-west4-a"; + // The name for your TPU. + String nodeName = "YOUR_TPY_NAME"; + // The accelerator type that specifies the version and size of the Cloud TPU you want to create. + // For more information about supported accelerator types for each TPU version, + // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions. + String acceleratorType = "v2-8"; + // Software version that specifies the version of the TPU runtime to install. + // For more information, see https://cloud.google.com/tpu/docs/runtimes + String tpuSoftwareVersion = "tpu-vm-tf-2.14.1"; + + createTpuVmWithStartupScript(projectId, zone, nodeName, acceleratorType, tpuSoftwareVersion); + } + + // Create a TPU VM with a startup script. + public static Node createTpuVmWithStartupScript(String projectId, String zone, + String nodeName, String acceleratorType, String tpuSoftwareVersion) + throws IOException, ExecutionException, InterruptedException { + // With these settings the client library handles the Operation's polling mechanism + // and prevent CancellationException error + TpuSettings.Builder clientSettings = + TpuSettings.newBuilder(); + clientSettings + .createNodeOperationSettings() + .setPollingAlgorithm( + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(5000L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(45000L)) + .setInitialRpcTimeout(Duration.ZERO) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ZERO) + .setTotalTimeout(Duration.ofHours(24L)) + .build())); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. + try (TpuClient tpuClient = TpuClient.create(clientSettings.build())) { + String parent = String.format("projects/%s/locations/%s", projectId, zone); + + // Create metadata map + Map metadata = new HashMap<>(); + metadata.put("startup-script", "your-script-here"); // Script content here + + Node tpuVm = + Node.newBuilder() + .setName(nodeName) + .setAcceleratorType(acceleratorType) + .setRuntimeVersion(tpuSoftwareVersion) + .putAllLabels(metadata) + .build(); + + CreateNodeRequest request = + CreateNodeRequest.newBuilder() + .setParent(parent) + .setNodeId(nodeName) + .setNode(tpuVm) + .build(); + + Node response = tpuClient.createNodeAsync(request).get(); + + System.out.printf("TPU VM created: %s\n", response.getName()); + return response; + } + } +} +//[END tpu_vm_create_startup_script] \ No newline at end of file diff --git a/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java new file mode 100644 index 00000000000..9b4f60939b8 --- /dev/null +++ b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java @@ -0,0 +1,86 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tpu; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static org.junit.Assert.assertNotNull; + +import com.google.api.gax.rpc.NotFoundException; +import com.google.cloud.tpu.v2.Node; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import org.junit.Assert; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@Timeout(value = 25, unit = TimeUnit.MINUTES) +public class CreateTpuVmWithStartupScriptIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String ZONE = "europe-west4-a"; + static String javaVersion = System.getProperty("java.version").substring(0, 2); + private static final String NODE_NAME = "test-tpu-with-script-" + javaVersion + "-" + + UUID.randomUUID().toString().substring(0, 8); + private static final String TPU_TYPE = "v2-8"; + private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; + + public static void requireEnvVar(String envVarName) { + assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) + .that(System.getenv(envVarName)).isNotEmpty(); + } + + @BeforeAll + public static void setUp() + throws IOException, ExecutionException, InterruptedException { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + + // Cleanup existing stale resources. + Util.cleanUpExistingTpu("test-tpu-with-script-" + javaVersion, PROJECT_ID, ZONE); + } + + @AfterAll + public static void cleanup() throws Exception { + DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, NODE_NAME); + + // Test that TPUs is deleted + Assertions.assertThrows( + NotFoundException.class, + () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME)); + } + + @Test + public void testCreateTpuVmWithStartupScript() + throws IOException, ExecutionException, InterruptedException { + Node node = CreateTpuVmWithStartupScript.createTpuVmWithStartupScript( + PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION); + + assertNotNull(node); + assertThat(node.getName().equals(NODE_NAME)); + Assert.assertTrue(node.containsLabels("startup-script")); + Assert.assertTrue(node.getLabelsMap().containsValue("your-script-here")); + + } +} \ No newline at end of file From d00dbb4dfbfae5d68500d2381c25494ea22c66c7 Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Thu, 31 Oct 2024 16:25:02 +0100 Subject: [PATCH 11/12] Fixed tests and empty lines --- tpu/src/main/java/tpu/CreateTpuVm.java | 2 +- .../tpu/CreateTpuVmWithStartupScript.java | 14 +-- .../java/tpu/DeleteForceQueuedResource.java | 1 - tpu/src/main/java/tpu/DeleteTpuVm.java | 2 +- tpu/src/main/java/tpu/GetTpuVm.java | 2 +- .../tpu/CreateTpuVmWithStartupScriptIT.java | 25 +---- ...thNetworkIT.java => QueuedResourceIT.java} | 31 ++---- tpu/src/test/java/tpu/TpuVmIT.java | 20 +--- tpu/src/test/java/tpu/Util.java | 103 ------------------ 9 files changed, 30 insertions(+), 170 deletions(-) rename tpu/src/test/java/tpu/{CreateQueuedResourceWithNetworkIT.java => QueuedResourceIT.java} (74%) delete mode 100644 tpu/src/test/java/tpu/Util.java diff --git a/tpu/src/main/java/tpu/CreateTpuVm.java b/tpu/src/main/java/tpu/CreateTpuVm.java index 5daefabb6d2..2f5e1a2da3b 100644 --- a/tpu/src/main/java/tpu/CreateTpuVm.java +++ b/tpu/src/main/java/tpu/CreateTpuVm.java @@ -39,7 +39,7 @@ public static void main(String[] args) // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; + String nodeName = "YOUR_TPU_NAME"; // The accelerator type that specifies the version and size of the Cloud TPU you want to create. // For more information about supported accelerator types for each TPU version, // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions. diff --git a/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java b/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java index d16c50dcc6a..e25fa04b5fd 100644 --- a/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java +++ b/tpu/src/main/java/tpu/CreateTpuVmWithStartupScript.java @@ -40,7 +40,7 @@ public static void main(String[] args) // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; + String nodeName = "YOUR_TPU_NAME"; // The accelerator type that specifies the version and size of the Cloud TPU you want to create. // For more information about supported accelerator types for each TPU version, // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions. @@ -79,16 +79,17 @@ public static Node createTpuVmWithStartupScript(String projectId, String zone, try (TpuClient tpuClient = TpuClient.create(clientSettings.build())) { String parent = String.format("projects/%s/locations/%s", projectId, zone); - // Create metadata map + String startupScriptContent = "#!/bin/bash\necho \"Hello from the startup script!\""; + // Add startup script to metadata Map metadata = new HashMap<>(); - metadata.put("startup-script", "your-script-here"); // Script content here + metadata.put("startup-script", startupScriptContent); Node tpuVm = Node.newBuilder() .setName(nodeName) .setAcceleratorType(acceleratorType) .setRuntimeVersion(tpuSoftwareVersion) - .putAllLabels(metadata) + .putAllMetadata(metadata) .build(); CreateNodeRequest request = @@ -98,10 +99,7 @@ public static Node createTpuVmWithStartupScript(String projectId, String zone, .setNode(tpuVm) .build(); - Node response = tpuClient.createNodeAsync(request).get(); - - System.out.printf("TPU VM created: %s\n", response.getName()); - return response; + return tpuClient.createNodeAsync(request).get(); } } } diff --git a/tpu/src/main/java/tpu/DeleteForceQueuedResource.java b/tpu/src/main/java/tpu/DeleteForceQueuedResource.java index ed499d8cac5..3de8567857d 100644 --- a/tpu/src/main/java/tpu/DeleteForceQueuedResource.java +++ b/tpu/src/main/java/tpu/DeleteForceQueuedResource.java @@ -17,7 +17,6 @@ package tpu; //[START tpu_queued_resources_delete_force] - import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.UnknownException; import com.google.cloud.tpu.v2alpha1.DeleteQueuedResourceRequest; diff --git a/tpu/src/main/java/tpu/DeleteTpuVm.java b/tpu/src/main/java/tpu/DeleteTpuVm.java index a63af99bf23..a76b1d5487c 100644 --- a/tpu/src/main/java/tpu/DeleteTpuVm.java +++ b/tpu/src/main/java/tpu/DeleteTpuVm.java @@ -39,7 +39,7 @@ public static void main(String[] args) // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; + String nodeName = "YOUR_TPU_NAME"; deleteTpuVm(projectId, zone, nodeName); } diff --git a/tpu/src/main/java/tpu/GetTpuVm.java b/tpu/src/main/java/tpu/GetTpuVm.java index 4a4ec43db2c..b1d6608b5b4 100644 --- a/tpu/src/main/java/tpu/GetTpuVm.java +++ b/tpu/src/main/java/tpu/GetTpuVm.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws IOException { // see https://cloud.google.com/tpu/docs/regions-zones String zone = "europe-west4-a"; // The name for your TPU. - String nodeName = "YOUR_TPY_NAME"; + String nodeName = "YOUR_TPU_NAME"; getTpuVm(projectId, zone, nodeName); } diff --git a/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java index 9b4f60939b8..7bb61f397d1 100644 --- a/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java +++ b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java @@ -20,7 +20,6 @@ import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertNotNull; -import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.tpu.v2.Node; import java.io.IOException; import java.util.UUID; @@ -28,7 +27,6 @@ import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -36,13 +34,11 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -@Timeout(value = 25, unit = TimeUnit.MINUTES) +@Timeout(value = 6, unit = TimeUnit.MINUTES) public class CreateTpuVmWithStartupScriptIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String ZONE = "europe-west4-a"; - static String javaVersion = System.getProperty("java.version").substring(0, 2); - private static final String NODE_NAME = "test-tpu-with-script-" + javaVersion + "-" - + UUID.randomUUID().toString().substring(0, 8); + private static final String NODE_NAME = "test-tpu-with-script-" + UUID.randomUUID(); private static final String TPU_TYPE = "v2-8"; private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; @@ -52,23 +48,14 @@ public static void requireEnvVar(String envVarName) { } @BeforeAll - public static void setUp() - throws IOException, ExecutionException, InterruptedException { + public static void setUp() { requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); requireEnvVar("GOOGLE_CLOUD_PROJECT"); - - // Cleanup existing stale resources. - Util.cleanUpExistingTpu("test-tpu-with-script-" + javaVersion, PROJECT_ID, ZONE); } @AfterAll public static void cleanup() throws Exception { DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, NODE_NAME); - - // Test that TPUs is deleted - Assertions.assertThrows( - NotFoundException.class, - () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME)); } @Test @@ -79,8 +66,8 @@ public void testCreateTpuVmWithStartupScript() assertNotNull(node); assertThat(node.getName().equals(NODE_NAME)); - Assert.assertTrue(node.containsLabels("startup-script")); - Assert.assertTrue(node.getLabelsMap().containsValue("your-script-here")); - + Assert.assertTrue(node.containsMetadata("startup-script")); + Assert.assertTrue(node.getMetadataMap().containsValue("#!/bin/bash\n" + + "echo \"Hello from the startup script!\"")); } } \ No newline at end of file diff --git a/tpu/src/test/java/tpu/CreateQueuedResourceWithNetworkIT.java b/tpu/src/test/java/tpu/QueuedResourceIT.java similarity index 74% rename from tpu/src/test/java/tpu/CreateQueuedResourceWithNetworkIT.java rename to tpu/src/test/java/tpu/QueuedResourceIT.java index 8e7f56fb97b..4d32639afa9 100644 --- a/tpu/src/test/java/tpu/CreateQueuedResourceWithNetworkIT.java +++ b/tpu/src/test/java/tpu/QueuedResourceIT.java @@ -17,15 +17,13 @@ package tpu; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; -import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.tpu.v2alpha1.QueuedResource; -import java.io.IOException; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Timeout; import org.junit.runner.RunWith; @@ -33,39 +31,34 @@ @RunWith(JUnit4.class) @Timeout(value = 6, unit = TimeUnit.MINUTES) -public class CreateQueuedResourceWithNetworkIT { +public class QueuedResourceIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String ZONE = "europe-west4-a"; - static String javaVersion = System.getProperty("java.version").substring(0, 2); - private static final String NODE_NAME = "test-tpu-queued-resource-network-" + javaVersion + "-" - + UUID.randomUUID().toString().substring(0, 8); + private static final String NODE_NAME = "test-tpu-queued-resource-network-" + UUID.randomUUID(); private static final String TPU_TYPE = "v2-8"; private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; - private static final String QUEUED_RESOURCE_NAME = "queued-resource-network-" + javaVersion + "-" - + UUID.randomUUID().toString().substring(0, 8); + private static final String QUEUED_RESOURCE_NAME = "queued-resource-network-" + UUID.randomUUID(); private static final String NETWORK_NAME = "default"; - @BeforeAll - public static void setUp() throws IOException { + public static void requireEnvVar(String envVarName) { + assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) + .that(System.getenv(envVarName)).isNotEmpty(); + } - // Cleanup existing stale resources. - Util.cleanUpExistingQueuedResources("queued-resource-network-", PROJECT_ID, ZONE); + @BeforeAll + public static void setUp() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); } @AfterAll public static void cleanup() { DeleteForceQueuedResource.deleteForceQueuedResource(PROJECT_ID, ZONE, QUEUED_RESOURCE_NAME); - - // Test that resource is deleted - Assertions.assertThrows( - NotFoundException.class, - () -> GetQueuedResource.getQueuedResource(PROJECT_ID, ZONE, QUEUED_RESOURCE_NAME)); } @Test public void testCreateQueuedResourceWithSpecifiedNetwork() throws Exception { - QueuedResource queuedResource = CreateQueuedResourceWithNetwork.createQueuedResourceWithNetwork( PROJECT_ID, ZONE, QUEUED_RESOURCE_NAME, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION, NETWORK_NAME); diff --git a/tpu/src/test/java/tpu/TpuVmIT.java b/tpu/src/test/java/tpu/TpuVmIT.java index 826193ee9bb..64a381b1d28 100644 --- a/tpu/src/test/java/tpu/TpuVmIT.java +++ b/tpu/src/test/java/tpu/TpuVmIT.java @@ -20,14 +20,12 @@ import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertNotNull; -import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.tpu.v2.Node; import java.io.IOException; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -39,13 +37,11 @@ @RunWith(JUnit4.class) @Timeout(value = 15, unit = TimeUnit.MINUTES) -@TestMethodOrder(MethodOrderer. OrderAnnotation. class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class TpuVmIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String ZONE = "asia-east1-c"; - static String javaVersion = System.getProperty("java.version").substring(0, 2); - private static final String NODE_NAME = "test-tpu-" + javaVersion + "-" - + UUID.randomUUID().toString().substring(0, 8); + private static final String NODE_NAME = "test-tpu-" + UUID.randomUUID(); private static final String TPU_TYPE = "v2-8"; private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.12.1"; private static final String NODE_PATH_NAME = @@ -57,29 +53,19 @@ public static void requireEnvVar(String envVarName) { } @BeforeAll - public static void setUp() - throws IOException, ExecutionException, InterruptedException { + public static void setUp() { requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); requireEnvVar("GOOGLE_CLOUD_PROJECT"); - - // Cleanup existing stale resources. - Util.cleanUpExistingTpu("test-tpu-" + javaVersion, PROJECT_ID, ZONE); } @AfterAll public static void cleanup() throws Exception { DeleteTpuVm.deleteTpuVm(PROJECT_ID, ZONE, NODE_NAME); - - // Test that TPUs is deleted - Assertions.assertThrows( - NotFoundException.class, - () -> GetTpuVm.getTpuVm(PROJECT_ID, ZONE, NODE_NAME)); } @Test @Order(1) public void testCreateTpuVm() throws IOException, ExecutionException, InterruptedException { - Node node = CreateTpuVm.createTpuVm( PROJECT_ID, ZONE, NODE_NAME, TPU_TYPE, TPU_SOFTWARE_VERSION); diff --git a/tpu/src/test/java/tpu/Util.java b/tpu/src/test/java/tpu/Util.java deleted file mode 100644 index dedd3628fd0..00000000000 --- a/tpu/src/test/java/tpu/Util.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package tpu; - -import com.google.cloud.tpu.v2.Node; -import com.google.cloud.tpu.v2.TpuClient; -import com.google.cloud.tpu.v2alpha1.QueuedResource; -import com.google.protobuf.Timestamp; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.concurrent.ExecutionException; - -public class Util { - private static final int DELETION_THRESHOLD_TIME_MINUTES = 30; - - // Delete TPU VMs which starts with the given prefixToDelete and - // has creation timestamp >30 minutes. - public static void cleanUpExistingTpu(String prefixToDelete, String projectId, String zone) - throws IOException, ExecutionException, InterruptedException { - try (TpuClient tpuClient = TpuClient.create()) { - String parent = String.format("projects/%s/locations/%s", projectId, zone); - for (Node node : tpuClient.listNodes(parent).iterateAll()) { - String creationTime = formatTimestamp(node.getCreateTime()); - String name = node.getName().substring(node.getName().lastIndexOf("/") + 1); - if (containPrefixToDeleteAndZone(node, prefixToDelete, zone) - && isCreatedBeforeThresholdTime(creationTime)) { - DeleteTpuVm.deleteTpuVm(projectId, zone, name); - } - } - } - } - - // Delete QueuedResources which starts with the given prefixToDelete and - // has creation timestamp >30 minutes. - public static void cleanUpExistingQueuedResources( - String prefixToDelete, String projectId, String zone) - throws IOException { - try (com.google.cloud.tpu.v2alpha1.TpuClient tpuClient = - com.google.cloud.tpu.v2alpha1.TpuClient.create()) { - String parent = String.format("projects/%s/locations/%s", projectId, zone); - - for (QueuedResource queuedResource : tpuClient.listQueuedResources(parent).iterateAll()) { - com.google.cloud.tpu.v2alpha1.Node node = queuedResource.getTpu().getNodeSpec(0).getNode(); - String creationTime = formatTimestamp(node.getCreateTime()); - String name = queuedResource.getName() - .substring(queuedResource.getName().lastIndexOf("/") + 1); - if (containPrefixToDeleteAndZone(queuedResource, prefixToDelete, zone) - && isCreatedBeforeThresholdTime(creationTime)) { - DeleteForceQueuedResource.deleteForceQueuedResource(projectId, zone, name); - } - } - } - } - - public static boolean containPrefixToDeleteAndZone( - Object resource, String prefixToDelete, String zone) { - boolean containPrefixAndZone = false; - try { - if (resource instanceof Node) { - containPrefixAndZone = ((Node) resource).getName().contains(prefixToDelete) - && ((Node) resource).getName().split("/")[3].contains(zone); - } - if (resource instanceof QueuedResource) { - containPrefixAndZone = ((QueuedResource) resource).getName().contains(prefixToDelete) - && ((QueuedResource) resource).getName().split("/")[3].contains(zone); - } - } catch (NullPointerException e) { - System.out.println("Resource not found, skipping deletion:"); - } - return containPrefixAndZone; - } - - public static boolean isCreatedBeforeThresholdTime(String timestamp) { - return OffsetDateTime.parse(timestamp).toInstant() - .isBefore(Instant.now().minus(DELETION_THRESHOLD_TIME_MINUTES, ChronoUnit.MINUTES)); - } - - private static String formatTimestamp(Timestamp timestamp) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant( - Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), - ZoneOffset.UTC); - return formatter.format(offsetDateTime); - } -} \ No newline at end of file From 952c4162ebf4f22b913c34a5a938e959664193ba Mon Sep 17 00:00:00 2001 From: Tetiana Yahodska Date: Fri, 1 Nov 2024 10:56:02 +0100 Subject: [PATCH 12/12] Changed zone --- tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java index 7bb61f397d1..c4b001f9e85 100644 --- a/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java +++ b/tpu/src/test/java/tpu/CreateTpuVmWithStartupScriptIT.java @@ -37,10 +37,10 @@ @Timeout(value = 6, unit = TimeUnit.MINUTES) public class CreateTpuVmWithStartupScriptIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String ZONE = "europe-west4-a"; + private static final String ZONE = "asia-east1-c"; private static final String NODE_NAME = "test-tpu-with-script-" + UUID.randomUUID(); private static final String TPU_TYPE = "v2-8"; - private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.14.1"; + private static final String TPU_SOFTWARE_VERSION = "tpu-vm-tf-2.12.1"; public static void requireEnvVar(String envVarName) { assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))