Skip to content

Commit 2646259

Browse files
committed
absorbing HTTP tracking changes
1 parent f1350ba commit 2646259

File tree

7 files changed

+183
-93
lines changed

7 files changed

+183
-93
lines changed

src/WebJobs.Script.WebHost/Controllers/FunctionsController.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,19 @@ public IActionResult Invoke(string name, [FromBody] FunctionInvocation invocatio
108108
{
109109
{ inputParameter.Name, invocation.Input }
110110
};
111-
Task.Run(() => scriptHost.CallAsync(function.Name, arguments));
111+
112+
Task.Run(async () =>
113+
{
114+
IDictionary<string, object> loggerScope = new Dictionary<string, object>
115+
{
116+
{ "MS_IgnoreActivity", null }
117+
};
118+
119+
using (_logger.BeginScope(loggerScope))
120+
{
121+
await scriptHost.CallAsync(function.Name, arguments);
122+
}
123+
});
112124

113125
return Accepted();
114126
}

src/WebJobs.Script.WebHost/WebJobsScriptHostService.cs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
using System.Linq;
77
using System.Threading;
88
using System.Threading.Tasks;
9+
using Microsoft.ApplicationInsights.AspNetCore;
10+
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
11+
using Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId;
912
using Microsoft.Azure.WebJobs.Logging;
1013
using Microsoft.Azure.WebJobs.Script.Scale;
1114
using Microsoft.Extensions.DependencyInjection;
@@ -34,6 +37,8 @@ public class WebJobsScriptHostService : IHostedService, IScriptHostManager, IDis
3437
private int _hostStartCount;
3538
private bool _disposed = false;
3639

40+
private static IDisposable _requestTrackingModule;
41+
3742
public WebJobsScriptHostService(IOptionsMonitor<ScriptApplicationHostOptions> applicationHostOptions, IScriptHostBuilder scriptHostBuilder, ILoggerFactory loggerFactory, IServiceProvider rootServiceProvider,
3843
IServiceScopeFactory rootScopeFactory, IScriptWebHostEnvironment scriptWebHostEnvironment, IEnvironment environment,
3944
HostPerformanceManager hostPerformanceManager, IOptions<HostHealthMonitorOptions> healthMonitorOptions)
@@ -43,6 +48,9 @@ public WebJobsScriptHostService(IOptionsMonitor<ScriptApplicationHostOptions> ap
4348
throw new ArgumentNullException(nameof(loggerFactory));
4449
}
4550

51+
// This will no-op if already initialized.
52+
InitializeApplicationInsightsRequestTracking();
53+
4654
_applicationHostOptions = applicationHostOptions ?? throw new ArgumentNullException(nameof(applicationHostOptions));
4755
_scriptWebHostEnvironment = scriptWebHostEnvironment ?? throw new ArgumentNullException(nameof(scriptWebHostEnvironment));
4856
_rootServiceProvider = rootServiceProvider;
@@ -144,6 +152,13 @@ private async Task StartHostAsync(CancellationToken cancellationToken, int attem
144152

145153
LogInitialization(localHost, isOffline, attemptCount, ++_hostStartCount);
146154

155+
if (!_scriptWebHostEnvironment.InStandbyMode)
156+
{
157+
// At this point we know that App Insights is initialized (if being used), so we
158+
// can dispose this early request tracking module, which forces our new one to take over.
159+
DisposeRequestTrackingModule();
160+
}
161+
147162
await _host.StartAsync(cancellationToken);
148163

149164
if (!startupMode.HasFlag(JobHostStartupMode.HandlingError))
@@ -231,6 +246,12 @@ await Utility.DelayWithBackoffAsync(attemptCount, cancellationToken, min: TimeSp
231246
}
232247
}
233248

249+
private void DisposeRequestTrackingModule()
250+
{
251+
_requestTrackingModule?.Dispose();
252+
_requestTrackingModule = null;
253+
}
254+
234255
public async Task StopAsync(CancellationToken cancellationToken)
235256
{
236257
_startupLoopTokenSource?.Cancel();
@@ -418,6 +439,33 @@ private async Task Orphan(IHost instance, ILogger logger, CancellationToken canc
418439
}
419440
}
420441

442+
private static void InitializeApplicationInsightsRequestTracking()
443+
{
444+
if (_requestTrackingModule != null)
445+
{
446+
return;
447+
}
448+
449+
// Requests may come in before the JobHost has started (like during cold starts), which means
450+
// they will not be properly tracked by Application Insights because there's nothing listening
451+
// for them yet. This wires up the request tracking module with default values to catch those
452+
// events and properly create an Activity. Once the JobHost has started, we dispose this and the
453+
// JobHost tracking module takes over.
454+
var module = new RequestTrackingTelemetryModule(new ApplicationInsightsApplicationIdProvider())
455+
{
456+
CollectionOptions = new RequestCollectionOptions
457+
{
458+
TrackExceptions = false,
459+
EnableW3CDistributedTracing = true,
460+
InjectResponseHeaders = true
461+
}
462+
};
463+
464+
module.Initialize(null);
465+
466+
_requestTrackingModule = module;
467+
}
468+
421469
protected virtual void Dispose(bool disposing)
422470
{
423471
if (!_disposed)
@@ -426,6 +474,7 @@ protected virtual void Dispose(bool disposing)
426474
{
427475
_startupLoopTokenSource?.Dispose();
428476
_hostRestartSemaphore.Dispose();
477+
DisposeRequestTrackingModule();
429478
}
430479
_disposed = true;
431480
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the MIT License. See License.txt in the project root for license information.
3+
4+
using Microsoft.Azure.WebJobs.Logging.ApplicationInsights;
5+
6+
namespace Microsoft.Azure.WebJobs.Script.Diagnostics
7+
{
8+
internal class FunctionsSdkVersionProvider : ISdkVersionProvider
9+
{
10+
public string GetSdkVersion()
11+
{
12+
return $"azurefunctions: {ScriptHost.Version}";
13+
}
14+
}
15+
}

src/WebJobs.Script/ScriptHostBuilderExtensions.cs

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,8 @@
33

44
using System;
55
using System.Collections.Generic;
6-
using Microsoft.ApplicationInsights;
76
using Microsoft.ApplicationInsights.DependencyCollector;
87
using Microsoft.ApplicationInsights.Extensibility;
9-
using Microsoft.ApplicationInsights.Extensibility.Implementation;
108
using Microsoft.Azure.WebJobs.Host.Executors;
119
using Microsoft.Azure.WebJobs.Logging;
1210
using Microsoft.Azure.WebJobs.Logging.ApplicationInsights;
@@ -242,19 +240,7 @@ internal static void ConfigureApplicationInsights(HostBuilderContext context, IL
242240
builder.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
243241
builder.Services.ConfigureOptions<ApplicationInsightsLoggerOptionsSetup>();
244242

245-
builder.Services.AddSingleton<ISdkVersionProvider, ApplicationInsightsSdkVersionProvider>();
246-
247-
// Override the default SdkVersion with the functions key
248-
builder.Services.AddSingleton<TelemetryClient>(provider =>
249-
{
250-
TelemetryConfiguration configuration = provider.GetService<TelemetryConfiguration>();
251-
TelemetryClient client = new TelemetryClient(configuration);
252-
253-
ISdkVersionProvider versionProvider = provider.GetService<ISdkVersionProvider>();
254-
client.Context.GetInternalContext().SdkVersion = versionProvider.GetSdkVersion();
255-
256-
return client;
257-
});
243+
builder.Services.AddSingleton<ISdkVersionProvider, FunctionsSdkVersionProvider>();
258244

259245
if (SystemEnvironment.Instance.IsPlaceholderModeEnabled())
260246
{
@@ -267,6 +253,12 @@ internal static void ConfigureApplicationInsights(HostBuilderContext context, IL
267253
break;
268254
}
269255
}
256+
257+
// Disable auto-http tracking when in placeholder mode.
258+
builder.Services.Configure<ApplicationInsightsLoggerOptions>(o =>
259+
{
260+
o.HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection = false;
261+
});
270262
}
271263
}
272264
}

src/WebJobs.Script/WebJobs.Script.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@
4141
<PackageReference Include="Microsoft.Azure.Functions.JavaWorker" Version="1.3.1-SNAPSHOT" />
4242
<PackageReference Include="Microsoft.Azure.Functions.NodeJsWorker" Version="1.0.2" />
4343
<PackageReference Include="Microsoft.Azure.Functions.PowerShellWorker" Version="0.1.90-preview" />
44-
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.6" />
44+
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.7-11551" />
4545
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.2" />
4646
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.2" />
47-
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.6" />
47+
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.7-11551" />
4848
<PackageReference Include="Microsoft.Build" Version="15.8.166" />
4949
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="2.8.2" />
5050
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="2.1.0" />

0 commit comments

Comments
 (0)