Skip to content

Commit d7c8704

Browse files
author
Dan Gidman
committed
SF-4342 EC2 instances are incorrectly identifying the Device Name.
1 parent c78b355 commit d7c8704

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

Src/StackifyLib/Models/EnvironmentDetail.cs

Lines changed: 38 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,39 @@ 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+
var encoding = Encoding.GetEncoding(response.CharacterSet);
117+
using (var responseStream = response.GetResponseStream())
118+
{
119+
using (var reader = new StreamReader(responseStream, encoding))
120+
{
121+
var id = reader.ReadToEnd();
122+
return string.IsNullOrWhiteSpace(id) ? null : id;
123+
}
124+
}
125+
}
126+
}
127+
catch // if not in aws this will timeout
128+
{
129+
return null;
130+
}
131+
132+
}
133+
97134
/// <summary>
98135
/// Get the display name of the windows service if it is a windows service
99136
/// </summary>
@@ -226,7 +263,7 @@ public EnvironmentDetail(bool loadDetails)
226263
IsWindowService();
227264
}
228265

229-
DeviceName = Environment.MachineName;
266+
DeviceName = GetEC2InstanceId() ?? Environment.MachineName;
230267

231268
if (string.IsNullOrEmpty(AppName) && !isWebRequest)
232269
{

0 commit comments

Comments
 (0)