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

Nservicebus7 feature branch #857

Merged
merged 13 commits into from
Dec 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/all_solutions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ jobs:
runs-on: windows-2019
strategy:
matrix:
namespace: [ CosmosDB, Couchbase, MongoDB, Msmq, MsSql, MySql, NServiceBus, Oracle, Postgres, RabbitMq, Redis ]
namespace: [ CosmosDB, Couchbase, MongoDB, Msmq, MsSql, MySql, NServiceBus, NServiceBus5, Oracle, Postgres, RabbitMq, Redis ]
fail-fast: false # we don't want one test failure in one namespace to kill the other runs

env:
Expand Down
2 changes: 2 additions & 0 deletions build/ArtifactBuilder/CoreAgentComponents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ protected override void CreateAgentComponents()
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.RabbitMq.dll",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.Sql.dll",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.StackExchangeRedis.dll",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.NServiceBus.dll",
};

var wrapperXmls = new[]
Expand All @@ -49,6 +50,7 @@ protected override void CreateAgentComponents()
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.RabbitMq.Instrumentation.xml",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.Sql.Instrumentation.xml",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.StackExchangeRedis.Instrumentation.xml",
$@"{SourceHomeBuilderPath}\extensions\NewRelic.Providers.Wrapper.NServiceBus.Instrumentation.xml",
};

ExtensionXsd = $@"{SourceHomeBuilderPath}\extensions\extension.xsd";
Expand Down
1 change: 1 addition & 0 deletions src/Agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased] changes
### New Features
* NServiceBus versions 6 and 7 are now supported in .NET Framework and .NET Core. ([#857](https://github.com/newrelic/newrelic-dotnet-agent/pull/857))

### Fixes
* Fixes issue [#36](https://github.com/newrelic/newrelic-dotnet-agent/issues/36): Total system memory will now be correctly reported on Linux. ([#855](https://github.com/newrelic/newrelic-dotnet-agent/pull/855))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,6 @@ public static AfterWrappedMethodDelegate GetDelegateFor(Action onComplete = null
};
}

[Obsolete("Use GetAsyncDelegateFor<T>")]
public static AfterWrappedMethodDelegate GetAsyncDelegateFor(IAgent agent, ISegment segment)
{
return GetAsyncDelegateFor<Task>(agent, segment, TaskContinueWithOption.UseSynchronizationContext);
}

public static AfterWrappedMethodDelegate GetAsyncDelegateFor<T>(IAgent agent, ISegment segment) where T : Task
{
return GetAsyncDelegateFor<T>(agent, segment, TaskContinueWithOption.UseSynchronizationContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,27 @@ SPDX-License-Identifier: Apache-2.0
-->
<extension xmlns="urn:newrelic-extension">
<instrumentation>
<tracerFactory>
<tracerFactory name="ReceiveMessageWrapper">
<match assemblyName="NServiceBus.Core" className="NServiceBus.InvokeHandlersBehavior">
<exactMethodMatcher methodName="Invoke" parameters="NServiceBus.Pipeline.Contexts.IncomingContext,System.Action" />
</match>
</tracerFactory>
<tracerFactory>
<tracerFactory name="SendMessageWrapper">
<match assemblyName="NServiceBus.Core" className="NServiceBus.Unicast.UnicastBus">
<exactMethodMatcher methodName="SendMessage" parameters="NServiceBus.Unicast.SendOptions,NServiceBus.Unicast.Messages.LogicalMessage" />
</match>
</tracerFactory>

<!--NSB 6 and above instrumentation points-->
<tracerFactory name="LoadHandlersConnectorWrapper">
<match assemblyName="NServiceBus.Core" className="NServiceBus.LoadHandlersConnector">
<exactMethodMatcher methodName="Invoke" parameters="NServiceBus.Pipeline.IIncomingLogicalMessageContext,System.Func`2[NServiceBus.Pipeline.IInvokeHandlerContext,System.Threading.Tasks.Task]" />
</match>
</tracerFactory>
<tracerFactory name="PipelineWrapper">
<match assemblyName="NServiceBus.Core" className="NServiceBus.Pipeline`1">
<exactMethodMatcher methodName="Invoke" parameters="!0" />
</match>
</tracerFactory>
</instrumentation>
</extension>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Threading.Tasks;
using NewRelic.Agent.Api;
using NewRelic.Agent.Extensions.Providers.Wrapper;

namespace NewRelic.Providers.Wrapper.NServiceBus
{
/// <summary>
/// This wrapper instruments message receive for NServiceBus v6+ library.
/// </summary>
public class LoadHandlersConnectorWrapper : IWrapper
{
private const string BrokerVendorName = "NServiceBus";
private const string WrapperName = "LoadHandlersConnectorWrapper";

public bool IsTransactionRequired => false;

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

public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall,
IAgent agent, ITransaction transaction)
{
var incomingLogicalMessageContext = instrumentedMethodCall.MethodCall.MethodArguments[0];

var message = NServiceBusHelpers.GetMessageFromIncomingLogicalMessageContext(incomingLogicalMessageContext);
if (message == null)
{
throw new NullReferenceException("logicalMessage");
}

var queueName = NServiceBusHelpers.TryGetQueueNameLoadHandlersConnector(message);

//If the transaction does not exist.
if (!transaction.IsValid)
{
transaction = agent.CreateTransaction(
destinationType: MessageBrokerDestinationType.Queue,
brokerVendorName: BrokerVendorName,
destination: queueName);

transaction.AttachToAsync();
transaction.DetachFromPrimary(); //Remove from thread-local type storage
}

var segment = transaction.StartMessageBrokerSegment(instrumentedMethodCall.MethodCall, MessageBrokerDestinationType.Queue, MessageBrokerAction.Consume, BrokerVendorName, queueName);

var headers = NServiceBusHelpers.GetHeadersFromIncomingLogicalMessageContext(incomingLogicalMessageContext);
NServiceBusHelpers.ProcessHeaders(headers, agent);

void OnComplete(Task task)
{
if (task == null)
{
return;
}

if (task.Status == TaskStatus.Faulted)
{
transaction.NoticeError(task.Exception);
}

if (task.Status == TaskStatus.RanToCompletion
|| task.Status == TaskStatus.Canceled
|| task.Status == TaskStatus.Faulted)
{
segment.End();
transaction.End();
}
}

return Delegates.GetAsyncDelegateFor<Task>(agent, segment, false, OnComplete);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
<PropertyGroup>
<TargetFramework>net45</TargetFramework>
<TargetFrameworks>net45;netstandard2.0</TargetFrameworks>
<AssemblyName>NewRelic.Providers.Wrapper.NServiceBus</AssemblyName>
<RootNamespace>NewRelic.Providers.Wrapper.NServiceBus</RootNamespace>
<Description>NServiceBus Wrapper Provider for New Relic .NET Agent</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NServiceBus" Version="5.2.0" />
</ItemGroup>
<ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net45'">
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Content Include="Instrumentation.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Collections.Generic;
using NewRelic.Agent.Api;
using NewRelic.Agent.Extensions.Providers.Wrapper;
using NewRelic.Reflection;

namespace NewRelic.Providers.Wrapper.NServiceBus
{
public class NServiceBusHelpers
{
private static Func<object, Dictionary<string, string>> _getHeadersSendMessageFunc;
private static Func<object, Dictionary<string, string>> _getHeadersPipelineFunc;
private static Func<object, Dictionary<string, string>> _getHeadersReceiveMessageFunc;

private static Func<object, object> _getIncomingLogicalMessageFunc;

private static Func<object, object> _getMessageFromIncomingLogicalMessageContextFunc;
private static Func<object, Dictionary<string, string>> _getHeadersFromIncomingLogicalMessageContextFunc;

private static Func<object, object> _getMessageFromOutgoingSendContextFunc;
private static Func<object, object> _getMessageFromOutgoingPublishContextFunc;

public const string OutgoingSendContextTypeName = "NServiceBus.OutgoingSendContext";
public const string OutgoingPublishContextTypeName = "NServiceBus.OutgoingPublishContext";


private static Func<object, Type> _getMessageTypeSendMessageFunc;
private static Func<object, Type> _getMessageTypePipelineFunc;
private static Func<object, Type> _getMessageTypeReceiveMessageFunc;
private static Func<object, Type> _getMessageTypeLoadHandlersConnectorFunc;

#region Wrapper Specific Helpers - does not depend on other bypasser results

public static object GetMessageFromOutgoingContext(object outgoingContext)
{
if (outgoingContext.GetType().FullName == OutgoingSendContextTypeName)
{
var getMessageFromOutgoingSendContextFunc = _getMessageFromOutgoingSendContextFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(outgoingContext.GetType(), "Message");
return getMessageFromOutgoingSendContextFunc(outgoingContext);
}
else if (outgoingContext.GetType().FullName == OutgoingPublishContextTypeName)
{
var getMessageFromOutgoingPublishContextFunc = _getMessageFromOutgoingPublishContextFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(outgoingContext.GetType(), "Message");
return getMessageFromOutgoingPublishContextFunc(outgoingContext);
}

return null;
}

public static object GetMessageFromIncomingLogicalMessageContext(object incomingLogicalMessageContext)
{
var getLogicalMessageContextFunc = _getMessageFromIncomingLogicalMessageContextFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(incomingLogicalMessageContext.GetType(), "Message");
return getLogicalMessageContextFunc(incomingLogicalMessageContext);
}


public static Dictionary<string, string> GetHeadersFromIncomingLogicalMessageContext(object incomingLogicalMessageContext)
{
var getHeadersFromIncomingLogicalMessageContextFunc = _getHeadersFromIncomingLogicalMessageContextFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Dictionary<string, string>>(incomingLogicalMessageContext.GetType(), "Headers");
return getHeadersFromIncomingLogicalMessageContextFunc(incomingLogicalMessageContext);
}

public static object GetIncomingLogicalMessage(object incomingContext)
{
var getLogicalMessageFunc = _getIncomingLogicalMessageFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<object>(incomingContext.GetType(), "IncomingLogicalMessage");
return getLogicalMessageFunc(incomingContext);
}

public static Dictionary<string, string> GetHeadersReceiveMessage(object logicalMessage)
{
var getHeadersReceiveMessageFunc = _getHeadersReceiveMessageFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Dictionary<string, string>>(logicalMessage.GetType(), "Headers");
return getHeadersReceiveMessageFunc(logicalMessage);
}

#endregion

// receive - load; no bypaser in here
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor typo

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix in a later PR..

public static void ProcessHeaders(Dictionary<string, string> headers, IAgent agent)
{
if (headers == null)
{
return;
}

agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, GetHeaderValue, TransportType.HTTP);

static IEnumerable<string> GetHeaderValue(Dictionary<string, string> carrier, string key)
{
if (carrier != null)
{
foreach (var item in carrier)
{
if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
{
return new string[] { item.Value };
}
}
}
return null;
}
}

public static void CreateOutboundHeadersSendMessage(IAgent agent, object logicalMessage)
{
var getHeadersSendMessageFunc = _getHeadersSendMessageFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Dictionary<string, string>>(logicalMessage.GetType(), "Headers");
CreateOutboundHeaders(agent, logicalMessage, getHeadersSendMessageFunc);
}

public static void CreateOutboundHeadersPipeline(IAgent agent, object logicalMessage)
{
var getHeadersPipelineFunc = _getHeadersPipelineFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Dictionary<string, string>>(logicalMessage.GetType(), "Headers");
CreateOutboundHeaders(agent, logicalMessage, getHeadersPipelineFunc);
}

private static void CreateOutboundHeaders(IAgent agent, object logicalMessage, Func<object, Dictionary<string, string>> getHeaders)
{
// We don't need to check if headers are null since we will create the headers object if its null
// create action for use later
var setHeaders = new Action<object, string, string>((carrier, key, value) =>
{
var headers = getHeaders(logicalMessage);
if (headers == null)
{
headers = new Dictionary<string, string>();
SetHeaders(carrier, headers);
}
else if (headers is IReadOnlyDictionary<string, object>)
{
headers = new Dictionary<string, string>(headers);
SetHeaders(carrier, headers);
}

headers[key] = value;
});

agent.CurrentTransaction.InsertDistributedTraceHeaders(logicalMessage, setHeaders);

static void SetHeaders(object logicalMessage, Dictionary<string, string> headers)
{
// Unlike the GetHeaders function, we can't cache this action. It is only valid for the specific logicalMessage object instance provided.
var action = VisibilityBypasser.Instance.GeneratePropertySetter<Dictionary<string, string>>(logicalMessage, "Headers");
action(headers);
}
}

/// <summary>
/// Returns a metric name based on the type of message. The source/destination queue isn't always known (depending on the circumstances) and in some cases isn't even relevant. The message type is always known and is always relevant.
/// </summary>
/// <param name="logicalMessage"></param>
/// <returns></returns>
public static string TryGetQueueNameSendMessage(object logicalMessage)
{
var getMessageTypeFunc = _getMessageTypeSendMessageFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Type>(logicalMessage.GetType(), "MessageType");
return TryGetQueueName(logicalMessage, getMessageTypeFunc);
}

/// <summary>
/// Returns a metric name based on the type of message. The source/destination queue isn't always known (depending on the circumstances) and in some cases isn't even relevant. The message type is always known and is always relevant.
/// </summary>
/// <param name="logicalMessage"></param>
/// <returns></returns>
public static string TryGetQueueNamePipeline(object logicalMessage)
{
var getMessageTypeFunc = _getMessageTypePipelineFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Type>(logicalMessage.GetType(), "MessageType");
return TryGetQueueName(logicalMessage, getMessageTypeFunc);
}

/// <summary>
/// Returns a metric name based on the type of message. The source/destination queue isn't always known (depending on the circumstances) and in some cases isn't even relevant. The message type is always known and is always relevant.
/// </summary>
/// <param name="logicalMessage"></param>
/// <returns></returns>
public static string TryGetQueueNameReceiveMessage(object logicalMessage)
{
var getMessageTypeFunc = _getMessageTypeReceiveMessageFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Type>(logicalMessage.GetType(), "MessageType");
return TryGetQueueName(logicalMessage, getMessageTypeFunc);
}

/// <summary>
/// Returns a metric name based on the type of message. The source/destination queue isn't always known (depending on the circumstances) and in some cases isn't even relevant. The message type is always known and is always relevant.
/// </summary>
/// <param name="logicalMessage"></param>
/// <returns></returns>
public static string TryGetQueueNameLoadHandlersConnector(object logicalMessage)
{
var getMessageTypeFunc = _getMessageTypeLoadHandlersConnectorFunc ??= VisibilityBypasser.Instance.GeneratePropertyAccessor<Type>(logicalMessage.GetType(), "MessageType");
return TryGetQueueName(logicalMessage, getMessageTypeFunc);
}

private static string TryGetQueueName(object logicalMessage, Func<object, Type> getMessageType)
{
var messageType = getMessageType(logicalMessage);

if (messageType == null)
{
return null;
}

return messageType.FullName;
}
}
}