阻止直到所有EC2实例都处于特定状态?

时间:2012-02-08 10:42:42

标签: java amazon-ec2

我写了一个函数,它应该阻塞,直到列表中的所有实例都不处于特定状态,所以这就是我所拥有的:

private void waitForInstanceState(List<String> instancesId, InstanceStateName state) {
    int numAchievedState = 0;

    while (numAchievedState != instancesId.size()) {

        numAchievedState = 0;

        DescribeInstanceStatusRequest describeRequest = new DescribeInstanceStatusRequest().withInstanceIds(instancesId);
        DescribeInstanceStatusResult instanceStatus = ec2.describeInstanceStatus(describeRequest);

        for (InstanceStatus status : instanceStatus.getInstanceStatuses()) {
            if (status.getInstanceState().getName().equals(state.toString())) {
                numAchievedState++;
            }
        }

        try {
            Thread.sleep(15000);
        } catch (InterruptedException ex) {
            Logger.getLogger(AmazonLibrary.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

调用上述函数的代码如下:

public void startInstace(List<String> instancesId) {

    StartInstancesRequest startRequest = new StartInstancesRequest(instancesId);
    ec2.startInstances(startRequest);

    waitForInstanceState(instancesId, InstanceStateName.Running);

    System.out.println("The instance has been started");


}

有时候,实例请求会为InstanceStatus返回null,我认为永远不会发生这种情况,因为亚马逊的实例总是有状态吗?此外,当在instanceRun函数中使用时,它可以工作,当InstanceStateName设置为Stopped并不运行时。不会抛出异常或错误。

1 个答案:

答案 0 :(得分:1)

以下完成了这项工作:

 private void waitForInstanceState(List<String> instancesId, InstanceStateName state) {
        int numAchievedState = 0;

        while (numAchievedState != instancesId.size()) {

            try {
                Thread.sleep(15000);
            } catch (InterruptedException ex) {
                Logger.getLogger(AmazonLibrary.class.getName()).log(Level.SEVERE, null, ex);
            }

            numAchievedState = 0;

            DescribeInstancesRequest describeInstance = new DescribeInstancesRequest().withInstanceIds(instancesId);
            DescribeInstancesResult describeResult = ec2.describeInstances(describeInstance);
            List<Reservation> reservations = describeResult.getReservations();

            //different instances might be in different reservation requests
            //so we need to traverse those
            for (Reservation reservation : reservations) {
                List<Instance> instances = reservation.getInstances();
                for (Instance instance : instances) {
                    if (instance.getState().getName().equals(state.toString())) {
                        numAchievedState++;
                    }
                }
            }
        }
    }