Beispiel #1
0
        public void ServiceIdentifiers_MatchTracerInstanceSettings()
        {
            const string service = "unit-test";
            const string version = "1.0.0";
            const string env     = "staging";

            var settings = new TracerSettings()
            {
                ServiceName    = service,
                ServiceVersion = version,
                Environment    = env
            };
            var tracer = TracerHelper.Create(settings);

            Tracer.UnsafeSetTracerInstance(tracer);

            using (var parentScope = Tracer.Instance.StartActive("parent"))
                using (var childScope = Tracer.Instance.StartActive("child"))
                {
                    Assert.Equal(service, CorrelationIdentifier.Service);
                    Assert.Equal(version, CorrelationIdentifier.Version);
                    Assert.Equal(env, CorrelationIdentifier.Env);
                }

            Assert.Equal(service, CorrelationIdentifier.Service);
            Assert.Equal(version, CorrelationIdentifier.Version);
            Assert.Equal(env, CorrelationIdentifier.Env);
        }
        public void LockedTracerInstanceSwap()
        {
            var tracerOne = TracerHelper.Create();
            var tracerTwo = new LockedTracer();

            TracerRestorerAttribute.SetTracer(tracerOne);
            Tracer.Instance.Should().Be(tracerOne);
            Tracer.Instance.TracerManager.Should().Be(tracerOne.TracerManager);

            TracerRestorerAttribute.SetTracer(null);
            Tracer.Instance.Should().BeNull();

            // Set the locked tracer
            TracerRestorerAttribute.SetTracer(tracerTwo);
            Tracer.Instance.Should().Be(tracerTwo);
            Tracer.Instance.TracerManager.Should().Be(tracerTwo.TracerManager);

            // We test the locked tracer cannot be replaced.
#pragma warning disable CS0618 // Setter isn't actually obsolete, just should be internal
            Assert.Throws <InvalidOperationException>(() => Tracer.Instance = tracerOne);

            Assert.Throws <InvalidOperationException>(() => Tracer.Instance = null);

            Assert.Throws <InvalidOperationException>(() => TracerManager.ReplaceGlobalManager(null, TracerManagerFactory.Instance));
            Assert.Throws <InvalidOperationException>(() => TracerManager.ReplaceGlobalManager(null, new CITracerManagerFactory(CIVisibility.Settings)));
        }
Beispiel #3
0
        private static Tracer CreateTracerWithIntegrationEnabled(string integrationName, bool enabled)
        {
            // Set up tracer
            var tracerSettings = new TracerSettings();

            tracerSettings.Integrations[integrationName].Enabled = enabled;
            return(TracerHelper.Create(tracerSettings));
        }
        public void One_Is_Allowed()
        {
            var traceContext = new TraceContext(TracerHelper.Create());
            var spanContext  = new SpanContext(null, traceContext, "Weeeee");
            var span         = new Span(spanContext, null);
            var rateLimiter  = new RateLimiter(maxTracesPerInterval: null);
            var allowed      = rateLimiter.Allowed(span);

            Assert.True(allowed);
        }
Beispiel #5
0
        public void PopulatesOnlyRootSpans()
        {
            var vars = GetMockVariables(SubscriptionId, DeploymentId, PlanResourceGroup, SiteResourceGroup);

            AzureAppServices.Metadata = new AzureAppServices(vars);
            var tracer       = TracerHelper.Create();
            var rootSpans    = new List <ISpan>();
            var nonRootSpans = new List <ISpan>();
            var iterations   = 5;
            var remaining    = iterations;

            while (remaining-- > 0)
            {
                using (var rootScope = tracer.StartActive("root"))
                {
                    rootSpans.Add(rootScope.Span);

                    using (var nestedScope = tracer.StartActive("nest-a"))
                    {
                        nonRootSpans.Add(nestedScope.Span);
                    }

                    using (var nestedScope = tracer.StartActive("nest-b"))
                    {
                        nonRootSpans.Add(nestedScope.Span);

                        using (var doublyNestedScope = tracer.StartActive("nest-b-1"))
                        {
                            nonRootSpans.Add(doublyNestedScope.Span);
                        }
                    }
                }
            }

            Assert.Equal(expected: iterations, actual: rootSpans.Count);
            Assert.NotEmpty(nonRootSpans);

            var rootSpansMissingExpectedTag =
                rootSpans.Where(s => s.GetTag(Tags.AzureAppServicesResourceId) != ExpectedResourceId).ToList();

            var nonRootSpansWithTag =
                nonRootSpans.Where(s => s.GetTag(Tags.AzureAppServicesResourceId) == ExpectedResourceId);

            var newLine         = Environment.NewLine;
            var detailedMessage =
                string.Join(
                    Environment.NewLine,
                    rootSpansMissingExpectedTag.Select(
                        r => $"Expected {ExpectedResourceId} {newLine}but received {r.GetTag(Tags.AzureAppServicesResourceId) ?? "NULL"} {newLine}{newLine}({r}) {newLine}"));

            var envVarValues = string.Join(", ", EnvVars.Select(e => $"{e}: {Environment.GetEnvironmentVariable(e)}"));

            Assert.True(!rootSpansMissingExpectedTag.Any(), $"All root spans should have the resource id: {newLine}{envVarValues}{newLine}{detailedMessage}");
            Assert.True(!nonRootSpansWithTag.Any(), "No non root spans should have the resource id.");
        }
Beispiel #6
0
        public void SetEnv(string env)
        {
            var settings = new TracerSettings()
            {
                Environment = env,
            };

            var   tracer = TracerHelper.Create(settings);
            ISpan span   = tracer.StartSpan("operation");

            Assert.Equal(env, span.GetTag(Tags.Env));
        }
Beispiel #7
0
        public void TestCreatePlaceholderScopeFailureDueToHttpError()
        {
            var httpRequest = new Mock <WebRequest>();

            httpRequest.Setup(h => h.GetResponse()).Throws(new WebException());

            _lambdaRequestMock.Setup(lr => lr.GetTraceContextRequest()).Returns(httpRequest.Object);

            var tracer = TracerHelper.Create();
            var scope  = LambdaCommon.CreatePlaceholderScope(tracer, _lambdaRequestMock.Object);

            scope.Should().BeNull();
        }
Beispiel #8
0
        public void Service_DefaultServiceNameIfUnset()
        {
            var settings = new TracerSettings();
            var tracer   = TracerHelper.Create(settings);

            Tracer.UnsafeSetTracerInstance(tracer);

            using (var parentScope = Tracer.Instance.StartActive("parent"))
                using (var childScope = Tracer.Instance.StartActive("child"))
                {
                    Assert.Equal(CorrelationIdentifier.Service, Tracer.Instance.DefaultServiceName);
                }

            Assert.Equal(CorrelationIdentifier.Service, Tracer.Instance.DefaultServiceName);
        }
Beispiel #9
0
        public void CreateDbCommandScope_ReturnNullForAdoNetDisabledIntegration(IDbCommand command, string integrationName, string dbType)
        {
            // HACK: avoid analyzer warning about not using arguments
            _ = dbType;

            var tracerSettings = new TracerSettings();

            tracerSettings.Integrations[integrationName].Enabled = true;
            tracerSettings.Integrations[nameof(IntegrationId.AdoNet)].Enabled = false;
            var tracer = TracerHelper.Create(tracerSettings);

            // Create scope
            using var scope = CreateDbCommandScope(tracer, command);
            Assert.Null(scope);
        }
        public void NormalTracerInstanceSwap()
        {
            var tracerOne = TracerHelper.Create();
            var tracerTwo = TracerHelper.Create();

            TracerRestorerAttribute.SetTracer(tracerOne);
            Tracer.Instance.Should().Be(tracerOne);
            Tracer.Instance.TracerManager.Should().Be(tracerOne.TracerManager);

            TracerRestorerAttribute.SetTracer(tracerTwo);
            Tracer.Instance.Should().Be(tracerTwo);
            Tracer.Instance.TracerManager.Should().Be(tracerTwo.TracerManager);

            TracerRestorerAttribute.SetTracer(null);
            Tracer.Instance.Should().BeNull();
        }
Beispiel #11
0
        public void CreateDbCommandScope_UsesReplacementServiceNameWhenProvided(IDbCommand command, string integrationName, string dbType)
        {
            // HACK: avoid analyzer warning about not using arguments
            _ = integrationName;

            // Set up tracer
            var collection = new NameValueCollection {
                { ConfigurationKeys.ServiceNameMappings, $"{dbType}:my-custom-type" }
            };
            IConfigurationSource source = new NameValueConfigurationSource(collection);
            var tracerSettings          = new TracerSettings(source);
            var tracer = TracerHelper.Create(tracerSettings);

            // Create scope
            using var scope = CreateDbCommandScope(tracer, command);
            Assert.Equal("my-custom-type", scope.Span.ServiceName);
        }
Beispiel #12
0
        public void VersionAndEnv_EmptyStringIfUnset()
        {
            var settings = new TracerSettings();
            var tracer   = TracerHelper.Create(settings);

            Tracer.UnsafeSetTracerInstance(tracer);

            using (var parentScope = Tracer.Instance.StartActive("parent"))
                using (var childScope = Tracer.Instance.StartActive("child"))
                {
                    Assert.Equal(string.Empty, CorrelationIdentifier.Version);
                    Assert.Equal(string.Empty, CorrelationIdentifier.Env);
                }

            Assert.Equal(string.Empty, CorrelationIdentifier.Version);
            Assert.Equal(string.Empty, CorrelationIdentifier.Env);
        }
Beispiel #13
0
        public void TestCreatePlaceholderScopeFailureDueToInvalidLong()
        {
            var response = new Mock <HttpWebResponse>(MockBehavior.Loose);

            response.Setup(c => c.StatusCode).Returns(HttpStatusCode.OK);
            response.Setup(c => c.Headers.Get("x-datadog-trace-id")).Returns("#$#");
            response.Setup(c => c.Headers.Get("x-datadog-span-id")).Returns("xxx_yyy");

            var httpRequest = new Mock <WebRequest>();

            httpRequest.Setup(h => h.GetResponse()).Returns(response.Object);

            _lambdaRequestMock.Setup(lr => lr.GetTraceContextRequest()).Returns(httpRequest.Object);

            var tracer = TracerHelper.Create();
            var scope  = LambdaCommon.CreatePlaceholderScope(tracer, _lambdaRequestMock.Object);

            scope.Should().BeNull();
        }
        private static int AskTheRateLimiterABunchOfTimes(RateLimiter rateLimiter, int howManyTimes)
        {
            var traceContext = new TraceContext(TracerHelper.Create());
            var spanContext  = new SpanContext(null, traceContext, "Weeeee");
            var span         = new Span(spanContext, null);

            var remaining    = howManyTimes;
            var allowedCount = 0;

            while (remaining-- > 0)
            {
                var allowed = rateLimiter.Allowed(span);
                if (allowed)
                {
                    allowedCount++;
                }
            }

            return(allowedCount);
        }
Beispiel #15
0
        public void TestCreatePlaceholderScopeSuccess()
        {
            var response = new Mock <HttpWebResponse>(MockBehavior.Loose);

            response.Setup(c => c.StatusCode).Returns(HttpStatusCode.OK);
            response.Setup(c => c.Headers.Get("x-datadog-trace-id")).Returns("1111");
            response.Setup(c => c.Headers.Get("x-datadog-span-id")).Returns("2222");

            var httpRequest = new Mock <WebRequest>();

            httpRequest.Setup(h => h.GetResponse()).Returns(response.Object);

            _lambdaRequestMock.Setup(lr => lr.GetTraceContextRequest()).Returns(httpRequest.Object);

            var tracer = TracerHelper.Create();
            var scope  = LambdaCommon.CreatePlaceholderScope(tracer, _lambdaRequestMock.Object);

            scope.Should().NotBeNull();
            scope.Span.TraceId.ToString().Should().Be("1111");
            scope.Span.SpanId.ToString().Should().Be("2222");
        }
Beispiel #16
0
        public void SetServiceName(string tracerServiceName, string spanServiceName, string expectedServiceName)
        {
            var settings = new TracerSettings()
            {
                ServiceName = tracerServiceName,
            };

            var   tracer = TracerHelper.Create(settings);
            ISpan span   = tracer.StartSpan("operationName", serviceName: spanServiceName);

            if (expectedServiceName == null)
            {
                // due to the service name fallback, if this runs at the same time as AzureAppServicesMetadataTests,
                // then AzureAppServices.IsRelevant returns true, and we may pull the service name from the AAS env vars
                var expectedServiceNames = TestRunners.ValidNames.Concat(new[] { AzureAppServicesTests.DeploymentId });
                Assert.Contains(span.ServiceName, expectedServiceNames);
            }
            else
            {
                Assert.Equal(expectedServiceName, span.ServiceName);
            }
        }
Beispiel #17
0
        public void ManuallyDistributedTrace_CarriesExpectedValues()
        {
            var tracer = TracerHelper.Create();

            ulong  traceId;
            ulong  parentSpanId;
            string samplingPriorityText;
            var    expectedSamplingPriority = SamplingPriorityValues.UserKeep;

            using (var scope = tracer.StartActive("manual.trace"))
            {
                scope.Span.SetTag(Tags.SamplingPriority, expectedSamplingPriority.ToString());
                traceId = scope.Span.TraceId;

                using (var parentSpanOfDistributedTrace = tracer.StartActive("SortOrders"))
                {
                    parentSpanId         = scope.Span.SpanId;
                    samplingPriorityText = parentSpanOfDistributedTrace.Span.GetTag(Tags.SamplingPriority);
                }
            }

            var distributedTraceContext = new SpanContext(traceId, parentSpanId);
            var secondTracer            = TracerHelper.Create();
            var spanCreationSettings    = new SpanCreationSettings()
            {
                Parent = distributedTraceContext
            };

            using (var scope = secondTracer.StartActive("manual.trace", spanCreationSettings))
            {
                scope.Span.SetTag(Tags.SamplingPriority, samplingPriorityText);
                Assert.True(scope.Span.TraceId == traceId, "Trace ID must match the parent trace.");
                var actualSamplingPriorityText = scope.Span.GetTag(Tags.SamplingPriority);
                Assert.True(actualSamplingPriorityText.Equals(expectedSamplingPriority.ToString()), "Sampling priority of manual distributed trace must match the original trace.");
            }
        }