コード例 #1
0
        public void TestEFCoreRequestWithEntityFrameworkCoreAndSqlDiagnosticListener()
        {
            // EntityFramework request will first trigger EntityFrameworkCoreDiagnosticListener and then SqlDiagnosticListener,
            // With EntityFrameworkCoreDiagnosticListener, SqlDiagnosticListener will process EF Core request.
            var subscription = new List <DiagnosticListenerBase>()
            {
                new EntityFrameworkCoreDiagnosticListener(),
                new SqlDiagnosticListener()
            };

            _subscription = DiagnosticListener.AllListeners.Subscribe(new DiagnosticListenerObserver(subscription));

            _recorder.BeginSegment("EFCoreRequestWithEntityFrameworkCoreAndSqlDiagnosticListener");

            var context = GetTestEFContext();

            var users = context.Users.Where(u => u.UserId == 1).ToList();

            var segment = _recorder.TraceContext.GetEntity();

            Assert.AreEqual(4, segment.Subsegments.Count);
            var subsegment = segment.Subsegments[3];

            Assert.IsNotNull(subsegment);
            Assert.IsNotNull(subsegment.Sql);
            Assert.AreEqual(0, subsegment.Subsegments.Count); // No nested duplicate subsegment
            Assert.AreEqual("sqlite", subsegment.Sql["database_type"]);
            Assert.AreEqual(_connectionString, subsegment.Sql["connection_string"]);
            Assert.AreEqual(connection.ServerVersion, subsegment.Sql["database_version"]);
            _recorder.EndSegment();
        }
コード例 #2
0
        /// <summary>
        /// Processes HTTP response.
        /// </summary>
        private static void ProcessHTTPResponse(Object sender, EventArgs e)
        {
            var context  = ((HttpApplication)sender).Context;
            var response = context.Response;

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

            Exception exc = context.Error; // Record exception, if any

            if (exc != null)
            {
                _recorder.AddException(exc);
            }

            TraceHeader traceHeader = GetTraceHeader(context);
            bool        isSampleDecisionRequested = traceHeader.Sampled == SampleDecision.Requested;

            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                SetSamplingDecision(traceHeader); // extracts sampling decision from the available segment
            }

            _recorder.EndSegment();
            // if the sample decision is requested, add the trace header to response
            if (isSampleDecisionRequested)
            {
                response.Headers.Add(TraceHeader.HeaderKey, traceHeader.ToString());
            }
        }
コード例 #3
0
        public async Task TestXrayContextMissingStrategySendAsync() // Test that respects ContextMissingStrategy
        {
            _recorder = new MockAWSXRayRecorder();

#if NET45
            AWSXRayRecorder.InitializeInstance(_recorder);
#else
            AWSXRayRecorder.InitializeInstance(recorder: _recorder);
#endif

            AWSXRayRecorder.Instance.ContextMissingStrategy = Core.Strategies.ContextMissingStrategy.LOG_ERROR;

            Assert.IsFalse(AWSXRayRecorder.Instance.IsTracingDisabled());

            _recorder.EndSegment();

            // The test should not break. No segment is available in the context, however, since the context missing strategy is log error,
            // no exception should be thrown by below code.

            var request = new HttpRequestMessage(HttpMethod.Get, URL);
            using (var response = await _httpClient.SendAsync(request))
            {
                Assert.IsNotNull(response);
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
コード例 #4
0
 public new void TestCleanup()
 {
     connection.Close();
     connection.Dispose();
     recorder.EndSegment();
     recorder.Dispose();
     base.TestCleanup();
 }
コード例 #5
0
 public void TestSegmentEndInLambda()
 {
     try
     {
         _recorder.EndSegment();
         Assert.Fail();
     }
     catch (UnsupportedOperationException)
     {
         // expected
     }
 }
コード例 #6
0
        public void Test_EFCore_unsuccessful_query()
        {
            var recorder = new AWSXRayRecorder();

            recorder.BeginSegment("TestSegment");
            var context = GetTestEFContext(false);
            var users   = context.Users.Where(u => u.UserId == 1).ToList();

            var segment = recorder.TraceContext.GetEntity();

            Assert.AreEqual(3, segment.Subsegments.Count);
            var query_subsegment = segment.Subsegments[2];

            AssertQueryNotCollected(query_subsegment);
            recorder.EndSegment();
        }
コード例 #7
0
        /// <summary>
        /// Process http response.
        /// </summary>
        internal static void ProcessResponse(HttpContext httpContext)
        {
            HttpResponse response = httpContext.Response;

            if (!AWSXRayRecorder.Instance.IsTracingDisabled())
            {
                var responseAttributes = PopulateResponseAttributes(response);
                _recorder.AddHttpInformation("response", responseAttributes);
            }

            if (AWSXRayRecorder.IsLambda())
            {
                _recorder.EndSubsegment();
            }
            else
            {
                _recorder.EndSegment();
            }
        }
コード例 #8
0
        public void TestTryParseSubsegment()
        {
            using (var recorder = new AWSXRayRecorder())
            {
                recorder.BeginSegment("TraceHeaderTest", TraceId);
                recorder.BeginSubsegment("subjob");
                var subsegment = TraceContext.GetEntity();

                TraceHeader header;
                Assert.IsTrue(TraceHeader.TryParse(subsegment, out header));

                Assert.AreEqual(TraceId, header.RootTraceId);
                Assert.AreEqual(subsegment.Id, header.ParentId);
                Assert.AreEqual(SampleDecision.Sampled, header.Sampled);

                recorder.EndSubsegment();
                recorder.EndSegment();
            }
        }
コード例 #9
0
        public void Test_EFCore_successful_query()
        {
            // Arrange
            var recorder = new AWSXRayRecorder();

            recorder.BeginSegment("TestSegment");
            var context = GetTestEFContext(true);
            // Act
            var users = context.Users.Where(u => u.UserId == 1).ToList();

            // Assert
            var segment = recorder.TraceContext.GetEntity();

            Assert.AreEqual(3, segment.Subsegments.Count); //2 subsegments from validating the db and 1 from the actual query
            var query_subsegment = segment.Subsegments[2];

            AssertQueryCollected(query_subsegment);

            recorder.EndSegment();
        }
コード例 #10
0
        /// <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();
            }
        }
コード例 #11
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");
            }
        }
コード例 #12
0
        public async Task InterceptAsync_DoesNot_CollectQueries_When_NotEnabled()
        {
            // arrange
#if !NET45
            var recorder = new AWSXRayRecorder {
                XRayOptions = new XRayOptions()
            };
#else
            var recorder = new AWSXRayRecorder();
#endif
            recorder.BeginSegment("test");
            var interceptor = new DbCommandInterceptor(recorder);

            // act
            await interceptor.InterceptAsync(() => Task.FromResult(0), _command);

            // assert
            var segment = AWSXRayRecorder.Instance.TraceContext.GetEntity();

            AssertNotCollected(recorder);
            recorder.EndSegment();
        }
コード例 #13
0
        public void TestTrustedConnection_DoesNotCollectUserID()
        {
            // arrange
#if !NET45
            var recorder = new AWSXRayRecorder {
                XRayOptions = new XRayOptions()
            };
#else
            var recorder = new AWSXRayRecorder();
#endif
            InitializeMockTrustedConnection();
            recorder.BeginSegment("test");
            var interceptor = new DbCommandInterceptor(recorder);

            // act
            interceptor.Intercept(() => 0, _command);

            // assert
            var segment = AWSXRayRecorder.Instance.TraceContext.GetEntity();

            AssertNotCollected(recorder, true);
            recorder.EndSegment();
        }
コード例 #14
0
        public async Task InterceptAsync_DoesNot_CollectQueries_When_EnabledGlobally_And_DisabledLocally()
        {
            // arrange
#if !NET45
            var recorder = new AWSXRayRecorder {
                XRayOptions = new XRayOptions {
                    CollectSqlQueries = true
                }
            };
#else
            ConfigurationManager.AppSettings[_collectSqlQueriesKey] = "true";
            AppSettings.Reset();
            var recorder = new AWSXRayRecorder();
#endif
            var interceptor = new DbCommandInterceptor(recorder, collectSqlQueries: false);
            recorder.BeginSegment("test");

            // act
            await interceptor.InterceptAsync(() => Task.FromResult(0), _command);

            // assert
            AssertNotCollected(recorder);
            recorder.EndSegment();
        }
コード例 #15
0
        public void Test_EFCore_query_with_exception()
        {
            var recorder = new AWSXRayRecorder();

            recorder.BeginSegment("TestSegment");
            var context = GetTestEFContext(true);

            try
            {
                context.Database.ExecuteSqlCommand("Select * From FakeTable"); // A false sql command which results in 'no such table: FakeTable' exception
            }
            catch
            {
                // ignore
            }

            var segment = recorder.TraceContext.GetEntity();

            Assert.AreEqual(3, segment.Subsegments.Count);
            var subsegment = segment.Subsegments[2];

            Assert.AreEqual(true, subsegment.HasFault);
            recorder.EndSegment();
        }
コード例 #16
0
        public void Intercept_CollectsQueries_When_EnabledGlobally()
        {
            // arrange
#if !NET45
            var recorder = new AWSXRayRecorder {
                XRayOptions = new XRayOptions {
                    CollectSqlQueries = true
                }
            };
#else
            ConfigurationManager.AppSettings[_collectSqlQueriesKey] = "true";
            AppSettings.Reset();
            var recorder = new AWSXRayRecorder();
#endif
            var interceptor = new DbCommandInterceptor(recorder);
            recorder.BeginSegment("test");

            // act
            interceptor.Intercept(() => 0, _command);

            // assert
            AssertCollected(recorder);
            recorder.EndSegment();
        }
コード例 #17
0
        public void TestAddEventHandlerToDynamoDBClient()
        {
            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                _handler.AddEventHandler(client);
                string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere";
                CustomResponses.SetResponse(client, null, requestId, true);

                _recorder.BeginSegment("test", TraceId);

                client.ListTables();

                var segment    = TraceContext.GetEntity();
                var subsegment = segment.Subsegments[0];
                _recorder.EndSegment();

                Assert.AreEqual(segment.Subsegments.Count, 1);
                Assert.AreEqual(subsegment.Name, "DynamoDBv2");
                Assert.AreEqual(subsegment.Aws["region"], RegionEndpoint.USEast1.SystemName);
                Assert.AreEqual(subsegment.Aws["operation"], "ListTables");
                Assert.AreEqual(requestId, subsegment.Aws["request_id"]);
                Assert.AreEqual("aws", subsegment.Namespace);
            }
        }
コード例 #18
0
        public void TestSyncCreateSegmentAndSubsegments()
        {
            _recorder.BeginSegment("parent", TraceId);

            Segment parent = (Segment)AWSXRayRecorder.Instance.TraceContext.GetEntity();

            _recorder.BeginSubsegment("child");
            Subsegment child = (Subsegment)AWSXRayRecorder.Instance.TraceContext.GetEntity();

            _recorder.EndSubsegment();
            Assert.ReferenceEquals(AWSXRayRecorder.Instance.TraceContext.GetEntity(), parent);

            _recorder.EndSegment();

            Assert.ReferenceEquals(parent, child.Parent);
            Assert.IsTrue(parent.Subsegments.Contains(child));
        }
コード例 #19
0
        /// <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);
        }