如何在AWS EC2实例中检查应用程序运行

Jim*_*mmy 12 instance amazon-ec2 amazon-web-services

如何查看我的应用运行的平台,AWS EC2实例,Azure角色实例和非云系统?现在我这样做:

if(isAzure())
{
    //run in Azure role instance
}
else if(isAWS())
{
   //run in AWS EC2 instance
}
else
{
   //run in the non-cloud system
}

//checked whether it runs in AWS EC2 instance or not.
bool isAWS()
{
  string url = "http://instance-data";
  try
  {
     WebRequest req = WebRequest.Create(url);
     req.GetResponse();
     return true;
  }
  catch
  {
     return false;
  }  
}
Run Code Online (Sandbox Code Playgroud)

但是当我的应用程序在非云系统中运行时,我遇到了一个问题,例如本地Windows系统.执行isAWS()方法时速度非常慢.代码'req.GetResponse()'需要很长时间.所以我想知道如何处理它?请帮我!提前致谢.

Raj*_*Raj 13

更好的方法是发出获取实例元数据的请求.

AWS文档:

要在正在运行的实例中查看所有类别的实例元数据,请使用以下URI:

http://169.254.169.254/latest/meta-data/

在Linux实例上,您可以使用cURL等工具,或使用GET命令,例如:

PROMPT> GET http://169.254.169.254/latest/meta-data/

这是使用Python Boto包装器的示例:

from boto.utils import get_instance_metadata

m = get_instance_metadata()

if len(m.keys()) > 0:
    print "Running on EC2"

else:
    print "Not running on EC2"
Run Code Online (Sandbox Code Playgroud)

  • 你现在可以设置重试限制:``get_instance_metadata(timeout = 0.5,num_retries = 1)`` (7认同)

Nat*_*ert 7

我认为你最初的想法非常好,但不需要提出网络请求.只需尝试查看名称是否解析(在python中):

def is_ec2():
    import socket
    try:
        socket.gethostbyname('instance-data.ec2.internal.')
        return True
    except socket.gaierror:
        return False
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:只有在您使用内部亚马逊解析器时才有效.如果你做了一些事情,比如将解析器指向8.8.8.8,这将失败.我们在亚马逊遇到DNS故障(他们的DNS服务器处于脱机状态)并且测试失败. (4认同)

Avk*_*han 2

正如您所说, WebRequest.Create() 调用在桌面上速度很慢,因此您确实需要检查网络流量(使用Netmon)来实际确定花费了很长时间的时间。此请求打开连接,连接到目标服务器,下载内容,然后关闭连接,因此最好知道这次时间发生在哪里。

另外,如果您只想知道任何 URL(在 Azure、EC2 或任何其他 Web 服务器上)是否处于活动状态并且工作正常,您可以使用以下命令请求仅下载标头

string URI = "http://www.microsoft.com";
HttpWebRequest  req = (HttpWebRequest)WebRequest.Create(URI);
req.Method = WebRequestMethods.Http.Head;
var response = req.GetResponse();
int TotalSize = Int32.Parse(response.Headers["Content-Length"]);
// Now you can parse the headers for 200 OK and know that it is working.
Run Code Online (Sandbox Code Playgroud)

您还可以仅使用 GET 一定范围的数据而不是完整数据来加快调用:

HttpWebRequest myHttpWebReq =(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebReq.AddRange(-200, ContentLength); // return first 0-200 bytes
//Now you can send the request and then parse date for headers for 200 OK
Run Code Online (Sandbox Code Playgroud)

上述任何一种方法都可以更快地获取您的网站的运行位置。