If a preemptible instance is forcibly recycled due to a market price change or insufficient resources, an interruption event is triggered. Before the preemptible instance is recycled, it enters the locked state and you are prompted that the instance will be recycled. This topic describes how to query interruption events of preemptible instances. You can automate the instance interruption and recycle processes based on the recycle status of instances.
Query interruption events of preemptible instances by using Cloud Monitor SDK
This section describes how to query interruption events of preemptible instances by using Cloud Monitor SDK for Java.
Query interruption events of preemptible instances by using instance metadata
Query interruption events of preemptible instances by calling an API operation
This section describes how to call the DescribeInstances operation to determine whether the instance has entered the to be recycled state based on the returned OperationLocks parameter.
public class DescribeInstancesSample {
public static void main(String[] args) throws InterruptedException {
OpenApiCaller caller = new OpenApiCaller();
JSONArray allInstances = new JSONArray();
allInstances.addAll(Arrays.asList("i-bp18hgfai8ekoqwo0***", "i-bp1ecbyds24ij63w1***"));
while (! allInstances.isEmpty()) {
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.setRegionId("cn-hangzhou");
request.setInstanceIds(allInstances.toJSONString());// Specify the ID of the instance and query only the instance whose ID has been specified.
DescribeInstancesResponse response = caller.doAction(request);
List<DescribeInstancesResponse.Instance> instanceList = response.getInstances();
if (instanceList ! = null && ! instanceList.isEmpty()) {
for (DescribeInstancesResponse.Instance instance : instanceList) {
System.out.println("result:instance:" + instance.getInstanceId() + ",az:" + instance.getZoneId());
if (instance.getOperationLocks() ! = null) {
for (DescribeInstancesResponse.Instance.LockReason lockReason : instance.getOperationLocks()) {
System.out.println("instance:" + instance.getInstanceId() + "-->lockReason:" + lockReason.getLockReason() + ",vmStatus:" + instance.getStatus());
if ("Recycling".equals(lockReason.getLockReason())) {
//do your action
System.out.println("spot instance will be recycled immediately, instance id:" + instance.getInstanceId());
allInstances.remove(instance.getInstanceId());
}
}
}
}
System.out.print("try describeInstances again later ...") ;
Thread.sleep(2 * 60 * 1000);
} else {
break;
}
}
}
}
instance:i-bp1ecbyds24ij63w****-->lockReason:Recycling,vmStatus:Stopped spot instance will be recycled immediately, instance id:i-bp1ecbyds24ij63w****