public void MetricBatchWithNoCommonElement()
        {
            var timestamp  = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var timestampL = timestamp;
            var interval   = 125L;
            var gaugeValue = 213d;

            var metricBatch = new NewRelicMetricBatch(
                metrics: new[]
            {
                NewRelicMetric.CreateSummaryMetric(
                    name: "SummaryMetric",
                    timestamp: timestampL,
                    attributes: null,
                    interval: interval,
                    summaryValue: new NewRelicMetricSummaryValue(
                        count: 10d,
                        sum: 64,
                        min: 3,
                        max: 15)),
                NewRelicMetric.CreateGaugeMetric(
                    name: "GaugeMetric",
                    timestamp: timestampL,
                    attributes: null,
                    value: gaugeValue),
            });

            var actualMetrics = metricBatch.Metrics.ToArray();

            Assert.Equal(2, actualMetrics.Length);
            Assert.Empty(metricBatch.CommonProperties.Attributes);
            Assert.Null(metricBatch.CommonProperties.IntervalMs);
            Assert.Null(metricBatch.CommonProperties.Timestamp);
        }
        public void SendANonEmptyMetricBatch()
        {
            var metricBatch = new NewRelicMetricBatch(
                metrics: new[]
            {
                NewRelicMetric.CreateGaugeMetric(
                    name: "TestMetric",
                    timestamp: null,
                    attributes: null,
                    value: 0),
            });

            var dataSender = new MetricDataSender(new TelemetryConfiguration()
            {
                ApiKey = "123456"
            });

            dataSender.WithHttpHandlerImpl((serializedJson) =>
            {
                var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                return(Task.FromResult(response));
            });

            var response = dataSender.SendDataAsync(metricBatch).Result;

            Assert.Equal(NewRelicResponseStatus.Success, response.ResponseStatus);
        }
        public void MetricBatchWithCommonTimestampAndNoMetrics()
        {
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            var metricBatch = new NewRelicMetricBatch(
                commonProperties: new NewRelicMetricBatchCommonProperties(
                    timestamp: timestamp,
                    intervalMs: null,
                    attributes: null),
                metrics: new NewRelicMetric[0]);

            Assert.Equal(timestamp, metricBatch.CommonProperties.Timestamp);
            Assert.Empty(metricBatch.Metrics);
        }
        public void ToJson_EmptyMetricBatch()
        {
            // Arrange
            var metricBatch = new NewRelicMetricBatch(new List <NewRelicMetric>(), new NewRelicMetricBatchCommonProperties(_timestampL, null, null));

            // Act
            var jsonString = metricBatch.ToJson();

            // Assert
            var resultMetricBatch = TestHelpers.DeserializeArrayFirst(jsonString);
            var resultCommonProps = TestHelpers.DeserializeObject(resultMetricBatch["common"]);

            TestHelpers.AssertForAttribValue(resultCommonProps, "timestamp", _timestampL);
        }
        public void MetricBatchAllowsCommonAndSpecificSameNamedFields()
        {
            var currentUtcTime  = DateTimeOffset.UtcNow;
            var commonTimestamp = currentUtcTime.ToUnixTimeMilliseconds();
            var commonInterval  = 125L;

            var metricTimestamp = currentUtcTime.AddMinutes(1).ToUnixTimeMilliseconds();
            var metricInterval  = 312L;

            var countValue = 88d;

            var metricBatch = new NewRelicMetricBatch(
                commonProperties: new NewRelicMetricBatchCommonProperties(
                    timestamp: commonTimestamp,
                    intervalMs: commonInterval,
                    attributes: new Dictionary <string, object>
            {
                { "Attr1Key", "comAttr1Value" },
            }),
                metrics: new[]
            {
                NewRelicMetric.CreateCountMetric(
                    name: "CountMetric",
                    timestamp: metricTimestamp,
                    attributes: new Dictionary <string, object>()
                {
                    { "Attr1Key", "metAttr1Value" },
                },
                    value: countValue,
                    intervalMs: metricInterval),
            });

            var actualMetrics = metricBatch.Metrics.ToArray();

            Assert.Equal(commonTimestamp, metricBatch.CommonProperties.Timestamp);
            Assert.Equal(commonInterval, metricBatch.CommonProperties.IntervalMs);
            Assert.Equal("comAttr1Value", metricBatch.CommonProperties.Attributes["Attr1Key"]);

            Assert.Equal(metricTimestamp, actualMetrics[0].Timestamp);
            Assert.Equal(metricInterval, actualMetrics[0].IntervalMs);
            Assert.Equal("metAttr1Value", actualMetrics[0].Attributes?["Attr1Key"]);
        }
        public void MetricBatchWithCommonPropertiesAndMetrics()
        {
            var timestamp   = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var interval    = 125L;
            var commonAttrs = new Dictionary <string, object>()
            {
                { "attr1Key", "attr1Value" }
            };
            var countValue = 88d;
            var gaugeValue = 213d;

            var metricBatch = new NewRelicMetricBatch(
                commonProperties: new NewRelicMetricBatchCommonProperties(
                    timestamp: timestamp,
                    intervalMs: interval,
                    attributes: new Dictionary <string, object>()
            {
                { "attr1Key", "attr1Value" },
            }),
                metrics: new[]
            {
                NewRelicMetric.CreateCountMetric(
                    name: "CountMetric",
                    timestamp: null,
                    attributes: null,
                    value: countValue,
                    intervalMs: interval),
                NewRelicMetric.CreateGaugeMetric(
                    name: "GaugeMetric",
                    timestamp: null,
                    attributes: null,
                    value: gaugeValue),
            });

            var actualMetrics = metricBatch.Metrics.ToArray();

            Assert.Equal(timestamp, metricBatch.CommonProperties.Timestamp);
            Assert.Equal(interval, metricBatch.CommonProperties.IntervalMs);
            Assert.Equal(2, actualMetrics.Length);
            Assert.Equal("count", actualMetrics[0].Type);
            Assert.Equal("gauge", actualMetrics[1].Type);
        }
        public void SendAnEmptyMetricBatch()
        {
            var spanBatch = new NewRelicMetricBatch(
                metrics: new NewRelicMetric[0]);

            var dataSender = new MetricDataSender(new TelemetryConfiguration()
            {
                ApiKey = "123456"
            });

            dataSender.WithHttpHandlerImpl((serializedJson) =>
            {
                var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                return(Task.FromResult(response));
            });

            var response = dataSender.SendDataAsync(spanBatch).Result;

            Assert.Equal(NewRelicResponseStatus.DidNotSend_NoData, response.ResponseStatus);
        }
示例#8
0
        private void CollectAndPostMetrics()
        {
            var attributes = new Dictionary <string, object>
            {
                { "service.instance.id", ServiceInstanceId.ToString() },
                { "service.name", ServiceName }
            };

            // First get overall metrics
            var client = MainWindow.AudioManagers.First().Client;

            var playersOnSrs = NewRelicMetric.CreateGaugeMetric("PlayersOnSrs",
                                                                null,
                                                                new Dictionary <string, object> {
                { "callsign", "HasCallsign" }
            },
                                                                client.GetBotCallsignCompatibleClients().Count);

            var players = client.GetHumanSrsClientNames();

            foreach (var sl2 in  client.GetBotCallsignCompatibleClients())
            {
                players.Remove(sl2);
            }
            var botCompatiblePlayersOnSrs = NewRelicMetric.CreateGaugeMetric("PlayersOnSrs",
                                                                             null,
                                                                             new Dictionary <string, object> {
                { "callsign", "NoCallsign" }
            },
                                                                             players.Count);

            // Get Thread metrics
            var warningCheckers = NewRelicMetric.CreateGaugeMetric("CheckerThreads",
                                                                   null,
                                                                   new Dictionary <string, object> {
                { "type", "WarningRadius" }
            },
                                                                   WarningRadiusChecker.WarningChecks.Count);

            var atcCheckers = NewRelicMetric.CreateGaugeMetric("CheckerThreads",
                                                               null,
                                                               new Dictionary <string, object> {
                { "type", "Atc" }
            },
                                                               AtcProgressChecker.AtcChecks.Count);

            var metrics = new List <NewRelicMetric> {
                playersOnSrs, botCompatiblePlayersOnSrs, warningCheckers, atcCheckers
            };

            var frequencyCount = new Dictionary <double, int>();

            List <double> botFreqs = new List <double>();

            // Get per-client metrics

            var totalPlayerCount     = client.GetHumanSrsClientNames().Count;
            var playerOnBotFreqCount = 0;

            // Get stats for the frequencies the bot is listening on
            foreach (var audioManager in MainWindow.AudioManagers)
            {
                var radioInfo          = audioManager.PlayerRadioInfo.radios.First();
                var playersOnFreqCount = audioManager.Client.GetHumansOnFreq(audioManager.PlayerRadioInfo.radios.First()).Count;
                playerOnBotFreqCount += playersOnFreqCount;

                botFreqs.Add(radioInfo.freq);
                metrics.Add(NewRelicMetric.CreateGaugeMetric("PlayersOnFrequency",
                                                             DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                             new Dictionary <string, object> {
                    { "frequency", $"{radioInfo.freq / 1000000} - Bot {radioInfo.botType}" }
                },
                                                             playersOnFreqCount));
                metrics.Add(NewRelicMetric.CreateGaugeMetric("PlayersOnBotFrequency",
                                                             DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                             new Dictionary <string, object> {
                    { "frequency", $"{radioInfo.freq / 1000000} - Bot {radioInfo.botType}" }
                },
                                                             playersOnFreqCount));
            }

            if (totalPlayerCount == 0 || playerOnBotFreqCount == 0)
            {
                metrics.Add(NewRelicMetric.CreateGaugeMetric("PlayersOnBotFrequencyPercentage",
                                                             DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                             null,
                                                             0));
            }
            else
            {
                var percentage = (double)playerOnBotFreqCount / totalPlayerCount * 100;

                metrics.Add(NewRelicMetric.CreateGaugeMetric("PlayersOnBotFrequencyPercentage",
                                                             DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                             null,
                                                             (int)percentage));
            }


            // Get stats for the frequencies the players are on that the bot may not be on
            foreach (var playerClient in MainWindow.AudioManagers.First().Client.GetHumanSrsClients())
            {
                // We just want people in aircraft
                if (playerClient.Coalition == 0 || playerClient.RadioInfo.unit.Equals("External AWACS") || playerClient.RadioInfo.unit.Equals("CA"))
                {
                    continue;
                }

                foreach (var radio in playerClient.RadioInfo.radios)
                {
                    if (botFreqs.Contains(radio.freq) || (int)radio.freq == 1 || radio.modulation == RadioInformation.Modulation.INTERCOM)
                    {
                        continue;
                    }
                    var freq = radio.freq;
                    if (frequencyCount.ContainsKey(freq))
                    {
                        frequencyCount[freq] += 1;
                    }
                    else
                    {
                        frequencyCount.Add(freq, 1);
                    }
                }
            }

            foreach (var data in frequencyCount)
            {
                metrics.Add(NewRelicMetric.CreateGaugeMetric("PlayersOnFrequency",
                                                             DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                             new Dictionary <string, object> {
                    { "frequency", $"{data.Key / 1000000}" }
                },
                                                             data.Value));
            }

            // Radio Call counts
            var counts = new Dictionary <string, Dictionary <string, int> >();

            while (RadioCallIntents.Count > 0)
            {
                RadioCallIntents.TryDequeue(out var call);
                if (call.Key == null)
                {
                    break;
                }
                if (!counts.ContainsKey(call.Key))
                {
                    counts.Add(call.Key, new Dictionary <string, int> {
                        { call.Value, 1 }
                    });
                }
                else if (!counts[call.Key].ContainsKey(call.Value))
                {
                    counts[call.Key].Add(call.Value, 1);
                }
                else
                {
                    counts[call.Key][call.Value] += 1;
                }
            }

            foreach (var count in counts)
            {
                var intent = count.Key;

                foreach (var frequencyCounts in count.Value)
                {
                    var frequency = frequencyCounts.Key;
                    var callCount = frequencyCounts.Value;

                    metrics.Add(NewRelicMetric.CreateGaugeMetric("RadioCalls",
                                                                 DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                                                 new Dictionary <string, object>
                    {
                        { "intent", intent },
                        { "frequency", frequency }
                    },
                                                                 callCount));
                }
            }


            var batchProperties = new NewRelicMetricBatchCommonProperties(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), null, attributes);
            var batch           = new NewRelicMetricBatch(metrics, batchProperties);

            _dataSender.SendDataAsync(batch);
        }
        public void ToJson_NonEmptyMetricBatch()
        {
            // Arrange
            var metricBatch = new NewRelicMetricBatch(
                commonProperties: new NewRelicMetricBatchCommonProperties(
                    timestamp: _timestampL,
                    intervalMs: _interval,
                    attributes: null),
                metrics: new[]
            {
                NewRelicMetric.CreateCountMetric(
                    name: "metric1",
                    timestamp: null,
                    attributes: _customAttributes,
                    value: _countValue,
                    intervalMs: _interval),
                NewRelicMetric.CreateSummaryMetric(
                    name: "metric2",
                    timestamp: null,
                    attributes: null,
                    interval: _interval,
                    summaryValue: _summaryValue),
            });

            // Act
            var jsonString = metricBatch.ToJson();

            // Assert
            var resultMetricBatches = TestHelpers.DeserializeArray(jsonString);

            TestHelpers.AssertForCollectionLength(resultMetricBatches, 1);

            // CountMetric
            var resultMetricBatch = resultMetricBatches.First();
            var resultCommonProps = TestHelpers.DeserializeObject(resultMetricBatch["common"]);

            TestHelpers.AssertForAttribValue(resultCommonProps, "timestamp", _timestampL);
            TestHelpers.AssertForAttribValue(resultCommonProps, "interval.ms", _interval);

            var resultMetrics = TestHelpers.DeserializeArray(resultMetricBatch["metrics"]);

            TestHelpers.AssertForCollectionLength(resultMetrics, 2);

            var countMetric = resultMetrics.First();

            TestHelpers.AssertForAttribCount(countMetric, 5);

            TestHelpers.AssertForAttribValue(countMetric, "name", "metric1");
            TestHelpers.AssertForAttribValue(countMetric, "type", "count");
            TestHelpers.AssertForAttribValue(countMetric, "value", _countValue);
            TestHelpers.AssertForAttribValue(countMetric, "interval.ms", _interval);

            var countMetricAttribs = TestHelpers.DeserializeObject(countMetric["attributes"]);

            TestHelpers.AssertForAttribCount(countMetricAttribs, 1);
            TestHelpers.AssertForAttribValue(countMetricAttribs, "attr1Key", "attr1Value");

            // SummaryMetric
            var summaryMetric = resultMetrics[1];

            TestHelpers.AssertForAttribCount(summaryMetric, 4);

            TestHelpers.AssertForAttribValue(summaryMetric, "name", "metric2");
            TestHelpers.AssertForAttribValue(summaryMetric, "type", "summary");
            TestHelpers.AssertForAttribValue(summaryMetric, "value", _summaryValue);
            TestHelpers.AssertForAttribValue(countMetric, "interval.ms", _interval);
        }