diff --git a/.github/ISSUE_TEMPLATE/comp_resourcedetectors_aws.md b/.github/ISSUE_TEMPLATE/comp_resourcedetectors_aws.md new file mode 100644 index 0000000000..06df0a1b1d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/comp_resourcedetectors_aws.md @@ -0,0 +1,41 @@ +--- +name: OpenTelemetry.ResourceDetectors.AWS +about: Issue with OpenTelemetry.ResourceDetectors.AWS +labels: comp:resourcedetectors.aws +--- + +# Issue with OpenTelemetry.ResourceDetectors.AWS + +List of [all OpenTelemetry NuGet +packages](https://www.nuget.org/profiles/OpenTelemetry) and version that you are +using (e.g. `OpenTelemetry 1.3.2`): + +* TBD + +Runtime version (e.g. `net462`, `net48`, `net6.0`, `net7.0` etc. You can +find this information from the `*.csproj` file): + +* TBD + +**Is this a feature request or a bug?** + +* [ ] Feature Request +* [ ] Bug + +**What is the expected behavior?** + +What do you expect to see? + +**What is the actual behavior?** + +What did you see instead? If you are reporting a bug, create a self-contained +project using the template of your choice and apply the minimum required code to +result in the issue you're observing. We will close this issue if: + +* The repro project you share with us is complex. We can't investigate custom + projects, so don't point us to such, please. +* If we can not reproduce the behavior you're reporting. + +## Additional Context + +Add any other context about the feature request here. diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 5a84797f2a..b6185d5eb7 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -60,6 +60,9 @@ components: - xiang17 src/OpenTelemetry.Instrumentation.Wcf/: - codeblanch + src/OpenTelemetry.ResourceDetectors.AWS/: + - srprash + - atshaw43 src/OpenTelemetry.ResourceDetectors.Azure/: - rajkumar-rangaraj - vishweshbankwar @@ -136,6 +139,9 @@ components: - xiang17 test/OpenTelemetry.Instrumentation.Wcf.Tests/: - codeblanch + test/OpenTelemetry.ResourceDetectors.AWS.Tests/: + - srprash + - atshaw43 test/OpenTelemetry.ResourceDetectors.Azure.Tests/: - rajkumar-rangaraj - vishweshbankwar diff --git a/.github/workflows/package-ResourceDetectors.AWS.yml b/.github/workflows/package-ResourceDetectors.AWS.yml new file mode 100644 index 0000000000..bad669cca3 --- /dev/null +++ b/.github/workflows/package-ResourceDetectors.AWS.yml @@ -0,0 +1,67 @@ +name: Pack OpenTelemetry.ResourceDetectors.AWS + +on: + workflow_dispatch: + inputs: + logLevel: + description: 'Log level' + required: true + default: 'warning' + push: + tags: + - 'ResourceDetectors.AWS-*' # trigger when we create a tag with prefix "ResourceDetectors.AWS-" + +jobs: + build-test-pack: + runs-on: ${{ matrix.os }} + permissions: + contents: write + env: + PROJECT: OpenTelemetry.ResourceDetectors.AWS + + strategy: + matrix: + os: [windows-latest] + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 # fetching all + + - uses: actions/setup-dotnet@v3.0.3 + with: + dotnet-version: '7.0.x' + + - name: Install dependencies + run: dotnet restore src/${{env.PROJECT}} + + - name: dotnet build ${{env.PROJECT}} + run: dotnet build src/${{env.PROJECT}} --configuration Release --no-restore -p:Deterministic=true + + - name: dotnet test ${{env.PROJECT}} + run: dotnet test test/${{env.PROJECT}}.Tests + + - name: dotnet pack ${{env.PROJECT}} + run: dotnet pack src/${{env.PROJECT}} --configuration Release --no-build + + - name: Publish Artifacts + uses: actions/upload-artifact@v3 + with: + name: ${{env.PROJECT}}-packages + path: '**/${{env.PROJECT}}/bin/**/*.*nupkg' + + - name: Publish Nuget + run: | + nuget push **/${{env.PROJECT}}/bin/**/*.nupkg -Source https://api.nuget.org/v3/index.json -ApiKey ${{ secrets.NUGET_TOKEN }} -SymbolApiKey ${{ secrets.NUGET_TOKEN }} + + - name: Create GitHub Prerelease + if: ${{ (contains(github.ref_name, '-alpha.') || contains(github.ref_name, '-beta.') || contains(github.ref_name, '-rc.')) }} + run: gh release create ${{ github.ref_name }} --title ${{ github.ref_name }} --verify-tag --notes "See [CHANGELOG](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/${{ github.ref_name }}/src/${{env.PROJECT}}/CHANGELOG.md) for details." --prerelease + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Create GitHub Release + if: ${{ !(contains(github.ref_name, '-alpha.') || contains(github.ref_name, '-beta.') || contains(github.ref_name, '-rc.')) }} + run: gh release create ${{ github.ref_name }} --title ${{ github.ref_name }} --verify-tag --notes "See [CHANGELOG](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/${{ github.ref_name }}/src/${{env.PROJECT}}/CHANGELOG.md) for details." --latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/opentelemetry-dotnet-contrib.sln b/opentelemetry-dotnet-contrib.sln index b8556d00c5..be1461ec46 100644 --- a/opentelemetry-dotnet-contrib.sln +++ b/opentelemetry-dotnet-contrib.sln @@ -284,6 +284,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{1FCC8E src\Shared\SpanHelper.cs = src\Shared\SpanHelper.cs EndProjectSection EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.ResourceDetectors.AWS", "src\OpenTelemetry.ResourceDetectors.AWS\OpenTelemetry.ResourceDetectors.AWS.csproj", "{71BABAC0-E299-48BF-93E2-C11C3840B037}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.ResourceDetectors.AWS.Tests", "test\OpenTelemetry.ResourceDetectors.AWS.Tests\OpenTelemetry.ResourceDetectors.AWS.Tests.csproj", "{DE898A1E-920E-476F-B0DB-A98AFD6E3BF4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -590,6 +594,14 @@ Global {9B7F7605-ADFF-4A47-9B64-FFF3E2EC9DEA}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B7F7605-ADFF-4A47-9B64-FFF3E2EC9DEA}.Release|Any CPU.ActiveCfg = Release|Any CPU {9B7F7605-ADFF-4A47-9B64-FFF3E2EC9DEA}.Release|Any CPU.Build.0 = Release|Any CPU + {71BABAC0-E299-48BF-93E2-C11C3840B037}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {71BABAC0-E299-48BF-93E2-C11C3840B037}.Debug|Any CPU.Build.0 = Debug|Any CPU + {71BABAC0-E299-48BF-93E2-C11C3840B037}.Release|Any CPU.ActiveCfg = Release|Any CPU + {71BABAC0-E299-48BF-93E2-C11C3840B037}.Release|Any CPU.Build.0 = Release|Any CPU + {DE898A1E-920E-476F-B0DB-A98AFD6E3BF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DE898A1E-920E-476F-B0DB-A98AFD6E3BF4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DE898A1E-920E-476F-B0DB-A98AFD6E3BF4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DE898A1E-920E-476F-B0DB-A98AFD6E3BF4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -680,6 +692,8 @@ Global {9B7F7605-ADFF-4A47-9B64-FFF3E2EC9DEA} = {93503FAF-D43D-48C0-818C-92EB90F7606B} {93503FAF-D43D-48C0-818C-92EB90F7606B} = {B75EE478-97F7-4E9F-9A5A-DB3D0988EDEA} {1FCC8EEC-9E75-4FEA-AFCF-363DD33FF0B9} = {22DF5DC0-1290-4E83-A9D8-6BB7DE3B3E63} + {71BABAC0-E299-48BF-93E2-C11C3840B037} = {22DF5DC0-1290-4E83-A9D8-6BB7DE3B3E63} + {DE898A1E-920E-476F-B0DB-A98AFD6E3BF4} = {2097345F-4DD3-477D-BC54-A922F9B2B402} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B0816796-CDB3-47D7-8C3C-946434DE3B66} diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/net462/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/net462/PublicAPI.Unshipped.txt index 1c7d693b10..94d28c0a6e 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/net462/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/net462/PublicAPI.Unshipped.txt @@ -1,12 +1,4 @@ OpenTelemetry.Contrib.Extensions.AWSXRay.AWSXRayIdGenerator -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.AWSEBSResourceDetector() -> void -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.AWSEC2ResourceDetector() -> void -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.ResourceDetectorUtils -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.ResourceDetectorUtils.ResourceDetectorUtils() -> void OpenTelemetry.Contrib.Extensions.AWSXRay.Trace.AWSXRayPropagator OpenTelemetry.Contrib.Extensions.AWSXRay.Trace.AWSXRayPropagator.AWSXRayPropagator() -> void OpenTelemetry.Trace.TracerProviderBuilderExtensions @@ -14,4 +6,4 @@ override OpenTelemetry.Contrib.Extensions.AWSXRay.Trace.AWSXRayPropagator.Extrac override OpenTelemetry.Contrib.Extensions.AWSXRay.Trace.AWSXRayPropagator.Fields.get -> System.Collections.Generic.ISet! override OpenTelemetry.Contrib.Extensions.AWSXRay.Trace.AWSXRayPropagator.Inject(OpenTelemetry.Context.Propagation.PropagationContext context, T carrier, System.Action! setter) -> void static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddXRayTraceId(this OpenTelemetry.Trace.TracerProviderBuilder! builder) -> OpenTelemetry.Trace.TracerProviderBuilder! -static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddXRayTraceIdWithSampler(this OpenTelemetry.Trace.TracerProviderBuilder! builder, OpenTelemetry.Trace.Sampler! sampler) -> OpenTelemetry.Trace.TracerProviderBuilder! \ No newline at end of file +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddXRayTraceIdWithSampler(this OpenTelemetry.Trace.TracerProviderBuilder! builder, OpenTelemetry.Trace.Sampler! sampler) -> OpenTelemetry.Trace.TracerProviderBuilder! diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt index ad1e9026fa..639ff112a6 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -1,21 +1,19 @@ -#nullable enable -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable> -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.Detect() -> System.Collections.Generic.IEnumerable> -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSECSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable> -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSECSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEKSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable> -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEKSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.Detect() -> System.Collections.Generic.IEnumerable> -OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>?' -*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.AWSEBSResourceDetector() -> void *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEBSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.AWSEC2ResourceDetector() -> void *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEC2ResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSECSResourceDetector +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSECSResourceDetector.AWSECSResourceDetector() -> void *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSECSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEKSResourceDetector +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEKSResourceDetector.AWSEKSResourceDetector() -> void *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSEKSResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.AWSLambdaResourceDetector() -> void +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.AWSLambdaResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.IResourceDetector *REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.IResourceDetector.Detect() -> System.Collections.Generic.IEnumerable>? -*REMOVED*OpenTelemetry.Resources.ResourceBuilderExtensions -*REMOVED*static OpenTelemetry.Resources.ResourceBuilderExtensions.AddDetector(this OpenTelemetry.Resources.ResourceBuilder resourceBuilder, OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.IResourceDetector resourceDetector) -> OpenTelemetry.Resources.ResourceBuilder \ No newline at end of file +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.ResourceDetectorUtils +*REMOVED*OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.ResourceDetectorUtils.ResourceDetectorUtils() -> void diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/AWSXRayEventSource.cs b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/AWSXRayEventSource.cs index 4e0ba6c9d9..1dff10cda4 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/AWSXRayEventSource.cs +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/AWSXRayEventSource.cs @@ -23,7 +23,7 @@ namespace OpenTelemetry.Contrib.Extensions.AWSXRay; [EventSource(Name = "OpenTelemetry-AWS-XRay")] internal class AWSXRayEventSource : EventSource { - public static AWSXRayEventSource Log = new AWSXRayEventSource(); + public static AWSXRayEventSource Log = new(); [NonEvent] public void ActivityContextExtractException(string format, Exception ex) @@ -34,15 +34,6 @@ public void ActivityContextExtractException(string format, Exception ex) } } - [NonEvent] - public void ResourceAttributesExtractException(string format, Exception ex) - { - if (this.IsEnabled(EventLevel.Warning, (EventKeywords)(-1))) - { - this.FailedToExtractResourceAttributes(format, ex.ToInvariantString()); - } - } - [Event(1, Message = "Failed to extract activity context in format: '{0}', context: '{1}'.", Level = EventLevel.Warning)] public void FailedToExtractActivityContext(string format, string exception) { @@ -54,16 +45,4 @@ public void FailedToInjectActivityContext(string format, string error) { this.WriteEvent(2, format, error); } - - [Event(3, Message = "Failed to extract resource attributes in '{0}'.", Level = EventLevel.Warning)] - public void FailedToExtractResourceAttributes(string format, string exception) - { - this.WriteEvent(3, format, exception); - } - - [Event(4, Message = "Failed to validate certificate in format: '{0}', error: '{1}'.", Level = EventLevel.Warning)] - public void FailedToValidateCertificate(string format, string error) - { - this.WriteEvent(4, format, error); - } } diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/CHANGELOG.md b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/CHANGELOG.md index 168af55a2f..e3cc1d02e0 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/CHANGELOG.md +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/CHANGELOG.md @@ -18,6 +18,12 @@ supporting ResourceBuilderExtensions extension, and migrate all detectors to implement OpenTelemetry.Resources.IResourceDetector ([#875](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/875)) +* Drop support for `AWSLambdaResourceDetector`. + AWS Lambda Resources are detected by `OpenTelemetry.Instrumentation.AWSLambda` + package + ([#1140](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1140)) +* Extract AWS Resource Detectors to dedicated package `OpenTelemetry.ResourceDetectors.AWS` + ([#1140](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1140)) ## 1.2.0 diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/OpenTelemetry.Contrib.Extensions.AWSXRay.csproj b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/OpenTelemetry.Contrib.Extensions.AWSXRay.csproj index 17a1720792..797ef8aca7 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/OpenTelemetry.Contrib.Extensions.AWSXRay.csproj +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/OpenTelemetry.Contrib.Extensions.AWSXRay.csproj @@ -13,14 +13,6 @@ - - - - - - - - diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/README.md b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/README.md index 7c6cc02923..25faacb78e 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/README.md +++ b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/README.md @@ -38,39 +38,6 @@ var tracerProvider = Sdk.CreateTracerProviderBuilder() Sdk.SetDefaultTextMapPropagator(new AWSXRayPropagator()); ``` -### AWS Resource Detectors - -The ADOT .NET SDK supports automatically recording metadata in -EC2, Elastic Beanstalk, ECS, and EKS environments. You can configure -the corresponding resource detector to the `TracerProvider` following -the EC2 example below. - -```csharp -using OpenTelemetry; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; -using OpenTelemetry.Resources; - -var tracerProvider = Sdk.CreateTracerProviderBuilder() - // other configurations - .SetResourceBuilder(ResourceBuilder - .CreateDefault() - .AddDetector(new AWSEC2ResourceDetector())) - .Build(); -``` - -The resource detectors will record the following metadata based on where -your application is running: - -- **AWSEC2ResourceDetector**: cloud provider, cloud platform, account id, -cloud available zone, host id, host type, aws region, host name. -- **AWSEBSResourceDetector**: cloud provider, cloud platform, service name, -service namespace, instance id, service version. -- **AWSECSResourceDetector**: cloud provider, cloud platform, container id. -- **AWSEKSResourceDetector**: cloud provider, cloud platform, cluster name, -container id. -- **AWSLambdaResourceDetector**: cloud provider, cloud platform, aws region, -function name, function version. - ## References - [OpenTelemetry Project](https://opentelemetry.io/) diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSLambdaResourceDetector.cs b/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSLambdaResourceDetector.cs deleted file mode 100644 index 5db498f547..0000000000 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSLambdaResourceDetector.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; -using System.Collections.Generic; -using OpenTelemetry.Resources; - -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; - -/// -/// Resource detector for application running in AWS Lambda. -/// -public class AWSLambdaResourceDetector : IResourceDetector -{ - private const string AWSLambdaRegion = "AWS_REGION"; - private const string AWSLambdaFunctionName = "AWS_LAMBDA_FUNCTION_NAME"; - private const string AWSLambdaFunctionVersion = "AWS_LAMBDA_FUNCTION_VERSION"; - - /// - /// Detector the required and optional resource attributes from AWS Lambda. - /// - /// Resource with key-value pairs of resource attributes. - public Resource Detect() - { - try - { - return new Resource(ExtractResourceAttributes()); - } - catch (Exception ex) - { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSLambdaResourceDetector), ex); - } - - return Resource.Empty; - } - - internal static List> ExtractResourceAttributes() - { - var resourceAttributes = new List>() - { - new KeyValuePair(AWSSemanticConventions.AttributeCloudProvider, "aws"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudPlatform, "aws_lambda"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudRegion, GetAWSRegion()), - new KeyValuePair(AWSSemanticConventions.AttributeFaasName, GetFunctionName()), - new KeyValuePair(AWSSemanticConventions.AttributeFaasVersion, GetFunctionVersion()), - }; - - return resourceAttributes; - } - - private static string GetAWSRegion() - { - return Environment.GetEnvironmentVariable(AWSLambdaRegion); - } - - private static string GetFunctionName() - { - return Environment.GetEnvironmentVariable(AWSLambdaFunctionName); - } - - private static string GetFunctionVersion() - { - return Environment.GetEnvironmentVariable(AWSLambdaFunctionVersion); - } -} diff --git a/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md b/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md index 7ce77b5913..0647e6f08a 100644 --- a/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* TldLogExporter to export `SpanId` value in `ext_dt_spanId` field instead of + `TraceId` value. + ([#1184](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1184)) + ## 1.5.0-alpha.3 Released 2023-Apr-19 diff --git a/src/OpenTelemetry.Exporter.Geneva/TLDExporter/TldLogExporter.cs b/src/OpenTelemetry.Exporter.Geneva/TLDExporter/TldLogExporter.cs index 701748e2e9..2e1a1d1cf1 100644 --- a/src/OpenTelemetry.Exporter.Geneva/TLDExporter/TldLogExporter.cs +++ b/src/OpenTelemetry.Exporter.Geneva/TLDExporter/TldLogExporter.cs @@ -257,7 +257,7 @@ internal void SerializeLogRecord(LogRecord logRecord) if (logRecord.SpanId != default) { - eb.AddCountedString("ext_dt_spanId", logRecord.TraceId.ToHexString()); + eb.AddCountedString("ext_dt_spanId", logRecord.SpanId.ToHexString()); partAFieldsCount++; } diff --git a/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentation.cs b/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentation.cs index 60478a2edf..75d5d87814 100644 --- a/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentation.cs @@ -168,17 +168,7 @@ private static void AfterExecuteCommand() return; } - try - { - if (activity.IsAllDataRequested) - { - activity.SetStatus(Status.Unset); - } - } - finally - { - activity.Stop(); - } + activity.Stop(); } private void BeforeExecuteCommand(MySqlDataTraceCommand command) diff --git a/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentationEventSource.cs b/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentationEventSource.cs index 573e486199..d2721d4375 100644 --- a/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentationEventSource.cs +++ b/src/OpenTelemetry.Instrumentation.MySqlData/MySqlDataInstrumentationEventSource.cs @@ -32,13 +32,13 @@ public void UnknownMySqlTraceEventType(int mysqlEventId, string message) this.WriteEvent(1, mysqlEventId, message); } - [Event(2, Message = "Error accured while processing trace event, MySqlTraceEventType: {0}, Message {1}, Exception: {2}", Level = EventLevel.Error)] + [Event(2, Message = "Error while processing trace event, MySqlTraceEventType: {0}, Message {1}, Exception: {2}", Level = EventLevel.Error)] public void ErrorTraceEvent(int mysqlEventId, string message, string exception) { this.WriteEvent(1, mysqlEventId, message, exception); } - [Event(2, Message = "Error accured while initializing MySqlDataInstrumentation, Message {0}, Exception: {1}", Level = EventLevel.Warning)] + [Event(3, Message = "Error while initializing MySqlDataInstrumentation, Message {0}, Exception: {1}", Level = EventLevel.Warning)] public void ErrorInitialize(string message, string exception) { this.WriteEvent(1, message, exception); diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Shipped.txt b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Shipped.txt index e69de29bb2..7dc5c58110 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Shipped.txt +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Unshipped.txt index 7d34433831..09483f805d 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/net462/PublicAPI.Unshipped.txt @@ -1,5 +1,5 @@ OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions -OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.get -> System.Action +OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.get -> System.Action? OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.set -> void OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.FlushInterval.get -> System.TimeSpan OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.FlushInterval.set -> void @@ -9,4 +9,8 @@ OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrume OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.EnrichActivityWithTimingEvents.get -> bool OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.EnrichActivityWithTimingEvents.set -> void OpenTelemetry.Trace.TracerProviderBuilderExtensions -static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, StackExchange.Redis.IConnectionMultiplexer connection = null, System.Action configure = null) -> OpenTelemetry.Trace.TracerProviderBuilder +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, StackExchange.Redis.IConnectionMultiplexer! connection) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, StackExchange.Redis.IConnectionMultiplexer! connection, System.Action! configure) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, string? name, StackExchange.Redis.IConnectionMultiplexer? connection, System.Action? configure) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, System.Action! configure) -> OpenTelemetry.Trace.TracerProviderBuilder! diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Shipped.txt b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Shipped.txt index e69de29bb2..7dc5c58110 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Shipped.txt +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt index 7d34433831..09483f805d 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -1,5 +1,5 @@ OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions -OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.get -> System.Action +OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.get -> System.Action? OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.Enrich.set -> void OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.FlushInterval.get -> System.TimeSpan OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.FlushInterval.set -> void @@ -9,4 +9,8 @@ OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrume OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.EnrichActivityWithTimingEvents.get -> bool OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions.EnrichActivityWithTimingEvents.set -> void OpenTelemetry.Trace.TracerProviderBuilderExtensions -static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, StackExchange.Redis.IConnectionMultiplexer connection = null, System.Action configure = null) -> OpenTelemetry.Trace.TracerProviderBuilder +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, StackExchange.Redis.IConnectionMultiplexer! connection) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, StackExchange.Redis.IConnectionMultiplexer! connection, System.Action! configure) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, string? name, StackExchange.Redis.IConnectionMultiplexer? connection, System.Action? configure) -> OpenTelemetry.Trace.TracerProviderBuilder! +static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddRedisInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder! builder, System.Action! configure) -> OpenTelemetry.Trace.TracerProviderBuilder! diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/CHANGELOG.md b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/CHANGELOG.md index 3f4f5845c2..4ee8f6ee7b 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/CHANGELOG.md +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +* Added a dependency on `OpenTelemetry.Api.ProviderBuilderExtensions` and + updated `TracerProviderBuilder.AddRedisInstrumentation` to support named + options. + ([#1183](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1183)) + ## 1.0.0-rc9.8 Released 2023-Feb-27 diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs index 0cd0bdc319..c4bca0e8ef 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs @@ -14,8 +14,6 @@ // limitations under the License. // -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; @@ -27,7 +25,7 @@ namespace OpenTelemetry.Instrumentation.StackExchangeRedis.Implementation; internal static class RedisProfilerEntryToActivityConverter { - private static readonly Lazy> MessageDataGetter = new(() => + private static readonly Lazy> MessageDataGetter = new(() => { var redisAssembly = typeof(IProfiledCommand).Assembly; Type profiledCommandType = redisAssembly.GetType("StackExchange.Redis.Profiling.ProfiledCommand"); @@ -39,10 +37,10 @@ internal static class RedisProfilerEntryToActivityConverter if (messageDelegate == null) { - return new Func(source => (null, null)); + return new Func(source => (null, null)); } - return new Func(source => + return new Func(source => { if (source == null) { @@ -55,10 +53,10 @@ internal static class RedisProfilerEntryToActivityConverter return (null, null); } - string script = null; + string? script = null; if (message.GetType() == scriptMessageType) { - script = scriptDelegate.Invoke(message); + script = scriptDelegate?.Invoke(message); } if (commandAndKeyFetcher.TryFetch(message, out var value)) @@ -70,7 +68,7 @@ internal static class RedisProfilerEntryToActivityConverter }); }); - public static Activity ProfilerCommandToActivity(Activity parentActivity, IProfiledCommand command, StackExchangeRedisCallsInstrumentationOptions options) + public static Activity? ProfilerCommandToActivity(Activity? parentActivity, IProfiledCommand command, StackExchangeRedisCallsInstrumentationOptions options) { var name = command.Command; // Example: SET; if (string.IsNullOrEmpty(name)) @@ -107,8 +105,6 @@ public static Activity ProfilerCommandToActivity(Activity parentActivity, IProfi // Total: // command.ElapsedTime; // 00:00:32.4988020 - activity.SetStatus(Status.Unset); - activity.SetTag(StackExchangeRedisCallsInstrumentation.RedisFlagsKeyName, command.Flags.ToString()); if (options.SetVerboseDatabaseStatements) @@ -178,7 +174,7 @@ public static Activity ProfilerCommandToActivity(Activity parentActivity, IProfi return activity; } - public static void DrainSession(Activity parentActivity, IEnumerable sessionCommands, StackExchangeRedisCallsInstrumentationOptions options) + public static void DrainSession(Activity? parentActivity, IEnumerable sessionCommands, StackExchangeRedisCallsInstrumentationOptions options) { foreach (var command in sessionCommands) { @@ -190,7 +186,7 @@ public static void DrainSession(Activity parentActivity, IEnumerable - private static Func CreateFieldGetter(Type classType, string fieldName, BindingFlags flags) + private static Func? CreateFieldGetter(Type classType, string fieldName, BindingFlags flags) { FieldInfo field = classType.GetField(fieldName, flags); if (field != null) diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/OpenTelemetry.Instrumentation.StackExchangeRedis.csproj b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/OpenTelemetry.Instrumentation.StackExchangeRedis.csproj index 45aa8b140d..36b3af1092 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/OpenTelemetry.Instrumentation.StackExchangeRedis.csproj +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/OpenTelemetry.Instrumentation.StackExchangeRedis.csproj @@ -7,6 +7,9 @@ true true Instrumentation.StackExchangeRedis- + enable + true + true @@ -15,7 +18,7 @@ - + diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs index 8d451142cd..63872364a0 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs @@ -14,11 +14,8 @@ // limitations under the License. // -using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Diagnostics; -using System.Threading; using OpenTelemetry.Instrumentation.StackExchangeRedis.Implementation; using OpenTelemetry.Internal; using OpenTelemetry.Trace; @@ -38,9 +35,9 @@ internal class StackExchangeRedisCallsInstrumentation : IDisposable internal static readonly string ActivityName = ActivitySourceName + ".Execute"; internal static readonly Version Version = typeof(StackExchangeRedisCallsInstrumentation).Assembly.GetName().Version; internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString()); - internal static readonly IEnumerable> CreationTags = new[] + internal static readonly IEnumerable> CreationTags = new[] { - new KeyValuePair(SemanticConventions.AttributeDbSystem, "redis"), + new KeyValuePair(SemanticConventions.AttributeDbSystem, "redis"), }; internal readonly ConcurrentDictionary<(ActivityTraceId TraceId, ActivitySpanId SpanId), (Activity Activity, ProfilingSession Session)> Cache @@ -77,7 +74,7 @@ public StackExchangeRedisCallsInstrumentation(IConnectionMultiplexer connection, /// Returns session for the Redis calls recording. /// /// Session associated with the current span context to record Redis calls. - public Func GetProfilerSessionsFactory() + public Func GetProfilerSessionsFactory() { return () => { @@ -86,7 +83,7 @@ public Func GetProfilerSessionsFactory() return null; } - Activity parent = Activity.Current; + var parent = Activity.Current; // If no parent use the default session. if (parent == null || parent.IdFormat != ActivityIdFormat.W3C) diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentationOptions.cs index 4b9e7c99f3..0e27e838d5 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentationOptions.cs @@ -14,7 +14,6 @@ // limitations under the License. // -using System; using System.Diagnostics; using OpenTelemetry.Trace; using StackExchange.Redis.Profiling; @@ -43,7 +42,7 @@ public class StackExchangeRedisCallsInstrumentationOptions /// : the activity being enriched. /// : the profiled redis command from which additional information can be extracted to enrich the activity. /// - public Action Enrich { get; set; } + public Action? Enrich { get; set; } /// /// Gets or sets a value indicating whether or not the should enrich Activity with entries about the Redis command processing/lifetime. Defaults to true. diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs index 22c7e56494..3bd9947930 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs @@ -14,7 +14,8 @@ // limitations under the License. // -using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using OpenTelemetry.Instrumentation.StackExchangeRedis; using OpenTelemetry.Internal; using StackExchange.Redis; @@ -26,6 +27,71 @@ namespace OpenTelemetry.Trace; /// public static class TracerProviderBuilderExtensions { + /// + /// Enables automatic data collection of outgoing requests to Redis. + /// + /// + /// Note: A will be resolved using the + /// application . + /// + /// being configured. + /// The instance of to chain the calls. + public static TracerProviderBuilder AddRedisInstrumentation( + this TracerProviderBuilder builder) + => AddRedisInstrumentation(builder, name: null, connection: null, configure: null); + + /// + /// Enables automatic data collection of outgoing requests to Redis. + /// + /// being configured. + /// to instrument. + /// The instance of to chain the calls. + public static TracerProviderBuilder AddRedisInstrumentation( + this TracerProviderBuilder builder, + IConnectionMultiplexer connection) + { + Guard.ThrowIfNull(connection); + + return AddRedisInstrumentation(builder, name: null, connection, configure: null); + } + + /// + /// Enables automatic data collection of outgoing requests to Redis. + /// + /// + /// Note: A will be resolved using the + /// application . + /// + /// being configured. + /// Callback to configure options. + /// The instance of to chain the calls. + public static TracerProviderBuilder AddRedisInstrumentation( + this TracerProviderBuilder builder, + Action configure) + { + Guard.ThrowIfNull(configure); + + return AddRedisInstrumentation(builder, name: null, connection: null, configure); + } + + /// + /// Enables automatic data collection of outgoing requests to Redis. + /// + /// being configured. + /// to instrument. + /// Callback to configure options. + /// The instance of to chain the calls. + public static TracerProviderBuilder AddRedisInstrumentation( + this TracerProviderBuilder builder, + IConnectionMultiplexer connection, + Action configure) + { + Guard.ThrowIfNull(connection); + Guard.ThrowIfNull(configure); + + return AddRedisInstrumentation(builder, name: null, connection, configure); + } + /// /// Enables automatic data collection of outgoing requests to Redis. /// @@ -35,55 +101,41 @@ public static class TracerProviderBuilderExtensions /// resolved using the application . /// /// being configured. + /// Optional name which is used when retrieving options. /// Optional to instrument. /// Optional callback to configure options. /// The instance of to chain the calls. public static TracerProviderBuilder AddRedisInstrumentation( this TracerProviderBuilder builder, - IConnectionMultiplexer connection = null, - Action configure = null) + string? name, + IConnectionMultiplexer? connection, + Action? configure) { Guard.ThrowIfNull(builder); - if (builder is not IDeferredTracerProviderBuilder deferredTracerProviderBuilder) - { - if (connection == null) - { - throw new NotSupportedException($"StackExchange.Redis {nameof(IConnectionMultiplexer)} must be supplied when dependency injection is unavailable - to enable dependency injection use the OpenTelemetry.Extensions.Hosting package"); - } + name ??= Options.DefaultName; - return AddRedisInstrumentation(builder, connection, new StackExchangeRedisCallsInstrumentationOptions(), configure); + if (configure != null) + { + builder.ConfigureServices(services => services.Configure(name, configure)); } - return deferredTracerProviderBuilder.Configure((sp, builder) => - { - if (connection == null) + return builder + .AddSource(StackExchangeRedisCallsInstrumentation.ActivitySourceName) + .AddInstrumentation(sp => { - connection = (IConnectionMultiplexer)sp.GetService(typeof(IConnectionMultiplexer)); if (connection == null) { - throw new InvalidOperationException($"StackExchange.Redis {nameof(IConnectionMultiplexer)} could not be resolved through application {nameof(IServiceProvider)}"); + connection = sp.GetService(); + if (connection == null) + { + throw new InvalidOperationException($"StackExchange.Redis {nameof(IConnectionMultiplexer)} could not be resolved through application {nameof(IServiceProvider)}"); + } } - } - AddRedisInstrumentation( - builder, - connection, - sp.GetOptions(), - configure); - }); - } - - private static TracerProviderBuilder AddRedisInstrumentation( - TracerProviderBuilder builder, - IConnectionMultiplexer connection, - StackExchangeRedisCallsInstrumentationOptions options, - Action configure) - { - configure?.Invoke(options); - - return builder - .AddInstrumentation(() => new StackExchangeRedisCallsInstrumentation(connection, options)) - .AddSource(StackExchangeRedisCallsInstrumentation.ActivitySourceName); + return new StackExchangeRedisCallsInstrumentation( + connection, + sp.GetRequiredService>().Get(name)); + }); } } diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Shipped.txt b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..815c92006a --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable \ No newline at end of file diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Unshipped.txt b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..2ca53c2ade --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/net462/PublicAPI.Unshipped.txt @@ -0,0 +1,6 @@ +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector.AWSEBSResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector.AWSEC2ResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Shipped.txt b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..4a0f8f92ce --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -0,0 +1,12 @@ +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector.AWSEBSResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSEBSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector.AWSEC2ResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSEC2ResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! +OpenTelemetry.ResourceDetectors.AWS.AWSECSResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSECSResourceDetector.AWSECSResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSECSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! +OpenTelemetry.ResourceDetectors.AWS.AWSEKSResourceDetector +OpenTelemetry.ResourceDetectors.AWS.AWSEKSResourceDetector.AWSEKSResourceDetector() -> void +OpenTelemetry.ResourceDetectors.AWS.AWSEKSResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEBSResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEBSResourceDetector.cs similarity index 84% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEBSResourceDetector.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/AWSEBSResourceDetector.cs index a4175dee53..00d53eb3fe 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEBSResourceDetector.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEBSResourceDetector.cs @@ -19,11 +19,10 @@ #if NETSTANDARD using System.Runtime.InteropServices; #endif - -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +using OpenTelemetry.ResourceDetectors.AWS.Models; using OpenTelemetry.Resources; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; /// /// Resource detector for application running in AWS ElasticBeanstalk environment. @@ -43,7 +42,7 @@ public Resource Detect() { try { - string? filePath = null; + string? filePath; #if NETSTANDARD if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -63,7 +62,7 @@ public Resource Detect() } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSEBSResourceDetector), ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSEBSResourceDetector), ex); } return Resource.Empty; @@ -73,9 +72,9 @@ internal static List> ExtractResourceAttributes(AWS { var resourceAttributes = new List>() { - new KeyValuePair(AWSSemanticConventions.AttributeCloudProvider, "aws"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudPlatform, "aws_elastic_beanstalk"), - new KeyValuePair(AWSSemanticConventions.AttributeServiceName, "aws_elastic_beanstalk"), + new(AWSSemanticConventions.AttributeCloudProvider, "aws"), + new(AWSSemanticConventions.AttributeCloudPlatform, "aws_elastic_beanstalk"), + new(AWSSemanticConventions.AttributeServiceName, "aws_elastic_beanstalk"), }; if (metadata != null) diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEC2ResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEC2ResourceDetector.cs similarity index 89% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEC2ResourceDetector.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/AWSEC2ResourceDetector.cs index b1014ddfa0..954cfdf060 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEC2ResourceDetector.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEC2ResourceDetector.cs @@ -16,11 +16,10 @@ using System; using System.Collections.Generic; - -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +using OpenTelemetry.ResourceDetectors.AWS.Models; using OpenTelemetry.Resources; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; /// /// Resource detector for application running on AWS EC2 instance. @@ -49,7 +48,7 @@ public Resource Detect() } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSEC2ResourceDetector), ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSEC2ResourceDetector), ex); } return Resource.Empty; @@ -59,9 +58,9 @@ internal static List> ExtractResourceAttributes(AWS { var resourceAttributes = new List>() { - new KeyValuePair(AWSSemanticConventions.AttributeCloudProvider, "aws"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudPlatform, "aws_ec2"), - new KeyValuePair(AWSSemanticConventions.AttributeHostName, hostName), + new(AWSSemanticConventions.AttributeCloudProvider, "aws"), + new(AWSSemanticConventions.AttributeCloudPlatform, "aws_ec2"), + new(AWSSemanticConventions.AttributeHostName, hostName), }; if (identity != null) diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSECSResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSECSResourceDetector.cs similarity index 85% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSECSResourceDetector.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/AWSECSResourceDetector.cs index 86d0474c9c..b7de0f6e82 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSECSResourceDetector.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSECSResourceDetector.cs @@ -19,10 +19,9 @@ using System.Net.Http; using System.Text.Json; using System.Text.RegularExpressions; - using OpenTelemetry.Resources; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; /// /// Resource detector for application running in AWS ECS. @@ -46,8 +45,8 @@ public Resource Detect() var resourceAttributes = new List>() { - new KeyValuePair(AWSSemanticConventions.AttributeCloudProvider, "aws"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudPlatform, "aws_ecs"), + new(AWSSemanticConventions.AttributeCloudProvider, "aws"), + new(AWSSemanticConventions.AttributeCloudPlatform, "aws_ecs"), }; try @@ -60,7 +59,7 @@ public Resource Detect() } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), ex); } try @@ -69,7 +68,7 @@ public Resource Detect() } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), ex); } return new Resource(resourceAttributes); @@ -93,14 +92,14 @@ internal static List> ExtractMetadataV4ResourceAttr if (!containerResponse.RootElement.TryGetProperty("ContainerARN", out var containerArnElement) || containerArnElement.GetString() is not string containerArn) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'ContainerARN' field")); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'ContainerARN' field")); return new List>(); } if (!taskResponse.RootElement.TryGetProperty("Cluster", out var clusterArnElement) || clusterArnElement.GetString() is not string clusterArn) { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'Cluster' field")); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'Cluster' field")); return new List>(); } @@ -134,7 +133,7 @@ internal static List> ExtractMetadataV4ResourceAttr } else { - AWSXRayEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException($"The ECS Metadata V4 response contained the unrecognized launch type '{launchTypeElement}'")); + AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSResourceDetector), new ArgumentException($"The ECS Metadata V4 response contained the unrecognized launch type '{launchTypeElement}'")); } if (taskResponse.RootElement.TryGetProperty("TaskARN", out var taskArnElement) && taskArnElement.ValueKind == JsonValueKind.String) @@ -172,14 +171,14 @@ internal static List> ExtractMetadataV4ResourceAttr if (logOptionsElement.TryGetProperty("awslogs-group", out var logGroupElement) && logGroupElement.ValueKind == JsonValueKind.String) { var logGroupName = logGroupElement.GetString()!; - resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogGroupNames, new string[] { logGroupName })); - resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogGroupArns, new string[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:*" })); + resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogGroupNames, new[] { logGroupName })); + resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogGroupArns, new[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:*" })); if (logOptionsElement.TryGetProperty("awslogs-stream", out var logStreamElement) && logStreamElement.ValueKind == JsonValueKind.String) { var logStreamName = logStreamElement.GetString()!; - resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogStreamNames, new string[] { logStreamName })); - resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogStreamArns, new string[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:log-stream:{logStreamName}" })); + resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogStreamNames, new[] { logStreamName })); + resourceAttributes.Add(new KeyValuePair(AWSSemanticConventions.AttributeLogStreamArns, new[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:log-stream:{logStreamName}" })); } } } diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEKSResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEKSResourceDetector.cs similarity index 87% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEKSResourceDetector.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/AWSEKSResourceDetector.cs index a03bc0db02..4f4faf4e77 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSEKSResourceDetector.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSEKSResourceDetector.cs @@ -18,12 +18,11 @@ using System.Collections.Generic; using System.Net.Http; using System.Text; - -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Http; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +using OpenTelemetry.ResourceDetectors.AWS.Http; +using OpenTelemetry.ResourceDetectors.AWS.Models; using OpenTelemetry.Resources; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; /// /// Resource detector for application running in AWS EKS. @@ -96,7 +95,7 @@ internal static List> ExtractResourceAttributes(str } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to load client token", ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to load client token", ex); } return null; @@ -120,7 +119,7 @@ internal static List> ExtractResourceAttributes(str } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get Container Id", ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get Container Id", ex); } return null; @@ -140,7 +139,7 @@ internal static List> ExtractResourceAttributes(str } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get cluster information", ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get cluster information", ex); } return null; @@ -155,7 +154,7 @@ private static bool IsEKSProcess(string credentials, HttpClientHandler? httpClie } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get EKS information", ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException($"{nameof(AWSEKSResourceDetector)} : Failed to get EKS information", ex); } return !string.IsNullOrEmpty(awsAuth); diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/AWSResourcesEventSource.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSResourcesEventSource.cs new file mode 100644 index 0000000000..b1f28aa6fc --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSResourcesEventSource.cs @@ -0,0 +1,48 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Diagnostics.Tracing; +using OpenTelemetry.Internal; + +namespace OpenTelemetry.ResourceDetectors.AWS; + +[EventSource(Name = "OpenTelemetry-ResourceDetectors-AWS")] +internal class AWSResourcesEventSource : EventSource +{ + public static AWSResourcesEventSource Log = new(); + + [NonEvent] + public void ResourceAttributesExtractException(string format, Exception ex) + { + if (this.IsEnabled(EventLevel.Warning, (EventKeywords)(-1))) + { + this.FailedToExtractResourceAttributes(format, ex.ToInvariantString()); + } + } + + [Event(1, Message = "Failed to extract resource attributes in '{0}'.", Level = EventLevel.Warning)] + public void FailedToExtractResourceAttributes(string format, string exception) + { + this.WriteEvent(3, format, exception); + } + + [Event(2, Message = "Failed to validate certificate in format: '{0}', error: '{1}'.", Level = EventLevel.Warning)] + public void FailedToValidateCertificate(string format, string error) + { + this.WriteEvent(4, format, error); + } +} diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSSemanticConventions.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AWSSemanticConventions.cs similarity index 97% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSSemanticConventions.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/AWSSemanticConventions.cs index afb4341c5b..b84ce97b17 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/AWSSemanticConventions.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AWSSemanticConventions.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; internal static class AWSSemanticConventions { diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/AssemblyInfo.cs b/src/OpenTelemetry.ResourceDetectors.AWS/AssemblyInfo.cs new file mode 100644 index 0000000000..ab546998b6 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/AssemblyInfo.cs @@ -0,0 +1,23 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Runtime.CompilerServices; + +#if SIGNED +[assembly: InternalsVisibleTo("OpenTelemetry.ResourceDetectors.AWS.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898")] +#else +[assembly: InternalsVisibleTo("OpenTelemetry.ResourceDetectors.AWS.Tests")] +#endif diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/CHANGELOG.md b/src/OpenTelemetry.ResourceDetectors.AWS/CHANGELOG.md new file mode 100644 index 0000000000..c3c3cc2a72 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## Unreleased + +* Initial release. Previously it was part of `OpenTelemetry.Contrib.Extensions.AWSXRay` + package. + ([#1140](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1140)) diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/Handler.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Http/Handler.cs similarity index 83% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/Handler.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Http/Handler.cs index 5ee545e2dd..27b89b2e2b 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/Handler.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Http/Handler.cs @@ -17,7 +17,7 @@ using System; using System.Net.Http; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Http; +namespace OpenTelemetry.ResourceDetectors.AWS.Http; internal class Handler { @@ -30,7 +30,7 @@ internal class Handler if (!serverCertificateValidationProvider.IsCertificateLoaded ?? false) { - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(Handler), "Failed to Load the certificate file into trusted collection"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(Handler), "Failed to Load the certificate file into trusted collection"); return null; } @@ -47,7 +47,7 @@ internal class Handler } catch (Exception ex) { - AWSXRayEventSource.Log.ResourceAttributesExtractException($"{nameof(Handler)} : Failed to create HttpClientHandler", ex); + AWSResourcesEventSource.Log.ResourceAttributesExtractException($"{nameof(Handler)} : Failed to create HttpClientHandler", ex); } return null; diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/ServerCertificateValidationProvider.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Http/ServerCertificateValidationProvider.cs similarity index 83% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/ServerCertificateValidationProvider.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Http/ServerCertificateValidationProvider.cs index fc48b71aac..5f26f4f064 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Http/ServerCertificateValidationProvider.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Http/ServerCertificateValidationProvider.cs @@ -20,12 +20,11 @@ using System.Net.Security; using System.Security.Cryptography.X509Certificates; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Http; +namespace OpenTelemetry.ResourceDetectors.AWS.Http; internal class ServerCertificateValidationProvider { - private static readonly ServerCertificateValidationProvider InvalidProvider = - new ServerCertificateValidationProvider(null); + private static readonly ServerCertificateValidationProvider InvalidProvider = new(null); private readonly X509Certificate2Collection? trustedCertificates; @@ -53,14 +52,14 @@ public static ServerCertificateValidationProvider FromCertificateFile(string cer { if (!File.Exists(certificateFile)) { - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Certificate File does not exist"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Certificate File does not exist"); return InvalidProvider; } var trustedCertificates = new X509Certificate2Collection(); if (!LoadCertificateToTrustedCollection(trustedCertificates, certificateFile)) { - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to load certificate in trusted collection"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to load certificate in trusted collection"); return InvalidProvider; } @@ -109,12 +108,12 @@ private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPoli { if ((errors | SslPolicyErrors.RemoteCertificateNotAvailable) == errors) { - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to validate certificate due to RemoteCertificateNotAvailable"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to validate certificate due to RemoteCertificateNotAvailable"); } if ((errors | SslPolicyErrors.RemoteCertificateNameMismatch) == errors) { - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to validate certificate due to RemoteCertificateNameMismatch"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), "Failed to validate certificate due to RemoteCertificateNameMismatch"); } } @@ -136,7 +135,7 @@ private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPoli } } - AWSXRayEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), $"Failed to validate certificate due to {chainErrors}"); + AWSResourcesEventSource.Log.FailedToValidateCertificate(nameof(ServerCertificateValidationProvider), $"Failed to validate certificate due to {chainErrors}"); } // check if at least one certificate in the chain is in our trust list @@ -158,7 +157,7 @@ private bool ValidateCertificate(X509Certificate2 cert, X509Chain chain, SslPoli } } - AWSXRayEventSource.Log.FailedToValidateCertificate( + AWSResourcesEventSource.Log.FailedToValidateCertificate( nameof(ServerCertificateValidationProvider), $"Server Certificates Chain cannot be trusted. The chain doesn't match with the Trusted Certificates provided. Server Certificates:{serverCertificates}. Trusted Certificates:{trustCertificates}"); } diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEBSMetadataModel.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEBSMetadataModel.cs similarity index 93% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEBSMetadataModel.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEBSMetadataModel.cs index ffb51d0ec1..a52c3b1526 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEBSMetadataModel.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEBSMetadataModel.cs @@ -16,7 +16,7 @@ using System.Text.Json.Serialization; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +namespace OpenTelemetry.ResourceDetectors.AWS.Models; internal class AWSEBSMetadataModel { diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEC2IdentityDocumentModel.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEC2IdentityDocumentModel.cs similarity index 93% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEC2IdentityDocumentModel.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEC2IdentityDocumentModel.cs index 9753ed7af1..666289cb13 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEC2IdentityDocumentModel.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEC2IdentityDocumentModel.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +namespace OpenTelemetry.ResourceDetectors.AWS.Models; internal class AWSEC2IdentityDocumentModel { diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterDataModel.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterDataModel.cs similarity index 92% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterDataModel.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterDataModel.cs index 7d36f83063..2345a7ded0 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterDataModel.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterDataModel.cs @@ -16,7 +16,7 @@ using System.Text.Json.Serialization; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +namespace OpenTelemetry.ResourceDetectors.AWS.Models; internal class AWSEKSClusterDataModel { diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterInformationModel.cs b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterInformationModel.cs similarity index 92% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterInformationModel.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterInformationModel.cs index d6193e47ab..1a9839b6a9 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/Models/AWSEKSClusterInformationModel.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/Models/AWSEKSClusterInformationModel.cs @@ -14,7 +14,7 @@ // limitations under the License. // -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +namespace OpenTelemetry.ResourceDetectors.AWS.Models; internal class AWSEKSClusterInformationModel { diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/OpenTelemetry.ResourceDetectors.AWS.csproj b/src/OpenTelemetry.ResourceDetectors.AWS/OpenTelemetry.ResourceDetectors.AWS.csproj new file mode 100644 index 0000000000..a4ec9726b9 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/OpenTelemetry.ResourceDetectors.AWS.csproj @@ -0,0 +1,33 @@ + + + + + netstandard2.0 + $(TargetFrameworks);$(NetFrameworkMinimumSupportedVersion) + OpenTelemetry Extensions - AWS Resource Detectors for ElasticBeanstalk, EC2, ECS, EKS. + ResourceDetectors.AWS- + enable + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/OpenTelemetry.ResourceDetectors.AWS/README.md b/src/OpenTelemetry.ResourceDetectors.AWS/README.md new file mode 100644 index 0000000000..525cbb75f4 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.AWS/README.md @@ -0,0 +1,47 @@ +# AWS Resource Detectors + +## Getting Started + +You need to install the +`OpenTelemetry.ResourceDetectors.AWS` to be able to use the +AWS Resource Detectors. + +The ADOT .NET SDK supports automatically recording metadata in +EC2, Elastic Beanstalk, ECS, and EKS environments. + +```shell +dotnet add package OpenTelemetry.ResourceDetectors.AWS +``` + +## Usage + +You can configure AWS resource detector to +the `TracerProvider` with the following EC2 example below. + +```csharp +using OpenTelemetry; +using OpenTelemetry.ResourceDetectors.AWS; + +var tracerProvider = Sdk.CreateTracerProviderBuilder() + // other configurations + .SetResourceBuilder(ResourceBuilder + .CreateEmpty() + .AddDetector(new AWSEC2ResourceDetector())) + .Build(); +``` + +The resource detectors will record the following metadata based on where +your application is running: + +- **AWSEC2ResourceDetector**: cloud provider, cloud platform, account id, +cloud available zone, host id, host type, aws region, host name. +- **AWSEBSResourceDetector**: cloud provider, cloud platform, service name, +service namespace, instance id, service version. +- **AWSECSResourceDetector**: cloud provider, cloud platform, container id. +- **AWSEKSResourceDetector**: cloud provider, cloud platform, cluster name, +container id. + +## References + +- [OpenTelemetry Project](https://opentelemetry.io/) +- [AWS Distro for OpenTelemetry .NET](https://aws-otel.github.io/docs/getting-started/dotnet-sdk) diff --git a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/ResourceDetectorUtils.cs b/src/OpenTelemetry.ResourceDetectors.AWS/ResourceDetectorUtils.cs similarity index 94% rename from src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/ResourceDetectorUtils.cs rename to src/OpenTelemetry.ResourceDetectors.AWS/ResourceDetectorUtils.cs index 2006ab040d..a54203e6b0 100644 --- a/src/OpenTelemetry.Contrib.Extensions.AWSXRay/Resources/ResourceDetectorUtils.cs +++ b/src/OpenTelemetry.ResourceDetectors.AWS/ResourceDetectorUtils.cs @@ -22,16 +22,16 @@ using System.Text.Json; using System.Threading.Tasks; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS; /// /// Class for resource detector utils. /// #pragma warning disable CA1052 -public class ResourceDetectorUtils +internal class ResourceDetectorUtils #pragma warning restore CA1052 { - private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web); + private static readonly JsonSerializerOptions JsonSerializerOptions = new(JsonSerializerDefaults.Web); internal static async Task SendOutRequest(string url, string method, KeyValuePair? header, HttpClientHandler? handler = null) { diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.ResourceDetectors.Azure/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt index e3dbfb40fc..00226a19b1 100644 --- a/src/OpenTelemetry.ResourceDetectors.Azure/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.ResourceDetectors.Azure/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -1,3 +1,6 @@ OpenTelemetry.ResourceDetectors.Azure.AppServiceResourceDetector OpenTelemetry.ResourceDetectors.Azure.AppServiceResourceDetector.AppServiceResourceDetector() -> void OpenTelemetry.ResourceDetectors.Azure.AppServiceResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! +OpenTelemetry.ResourceDetectors.Azure.AzureVMResourceDetector +OpenTelemetry.ResourceDetectors.Azure.AzureVMResourceDetector.AzureVMResourceDetector() -> void +OpenTelemetry.ResourceDetectors.Azure.AzureVMResourceDetector.Detect() -> OpenTelemetry.Resources.Resource! diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/AppServiceResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.Azure/AppServiceResourceDetector.cs index e71e8842a0..277756f7cb 100644 --- a/src/OpenTelemetry.ResourceDetectors.Azure/AppServiceResourceDetector.cs +++ b/src/OpenTelemetry.ResourceDetectors.Azure/AppServiceResourceDetector.cs @@ -28,14 +28,14 @@ public sealed class AppServiceResourceDetector : IResourceDetector { internal static readonly IReadOnlyDictionary AppServiceResourceAttributes = new Dictionary { - ["appSrv_SiteName"] = "WEBSITE_SITE_NAME", - [ResourceSemanticConventions.AttributeServiceName] = "WEBSITE_SITE_NAME", - [ResourceSemanticConventions.AttributeServiceInstance] = "WEBSITE_INSTANCE_ID", - ["appSrv_SlotName"] = "WEBSITE_SLOT_NAME", - ["appSrv_wsStamp"] = "WEBSITE_HOME_STAMPNAME", - ["appSrv_wsHost"] = "WEBSITE_HOSTNAME", - ["appSrv_wsOwner"] = "WEBSITE_OWNER_NAME", - ["appSrv_ResourceGroup"] = "WEBSITE_RESOURCE_GROUP", + [ResourceAttributeConstants.AppServiceSiteName] = ResourceAttributeConstants.AppServiceSiteNameEnvVar, + [ResourceSemanticConventions.AttributeServiceName] = ResourceAttributeConstants.AppServiceSiteNameEnvVar, + [ResourceSemanticConventions.AttributeServiceInstance] = ResourceAttributeConstants.AppServiceInstanceIdEnvVar, + [ResourceAttributeConstants.AppServiceSlotName] = ResourceAttributeConstants.AppServiceSlotNameEnvVar, + [ResourceAttributeConstants.AppServiceStamp] = ResourceAttributeConstants.AppServiceStampNameEnvVar, + [ResourceAttributeConstants.AppServiceHost] = ResourceAttributeConstants.AppServiceHostNameEnvVar, + [ResourceAttributeConstants.AppServiceOwner] = ResourceAttributeConstants.AppServiceOwnerNameEnvVar, + [ResourceAttributeConstants.AppServiceResourceGroup] = ResourceAttributeConstants.AppServiceResourceGroupEnvVar, }; /// diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/AzureVMResourceDetector.cs b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVMResourceDetector.cs new file mode 100644 index 0000000000..f5f702de74 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVMResourceDetector.cs @@ -0,0 +1,68 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Collections.Generic; +using OpenTelemetry.Resources; +using OpenTelemetry.Trace; + +namespace OpenTelemetry.ResourceDetectors.Azure; + +/// +/// Resource detector for Azure VM environment. +/// +public sealed class AzureVMResourceDetector : IResourceDetector +{ + internal static readonly IReadOnlyCollection ExpectedAzureAmsFields = new string[] + { + ResourceAttributeConstants.AzureVmId, + ResourceAttributeConstants.AzureVmLocation, + ResourceAttributeConstants.AzureVmName, + ResourceAttributeConstants.AzureVmOsType, + ResourceAttributeConstants.AzureVmResourceGroup, + ResourceAttributeConstants.AzureVmResourceId, + ResourceAttributeConstants.AzureVmSku, + ResourceAttributeConstants.AzureVmVersion, + ResourceAttributeConstants.AzureVmSize, + ResourceAttributeConstants.AzureVmScaleSetName, + ResourceAttributeConstants.AzureVmSubscriptionId, + ResourceSemanticConventions.AttributeServiceInstance, + }; + + /// + public Resource Detect() + { + List>? attributeList = null; + try + { + var vmMetaDataResponse = AzureVmMetaDataRequestor.GetAzureVmMetaDataResponse(); + if (vmMetaDataResponse != null) + { + attributeList = new List>(ExpectedAzureAmsFields.Count); + foreach (var field in ExpectedAzureAmsFields) + { + attributeList.Add(new KeyValuePair(field, vmMetaDataResponse.GetValueForField(field))); + } + } + } + catch + { + // TODO: log exception. + return Resource.Empty; + } + + return attributeList == null ? Resource.Empty : new Resource(attributeList); + } +} diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetaDataRequestor.cs b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetaDataRequestor.cs new file mode 100644 index 0000000000..4bbb36ab03 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetaDataRequestor.cs @@ -0,0 +1,43 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Net.Http; +using System.Text.Json; + +namespace OpenTelemetry.ResourceDetectors.Azure; + +internal static class AzureVmMetaDataRequestor +{ + private const string AzureVmMetadataEndpointURL = "http://169.254.169.254/metadata/instance/compute?api-version=2021-12-13&format=json"; + + public static Func GetAzureVmMetaDataResponse { get; internal set; } = GetAzureVmMetaDataResponseDefault!; + + public static AzureVmMetadataResponse? GetAzureVmMetaDataResponseDefault() + { + using var httpClient = new HttpClient(); + + httpClient.DefaultRequestHeaders.Add("Metadata", "True"); + var res = httpClient.GetStringAsync(AzureVmMetadataEndpointURL).ConfigureAwait(false).GetAwaiter().GetResult(); + + if (res != null) + { + return JsonSerializer.Deserialize(res); + } + + return null; + } +} diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetadataResponse.cs b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetadataResponse.cs new file mode 100644 index 0000000000..41a2c1bc2f --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.Azure/AzureVmMetadataResponse.cs @@ -0,0 +1,101 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Text.Json.Serialization; +using OpenTelemetry.Trace; + +namespace OpenTelemetry.ResourceDetectors.Azure; +internal sealed class AzureVmMetadataResponse +{ + [JsonPropertyName("location")] + public string? Location { get; set; } + + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("osType")] + public string? OsType { get; set; } + + [JsonPropertyName("resourceGroupName")] + public string? ResourceGroupName { get; set; } + + [JsonPropertyName("resourceId")] + public string? ResourceId { get; set; } + + [JsonPropertyName("sku")] + public string? Sku { get; set; } + + [JsonPropertyName("subscriptionId")] + public string? SubscriptionId { get; set; } + + [JsonPropertyName("version")] + public string? Version { get; set; } + + [JsonPropertyName("vmId")] + public string? VmId { get; set; } + + [JsonPropertyName("vmScaleSetName")] + public string? VmScaleSetName { get; set; } + + [JsonPropertyName("vmSize")] + public string? VmSize { get; set; } + + internal string GetValueForField(string fieldName) + { + string? amsValue = null; + switch (fieldName) + { + case "azInst_osType": + amsValue = this.OsType; + break; + case "azInst_location": + amsValue = this.Location; + break; + case "azInst_name": + amsValue = this.Name; + break; + case "azInst_sku": + amsValue = this.Sku; + break; + case "azInst_version": + amsValue = this.Version; + break; + case "azInst_vmId": + case ResourceSemanticConventions.AttributeServiceInstance: + amsValue = this.VmId; + break; + case "azInst_vmSize": + amsValue = this.VmSize; + break; + case "azInst_subscriptionId": + amsValue = this.SubscriptionId; + break; + case "azInst_resourceId": + amsValue = this.ResourceId; + break; + case "azInst_resourceGroupName": + amsValue = this.ResourceGroupName; + break; + case "azInst_vmScaleSetName": + amsValue = this.VmScaleSetName; + break; + } + + amsValue ??= string.Empty; + + return amsValue; + } +} diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/CHANGELOG.md b/src/OpenTelemetry.ResourceDetectors.Azure/CHANGELOG.md index 32baee3f54..d5cad43209 100644 --- a/src/OpenTelemetry.ResourceDetectors.Azure/CHANGELOG.md +++ b/src/OpenTelemetry.ResourceDetectors.Azure/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +* Added Azure VM resource detector. +([#1182](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1182)) + ## 1.0.0-alpha.1 Released 2023-Apr-19 diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/OpenTelemetry.ResourceDetectors.Azure.csproj b/src/OpenTelemetry.ResourceDetectors.Azure/OpenTelemetry.ResourceDetectors.Azure.csproj index 19c0f3f377..5ddc90d943 100644 --- a/src/OpenTelemetry.ResourceDetectors.Azure/OpenTelemetry.ResourceDetectors.Azure.csproj +++ b/src/OpenTelemetry.ResourceDetectors.Azure/OpenTelemetry.ResourceDetectors.Azure.csproj @@ -10,6 +10,7 @@ + diff --git a/src/OpenTelemetry.ResourceDetectors.Azure/ResourceAttributeConstants.cs b/src/OpenTelemetry.ResourceDetectors.Azure/ResourceAttributeConstants.cs new file mode 100644 index 0000000000..299046fe60 --- /dev/null +++ b/src/OpenTelemetry.ResourceDetectors.Azure/ResourceAttributeConstants.cs @@ -0,0 +1,49 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace OpenTelemetry.ResourceDetectors.Azure; +internal class ResourceAttributeConstants +{ + // AppService resource attributes + internal const string AppServiceSiteName = "appSrv_SiteName"; + internal const string AppServiceSlotName = "appSrv_SlotName"; + internal const string AppServiceStamp = "appSrv_wsStamp"; + internal const string AppServiceHost = "appSrv_wsHost"; + internal const string AppServiceOwner = "appSrv_wsOwner"; + internal const string AppServiceResourceGroup = "appSrv_ResourceGroup"; + + // Azure VM resource attributes + internal const string AzureVmId = "azInst_vmId"; + internal const string AzureVmLocation = "azInst_location"; + internal const string AzureVmName = "azInst_name"; + internal const string AzureVmOsType = "azInst_osType"; + internal const string AzureVmResourceGroup = "azInst_resourceGroupName"; + internal const string AzureVmResourceId = "azInst_resourceId"; + internal const string AzureVmSku = "azInst_sku"; + internal const string AzureVmVersion = "azInst_version"; + internal const string AzureVmSize = "azInst_vmSize"; + internal const string AzureVmScaleSetName = "azInst_vmScaleSetName"; + internal const string AzureVmSubscriptionId = "azInst_subscriptionId"; + + // AppService environment variables + internal const string AppServiceSiteNameEnvVar = "WEBSITE_SITE_NAME"; + internal const string AppServiceInstanceIdEnvVar = "WEBSITE_INSTANCE_ID"; + internal const string AppServiceSlotNameEnvVar = "WEBSITE_SLOT_NAME"; + internal const string AppServiceStampNameEnvVar = "WEBSITE_HOME_STAMPNAME"; + internal const string AppServiceHostNameEnvVar = "WEBSITE_HOSTNAME"; + internal const string AppServiceOwnerNameEnvVar = "WEBSITE_OWNER_NAME"; + internal const string AppServiceResourceGroupEnvVar = "WEBSITE_RESOURCE_GROUP"; +} diff --git a/src/Shared/ActivityInstrumentationHelper.cs b/src/Shared/ActivityInstrumentationHelper.cs index 1ba9636dfa..1c2f97ce70 100644 --- a/src/Shared/ActivityInstrumentationHelper.cs +++ b/src/Shared/ActivityInstrumentationHelper.cs @@ -14,9 +14,13 @@ // limitations under the License. // +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Diagnostics; using System.Linq.Expressions; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/DiagnosticSourceListener.cs b/src/Shared/DiagnosticSourceListener.cs index 9dc3f74a7b..38a6ee2410 100644 --- a/src/Shared/DiagnosticSourceListener.cs +++ b/src/Shared/DiagnosticSourceListener.cs @@ -14,10 +14,14 @@ // limitations under the License. // +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Collections.Generic; using System.Diagnostics; using OpenTelemetry.Internal; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/DiagnosticSourceSubscriber.cs b/src/Shared/DiagnosticSourceSubscriber.cs index 99a25bbf7f..5435b90a3f 100644 --- a/src/Shared/DiagnosticSourceSubscriber.cs +++ b/src/Shared/DiagnosticSourceSubscriber.cs @@ -13,11 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. // + +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using OpenTelemetry.Internal; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/InstrumentationEventSource.cs b/src/Shared/InstrumentationEventSource.cs index 07f9f56057..4321679472 100644 --- a/src/Shared/InstrumentationEventSource.cs +++ b/src/Shared/InstrumentationEventSource.cs @@ -14,9 +14,13 @@ // limitations under the License. // +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Diagnostics.Tracing; using OpenTelemetry.Internal; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/MultiTypePropertyFetcher.cs b/src/Shared/MultiTypePropertyFetcher.cs index 122d40743f..4c8fb3fb0c 100644 --- a/src/Shared/MultiTypePropertyFetcher.cs +++ b/src/Shared/MultiTypePropertyFetcher.cs @@ -14,10 +14,14 @@ // limitations under the License. // +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/PropertyFetcher.cs b/src/Shared/PropertyFetcher.cs index 8aab31e0be..4549699132 100644 --- a/src/Shared/PropertyFetcher.cs +++ b/src/Shared/PropertyFetcher.cs @@ -14,9 +14,13 @@ // limitations under the License. // +#nullable disable + +#pragma warning disable IDE0005 // Using directive is unnecessary. using System; using System.Linq; using System.Reflection; +#pragma warning restore IDE0005 // Using directive is unnecessary. namespace OpenTelemetry.Instrumentation; diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.csproj b/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.csproj index b1b26be408..908d078099 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.csproj +++ b/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.csproj @@ -22,40 +22,6 @@ - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSLambdaResourceDetector.cs b/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSLambdaResourceDetector.cs deleted file mode 100644 index 0b6a62a1cc..0000000000 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSLambdaResourceDetector.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; -using System.Linq; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; -using Xunit; - -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; - -public class TestAWSLambdaResourceDetector -{ - [Fact] - public void TestDetect() - { - Environment.SetEnvironmentVariable("AWS_REGION", "us-east-1"); - Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", "testfunction"); - Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_VERSION", "latest"); - - var resourceAttributes = new AWSLambdaResourceDetector().Detect().Attributes.ToDictionary(x => x.Key, x => x.Value); - - Assert.Equal("aws", resourceAttributes[AWSSemanticConventions.AttributeCloudProvider]); - Assert.Equal("aws_lambda", resourceAttributes[AWSSemanticConventions.AttributeCloudPlatform]); - Assert.Equal("us-east-1", resourceAttributes[AWSSemanticConventions.AttributeCloudRegion]); - Assert.Equal("testfunction", resourceAttributes[AWSSemanticConventions.AttributeFaasName]); - Assert.Equal("latest", resourceAttributes[AWSSemanticConventions.AttributeFaasVersion]); - - Environment.SetEnvironmentVariable("AWS_REGION", null); - Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", null); - Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_VERSION", null); - } -} diff --git a/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs b/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs index 0539a93d4e..55cdb58011 100644 --- a/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs +++ b/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // + using System; using System.Diagnostics; using System.Net; @@ -304,13 +305,13 @@ public async Task ProfilerSessionsHandleMultipleSpans() public void StackExchangeRedis_BadArgs() { TracerProviderBuilder builder = null; - Assert.Throws(() => builder.AddRedisInstrumentation(null)); + Assert.Throws(() => builder.AddRedisInstrumentation(connection: null)); var activityProcessor = new Mock>(); var exception = Assert.Throws(() => Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) - .AddRedisInstrumentation(null) + .AddRedisInstrumentation(name: null, connection: null, configure: null) .Build()); Assert.Equal("StackExchange.Redis IConnectionMultiplexer could not be resolved through application IServiceProvider", exception.Message); } diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEBSResourceDetector.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEBSResourceDetectorTests.cs similarity index 86% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEBSResourceDetector.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEBSResourceDetectorTests.cs index 7c63dc09d9..82a6337d84 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEBSResourceDetector.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEBSResourceDetectorTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,14 +15,13 @@ // using System.Linq; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; -public class TestAWSEBSResourceDetector +public class AWSEBSResourceDetectorTests { - private const string AWSEBSMetadataFilePath = "Resources/SampleMetadataFiles/environment.conf"; + private const string AWSEBSMetadataFilePath = "SampleMetadataFiles/environment.conf"; [Fact] public void TestDetect() diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEC2ResourceDetector.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEC2ResourceDetectorTests.cs similarity index 92% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEC2ResourceDetector.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEC2ResourceDetectorTests.cs index 8750fa7cdd..e3a5444e58 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEC2ResourceDetector.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEC2ResourceDetectorTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,12 +15,11 @@ // using System.Linq; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; -public class TestAWSEC2ResourceDetector +public class AWSEC2ResourceDetectorTests { [Fact] public void TestDetect() diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSECSResourceDetector.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSECSResourceDetectorTests.cs similarity index 92% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSECSResourceDetector.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSECSResourceDetectorTests.cs index 53d029ba0d..02832a6edf 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSECSResourceDetector.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSECSResourceDetectorTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,30 +14,29 @@ // limitations under the License. // +#if !NETFRAMEWORK + using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; - -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; -public class TestAWSECSResourceDetector : IDisposable +public class AWSECSResourceDetectorTests : IDisposable { - private const string AWSECSMetadataFilePath = "Resources/SampleMetadataFiles/testcgroup"; + private const string AWSECSMetadataFilePath = "SampleMetadataFiles/testcgroup"; private const string AWSECSMetadataURLKey = "ECS_CONTAINER_METADATA_URI"; private const string AWSECSMetadataURLV4Key = "ECS_CONTAINER_METADATA_URI_V4"; - public TestAWSECSResourceDetector() + public AWSECSResourceDetectorTests() { this.ResetEnvironment(); } @@ -134,15 +133,10 @@ internal void ResetEnvironment() internal class MockEcsMetadataEndpoint : IAsyncDisposable { public readonly Uri Address; - private readonly string containerJsonPath; - private readonly string taskJsonPath; private readonly IWebHost server; public MockEcsMetadataEndpoint(string containerJsonPath, string taskJsonPath) { - this.containerJsonPath = containerJsonPath; - this.taskJsonPath = taskJsonPath; - this.server = new WebHostBuilder() .UseKestrel() .UseUrls("http://127.0.0.1:0") // Use random localhost port @@ -152,14 +146,14 @@ public MockEcsMetadataEndpoint(string containerJsonPath, string taskJsonPath) { if (context.Request.Method == HttpMethods.Get && context.Request.Path == "/") { - var content = await File.ReadAllTextAsync($"{Environment.CurrentDirectory}/Resources/{containerJsonPath}"); + var content = await File.ReadAllTextAsync($"{Environment.CurrentDirectory}/{containerJsonPath}"); var data = Encoding.UTF8.GetBytes(content); context.Response.ContentType = "application/json"; await context.Response.Body.WriteAsync(data); } else if (context.Request.Method == HttpMethods.Get && context.Request.Path == "/task") { - var content = await File.ReadAllTextAsync($"{Environment.CurrentDirectory}/Resources/{taskJsonPath}"); + var content = await File.ReadAllTextAsync($"{Environment.CurrentDirectory}/{taskJsonPath}"); var data = Encoding.UTF8.GetBytes(content); context.Response.ContentType = "application/json"; await context.Response.Body.WriteAsync(data); @@ -187,3 +181,4 @@ protected virtual async ValueTask DisposeAsyncCore() } } } +#endif diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEKSResourceDetector.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEKSResourceDetectorTests.cs similarity index 91% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEKSResourceDetector.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEKSResourceDetectorTests.cs index 338ca4aaa2..643a468c97 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/TestAWSEKSResourceDetector.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/AWSEKSResourceDetectorTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +14,17 @@ // limitations under the License. // +#if !NETFRAMEWORK + using System.Linq; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; -public class TestAWSEKSResourceDetector +public class AWSEKSResourceDetectorTests { - private const string AWSEKSCredentialsPath = "Resources/SampleMetadataFiles/testekstoken"; - private const string AWSEKSMetadataFilePath = "Resources/SampleMetadataFiles/testcgroup"; + private const string AWSEKSCredentialsPath = "SampleMetadataFiles/testekstoken"; + private const string AWSEKSMetadataFilePath = "SampleMetadataFiles/testcgroup"; [Fact] public void TestDetect() @@ -106,3 +107,5 @@ public void TestDeserializeResponse() Assert.Equal("Test", eksClusterInformation.Data.ClusterName); } } + +#endif diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/CertificateUploader.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/CertificateUploader.cs similarity index 97% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/CertificateUploader.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/CertificateUploader.cs index 5b9c310500..1a791bf2e3 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/CertificateUploader.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/CertificateUploader.cs @@ -14,13 +14,15 @@ // limitations under the License. // +#if !NETFRAMEWORK + using System; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources.Http; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests.Http; internal class CertificateUploader : IDisposable { @@ -81,3 +83,5 @@ public void Dispose() } } } + +#endif diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestHandler.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/HandlerTests.cs similarity index 84% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestHandler.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/HandlerTests.cs index cbac46d149..4a08e6ee05 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestHandler.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/HandlerTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +14,14 @@ // limitations under the License. // -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Http; +#if !NETFRAMEWORK + +using OpenTelemetry.ResourceDetectors.AWS.Http; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources.Http; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests.Http; -public class TestHandler +public class HandlerTests { private const string INVALIDCRTNAME = "invalidcert"; @@ -42,3 +44,5 @@ public void TestInValidHandler() Assert.Null(Handler.Create(INVALIDCRTNAME)); } } + +#endif diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestServerCertificateValidationProvider.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/ServerCertificateValidationProviderTests.cs similarity index 90% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestServerCertificateValidationProvider.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/ServerCertificateValidationProviderTests.cs index baa289b2db..7f69902b6c 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/Http/TestServerCertificateValidationProvider.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/Http/ServerCertificateValidationProviderTests.cs @@ -1,4 +1,4 @@ -// +// // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +14,16 @@ // limitations under the License. // +#if !NETFRAMEWORK + using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Http; +using OpenTelemetry.ResourceDetectors.AWS.Http; using Xunit; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources.Http; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests.Http; -public class TestServerCertificateValidationProvider +public class ServerCertificateValidationProviderTests { private const string INVALIDCRTNAME = "invalidcert"; @@ -65,3 +67,5 @@ public void TestInValidCertificate() Assert.False(serverCertificateValidationProvider.IsCertificateLoaded); } } + +#endif diff --git a/test/OpenTelemetry.ResourceDetectors.AWS.Tests/OpenTelemetry.ResourceDetectors.AWS.Tests.csproj b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/OpenTelemetry.ResourceDetectors.AWS.Tests.csproj new file mode 100644 index 0000000000..061f4214ac --- /dev/null +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/OpenTelemetry.ResourceDetectors.AWS.Tests.csproj @@ -0,0 +1,52 @@ + + + + Unit test project for AWS Detector for OpenTelemetry + + net7.0;net6.0 + $(TargetFrameworks);$(NetFrameworkMinimumSupportedVersion) + enable + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEBSMetadataModel.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEBSMetadataModel.cs similarity index 87% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEBSMetadataModel.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEBSMetadataModel.cs index 5b473225cd..d3a7e3efca 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEBSMetadataModel.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEBSMetadataModel.cs @@ -14,9 +14,9 @@ // limitations under the License. // -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +using OpenTelemetry.ResourceDetectors.AWS.Models; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; internal class SampleAWSEBSMetadataModel : AWSEBSMetadataModel { diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEC2IdentityDocumentModel.cs b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEC2IdentityDocumentModel.cs similarity index 89% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEC2IdentityDocumentModel.cs rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEC2IdentityDocumentModel.cs index 45a068bf86..b2cefe849a 100644 --- a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleAWSEC2IdentityDocumentModel.cs +++ b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleAWSEC2IdentityDocumentModel.cs @@ -14,9 +14,9 @@ // limitations under the License. // -using OpenTelemetry.Contrib.Extensions.AWSXRay.Resources.Models; +using OpenTelemetry.ResourceDetectors.AWS.Models; -namespace OpenTelemetry.Contrib.Extensions.AWSXRay.Tests.Resources; +namespace OpenTelemetry.ResourceDetectors.AWS.Tests; internal class SampleAWSEC2IdentityDocumentModel : AWSEC2IdentityDocumentModel { diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/environment.conf b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/environment.conf similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/environment.conf rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/environment.conf diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/testcgroup b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/testcgroup similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/testcgroup rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/testcgroup diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/testekstoken b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/testekstoken similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/SampleMetadataFiles/testekstoken rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/SampleMetadataFiles/testekstoken diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-container-ec2.json b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-container-ec2.json similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-container-ec2.json rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-container-ec2.json diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-container-fargate.json b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-container-fargate.json similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-container-fargate.json rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-container-fargate.json diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-task-ec2.json b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-task-ec2.json similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-task-ec2.json rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-task-ec2.json diff --git a/test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-task-fargate.json b/test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-task-fargate.json similarity index 100% rename from test/OpenTelemetry.Contrib.Extensions.AWSXRay.Tests/Resources/ecs_metadata/metadatav4-response-task-fargate.json rename to test/OpenTelemetry.ResourceDetectors.AWS.Tests/ecs_metadata/metadatav4-response-task-fargate.json diff --git a/test/OpenTelemetry.ResourceDetectors.Azure.Tests/AzureResourceDetectorTests.cs b/test/OpenTelemetry.ResourceDetectors.Azure.Tests/AzureResourceDetectorTests.cs index 42404a0a1a..03c04a34da 100644 --- a/test/OpenTelemetry.ResourceDetectors.Azure.Tests/AzureResourceDetectorTests.cs +++ b/test/OpenTelemetry.ResourceDetectors.Azure.Tests/AzureResourceDetectorTests.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using OpenTelemetry.Resources; +using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.ResourceDetectors.Azure.Tests; @@ -30,7 +31,7 @@ public void AppServiceResourceDetectorReturnsResourceWithAttributes() { foreach (var kvp in AppServiceResourceDetector.AppServiceResourceAttributes) { - if (kvp.Value == "WEBSITE_SITE_NAME") + if (kvp.Value == ResourceAttributeConstants.AppServiceSiteNameEnvVar) { continue; } @@ -39,7 +40,7 @@ public void AppServiceResourceDetectorReturnsResourceWithAttributes() } // Special case for service.name and appSrv_SiteName attribute - Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", "ServiceName"); + Environment.SetEnvironmentVariable(ResourceAttributeConstants.AppServiceSiteNameEnvVar, "ServiceName"); } catch { @@ -50,14 +51,49 @@ public void AppServiceResourceDetectorReturnsResourceWithAttributes() foreach (var kvp in AppServiceResourceDetector.AppServiceResourceAttributes) { - if (kvp.Value == "WEBSITE_SITE_NAME") + if (kvp.Value == ResourceAttributeConstants.AppServiceSiteNameEnvVar) { Assert.Contains(new KeyValuePair(kvp.Key, "ServiceName"), resource.Attributes); + continue; } - else + + Assert.Contains(new KeyValuePair(kvp.Key, kvp.Key), resource.Attributes); + } + } + + [Fact] + public void TestAzureVmResourceDetector() + { + AzureVmMetaDataRequestor.GetAzureVmMetaDataResponse = () => + { + return new AzureVmMetadataResponse() + { + // using values same as key for test. + VmId = ResourceAttributeConstants.AzureVmId, + Location = ResourceAttributeConstants.AzureVmLocation, + Name = ResourceAttributeConstants.AzureVmName, + OsType = ResourceAttributeConstants.AzureVmOsType, + ResourceGroupName = ResourceAttributeConstants.AzureVmResourceGroup, + ResourceId = ResourceAttributeConstants.AzureVmResourceId, + Sku = ResourceAttributeConstants.AzureVmSku, + Version = ResourceAttributeConstants.AzureVmVersion, + VmSize = ResourceAttributeConstants.AzureVmSize, + VmScaleSetName = ResourceAttributeConstants.AzureVmScaleSetName, + SubscriptionId = ResourceAttributeConstants.AzureVmSubscriptionId, + }; + }; + + var resource = ResourceBuilder.CreateEmpty().AddDetector(new AzureVMResourceDetector()).Build(); + Assert.NotNull(resource); + foreach (var field in AzureVMResourceDetector.ExpectedAzureAmsFields) + { + if (field == ResourceSemanticConventions.AttributeServiceInstance) { - Assert.Contains(new KeyValuePair(kvp.Key, kvp.Key), resource.Attributes); + Assert.Contains(new KeyValuePair(field, ResourceAttributeConstants.AzureVmId), resource.Attributes); + continue; } + + Assert.Contains(new KeyValuePair(field, field), resource.Attributes); } }