示例#1
0
 protected void Application_End(object sender, EventArgs e)
 {
     if (_Server != null)
     {
         _Server.Stop();
     }
 }
        private static void Main(string[] args)
        {
            var fileName = args[0];

            var metricServer = new MetricServer(null, new MetricServerOptions {
                Port = 58433, Host = Debugger.IsAttached ? "127.0.0.1" : "*"
            });

            try
            {
                metricServer.Start();

                Observable.Create <string>(async(o, cancel) =>
                {
                    using var reader = File.OpenText(fileName);
                    while (!cancel.IsCancellationRequested)
                    {
                        var line = reader.ReadLine();
                        if (reader.BaseStream.Length < reader.BaseStream.Position)
                        {
                            reader.BaseStream.Seek(0, SeekOrigin.Begin);
                        }

                        if (line != null)
                        {
                            Console.WriteLine();
                            Console.WriteLine(line);
                            o.OnNext(line);
                        }
                        else
                        {
                            Console.Write(".");
                            await Task.Delay(1000, cancel);
                        }
                    }

                    o.OnCompleted();
                })
                .Select(JObject.Parse)
                .Select(j => new Reading(j))
                .SelectMany(r => r.Metrics.Select(m => new Metric(r.Unique + m.Key, m.Key, m.Value, r.Labels)))
                .Subscribe(m =>
                {
                    if (!metrics.TryGetValue(m.Unique, out var gauge))
                    {
                        gauge = Metrics.CreateGauge("rtl433_" + m.Name, "", true, "model", "channel", "id", "unique");
                    }
                    gauge.WithLabels(m.LabelValues)
                    .Set(m.Value, DateTimeOffset.Now);
                });

                var mre = new ManualResetEvent(false);
                Console.CancelKeyPress += (sender, eventArgs) => mre.Set();
                mre.WaitOne();
            }
            finally
            {
                metricServer.Stop();
            }
        }
示例#3
0
 public void Stop()
 {
     Logger.LogAction("stopping prometheus server", () =>
     {
         _collector.Stop();
         _server.Stop();
     });
 }
示例#4
0
 /// <summary>
 /// Stop metric server if enabled
 /// </summary>
 /// <returns></returns>
 public static void StopWhenEnabled(this MetricServer server, IModuleConfig config, Serilog.ILogger logger)
 {
     if (config.EnableMetrics)
     {
         server.Stop();;
         logger.Information("Stopped prometheus metric server");
     }
 }
        /// <inheritdoc/>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Stopping Prometheus MetricServer at {DateTime.UtcNow}.");

            _metricServer.Stop();

            return(Task.CompletedTask);
        }
示例#6
0
        public void Start_Stop_IsRunning()
        {
            const int port         = 9000;
            var       metricServer = new MetricServer(port);

            metricServer.Start();
            Assert.True(metricServer.IsRunning);
            metricServer.Stop();
            Assert.False(metricServer.IsRunning);
        }
示例#7
0
 //stopping server
 public void StopServer()
 {
     if (ServerMetricsIsON)
     {
         mSrv.Stop();
     }
     if (PushGatewayIsON)
     {
         pusher.Stop();
     }
 }
示例#8
0
        public void Start_Stop_IsRunning()
        {
            var metricServer = new MetricServer(new CollectorRegistry(), new MetricServerOptions {
                Port = _port
            });

            metricServer.Start();
            Assert.True(metricServer.IsRunning);
            metricServer.Stop();
            Assert.False(metricServer.IsRunning);
        }
        // TODO: on reload

        /// <summary>
        /// Plugin destruction
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                server.Stop();
                foreach (Collectors.BaseCollector collector in collectors)
                {
                    collector.Dispose();
                }
            }
            base.Dispose(disposing);
        }
        /// <summary>
        /// Run module host
        /// </summary>
        public async Task <int> RunAsync()
        {
            // Wait until the module unloads
            while (true)
            {
                using (var hostScope = ConfigureContainer(_config)) {
                    _reset = new TaskCompletionSource <bool>();
                    var module           = hostScope.Resolve <IModuleHost>();
                    var events           = hostScope.Resolve <IEventEmitter>();
                    var workerSupervisor = hostScope.Resolve <IWorkerSupervisor>();
                    var logger           = hostScope.Resolve <ILogger>();
                    var config           = new Config(_config);
                    logger.Information("Initiating prometheus at port {0}/metrics", kPublisherPrometheusPort);
                    var server = new MetricServer(port: kPublisherPrometheusPort);
                    try {
                        server.StartWhenEnabled(config, logger);
                        var product = "OpcPublisher_" +
                                      GetType().Assembly.GetReleaseVersion().ToString();
                        kPublisherModuleStart.Inc();
                        // Start module
                        await module.StartAsync(IdentityType.Publisher, SiteId,
                                                product, this);

                        await workerSupervisor.StartAsync();

                        OnRunning?.Invoke(this, true);
                        await Task.WhenAny(_reset.Task, _exit.Task);

                        if (_exit.Task.IsCompleted)
                        {
                            logger.Information("Module exits...");
                            return(_exitCode);
                        }

                        _reset = new TaskCompletionSource <bool>();
                        logger.Information("Module reset...");
                    }
                    catch (Exception ex) {
                        logger.Error(ex, "Error during module execution - restarting!");
                    }
                    finally {
                        await workerSupervisor.StopAsync();

                        await module.StopAsync();

                        kPublisherModuleStart.Set(0);
                        server.Stop();
                        OnRunning?.Invoke(this, false);
                    }
                }
            }
        }
示例#11
0
        static void Main(string[] args)
        {
            var metricServer = new MetricServer(hostname: "localhost", port: 1234);

            metricServer.Start();

            var counter = Metrics.CreateCounter("myCounter", "help text", labelNames: new [] { "method", "endpoint" });

            counter.Labels("GET", "/").Inc();
            counter.Labels("POST", "/cancel").Inc();


            var gauge = Metrics.CreateGauge("gauge", "help text");

            gauge.Inc(3.4);
            gauge.Dec(2.1);
            gauge.Set(5.3);

            var hist = Metrics.CreateHistogram("myHistogram", "help text", buckets: new[] { 0, 0.2, 0.4, 0.6, 0.8, 0.9 });

            hist.Observe(0.4);

            var summary = Metrics.CreateSummary("mySummary", "help text");

            summary.Observe(5.3);

            var random = new Random();

            Observable.Interval(TimeSpan.FromSeconds(0.5)).Subscribe(l =>
            {
                counter.Inc();
                counter.Labels("GET", "/").Inc(2);
                gauge.Set(random.NextDouble() + 2);
                hist.Observe(random.NextDouble());
                summary.Observe(random.NextDouble());

                var httpRequest    = (HttpWebRequest)WebRequest.Create("http://localhost:1234/metrics");
                httpRequest.Method = "GET";

                using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    var text = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
                    Console.WriteLine(text);
                }

                Console.WriteLine("ENTER to quit");
            });

            Console.ReadLine();
            metricServer.Stop();
        }
示例#12
0
        static void Main(string[] args)
        {
            IMetricServer metricServer = new MetricServer("localhost", 9091);

            metricServer.Start();

            var counter = Metrics.CreateCounter("test_count", "helptext");

            counter.Inc();

            Console.WriteLine("Press any key..");
            Console.ReadKey();
            metricServer.Stop();
        }
示例#13
0
        public Task StopAsync(CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("{ServiceName} stopping...", ServiceName);
                metricServer.Stop();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error when {ServiceName} stopping", ServiceName);
            }

            return(Task.CompletedTask);
        }
示例#14
0
        static void Main()
        {
            // You can use DefaultFactory
            IMetricServer metricServer = new MetricServer();

            metricServer.Start();

            var counter = Metrics.DefaultFactory.CreateCounter("test_count", "helptext");

            counter.Inc();

            Console.WriteLine("Press any key..");
            Console.ReadKey();
            metricServer.Stop();
        }
示例#15
0
        public async Task Check_MapPath(string mapPath)
        {
            const int port         = 9000;
            var       metricServer = new MetricServer(port, mapPath);

            metricServer.Start();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetStringAsync($"http://localhost:{port}" + mapPath);

                Assert.False(string.IsNullOrEmpty(response));
            }

            metricServer.Stop();
        }
示例#16
0
        public async Task Url_NotFound()
        {
            const int port         = 9000;
            var       metricServer = new MetricServer(port);

            metricServer.Start();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync($"http://localhost:{port}");

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }

            metricServer.Stop();
        }
        public async Task MapPath_WithEndSlash()
        {
            const int port         = 9000;
            var       metricServer = new MetricServer(port, "/test");

            metricServer.Start();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetStringAsync($"http://localhost:{port}/test/");

                Assert.False(string.IsNullOrEmpty(response));
            }

            metricServer.Stop();
        }
示例#18
0
        public async Task Base_MapPath()
        {
            var metricServer = new MetricServer(new CollectorRegistry(), new MetricServerOptions {
                Port = _port
            });

            metricServer.Start();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetStringAsync($"http://localhost:{_port}/metrics");

                Assert.False(string.IsNullOrEmpty(response));
            }

            metricServer.Stop();
        }
示例#19
0
        public static async Task Main(string[] args)
        {
            ConfigureServices();

            ipAddress = HeliosIpAddress;

            var metricServer = new MetricServer("0.0.0.0", 9091);

            metricServer.Start();

            var cts = new CancellationTokenSource();

            await StartUpdateInterval(cts.Token);

            metricServer.Stop();
            Log.CloseAndFlush();
        }
示例#20
0
        public async Task Url_NotFound()
        {
            var metricServer = new MetricServer(new CollectorRegistry(), new MetricServerOptions {
                Port = _port
            });

            metricServer.Start();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync($"http://localhost:{_port}");

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }

            metricServer.Stop();
        }
示例#21
0
        private void OnShutdown(AssemblyLoadContext context)
        {
            _logger.Information("Shutting down Ditto");

            try
            {
                _service?.StopAsync().GetAwaiter().GetResult();
                _metricsServer?.Stop();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error shutting down Ditto cleanly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
示例#22
0
        public async Task FindMetric()
        {
            const int port         = 9000;
            var       metricServer = new MetricServer(port);

            metricServer.Start();

            const string metricName = "myCounter";
            var          counter    = Metrics.CreateCounter(metricName, "helptext");

            counter.Inc();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetStringAsync($"http://localhost:{port}/metrics");

                Assert.Contains(metricName, response);
            }

            metricServer.Stop();
        }
示例#23
0
        static void Main()
        {
            var registry = new CollectorRegistry();
            var options  = new MetricServerOptions
            {
                CollectorRegistryInstance = registry,
                UseDefaultCollectors      = true
            };
            var factory = new MetricFactory(registry);

            IMetricServer metricServer = new MetricServer(options);

            metricServer.Start();

            var counter = factory.CreateCounter("test_count", "helptext");

            counter.Inc();

            Console.WriteLine("Press any key..");
            Console.ReadKey();
            metricServer.Stop();
        }
        static void Main()
        {
            var options = new MetricServerOptions
            {
                Port = 9091
            };

            ICollectorRegistry registry = new CollectorRegistry();
            var factory = new MetricFactory(registry);

            IMetricServer metricServer = new MetricServer(registry, options);

            metricServer.Start();

            var counter = factory.CreateCounter("test_count", "helptext");

            counter.Inc();

            Console.WriteLine("Press any key..");
            Console.ReadKey();
            metricServer.Stop();
        }
示例#25
0
        static void Main(string[] args)
        {
            // Inicializar variables para Nlog
            NlogIni();

            MetricServer metricServer = new MetricServer(port: 7073);

            metricServer.Start();

            //scrape counters
            PrometheusLog.prometheo_error     = Metrics.CreateGauge("prometheo_error", "Este campo indica que han ocurridos errores en los logs.");
            PrometheusLog.prometheo_warning   = Metrics.CreateGauge("prometheo_warning", "Este campo indica el numero de warnigs en los logs.");
            PrometheusLog.prometheo_exception = Metrics.CreateGauge("prometheo_exception", "Este campo indica el numero de exception en los logs.");
            PrometheusLog.prometheo_info      = Metrics.CreateGauge("prometheo_info", "Este campo indica el numero de los logs de información.");


            PrometheusLog.prometheo_info.Inc(1);
            logger.Info("Iniciando Monitor de log............");

            // Inicializa el motor de monitoreo.

            try {
                MonitorLog monitor = new MonitorLog(@ConfigurationManager.AppSettings["logDir"], "*.log");
                monitor.monitorear();
            }catch (monitorException mex) {
                PrometheusLog.prometheo_exception.Inc(1);
                logger.Error(mex.Message);
                return;
            }

            Console.WriteLine("Precione <enter. para continuar");

            var String = Console.ReadLine();

            if (String == "Fin")
            {
                metricServer.Stop();
            }
        }
示例#26
0
        static void Main(string[] args)
        {
            MetricServer metricServer;
            Random       random = new Random();

            Console.WriteLine("Metrics generator started");

            try
            {
                metricServer = new MetricServer(port: 1234);
                metricServer.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception while creating MetricServer: {ex.Message}");
                return;
            }

            Gauge   speedGauge    = Metrics.CreateGauge("speed", "Speed in km/h");
            Counter randomCounter = Metrics.CreateCounter("speed_limit_exceeded", "Speed limit exceeded");

            do
            {
                double speed = 100 * random.NextDouble();
                speedGauge.Set(speed);

                if (speed > 80)
                {
                    randomCounter.Inc();
                }

                Console.WriteLine($"Speed = {speed}");

                Thread.Sleep(random.Next(200, 2000));
            } while (true /* !Console.KeyAvailable */);

            metricServer.Stop();
        }
示例#27
0
        private static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            var metricServer = new MetricServer(10250);

            metricServer.Start();

            Console.WriteLine("Started metric server at localhost:10250 (http://localhost:10250/metrics)");

            Console.WriteLine("Starting up actor system...");
            var system = ActorSystem.Create("akka-performance-demo");

            var didMonitorRegister = ActorMonitoringExtension.RegisterMonitor(system, new ActorPrometheusMonitor(system));

            Console.WriteLine(didMonitorRegister
                ? "Successfully registered Prometheus monitor"
                : "Failed to register Prometheus monitor");

            // Start up three sets of Pluto and Charon (reference to I'm Your Moon by Jonathan Coulton)
            for (var i = 0; i < 3; i++)
            {
                var pluto  = system.ActorOf <PlutoActor>();
                var charon = system.ActorOf <CharonActor>();
                charon.Tell(pluto);
            }

            Thread.Sleep(TimeSpan.FromSeconds(15));

            Console.WriteLine("Shutting down...");
            system.Terminate().Wait();
            Console.WriteLine("Shutdown complete");

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            metricServer.Stop();
        }
示例#28
0
        public async Task FindMetric()
        {
            var registry     = new CollectorRegistry();
            var factory      = new MetricFactory(registry);
            var metricServer = new MetricServer(registry, new MetricServerOptions {
                Port = _port
            });

            metricServer.Start();

            const string metricName = "myCounter";
            var          counter    = factory.CreateCounter(metricName, "helptext");

            counter.Inc();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetStringAsync($"http://localhost:{_port}/metrics");

                Assert.Contains(metricName, response);
            }

            metricServer.Stop();
        }
 protected override Task OnStop(IMessageSession session)
 {
     metricServer.Stop();
     return Task.CompletedTask;
 }
示例#30
0
 public void Dispose()
 {
     _metricServer.Stop();
 }