-
Notifications
You must be signed in to change notification settings - Fork 893
[API] Support environment variable context propagation #7174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
0461e49
[Api] Support env var context propagation
martincostello 3a40508
[Examples] Add example project
martincostello 244414b
[API] Fix README
martincostello 7c2c2be
[API] Extend coverage
martincostello c466ea3
[API] Refactor EnvironmentVariableCarrier
martincostello c82e85f
Merge branch 'main' into gh-6776
martincostello 295ca0d
[Infra] Fix merge
martincostello cf17a7d
[API] Address feedback
martincostello a2abdc5
[API] Harden sample
martincostello 036e48b
Merge branch 'main' into gh-6776
martincostello da54674
[API] Address review comments
martincostello 1aba85f
[API] Move to experimental
martincostello 9e237f9
[API] Capture values once
martincostello f4cbd76
[API] Update documentation
martincostello f81a474
[API] Fix lint warning
martincostello 2a482f5
[API] Update solution file
martincostello 4612794
[API] Fix build
martincostello c195440
[API] Fix build
martincostello 93f076c
[API] Fix build
martincostello 73a96e3
[API] Update CHANGELOG
martincostello File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12 changes: 12 additions & 0 deletions
12
examples/EnvironmentVariables/Examples.EnvironmentVariables.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>$(DefaultTargetFrameworkForExampleApps)</TargetFramework> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Api\OpenTelemetry.Api.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,235 @@ | ||
| // Copyright The OpenTelemetry Authors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| using System.Collections; | ||
| using System.Diagnostics; | ||
| using System.Reflection; | ||
| using System.Text; | ||
| using OpenTelemetry; | ||
| using OpenTelemetry.Context.Propagation; | ||
|
|
||
| namespace Examples.EnvironmentVariables; | ||
|
|
||
| internal static class Program | ||
| { | ||
| private const string ActivitySourceName = "Examples.EnvironmentVariables"; | ||
| private const string ChildModeArgument = "--child"; | ||
|
|
||
| private static readonly ActivitySource ActivitySource = new(ActivitySourceName); | ||
| private static readonly TextMapPropagator Propagator = new CompositeTextMapPropagator( | ||
| [ | ||
| new TraceContextPropagator(), | ||
| new BaggagePropagator(), | ||
| ]); | ||
|
|
||
| public static int Main(string[] args) | ||
| { | ||
| using var listener = CreateActivityListener(); | ||
|
|
||
| return args.Contains(ChildModeArgument, StringComparer.Ordinal) | ||
| ? RunAsChild() | ||
| : RunAsParent(); | ||
| } | ||
|
|
||
| private static int RunAsParent() | ||
| { | ||
| Baggage.ClearBaggage(); | ||
| Baggage.SetBaggage("tenant.id", "contoso"); | ||
| Baggage.SetBaggage("user.id", "alice"); | ||
|
|
||
| using var activity = ActivitySource.StartActivity("parent-process"); | ||
| if (activity == null) | ||
| { | ||
| Console.Error.WriteLine("Failed to create the parent activity."); | ||
| return 1; | ||
| } | ||
|
|
||
| WriteProcessContext("Parent", activity, default, Baggage.Current); | ||
|
|
||
| var startInfo = CreateChildStartInfo(); | ||
|
|
||
| CopyCurrentEnvironment(startInfo.Environment); | ||
|
|
||
| var context = new PropagationContext(activity.Context, Baggage.Current); | ||
| Propagator.Inject(context, startInfo.Environment, EnvironmentVariableCarrier.Set); | ||
|
|
||
| Console.WriteLine("[Parent] Injected environment variables:"); | ||
| WritePropagationFields("Parent", startInfo.Environment); | ||
| Console.WriteLine(); | ||
|
|
||
| using var child = Process.Start(startInfo); | ||
| if (child == null) | ||
| { | ||
| Console.Error.WriteLine("Failed to start the child process."); | ||
| return 1; | ||
| } | ||
|
|
||
| var childStandardOutput = child.StandardOutput.ReadToEnd(); | ||
| var childStandardError = child.StandardError.ReadToEnd(); | ||
|
|
||
| child.WaitForExit(); | ||
|
martincostello marked this conversation as resolved.
Outdated
|
||
|
|
||
| if (!string.IsNullOrEmpty(childStandardOutput)) | ||
| { | ||
| Console.WriteLine(); | ||
| Console.Write(childStandardOutput); | ||
| } | ||
|
|
||
| if (!string.IsNullOrEmpty(childStandardError)) | ||
| { | ||
| Console.Error.Write(childStandardError); | ||
| } | ||
|
|
||
| Console.WriteLine(); | ||
| Console.WriteLine($"[Parent] Child process exited with code {child.ExitCode}."); | ||
|
|
||
| return child.ExitCode; | ||
| } | ||
|
|
||
| private static int RunAsChild() | ||
| { | ||
| var carrier = EnvironmentVariableCarrier.Capture(); | ||
| var parentContext = Propagator.Extract(default, carrier, EnvironmentVariableCarrier.Get); | ||
|
|
||
| Baggage.Current = parentContext.Baggage; | ||
|
|
||
| using var activity = ActivitySource.StartActivity( | ||
| "child-process", | ||
| ActivityKind.Internal, | ||
| parentContext.ActivityContext); | ||
|
|
||
| if (activity == null) | ||
| { | ||
| Console.Error.WriteLine("Failed to create the child activity."); | ||
| return 1; | ||
| } | ||
|
|
||
| Console.WriteLine(" [Child] Captured propagated environment variables:"); | ||
| WritePropagationFields("Child", carrier); | ||
| Console.WriteLine(); | ||
|
|
||
| WriteProcessContext("Child", activity, parentContext.ActivityContext, Baggage.Current); | ||
|
|
||
| return 0; | ||
| } | ||
|
|
||
| private static ActivityListener CreateActivityListener() | ||
| { | ||
| var listener = new ActivityListener | ||
| { | ||
| ShouldListenTo = static source => source.Name == ActivitySourceName, | ||
| Sample = static (ref _) => ActivitySamplingResult.AllDataAndRecorded, | ||
| SampleUsingParentId = static (ref _) => ActivitySamplingResult.AllDataAndRecorded, | ||
| }; | ||
|
|
||
| ActivitySource.AddActivityListener(listener); | ||
|
|
||
| return listener; | ||
| } | ||
|
|
||
| private static ProcessStartInfo CreateChildStartInfo() | ||
| { | ||
| var processPath = Environment.ProcessPath | ||
| ?? throw new InvalidOperationException("The current process path is unavailable."); | ||
|
|
||
| var entryAssemblyPath = Assembly.GetEntryAssembly()?.Location | ||
| ?? throw new InvalidOperationException("The entry assembly path is unavailable."); | ||
|
|
||
| var fileName = Path.GetFileNameWithoutExtension(processPath); | ||
|
|
||
| var startInfo = new ProcessStartInfo(processPath) | ||
| { | ||
| RedirectStandardError = true, | ||
| RedirectStandardOutput = true, | ||
| UseShellExecute = false, | ||
| }; | ||
|
|
||
| if (string.Equals(fileName, "dotnet", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| startInfo.ArgumentList.Add(entryAssemblyPath); | ||
| } | ||
|
|
||
| startInfo.ArgumentList.Add(ChildModeArgument); | ||
|
|
||
| return startInfo; | ||
| } | ||
|
|
||
| private static void CopyCurrentEnvironment(IDictionary<string, string?> environment) | ||
| { | ||
| foreach (DictionaryEntry variable in Environment.GetEnvironmentVariables()) | ||
| { | ||
| environment[(string)variable.Key] = variable.Value?.ToString(); | ||
| } | ||
| } | ||
|
|
||
| private static void WriteProcessContext( | ||
| string role, | ||
| Activity activity, | ||
| ActivityContext parentContext, | ||
| Baggage baggage) | ||
| { | ||
| string indent = role is "Parent" ? string.Empty : " "; | ||
|
|
||
| Console.WriteLine($"{indent}[{role}] ProcessId: {Environment.ProcessId}"); | ||
| Console.WriteLine($"{indent}[{role}] TraceId: {activity.TraceId}"); | ||
| Console.WriteLine($"{indent}[{role}] SpanId: {activity.SpanId}"); | ||
| Console.WriteLine($"{indent}[{role}] ParentSpanId: {FormatSpanId(activity.ParentSpanId)}"); | ||
|
|
||
| if (parentContext != default) | ||
| { | ||
| Console.WriteLine($"{indent}[{role}] ExtractedParentTraceId: {parentContext.TraceId}"); | ||
| Console.WriteLine($"{indent}[{role}] ExtractedParentSpanId: {FormatSpanId(parentContext.SpanId)}"); | ||
| } | ||
|
|
||
| Console.WriteLine($"{indent}[{role}] Baggage: {FormatBaggage(baggage)}"); | ||
|
|
||
| static string FormatSpanId(ActivitySpanId spanId) | ||
| { | ||
| return spanId == default ? "<none>" : spanId.ToString(); | ||
| } | ||
|
|
||
| static string FormatBaggage(Baggage baggage) | ||
| { | ||
| if (baggage.Count == 0) | ||
| { | ||
| return "<empty>"; | ||
| } | ||
|
|
||
| var builder = new StringBuilder(); | ||
|
|
||
| foreach (var item in baggage.GetBaggage()) | ||
| { | ||
| if (builder.Length > 0) | ||
| { | ||
| builder.Append(", "); | ||
| } | ||
|
|
||
| builder.Append(item.Key); | ||
| builder.Append('='); | ||
| builder.Append(item.Value); | ||
| } | ||
|
|
||
| return builder.ToString(); | ||
| } | ||
| } | ||
|
|
||
| private static void WritePropagationFields<T>(string role, T carrier) | ||
| where T : IEnumerable<KeyValuePair<string, string?>> | ||
| { | ||
| if (Propagator.Fields is not { Count: > 0 } fields) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| string indent = role is "Parent" ? string.Empty : " "; | ||
|
|
||
| foreach (var field in fields) | ||
| { | ||
| var normalized = EnvironmentVariableCarrier.NormalizeKey(field); | ||
| var values = EnvironmentVariableCarrier.Get(carrier, field); | ||
| var value = values?.FirstOrDefault(); | ||
|
|
||
| Console.WriteLine($"{indent}[{role}] {normalized}={value ?? "<not set>"}"); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier | ||
| static OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier.Capture() -> System.Collections.Generic.IReadOnlyDictionary<string!, string?>! | ||
| static OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier.Capture(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string!, string?>>! environmentVariables) -> System.Collections.Generic.IReadOnlyDictionary<string!, string?>! | ||
| static OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier.Get<T>(T carrier, string! key) -> System.Collections.Generic.IEnumerable<string!>? | ||
| static OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier.NormalizeKey(string! key) -> string! | ||
| static OpenTelemetry.Context.Propagation.EnvironmentVariableCarrier.Set<T>(T carrier, string! key, string! value) -> void |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.