EC2 Java Api 等待 Ec2 实例创建。

发布于 2024-12-08 07:13:44 字数 248 浏览 0 评论 0原文

我刚刚开始在 Java 中使用 Amazon EC2 API。

我已经使用 ec2.runInstances(runInstancesRequest); 创建了实例

但实例启动需要一些时间(通常为 1-2 分钟)。 我需要通过 Java EC2 API 获取机器的公共 DNS。

我如何知道实例何时从“待处理”状态更改为“已处理”状态,以及如何通过 EC2 API 获取 EC2 实例的公共 DNS。

提前致谢。 神无

I have just started using Amazon EC2 API in Java.

I have created instances using ec2.runInstances(runInstancesRequest);

But it will take some time for the instance to get launched (typically 1-2 mins).
I need to get the public DNS of the machine via Java EC2 API.

How do I know when the instances change from "pending" state to "processed" state, and How can I get the public DNS of the EC2 instance through the EC2 API.

Thanks in advance.
Kanna

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一百个冬季 2024-12-15 07:13:44

SDK 没有发出任何事件模型或其他信号来告诉您 EC2 对象何时更改状态 - 唯一的查找方法是对对象重复发出DescribeXXXXXXXX 调用,例如每 30 秒一次,直到状态字段发生变化。

调用执行和响应的最短时间是有限的,因此您需要找到一个在前一个请求完成之前不会触发请求的时间间隔。或者只是等待响应,然后再等待“n”秒,然后重新发出呼叫。您也不希望向 AWS API 发送快速请求,即使它们是在响应之间定时的。在我的控制器应用程序中,我将间隔设置为 30 秒,发出请求,等待响应,然后从间隔中减去经过的时间并休眠那么长时间。在多线程模型中,我可以同时跟踪许多对象的状态变化,而不会占用本地 CPU 或 API。

一旦检测到状态更改(并且假设新状态符合您的预期 - 不要忘记处理故障模式),您可以获得各种描述性信息,包括公共 DNS 地址(在实例对象的情况下)来自 API 响应对象中返回的结构。

There is no event model or other signal raised by the SDK to tell you when an EC2 object changes state - the only way to find out is to issue a DescribeXXXXXXXX call on the object on a repeated basis, say once every 30 seconds, until the state field changes.

There's a finite minimum time for the call to execute and respond, so you need to find an interval that doesn't fire requests before the prior one has completed. Or simply wait for the response, and then wait another 'n' seconds before re-issuing the call. You also don't want to spam the AWS API with rapid requests, even if they're timed between responses. In my controller application, I set the interval at 30 seconds, issue the request, wait for the response, and then subtract the elapsed time from the interval and sleep that long. In a multithreaded model, I can thereby track state changes on many objects simultaneously without swamping either my local CPU or the API.

Once the change of state has been detected (and assuming the new state is whet you expect - don't forget to handle failure modes) you can get a wide variety of descriptive information, including public DNS address (in the case of instance objects) from the structure returned in the API response object.

情定在深秋 2024-12-15 07:13:44

这就是我正在做的事情。如果有更优雅的方法来做到这一点,我很乐意看到它。

        Callable<String> getInstanceMetadata = () -> {
          Instance instance = null;
          while (null == instance) {
            // Describe the instance to check its state
            Thread.sleep(10 * 1000);
            //Each reservation is a representation of a request that may be tens of nodes.
            List<Reservation> reservations = ec2.describeInstances().getReservations();
            //create a stream of instances from all reservations
            Stream<Instance> instancesStream = reservations.stream().flatMap(reservation -> reservation.getInstances().stream());
            //filter the stream to find the instance with the instanceId
            instance = instancesStream.filter(i -> i.getInstanceId().equals(instanceId)).findFirst().orElse(null);
        }

        String publicIp = instance.getPublicIpAddress();
        assert instance.getInstanceId() == instanceId;

        log.debug("Successfully created ec2 node {} with public IP {}", instance.getInstanceId(), publicIp);
        return instance.getInstanceId()
    };

    TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor());

This is what I'm doing. If there's a more elegant way to do it I would love to see it.

        Callable<String> getInstanceMetadata = () -> {
          Instance instance = null;
          while (null == instance) {
            // Describe the instance to check its state
            Thread.sleep(10 * 1000);
            //Each reservation is a representation of a request that may be tens of nodes.
            List<Reservation> reservations = ec2.describeInstances().getReservations();
            //create a stream of instances from all reservations
            Stream<Instance> instancesStream = reservations.stream().flatMap(reservation -> reservation.getInstances().stream());
            //filter the stream to find the instance with the instanceId
            instance = instancesStream.filter(i -> i.getInstanceId().equals(instanceId)).findFirst().orElse(null);
        }

        String publicIp = instance.getPublicIpAddress();
        assert instance.getInstanceId() == instanceId;

        log.debug("Successfully created ec2 node {} with public IP {}", instance.getInstanceId(), publicIp);
        return instance.getInstanceId()
    };

    TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor());
爱你不解释 2024-12-15 07:13:44

实际上,您可以通过 POLL 来了解实例的状态。这里有一些 Bash 代码可以做到这一点,只需将其适应 JAVA 即可。 Java SDK 中可能有类似的命令,这样您就不必从 Java 执行 Bash。命令“ec2-describe-instances”来自 Amazon AWS CLI。我将启动函数或方法来等待运行状态来测试实例是否处于“待处理”状态,如果实例未启动或“待处理”则失败。然后记录时间,假设最多为 3 分钟,然后继续循环轮询“正在运行”状态,检查 3 分钟限制。返回调用点,以先到者为准,“未启动”、“超出启动时间”或“正在运行”。

    setInstanceStatus () {
  instanceStatus=`ec2-describe-instances $INSTANCE_ID -C $CERTIFICATE_FILE -K $PRIVATE_KEY --region $REGION -U $AWS_URL`

  is_pending="`echo $instanceStatus|grep -c " pending "`"
  is_running="`echo $instanceStatus|grep -c " running "`"
  is_shutting_down="`echo $instanceStatus|grep -c " shutting-down "`"
  is_terminated="`echo $instanceStatus|grep -c " terminated "`"
  is_stopping="`echo $instanceStatus|grep -c " stopping "`"
  is_stopped="`echo $instanceStatus|grep -c " stopped "`"

  if   [ "$is_pending" -eq "1" ]; then
    status="pending"
  elif [  "$is_running" -eq "1" ]; then
    status="running"
  elif [  "$is_shutting_down" -eq "1" ]; then
    status="shutting-down"
  elif [  "$is_terminated" -eq "1" ]; then
    status="terminated"
  elif [  "$is_stopping" -eq "1" ]; then
    status="stopping"
  elif [  "$is_stopped" -eq "1" ]; then
    status="stopped"
  else
    status="bad-instance-state"
  fi
}

Actually, you can POLL to find out the status of an instance. Here is some Bash code to do that, just adapt it to JAVA. You MAY have a similar command in the Java SDK so that you don't have to do an execution of Bash from Java. The command 'ec2-describe-instances' comes from the Amazon AWS CLI. I would start out the function or method to wait for running state to test if instance is 'pending', and fail if it is not starting or 'pending'. Then record the time, and give it a max of let's say 3 minutes, and just keep polling for 'running' status in a loop, checking for the 3 minute limit. Return to the calling point whichever comes first, 'not started','startup time exceeded', or 'running'.

    setInstanceStatus () {
  instanceStatus=`ec2-describe-instances $INSTANCE_ID -C $CERTIFICATE_FILE -K $PRIVATE_KEY --region $REGION -U $AWS_URL`

  is_pending="`echo $instanceStatus|grep -c " pending "`"
  is_running="`echo $instanceStatus|grep -c " running "`"
  is_shutting_down="`echo $instanceStatus|grep -c " shutting-down "`"
  is_terminated="`echo $instanceStatus|grep -c " terminated "`"
  is_stopping="`echo $instanceStatus|grep -c " stopping "`"
  is_stopped="`echo $instanceStatus|grep -c " stopped "`"

  if   [ "$is_pending" -eq "1" ]; then
    status="pending"
  elif [  "$is_running" -eq "1" ]; then
    status="running"
  elif [  "$is_shutting_down" -eq "1" ]; then
    status="shutting-down"
  elif [  "$is_terminated" -eq "1" ]; then
    status="terminated"
  elif [  "$is_stopping" -eq "1" ]; then
    status="stopping"
  elif [  "$is_stopped" -eq "1" ]; then
    status="stopped"
  else
    status="bad-instance-state"
  fi
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文