抢占式实例可能会因为价格因素或者市场供需变化而被强制回收,此时会触发抢占式实例的中断。回收前,抢占式实例会进入锁定状态,提示实例将会被自动回收。本文介绍如何查询抢占式实例中断事件,您可以针对实例回收状态自动化处理实例的退出逻辑。
通过云监控SDK查询抢占式实例中断事件
以云监控Java SDK为例,介绍如何查询抢占式实例中断事件。
通过实例元数据获取查询抢占式实例中断事件
通过API查询抢占式实例中断事件
使用DescribeInstances,根据返回的OperationLocks判断实例是否进入待回收状态。
代码示例(DescribeInstancesSample.java)如下所示。
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());//指定实例ID,效率最高
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****