コード例 #1
1
    public void should_report_the_rate_of_change() {
      var minute = TimeSpan.FromMinutes(1);
      var config = new MetricConfig("counter1");
      var clock = new StepClock(TimeSpan.FromMinutes(1));
      var context = new MetricContext(clock);
      var counter = new StepCounter(config, context);
      
      clock.TickNow(1);
      counter.Increment(10);

      Measure measure = Testing.Sync<Measure>(counter, counter.GetMeasure,
        counter.context_);
      Assert.That(measure.Value, Is.EqualTo(10d/minute.Ticks));
      
      counter.OnStep();
      clock.TickNow(1);
      counter.Increment(10);

      measure = Testing.Sync<Measure>(counter, counter.GetMeasure,
        counter.context_);
      Assert.That(measure.Value, Is.EqualTo(10d/minute.Ticks),
        "Should report the same value as previously, since the rate was the same.");
      
      counter.OnStep();
      clock.TickNow(1);
      counter.Increment(20);

      measure = Testing.Sync<Measure>(counter, counter.GetMeasure,
        counter.context_);
      Assert.That(measure.Value, Is.EqualTo(10d/minute.Ticks*2),
        "Should report the double of the previously value, since the rate was doubled.");
    }
コード例 #2
0
 internal StreamMetric(
     MetricName metricName,
     IMetricValueProvider metricValueProvider,
     MetricConfig config)
 {
     this.metricName          = metricName;
     this.metricValueProvider = metricValueProvider;
     this.config = config;
 }
コード例 #3
0
        public void CanParseStaticResolutionName()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/static-name.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.Equal("my-cool-machine", results.LookupName());
        }
コード例 #4
0
        public async void CanInsertIntoInflux2Token()
        {
            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithDockerEndpoint(DockerUtils.DockerEndpoint())
                                        .WithImage("influxdb:2.0-alpine")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_ADMIN_TOKEN", "thisistheinfluxdbtoken")
                                        .WithPortBinding(8086, assignRandomHostPort: true)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));

            await using var container = testContainersBuilder.Build();
            await container.StartAsync();

            var baseUrl   = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/influx2.config"
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            config.AppSettings.Settings["influx2_address"].Value = baseUrl;
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            using var writer = new Influx2Writer(results.Influx2, "my-pc");
            for (int attempts = 0;; attempts++)
            {
                try
                {
                    await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());

                    var influxDBClient = InfluxDBClientFactory.Create(results.Influx2.Options);
                    var flux           = "from(bucket:\"mydb\") |> range(start: -1h)";
                    var queryApi       = influxDBClient.GetQueryApi();
                    var tables         = await queryApi.QueryAsync(flux, "myorg");

                    var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
                    Assert.Contains("/intelcpu/0/temperature/0", fields);
                    break;
                }
                catch (Exception)
                {
                    if (attempts >= 10)
                    {
                        throw;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
コード例 #5
0
    public void should_copy_config_tags_when_new_is_added() {
      var config = new MetricConfig("test1", new Tag("tag1", "tag1"));
      var config2 = config.WithAdditionalTag(new Tag("tag2", "tag2"));

      Tag tag = config2.Tags.FirstOrDefault(x => x.Name == "tag1");
      Assert.That(tag, Is.Not.Null);
      Assert.That(tag.Name, Is.EqualTo("tag1"));

      tag = config2.Tags.FirstOrDefault(x => x.Name == "tag2");
      Assert.That(tag, Is.Not.Null);
      Assert.That(tag.Name, Is.EqualTo("tag2"));
    }
コード例 #6
0
ファイル: ConfigTest.cs プロジェクト: netmintech/OhmGraphite
        public void CanParseHiddenSensors()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/hidden-sensors.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.True(results.IsHidden("/amdcpu/0/load/1"));
            Assert.True(results.IsHidden("/amdcpu/0/load/2"));
            Assert.False(results.IsHidden("/amdcpu/0/load/3"));
        }
コード例 #7
0
        public void should_copy_config_tags_when_new_is_added()
        {
            var config  = new MetricConfig("test1", new Tag("tag1", "tag1"));
            var config2 = config.WithAdditionalTag(new Tag("tag2", "tag2"));

            Tag tag = config2.Tags.FirstOrDefault(x => x.Name == "tag1");

            Assert.That(tag, Is.Not.Null);
            Assert.That(tag.Name, Is.EqualTo("tag1"));

            tag = config2.Tags.FirstOrDefault(x => x.Name == "tag2");
            Assert.That(tag, Is.Not.Null);
            Assert.That(tag.Name, Is.EqualTo("tag2"));
        }
コード例 #8
0
        public void should_report_the_max_value_of_a_step()
        {
            var config = new MetricConfig("counter1");
            var min    = new StepMaxGauge(config);

            min.Update(42L);
            min.GetMeasure(measure =>
                           Assert.That(measure.Value, Is.EqualTo(42L)));

            min.OnStep();
            min.Update(50L);
            min.GetMeasure(measure =>
                           Assert.That(measure.Value, Is.EqualTo(50L)));
        }
コード例 #9
0
    public void should_report_the_max_value_of_a_step()
    {
      var config = new MetricConfig("counter1");
      var min = new StepMaxGauge(config);

      min.Update(42L);
      min.GetMeasure(measure =>
        Assert.That(measure.Value, Is.EqualTo(42L)));

      min.OnStep();
      min.Update(50L);
      min.GetMeasure(measure =>
        Assert.That(measure.Value, Is.EqualTo(50L)));
    }
コード例 #10
0
ファイル: ConfigTest.cs プロジェクト: broadside74/OhmGraphite
        public void CanInstallCertificateVerification()
        {
            var current = ServicePointManager.ServerCertificateValidationCallback;

            MetricConfig.InstallCertificateVerification("true");
            Assert.Equal(current, ServicePointManager.ServerCertificateValidationCallback);

            MetricConfig.InstallCertificateVerification("false");
            Assert.NotEqual(current, ServicePointManager.ServerCertificateValidationCallback);

            MetricConfig.InstallCertificateVerification("assets/influxdb-selfsigned.crt");
            Assert.NotEqual(current, ServicePointManager.ServerCertificateValidationCallback);

            ServicePointManager.ServerCertificateValidationCallback = null;
        }
コード例 #11
0
ファイル: ConfigTest.cs プロジェクト: broadside74/OhmGraphite
        public void CanParseSensorAlias()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/rename.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.True(results.TryGetAlias("/amdcpu/0/load/1", out string alias));
            Assert.Equal("CPU Core 0 T0", alias);
            Assert.True(results.TryGetAlias("/amdcpu/0/load/2", out alias));
            Assert.Equal("CPU Core 0 T1", alias);
            Assert.False(results.TryGetAlias("/amdcpu/0/load/3", out alias));
        }
コード例 #12
0
        public void CanParsePrometheusConfig()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/prometheus.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.Null(results.Graphite);
            Assert.Null(results.Influx);
            Assert.NotNull(results.Prometheus);
            Assert.Equal(4446, results.Prometheus.Port);
            Assert.Equal("127.0.0.1", results.Prometheus.Host);
        }
コード例 #13
0
        public void CanParseGraphiteConfig()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/graphite.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.NotNull(results.Graphite);
            Assert.Null(results.Influx);
            Assert.Equal("myhost", results.Graphite.Host);
            Assert.Equal(2004, results.Graphite.Port);
            Assert.Equal(TimeSpan.FromSeconds(6), results.Interval);
            Assert.True(results.Graphite.Tags);
        }
コード例 #14
0
        public void CanParseTimescaleConfig()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/timescale.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.Null(results.Graphite);
            Assert.Null(results.Influx);
            Assert.Null(results.Prometheus);
            Assert.NotNull(results.Timescale);
            Assert.Equal("Host=vm-ubuntu;Username=ohm;Password=123456", results.Timescale.Connection);
            Assert.False(results.Timescale.SetupTable);
        }
コード例 #15
0
        public void should_measure_the_total_time_per_step()
        {
            var minute  = TimeSpan.FromMinutes(1);
            var config  = new MetricConfig("counter1");
            var clock   = new StepClock(TimeSpan.FromMinutes(1));
            var context = new MetricContext(clock);
            var timer   =
                new BucketTimer.Builder(config)
                .WithBuckets(new long[] { 60, 120, 180 })
                .WithTimeUnit(TimeUnit.Seconds)
                .WithMeasureUnit(TimeUnit.Minutes)
                .WithContext(context)
                .Build();

            IMetric total =
                timer
                .Metrics
                .First(
                    x => x.Config.Tags.FirstOrDefault(t => t.Value == "total") != null);

            clock.TickNow(1);

            timer.Update(TimeSpan.FromSeconds(10));
            timer.Update(TimeSpan.FromSeconds(10));
            timer.Update(TimeSpan.FromSeconds(10));

            var measure = Testing.Sync <Measure>(total, total.GetMeasure, context);

            Assert.That(measure.Value, Is.EqualTo(30d / 60));

            OnStep(total);
            clock.TickNow(1);

            timer.Update(TimeSpan.FromSeconds(30));

            measure = Testing.Sync <Measure>(total, total.GetMeasure, context);
            Assert.That(measure.Value, Is.EqualTo(30d / 60));

            OnStep(total);
            clock.TickNow(1);

            timer.Update(TimeSpan.FromSeconds(60));

            measure = Testing.Sync <Measure>(total, total.GetMeasure, context);
            Assert.That(measure.Value, Is.EqualTo(1));
        }
コード例 #16
0
        public void GetPercentageDepth2()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "GoalsScoredMetric",
                depth = 2
            };
            GoalsScoredMetric metric = new GoalsScoredMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            metric.GetPercentage(out int pTeam1, out int pTeam2, teamId1, teamId2, actualFixture);

            // Assert
            Assert.AreEqual(pTeam1, 33);
            Assert.AreEqual(pTeam2, 67);
        }
コード例 #17
0
        public void GetPointsDepth1()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "GoalsScoredMetric",
                depth = 1
            };
            GoalsScoredMetric metric = new GoalsScoredMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            metric.GetPoints(out double pTeam1, out double pTeam2, teamId1, teamId2, actualFixture);

            // Assert
            Assert.AreEqual(pTeam1, 0);
            Assert.AreEqual(pTeam2, 0);
        }
コード例 #18
0
        private void Init(MetricConfig config)
        {
            this.DataType = config.DataType;
            this.Name     = config.Name;

            try
            {
                // todo parser for expressions
                // this.MetricExpression = (MetricsExpression<T>)config.MetricFunction;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
                // todo extra error handling
            }
        }
コード例 #19
0
ファイル: LastGamesMetric.t.cs プロジェクト: mcmarcu/betting
        public void GetPercentageDepth1()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 1
            };
            LastGamesMetric metric = new LastGamesMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            metric.GetPercentage(out int pTeam1, out int pTeam2, teamId1, teamId2, actualFixture);

            // Assert
            Assert.AreEqual(pTeam1, 50);
            Assert.AreEqual(pTeam2, 50);
        }
コード例 #20
0
        public void CanParseInfluxDbConfig()
        {
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/influx.config"
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            Assert.Null(results.Graphite);
            Assert.NotNull(results.Influx);
            Assert.Equal(TimeSpan.FromSeconds(6), results.Interval);
            Assert.Equal("http://192.168.1.15:8086/", results.Influx.Address.ToString());
            Assert.Equal("mydb", results.Influx.Db);
            Assert.Equal("my_user", results.Influx.User);
            Assert.Equal("my_pass", results.Influx.Password);
        }
コード例 #21
0
ファイル: LastGamesMetric.t.cs プロジェクト: mcmarcu/betting
        public void GetPointsDepth2()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 2
            };
            LastGamesMetric metric = new LastGamesMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            metric.GetPoints(out double pTeam1, out double pTeam2, teamId1, teamId2, actualFixture);

            // Assert
            Assert.AreEqual(pTeam1, 1);
            Assert.AreEqual(pTeam2, 4);
        }
コード例 #22
0
        internal virtual bool AddStatMetric(MetricName name, IMeasurableStat stat, MetricConfig config = null)
        {
            if (!NoRunnable)
            {
                if (!metrics.ContainsKey(name))
                {
                    StreamMetric metric = new StreamMetric(name, stat, config ?? this.config);
                    metrics.Add(name, metric);
                    stats.Add(stat);
                    return(true);
                }

                return(false);
            }

            return(false);
        }
コード例 #23
0
ファイル: GlobalStatsData.t.cs プロジェクト: mcmarcu/betting
        public void GetAllYearsData()
        {
            // Arrange
            configManagerMock.Setup(p => p.GetBetStyle()).Returns("1");
            configManagerMock.Setup(p => p.GetUseExpanded()).Returns(false);
            configManagerMock.Setup(p => p.GetMaxOdds()).Returns(10);
            configManagerMock.Setup(p => p.GetMinOdds()).Returns(1);
            configManagerMock.Setup(p => p.GetDrawMargin()).Returns(10);
            configManagerMock.Setup(p => p.GetDrawMixedMargin()).Returns(20);
            configManagerMock.Setup(p => p.GetMinMetricCorrect()).Returns(1);
            configManagerMock.Setup(p => p.GetMatchDay()).Returns(4);
            configManagerMock.Setup(p => p.GetReverseDays()).Returns(4);
            configManagerMock.Setup(p => p.GetYear()).Returns(0);
            configManagerMock.Setup(p => p.GetReverseYears()).Returns(4);
            configManagerMock.Setup(p => p.GetLogLevel()).Returns(ConfigManager.LogLevel.LOG_DEBUG);
            configManagerMock.Setup(p => p.GetMinYearProfit()).Returns(70);



            MetricConfig metricConfigLastGames = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 1
            };

            List <MetricConfig> configs = new List <MetricConfig>
            {
                metricConfigLastGames
            };

            // Act
            GlobalStats globalStats = new GlobalStats(configs, configManagerMock.Object, fixtureRetrieverMock.Object, logger);

            globalStats.GetAllYearsData(out bool success, out double rate, out double averageProfit);

            // Assert
            double correctFixturesWithDataPerYear = 0 + 2 + 1;
            double totalFixturesWithDataPerYear   = 2 + 2 + 2;

            Assert.AreEqual(rate, correctFixturesWithDataPerYear / totalFixturesWithDataPerYear * 100);
            Assert.AreEqual(success, false);
            Assert.AreEqual(averageProfit, (0 - 1 - 1)
                            + (commonOdds["1"] - 1 + commonOdds["2"] - 1)
                            + (commonOdds["2"] - 1 - 1));
        }
コード例 #24
0
ファイル: MeterShould.cs プロジェクト: nvsnkv/NVs.Probe
        public async Task ReturnFailedMeasurementFromFailedCommand()
        {
            var config = new MetricConfig(new Metric("failed/measurement"), "some random stuff");

            runner
            .Setup(r => r.Execute(config.Command, It.IsAny <CancellationToken>()))
            .Throws <DivideByZeroException>();

            var meter  = new Meter(runner.Object, logger.Object);
            var result = await meter.Measure(config, CancellationToken.None);

            result.Metric.Should().BeSameAs(config.Metric);
            result.Should().BeOfType(typeof(FailedMeasurement));
            var failure = result as FailedMeasurement;

            // ReSharper disable once PossibleNullReferenceException
            failure.Exception.Should().BeOfType <DivideByZeroException>();
        }
コード例 #25
0
        public void GetGoals()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "GoalsScoredMetric",
                depth = 2
            };
            GoalsScoredMetric metric = new GoalsScoredMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            double goalsConcededTeam1 = metric.GetGoals(actualFixture, teamId1);
            double goalsConcededTeam2 = metric.GetGoals(actualFixture, teamId2);

            // Assert
            Assert.AreEqual(goalsConcededTeam1, actualFixture.finalScore.homeTeamGoals);
            Assert.AreEqual(goalsConcededTeam2, actualFixture.finalScore.awayTeamGoals);
        }
コード例 #26
0
ファイル: MetricFactory.t.cs プロジェクト: mcmarcu/betting
        public void GetMetricsCheckWrongType()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "LastGamesMetricMisspelled",
                depth = 1
            };

            List <MetricConfig> configs = new List <MetricConfig>
            {
                metricConfig
            };

            // Act
            // Assert
            Assert.Throws(typeof(ArgumentException), delegate { MetricFactory.GetMetrics(configs, year, configManagerMock.Object, fixtureRetrieverMock.Object); });
        }
コード例 #27
0
ファイル: LastGamesMetric.t.cs プロジェクト: mcmarcu/betting
        public void GetPoints()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 2
            };
            LastGamesMetric metric = new LastGamesMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            double pointsTeam1 = metric.GetPoints(actualFixture, teamId1);
            double pointsTeam2 = metric.GetPoints(actualFixture, teamId2);

            // Assert
            Assert.AreEqual(pointsTeam1, 0);
            Assert.AreEqual(pointsTeam2, 3);
        }
コード例 #28
0
        public void GetFixturesDepth1()
        {
            // Arrange
            MetricConfig metricConfig = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 1
            };
            MetricInterface metric = new LastGamesMetric(metricConfig, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Act
            int fixtureIdx = metric.FindFixtures(year, actualFixture.homeTeamId, actualFixture.fixtureId, 1);

            // Assert
            Assert.AreEqual(fixtureIdx, 1);
            Assert.AreEqual(fixturesTeam[fixtureIdx].homeTeamName, team);
            Assert.AreEqual(fixturesTeam[fixtureIdx].awayTeamName, "secondGame");
        }
コード例 #29
0
ファイル: MeterShould.cs プロジェクト: nvsnkv/NVs.Probe
        public async Task ProvideResultsForSuccessfulMeasurement()
        {
            var config = new MetricConfig(new Metric("dotnet/version"), "dotnet --version");

            runner
            .Setup(r => r.Execute(config.Command, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(Environment.Version.ToString()));

            var meter  = new Meter(runner.Object, logger.Object);
            var result = await meter.Measure(config, CancellationToken.None);

            result.Metric.Should().BeSameAs(config.Metric);
            result.Should().BeOfType <SuccessfulMeasurement>();
            var success = result as SuccessfulMeasurement;

            // ReSharper disable once PossibleNullReferenceException
            success.Result.Should().Match(s => Regex.IsMatch(s, @"\d+.\d+.\d+"));
        }
コード例 #30
0
    public void should_measure_the_total_time_per_step() {
      var minute = TimeSpan.FromMinutes(1);
      var config = new MetricConfig("counter1");
      var clock = new StepClock(TimeSpan.FromMinutes(1));
      var context = new MetricContext(clock);
      var timer =
        new BucketTimer.Builder(config)
          .WithBuckets(new long[] {60, 120, 180})
          .WithTimeUnit(TimeUnit.Seconds)
          .WithMeasureUnit(TimeUnit.Minutes)
          .WithContext(context)
          .Build();

      IMetric total =
        timer
          .Metrics
          .First(
            x => x.Config.Tags.FirstOrDefault(t => t.Value == "total") != null);

      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(10));
      timer.Update(TimeSpan.FromSeconds(10));
      timer.Update(TimeSpan.FromSeconds(10));

      var measure = Testing.Sync<Measure>(total, total.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(30d/60));
      
      OnStep(total);
      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(30));

      measure = Testing.Sync<Measure>(total, total.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(30d / 60));

      OnStep(total);
      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(60));

      measure = Testing.Sync<Measure>(total, total.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(1));
    }
コード例 #31
0
        public InstanceRegistry(InstanceRepository instanceRepository, ArtemisClientConfig config)
        {
            Preconditions.CheckArgument(instanceRepository != null, "instance repository");
            Preconditions.CheckArgument(config != null, "config");
            _instanceRepository = instanceRepository;
            _ttl      = config.ConfigurationManager.GetProperty(config.Key("instance-registry.instance-ttl"), 20 * 1000, 5 * 1000, 24 * 60 * 60 * 1000);
            _interval = config.ConfigurationManager.GetProperty(config.Key("instance-registry.heartbeat-interval"), 5 * 1000, 500, 5 * 60 * 1000);

            Action <WebSocket> onOpen = (webSocket) => {
            };
            Action <WebSocket, MessageEventArgs> onMessage = (webSocket, message) =>
            {
                AcceptHeartbeat(message);
            };

            _sessionContext = new WebSocketSessionContext(config, onOpen, onMessage);

            var heartbeatStatusMetricConfig = new MetricConfig(new Dictionary <string, string>()
            {
                { "metric_name_distribution", config.Key("heartbeat.event.distribution") }
            });

            _heartbeatStatus         = config.EventMetricManager.GetMetric(config.Key("heartbeat.event"), heartbeatStatusMetricConfig);
            _prepareHeartbeatLatency = config.AuditMetricManager.GetMetric(config.Key("heartbeat.prepare-latency"), new MetricConfig(new Dictionary <string, string>()
            {
                { "metric_name_distribution", config.Key("heartbeat.prepare-latency.distribution") }
            }));
            _sendHeartbeatLatency = config.AuditMetricManager.GetMetric(config.Key("heartbeat.send-latency"), new MetricConfig(new Dictionary <string, string>()
            {
                { "metric_name_distribution", config.Key("heartbeat.send-latency.distribution") }
            }));
            _acceptHeartbeatLatency = config.AuditMetricManager.GetMetric(config.Key("heartbeat.accept-latency"), new MetricConfig(new Dictionary <string, string>()
            {
                { "metric_name_distribution", config.Key("heartbeat.accept-latency.distribution") }
            }));

            _heartbeater = new DynamicTimer(config.ConfigurationManager.GetProperty(config.Key("instances-registry.heartbeat-interval.dynamic-scheduled-thread.run-interval"), 1000, 500, 90 * 1000),
                                            () =>
            {
                CheckHeartbeat();
            });
        }
コード例 #32
0
        private MqttApplicationMessage CreateAnnouncement(MetricConfig config, object device, IMqttClientOptions options)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (logger.WithTopic(config.Metric))
            {
                try
                {
                    var uniqueId = $"probe_{options.ClientId}_{config.Metric.Topic.Replace('/', '_')}";
                    using (logger.BeginScope($"UniqueId: {uniqueId}"))
                    {
                        var payload = new
                        {
                            state_topic = config.Metric.Topic,
                            name        = config.Metric.Topic.Split('/').Last(),
                            unique_id   = uniqueId,
                            device
                        };
                        var message = new MqttApplicationMessageBuilder()
                                      .WithTopic($"homeassistant/sensor/probe/{uniqueId}/config")
                                      .WithPayload(JsonConvert.SerializeObject(payload))
                                      .Build();

                        logger.LogInformation("Announcement built. Payload: {@payload}", payload);
                        return(message);
                    }
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Failed to create announcement!");
                    throw;
                }
            }
        }
コード例 #33
0
        internal virtual bool AddImmutableMetric <T>(MetricName name, T value, MetricConfig config = null)
        {
            if (!NoRunnable)
            {
                if (!metrics.ContainsKey(name))
                {
                    StreamMetric metric =
                        new StreamMetric(name, new ImmutableMetricValue <T>(value), config ?? this.config);
                    metrics.Add(name, metric);
                    if (value is IMeasurableStat stat)
                    {
                        stats.Add(stat);
                    }
                    return(true);
                }

                return(false);
            }

            return(false);
        }
コード例 #34
0
ファイル: MetricFactory.t.cs プロジェクト: mcmarcu/betting
        public void GetMetricsCheckType()
        {
            // Arrange
            MetricConfig metricConfigLastGames = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 1
            };

            List <MetricConfig> configs = new List <MetricConfig>
            {
                metricConfigLastGames
            };

            // Act
            List <MetricInterface> metrics = MetricFactory.GetMetrics(configs, year, configManagerMock.Object, fixtureRetrieverMock.Object);

            // Assert
            Assert.AreEqual(metrics.Count, 1);
            Assert.AreEqual(metrics[0].GetType(), typeof(LastGamesMetric));
            Assert.AreEqual(metrics[0].year, year);
        }
コード例 #35
0
    public void should_serialize_measure_into_influx_format() {
      var tags =
        new Tags.Builder()
          .WithTag("tag1", "tagValue1")
          .Build();
      var config = new MetricConfig("myMetric", tags);
      var measure = new Measure(config, 1000);

      var date = DateTime.Now;
      var api = new ApiEndpointMock();
      var observer = new InfluxObserver(api, TimeSpan.FromMilliseconds(50));
      observer.Observe(measure, date);
      observer.Observe(measure, date);

      long epoch = date.ToUnixEpoch().ToNanos(TimeUnit.Seconds);
      string points = "myMetric,{0} value={1} {2}\nmyMetric,{0} value={1} {2}\n"
        .Fmt("tag1=tagValue1", measure.Value, epoch.ToString());

      Thread.Sleep(TimeSpan.FromMilliseconds(100));

      Assert.That(api.PostedSeries, Is.EqualTo(points));
    }
コード例 #36
0
    public void should_count_the_number_of_times_a_bucket_was_hit() {
      var minute = TimeSpan.FromMinutes(1);
      var config = new MetricConfig("counter1");
      var clock = new StepClock(TimeSpan.FromMinutes(3));
      var context = new MetricContext(clock);
      var timer =
        new BucketTimer.Builder(config)
          .WithBuckets(new long[] { 60, 120, 180 })
          .WithTimeUnit(TimeUnit.Seconds)
          .WithMeasureUnit(TimeUnit.Minutes)
          .WithContext(context)
          .Build();

      IMetric b60 = GetMetricWithTag(timer, "bucket=060s");
      IMetric b120 = GetMetricWithTag(timer, "bucket=120s");
      IMetric b180 = GetMetricWithTag(timer, "bucket=180s");

      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(10));
      timer.Update(TimeSpan.FromSeconds(10));
      timer.Update(TimeSpan.FromSeconds(10));

      var measure = Testing.Sync<Measure>(b60, b60.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(1));

      measure = Testing.Sync<Measure>(b120, b120.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(0));

      measure = Testing.Sync<Measure>(b180, b180.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(0));

      OnStep(b60, b120, b180);
      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(30));
      timer.Update(TimeSpan.FromSeconds(61));
      timer.Update(TimeSpan.FromSeconds(65));

      measure = Testing.Sync<Measure>(b60, b60.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(1/3d));

      measure = Testing.Sync<Measure>(b120, b120.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(2/3d));

      measure = Testing.Sync<Measure>(b180, b180.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(0));

      OnStep(b60, b120, b180);
      clock.TickNow(1);

      timer.Update(TimeSpan.FromSeconds(180));

      measure = Testing.Sync<Measure>(b60, b60.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(0));

      measure = Testing.Sync<Measure>(b120, b120.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(0));

      measure = Testing.Sync<Measure>(b180, b180.GetMeasure, context);
      Assert.That(measure.Value, Is.EqualTo(1/3d));
    }
コード例 #37
0
    public void should_copy_config_when_new_tag_is_added() {
      var config = new MetricConfig("test1");
      var config2 = config.WithAdditionalTag(new Tag("tag1", "tag1"));

      Assert.That(config, Is.Not.SameAs(config2));
    }