Example #1
0
        private void OnEndRequest(object sender, EventArgs eventArgs)
        {
            try
            {
                if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    // integration disabled
                    return;
                }

                if (sender is HttpApplication app &&
                    app.Context.Items[_httpContextScopeKey] is Scope scope)
                {
                    scope.Span.SetHttpStatusCode(app.Context.Response.StatusCode, isServer: true);

                    if (app.Context.Items[SharedConstants.HttpContextPropagatedResourceNameKey] is string resourceName &&
                        !string.IsNullOrEmpty(resourceName))
                    {
                        scope.Span.ResourceName = resourceName;
                    }
                    else
                    {
                        string path = UriHelpers.GetCleanUriPath(app.Request.Url);
                        scope.Span.ResourceName = $"{app.Request.HttpMethod.ToUpperInvariant()} {path.ToLowerInvariant()}";
                    }

                    scope.Dispose();
                }
        public string GetDefaultResourceName(HttpRequest request)
        {
            string httpMethod = request.Method?.ToUpperInvariant() ?? "UNKNOWN";

            string absolutePath = request.PathBase.HasValue
                                      ? request.PathBase.ToUriComponent() + request.Path.ToUriComponent()
                                      : request.Path.ToUriComponent();

            string resourceUrl = UriHelpers.GetCleanUriPath(absolutePath)
                                 .ToLowerInvariant();

            return($"{httpMethod} {resourceUrl}");
        }
        internal static void UpdateSpan(IHttpControllerContext controllerContext, Span span, AspNetTags tags, IEnumerable <KeyValuePair <string, string> > headerTags)
        {
            try
            {
                var newResourceNamesEnabled = Tracer.Instance.Settings.RouteTemplateResourceNamesEnabled;
                var request    = controllerContext.Request;
                Uri requestUri = request.RequestUri;

                string host   = request.Headers.Host ?? string.Empty;
                string rawUrl = requestUri?.ToString().ToLowerInvariant() ?? string.Empty;
                string method = request.Method.Method?.ToUpperInvariant() ?? "GET";
                string route  = null;
                try
                {
                    route = controllerContext.RouteData.Route.RouteTemplate;
                }
                catch
                {
                }

                string resourceName;

                if (route != null)
                {
                    resourceName = $"{method} {(newResourceNamesEnabled ? "/" : string.Empty)}{route.ToLowerInvariant()}";
                }
                else if (requestUri != null)
                {
                    var cleanUri = UriHelpers.GetCleanUriPath(requestUri);
                    resourceName = $"{method} {cleanUri.ToLowerInvariant()}";
                }
                else
                {
                    resourceName = $"{method}";
                }

                string controller = string.Empty;
                string action     = string.Empty;
                string area       = string.Empty;
                try
                {
                    var routeValues = controllerContext.RouteData.Values;
                    if (routeValues != null)
                    {
                        controller = (routeValues.GetValueOrDefault("controller") as string)?.ToLowerInvariant();
                        action     = (routeValues.GetValueOrDefault("action") as string)?.ToLowerInvariant();
                        area       = (routeValues.GetValueOrDefault("area") as string)?.ToLowerInvariant();
                    }
                }
                catch
                {
                }

                // Replace well-known routing tokens
                resourceName =
                    resourceName
                    .Replace("{area}", area)
                    .Replace("{controller}", controller)
                    .Replace("{action}", action);

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: method,
                    host: host,
                    httpUrl: rawUrl,
                    tags,
                    headerTags);

                tags.AspNetAction     = action;
                tags.AspNetController = controller;
                tags.AspNetArea       = area;
                tags.AspNetRoute      = route;

                if (newResourceNamesEnabled)
                {
                    // set the resource name in the HttpContext so TracingHttpModule can update root span
                    var httpContext = System.Web.HttpContext.Current;
                    if (httpContext is not null)
                    {
                        httpContext.Items[SharedConstants.HttpContextPropagatedResourceNameKey] = resourceName;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error populating scope data.");
            }
        }
        public void CleanUriSegment(string segment, string expected)
        {
            string actual = UriHelpers.GetCleanUriPath(segment);

            Assert.Equal(expected, actual);
        }
Example #5
0
        internal static void UpdateSpan(IHttpControllerContext controllerContext, Span span, AspNetTags tags, IEnumerable <KeyValuePair <string, string> > headerTags)
        {
            try
            {
                var newResourceNamesEnabled = Tracer.Instance.Settings.RouteTemplateResourceNamesEnabled;
                var request    = controllerContext.Request;
                Uri requestUri = request.RequestUri;

                string host   = request.Headers.Host ?? string.Empty;
                string rawUrl = requestUri?.ToString().ToLowerInvariant() ?? string.Empty;
                string method = request.Method.Method?.ToUpperInvariant() ?? "GET";
                string route  = null;
                try
                {
                    route = controllerContext.RouteData.Route.RouteTemplate;
                }
                catch
                {
                }

                IDictionary <string, object> routeValues = null;
                try
                {
                    routeValues = controllerContext.RouteData.Values;
                }
                catch
                {
                }

                string resourceName;

                string controller = string.Empty;
                string action     = string.Empty;
                string area       = string.Empty;

                if (route is not null && routeValues is not null)
                {
                    resourceName = AspNetResourceNameHelper.CalculateResourceName(
                        httpMethod: method,
                        routeTemplate: route,
                        routeValues,
                        defaults: null,
                        out area,
                        out controller,
                        out action,
                        addSlashPrefix: newResourceNamesEnabled,
                        expandRouteTemplates: newResourceNamesEnabled && Tracer.Instance.Settings.ExpandRouteTemplatesEnabled);
                }
                else if (requestUri != null)
                {
                    var cleanUri = UriHelpers.GetCleanUriPath(requestUri);
                    resourceName = $"{method} {cleanUri}";
                }
                else
                {
                    resourceName = $"{method}";
                }

                if (route is null && routeValues is not null)
                {
                    // we weren't able to get the route template (somehow) but _were_ able to
                    // get the route values. Not sure how this is possible, but is preexisting behaviour
                    try
                    {
                        controller = (routeValues.GetValueOrDefault("controller") as string)?.ToLowerInvariant();
                        action     = (routeValues.GetValueOrDefault("action") as string)?.ToLowerInvariant();
                        area       = (routeValues.GetValueOrDefault("area") as string)?.ToLowerInvariant();
                    }
                    catch
                    {
                    }
                }

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: method,
                    host: host,
                    httpUrl: rawUrl,
                    tags,
                    headerTags);

                if (tags is not null)
                {
                    tags.AspNetAction     = action;
                    tags.AspNetController = controller;
                    tags.AspNetArea       = area;
                    tags.AspNetRoute      = route;
                }

                if (newResourceNamesEnabled)
                {
                    // set the resource name in the HttpContext so TracingHttpModule can update root span
                    var httpContext = System.Web.HttpContext.Current;
                    if (httpContext is not null)
                    {
                        httpContext.Items[SharedItems.HttpContextPropagatedResourceNameKey] = resourceName;
                    }
                }
            }
        /// <summary>
        /// Creates a scope used to instrument an MVC action and populates some common details.
        /// </summary>
        /// <param name="controllerContext">The System.Web.Mvc.ControllerContext that was passed as an argument to the instrumented method.</param>
        /// <returns>A new scope used to instrument an MVC action.</returns>
        public static Scope CreateScope(ControllerContextStruct controllerContext)
        {
            Scope scope = null;

            try
            {
                if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    // integration disabled, don't create a scope, skip this trace
                    return(null);
                }

                var httpContext = controllerContext.HttpContext;

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

                var    newResourceNamesEnabled = Tracer.Instance.Settings.RouteTemplateResourceNamesEnabled;
                string host         = httpContext.Request.Headers.Get("Host");
                string httpMethod   = httpContext.Request.HttpMethod.ToUpperInvariant();
                string url          = httpContext.Request.RawUrl.ToLowerInvariant();
                string resourceName = null;

                RouteData            routeData   = controllerContext.RouteData;
                Route                route       = routeData?.Route as Route;
                RouteValueDictionary routeValues = routeData?.Values;
                bool wasAttributeRouted          = false;

                if (route == null && routeData?.Route.GetType().FullName == RouteCollectionRouteTypeName)
                {
                    var routeMatches = routeValues?.GetValueOrDefault("MS_DirectRouteMatches") as List <RouteData>;

                    if (routeMatches?.Count > 0)
                    {
                        // route was defined using attribute routing i.e. [Route("/path/{id}")]
                        // get route and routeValues from the RouteData in routeMatches
                        wasAttributeRouted = true;
                        route       = routeMatches[0].Route as Route;
                        routeValues = routeMatches[0].Values;

                        if (route != null)
                        {
                            var resourceUrl = route.Url?.ToLowerInvariant() ?? string.Empty;
                            if (resourceUrl.FirstOrDefault() != '/')
                            {
                                resourceUrl = string.Concat("/", resourceUrl);
                            }

                            resourceName = $"{httpMethod} {resourceUrl}";
                        }
                    }
                }

                string routeUrl       = route?.Url;
                string areaName       = (routeValues?.GetValueOrDefault("area") as string)?.ToLowerInvariant();
                string controllerName = (routeValues?.GetValueOrDefault("controller") as string)?.ToLowerInvariant();
                string actionName     = (routeValues?.GetValueOrDefault("action") as string)?.ToLowerInvariant();

                if (newResourceNamesEnabled && string.IsNullOrEmpty(resourceName) && !string.IsNullOrEmpty(routeUrl))
                {
                    resourceName = $"{httpMethod} /{routeUrl.ToLowerInvariant()}";
                }

                if (string.IsNullOrEmpty(resourceName) && httpContext.Request.Url != null)
                {
                    var cleanUri = UriHelpers.GetCleanUriPath(httpContext.Request.Url);
                    resourceName = $"{httpMethod} {cleanUri.ToLowerInvariant()}";
                }

                if (string.IsNullOrEmpty(resourceName))
                {
                    // Keep the legacy resource name, just to have something
                    resourceName = $"{httpMethod} {controllerName}.{actionName}";
                }

                // Replace well-known routing tokens
                resourceName =
                    resourceName
                    .Replace("{area}", areaName)
                    .Replace("{controller}", controllerName)
                    .Replace("{action}", actionName);

                if (newResourceNamesEnabled && !wasAttributeRouted && routeValues is not null && route is not null)
                {
                    // Remove unused parameters from conventional route templates
                    // Don't bother with routes defined using attribute routing
                    foreach (var parameter in route.Defaults)
                    {
                        var parameterName = parameter.Key;
                        if (parameterName != "area" &&
                            parameterName != "controller" &&
                            parameterName != "action" &&
                            !routeValues.ContainsKey(parameterName))
                        {
                            resourceName = resourceName.Replace($"/{{{parameterName}}}", string.Empty);
                        }
                    }
                }

                SpanContext propagatedContext = null;
                var         tracer            = Tracer.Instance;
                var         tagsFromHeaders   = Enumerable.Empty <KeyValuePair <string, string> >();

                if (tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var headers = httpContext.Request.Headers.Wrap();
                        propagatedContext = SpanContextPropagator.Instance.Extract(headers);
                        tagsFromHeaders   = SpanContextPropagator.Instance.ExtractHeaderTags(headers, tracer.Settings.HeaderTags, SpanContextPropagator.HttpRequestHeadersTagPrefix);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                var tags = new AspNetTags();
                scope = Tracer.Instance.StartActiveWithTags(OperationName, propagatedContext, tags: tags);
                Span span = scope.Span;

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: httpMethod,
                    host: host,
                    httpUrl: url,
                    tags,
                    tagsFromHeaders);

                tags.AspNetRoute      = routeUrl;
                tags.AspNetArea       = areaName;
                tags.AspNetController = controllerName;
                tags.AspNetAction     = actionName;

                tags.SetAnalyticsSampleRate(IntegrationId, tracer.Settings, enabledWithGlobalSetting: true);

                if (newResourceNamesEnabled)
                {
                    // set the resource name in the HttpContext so TracingHttpModule can update root span
                    httpContext.Items[SharedConstants.HttpContextPropagatedResourceNameKey] = resourceName;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error creating or populating scope.");
            }

            return(scope);
        }
        private void OnEndRequest(object sender, EventArgs eventArgs)
        {
            try
            {
                if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    // integration disabled
                    return;
                }

                if (sender is HttpApplication app &&
                    app.Context.Items[_httpContextScopeKey] is Scope scope)
                {
                    try
                    {
                        // HttpServerUtility.TransferRequest presents an issue: The IIS request pipeline is run a second time
                        // from the same incoming HTTP request, but the HttpContext and HttpRequest objects from the two pipeline
                        // requests are completely isolated. Fortunately, the second request (somehow) maintains the original
                        // ExecutionContext, so the parent-child relationship between the two aspnet.request spans are correct.
                        //
                        // Since the EndRequest event will fire first for the second request, and this represents the HTTP response
                        // seen by end-users of the site, we'll only set HTTP tags on the root span and current span (if different)
                        // once with the information from the corresponding HTTP response.
                        // When this code is invoked again for the original HTTP request the HTTP tags must not be modified.
                        //
                        // Note: HttpServerUtility.TransferRequest cannot be invoked more than once, so we'll have at most two nested (in-process)
                        // aspnet.request spans at any given time: https://referencesource.microsoft.com/#System.Web/Hosting/IIS7WorkerRequest.cs,2400
                        var rootScope = scope.Root;
                        var rootSpan  = rootScope.Span;

                        if (!rootSpan.HasHttpStatusCode())
                        {
                            rootSpan.SetHttpStatusCode(app.Context.Response.StatusCode, isServer: true, Tracer.Instance.Settings);
                            AddHeaderTagsFromHttpResponse(app.Context, rootScope);

                            if (scope.Span != rootSpan)
                            {
                                scope.Span.SetHttpStatusCode(app.Context.Response.StatusCode, isServer: true, Tracer.Instance.Settings);
                                AddHeaderTagsFromHttpResponse(app.Context, scope);
                            }
                        }

                        if (app.Context.Items[SharedItems.HttpContextPropagatedResourceNameKey] is string resourceName &&
                            !string.IsNullOrEmpty(resourceName))
                        {
                            scope.Span.ResourceName = resourceName;
                        }
                        else
                        {
                            string path = UriHelpers.GetCleanUriPath(app.Request.Url);
                            scope.Span.ResourceName = $"{app.Request.HttpMethod.ToUpperInvariant()} {path.ToLowerInvariant()}";
                        }

                        var security = Security.Instance;
                        if (security.Settings.Enabled)
                        {
                            var httpContext = (sender as HttpApplication)?.Context;

                            if (httpContext == null)
                            {
                                return;
                            }

                            security.InstrumentationGateway.RaiseRequestEnd(httpContext, httpContext.Request, scope.Span, null);
                            security.InstrumentationGateway.RaiseLastChanceToWriteTags(httpContext, scope.Span);
                        }

                        scope.Dispose();
                    }
                    finally
                    {
                        // Clear the context to make sure another TracingHttpModule doesn't try to close the same scope
                        TryClearContext(app.Context);
                    }
                }
Example #8
0
        /// <summary>
        /// Creates a scope used to instrument an MVC action and populates some common details.
        /// </summary>
        /// <param name="controllerContext">The System.Web.Mvc.ControllerContext that was passed as an argument to the instrumented method.</param>
        /// <returns>A new scope used to instrument an MVC action.</returns>
        internal static Scope CreateScope(ControllerContextStruct controllerContext)
        {
            Scope scope = null;

            try
            {
                var httpContext = controllerContext.HttpContext;
                if (httpContext == null)
                {
                    return(null);
                }

                Span span = null;
                // integration enabled, go create a scope!
                var tracer = Tracer.Instance;
                if (tracer.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    var    newResourceNamesEnabled = tracer.Settings.RouteTemplateResourceNamesEnabled;
                    string host         = httpContext.Request.Headers.Get("Host");
                    string httpMethod   = httpContext.Request.HttpMethod.ToUpperInvariant();
                    string url          = httpContext.Request.RawUrl.ToLowerInvariant();
                    string resourceName = null;

                    RouteData            routeData   = controllerContext.RouteData;
                    Route                route       = routeData?.Route as Route;
                    RouteValueDictionary routeValues = routeData?.Values;
                    bool wasAttributeRouted          = false;
                    bool isChildAction = controllerContext.ParentActionViewContext.RouteData?.Values["controller"] is not null;

                    if (isChildAction && newResourceNamesEnabled)
                    {
                        // For child actions, we want to stick to what was requested in the http request.
                        // And the child action being a child, then we have already computed the resourcename.
                        resourceName = httpContext.Items[SharedItems.HttpContextPropagatedResourceNameKey] as string;
                    }

                    if (route == null && routeData?.Route.GetType().FullName == RouteCollectionRouteTypeName)
                    {
                        var routeMatches = routeValues?.GetValueOrDefault("MS_DirectRouteMatches") as List <RouteData>;

                        if (routeMatches?.Count > 0)
                        {
                            // route was defined using attribute routing i.e. [Route("/path/{id}")]
                            // get route and routeValues from the RouteData in routeMatches
                            wasAttributeRouted = true;
                            route       = routeMatches[0].Route as Route;
                            routeValues = routeMatches[0].Values;
                        }
                    }

                    string routeUrl = route?.Url;
                    string areaName;
                    string controllerName;
                    string actionName;

                    if ((wasAttributeRouted || newResourceNamesEnabled) && string.IsNullOrEmpty(resourceName) && !string.IsNullOrEmpty(routeUrl))
                    {
                        resourceName = AspNetResourceNameHelper.CalculateResourceName(
                            httpMethod: httpMethod,
                            routeTemplate: routeUrl,
                            routeValues,
                            defaults: wasAttributeRouted ? null : route.Defaults,
                            out areaName,
                            out controllerName,
                            out actionName,
                            expandRouteTemplates: newResourceNamesEnabled && tracer.Settings.ExpandRouteTemplatesEnabled);
                    }
                    else
                    {
                        // just grab area/controller/action directly
                        areaName       = (routeValues?.GetValueOrDefault("area") as string)?.ToLowerInvariant();
                        controllerName = (routeValues?.GetValueOrDefault("controller") as string)?.ToLowerInvariant();
                        actionName     = (routeValues?.GetValueOrDefault("action") as string)?.ToLowerInvariant();
                    }

                    if (string.IsNullOrEmpty(resourceName) && httpContext.Request.Url != null)
                    {
                        var cleanUri = UriHelpers.GetCleanUriPath(httpContext.Request.Url);
                        resourceName = $"{httpMethod} {cleanUri.ToLowerInvariant()}";
                    }

                    if (string.IsNullOrEmpty(resourceName))
                    {
                        // Keep the legacy resource name, just to have something
                        resourceName = $"{httpMethod} {controllerName}.{actionName}";
                    }

                    SpanContext propagatedContext = null;
                    var         tagsFromHeaders   = Enumerable.Empty <KeyValuePair <string, string> >();

                    if (tracer.InternalActiveScope == null)
                    {
                        try
                        {
                            // extract propagated http headers
                            var headers = httpContext.Request.Headers.Wrap();
                            propagatedContext = SpanContextPropagator.Instance.Extract(headers);
                            tagsFromHeaders   = SpanContextPropagator.Instance.ExtractHeaderTags(headers, tracer.Settings.HeaderTags, SpanContextPropagator.HttpRequestHeadersTagPrefix);
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, "Error extracting propagated HTTP headers.");
                        }
                    }

                    var tags = new AspNetTags();
                    scope = tracer.StartActiveInternal(isChildAction ? ChildActionOperationName : OperationName, propagatedContext, tags: tags);
                    span  = scope.Span;

                    span.DecorateWebServerSpan(
                        resourceName: resourceName,
                        method: httpMethod,
                        host: host,
                        httpUrl: url,
                        tags,
                        tagsFromHeaders);

                    tags.AspNetRoute      = routeUrl;
                    tags.AspNetArea       = areaName;
                    tags.AspNetController = controllerName;
                    tags.AspNetAction     = actionName;

                    tags.SetAnalyticsSampleRate(IntegrationId, tracer.Settings, enabledWithGlobalSetting: true);

                    if (newResourceNamesEnabled && string.IsNullOrEmpty(httpContext.Items[SharedItems.HttpContextPropagatedResourceNameKey] as string))
                    {
                        // set the resource name in the HttpContext so TracingHttpModule can update root span
                        httpContext.Items[SharedItems.HttpContextPropagatedResourceNameKey] = resourceName;
                    }

                    tracer.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error creating or populating scope.");
            }

            return(scope);
        }