public void FailToObtainAzureInstanceMetadataFieldsAltogether() { HeartbeatProviderMock hbeatMock = new HeartbeatProviderMock(); AzureInstanceMetadataRequestMock azureInstanceRequestorMock = new AzureInstanceMetadataRequestMock( getComputeMetadata: () => { try { throw new System.Exception("Failure"); } catch { } return(null); }); var azureIMSFields = new AzureComputeMetadataHeartbeatPropertyProvider(azureInstanceRequestorMock); var defaultFields = azureIMSFields.ExpectedAzureImsFields; // not adding the fields we're looking for, simulation of the Azure Instance Metadata service not being present... var taskWaiter = azureIMSFields.SetDefaultPayloadAsync(hbeatMock).ConfigureAwait(false); Assert.False(taskWaiter.GetAwaiter().GetResult()); // nop await for tests foreach (string fieldName in defaultFields) { string heartbeatFieldName = string.Concat(AzureComputeMetadataHeartbeatPropertyProvider.HeartbeatPropertyPrefix, fieldName); Assert.False(hbeatMock.HbeatProps.ContainsKey(heartbeatFieldName)); } }
public void GetAzureInstanceMetadataFieldsAsExpected() { HeartbeatProviderMock hbeatMock = new HeartbeatProviderMock(); AzureInstanceMetadataRequestMock azureInstanceRequestorMock = new AzureInstanceMetadataRequestMock(); AzureComputeMetadataHeartbeatPropertyProvider azureIMSFields = new AzureComputeMetadataHeartbeatPropertyProvider(azureInstanceRequestorMock); var taskWaiter = azureIMSFields.SetDefaultPayloadAsync(hbeatMock).ConfigureAwait(false); Assert.True(taskWaiter.GetAwaiter().GetResult()); // no await for tests foreach (string fieldName in azureIMSFields.ExpectedAzureImsFields) { string expectedFieldName = string.Concat(AzureComputeMetadataHeartbeatPropertyProvider.HeartbeatPropertyPrefix, fieldName); Assert.True(hbeatMock.HbeatProps.ContainsKey(expectedFieldName)); Assert.False(string.IsNullOrEmpty(hbeatMock.HbeatProps[expectedFieldName])); } }
public void AzureInstanceMetadataObtainedSuccessfully() { AzureInstanceComputeMetadata expected = new AzureInstanceComputeMetadata() { Location = "US-West", Name = "test-vm01", Offer = "D9_USWest", OsType = "Linux", PlatformFaultDomain = "0", PlatformUpdateDomain = "0", Publisher = "Microsoft", ResourceGroupName = "test.resource-group_01", Sku = "Windows_10", SubscriptionId = Guid.NewGuid().ToString(), Version = "10.8a", VmId = Guid.NewGuid().ToString(), VmSize = "A8" }; HeartbeatProviderMock hbeatMock = new HeartbeatProviderMock(); AzureInstanceMetadataRequestMock azureInstanceRequestorMock = new AzureInstanceMetadataRequestMock( getComputeMetadata: () => { return(expected); }); var azureIMSFields = new AzureComputeMetadataHeartbeatPropertyProvider(azureInstanceRequestorMock); var defaultFields = azureIMSFields.ExpectedAzureImsFields; // not adding the fields we're looking for, simulation of the Azure Instance Metadata service not being present... var taskWaiter = azureIMSFields.SetDefaultPayloadAsync(hbeatMock).ConfigureAwait(false); Assert.True(taskWaiter.GetAwaiter().GetResult()); // nop await for tests foreach (string fieldName in defaultFields) { string heartbeatFieldName = string.Concat(AzureComputeMetadataHeartbeatPropertyProvider.HeartbeatPropertyPrefix, fieldName); Assert.True(hbeatMock.HbeatProps.ContainsKey(heartbeatFieldName)); Assert.Equal(expected.GetValueForField(fieldName), hbeatMock.HbeatProps[heartbeatFieldName]); } }
public void AzureImsResponseExcludesMalformedValues() { string testPath = "malformedValues"; using (new AzureInstanceMetadataServiceMock( AzureInstanceMetadataEndToEndTests.MockTestUri, testPath, (response) => { response.StatusCode = (int)HttpStatusCode.OK; // make it a malicious-ish response... var malformedData = this.GetTestMetadata(); malformedData.Name = "Not allowed for VM names"; malformedData.ResourceGroupName = "Not allowed for resource group name"; malformedData.SubscriptionId = "Definitely-not-a GUID up here"; var malformedJsonStream = this.GetTestMetadataStream(malformedData); response.SetContentLength(malformedJsonStream.Length); response.ContentType = "application/json"; response.SetContentEncoding(Encoding.UTF8); response.WriteStreamToBody(malformedJsonStream); })) { var azureIms = new AzureMetadataRequestor { BaseAimsUri = string.Concat(AzureInstanceMetadataEndToEndTests.MockTestUri, testPath, "/") }; var azureImsProps = new AzureComputeMetadataHeartbeatPropertyProvider(azureIms); var hbeatProvider = new HeartbeatProviderMock(); var azureIMSData = azureImsProps.SetDefaultPayloadAsync(hbeatProvider); azureIMSData.Wait(); Assert.Empty(hbeatProvider.HbeatProps["azInst_name"]); Assert.Empty(hbeatProvider.HbeatProps["azInst_resourceGroupName"]); Assert.Empty(hbeatProvider.HbeatProps["azInst_subscriptionId"]); } }
/// <summary> /// Initializes a new instance of the <see cref="AzureInstanceMetadataTelemetryModule" /> class. /// Creates a heartbeat property collector that obtains and inserts data from the Azure Instance /// Metadata service if it is present and available to the currently running process. If it is not /// present no added IMS data is added to the heartbeat. /// </summary> /// <param name="unused">Unused parameter for this TelemetryModule.</param> public void Initialize(TelemetryConfiguration unused) { // Core SDK creates 1 instance of a module but calls Initialize multiple times if (!this.isInitialized) { lock (this.lockObject) { if (!this.isInitialized) { var telemetryModules = TelemetryModules.Instance; foreach (var module in telemetryModules.Modules) { if (module is IHeartbeatPropertyManager hbeatManager) { // start off the heartbeat property collection process, but don't wait for it nor report // any status from here, fire and forget. The thread running the collection will report // to the core event log. try { var heartbeatProperties = new AzureComputeMetadataHeartbeatPropertyProvider(); Task.Factory.StartNew( async() => await heartbeatProperties.SetDefaultPayloadAsync(hbeatManager) .ConfigureAwait(false)); } catch (Exception heartbeatAquisitionException) { WindowsServerEventSource.Log.AzureInstanceMetadataFailureWithException(heartbeatAquisitionException.Message, heartbeatAquisitionException.InnerException?.Message); } } } this.isInitialized = true; } } } }
public void SpoofedResponseFromAzureIMSDoesntCrash() { var testMetadata = this.GetTestMetadata(); string testPath = "spoofedResponse"; using (new AzureInstanceMetadataServiceMock( AzureInstanceMetadataEndToEndTests.MockTestUri, testPath, (response) => { response.StatusCode = (int)HttpStatusCode.OK; var jsonStream = this.GetTestMetadataStream(testMetadata); response.SetContentLength(jsonStream.Length); response.ContentType = "application/json"; response.SetContentEncoding(Encoding.UTF8); response.WriteStreamToBody(jsonStream); })) { var azureIms = new AzureMetadataRequestor { BaseAimsUri = string.Concat(AzureInstanceMetadataEndToEndTests.MockTestUri, testPath, "/") }; var azureImsProps = new AzureComputeMetadataHeartbeatPropertyProvider(); var azureIMSData = azureIms.GetAzureComputeMetadataAsync(); azureIMSData.Wait(); foreach (string fieldName in azureImsProps.ExpectedAzureImsFields) { string fieldValue = azureIMSData.Result.GetValueForField(fieldName); Assert.NotNull(fieldValue); Assert.Equal(fieldValue, testMetadata.GetValueForField(fieldName)); } } }
public void AzureIMSReturnsExpectedValuesForEachFieldAfterSerialization() { AzureInstanceComputeMetadata expectMetadata = new AzureInstanceComputeMetadata() { Location = "US-West", Name = "test-vm01", Offer = "D9_USWest", OsType = "Linux", PlacementGroupId = "placement-grp", PlatformFaultDomain = "0", PlatformUpdateDomain = "0", Publisher = "Microsoft", ResourceGroupName = "test.resource-group_01", Sku = "Windows_10", SubscriptionId = Guid.NewGuid().ToString(), Tags = "thisTag;thatTag", Version = "10.8a", VmId = Guid.NewGuid().ToString(), VmSize = "A8" }; DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(AzureInstanceComputeMetadata)); // use the expected JSON field name style, uses camelCase... string jsonFormatString = @"{{ ""osType"": ""{0}"", ""location"": ""{1}"", ""name"": ""{2}"", ""offer"": ""{3}"", ""placementGroupId"": ""{4}"", ""platformFaultDomain"": ""{5}"", ""platformUpdateDomain"": ""{6}"", ""publisher"": ""{7}"", ""sku"": ""{8}"", ""version"": ""{9}"", ""vmId"": ""{10}"", ""vmSize"": ""{11}"", ""subscriptionId"": ""{12}"", ""tags"": ""{13}"", ""resourceGroupName"": ""{14}"" }}"; string json = string.Format( System.Globalization.CultureInfo.InvariantCulture, jsonFormatString, expectMetadata.OsType, expectMetadata.Location, expectMetadata.Name, expectMetadata.Offer, expectMetadata.PlacementGroupId, expectMetadata.PlatformFaultDomain, expectMetadata.PlatformUpdateDomain, expectMetadata.Publisher, expectMetadata.Sku, expectMetadata.Version, expectMetadata.VmId, expectMetadata.VmSize, expectMetadata.SubscriptionId, expectMetadata.Tags, expectMetadata.ResourceGroupName); var jsonBytes = Encoding.UTF8.GetBytes(json); MemoryStream jsonStream = new MemoryStream(jsonBytes, 0, jsonBytes.Length); AzureInstanceComputeMetadata compareMetadata = (AzureInstanceComputeMetadata)deserializer.ReadObject(jsonStream); AzureComputeMetadataHeartbeatPropertyProvider heartbeatProps = new AzureComputeMetadataHeartbeatPropertyProvider(); foreach (string fieldName in heartbeatProps.ExpectedAzureImsFields) { Assert.Equal(expectMetadata.GetValueForField(fieldName), compareMetadata.GetValueForField(fieldName)); } }