From db0431943440f18f564c08a6c1a9f577cd0cc5e4 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 07:45:00 +0530 Subject: [PATCH 1/9] add env variable --- .../src/Telemetry/VmMetadataApiHandler.cs | 22 ++++++--- .../VmMetadataApiHandlerTest.cs | 49 ++++++++++++++----- 2 files changed, 50 insertions(+), 21 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index b9d9c60d36..d176d7d4c0 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -34,28 +34,34 @@ internal static class VmMetadataApiHandler private static bool isInitialized = false; private static AzureVMMetadata azMetadata = null; - internal static void TryInitialize(CosmosHttpClient httpClient) { - if (VmMetadataApiHandler.isInitialized) + bool isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); + if (System.Diagnostics.Debugger.IsAttached || isVMMetadataAccessDisabled) { return; } - - lock (VmMetadataApiHandler.lockObject) + else { if (VmMetadataApiHandler.isInitialized) { return; } - DefaultTrace.TraceInformation("Initializing VM Metadata API "); + lock (VmMetadataApiHandler.lockObject) + { + if (VmMetadataApiHandler.isInitialized) + { + return; + } + + DefaultTrace.TraceInformation("Initializing VM Metadata API "); - VmMetadataApiHandler.isInitialized = true; + VmMetadataApiHandler.isInitialized = true; - _ = Task.Run(() => MetadataApiCallAsync(httpClient), default); + _ = Task.Run(() => MetadataApiCallAsync(httpClient), default); + } } - } private static async Task MetadataApiCallAsync(CosmosHttpClient httpClient) diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index 5af170d28a..ab050e7dd3 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -17,7 +17,6 @@ namespace Microsoft.Azure.Cosmos using Microsoft.Azure.Cosmos.Telemetry.Models; using Microsoft.Azure.Cosmos.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; - using Moq; using Newtonsoft.Json; using Util; @@ -25,7 +24,7 @@ namespace Microsoft.Azure.Cosmos public class VmMetadataApiHandlerTest { [TestInitialize] - public void Intialize() + public void Initialize() { var isInitializedField = typeof(VmMetadataApiHandler).GetField("isInitialized", BindingFlags.Static | @@ -39,8 +38,21 @@ public void Intialize() } [TestMethod] - public async Task GetVmIdAsMachineIdTest() + [DataRow(true, false)] + [DataRow(false, false)] + [DataRow(false, true)] + public async Task GetVmIdAsMachineIdTest(bool isVmMetadataAccessDisabled, bool isDebuggerAttached) { + if (isVmMetadataAccessDisabled) + { + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", "true"); + } + + if (isDebuggerAttached) + { + System.Diagnostics.Debugger.Launch(); + } + static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) { object jsonObject = JsonConvert.DeserializeObject("{\"compute\":{\"azEnvironment\":\"AzurePublicCloud\",\"customData\":\"\",\"isHostCompatibilityLayerVm\":\"false\",\"licenseType\":\"\",\"location\":\"eastus\",\"name\":\"sourabh-testing\",\"offer\":\"UbuntuServer\",\"osProfile\":{\"adminUsername\":\"azureuser\",\"computerName\":\"sourabh-testing\"},\"osType\":\"Linux\",\"placementGroupId\":\"\",\"plan\":{\"name\":\"\",\"product\":\"\",\"publisher\":\"\"},\"platformFaultDomain\":\"0\",\"platformUpdateDomain\":\"0\",\"provider\":\"Microsoft.Compute\",\"publicKeys\":[{\"keyData\":\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5uCeOAm3ehmhI+2PbMoMl17Eo\r\nqfHKCycSaBJsv9qxlmBOuFheSJc1XknJleXUSsuTO016/d1PyWpevnqOZNRksWoa\r\nJvQ23sDTxcK+X2OP3QlCUeX4cMjPXqlL8z1UYzU4Bx3fFvf8fs67G3N72sxWBw5P\r\nZyuXyhBm0NCe/2NYMKgEDT4ma8XszO0ikbhoPKbMbgHAQk/ktWQHNcqYOPQKEWqp\r\nEK1R0rjS2nmtovfScP/ZGXcvOpJ1/NDBo4dh1K+OxOGM/4PSH/F448J5Zy4eAyEk\r\nscys+IpeIOTOlRUy/703SNIX0LEWlnYqbyL9c1ypcYLQqF76fKkDfzzFI/OWVlGw\r\nhj/S9uP8iMsR+fhGIbn6MAa7O4DWPWLuedSp7KDYyjY09gqNJsfuaAJN4LiC6bPy\r\nhknm0PVLK3ux7EUOt+cZrHCdIFWbdOtxiPNIl1tkv9kV5aE5Aj2gJm4MeB9uXYhS\r\nOuksboBc0wyUGrl9+XZJ1+NlZOf7IjVi86CieK8= generated-by-azure\r\n\",\"path\":\"/home/azureuser/.ssh/authorized_keys\"}],\"publisher\":\"Canonical\",\"resourceGroupName\":\"sourabh-telemetry-sdk\",\"resourceId\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/virtualMachines/sourabh-testing\",\"securityProfile\":{\"secureBootEnabled\":\"false\",\"virtualTpmEnabled\":\"false\"},\"sku\":\"18.04-LTS\",\"storageProfile\":{\"dataDisks\":[],\"imageReference\":{\"id\":\"\",\"offer\":\"UbuntuServer\",\"publisher\":\"Canonical\",\"sku\":\"18.04-LTS\",\"version\":\"latest\"},\"osDisk\":{\"caching\":\"ReadWrite\",\"createOption\":\"FromImage\",\"diffDiskSettings\":{\"option\":\"\"},\"diskSizeGB\":\"30\",\"encryptionSettings\":{\"enabled\":\"false\"},\"image\":{\"uri\":\"\"},\"managedDisk\":{\"id\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/disks/sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"storageAccountType\":\"Premium_LRS\"},\"name\":\"sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"osType\":\"Linux\",\"vhd\":{\"uri\":\"\"},\"writeAcceleratorEnabled\":\"false\"}},\"subscriptionId\":\"8fba6d4f-7c37-4d13-9063-fd58ad2b86e2\",\"tags\":\"azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true\",\"tagsList\":[{\"name\":\"azsecpack\",\"value\":\"nonprod\"},{\"name\":\"platformsettings.host_environment.service.platform_optedin_for_rootcerts\",\"value\":\"true\"}],\"version\":\"18.04.202103250\",\"vmId\":\"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd\",\"vmScaleSetName\":\"\",\"vmSize\":\"Standard_D2s_v3\",\"zone\":\"1\"},\"network\":{\"interface\":[{\"ipv4\":{\"ipAddress\":[{\"privateIpAddress\":\"10.0.7.5\",\"publicIpAddress\":\"\"}],\"subnet\":[{\"address\":\"10.0.7.0\",\"prefix\":\"24\"}]},\"ipv6\":{\"ipAddress\":[]},\"macAddress\":\"000D3A8F8BA0\"}]}}"); @@ -53,13 +65,24 @@ static Task sendFunc(HttpRequestMessage request, Cancellati } HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); - CosmosHttpClient cosmoshttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); + CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); - VmMetadataApiHandler.TryInitialize(cosmoshttpClient); + VmMetadataApiHandler.TryInitialize(cosmosHttpClient); await Task.Delay(2000); - Assert.AreEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); - Assert.AreEqual(VmMetadataApiHandler.GetMachineRegion(), "eastus"); + + if (isVmMetadataAccessDisabled || isDebuggerAttached) + { + Assert.AreNotEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); + Assert.IsNull(VmMetadataApiHandler.GetMachineRegion(), VmMetadataApiHandler.GetMachineRegion()); + + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", "false"); + } + else + { + Assert.AreEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); + Assert.AreEqual(VmMetadataApiHandler.GetMachineRegion(), "eastus"); + } } [TestMethod] @@ -77,9 +100,9 @@ static Task sendFunc(HttpRequestMessage request, Cancellati } HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); - CosmosHttpClient cosmoshttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); + CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); - VmMetadataApiHandler.TryInitialize(cosmoshttpClient); + VmMetadataApiHandler.TryInitialize(cosmosHttpClient); await Task.Delay(2000); Assert.IsNull(VmMetadataApiHandler.GetMachineInfo()); @@ -95,9 +118,9 @@ public async Task GetHashedMachineNameAsMachineIdTest() static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) { throw new Exception("error while making API call"); }; HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); - CosmosHttpClient cosmoshttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); + CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); - VmMetadataApiHandler.TryInitialize(cosmoshttpClient); + VmMetadataApiHandler.TryInitialize(cosmosHttpClient); await Task.Delay(2000); Assert.AreEqual(expectedMachineId, VmMetadataApiHandler.GetMachineId()); @@ -139,7 +162,7 @@ public void CatchMetadataApiCallExceptionTest() static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) { throw new Exception("error while making API call"); }; HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); - CosmosHttpClient cosmoshttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); + CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); string expectedMsg = "Azure Environment metadata information not available."; ManualResetEvent manualResetEvent = new ManualResetEvent(false); @@ -155,7 +178,7 @@ void TraceHandler(string message) DefaultTrace.TraceSource.Listeners.Add(new TestTraceListener { Callback = TraceHandler }); DefaultTrace.InitEventListener(); - VmMetadataApiHandler.TryInitialize(cosmoshttpClient); + VmMetadataApiHandler.TryInitialize(cosmosHttpClient); int timeout = 30000; Assert.IsTrue(manualResetEvent.WaitOne(timeout)); From 96ff6aca228bc9c736a7535a24707842006bd072 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 15:15:04 +0530 Subject: [PATCH 2/9] fixed tests --- .../src/Telemetry/VmMetadataApiHandler.cs | 11 +++++++- .../VmMetadataApiHandlerTest.cs | 25 ++++++++----------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index d176d7d4c0..49ba8d317d 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -36,7 +36,16 @@ internal static class VmMetadataApiHandler private static AzureVMMetadata azMetadata = null; internal static void TryInitialize(CosmosHttpClient httpClient) { - bool isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); + bool isVMMetadataAccessDisabled = false; // Default value + try + { + isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); + } + catch (Exception ex) + { + DefaultTrace.TraceWarning($"Error while reading environment variable COSMOS_DISABLE_VM_METADATA_ACCESS {0}", ex.Message); + } + if (System.Diagnostics.Debugger.IsAttached || isVMMetadataAccessDisabled) { return; diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index ab050e7dd3..010e5b0682 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -38,21 +38,14 @@ public void Initialize() } [TestMethod] - [DataRow(true, false)] - [DataRow(false, false)] - [DataRow(false, true)] - public async Task GetVmIdAsMachineIdTest(bool isVmMetadataAccessDisabled, bool isDebuggerAttached) + [DataRow("true", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as true, VM ID should not be fetched")] + [DataRow("false", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as false, VM ID should be fetched")] + [DataRow(null, DisplayName = "When nothing is set, VM ID should be fetched ")] + [DataRow("invalid value", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as an 'invalid value', VM ID should be fetched")] + public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { - if (isVmMetadataAccessDisabled) - { - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", "true"); - } + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); - if (isDebuggerAttached) - { - System.Diagnostics.Debugger.Launch(); - } - static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) { object jsonObject = JsonConvert.DeserializeObject("{\"compute\":{\"azEnvironment\":\"AzurePublicCloud\",\"customData\":\"\",\"isHostCompatibilityLayerVm\":\"false\",\"licenseType\":\"\",\"location\":\"eastus\",\"name\":\"sourabh-testing\",\"offer\":\"UbuntuServer\",\"osProfile\":{\"adminUsername\":\"azureuser\",\"computerName\":\"sourabh-testing\"},\"osType\":\"Linux\",\"placementGroupId\":\"\",\"plan\":{\"name\":\"\",\"product\":\"\",\"publisher\":\"\"},\"platformFaultDomain\":\"0\",\"platformUpdateDomain\":\"0\",\"provider\":\"Microsoft.Compute\",\"publicKeys\":[{\"keyData\":\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5uCeOAm3ehmhI+2PbMoMl17Eo\r\nqfHKCycSaBJsv9qxlmBOuFheSJc1XknJleXUSsuTO016/d1PyWpevnqOZNRksWoa\r\nJvQ23sDTxcK+X2OP3QlCUeX4cMjPXqlL8z1UYzU4Bx3fFvf8fs67G3N72sxWBw5P\r\nZyuXyhBm0NCe/2NYMKgEDT4ma8XszO0ikbhoPKbMbgHAQk/ktWQHNcqYOPQKEWqp\r\nEK1R0rjS2nmtovfScP/ZGXcvOpJ1/NDBo4dh1K+OxOGM/4PSH/F448J5Zy4eAyEk\r\nscys+IpeIOTOlRUy/703SNIX0LEWlnYqbyL9c1ypcYLQqF76fKkDfzzFI/OWVlGw\r\nhj/S9uP8iMsR+fhGIbn6MAa7O4DWPWLuedSp7KDYyjY09gqNJsfuaAJN4LiC6bPy\r\nhknm0PVLK3ux7EUOt+cZrHCdIFWbdOtxiPNIl1tkv9kV5aE5Aj2gJm4MeB9uXYhS\r\nOuksboBc0wyUGrl9+XZJ1+NlZOf7IjVi86CieK8= generated-by-azure\r\n\",\"path\":\"/home/azureuser/.ssh/authorized_keys\"}],\"publisher\":\"Canonical\",\"resourceGroupName\":\"sourabh-telemetry-sdk\",\"resourceId\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/virtualMachines/sourabh-testing\",\"securityProfile\":{\"secureBootEnabled\":\"false\",\"virtualTpmEnabled\":\"false\"},\"sku\":\"18.04-LTS\",\"storageProfile\":{\"dataDisks\":[],\"imageReference\":{\"id\":\"\",\"offer\":\"UbuntuServer\",\"publisher\":\"Canonical\",\"sku\":\"18.04-LTS\",\"version\":\"latest\"},\"osDisk\":{\"caching\":\"ReadWrite\",\"createOption\":\"FromImage\",\"diffDiskSettings\":{\"option\":\"\"},\"diskSizeGB\":\"30\",\"encryptionSettings\":{\"enabled\":\"false\"},\"image\":{\"uri\":\"\"},\"managedDisk\":{\"id\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/disks/sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"storageAccountType\":\"Premium_LRS\"},\"name\":\"sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"osType\":\"Linux\",\"vhd\":{\"uri\":\"\"},\"writeAcceleratorEnabled\":\"false\"}},\"subscriptionId\":\"8fba6d4f-7c37-4d13-9063-fd58ad2b86e2\",\"tags\":\"azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true\",\"tagsList\":[{\"name\":\"azsecpack\",\"value\":\"nonprod\"},{\"name\":\"platformsettings.host_environment.service.platform_optedin_for_rootcerts\",\"value\":\"true\"}],\"version\":\"18.04.202103250\",\"vmId\":\"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd\",\"vmScaleSetName\":\"\",\"vmSize\":\"Standard_D2s_v3\",\"zone\":\"1\"},\"network\":{\"interface\":[{\"ipv4\":{\"ipAddress\":[{\"privateIpAddress\":\"10.0.7.5\",\"publicIpAddress\":\"\"}],\"subnet\":[{\"address\":\"10.0.7.0\",\"prefix\":\"24\"}]},\"ipv6\":{\"ipAddress\":[]},\"macAddress\":\"000D3A8F8BA0\"}]}}"); @@ -71,7 +64,9 @@ static Task sendFunc(HttpRequestMessage request, Cancellati await Task.Delay(2000); - if (isVmMetadataAccessDisabled || isDebuggerAttached) + if (isVmMetadataAccessDisabled != null && + Boolean.TryParse(isVmMetadataAccessDisabled, out bool isVmMetadataAccessDisabledBool) && + isVmMetadataAccessDisabledBool) { Assert.AreNotEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); Assert.IsNull(VmMetadataApiHandler.GetMachineRegion(), VmMetadataApiHandler.GetMachineRegion()); @@ -83,6 +78,8 @@ static Task sendFunc(HttpRequestMessage request, Cancellati Assert.AreEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); Assert.AreEqual(VmMetadataApiHandler.GetMachineRegion(), "eastus"); } + + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", null); } [TestMethod] From 4e6055bfb0999105128a70575460d52cbdb2f2b9 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 17:03:13 +0530 Subject: [PATCH 3/9] removed try-catch --- .../src/Telemetry/VmMetadataApiHandler.cs | 11 +---------- .../VmMetadataApiHandlerTest.cs | 1 - 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index 49ba8d317d..18c9bc79e4 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -36,16 +36,7 @@ internal static class VmMetadataApiHandler private static AzureVMMetadata azMetadata = null; internal static void TryInitialize(CosmosHttpClient httpClient) { - bool isVMMetadataAccessDisabled = false; // Default value - try - { - isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); - } - catch (Exception ex) - { - DefaultTrace.TraceWarning($"Error while reading environment variable COSMOS_DISABLE_VM_METADATA_ACCESS {0}", ex.Message); - } - + bool isVMMetadataAccessDisabled = isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); if (System.Diagnostics.Debugger.IsAttached || isVMMetadataAccessDisabled) { return; diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index 010e5b0682..60b4142578 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -41,7 +41,6 @@ public void Initialize() [DataRow("true", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as true, VM ID should not be fetched")] [DataRow("false", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as false, VM ID should be fetched")] [DataRow(null, DisplayName = "When nothing is set, VM ID should be fetched ")] - [DataRow("invalid value", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as an 'invalid value', VM ID should be fetched")] public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); From 1d046186bed3b59152d615411b8e67ee90974f7d Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 17:50:59 +0530 Subject: [PATCH 4/9] add doc --- .../src/Telemetry/VmMetadataApiHandler.cs | 15 +++++++++++++-- .../VmMetadataApiHandlerTest.cs | 1 - 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index 18c9bc79e4..e18934578d 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -34,10 +34,21 @@ internal static class VmMetadataApiHandler private static bool isInitialized = false; private static AzureVMMetadata azMetadata = null; + + /// + /// Check for environment variable COSMOS_DISABLE_VM_METADATA_ACCESS to decide if VM metadata call should be made or not. + /// If environment variable is set to true, then VM metadata call will not be made. + /// If environment variable is set to false, then VM metadata call will be made. + /// If environment variable is not set, then set the value according to the debugger which means + /// In Debug mode, it is will be true and VM metadata call will be disabled. + /// In Release mode, it is will be false and VM metadata call will be enabled. + /// . + /// internal static void TryInitialize(CosmosHttpClient httpClient) { - bool isVMMetadataAccessDisabled = isVMMetadataAccessDisabled = ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); - if (System.Diagnostics.Debugger.IsAttached || isVMMetadataAccessDisabled) + bool isVMMetadataAccessDisabled = + ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", System.Diagnostics.Debugger.IsAttached); + if (isVMMetadataAccessDisabled) { return; } diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index 60b4142578..f3cba1309b 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -40,7 +40,6 @@ public void Initialize() [TestMethod] [DataRow("true", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as true, VM ID should not be fetched")] [DataRow("false", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as false, VM ID should be fetched")] - [DataRow(null, DisplayName = "When nothing is set, VM ID should be fetched ")] public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); From 10d3911c00b1808b84da51933434c6beab500b02 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 21:29:31 +0530 Subject: [PATCH 5/9] remove else --- .../src/Telemetry/VmMetadataApiHandler.cs | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index e18934578d..7a6c5e224e 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -52,26 +52,24 @@ internal static void TryInitialize(CosmosHttpClient httpClient) { return; } - else + + if (VmMetadataApiHandler.isInitialized) + { + return; + } + + lock (VmMetadataApiHandler.lockObject) { if (VmMetadataApiHandler.isInitialized) { return; } - lock (VmMetadataApiHandler.lockObject) - { - if (VmMetadataApiHandler.isInitialized) - { - return; - } + DefaultTrace.TraceInformation("Initializing VM Metadata API "); - DefaultTrace.TraceInformation("Initializing VM Metadata API "); + VmMetadataApiHandler.isInitialized = true; - VmMetadataApiHandler.isInitialized = true; - - _ = Task.Run(() => MetadataApiCallAsync(httpClient), default); - } + _ = Task.Run(() => MetadataApiCallAsync(httpClient), default); } } From 95f2b405d45d98963bcc420213ee28157bcd6fe9 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Wed, 3 Jul 2024 21:57:56 +0530 Subject: [PATCH 6/9] put try-catch around test --- .../VmMetadataApiHandlerTest.cs | 52 ++++++++++--------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index f3cba1309b..9ff7dc2472 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -44,40 +44,44 @@ public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); - static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) + try { - object jsonObject = JsonConvert.DeserializeObject("{\"compute\":{\"azEnvironment\":\"AzurePublicCloud\",\"customData\":\"\",\"isHostCompatibilityLayerVm\":\"false\",\"licenseType\":\"\",\"location\":\"eastus\",\"name\":\"sourabh-testing\",\"offer\":\"UbuntuServer\",\"osProfile\":{\"adminUsername\":\"azureuser\",\"computerName\":\"sourabh-testing\"},\"osType\":\"Linux\",\"placementGroupId\":\"\",\"plan\":{\"name\":\"\",\"product\":\"\",\"publisher\":\"\"},\"platformFaultDomain\":\"0\",\"platformUpdateDomain\":\"0\",\"provider\":\"Microsoft.Compute\",\"publicKeys\":[{\"keyData\":\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5uCeOAm3ehmhI+2PbMoMl17Eo\r\nqfHKCycSaBJsv9qxlmBOuFheSJc1XknJleXUSsuTO016/d1PyWpevnqOZNRksWoa\r\nJvQ23sDTxcK+X2OP3QlCUeX4cMjPXqlL8z1UYzU4Bx3fFvf8fs67G3N72sxWBw5P\r\nZyuXyhBm0NCe/2NYMKgEDT4ma8XszO0ikbhoPKbMbgHAQk/ktWQHNcqYOPQKEWqp\r\nEK1R0rjS2nmtovfScP/ZGXcvOpJ1/NDBo4dh1K+OxOGM/4PSH/F448J5Zy4eAyEk\r\nscys+IpeIOTOlRUy/703SNIX0LEWlnYqbyL9c1ypcYLQqF76fKkDfzzFI/OWVlGw\r\nhj/S9uP8iMsR+fhGIbn6MAa7O4DWPWLuedSp7KDYyjY09gqNJsfuaAJN4LiC6bPy\r\nhknm0PVLK3ux7EUOt+cZrHCdIFWbdOtxiPNIl1tkv9kV5aE5Aj2gJm4MeB9uXYhS\r\nOuksboBc0wyUGrl9+XZJ1+NlZOf7IjVi86CieK8= generated-by-azure\r\n\",\"path\":\"/home/azureuser/.ssh/authorized_keys\"}],\"publisher\":\"Canonical\",\"resourceGroupName\":\"sourabh-telemetry-sdk\",\"resourceId\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/virtualMachines/sourabh-testing\",\"securityProfile\":{\"secureBootEnabled\":\"false\",\"virtualTpmEnabled\":\"false\"},\"sku\":\"18.04-LTS\",\"storageProfile\":{\"dataDisks\":[],\"imageReference\":{\"id\":\"\",\"offer\":\"UbuntuServer\",\"publisher\":\"Canonical\",\"sku\":\"18.04-LTS\",\"version\":\"latest\"},\"osDisk\":{\"caching\":\"ReadWrite\",\"createOption\":\"FromImage\",\"diffDiskSettings\":{\"option\":\"\"},\"diskSizeGB\":\"30\",\"encryptionSettings\":{\"enabled\":\"false\"},\"image\":{\"uri\":\"\"},\"managedDisk\":{\"id\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/disks/sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"storageAccountType\":\"Premium_LRS\"},\"name\":\"sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"osType\":\"Linux\",\"vhd\":{\"uri\":\"\"},\"writeAcceleratorEnabled\":\"false\"}},\"subscriptionId\":\"8fba6d4f-7c37-4d13-9063-fd58ad2b86e2\",\"tags\":\"azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true\",\"tagsList\":[{\"name\":\"azsecpack\",\"value\":\"nonprod\"},{\"name\":\"platformsettings.host_environment.service.platform_optedin_for_rootcerts\",\"value\":\"true\"}],\"version\":\"18.04.202103250\",\"vmId\":\"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd\",\"vmScaleSetName\":\"\",\"vmSize\":\"Standard_D2s_v3\",\"zone\":\"1\"},\"network\":{\"interface\":[{\"ipv4\":{\"ipAddress\":[{\"privateIpAddress\":\"10.0.7.5\",\"publicIpAddress\":\"\"}],\"subnet\":[{\"address\":\"10.0.7.0\",\"prefix\":\"24\"}]},\"ipv6\":{\"ipAddress\":[]},\"macAddress\":\"000D3A8F8BA0\"}]}}"); - string payload = JsonConvert.SerializeObject(jsonObject); - HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) + static Task sendFunc(HttpRequestMessage request, CancellationToken cancellationToken) { - Content = new StringContent(payload, Encoding.UTF8, "application/json") - }; - return Task.FromResult(response); - } + object jsonObject = JsonConvert.DeserializeObject("{\"compute\":{\"azEnvironment\":\"AzurePublicCloud\",\"customData\":\"\",\"isHostCompatibilityLayerVm\":\"false\",\"licenseType\":\"\",\"location\":\"eastus\",\"name\":\"sourabh-testing\",\"offer\":\"UbuntuServer\",\"osProfile\":{\"adminUsername\":\"azureuser\",\"computerName\":\"sourabh-testing\"},\"osType\":\"Linux\",\"placementGroupId\":\"\",\"plan\":{\"name\":\"\",\"product\":\"\",\"publisher\":\"\"},\"platformFaultDomain\":\"0\",\"platformUpdateDomain\":\"0\",\"provider\":\"Microsoft.Compute\",\"publicKeys\":[{\"keyData\":\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5uCeOAm3ehmhI+2PbMoMl17Eo\r\nqfHKCycSaBJsv9qxlmBOuFheSJc1XknJleXUSsuTO016/d1PyWpevnqOZNRksWoa\r\nJvQ23sDTxcK+X2OP3QlCUeX4cMjPXqlL8z1UYzU4Bx3fFvf8fs67G3N72sxWBw5P\r\nZyuXyhBm0NCe/2NYMKgEDT4ma8XszO0ikbhoPKbMbgHAQk/ktWQHNcqYOPQKEWqp\r\nEK1R0rjS2nmtovfScP/ZGXcvOpJ1/NDBo4dh1K+OxOGM/4PSH/F448J5Zy4eAyEk\r\nscys+IpeIOTOlRUy/703SNIX0LEWlnYqbyL9c1ypcYLQqF76fKkDfzzFI/OWVlGw\r\nhj/S9uP8iMsR+fhGIbn6MAa7O4DWPWLuedSp7KDYyjY09gqNJsfuaAJN4LiC6bPy\r\nhknm0PVLK3ux7EUOt+cZrHCdIFWbdOtxiPNIl1tkv9kV5aE5Aj2gJm4MeB9uXYhS\r\nOuksboBc0wyUGrl9+XZJ1+NlZOf7IjVi86CieK8= generated-by-azure\r\n\",\"path\":\"/home/azureuser/.ssh/authorized_keys\"}],\"publisher\":\"Canonical\",\"resourceGroupName\":\"sourabh-telemetry-sdk\",\"resourceId\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/virtualMachines/sourabh-testing\",\"securityProfile\":{\"secureBootEnabled\":\"false\",\"virtualTpmEnabled\":\"false\"},\"sku\":\"18.04-LTS\",\"storageProfile\":{\"dataDisks\":[],\"imageReference\":{\"id\":\"\",\"offer\":\"UbuntuServer\",\"publisher\":\"Canonical\",\"sku\":\"18.04-LTS\",\"version\":\"latest\"},\"osDisk\":{\"caching\":\"ReadWrite\",\"createOption\":\"FromImage\",\"diffDiskSettings\":{\"option\":\"\"},\"diskSizeGB\":\"30\",\"encryptionSettings\":{\"enabled\":\"false\"},\"image\":{\"uri\":\"\"},\"managedDisk\":{\"id\":\"/subscriptions/8fba6d4f-7c37-4d13-9063-fd58ad2b86e2/resourceGroups/sourabh-telemetry-sdk/providers/Microsoft.Compute/disks/sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"storageAccountType\":\"Premium_LRS\"},\"name\":\"sourabh-testing_OsDisk_1_9a54abfc5ba149c6a106bd9e5b558c2a\",\"osType\":\"Linux\",\"vhd\":{\"uri\":\"\"},\"writeAcceleratorEnabled\":\"false\"}},\"subscriptionId\":\"8fba6d4f-7c37-4d13-9063-fd58ad2b86e2\",\"tags\":\"azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true\",\"tagsList\":[{\"name\":\"azsecpack\",\"value\":\"nonprod\"},{\"name\":\"platformsettings.host_environment.service.platform_optedin_for_rootcerts\",\"value\":\"true\"}],\"version\":\"18.04.202103250\",\"vmId\":\"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd\",\"vmScaleSetName\":\"\",\"vmSize\":\"Standard_D2s_v3\",\"zone\":\"1\"},\"network\":{\"interface\":[{\"ipv4\":{\"ipAddress\":[{\"privateIpAddress\":\"10.0.7.5\",\"publicIpAddress\":\"\"}],\"subnet\":[{\"address\":\"10.0.7.0\",\"prefix\":\"24\"}]},\"ipv6\":{\"ipAddress\":[]},\"macAddress\":\"000D3A8F8BA0\"}]}}"); + string payload = JsonConvert.SerializeObject(jsonObject); + HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(payload, Encoding.UTF8, "application/json") + }; + return Task.FromResult(response); + } - HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); - CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); + HttpMessageHandler messageHandler = new MockMessageHandler(sendFunc); + CosmosHttpClient cosmosHttpClient = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)); - VmMetadataApiHandler.TryInitialize(cosmosHttpClient); + VmMetadataApiHandler.TryInitialize(cosmosHttpClient); - await Task.Delay(2000); + await Task.Delay(2000); - if (isVmMetadataAccessDisabled != null && - Boolean.TryParse(isVmMetadataAccessDisabled, out bool isVmMetadataAccessDisabledBool) && - isVmMetadataAccessDisabledBool) - { - Assert.AreNotEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); - Assert.IsNull(VmMetadataApiHandler.GetMachineRegion(), VmMetadataApiHandler.GetMachineRegion()); + if (isVmMetadataAccessDisabled != null && + Boolean.TryParse(isVmMetadataAccessDisabled, out bool isVmMetadataAccessDisabledBool) && + isVmMetadataAccessDisabledBool) + { + Assert.AreNotEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); + Assert.IsNull(VmMetadataApiHandler.GetMachineRegion(), VmMetadataApiHandler.GetMachineRegion()); + } + else + { + Assert.AreEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); + Assert.AreEqual(VmMetadataApiHandler.GetMachineRegion(), "eastus"); + } - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", "false"); } - else + finally { - Assert.AreEqual($"{VmMetadataApiHandler.VmIdPrefix}{"d0cb93eb-214b-4c2b-bd3d-cc93e90d9efd"}", VmMetadataApiHandler.GetMachineId()); - Assert.AreEqual(VmMetadataApiHandler.GetMachineRegion(), "eastus"); + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", null); } - - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", null); } [TestMethod] From b9041f69a97ccdfb234e22921cd6d66d41d31533 Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Thu, 4 Jul 2024 07:28:45 +0530 Subject: [PATCH 7/9] remove debugger --- .../src/Telemetry/VmMetadataApiHandler.cs | 6 ++---- .../VmMetadataApiHandlerTest.cs | 6 +++++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index 7a6c5e224e..c88bc1c510 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -39,15 +39,13 @@ internal static class VmMetadataApiHandler /// Check for environment variable COSMOS_DISABLE_VM_METADATA_ACCESS to decide if VM metadata call should be made or not. /// If environment variable is set to true, then VM metadata call will not be made. /// If environment variable is set to false, then VM metadata call will be made. - /// If environment variable is not set, then set the value according to the debugger which means - /// In Debug mode, it is will be true and VM metadata call will be disabled. - /// In Release mode, it is will be false and VM metadata call will be enabled. + /// If environment variable is not set, then VM metadata call will be made. /// . /// internal static void TryInitialize(CosmosHttpClient httpClient) { bool isVMMetadataAccessDisabled = - ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", System.Diagnostics.Debugger.IsAttached); + ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); if (isVMMetadataAccessDisabled) { return; diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index 9ff7dc2472..2145815887 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -40,9 +40,13 @@ public void Initialize() [TestMethod] [DataRow("true", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as true, VM ID should not be fetched")] [DataRow("false", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as false, VM ID should be fetched")] + [DataRow(null, DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is NOT set, VM ID should be fetched")] public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); + if (isVmMetadataAccessDisabled != null) + { + Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); + } try { From 2a22d04781dc1fc411fdccdce34ab5a9d8455e1f Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Mon, 8 Jul 2024 06:02:12 +0530 Subject: [PATCH 8/9] update env variable name and updated known issue section --- .../src/Telemetry/VmMetadataApiHandler.cs | 4 ++-- .../VmMetadataApiHandlerTest.cs | 10 +++++----- changelog.md | 1 + 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs index c88bc1c510..96836a6c64 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/VmMetadataApiHandler.cs @@ -36,7 +36,7 @@ internal static class VmMetadataApiHandler private static AzureVMMetadata azMetadata = null; /// - /// Check for environment variable COSMOS_DISABLE_VM_METADATA_ACCESS to decide if VM metadata call should be made or not. + /// Check for environment variable COSMOS_DISABLE_IMDS_ACCESS to decide if VM metadata call should be made or not. /// If environment variable is set to true, then VM metadata call will not be made. /// If environment variable is set to false, then VM metadata call will be made. /// If environment variable is not set, then VM metadata call will be made. @@ -45,7 +45,7 @@ internal static class VmMetadataApiHandler internal static void TryInitialize(CosmosHttpClient httpClient) { bool isVMMetadataAccessDisabled = - ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", false); + ConfigurationManager.GetEnvironmentVariable("COSMOS_DISABLE_IMDS_ACCESS", false); if (isVMMetadataAccessDisabled) { return; diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs index 2145815887..0c60b627dc 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/VmMetadataApiHandlerTest.cs @@ -38,14 +38,14 @@ public void Initialize() } [TestMethod] - [DataRow("true", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as true, VM ID should not be fetched")] - [DataRow("false", DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is set as false, VM ID should be fetched")] - [DataRow(null, DisplayName = "When COSMOS_DISABLE_VM_METADATA_ACCESS is NOT set, VM ID should be fetched")] + [DataRow("true", DisplayName = "When COSMOS_DISABLE_IMDS_ACCESS is set as true, VM ID should not be fetched")] + [DataRow("false", DisplayName = "When COSMOS_DISABLE_IMDS_ACCESS is set as false, VM ID should be fetched")] + [DataRow(null, DisplayName = "When COSMOS_DISABLE_IMDS_ACCESS is NOT set, VM ID should be fetched")] public async Task GetVmIdAsMachineIdTest(string isVmMetadataAccessDisabled) { if (isVmMetadataAccessDisabled != null) { - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", isVmMetadataAccessDisabled); + Environment.SetEnvironmentVariable("COSMOS_DISABLE_IMDS_ACCESS", isVmMetadataAccessDisabled); } try @@ -84,7 +84,7 @@ static Task sendFunc(HttpRequestMessage request, Cancellati } finally { - Environment.SetEnvironmentVariable("COSMOS_DISABLE_VM_METADATA_ACCESS", null); + Environment.SetEnvironmentVariable("COSMOS_DISABLE_IMDS_ACCESS", null); } } diff --git a/changelog.md b/changelog.md index 658274524d..10a93874a2 100644 --- a/changelog.md +++ b/changelog.md @@ -1393,6 +1393,7 @@ Below is a list of any know issues affecting the [recommended minimum version](# | --- | --- | --- | --- | | `FeedIterator` enters an infinite loop after a physical partition split occurs in a container using hierarchical partition keys. | Queries using prefix partition keys. | Rather than having the PK included in the query request options, filtering on top level hierarchical Pks should be done through where clauses. | [#4326](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4326) | | Single partition queries (queries explicitly targetted to single partition or any queries on collection that had single physical partition) that resume using continuation token after partition split can observe failure on SDK v3.38 and beyond. | Explicit query exeuction using continuation token will fail query execution if these conditions are met. | Turn off Optimistic Direct Execution during query execution either by setting EnableOptimisticDirectExecution to false in query request options or by setting environment variable AZURE_COSMOS_OPTIMISTIC_DIRECT_EXECUTION_ENABLED to false. | [#4432](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4432) | +| An [Azure API](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=linux) call is made to get the VM information. This call fails if cutomer is on non-Azure VM. | Although this call is made only during once during client initialization but this failure would come up into monitoring tool which leads to a confusion.| Turn off this call by setting environment variable COSMOS_DISABLE_IMDS_ACCESS to false. |[#4187](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4187) | ## Release & Retirement dates From c2b81fb42304b2d917557c583d51c4d4b6215c0c Mon Sep 17 00:00:00 2001 From: Sourabh Jain Date: Mon, 8 Jul 2024 06:06:48 +0530 Subject: [PATCH 9/9] updstade doc --- changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index 10a93874a2..bbaaddcc3e 100644 --- a/changelog.md +++ b/changelog.md @@ -1393,7 +1393,7 @@ Below is a list of any know issues affecting the [recommended minimum version](# | --- | --- | --- | --- | | `FeedIterator` enters an infinite loop after a physical partition split occurs in a container using hierarchical partition keys. | Queries using prefix partition keys. | Rather than having the PK included in the query request options, filtering on top level hierarchical Pks should be done through where clauses. | [#4326](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4326) | | Single partition queries (queries explicitly targetted to single partition or any queries on collection that had single physical partition) that resume using continuation token after partition split can observe failure on SDK v3.38 and beyond. | Explicit query exeuction using continuation token will fail query execution if these conditions are met. | Turn off Optimistic Direct Execution during query execution either by setting EnableOptimisticDirectExecution to false in query request options or by setting environment variable AZURE_COSMOS_OPTIMISTIC_DIRECT_EXECUTION_ENABLED to false. | [#4432](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4432) | -| An [Azure API](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=linux) call is made to get the VM information. This call fails if cutomer is on non-Azure VM. | Although this call is made only during once during client initialization but this failure would come up into monitoring tool which leads to a confusion.| Turn off this call by setting environment variable COSMOS_DISABLE_IMDS_ACCESS to false. |[#4187](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4187) | +| An [Azure API](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=linux) call is made to get the VM information. This call fails if cutomer is on non-Azure VM. | Although this call is made only once, during client initialization but this failure would come up into monitoring tool (e.g AppInsights, Datadog etc.) which leads to a confusion for a developer.| Turn off this call by setting environment variable COSMOS_DISABLE_IMDS_ACCESS to true. |[#4187](https://github.com/Azure/azure-cosmos-dotnet-v3/issues/4187) | ## Release & Retirement dates