Skip to content
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

TEST PR - DO NOT MERGE #2774

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
ea80daa
wip
tippmar-nr Aug 13, 2024
75422d6
Initial POC implementation is working
tippmar-nr Aug 13, 2024
e9ce99f
New instrumentation stuff
tippmar-nr Aug 13, 2024
e20c363
app name tweak
tippmar-nr Aug 14, 2024
3d511ad
cleanup
tippmar-nr Aug 14, 2024
494684c
More cleanup
tippmar-nr Aug 14, 2024
61201f4
added more trigger types
tippmar-nr Aug 14, 2024
707c3d9
Cleanup, optimization
tippmar-nr Aug 14, 2024
c967297
Updated Serilog to latest everywhere
tippmar-nr Aug 16, 2024
692236d
Minor cleanup
tippmar-nr Aug 16, 2024
fa2dd3e
Fix ilrepack issues for serilog
tippmar-nr Aug 16, 2024
ecc964a
Updated Serilog to latest everywhere
tippmar-nr Aug 16, 2024
a32b438
Fix ilrepack issues for serilog
tippmar-nr Aug 16, 2024
7e7c482
Refactor GuidGenerator to work around ILRepack of System.Diagnostics.…
tippmar-nr Aug 16, 2024
f61dee6
Null checking
tippmar-nr Aug 16, 2024
cf4f926
Merge branch 'chore/update-serilog' into poc/azure-function-instrumen…
tippmar-nr Aug 16, 2024
1304087
Visibility bypasser caching
tippmar-nr Aug 19, 2024
a4a0e77
Composite tests for GuidGenerator changes
tippmar-nr Aug 19, 2024
7a1cd92
Fixes for GuidGenerator unit testing
tippmar-nr Aug 19, 2024
6406d92
Revert composite test changes, exclude GuidGenerator
tippmar-nr Aug 20, 2024
1271df5
Merge branch 'main' into chore/update-serilog
tippmar-nr Aug 20, 2024
601a177
Reverting a change
tippmar-nr Aug 20, 2024
d3c0a22
Merge branch 'chore/update-serilog' of https://github.com/newrelic/ne…
tippmar-nr Aug 20, 2024
1e892ed
Merge branch 'chore/update-serilog' into poc/azure-function-instrumen…
tippmar-nr Aug 20, 2024
725c4ed
Limit profiler logging to INFO or higher when in Azure Function mode
tippmar-nr Aug 20, 2024
ba295aa
chore: Update Profiler NuGet Package Reference to v10.28.0.40 (#2703)
github-actions[bot] Aug 20, 2024
e618ce9
Merge branch 'poc/azure-function-instrumention/nugetupdate' into poc/…
tippmar-nr Aug 20, 2024
2d90a9e
Merge latest from main, resolve conflicts
tippmar-nr Aug 20, 2024
0279e83
Profiler updates for azure function detection
tippmar-nr Aug 20, 2024
d0b2c59
Merge latest from main
tippmar-nr Aug 20, 2024
5dc44b4
Modify app name priority for azure function
tippmar-nr Aug 20, 2024
d090551
log message oops
tippmar-nr Aug 21, 2024
527130b
chore: Update Profiler NuGet Package Reference to v10.29.0.32 (#2705)
github-actions[bot] Aug 21, 2024
6b66651
Fix logic for determining whether to instrument in azure function mode
tippmar-nr Aug 22, 2024
5bb20d0
Merge branch 'poc/azure-function-instrumentation' of https://github.c…
tippmar-nr Aug 22, 2024
d207723
Azure vendor info check wasn't correctly implemented
tippmar-nr Aug 26, 2024
6870167
ReportedConfig tweak
tippmar-nr Aug 26, 2024
3ec5ddb
Merge branch 'poc/azure-function-instrumentation' into feature/azure-…
jaffinito Aug 27, 2024
129cf1f
Fixed up resourse groups and some minor changes all around.
jaffinito Aug 29, 2024
9d739b5
Feature work: Azure Function Mode Config (#2723)
tippmar-nr Aug 30, 2024
fd03d84
Azure functions: Unit tests (#2726)
tippmar-nr Aug 30, 2024
5f48908
Finish remaining todos and initial code cleanup. (#2725)
jaffinito Aug 30, 2024
9483c5d
Merge branch 'main' into feature/azure-functions
tippmar-nr Sep 3, 2024
37d155e
Feature work: Azure functions integration test framework (#2737)
tippmar-nr Sep 5, 2024
9911b8a
Merge remote-tracking branch 'origin/main' into feature/azure-functions
tippmar-nr Sep 5, 2024
e41c19e
Feature work: More integration tests (#2739)
tippmar-nr Sep 6, 2024
5464347
Feature work: Disable AspNetCore middleware wrapper (#2740)
tippmar-nr Sep 9, 2024
e53ecd1
profiler unit test fix
tippmar-nr Sep 9, 2024
d87e318
Merge branch 'feature/azure-functions' of https://github.com/newrelic…
tippmar-nr Sep 9, 2024
557a867
Feature work: Added QueueTrigger function to integration tests (#2745)
tippmar-nr Sep 9, 2024
e2dadbb
Check azure site name for null and don't use as app name
tippmar-nr Sep 10, 2024
d3c8bb7
Parse the request method / path and response status code for HttpTrig…
tippmar-nr Sep 10, 2024
2161ca0
Merge from main, resolve conflicts
tippmar-nr Sep 17, 2024
9d770af
Cleanup
tippmar-nr Sep 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions src/Agent/NewRelic/Agent/Core/Config/Configuration.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.6.0.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.1" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

using Microsoft.AspNetCore.Http;
using NewRelic.Agent.Api;
using NewRelic.Agent.Extensions.Providers.Wrapper;

public class FunctionsHttpProxyingMiddlewareWrapper : IWrapper
{
private const string WrapperName = "FunctionsHttpProxyingMiddlewareWrapper";

public bool IsTransactionRequired => false;

public CanWrapResponse CanWrap(InstrumentedMethodInfo methodInfo)
{
return new CanWrapResponse(WrapperName.Equals(methodInfo.RequestedWrapperName));
}

/// <summary>
/// Gets request method / path for Azure function HttpTrigger invocations
/// in apps that use the Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore package
/// </summary>
public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
{
if (agent.Configuration.AzureFunctionModeEnabled)
{
switch (instrumentedMethodCall.MethodCall.Method.MethodName)
{
case "AddHttpContextToFunctionContext":
var httpContext = (HttpContext)instrumentedMethodCall.MethodCall.MethodArguments[1];

agent.CurrentTransaction.SetRequestMethod(httpContext.Request.Method);
agent.CurrentTransaction.SetUri(httpContext.Request.Path);
break;
// not needed at present for getting status code, but keep in case we need to get more from httpContext - also update instrumentation.xml
//case "TryHandleHttpResult":
// object result = instrumentedMethodCall.MethodCall.MethodArguments[0];
// httpContext = (HttpContext)instrumentedMethodCall.MethodCall.MethodArguments[2];
// bool isInvocationResult = (bool)instrumentedMethodCall.MethodCall.MethodArguments[3];

// agent.CurrentTransaction.SetHttpResponseStatusCode(httpContext.Response.StatusCode);
// break;
//case "TryHandleOutputBindingsHttpResult":
// httpContext = (HttpContext)instrumentedMethodCall.MethodCall.MethodArguments[1];
// agent.CurrentTransaction.SetHttpResponseStatusCode(httpContext.Response.StatusCode);
// break;
}
}

return Delegates.NoOp;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,19 @@ SPDX-License-Identifier: Apache-2.0
<exactMethodMatcher methodName="Build" />
</match>
</tracerFactory>

<tracerFactory name="FunctionsHttpProxyingMiddlewareWrapper">
<match assemblyName="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" className="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware">
<exactMethodMatcher methodName="AddHttpContextToFunctionContext" />
</match>
<!-- save in case we need these later
<match assemblyName="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" className="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware">
<exactMethodMatcher methodName="TryHandleHttpResult" />
</match>
<match assemblyName="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" className="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware">
<exactMethodMatcher methodName="TryHandleOutputBindingsHttpResult" />
</match>
-->
</tracerFactory>
</instrumentation>
</extension>
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using NewRelic.Agent.Api;
using NewRelic.Agent.Extensions.Providers.Wrapper;
Expand Down Expand Up @@ -78,6 +80,12 @@ public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall ins
transaction.AddFaasAttribute("faas.trigger", functionDetails.Trigger);
transaction.AddFaasAttribute("faas.invocation_id", functionDetails.InvocationId);

if (functionDetails.IsWebTrigger && !string.IsNullOrEmpty(functionDetails.RequestMethod))
{
transaction.SetRequestMethod(functionDetails.RequestMethod);
transaction.SetUri(functionDetails.RequestPath);
}

var segment = transaction.StartTransactionSegment(instrumentedMethodCall.MethodCall, functionDetails.FunctionName);

return Delegates.GetAsyncDelegateFor<Task>(
Expand All @@ -96,6 +104,35 @@ void InvokeFunctionAsyncResponse(Task responseTask)
transaction.NoticeError(responseTask.Exception);
return;
}

if (functionDetails.IsWebTrigger)
{
// GetInvocationResult is a static extension method
// there are multiple GetInvocationResult methods in this type; we want the one without any generic parameters
Type type = functionContext.GetType().Assembly.GetType("Microsoft.Azure.Functions.Worker.FunctionContextBindingFeatureExtensions");
var getInvocationResultMethod = type.GetMethods().Single(m => m.Name == "GetInvocationResult" && !m.ContainsGenericParameters);

dynamic invocationResult = getInvocationResultMethod.Invoke(null, new[] { functionContext });
var result = invocationResult?.Value;

// the result always seems to be of this type regardless of whether the app
// uses the Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore package or not
var resultTypeName = result?.GetType().Name;
if (resultTypeName == "GrpcHttpResponseData")
{
transaction.SetHttpResponseStatusCode((int)result.StatusCode);
}
else
{
agent.Logger.Debug($"Unexpected Azure Function invocationResult.Value type '{resultTypeName ?? "(null)"}' - unable to set http response status code.");
}
}

}
catch (Exception ex)
{
agent.Logger.Error(ex, "Error processing Azure Function response.");
throw;
}
finally
{
Expand All @@ -108,7 +145,11 @@ void InvokeFunctionAsyncResponse(Task responseTask)

internal class FunctionDetails
{
private static ConcurrentDictionary<string, string> _functionTriggerCache = new();
private static MethodInfo _bindFunctionInputAsync;
private static MethodInfo _genericFunctionInputBindingFeatureGetter;
private static bool? _hasAspNetCoreExtensionsReference;

private static readonly ConcurrentDictionary<string, string> _functionTriggerCache = new();
private static Func<object, object> _functionDefinitionGetter;
private static Func<object, object> _parametersGetter;
private static Func<object, IReadOnlyDictionary<string, object>> _propertiesGetter;
Expand Down Expand Up @@ -179,24 +220,98 @@ public FunctionDetails(dynamic functionContext, IAgent agent)
{
Trigger = trigger;
}

if (IsWebTrigger)
{
ParseRequestParameters(agent, functionContext);
}
}
catch(Exception ex)
catch (Exception ex)
{
agent.Logger.Error(ex, "Error getting Azure Function details.");
throw;
}
}

private void ParseRequestParameters(IAgent agent, dynamic functionContext)
{
if (!_hasAspNetCoreExtensionsReference.HasValue)
{
// see if the Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore assembly is in the list of loaded assemblies
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == "Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore");
_hasAspNetCoreExtensionsReference = assembly != null;

if (_hasAspNetCoreExtensionsReference.Value)
agent.Logger.Debug("Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore assembly is loaded; not parsing request parameters in InvokeFunctionAsyncWrapper.");
}

// don't parse request parameters here if the Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore assembly is loaded.
// If it is loaded, parsing occurs over in FunctionsHttpProxyingMiddlewareWrapper
if (_hasAspNetCoreExtensionsReference.Value)
{
return;
}

object features = functionContext.Features;

if (_genericFunctionInputBindingFeatureGetter == null) // cache the methodinfo lookups for performance
{
var get = features.GetType().GetMethod("Get");
if (get != null)
{
_genericFunctionInputBindingFeatureGetter = get.MakeGenericMethod(features.GetType().Assembly.GetType("Microsoft.Azure.Functions.Worker.Context.Features.IFunctionInputBindingFeature"));
}
else
{
agent.Logger.Debug("Unable to find FunctionContext.Features.Get method; unable to parse request parameters.");
return;
}

var bindFunctionInputType = features.GetType().Assembly.GetType("Microsoft.Azure.Functions.Worker.Context.Features.IFunctionInputBindingFeature");
if (bindFunctionInputType == null)
{
agent.Logger.Debug("Unable to find IFunctionInputBindingFeature type; unable to parse request parameters.");
return;
}
_bindFunctionInputAsync = bindFunctionInputType.GetMethod("BindFunctionInputAsync");
if (_bindFunctionInputAsync == null)
{
agent.Logger.Debug("Unable to find BindFunctionInputAsync method; unable to parse request parameters.");
return;
}
}

if (_genericFunctionInputBindingFeatureGetter != null)
{
// Get the input binding feature and bind the input from the function context
var inputBindingFeature = _genericFunctionInputBindingFeatureGetter.Invoke(features, new object[] { });
dynamic valueTask = _bindFunctionInputAsync.Invoke(inputBindingFeature, new object[] { functionContext });
valueTask.AsTask().Wait();
var inputArguments = valueTask.Result.Values;
var reqData = inputArguments[0];

if (reqData != null && reqData.GetType().Name == "GrpcHttpRequestData" && !string.IsNullOrEmpty(reqData.Method))
{
RequestMethod = reqData.Method;
Uri uri = reqData.Url;
RequestPath = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
}
}
}

public bool IsValid()
{
return !string.IsNullOrEmpty(FunctionName) && !string.IsNullOrEmpty(Trigger) && !string.IsNullOrEmpty(InvocationId);
}

public string FunctionName { get; private set; }
public string FunctionName { get; }

public string Trigger { get; private set; }
public string InvocationId { get; private set; }
public string Trigger { get; }
public string InvocationId { get; }
public bool IsWebTrigger => Trigger == "http";
public string RequestMethod { get; private set; }
public string RequestPath { get; private set; }
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public void Test()

var expectedAgentAttributes = new Dictionary<string, string>
{
{ "request.uri", "/Unknown"}
{ "request.uri", "/api/httpTriggerFunctionUsingAspNetCorePipeline"}
};

var transactionTraceExpectedAttributes = new Dictionary<string, object>()
Expand Down
Loading