如何查看我的应用运行的平台,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;
}
}
但是当我的应用程序在非云系统中运行时,我遇到了一个问题,例如本地Windows系统。执行isAWS()方法时速度非常慢。代码'req.GetResponse()'需要很长时间。所以我想知道如何处理它?请帮我!提前谢谢。
答案 0 :(得分:11)
更好的方法是发出获取实例元数据的请求。
从正在运行的内容中查看所有类别的实例元数据 实例,使用以下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"
答案 1 :(得分:7)
我认为您最初的想法非常好,但无需提出网络请求。只需尝试查看名称是否解析(在python中):
def is_ec2():
import socket
try:
socket.gethostbyname('instance-data.ec2.internal.')
return True
except socket.gaierror:
return False
答案 2 :(得分: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.
你也可以只使用一系列数据而不是全数据来加速呼叫:
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
上述任何一种方法都可以更快地到达您网站的运行位置。
答案 3 :(得分:2)
在ec2 Ubuntu实例上,文件/sys/hypervisor/uuid
存在,前三个字符为'ec2'。我喜欢使用它,因为它不依赖于外部服务器。