Skip to content

Commit a1b59bf

Browse files
committed
Merge pull request #8 from danatcofo/feature/SF-4342
SF-4342 EC2 instances are incorrectly identifying the Device Name.
2 parents e3ab336 + 3c9f480 commit a1b59bf

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

Src/StackifyLib/Models/EnvironmentDetail.cs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
using System;
22
using System.Configuration;
3+
using System.IO;
34
using System.Linq;
5+
using System.Linq.Expressions;
46
using System.Management;
7+
using System.Net;
58
using System.Runtime.Serialization;
9+
using System.Text;
610
using System.Text.RegularExpressions;
711
using System.Web.Hosting;
812
using StackifyLib.Utils;
@@ -94,6 +98,43 @@ private void GetAzureInfo()
9498
}
9599
}
96100

101+
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#d0e30002
102+
const string EC2InstanceIdUrl = "http://169.254.169.254/latest/meta-data/instance-id";
103+
104+
/// <summary>
105+
/// Get the EC2 Instance name if it exists else null
106+
/// </summary>
107+
public static string GetEC2InstanceId()
108+
{
109+
try
110+
{
111+
var request = (HttpWebRequest)WebRequest.Create(EC2InstanceIdUrl);
112+
// wait 5 seconds
113+
request.Timeout = 5000;
114+
using (var response = (HttpWebResponse) request.GetResponse())
115+
{
116+
if ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300)
117+
{
118+
var encoding = Encoding.GetEncoding(response.CharacterSet);
119+
using (var responseStream = response.GetResponseStream())
120+
{
121+
using (var reader = new StreamReader(responseStream, encoding))
122+
{
123+
var id = reader.ReadToEnd();
124+
return string.IsNullOrWhiteSpace(id) ? null : id;
125+
}
126+
}
127+
}
128+
return null;
129+
}
130+
}
131+
catch // if not in aws this will timeout
132+
{
133+
return null;
134+
}
135+
136+
}
137+
97138
/// <summary>
98139
/// Get the display name of the windows service if it is a windows service
99140
/// </summary>
@@ -226,7 +267,7 @@ public EnvironmentDetail(bool loadDetails)
226267
IsWindowService();
227268
}
228269

229-
DeviceName = Environment.MachineName;
270+
DeviceName = GetEC2InstanceId() ?? Environment.MachineName;
230271

231272
if (string.IsNullOrEmpty(AppName) && !isWebRequest)
232273
{

0 commit comments

Comments
 (0)