public void SqlTraceIsSentToAggregator()
        {
            var commandText      = "Select * from Table1";
            var duration         = TimeSpan.FromMilliseconds(500);
            var datastoreSegment = TestTransactions.BuildSegment(null, DatastoreVendor.MSSQL, "Table1", commandText, new TimeSpan(), duration, null, null, null, "myhost", "myport", "mydatabase");
            var segments         = Enumerable.Empty <Segment>();

            segments = segments.Concat(new[] { datastoreSegment });

            var transaction     = TestTransactions.CreateTestTransactionWithSegments(segments);
            var transactionName = _transactionMetricNameMaker.GetTransactionMetricName(transaction.TransactionName);

            Mock.Arrange(() => _configuration.SlowSqlEnabled).Returns(true);
            Mock.Arrange(() => _configuration.SqlExplainPlanThreshold).Returns(TimeSpan.FromMilliseconds(100));

            var privateTransactionTransformer = new PrivateAccessor(_transactionTransformer);
            var args = new object[] { transaction, transactionName };

            privateTransactionTransformer.CallMethod("Transform", args);

            var privateSqlTraceStatsInAggregator = new PrivateAccessor(_sqlTraceAggregator).GetField("_sqlTraceStats");
            var privateSqlTraceStatsCollection   = (SqlTraceStatsCollection)privateSqlTraceStatsInAggregator;
            var tracesCount = ((IDictionary <long, SqlTraceWireModel>)privateSqlTraceStatsCollection.Collection).Count;

            Assert.AreEqual(tracesCount, 1);
        }
        public void SetUp()
        {
            _localConfig = new configuration();
            _localConfig.distributedTracing.enabled = true;
            _serverConfig  = new ServerConfiguration();
            _runTimeConfig = new RunTimeConfiguration();
            _defaultConfig = new TestableDefaultConfiguration(Mock.Create <IEnvironment>(), _localConfig, _serverConfig, _runTimeConfig,
                                                              new SecurityPoliciesConfiguration(), Mock.Create <IProcessStatic>(), Mock.Create <IHttpRuntimeStatic>(), Mock.Create <IConfigurationManagerStatic>(),
                                                              Mock.Create <IDnsStatic>());

            _transactionMetricNameMaker = Mock.Create <ITransactionMetricNameMaker>();
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.Matches <ITransactionName>(txName => txName.IsWeb)))
            .Returns(new TransactionMetricName("WebTransaction", "TransactionName"));
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.Matches <ITransactionName>(txName => !txName.IsWeb))).Returns(new TransactionMetricName("OtherTransaction", "TransactionName"));

            _transactionSegmentState = Mock.Create <ITransactionSegmentState>();
            Mock.Arrange(() => _transactionSegmentState.GetRelativeTime()).Returns(() => TimeSpan.Zero);
            Mock.Arrange(() => _transactionSegmentState.AttribDefs).Returns(() => new AttributeDefinitions(new AttributeFilter(new AttributeFilter.Settings())));

            _segmentTreeMaker = Mock.Create <ISegmentTreeMaker>();

            _metricNameService = Mock.Create <IMetricNameService>();

            _metricBuilder    = Mock.Create <IMetricBuilder>();
            _metricAggregator = Mock.Create <IMetricAggregator>();

            _configurationService = Mock.Create <IConfigurationService>();
            Mock.Arrange(() => _configurationService.Configuration).Returns(_defaultConfig);

            _transactionTraceAggregator = Mock.Create <ITransactionTraceAggregator>();
            _transactionTraceMaker      = Mock.Create <ITransactionTraceMaker>();
            _transactionEventAggregator = Mock.Create <ITransactionEventAggregator>();
            _transactionEventMaker      = Mock.Create <ITransactionEventMaker>();
            _transactionAttributeMaker  = Mock.Create <ITransactionAttributeMaker>();
            _errorTraceAggregator       = Mock.Create <IErrorTraceAggregator>();
            _errorTraceMaker            = Mock.Create <IErrorTraceMaker>();
            _errorEventAggregator       = Mock.Create <IErrorEventAggregator>();
            _errorEventMaker            = Mock.Create <IErrorEventMaker>();
            _sqlTraceAggregator         = Mock.Create <ISqlTraceAggregator>();
            _sqlTraceMaker = Mock.Create <ISqlTraceMaker>();

            _spanEventAggregator = Mock.Create <ISpanEventAggregator>();
            Mock.Arrange(() => _spanEventAggregator.IsServiceEnabled).Returns(() => _defaultConfig != null && _defaultConfig.SpanEventsEnabled && _defaultConfig.SpanEventsMaxSamplesStored > 0 && _defaultConfig.DistributedTracingEnabled);
            Mock.Arrange(() => _spanEventAggregator.IsServiceAvailable).Returns(() => _defaultConfig != null && _defaultConfig.SpanEventsEnabled && _defaultConfig.SpanEventsMaxSamplesStored > 0 && _defaultConfig.DistributedTracingEnabled);

            _spanEventAggregatorInfiniteTracing = Mock.Create <ISpanEventAggregatorInfiniteTracing>();
            Mock.Arrange(() => _spanEventAggregatorInfiniteTracing.IsServiceEnabled).Returns(() => !string.IsNullOrWhiteSpace(_defaultConfig?.InfiniteTracingTraceObserverHost));
            Mock.Arrange(() => _spanEventAggregatorInfiniteTracing.IsServiceAvailable).Returns(() => !string.IsNullOrWhiteSpace(_defaultConfig?.InfiniteTracingTraceObserverHost));

            _spanEventMaker        = Mock.Create <ISpanEventMaker>();
            _customEventAggregator = Mock.Create <ICustomEventAggregator>();
            _errorService          = Mock.Create <IErrorService>();

            _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            _agentTimerService      = Mock.Create <IAgentTimerService>();
            _transactionTransformer = new TransactionTransformer(_transactionMetricNameMaker, _segmentTreeMaker, _metricNameService, _metricAggregator, _configurationService, _transactionTraceAggregator, _transactionTraceMaker, _transactionEventAggregator, _transactionEventMaker, _transactionAttributeMaker, _errorTraceAggregator, _errorTraceMaker, _errorEventAggregator, _errorEventMaker, _sqlTraceAggregator, _sqlTraceMaker, _spanEventAggregator, _spanEventMaker, _agentTimerService, Mock.Create <IAdaptiveSampler>(), _errorService, _spanEventAggregatorInfiniteTracing);
            _customEventTransformer = new CustomEventTransformer(_configurationService, _customEventAggregator, _attribDefSvc);
        }
        public void SetUp()
        {
            // Mocks
            _transactionMetricNameMaker = Mock.Create <ITransactionMetricNameMaker>();
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.Matches <ITransactionName>(txName => txName.IsWeb)))
            .Returns(new TransactionMetricName("WebTransaction", "TransactionName"));
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.Matches <ITransactionName>(txName => !txName.IsWeb))).Returns(new TransactionMetricName("OtherTransaction", "TransactionName"));

            _metricAggregator = Mock.Create <IMetricAggregator>();

            _configuration        = GetDefaultConfiguration();
            _configurationService = Mock.Create <IConfigurationService>();
            Mock.Arrange(() => _configurationService.Configuration).Returns(_configuration);

            _transactionTraceAggregator         = Mock.Create <ITransactionTraceAggregator>();
            _transactionTraceMaker              = Mock.Create <ITransactionTraceMaker>();
            _transactionEventAggregator         = Mock.Create <ITransactionEventAggregator>();
            _transactionEventMaker              = Mock.Create <ITransactionEventMaker>();
            _transactionAttributeMaker          = Mock.Create <ITransactionAttributeMaker>();
            _errorTraceAggregator               = Mock.Create <IErrorTraceAggregator>();
            _errorTraceMaker                    = Mock.Create <IErrorTraceMaker>();
            _errorEventAggregator               = Mock.Create <IErrorEventAggregator>();
            _errorEventMaker                    = Mock.Create <IErrorEventMaker>();
            _spanEventAggregator                = Mock.Create <ISpanEventAggregator>();
            _spanEventAggregatorInfiniteTracing = Mock.Create <ISpanEventAggregatorInfiniteTracing>();
            _spanEventMaker    = Mock.Create <ISpanEventMaker>();
            _agentTimerService = Mock.Create <IAgentTimerService>();

            _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));
            _errorService = Mock.Create <IErrorService>();

            // Non-Mocks
            _segmentTreeMaker = new SegmentTreeMaker();

            _metricNameService = Mock.Create <IMetricNameService>();
            Mock.Arrange(() => _metricNameService.RenameMetric(Arg.IsAny <string>())).Returns <string>(name => name);

            var dataTransportService = Mock.Create <DataTransport.IDataTransportService>();
            var scheduler            = Mock.Create <Time.IScheduler>();
            var processStatic        = Mock.Create <SystemInterfaces.IProcessStatic>();
            var agentHealthReporter  = Mock.Create <AgentHealth.IAgentHealthReporter>();

            _sqlTraceAggregator = new SqlTraceAggregator(dataTransportService, scheduler, processStatic, agentHealthReporter);

            _transactionAttributeMaker = new TransactionAttributeMaker(_configurationService, _attribDefSvc);

            _sqlTraceMaker = new SqlTraceMaker(_configurationService, _attribDefSvc, new DatabaseService(Mock.Create <ICacheStatsReporter>()));

            // create TransactionTransformer
            _transactionTransformer = new TransactionTransformer(_transactionMetricNameMaker, _segmentTreeMaker, _metricNameService, _metricAggregator, _configurationService, _transactionTraceAggregator, _transactionTraceMaker, _transactionEventAggregator, _transactionEventMaker, _transactionAttributeMaker, _errorTraceAggregator, _errorTraceMaker, _errorEventAggregator, _errorEventMaker, _sqlTraceAggregator, _sqlTraceMaker, _spanEventAggregator, _spanEventMaker, _agentTimerService, Mock.Create <IAdaptiveSampler>(), _errorService, _spanEventAggregatorInfiniteTracing);
        }
        public void Transform(IInternalTransaction transaction)
        {
            if (transaction.Ignored)
            {
                return;
            }

            ComputeSampled(transaction);

            var immutableTransaction = transaction.ConvertToImmutableTransaction();

            // Note: Metric names are normally handled internally by the IMetricBuilder. However, transactionMetricName is an exception because (sadly) it is used for more than just metrics. For example, transaction events need to use metric name, as does RUM and CAT.
            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);

            if (transactionMetricName.ShouldIgnore)
            {
                Log.FinestFormat("Transaction \"{0}\" is being ignored due to metric naming rules", transactionMetricName);
                return;
            }

            using (_agentTimerService.StartNew("Transform", transactionMetricName.PrefixedName))
            {
                Transform(immutableTransaction, transactionMetricName);
            }

            Log.FinestFormat("Transaction {0} ({1}) transform completed.", transaction.Guid, transactionMetricName);
        }
        public void SetUp()
        {
            _configuration = Mock.Create <IConfiguration>();

            _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            Mock.Arrange(() => _configuration.ErrorCollectorEnabled).Returns(true);
            Mock.Arrange(() => _configuration.ErrorCollectorCaptureEvents).Returns(true);

            _configurationService = Mock.Create <IConfigurationService>();
            Mock.Arrange(() => _configurationService.Configuration).Returns(_configuration);

            _transactionMetricNameMaker = Mock.Create <ITransactionMetricNameMaker>();
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny <ITransactionName>()))
            .Returns(new TransactionMetricName("WebTransaction", "TransactionName"));

            _segmentTreeMaker = Mock.Create <ISegmentTreeMaker>();
            Mock.Arrange(() => _segmentTreeMaker.BuildSegmentTrees(Arg.IsAny <IEnumerable <Segment> >()))
            .Returns(new[] { BuildNode() });

            _errorEventMaker = new ErrorEventMaker(_attribDefSvc);

            _timerFactory = new TimerFactory();

            _transactionAttributeMaker = new TransactionAttributeMaker(_configurationService, _attribDefSvc);
            _errorService = new ErrorService(_configurationService);
        }
Esempio n. 6
0
        public void GetTransactionEvent_ReturnsSyntheticEvent()
        {
            // ARRANGE
            var transaction = BuildTestTransaction(isSynthetics: true);

            var immutableTransaction  = transaction.ConvertToImmutableTransaction();
            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);
            var txStats    = new TransactionMetricStatsCollection(transactionMetricName);
            var attributes = _transactionAttributeMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15), txStats);

            // ACT
            var transactionEvent = _transactionEventMaker.GetTransactionEvent(immutableTransaction, attributes);

            // ASSERT
            Assert.NotNull(transactionEvent);
            Assert.IsTrue(transactionEvent.IsSynthetics);
        }
        private void OnTransactionFinalized(TransactionFinalizedEvent eventData)
        {
            var internalTransaction = eventData.Transaction;

            // When a transaction gets finalized it means it never ended cleanly, so we should try to estimate when it ended based on its last finished segment
            var immutableTransaction = internalTransaction.ConvertToImmutableTransaction();
            var lastStartedSegment   = TryGetLastStartedSegment(immutableTransaction);
            var lastFinishedSegment  = TryGetLastFinishedSegment(immutableTransaction);
            var estimatedDuration    = GetEstimatedTransactionDuration(internalTransaction, lastStartedSegment, lastFinishedSegment);
            var finishedTransaction  = false;

            try
            {
                internalTransaction.ForceChangeDuration(estimatedDuration);

                // Then we should mark the transaction as cleanly finished so it won't get finalized again
                finishedTransaction = Finish(internalTransaction);

                if (finishedTransaction)
                {
                    // Then we send it off to be transformed as with normal transactions
                    _transactionTransformer.Transform(internalTransaction);
                }
            }
            finally
            {
                if (finishedTransaction)
                {
                    // Finally, we announce the event to our agent health reporter
                    var transactionMetricName   = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);
                    var lastFinishedSegmentName = lastFinishedSegment != null
                        ? lastFinishedSegment.GetTransactionTraceName()
                        : "<unknown>";

                    var lastStartedSegmentName = lastStartedSegment != null
                        ? lastStartedSegment.GetTransactionTraceName()
                        : "<unknown>";

                    _agentHealthReporter.ReportTransactionGarbageCollected(transactionMetricName, lastStartedSegmentName, lastFinishedSegmentName);
                }
            }
        }
Esempio n. 8
0
        public string GetScript(IInternalTransaction transaction, string nonce)
        {
            if (string.IsNullOrEmpty(_configurationService.Configuration.BrowserMonitoringJavaScriptAgent))
            {
                return(null);
            }

            if (_configurationService.Configuration.BrowserMonitoringJavaScriptAgentLoaderType.Equals("none", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            if (transaction.Ignored)
            {
                Log.Debug("Skipping RUM injection because transaction is ignored");
                return(null);
            }

            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(transaction.CandidateTransactionName.CurrentTransactionName);

            if (transactionMetricName.ShouldIgnore)
            {
                Log.Debug("Skipping RUM injection because transaction name is ignored");
                return(null);
            }

            var licenseKey = _configurationService.Configuration.AgentLicenseKey;

            if (licenseKey == null)
            {
                throw new NullReferenceException(nameof(licenseKey));
            }
            if (licenseKey.Length <= 0)
            {
                throw new Exception("License key is empty");
            }

            var browserConfigurationData = GetBrowserConfigurationData(transaction, transactionMetricName, licenseKey);

            // getting a stack trace is expensive, so only do it if we are going to log
            if (Log.IsFinestEnabled)
            {
                transaction.LogFinest("RUM: TryGetBrowserTimingHeader success.");
            }

            var scriptNonce = String.IsNullOrEmpty(nonce) ? String.Empty : $@" nonce=""{HttpUtility.HtmlAttributeEncode(nonce)}""";

            // The JavaScript variable NREUMQ stands for New Relic End User Metric "Q". This was the name before marketing renamed "EUM" to "RUM".
            // We can't change the name of the variable since: (a) we have to be consistent across agents, and (b) it has to be in sync with the rum.js file which is downloaded from NR servers.
            var javascriptAgentConfiguration = $"window.NREUM||(NREUM={{}});NREUM.info = {browserConfigurationData.ToJsonString()}";
            var javascriptAgent = _configurationService.Configuration.BrowserMonitoringJavaScriptAgent;

            return($"<script type=\"text/javascript\"{scriptNonce}>{javascriptAgentConfiguration}</script><script type=\"text/javascript\"{scriptNonce}>{javascriptAgent}</script>");
        }
        public void GetErrorEvent_InTransaction_IfStatusCodeIs404_ContainsCorrectAttributes()
        {
            var transaction          = BuildTestTransaction(statusCode: 404, uri: "http://www.newrelic.com/test?param=value", isSynthetics: false, isCAT: false, referrerUri: "http://referrer.uri");
            var immutableTransaction = transaction.ConvertToImmutableTransaction();

            var errorData             = transaction.TransactionMetadata.TransactionErrorState.ErrorData;
            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);
            var txStats = new TransactionMetricStatsCollection(transactionMetricName);

            var attributes = _transactionAttributeMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15), txStats);

            var errorEvent = _errorEventMaker.GetErrorEvent(immutableTransaction, attributes);

            var intrinsicAttributes = errorEvent.IntrinsicAttributes().Keys.ToArray();
            var agentAttributes     = errorEvent.AgentAttributes().Keys.ToArray();
            var userAttributes      = errorEvent.UserAttributes().Keys.ToArray();

            NrAssert.Multiple(
                () => Assert.AreEqual(false, errorEvent.IsSynthetics),
                () => Assert.AreEqual(7, agentAttributes.Length),
                () => Assert.AreEqual(7, intrinsicAttributes.Length),
                () => Assert.AreEqual(0, userAttributes.Length),

                () => Assert.Contains("queue_wait_time_ms", agentAttributes),
                () => Assert.Contains("response.status", agentAttributes),
                () => Assert.Contains("http.statusCode", agentAttributes),
                () => Assert.Contains("original_url", agentAttributes),
                () => Assert.Contains("request.uri", agentAttributes),
                () => Assert.Contains("request.referer", agentAttributes),
                () => Assert.Contains("host.displayName", agentAttributes),

                () => Assert.Contains("duration", intrinsicAttributes),
                () => Assert.Contains("error.class", intrinsicAttributes),
                () => Assert.Contains("error.message", intrinsicAttributes),
                () => Assert.Contains("queueDuration", intrinsicAttributes),
                () => Assert.Contains("transactionName", intrinsicAttributes),
                () => Assert.Contains("timestamp", intrinsicAttributes),
                () => Assert.Contains("type", intrinsicAttributes)
                );
        }
        public void SetUp()
        {
            UpdateDefaultConfiguration();

            var configurationService = Mock.Create <IConfigurationService>();

            Mock.Arrange(() => configurationService.Configuration).Returns(() => _configuration);

            _configurationAutoResponder = new ConfigurationAutoResponder(_configuration);

            _transactionMetricNameMaker = Mock.Create <ITransactionMetricNameMaker>();
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny <ITransactionName>())).Returns(new TransactionMetricName("prefix", "suffix"));

            _transactionAttributeMaker = Mock.Create <ITransactionAttributeMaker>();
            _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            _browserMonitoringScriptMaker = new BrowserMonitoringScriptMaker(configurationService, _transactionMetricNameMaker, _transactionAttributeMaker, _attribDefSvc);
        }
        public void Test(TestCase testCase)
        {
            // ARRANGE
            SetUp(testCase);

            var transactionMetricName = GetTransactionMetricName(testCase.TransactionName);

            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny <ITransactionName>()))
            .Returns(transactionMetricName);

            ITimer timer        = Mock.Create <ITimer>();
            var    responseTime = TimeSpan.FromMilliseconds(testCase.ApplicationTimeMilliseconds);

            Mock.Arrange(() => timer.Duration).Returns(responseTime);

            ITransactionName name   = TransactionName.ForWebTransaction(transactionMetricName.Prefix, transactionMetricName.UnPrefixedName);
            var priority            = 0.5f;
            IInternalTransaction tx = new Transaction(_configuration, name, timer, DateTime.UtcNow, Mock.Create <ICallStackManager>(), Mock.Create <IDatabaseService>(), priority, Mock.Create <IDatabaseStatementParser>(), Mock.Create <IDistributedTracePayloadHandler>(), Mock.Create <IErrorService>(), _attribDefs);

            tx.TransactionMetadata.SetQueueTime(TimeSpan.FromMilliseconds(testCase.QueueTimeMilliseconds));
            testCase.UserAttributes.ForEach(attr => tx.AddCustomAttribute(attr.Key, attr.Value));
            tx.TransactionMetadata.SetCrossApplicationReferrerTripId("");
            // ACT
            var browserMonitoringScript = _browserMonitoringScriptMaker.GetScript(tx);

            // ASSERT
            var extractedConfigurationDataJson = Regex.Match(browserMonitoringScript, @"NREUM.info = (\{.+\})").Groups[1].Value;
            var actualConfigurationData        = JsonConvert.DeserializeObject <ExpectedBrowserMonitoringConfigurationData>(extractedConfigurationDataJson);

            NrAssert.Multiple
            (
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.Agent, actualConfigurationData.Agent),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.ApplicationId, actualConfigurationData.ApplicationId),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.ApplicationTimeMilliseconds, actualConfigurationData.ApplicationTimeMilliseconds),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.Beacon, actualConfigurationData.Beacon),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.BrowserLicenseKey, actualConfigurationData.BrowserLicenseKey),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.ErrorBeacon, actualConfigurationData.ErrorBeacon),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.ObfuscatedTransactionName, actualConfigurationData.ObfuscatedTransactionName),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.ObfuscatedUserAttributes, actualConfigurationData.ObfuscatedUserAttributes),
                () => Assert.AreEqual(testCase.ExpectedConfigurationData.QueueTimeMilliseconds, actualConfigurationData.QueueTimeMilliseconds)
            );

            Teardown();
        }
Esempio n. 12
0
        public void SetUp()
        {
            _timerFactory = Mock.Create <ITimerFactory>();


            _configuration = Mock.Create <IConfiguration>();
            Mock.Arrange(() => _configuration.ErrorCollectorEnabled).Returns(true);
            _configurationService = Mock.Create <IConfigurationService>();
            Mock.Arrange(() => _configurationService.Configuration).Returns(_configuration);

            _transactionMetricNameMaker = Mock.Create <ITransactionMetricNameMaker>();
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny <ITransactionName>()))
            .Returns(new TransactionMetricName("WebTransaction", "TransactionName"));


            _errorService = new ErrorService(_configurationService);
            _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));

            _transactionEventMaker     = new TransactionEventMaker(_attribDefSvc);
            _transactionAttributeMaker = new TransactionAttributeMaker(_configurationService, _attribDefSvc);
        }
Esempio n. 13
0
        public void Finish_UpdatesTransactionPathHash()
        {
            var transaction = Mock.Create <IInternalTransaction>();

            Mock.Arrange(() => transaction.Finish()).Returns(true);

            var transactionName = TransactionName.ForWebTransaction("a", "b");

            Mock.Arrange(() => transaction.CandidateTransactionName.CurrentTransactionName).Returns(transactionName);
            Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(transactionName)).Returns(new TransactionMetricName("c", "d"));
            Mock.Arrange(() => transaction.TransactionMetadata.CrossApplicationReferrerPathHash).Returns("referrerPathHash");
            Mock.Arrange(() => _pathHashMaker.CalculatePathHash("c/d", "referrerPathHash")).Returns("pathHash");

            _transactionFinalizer.Finish(transaction);

            Mock.Assert(() => transaction.TransactionMetadata.SetCrossApplicationPathHash("pathHash"));
        }
Esempio n. 14
0
        public void GetSpanEvent_ReturnsSpanEventPerSegment_ValidateCount()
        {
            // ARRANGE
            var segments = new List <Segment>()
            {
                _baseGenericSegment.CreateSimilar(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(5), new List <KeyValuePair <string, object> >()),
                _childGenericSegment.CreateSimilar(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(5), new List <KeyValuePair <string, object> >())
            };
            var immutableTransaction = BuildTestTransaction(segments, sampled: true, hasIncomingPayload: false);

            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);
            var metricStatsCollection = new TransactionMetricStatsCollection(transactionMetricName);
            var transactionAttribs    = _transactionAttribMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(1), immutableTransaction.Duration, metricStatsCollection);

            // ACT
            var spanEvents = _spanEventMaker.GetSpanEvents(immutableTransaction, TransactionName, transactionAttribs);

            // ASSERT
            // +1 is for the faux root segment.
            Assert.AreEqual(segments.Count + 1, spanEvents.Count());
        }
Esempio n. 15
0
        public void Test(TestCase testCase)
        {
            Mock.Arrange(() => _configuration.ApplicationNames).Returns(new[] { testCase.AppName });

            // ConvertToImmutableTransaction a transaction for the test data
            _transaction = GetTransactionBuilderFor(_configuration, testCase);

            // Simulate external requests as dictated by the test data
            var namePriority = 10;
            var expectedAndActualOutboundRequestPayloads = new Dictionary <CrossApplicationRequestData, CrossApplicationRequestData>();

            testCase.OutboundRequests?.ForEach(request =>
            {
                var transactionName = GetTransactionNameFromString(request.OutboundTxnName);
                _transaction.CandidateTransactionName.TrySet(transactionName, (TransactionNamePriority)namePriority++);
                var outboundHeaders       = _agent.CurrentTransaction.GetRequestMetadata().ToDictionary();
                var actualOutboundPayload = _catHeaderHandler.TryDecodeInboundRequestHeaders(outboundHeaders, GetHeaderValue);
                var requestData           = new CrossApplicationRequestData(
                    (string)request.ExpectedOutboundPayload[0],
                    (bool)request.ExpectedOutboundPayload[1],
                    (string)request.ExpectedOutboundPayload[2],
                    (string)request.ExpectedOutboundPayload[3]
                    );
                expectedAndActualOutboundRequestPayloads.Add(requestData, actualOutboundPayload);
                _transaction.TransactionMetadata.MarkHasCatResponseHeaders();

                List <string> GetHeaderValue(Dictionary <string, string> headers, string key)
                {
                    var headerValues = new List <string>();
                    foreach (var item in headers)
                    {
                        if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                        {
                            headerValues.Add(item.Value);
                        }
                    }
                    return(headerValues);
                }
            });

            // Simulate the transaction ending (this logic is normally performed by Agent.EndTransaction)
            _transaction.CandidateTransactionName.TrySet(GetTransactionNameFromString(testCase.TransactionName), (TransactionNamePriority)9999);
            var currentTransactionName       = _transaction.CandidateTransactionName.CurrentTransactionName;
            var currentTransactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(currentTransactionName);
            var pathHash = _pathHashMaker.CalculatePathHash(currentTransactionMetricName.PrefixedName, _transaction.TransactionMetadata.CrossApplicationReferrerPathHash);

            _transaction.TransactionMetadata.SetCrossApplicationPathHash(pathHash);
            var transaction = _transaction.ConvertToImmutableTransaction();
            var totalTime   = transaction.Duration;

            // Get the attributes that would be created for this transaction
            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(transaction.TransactionName);
            var txStats    = new TransactionMetricStatsCollection(transactionMetricName);
            var attributes = _transactionAttributeMaker.GetAttributes(transaction, transactionMetricName, null, totalTime, txStats);
            var intrinsics = attributes.GetAttributeValuesDic(AttributeClassification.Intrinsics);

            // Run assertions
            testCase.ExpectedIntrinsicFields.ForEach(kvp =>
            {
                Assert.True(intrinsics.ContainsKey(kvp.Key), $"Expected intrinsic attribute '{kvp.Key}' was not found");
                Assert.AreEqual(kvp.Value, intrinsics[kvp.Key], $"Attribute '{kvp.Key}': expected value '{kvp.Value}' but found '{intrinsics[kvp.Key]}'");
            });

            testCase.NonExpectedIntrinsicFields.ForEach(field =>
            {
                Assert.False(intrinsics.ContainsKey(field), $"Found unexpected intrinsic attribute '{field}'");
            });

            if (testCase.OutboundRequests != null)
            {
                expectedAndActualOutboundRequestPayloads.ForEach(kvp =>
                {
                    var expected = kvp.Key;
                    var actual   = kvp.Value;
                    Assert.NotNull(actual, "Outbound request did not have any CAT headers");
                    Assert.AreEqual(expected.TransactionGuid, actual.TransactionGuid, $"Expected outbound.TransactionGuid to be '{expected.TransactionGuid}' but found '{actual.TransactionGuid}'");
                    Assert.AreEqual(expected.PathHash, actual.PathHash, $"Expected outbound.PathHash to be '{expected.TransactionGuid}' but found '{actual.TransactionGuid}'");
                    Assert.AreEqual(expected.TripId, actual.TripId, $"Expected outbound.TripId to be '{expected.TransactionGuid}' but found '{actual.TransactionGuid}'");
                    Assert.AreEqual(expected.Unused, actual.Unused, $"Expected outbound.Unused to be '{expected.Unused}' but found '{actual.Unused}'");
                });
            }
        }