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();
            }
        }
Example #2
0
        private static IManage CreateManager(MetricConfig config, SensorCollector collector)
        {
            double seconds = config.Interval.TotalSeconds;

            if (config.Graphite != null)
            {
                Logger.Info(
                    $"Graphite host: {config.Graphite.Host} port: {config.Graphite.Port} interval: {seconds} tags: {config.Graphite.Tags}");
                var writer = new GraphiteWriter(config.Graphite.Host,
                                                config.Graphite.Port,
                                                Environment.MachineName,
                                                config.Graphite.Tags);
                return(new MetricTimer(config.Interval, collector, writer));
            }
            else if (config.Prometheus != null)
            {
                Logger.Info($"Prometheus port: {config.Prometheus.Port}");
                var prometheusCollection = new PrometheusCollection(collector, Environment.MachineName);
                var server = new MetricServer(config.Prometheus.Host, config.Prometheus.Port);
                return(new PrometheusServer(server, collector, prometheusCollection));
            }
            else
            {
                Logger.Info($"Influxdb address: {config.Influx.Address} db: {config.Influx.Db}");
                var writer = new InfluxWriter(config.Influx, Environment.MachineName);
                return(new MetricTimer(config.Interval, collector, writer));
            }
        }
        public static async Task Main(string[] args)
        {
            var server = new MetricServer(hostname: "localhost", port: 5001, useHttps: false);

            server.Start();
            await CreateHostBuilder(args).Build().RunAsync();
        }
Example #4
0
        static void Main(string[] args)
        {
            if (!File.Exists(Config.CollectorConfigPath))
            {
                WriteLine("No collector config path configured. Set $env:COLLECTOR_CONFIG_PATH");
                return;
            }

            var logger = new LoggerConfiguration()
                         .ReadFrom.AppSettings()
                         .CreateLogger();

            var json            = File.ReadAllText(Config.CollectorConfigPath);
            var collectorConfig = JsonConvert.DeserializeObject <CollectorConfiguration>(json);

            if (!collectorConfig.PerformanceCounterCollectors.Any())
            {
                logger.Information("No collectors configured. Config file path: {Path}", Config.CollectorConfigPath);
                return;
            }

            DefaultCollectorRegistry.Instance.Clear();
            DefaultCollectorRegistry.Instance.RegisterOnDemandCollectors(
                new ConfiguredPerformanceCounterCollector(collectorConfig, Config.RecordCollections, logger));

            var server = new MetricServer(Config.MetricsPort);

            server.Start();
            logger.Information("Metrics server listening on port: {Port}", Config.MetricsPort);

            _ResetEvent.WaitOne();
        }
        public MetricsService(IOptions <MetricsOptions> options, ILogger <MetricsService> logger) : base(logger)
        {
            var hostname = options.Value.Hostname;

            if (hostname == "0.0.0.0" || string.IsNullOrEmpty(hostname))
            {
                hostname = "+";
            }

            options.Value.Hostname = hostname;

            if (string.IsNullOrEmpty(options.Value.Endpoint))
            {
                options.Value.Endpoint = "metrics/";
            }

            if (options.Value.Port == default)
            {
                options.Value.Port = 8080;
            }

            this.m_options = options.Value;
            this.m_server  = new MetricServer(hostname, options.Value.Port, options.Value.Endpoint);
            this.m_logger  = logger;
        }
Example #6
0
        private static IManage CreateManager(MetricConfig config, SensorCollector collector)
        {
            var    hostname = config.LookupName();
            double seconds  = config.Interval.TotalSeconds;

            if (config.Graphite != null)
            {
                Logger.Info(
                    $"Graphite host: {config.Graphite.Host} port: {config.Graphite.Port} interval: {seconds} tags: {config.Graphite.Tags}");
                var writer = new GraphiteWriter(config.Graphite.Host,
                                                config.Graphite.Port,
                                                hostname,
                                                config.Graphite.Tags);
                return(new MetricTimer(config.Interval, collector, writer));
            }
            else if (config.Prometheus != null)
            {
                Logger.Info($"Prometheus port: {config.Prometheus.Port}");
                var prometheusCollection = new PrometheusCollection(collector, hostname, Metrics.DefaultRegistry);
                var server = new MetricServer(config.Prometheus.Host, config.Prometheus.Port);
                return(new PrometheusServer(server, collector));
            }
            else if (config.Timescale != null)
            {
                var writer = new TimescaleWriter(config.Timescale.Connection, config.Timescale.SetupTable, hostname);
                return(new MetricTimer(config.Interval, collector, writer));
            }
            else
            {
                Logger.Info($"Influxdb address: {config.Influx.Address} db: {config.Influx.Db}");
                var writer = new InfluxWriter(config.Influx, hostname);
                return(new MetricTimer(config.Interval, collector, writer));
            }
        }
Example #7
0
        private Task StartMetricsServer()
        {
            Thread.Sleep(TimeSpan.FromSeconds(ConfigData.Data.Bot.BotWarmupTimeInSeconds));
            if (this._client == null || this._client.CurrentUser == null)
            {
                this._logger.Log("Delaying metric server startup");
                Thread.Sleep(TimeSpan.FromSeconds(ConfigData.Data.Bot.BotWarmupTimeInSeconds));
            }
            this._logger.Log("Starting metrics server");

            var prometheusPort = 4444;

            if (!this._client.CurrentUser.Id.Equals(Constants.BotProductionId))
            {
                this._logger.Log("Prometheus port selected is non-production");
                prometheusPort = 4422;
            }

            this._logger.Log($"Prometheus starting on port {prometheusPort}");

            var server = new MetricServer("localhost", prometheusPort);

            server.Start();

            this._logger.Log($"Prometheus running on localhost:{prometheusPort}/metrics");
            return(Task.CompletedTask);
        }
Example #8
0
        // Use this for initialization
        private void Start()
        {
            if (!Application.isEditor)
            {
                metricServer = new MetricServer(port: 1234);
                metricServer.Start();
            }


            resetCounter          = Metrics.CreateCounter("reset", "How many times the worker has been reset");
            herbivorousInUseGauge =
                Metrics.CreateGauge("herbivorousInUse", "Current total amount of herbivorous agents");
            carnivorousInUseGauge =
                Metrics.CreateGauge("carnivorousInUse", "Current total amount of carnivorous agents");
            herbivorousSpecieLifeExpectancyGauge =
                Metrics.CreateGauge("herbivorousSpecieLifeExpectancy", "Life expectancy of herbivorous specie");
            carnivorousSpecieLifeExpectancyGauge =
                Metrics.CreateGauge("carnivorousSpecieLifeExpectancy", "Life expectancy of carnivorous specie");

            evolAcademy = FindObjectOfType <EvolAcademy>();



            workerObjects = new List <Utils.Tuple <Utils.Tuple <int, int>, GameObject> >();

            // Instanciate pools to spawn / release objects
            herbivorousPool = new Pool(ItemsToSpawn.Find(go => go.name.Equals("HerbivorousAgent")), false);
            carnivorousPool = new Pool(ItemsToSpawn.Find(go => go.name.Equals("CarnivorousAgent")), false);
            herbPool        = new Pool(ItemsToSpawn.Find(go => go.name.Equals("Herb")), false);
            godPool         = new Pool(ItemsToSpawn.Find(go => go.name.Equals("GodAgent")), false);
            SpawnWorkers();
        }
Example #9
0
        static async Task Main()
        {
            Console.CancelKeyPress += OnExit;

            Console.Title = "Lhi.HsbDemo.Orders.EmailNotificationHandler";

            // Start Metrics for Prometheus
            //var metricServer = new MetricServer(port: 3031);
            var prometheus   = AppSettings.Prometheus;
            var metricServer = new MetricServer(prometheus, 3031);

            metricServer.Start();

            var endpointConfiguration = new EndpointConfiguration("Lhi.NsbDemo.Orders.EmailNotificationHandler");

            // Configure Stackify
            StackifyLib.Config.ApiKey      = AppSettings.StackifyApiKey;
            StackifyLib.Config.AppName     = AppSettings.StackifyApiName;
            StackifyLib.Config.Environment = AppSettings.StackifyEnvironment;
            // configure Serilog
            var tracingLog = new LoggerConfiguration()
                             .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(AppSettings.ElasticSearchUrl))
            {
                AutoRegisterTemplate        = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
                IndexFormat  = "nsbdemo-{0:yyyy.MM.dd}",
                InlineFields = true
            })
                             .WriteTo.Stackify()
                             .MinimumLevel.Information()
                             .CreateLogger();
            var serilogFactory = LogManager.Use <SerilogFactory>();

            serilogFactory.WithLogger(tracingLog);
            endpointConfiguration.EnableFeature <TracingLog>();
            endpointConfiguration.SerilogTracingTarget(tracingLog);

            var transport = endpointConfiguration.UseTransport <RabbitMQTransport>();

            transport.UseConventionalRoutingTopology();
            var rabbitmqConnectionString = AppSettings.RabbitMQUrl;

            transport.ConnectionString(rabbitmqConnectionString);

            //endpointConfiguration.UseSerialization<NewtonsoftSerializer>();

            endpointConfiguration.EnableInstallers();
            endpointConfiguration.Conventions()
            //.DefiningEventsAs(c => c.Namespace != null && c.Name.EndsWith("Event"))
            .DefiningCommandsAs(c => c.Namespace != null && c.Name.EndsWith("Command"));

            var endpointInstance = Endpoint.Start(endpointConfiguration)
                                   .GetAwaiter().GetResult();

            // Wait until the message arrives.
            closingEvent.WaitOne();

            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
        public async Task RunAsync(CancellationToken cancel)
        {
            _log.Info($"Configured to probe Docker on {DockerUrl}");

            _tracker = new DockerTracker(new Uri(DockerUrl));

            Metrics.DefaultRegistry.AddBeforeCollectCallback(UpdateMetricsAsync);

            var server = new MetricServer(9417);

#if DEBUG
            _log.Info($"Open http://localhost:9417/metrics to initiate a probe.");
#endif

            server.Start();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    await Task.Delay(-1, cancel);
                }
                catch (TaskCanceledException) when(cancel.IsCancellationRequested)
                {
                    // Totally normal - we are exiting.
                    break;
                }
            }

            await server.StopAsync();
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="pveHostsAndPortHA"></param>
        /// <param name="pveUsername"></param>
        /// <param name="pvePassword"></param>
        /// <param name="pveApiToken"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="url"></param>
        /// <param name="prefix"></param>
        /// <param name="exportNodeDiskInfo"></param>
        public PrometheusExporter(string pveHostsAndPortHA,
                                  string pveUsername,
                                  string pvePassword,
                                  string pveApiToken,
                                  ILoggerFactory loggerFactory,
                                  string host,
                                  int port,
                                  string url,
                                  string prefix,
                                  bool exportNodeDiskInfo)
            : this(Prometheus.Metrics.NewCustomRegistry(), prefix, exportNodeDiskInfo)
        {
            _registry.AddBeforeCollectCallback(async() =>
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var client           = ClientHelper.GetClientFromHA(pveHostsAndPortHA);
                client.LoggerFactory = loggerFactory;
                if (string.IsNullOrWhiteSpace(pveApiToken))
                {
                    await client.Login(pveUsername, pvePassword);
                }
                await Collect(client);

                stopwatch.Stop();
            });

            _server = new MetricServer(host, port, url, _registry);
        }
Example #12
0
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            var server = new MetricServer(hostname: "localhost", port: 5000);

            server.Start();
        }
Example #13
0
        public MetricsService(IRocksDbContext context, IConfigManager config)
        {
            _context = context;
            var rpcConfig = config.GetConfig <RpcConfig>("rpc") ?? RpcConfig.Default;

            _server = new MetricServer(hostname: "*", port: rpcConfig.MetricsPort);
        }
Example #14
0
        /// <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             moduleConfig     = hostScope.Resolve <IModuleConfig>();
                    var             identity         = hostScope.Resolve <IIdentity>();
                    ISessionManager sessionManager   = null;
                    var             server           = new MetricServer(port: kPublisherPrometheusPort);
                    try {
                        var version = GetType().Assembly.GetReleaseVersion().ToString();
                        logger.Information("Starting module OpcPublisher version {version}.", version);
                        logger.Information("Initiating prometheus at port {0}/metrics", kPublisherPrometheusPort);
                        server.StartWhenEnabled(moduleConfig, logger);
                        CheckDeprecatedParams(logger);
                        // Start module
                        await module.StartAsync(IdentityType.Publisher, SiteId,
                                                "OpcPublisher", version, this);

                        kPublisherModuleStart.WithLabels(
                            identity.DeviceId ?? "", identity.ModuleId ?? "").Inc();
                        await workerSupervisor.StartAsync();

                        sessionManager = hostScope.Resolve <ISessionManager>();
                        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 sessionManager?.StopAsync();

                        await module.StopAsync();

                        OnRunning?.Invoke(this, false);
                        kPublisherModuleStart.WithLabels(
                            identity.DeviceId ?? "", identity.ModuleId ?? "").Set(0);
                        server.StopWhenEnabled(moduleConfig, logger);
                    }
                }
            }
        }
Example #15
0
        private static void StartMetricServer()
        {
            var metricsPort = Config.Current.GetValue <int>("Metrics:Port");
            var server      = new MetricServer(metricsPort);

            server.Start();
            Console.WriteLine($"Metrics server listening on port ${metricsPort}");
        }
Example #16
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");
     }
 }
Example #17
0
        private void StartMetricServer()
        {
            var metricsPort = 80;
            var server      = new MetricServer(metricsPort);

            server.Start();
            Console.WriteLine($"Metrics server listening on port {metricsPort}");
        }
Example #18
0
        private static void StartMetricServer(IConfiguration config)
        {
            var metricsPort = config.GetValue <int>("Metrics:Port");
            var server      = new MetricServer(metricsPort);

            server.Start();
            Log.Information("Metrics server listening on port: {metricsPort}", metricsPort);
        }
        public static void StartMetrics(string instanceName, int bindPort, string bindHost = null)
        {
            _name = instanceName;

            _srv = bindHost != null ? new MetricServer(bindHost, bindPort) : new MetricServer(bindPort);

            _srv.Start();
        }
Example #20
0
        public static void Main(string[] args)
        {
            var server = new MetricServer(port: 9000);

            server.Start();

            CreateHostBuilder(args).Build().Run();
        }
Example #21
0
        /// <inheritdoc/>
        public void Start()
        {
            const string path = "metrics/";

            _logger.Information($"Starting metric server on port {_configuration.Port} on path '{path}'");
            _server = new MetricServer(hostname: "*", port: _configuration.Port, url: path, registry: _collectorRegistry);
            _server.Start();
        }
        /// <summary>
        /// Initialises Prometheus
        /// </summary>
        /// <param name="game">TShock game</param>
        public TShockPrometheus(Main game) : base(game)
        {
            Metrics.SuppressDefaultMetrics();
            server = new MetricServer(port: 9763); // TODO: read config

            collectors.Add(new Collectors.ConnectedPlayers(this));
            collectors.Add(new Collectors.DotNetStats(this));
            collectors.Add(new Collectors.TicksPerSecond(this));
        }
Example #23
0
        static void Main(string[] args)
        {
            Menu menu   = new Menu();
            var  server = new MetricServer(hostname: "localhost", port: 1234);

            server.Start();
            TickTock.Inc();
            menu.MainMenu();
        }
Example #24
0
        private static void ConfigurePrometheusListener(IConfigurationRoot configuration)
        {
            var port = int.Parse(configuration["PrometheusPort"]);

            Log.Information("Starting Prometheus listener at {uri}", $"+:{port}");
            var server = new MetricServer(hostname: "+", port: port);

            server.Start();
        }
Example #25
0
        public ProcessorMetricServer(ILogger logger)
        {
            _logger       = logger;
            _metricServer = new MetricServer(port: 9201);
            _counter      = Metrics.CreateCounter("processor_messagecounter", "counting accumulative all messages sent to redis and calculate messages processed by a second");

            _metricServer.Start();
            _logger.Debug($"[Processor at {DateTime.Now}] Metric server started");
        }
        public ExporterService(ILogger <ExporterService> logger, IOptions <ServerOptions> serverOptions)
        {
            _logger = logger;

            _server = new MetricServer(serverOptions.Value.Hostname, serverOptions.Value.Port,
                                       serverOptions.Value.Path);
            _listeningUrl = new UriBuilder("http", serverOptions.Value.Hostname, serverOptions.Value.Port,
                                           serverOptions.Value.Path).ToString();
        }
Example #27
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);
        }
Example #28
0
        public static void Main(string[] args)
        {
            var envConfig = new ConfigurationBuilder().AddEnvironmentVariables().Build();

            var metricServer = new MetricServer(port: int.Parse(envConfig["config:metricport"]));

            metricServer.Start();

            CreateHostBuilder(args).Build().Run();
        }
Example #29
0
        protected void Application_Start(object sender, EventArgs e)
        {
            var metricsEnabled = bool.Parse(ConfigurationManager.AppSettings["Computation:Metrics:Enabled"]);

            if (metricsEnabled)
            {
                _Server = new MetricServer(50505);
                _Server.Start();
            }
        }
Example #30
0
        static async Task Main(string[] args)
        {
            Task.Run(() => ConsumeMessages("my-client-1", "my-consumer-group-1", "my-topic-1", 100));
            Task.Run(() => ConsumeMessages("my-client-2", "my-consumer-group-2", "my-topic-1", 110));

            var metricServer = new MetricServer(port: 7075);

            metricServer.Start();
            Console.ReadLine();
        }