If a preemptible instance is forcefully 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 automatically recycled. This topic describes how to query whether a preemptible instance is interrupted.
Method 1: Use an CloudMonitor SDK
This section describes how to use CloudMonitor SDK for Java to query the interruption events of a preemptible instance.
Access CloudMonitor SDK for Java.
For more information, see SDK reference.
Query the interruption events of a preemptible instance by using the SDK.
Sample code:
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.google.gson.Gson; import java.util.*; import com.aliyuncs.cms.model.v20190101.*; public class DescribeSystemEventAttribute { public static void main(String[] args) { // Initialize a DefaultAcsClient instance. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime environment. // If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code shows how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use Security Token Service (STS) tokens, which provide higher security. DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); IAcsClient client = new DefaultAcsClient(profile); // Query the interruption events of preemptible instances. DescribeSystemEventAttributeRequest request = new DescribeSystemEventAttributeRequest(); request.setRegionId("cn-hangzhou"); request.setProduct("ECS"); request.setEventType("StatusNotification"); request.setName("Instance:PreemptibleInstanceInterruption"); try { // Obtain the responses. DescribeSystemEventAttributeResponse response = client.getAcsResponse(request); System.out.println(new Gson().toJson(response)); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { System.out.println("ErrCode:" + e.getErrCode()); System.out.println("ErrMsg:" + e.getErrMsg()); System.out.println("RequestId:" + e.getRequestId()); } } }
Check the interruption events of preemptible instances based on the responses.
The following section shows a sample interruption event notification in the JSON format for a preemptible instance:
{ "ver": "1.0", "id": "2256A988-0B26-4E2B-820A-8A********E5", "product": "ECS", "resourceId": "acs:ecs:cn-hangzhou:169070********30:instance/i-bp1ecr********5go2go", "level": "INFO", "name": "Instance:PreemptibleInstanceInterruption", "userId": "169070********30", "eventTime": "20190409T121826.922+0800", "regionId": "cn-hangzhou", "content": { "instanceId": "i-bp1ecr********5go2go", "action": "delete" } }
The following table describes the fields that are contained in the
content
parameter. For information about more parameters, see DescribeSystemEventAttribute.Field
Description
Example
instanceId
The ID of the preemptible instance.
i-bp1ecr********5go2go
action
The action on the preemptible instance. If the parameter is set to delete, the interrupted preemptible instance is forcefully recycled.
delete
Method 2: Query the interruption events of a preemptible instance by using instance metadata
Linux instance
# Obtain the access credentials of the metadata server for authentication.
TOKEN=`curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds:<Validity period of the metadata server access credentials>"`
# Query whether the preemptible instance is interrupted and recycled.
curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/meta-data/instance/spot/termination-time
Windows instance
# Obtain the access credentials of the metadata server for authentication.
$token=Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "<Validity period of the metadata server access credentials>"} -Method PUT -Uri http://100.100.100.200/latest/api/token
# Query whether the preemptible instance is interrupted and recycled.
Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token" = $token} -Method GET -Uri http://100.100.100.200/latest/meta-data/instance/spot/termination-time
If 404 is returned, the instance is available.
If a UTC timestamp such as
2015-01-05T18:02:00Z
is returned, the instance is due to be recycled at the specified time point.
Query the interruption events of a preemptible instance by calling an API operation
This section describes how to call the DescribeInstances operation to check whether the instance is in the To Be Released state based on the OperationLocks array in the response.
If null is returned, the instance is available.
If Recycling is returned for the LockReason parameter, the preemptible instance is interrupted and is due to be recycled.
Sample DescribeInstancesSample.java code:
import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.AcsRequest;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import java.util.*;
public class DescribeInstancesSample {
public static void main(String[] args) throws InterruptedException {
// Initialize a DefaultAcsClient instance.
OpenApiCaller caller = new OpenApiCaller();
// Specify the IDs of one or more instances.
JSONArray allInstances = new JSONArray();
allInstances.addAll(Arrays.asList("i-bp1i9c3qiv1qs6nc****"));
while (!allInstances.isEmpty()) {
DescribeInstancesRequest request = new DescribeInstancesRequest();
// Specify the region ID of the instance.
request.setRegionId("cn-hangzhou");
// Specify instance IDs.
request.setInstanceIds(allInstances.toJSONString());
// Obtain the responses.
DescribeInstancesResponse response = caller.doAction(request);
// Obtain instance-specific results.
List<DescribeInstancesResponse.Instance> instanceList = response.getInstances();
if (instanceList != null && !instanceList.isEmpty()) {
for (DescribeInstancesResponse.Instance instance : instanceList) {
// View the IDs and zone information of the queried instances.
System.out.println("result:instance:" + instance.getInstanceId() + ",az:" + instance.getZoneId());
if (instance.getOperationLocks() != null) {
for (DescribeInstancesResponse.Instance.LockReason lockReason : instance.getOperationLocks()) {
// If an instance is locked, view the instance ID and the lock reason.
System.out.println("instance:" + instance.getInstanceId() + "-->lockReason:" + lockReason.getLockReason() + ",vmStatus:" + instance.getStatus());
if ("Recycling".equals(lockReason.getLockReason())) {
// View the IDs of the instances to be recycled.
System.out.println("spot instance will be recycled immediately, instance id:" + instance.getInstanceId());
allInstances.remove(instance.getInstanceId());
}
}
}
}
// If a preemptible instance is not locked, it is queried every 2 minutes.
System.out.print("try describeInstances again later ...");
Thread.sleep(2 * 60 * 1000);
} else {
break;
}
}
}
}
// Initialize a DefaultAcsClient instance.
class OpenApiCaller{
IClientProfile profile;
IAcsClient client;
public OpenApiCaller() {
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime environment.
// If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code provides an example on how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use STS tokens, which provide higher security.
profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
client = new DefaultAcsClient(profile);
}
public <T extends AcsResponse> T doAction(AcsRequest<T> var1) {
try {
return client.getAcsResponse(var1);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
The following response is returned if the recycle is triggered:
result:instance:i-bp1i9c3qiv1qs6nc****,az:cn-hangzhou-i
instance:i-bp1i9c3qiv1qs6nc****-->lockReason:Recycling,vmStatus:Stopped
spot instance will be recycled immediately, instance id:i-bp1i9c3qiv1qs6nc****