From b14ecd1e2cffb4c41c3f95290b929213f9ac518c Mon Sep 17 00:00:00 2001 From: Andreas Janning Date: Fri, 6 Sep 2024 11:18:38 +0200 Subject: [PATCH] Make sure an instance exists in the cloud before trying to delete it. Else jenkins nodes cannot be deleted if there is no corresponding instance in the cloud. --- .../computeengine/ComputeEngineInstance.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/google/jenkins/plugins/computeengine/ComputeEngineInstance.java b/src/main/java/com/google/jenkins/plugins/computeengine/ComputeEngineInstance.java index ec0f92a2..6bf1bd8e 100644 --- a/src/main/java/com/google/jenkins/plugins/computeengine/ComputeEngineInstance.java +++ b/src/main/java/com/google/jenkins/plugins/computeengine/ComputeEngineInstance.java @@ -16,8 +16,11 @@ package com.google.jenkins.plugins.computeengine; +import static com.google.jenkins.plugins.computeengine.ComputeEngineCloud.CLOUD_ID_LABEL_KEY; + import com.google.cloud.graphite.platforms.plugin.client.ComputeClient.OperationException; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; import com.google.jenkins.plugins.computeengine.ssh.GoogleKeyCredential; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.Extension; @@ -30,6 +33,7 @@ import hudson.slaves.RetentionStrategy; import java.io.IOException; import java.util.Collections; +import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; @@ -130,9 +134,16 @@ protected void _terminate(TaskListener listener) throws IOException, Interrupted .createSnapshotSync(cloud.getProjectId(), this.zone, this.getNodeName(), createSnapshotTimeout); } - // If the instance is running, attempt to terminate it. This is an async call and we + Map filterLabel = ImmutableMap.of(CLOUD_ID_LABEL_KEY, cloud.getInstanceId()); + var instanceExistsInCloud = + cloud.getClient().listInstancesWithLabel(cloud.getProjectId(), filterLabel).stream() + .anyMatch(instance -> instance.getName().equals(name)); + + // If the instance exists in the cloud, attempt to terminate it. This is an async call and we // return immediately, hoping for the best. - cloud.getClient().terminateInstanceAsync(cloud.getProjectId(), zone, name); + if (instanceExistsInCloud) { + cloud.getClient().terminateInstanceAsync(cloud.getProjectId(), zone, name); + } } catch (CloudNotFoundException cnfe) { listener.error(cnfe.getMessage()); } catch (OperationException oe) {