/// <summary>
        /// Processes HTTP request.
        /// </summary>
        private static void ProcessHTTPRequest(Object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;

            if (context.Items.Contains(XRayEntity))
            {
                return; // Do not override segment for the current request
            }

            var         request     = context.Request;
            TraceHeader traceHeader = GetTraceHeader(context);

            // Make sample decision
            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                SetSamplingDecision(request, traceHeader);
            }

            var timestamp = context.Timestamp.ToUniversalTime().ToUnixTimeSeconds(); // Gets initial timestamp of current HTTP Request

            _recorder.BeginSegment(GetSegmentNamingStrategy().GetSegmentName(request), traceHeader.RootTraceId, timestamp, traceHeader.ParentId, traceHeader.Sampled);

            if (!AWSXRayRecorder.Instance.IsTracingDisabled())
            {
                Dictionary <string, object> requestAttributes = new Dictionary <string, object>();
                ProcessRequestAttributes(request, requestAttributes);
                _recorder.AddHttpInformation("request", requestAttributes);
            }

            context.Items.Add(XRayEntity, Core.Internal.Utils.TraceContext.GetEntity());
        }
예제 #2
0
        /// <summary>
        /// Processes HTTP request.
        /// </summary>
        private static void ProcessHTTPRequest(Object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;

            string ruleName = null;

            var         request     = context.Request;
            TraceHeader traceHeader = GetTraceHeader(context);

            var segmentName = GetSegmentNamingStrategy().GetSegmentName(request);

            // Make sample decision
            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                SamplingResponse response = MakeSamplingDecision(request, traceHeader, segmentName);
                ruleName = response.RuleName;
            }

            var timestamp = context.Timestamp.ToUniversalTime();                                     // Gets initial timestamp of current HTTP Request

            SamplingResponse samplingResponse = new SamplingResponse(ruleName, traceHeader.Sampled); // get final ruleName and SampleDecision

            _recorder.BeginSegment(segmentName, traceHeader.RootTraceId, traceHeader.ParentId, samplingResponse, timestamp);

            if (!AWSXRayRecorder.Instance.IsTracingDisabled())
            {
                Dictionary <string, object> requestAttributes = new Dictionary <string, object>();
                ProcessRequestAttributes(request, requestAttributes);
                _recorder.AddHttpInformation("request", requestAttributes);
            }
        }
        /// <summary>
        /// Processes HTTP response
        /// </summary>
        private void ProcessHTTPResponse(HttpContext context)
        {
            HttpResponse response = context.Response;

            if (!AWSXRayRecorder.Instance.IsTracingDisabled())
            {
                var responseAttributes = new Dictionary <string, object>();
                PopulateResponseAttributes(response, responseAttributes);
                _recorder.AddHttpInformation("response", responseAttributes);
            }

            if (AWSXRayRecorder.Instance.IsLambda())
            {
                _recorder.EndSubsegment();
            }
            else
            {
                _recorder.EndSegment();
            }
        }
        private void AddHttpInformation(IWebResponseData httpResponse)
        {
            var responseAttributes = new Dictionary <string, object>();
            int statusCode         = (int)httpResponse.StatusCode;

            if (statusCode >= 400 && statusCode <= 499)
            {
                _recorder.MarkError();

                if (statusCode == 429)
                {
                    _recorder.MarkThrottle();
                }
            }
            else if (statusCode >= 500 && statusCode <= 599)
            {
                _recorder.MarkFault();
            }

            responseAttributes["status"]         = statusCode;
            responseAttributes["content_length"] = httpResponse.ContentLength;
            _recorder.AddHttpInformation("response", responseAttributes);
        }
예제 #5
0
        private void AddHttpInformation(IWebResponseData httpResponse)
        {
            var responseAttributes = new Dictionary <string, object>();
            var statusCode         = httpResponse.StatusCode;

            if (!statusCode.IsSuccessStatusCode())
            {
                _recorder.MarkError();

                if (statusCode.IsTooManyRequests())
                {
                    _recorder.MarkThrottle();
                }
            }
            else if (statusCode.IsFault())
            {
                _recorder.MarkFault();
            }

            responseAttributes["status"]         = statusCode;
            responseAttributes["content_length"] = httpResponse.ContentLength;
            _recorder.AddHttpInformation("response", responseAttributes);
        }
예제 #6
0
        public void TestAddHttp()
        {
            _recorder.BeginSegment("test", TraceId);
            var segment = AWSXRayRecorder.Instance.TraceContext.GetEntity();

            _recorder.AddHttpInformation("key", "value");

            Assert.AreEqual("value", segment.Http["key"]);

            _recorder.EndSegment();
        }
예제 #7
0
        public void TestLogErrorModeForContextMissingStrategy()
        {
            using (var recorder = new AWSXRayRecorder())
            {
                recorder.ContextMissingStrategy = ContextMissingStrategy.LOG_ERROR;

                recorder.EndSegment();
                recorder.BeginSubsegment("no segment");
                recorder.EndSubsegment();
                recorder.SetNamespace("dummy namespace");
                recorder.AddAnnotation("key", "value");
                recorder.AddHttpInformation("key", "value");
                recorder.MarkError();
                recorder.MarkFault();
                recorder.MarkThrottle();
                recorder.AddException(new ArgumentNullException());
                recorder.AddPrecursorId(Entity.GenerateId());
                recorder.AddSqlInformation("sqlKey", "value");
                recorder.AddMetadata("key", "value");
            }
        }
        /// <summary>
        /// Sends an HTTP request to the inner handler to send to the server as an asynchronous
        /// operation.
        /// </summary>
        /// <param name="request">The HTTP request message to send to the server.</param>
        /// <param name="cancellationToken">A cancellation token to cancel operation.</param>
        /// <returns>Returns System.Threading.Tasks.Task. The task object representing the asynchronous operation.</returns>
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            string headerSring = null;

            if (request.Headers.TryGetValues(TraceHeader.HeaderKey, out IEnumerable <string> headerValue))
            {
                headerSring = headerValue.First();
            }

            // If Trace header doesn't exist, which means this is the root node. Create a new traceId and inject the trace header.
            if (!TraceHeader.TryParse(headerSring, out TraceHeader traceHeader))
            {
                _logger.DebugFormat("Trace header doesn't exist or not valid. Injecting a new one. existing header = {0}", headerSring);
                traceHeader = new TraceHeader
                {
                    RootTraceId = TraceId.NewId(),
                    ParentId    = null,
                    Sampled     = SampleDecision.Unknown
                };
            }

            bool isSampleDecisionRequested = traceHeader.Sampled == SampleDecision.Requested;

            // Make sample decision
            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                traceHeader.Sampled = _recorder.SamplingStrategy.Sample(request);
            }

            _recorder.BeginSegment(SegmentNamingStrategy.GetSegmentName(request), traceHeader.RootTraceId, traceHeader.ParentId, traceHeader.Sampled);

            if (!AppSettings.IsXRayTracingDisabled)
            {
                var requestAttributes = new Dictionary <string, object>();
                requestAttributes["url"]    = request.RequestUri.AbsoluteUri;
                requestAttributes["method"] = request.Method.Method;
                string xForwardedFor = GetXForwardedFor(request);
                if (xForwardedFor == null)
                {
                    requestAttributes["client_ip"] = GetClientIpAddress(request);
                }
                else
                {
                    requestAttributes["client_ip"]       = xForwardedFor;
                    requestAttributes["x_forwarded_for"] = true;
                }

                requestAttributes["user_agent"] = request.Headers.UserAgent.ToString();
                _recorder.AddHttpInformation("request", requestAttributes);
            }

            var response = await base.SendAsync(request, cancellationToken);

            if (!AppSettings.IsXRayTracingDisabled)
            {
                var responseAttributes = new Dictionary <string, object>();
                int statusCode         = (int)response.StatusCode;
                if (statusCode >= 400 && statusCode <= 499)
                {
                    _recorder.MarkError();
                    if (statusCode == 429)
                    {
                        _recorder.MarkThrottle();
                    }
                }
                else if (statusCode >= 500 && statusCode <= 599)
                {
                    _recorder.MarkFault();
                }

                responseAttributes["status"] = statusCode;

                if (response.Content != null && response.Content.Headers.ContentLength != null)
                {
                    responseAttributes["content_length"] = response.Content.Headers.ContentLength;
                }

                _recorder.AddHttpInformation("response", responseAttributes);
            }

            _recorder.EndSegment();

            // If the sample decision is requested, added the trace header to response
            if (isSampleDecisionRequested)
            {
                response.Headers.Add(TraceHeader.HeaderKey, traceHeader.ToString());
            }

            return(response);
        }
        /// <summary>
        /// Process http request.
        /// </summary>
        internal static void ProcessRequest(HttpContext httpContext)
        {
            HttpRequest request      = httpContext.Request;
            string      headerString = null;

            if (request.Headers.TryGetValue(TraceHeader.HeaderKey, out StringValues headerValue))
            {
                if (headerValue.Count >= 1)
                {
                    headerString = headerValue[0];
                }
            }

            if (!TraceHeader.TryParse(headerString, out TraceHeader traceHeader))
            {
                _logger.DebugFormat("Trace header doesn't exist or not valid : ({0}). Injecting a new one.", headerString);
                traceHeader = new TraceHeader
                {
                    RootTraceId = TraceId.NewId(),
                    ParentId    = null,
                    Sampled     = SampleDecision.Unknown
                };
            }

            var  segmentName = SegmentNamingStrategy.GetSegmentName(request);
            bool isSampleDecisionRequested = traceHeader.Sampled == SampleDecision.Requested;

            string ruleName = null;

            // Make sample decision
            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                string           host           = request.Host.Host;
                string           url            = request.Path;
                string           method         = request.Method;
                SamplingInput    samplingInput  = new SamplingInput(host, url, method, segmentName, _recorder.Origin);
                SamplingResponse sampleResponse = _recorder.SamplingStrategy.ShouldTrace(samplingInput);
                traceHeader.Sampled = sampleResponse.SampleDecision;
                ruleName            = sampleResponse.RuleName;
            }

            if (AWSXRayRecorder.IsLambda())
            {
                _recorder.BeginSubsegment(segmentName);
            }
            else
            {
                SamplingResponse samplingResponse = new SamplingResponse(ruleName, traceHeader.Sampled); // get final ruleName and SampleDecision
                _recorder.BeginSegment(SegmentNamingStrategy.GetSegmentName(request), traceHeader.RootTraceId, traceHeader.ParentId, samplingResponse);
            }

            if (!AWSXRayRecorder.Instance.IsTracingDisabled())
            {
                var requestAttributes = PopulateRequestAttributes(request);
                _recorder.AddHttpInformation("request", requestAttributes);
            }

            // Mark the segment as auto-instrumented
            AgentUtil.AddAutoInstrumentationMark();

            if (isSampleDecisionRequested)
            {
                httpContext.Response.Headers.Add(TraceHeader.HeaderKey, traceHeader.ToString()); // Its recommended not to modify response header after _next.Invoke() call
            }
        }