-
Notifications
You must be signed in to change notification settings - Fork 494
/
VmMetadataApiHandler.cs
164 lines (137 loc) · 5.95 KB
/
VmMetadataApiHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Telemetry
{
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Cosmos.Telemetry.Models;
using Microsoft.Azure.Documents;
using Newtonsoft.Json.Linq;
using Util;
/// <summary>
/// Task to collect virtual machine metadata information. using instance metedata service API.
/// ref: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=windows
/// Collects only application region and environment information
/// </summary>
internal static class VmMetadataApiHandler
{
internal const string HashedMachineNamePrefix = "hashedMachineName:";
internal const string VmIdPrefix = "vmId:";
internal const string UuidPrefix = "uuid:";
internal static readonly Uri vmMetadataEndpointUrl = new ("http://169.254.169.254/metadata/instance?api-version=2020-06-01");
private static readonly string nonAzureCloud = "NonAzureVM";
private static readonly object lockObject = new object();
private static bool isInitialized = false;
private static AzureVMMetadata azMetadata = null;
internal static void TryInitialize(CosmosHttpClient httpClient)
{
if (VmMetadataApiHandler.isInitialized)
{
return;
}
lock (VmMetadataApiHandler.lockObject)
{
if (VmMetadataApiHandler.isInitialized)
{
return;
}
DefaultTrace.TraceInformation("Initializing VM Metadata API ");
VmMetadataApiHandler.isInitialized = true;
_ = Task.Run(() => MetadataApiCallAsync(httpClient), default);
}
}
private static async Task MetadataApiCallAsync(CosmosHttpClient httpClient)
{
try
{
DefaultTrace.TraceInformation($"Loading VM Metadata");
static ValueTask<HttpRequestMessage> CreateRequestMessage()
{
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = VmMetadataApiHandler.vmMetadataEndpointUrl,
Method = HttpMethod.Get,
};
request.Headers.Add("Metadata", "true");
return new ValueTask<HttpRequestMessage>(request);
}
HttpResponseMessage response = await httpClient
.SendHttpAsync(createRequestMessageAsync: CreateRequestMessage,
resourceType: ResourceType.Telemetry,
timeoutPolicy: HttpTimeoutPolicyNoRetry.Instance,
clientSideRequestStatistics: null,
cancellationToken: default);
azMetadata = await VmMetadataApiHandler.ProcessResponseAsync(response);
DefaultTrace.TraceInformation($"Succesfully get Instance Metadata Response : {0}", azMetadata.Compute.VMId);
}
catch (Exception e)
{
DefaultTrace.TraceInformation($"Azure Environment metadata information not available. {0}", e.Message);
}
}
internal static async Task<AzureVMMetadata> ProcessResponseAsync(HttpResponseMessage httpResponseMessage)
{
if (httpResponseMessage.Content == null)
{
return null;
}
string jsonVmInfo = await httpResponseMessage.Content.ReadAsStringAsync();
return JObject.Parse(jsonVmInfo).ToObject<AzureVMMetadata>();
}
/// <summary>
/// Get VM Id if it is Azure System
/// else Get Hashed MachineName
/// else Generate an unique id for this machine/process
/// </summary>
/// <returns>machine id</returns>
internal static string GetMachineId()
{
if (!String.IsNullOrWhiteSpace(VmMetadataApiHandler.azMetadata?.Compute?.VMId))
{
return VmMetadataApiHandler.azMetadata.Compute.VMId;
}
return VmMetadataApiHandler.uniqueId.Value;
}
/// <summary>
/// Get Machine Information (If Azure System) else null
/// </summary>
/// <returns>Compute</returns>
internal static Compute GetMachineInfo()
{
return VmMetadataApiHandler.azMetadata?.Compute;
}
/// <summary>
/// Get Machine Region (If Azure System) else null
/// </summary>
/// <returns>VM region</returns>
internal static string GetMachineRegion()
{
return VmMetadataApiHandler.azMetadata?.Compute?.Location;
}
/// <summary>
/// Get Machine Region (If Azure System) else null
/// </summary>
/// <returns>VM region</returns>
internal static string GetCloudInformation()
{
return VmMetadataApiHandler.azMetadata?.Compute?.AzEnvironment ?? VmMetadataApiHandler.nonAzureCloud;
}
private static readonly Lazy<string> uniqueId = new Lazy<string>(() =>
{
try
{
return $"{VmMetadataApiHandler.HashedMachineNamePrefix}{HashingExtension.ComputeHash(Environment.MachineName)}";
}
catch (Exception ex)
{
DefaultTrace.TraceWarning($"Error while generating hashed machine name {0}", ex.Message);
}
return $"{VmMetadataApiHandler.UuidPrefix}{Guid.NewGuid()}";
});
}
}