public static void Execute(
            object wireProtocol,
            object connection,
            object boxedCancellationToken,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (wireProtocol == null)
            {
                throw new ArgumentNullException(nameof(wireProtocol));
            }

            const string methodName = nameof(Execute);
            Action <object, object, CancellationToken> execute;
            var wireProtocolType = wireProtocol.GetType();

            var cancellationToken = (CancellationToken)boxedCancellationToken;

            try
            {
                execute =
                    MethodBuilder <Action <object, object, CancellationToken> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(wireProtocolType)
                    .WithParameters(connection, cancellationToken)
                    .WithNamespaceAndNameFilters(ClrNames.Void, "MongoDB.Driver.Core.Connections.IConnection", ClrNames.CancellationToken)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: IWireProtocol,
                    methodName: methodName,
                    instanceType: wireProtocol.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = CreateScope(wireProtocol, connection))
            {
                try
                {
                    execute(wireProtocol, connection, cancellationToken);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
コード例 #2
0
        public static object CallElasticsearch <TResponse>(
            object pipeline,
            object requestData,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (pipeline == null)
            {
                throw new ArgumentNullException(nameof(pipeline));
            }

            const string methodName = nameof(CallElasticsearch);
            Func <object, object, TResponse> callElasticSearch;
            var pipelineType    = pipeline.GetType();
            var genericArgument = typeof(TResponse);

            try
            {
                callElasticSearch =
                    MethodBuilder <Func <object, object, TResponse> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(pipelineType)
                    .WithMethodGenerics(genericArgument)
                    .WithParameters(requestData)
                    .WithNamespaceAndNameFilters(ClrNames.Ignore, "Elasticsearch.Net.RequestData")
                    .Build();
            }
            catch (Exception ex)
            {
                // profiled app will not continue working as expected without this method
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: RequestPipelineInterfaceTypeName,
                    methodName: methodName,
                    instanceType: pipeline.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = ElasticsearchNetCommon.CreateScope(Tracer.Instance, IntegrationId, pipeline.DuckCast <RequestPipelineStruct>(), new RequestDataV6(requestData)))
            {
                try
                {
                    return(callElasticSearch(pipeline, requestData));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
        public static object GetRequestStream(object webRequest, int opCode, int mdToken, long moduleVersionPtr)
        {
            const string methodName = nameof(GetRequestStream);

            Func <object, Stream> callGetRequestStream;

            try
            {
                var instrumentedType = webRequest.GetInstrumentedType(WebRequestTypeName);
                callGetRequestStream =
                    MethodBuilder <Func <object, Stream> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(instrumentedType)
                    .WithNamespaceAndNameFilters("System.IO.Stream")
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: WebRequestTypeName,
                    methodName: methodName,
                    instanceType: webRequest.GetType().AssemblyQualifiedName);
                throw;
            }

            var request = (WebRequest)webRequest;

            if (!(request is HttpWebRequest) || !IsTracingEnabled(request))
            {
                return(callGetRequestStream(webRequest));
            }

            var tracer = Tracer.Instance;

            if (tracer.Settings.IsIntegrationEnabled(IntegrationId))
            {
                var spanContext = ScopeFactory.CreateHttpSpanContext(tracer, IntegrationId);

                if (spanContext != null)
                {
                    // Add distributed tracing headers to the HTTP request.
                    // The expected sequence of calls is GetRequestStream -> GetResponse. Headers can't be modified after calling GetRequestStream.
                    // At the same time, we don't want to set an active scope now, because it's possible that GetResponse will never be called.
                    // Instead, we generate a spancontext and inject it in the headers. GetResponse will fetch them and create an active scope with the right id.
                    SpanContextPropagator.Instance.Inject(spanContext, request.Headers.Wrap());
                }
            }

            return(callGetRequestStream(webRequest));
        }
        public static object ExecuteReader(
            object command,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteReader;
            Func <IDbCommand, IDataReader> instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedInterface(IDbCommandTypeName);

                instrumentedMethod =
                    MethodBuilder <Func <IDbCommand, IDataReader> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(targetType)
                    .WithNamespaceAndNameFilters(AdoNetConstants.TypeNames.IDataReader)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: IDbCommandTypeName,
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            var dbCommand = command as IDbCommand;

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, dbCommand))
            {
                try
                {
                    return(instrumentedMethod(dbCommand));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
コード例 #5
0
        public static bool HandleRequest(
            object channelHandler,
            object requestContext,
            object currentOperationContext,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (channelHandler == null)
            {
                throw new ArgumentNullException(nameof(channelHandler));
            }

            Func <object, object, object, bool> instrumentedMethod;
            var declaringType = channelHandler.GetInstrumentedType(ChannelHandlerTypeName);

            try
            {
                instrumentedMethod = MethodBuilder <Func <object, object, object, bool> >
                                     .Start(moduleVersionPtr, mdToken, opCode, nameof(HandleRequest))
                                     .WithConcreteType(declaringType)
                                     .WithParameters(requestContext, currentOperationContext)
                                     .WithNamespaceAndNameFilters(
                    ClrNames.Bool,
                    "System.ServiceModel.Channels.RequestContext",
                    "System.ServiceModel.OperationContext")
                                     .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: ChannelHandlerTypeName,
                    methodName: nameof(HandleRequest),
                    instanceType: channelHandler.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = CreateScope(requestContext))
            {
                try
                {
                    return(instrumentedMethod(channelHandler, requestContext, currentOperationContext));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
コード例 #6
0
        private static object ExecuteReader(
            object command,
            int opCode,
            int mdToken,
            long moduleVersionPtr,
            string sqlClientNamespace,
            string dataReaderTypeName)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteReader;
            Func<object, object> instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedType(sqlClientNamespace, SqlCommandTypeName);

                instrumentedMethod =
                    MethodBuilder<Func<object, object>>
                       .Start(moduleVersionPtr, mdToken, opCode, methodName)
                       .WithConcreteType(targetType)
                       .WithNamespaceAndNameFilters(dataReaderTypeName)
                       .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: $"{sqlClientNamespace}.{SqlCommandTypeName}",
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, command as DbCommand))
            {
                try
                {
                    return instrumentedMethod(command);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
        public static object ExecuteAsync(
            object apiController,
            object controllerContext,
            object boxedCancellationToken,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (apiController == null)
            {
                throw new ArgumentNullException(nameof(apiController));
            }

            var cancellationToken  = (CancellationToken)boxedCancellationToken;
            var httpControllerType = apiController.GetInstrumentedInterface(HttpControllerTypeName);

            Type taskResultType;

            try
            {
                var request = controllerContext.GetProperty <object>("Request").GetValueOrDefault();
                var httpRequestMessageType = request.GetInstrumentedType("System.Net.Http.HttpRequestMessage");

                // The request should never be null, so get the base type found in System.Net.Http.dll
                if (httpRequestMessageType != null)
                {
                    var systemNetHttpAssembly = httpRequestMessageType.Assembly;
                    taskResultType = systemNetHttpAssembly.GetType("System.Net.Http.HttpResponseMessage", true);
                }

                // This should never happen, but put in a reasonable fallback of finding the first System.Net.Http.dll in the AppDomain
                else
                {
                    Log.Warning($"{nameof(AspNetWebApi2Integration)}.{nameof(ExecuteAsync)}: Unable to find System.Net.Http.HttpResponseMessage Type from method arguments. Using fallback logic to find the Type needed for return type.");
                    var statsd = Tracer.Instance.Statsd;
                    statsd?.Warning(source: $"{nameof(AspNetWebApi2Integration)}.{nameof(ExecuteAsync)}", message: "Unable to find System.Net.Http.HttpResponseMessage Type from method arguments. Using fallback logic to find the Type needed for return type.", null);

                    var systemNetHttpAssemblies    = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.GetName().Name.Equals("System.Net.Http", StringComparison.OrdinalIgnoreCase));
                    var firstSystemNetHttpAssembly = systemNetHttpAssemblies.First();
                    taskResultType = firstSystemNetHttpAssembly.GetType("System.Net.Http.HttpResponseMessage", true);
                }
            }
            catch (Exception ex)
            {
                // This shouldn't happen because the System.Net.Http assembly should have been loaded if this method was called
                // The profiled app will not continue working as expected without this method
                Log.Error(ex, "Error finding types in the user System.Net.Http assembly.");
                throw;
            }

            Func <object, object, CancellationToken, object> instrumentedMethod = null;

            try
            {
                instrumentedMethod = MethodBuilder <Func <object, object, CancellationToken, object> >
                                     .Start(moduleVersionPtr, mdToken, opCode, nameof(ExecuteAsync))
                                     .WithConcreteType(httpControllerType)
                                     .WithParameters(controllerContext, cancellationToken)
                                     .WithNamespaceAndNameFilters(
                    ClrNames.HttpResponseMessageTask,
                    HttpControllerContextTypeName,
                    ClrNames.CancellationToken)
                                     .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: HttpControllerTypeName,
                    methodName: nameof(ExecuteAsync),
                    instanceType: apiController.GetType().AssemblyQualifiedName);
                throw;
            }

            return(AsyncHelper.InvokeGenericTaskDelegate(
                       owningType: apiController.GetType(),
                       taskResultType: taskResultType,
                       nameOfIntegrationMethod: nameof(ExecuteAsyncInternal),
                       integrationType: typeof(AspNetWebApi2Integration),
                       instrumentedMethod,
                       apiController,
                       controllerContext,
                       cancellationToken));
        }
コード例 #8
0
        public static object TestInvoker_RunAsync(
            object testInvoker,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (testInvoker == null)
            {
                throw new ArgumentNullException(nameof(testInvoker));
            }

            Type testInvokerType = testInvoker.GetType();
            Func <object, object> executeAsync;

            try
            {
                executeAsync =
                    MethodBuilder <Func <object, object> >
                    .Start(moduleVersionPtr, mdToken, opCode, XUnitRunAsyncMethod)
                    .WithConcreteType(testInvokerType)
                    .WithDeclaringTypeGenerics(testInvokerType.BaseType.GenericTypeArguments)
                    .WithNamespaceAndNameFilters("System.Threading.Tasks.Task`1<System.Decimal>")
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: XUnitTestInvokerType,
                    methodName: XUnitRunAsyncMethod,
                    instanceType: testInvokerType.AssemblyQualifiedName);
                throw;
            }

            object    returnValue = null;
            Exception exception   = null;

            try
            {
                returnValue = executeAsync(testInvoker);
            }
            catch (TargetInvocationException ex)
            {
                exception = ex.InnerException;
                throw;
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                returnValue = AsyncTool.AddContinuation(returnValue, exception, testInvoker, (r, ex, state) => InvokerContinuation(r, ex, state));
            }

            return(returnValue);
        }
コード例 #9
0
        public static object Validate(
            object documentValidator,
            object originalQuery,
            object schema,
            object document,
            object rules,
            object userContext,
            object inputs,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (documentValidator == null)
            {
                throw new ArgumentNullException(nameof(documentValidator));
            }

            const string methodName = nameof(Validate);

            // At runtime, get a Type object for GraphQL.ExecutionResult
            var documentValidatorInstanceType = documentValidator.GetType();
            Func <object, object, object, object, object, object, object, object> instrumentedMethod;

            try
            {
                instrumentedMethod =
                    MethodBuilder <Func <object, object, object, object, object, object, object, object> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(documentValidatorInstanceType)
                    .WithParameters(originalQuery, schema, document, rules, userContext, inputs)
                    .WithNamespaceAndNameFilters(
                        GraphQLValidationResultInterfaceName,
                        ClrNames.String,
                        "GraphQL.Types.ISchema",
                        "GraphQL.Language.AST.Document",
                        "System.Collections.Generic.IEnumerable`1",
                        ClrNames.Ignore,
                        "GraphQL.Inputs")
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: GraphQLDocumentValidatorInterfaceName,
                    methodName: methodName,
                    instanceType: documentValidator.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = CreateScopeFromValidate(document))
            {
                try
                {
                    var validationResult = instrumentedMethod(documentValidator, originalQuery, schema, document, rules, userContext, inputs);
                    RecordExecutionErrorsIfPresent(scope.Span, "GraphQL.Validation.ValidationError", validationResult.GetProperty("Errors").GetValueOrDefault());
                    return(validationResult);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
コード例 #10
0
        public static object TestCommand_Execute(
            object testMethodCommand,
            object testExecutionContext,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (testMethodCommand == null)
            {
                throw new ArgumentNullException(nameof(testMethodCommand));
            }

            Type testMethodCommandType = testMethodCommand.GetType();
            Func <object, object, object> execute;

            try
            {
                execute = MethodBuilder <Func <object, object, object> >
                          .Start(moduleVersionPtr, mdToken, opCode, NUnitExecuteMethod)
                          .WithConcreteType(testMethodCommandType)
                          .WithParameters(testExecutionContext)
                          .WithNamespaceAndNameFilters(NUnitTestResultType, NUnitTestExecutionContextType)
                          .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: NUnitTestCommandType,
                    methodName: NUnitExecuteMethod,
                    instanceType: testMethodCommandType.AssemblyQualifiedName);
                throw;
            }

            if (testMethodCommandType.FullName != NUnitTestMethodCommandType &&
                testMethodCommandType.FullName != NUnitSkipCommandType)
            {
                return(execute(testMethodCommand, testExecutionContext));
            }

            Scope scope = CreateScope(testExecutionContext, testMethodCommandType);

            if (scope is null)
            {
                return(execute(testMethodCommand, testExecutionContext));
            }

            using (scope)
            {
                object    result    = null;
                Exception exception = null;
                try
                {
                    scope.Span.ResetStartTime();
                    result = execute(testMethodCommand, testExecutionContext);
                }
                catch (Exception ex)
                {
                    exception = ex;
                    throw;
                }
                finally
                {
                    FinishScope(scope, testExecutionContext, exception);
                }

                return(result);
            }
        }
コード例 #11
0
        public static object BeginInvokeAction(
            object asyncControllerActionInvoker,
            object controllerContext,
            object actionName,
            object callback,
            object state,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            if (asyncControllerActionInvoker == null)
            {
                throw new ArgumentNullException(nameof(asyncControllerActionInvoker));
            }

            Scope scope = null;

            try
            {
                if (HttpContext.Current != null)
                {
                    scope = CreateScope(controllerContext.DuckCast <ControllerContextStruct>());
                    HttpContext.Current.Items[HttpContextKey] = scope;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error instrumenting method {MethodName}", "System.Web.Mvc.Async.IAsyncActionInvoker.BeginInvokeAction()");
            }

            Func <object, object, object, object, object, object> instrumentedMethod;

            try
            {
                var asyncActionInvokerType = asyncControllerActionInvoker.GetInstrumentedInterface(AsyncActionInvokerTypeName);

                instrumentedMethod = MethodBuilder <Func <object, object, object, object, object, object> >
                                     .Start(moduleVersionPtr, mdToken, opCode, nameof(BeginInvokeAction))
                                     .WithConcreteType(asyncActionInvokerType)
                                     .WithParameters(controllerContext, actionName, callback, state)
                                     .WithNamespaceAndNameFilters(
                    ClrNames.IAsyncResult,
                    "System.Web.Mvc.ControllerContext",
                    ClrNames.String,
                    ClrNames.AsyncCallback,
                    ClrNames.Object)
                                     .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: AsyncActionInvokerTypeName,
                    methodName: nameof(BeginInvokeAction),
                    instanceType: asyncControllerActionInvoker.GetType().AssemblyQualifiedName);
                throw;
            }

            try
            {
                // call the original method, inspecting (but not catching) any unhandled exceptions
                return(instrumentedMethod(asyncControllerActionInvoker, controllerContext, actionName, callback, state));
            }
            catch (Exception ex)
            {
                scope?.Span.SetException(ex);
                throw;
            }
        }