15

How can I check which platform my app runs, AWS EC2 instance, Azure Role instance and non-cloud system? now I do that like this:

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;
  }  
}

but I have one problem when my apps runs in the non-cloud system, like local windows system. It got very slowly while executing isAWS() method. the code 'req.GetResponse()' takes a long time. so I want to know how can I to deal with it? please help me! thanks in advance.

Jimmy
  • 153
  • 1
  • 1
  • 5

4 Answers4

13

The better way to do this would be to make a request to get instance metadata.

From the AWS Documentation:

To view all categories of instance metadata from within a running instance, use the following URI:

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

On a Linux instance, you can use a tool such as cURL, or use the GET command, for example:

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

Here's an example using the Python Boto wrapper:

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"
Raj
  • 3,791
  • 5
  • 43
  • 56
7

I think your original idea is pretty good, but no need to make the web request. Simply try to see if the name resolves (in python):

def is_ec2():
    import socket
    try:
        socket.gethostbyname('instance-data.ec2.internal.')
        return True
    except socket.gaierror:
        return False
Nathan Binkert
  • 8,744
  • 1
  • 29
  • 37
  • 4
    FYI: this only works if you're using the internal amazon resolver. If you do something like point your resolver to 8.8.8.8, this will fail. We had a DNS failure at amazon (their dns server was offline) and the test failed. – Nathan Binkert Aug 13 '13 at 22:59
  • That host is not available for me using the amazon resolver. You have to drop the domain name and let the resolver append its default. So use `socket.gethostbyname('instance-data`). – nmgeek Mar 29 '18 at 14:48
2

As you said the WebRequest.Create() call is slow on your desktop so you really need to check the network traffic (using Netmon) to actually determine what took long time. This request, opens connection, connects to target server, downloads the content and then close the connection so it is good to know where this time is taken.

Also if you just want to know if any URL (on Azure, on EC2 or any other web server is live and working fine you can just request to only download headers by using

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.

You can also use GET only a range of the data instead of full data to expedite to call:

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

Any of the above method will be faster to get where your site is running.

AvkashChauhan
  • 20,495
  • 3
  • 34
  • 65
  • Thanks your post! It got faster when I change the method you provided. – Jimmy Jun 07 '12 at 01:33
  • I am glad it worked for u. grateful if you accept my suggestions as answer. Thanks you!! – AvkashChauhan Jun 07 '12 at 01:43
  • Thanks your post! It got faster when I changed the method you provided. but it still slowly when my site isn't working. as usual, the code 'req.GetResponse()' takes about 3 seconds time. so I want to know how to get faster when request's getting responses from the server? – Jimmy Jun 07 '12 at 01:43
  • "site is not working" does it mean the URL is bogus because there is no site? The response in case of bad URL will be longer in some case as requesting network might wait a little to get response if there is none, this is how the network is designed. If there is immediate response the call will be back instantly otherwise wait to check if it can get data and then finally comes back as there is no response. – AvkashChauhan Jun 07 '12 at 01:47
  • "site is not working" it means the URL is not available. so I want to know whether have some solutions to deal with this issue? – Jimmy Jun 07 '12 at 08:06
1

On ec2 Ubuntu instances, the file /sys/hypervisor/uuid exists and its first three characters are 'ec2'. I like using this because it doesn't rely on external servers.

nmgeek
  • 2,127
  • 1
  • 23
  • 31