1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.cloud.notebooks.v1beta1.it; 18 19 import com.google.cloud.notebooks.v1beta1.DeleteInstanceRequest; 20 import com.google.cloud.notebooks.v1beta1.Instance; 21 import com.google.cloud.notebooks.v1beta1.ListInstancesRequest; 22 import com.google.cloud.notebooks.v1beta1.NotebookServiceClient; 23 import com.google.cloud.notebooks.v1beta1.NotebookServiceClient.ListInstancesPagedResponse; 24 import com.google.protobuf.util.Timestamps; 25 import java.time.Instant; 26 import java.time.temporal.ChronoUnit; 27 28 public class Util { 29 30 // Cleans existing test resources if any. 31 private static final int DELETION_THRESHOLD_TIME_HOURS = 24; 32 33 /** Bring down any instances that are older than 24 hours */ cleanUpNotebookInstances( NotebookServiceClient client, String parent, String prefix)34 public static void cleanUpNotebookInstances( 35 NotebookServiceClient client, String parent, String prefix) { 36 ListInstancesPagedResponse listInstancesPagedResponse = 37 client.listInstances(ListInstancesRequest.newBuilder().setParent(parent).build()); 38 for (Instance instance : listInstancesPagedResponse.iterateAll()) { 39 if (isCreatedBeforeThresholdTime( 40 Instant.ofEpochMilli(Timestamps.toMillis(instance.getCreateTime()))) 41 && instance.getName().startsWith(prefix)) { 42 client.deleteInstanceAsync( 43 DeleteInstanceRequest.newBuilder().setName(instance.getName()).build()); 44 } 45 } 46 } 47 isCreatedBeforeThresholdTime(Instant instant)48 private static boolean isCreatedBeforeThresholdTime(Instant instant) { 49 return instant.isBefore(Instant.now().minus(DELETION_THRESHOLD_TIME_HOURS, ChronoUnit.HOURS)); 50 } 51 } 52