|
1 | 1 | using System; |
2 | 2 | using System.Configuration; |
| 3 | +using System.IO; |
3 | 4 | using System.Linq; |
| 5 | +using System.Linq.Expressions; |
4 | 6 | using System.Management; |
| 7 | +using System.Net; |
5 | 8 | using System.Runtime.Serialization; |
| 9 | +using System.Text; |
6 | 10 | using System.Text.RegularExpressions; |
7 | 11 | using System.Web.Hosting; |
8 | 12 | using StackifyLib.Utils; |
@@ -94,6 +98,43 @@ private void GetAzureInfo() |
94 | 98 | } |
95 | 99 | } |
96 | 100 |
|
| 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 | + |
97 | 138 | /// <summary> |
98 | 139 | /// Get the display name of the windows service if it is a windows service |
99 | 140 | /// </summary> |
@@ -226,7 +267,7 @@ public EnvironmentDetail(bool loadDetails) |
226 | 267 | IsWindowService(); |
227 | 268 | } |
228 | 269 |
|
229 | | - DeviceName = Environment.MachineName; |
| 270 | + DeviceName = GetEC2InstanceId() ?? Environment.MachineName; |
230 | 271 |
|
231 | 272 | if (string.IsNullOrEmpty(AppName) && !isWebRequest) |
232 | 273 | { |
|
0 commit comments