Fix azure vm resource detector tests/Suppress instrumentation for urllib call (#2178)

This commit is contained in:
Leighton Chen
2024-02-14 12:51:27 -08:00
committed by GitHub
parent 1a984d3ba1
commit 02e38edc54
3 changed files with 65 additions and 61 deletions

View File

@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased ## Unreleased
- Drop uspport for 3.7 - Drop support for 3.7
([#2151](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2151)) ([#2151](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2151))
- `opentelemetry-resource-detector-azure` Added 10s timeout to VM Resource Detector - `opentelemetry-resource-detector-azure` Added 10s timeout to VM Resource Detector
([#2119](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2119)) ([#2119](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2119))
@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#2132](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2132)) ([#2132](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2132))
- `opentelemetry-resource-detector-azure` Changed timeout to 4 seconds due to [timeout bug](https://github.com/open-telemetry/opentelemetry-python/issues/3644) - `opentelemetry-resource-detector-azure` Changed timeout to 4 seconds due to [timeout bug](https://github.com/open-telemetry/opentelemetry-python/issues/3644)
([#2136](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2136)) ([#2136](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2136))
- `opentelemetry-resource-detector-azure` Suppress instrumentation for `urllib` call
([#2178](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2178))
## Version 1.22.0/0.43b0 (2023-12-14) ## Version 1.22.0/0.43b0 (2023-12-14)

View File

@ -17,6 +17,12 @@ from logging import getLogger
from urllib.error import URLError from urllib.error import URLError
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
from opentelemetry.context import (
_SUPPRESS_INSTRUMENTATION_KEY,
attach,
detach,
set_value,
)
from opentelemetry.sdk.resources import Resource, ResourceDetector from opentelemetry.sdk.resources import Resource, ResourceDetector
from opentelemetry.semconv.resource import ( from opentelemetry.semconv.resource import (
CloudPlatformValues, CloudPlatformValues,
@ -49,64 +55,60 @@ class AzureVMResourceDetector(ResourceDetector):
# pylint: disable=no-self-use # pylint: disable=no-self-use
def detect(self) -> "Resource": def detect(self) -> "Resource":
attributes = {} attributes = {}
metadata_json = ( token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
_AzureVMMetadataServiceRequestor().get_azure_vm_metadata() metadata_json = _get_azure_vm_metadata()
)
if not metadata_json: if not metadata_json:
return Resource(attributes) return Resource(attributes)
for attribute_key in EXPECTED_AZURE_AMS_ATTRIBUTES: for attribute_key in EXPECTED_AZURE_AMS_ATTRIBUTES:
attributes[ attributes[attribute_key] = _get_attribute_from_metadata(
attribute_key
] = _AzureVMMetadataServiceRequestor().get_attribute_from_metadata(
metadata_json, attribute_key metadata_json, attribute_key
) )
detach(token)
return Resource(attributes) return Resource(attributes)
class _AzureVMMetadataServiceRequestor: def _get_azure_vm_metadata():
def get_azure_vm_metadata(self): # pylint: disable=no-self-use request = Request(_AZURE_VM_METADATA_ENDPOINT)
request = Request(_AZURE_VM_METADATA_ENDPOINT) request.add_header("Metadata", "True")
request.add_header("Metadata", "True") try:
try: # TODO: Changed to 4s to fit into OTel SDK's 5 second timeout.
# TODO: Changed to 4s to fit into OTel SDK's 5 second timeout. # Lengthen or allow user input if issue is resolved.
# Lengthen or allow user input if issue is resolved. # See https://github.com/open-telemetry/opentelemetry-python/issues/3644
# See https://github.com/open-telemetry/opentelemetry-python/issues/3644 with urlopen(request, timeout=4) as response:
with urlopen(request, timeout=4) as response: return loads(response.read())
return loads(response.read()) except URLError:
except URLError: # Not on Azure VM
# Not on Azure VM return None
return None except Exception as e: # pylint: disable=broad-except,invalid-name
except Exception as e: # pylint: disable=broad-except,invalid-name _logger.exception("Failed to receive Azure VM metadata: %s", e)
_logger.exception("Failed to receive Azure VM metadata: %s", e) return None
return None
def get_attribute_from_metadata(
self, metadata_json, attribute_key def _get_attribute_from_metadata(metadata_json, attribute_key):
): # pylint: disable=no-self-use ams_value = ""
ams_value = "" if attribute_key == _AZURE_VM_SCALE_SET_NAME_ATTRIBUTE:
if attribute_key == _AZURE_VM_SCALE_SET_NAME_ATTRIBUTE: ams_value = metadata_json["vmScaleSetName"]
ams_value = metadata_json["vmScaleSetName"] elif attribute_key == _AZURE_VM_SKU_ATTRIBUTE:
elif attribute_key == _AZURE_VM_SKU_ATTRIBUTE: ams_value = metadata_json["sku"]
ams_value = metadata_json["sku"] elif attribute_key == ResourceAttributes.CLOUD_PLATFORM:
elif attribute_key == ResourceAttributes.CLOUD_PLATFORM: ams_value = CloudPlatformValues.AZURE_VM.value
ams_value = CloudPlatformValues.AZURE_VM.value elif attribute_key == ResourceAttributes.CLOUD_PROVIDER:
elif attribute_key == ResourceAttributes.CLOUD_PROVIDER: ams_value = CloudProviderValues.AZURE.value
ams_value = CloudProviderValues.AZURE.value elif attribute_key == ResourceAttributes.CLOUD_REGION:
elif attribute_key == ResourceAttributes.CLOUD_REGION: ams_value = metadata_json["location"]
ams_value = metadata_json["location"] elif attribute_key == ResourceAttributes.CLOUD_RESOURCE_ID:
elif attribute_key == ResourceAttributes.CLOUD_RESOURCE_ID: ams_value = metadata_json["resourceId"]
ams_value = metadata_json["resourceId"] elif attribute_key in (
elif attribute_key in ( ResourceAttributes.HOST_ID,
ResourceAttributes.HOST_ID, ResourceAttributes.SERVICE_INSTANCE_ID,
ResourceAttributes.SERVICE_INSTANCE_ID, ):
): ams_value = metadata_json["vmId"]
ams_value = metadata_json["vmId"] elif attribute_key == ResourceAttributes.HOST_NAME:
elif attribute_key == ResourceAttributes.HOST_NAME: ams_value = metadata_json["name"]
ams_value = metadata_json["name"] elif attribute_key == ResourceAttributes.HOST_TYPE:
elif attribute_key == ResourceAttributes.HOST_TYPE: ams_value = metadata_json["vmSize"]
ams_value = metadata_json["vmSize"] elif attribute_key == ResourceAttributes.OS_TYPE:
elif attribute_key == ResourceAttributes.OS_TYPE: ams_value = metadata_json["osType"]
ams_value = metadata_json["osType"] elif attribute_key == ResourceAttributes.OS_VERSION:
elif attribute_key == ResourceAttributes.OS_VERSION: ams_value = metadata_json["version"]
ams_value = metadata_json["version"] return ams_value
return ams_value

View File

@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import unittest import unittest
from unittest.mock import Mock, patch from unittest.mock import patch
# pylint: disable=no-name-in-module # pylint: disable=no-name-in-module
from opentelemetry.resource.detector.azure.vm import AzureVMResourceDetector from opentelemetry.resource.detector.azure.vm import AzureVMResourceDetector
@ -363,18 +363,18 @@ WINDOWS_ATTRIBUTES = {
class TestAzureVMResourceDetector(unittest.TestCase): class TestAzureVMResourceDetector(unittest.TestCase):
@patch("opentelemetry.resource.detector.azure.vm.urlopen") @patch("opentelemetry.resource.detector.azure.vm.urlopen")
def test_linux(self, mock_urlopen): def test_linux(self, mock_urlopen):
mock_response = Mock() mock_urlopen.return_value.__enter__.return_value.read.return_value = (
mock_urlopen.return_value = mock_response LINUX_JSON
mock_response.read.return_value = LINUX_JSON )
attributes = AzureVMResourceDetector().detect().attributes attributes = AzureVMResourceDetector().detect().attributes
for attribute_key, attribute_value in LINUX_ATTRIBUTES.items(): for attribute_key, attribute_value in LINUX_ATTRIBUTES.items():
self.assertEqual(attributes[attribute_key], attribute_value) self.assertEqual(attributes[attribute_key], attribute_value)
@patch("opentelemetry.resource.detector.azure.vm.urlopen") @patch("opentelemetry.resource.detector.azure.vm.urlopen")
def test_windows(self, mock_urlopen): def test_windows(self, mock_urlopen):
mock_response = Mock() mock_urlopen.return_value.__enter__.return_value.read.return_value = (
mock_urlopen.return_value = mock_response WINDOWS_JSON
mock_response.read.return_value = WINDOWS_JSON )
attributes = AzureVMResourceDetector().detect().attributes attributes = AzureVMResourceDetector().detect().attributes
for attribute_key, attribute_value in LINUX_ATTRIBUTES.items(): for attribute_key, attribute_value in WINDOWS_ATTRIBUTES.items():
self.assertEqual(attributes[attribute_key], attribute_value) self.assertEqual(attributes[attribute_key], attribute_value)