static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console(new RenderedCompactJsonFormatter()) .Enrich.FromLogContext() .CreateLogger(); // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s ThreadPool.SetMaxThreads(100, 100); ThreadPool.SetMinThreads(50, 50); Parser.Default.ParseArguments <DeploymentPoolArgs>(args) .WithParsed(parsedArgs => { parsedArgs.Validate(); var spatialRefreshToken = Environment.GetEnvironmentVariable(SpatialRefreshTokenEnvironmentVariable) ?? throw new Exception( $"{SpatialRefreshTokenEnvironmentVariable} environment variable is required."); if (spatialRefreshToken == "") { throw new ArgumentException("Refresh token should not be empty"); } IAnalyticsSender analyticsSender = new AnalyticsSenderBuilder("deployment_pool") .WithCommandLineArgs(parsedArgs) .With(new LogExceptionStrategy(Log.Logger)) .Build(); var spatialDeploymentClient = DeploymentServiceClient.Create(credentials: new PlatformRefreshTokenCredential(spatialRefreshToken)); var spatialSnapshotClient = SnapshotServiceClient.Create(credentials: new PlatformRefreshTokenCredential(spatialRefreshToken)); var platformInvoker = new PlatformInvoker(parsedArgs, spatialDeploymentClient, spatialSnapshotClient, analyticsSender); var cancelTokenSource = new CancellationTokenSource(); var cancelToken = cancelTokenSource.Token; var metricsServer = new MetricServer(parsedArgs.MetricsPort).Start(); var dplPool = new DeploymentPool(parsedArgs, spatialDeploymentClient, platformInvoker, cancelToken, analyticsSender); var dplPoolTask = Task.Run(() => dplPool.Start()); var unixSignalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) })); Task.WaitAny(dplPoolTask, unixSignalTask); if (unixSignalTask.IsCompleted) { Log.Information($"Received UNIX signal {unixSignalTask.Result}"); Log.Information("Server shutting down..."); cancelTokenSource.Cancel(); metricsServer.StopAsync(); dplPoolTask.Wait(); Log.Information("Server stopped cleanly"); } else { /* The server task has completed; we can just exit. */ Log.Information($"The deployment pool has stopped itself or encountered an unhandled exception {dplPoolTask.Exception}"); } }); }
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(); }
private static async Task Main() { const int characterId = 1; var actionFactory = new PlayerActionFactory(); IPlayerActionLogger logger = new MongoPlayerActionLogger(new MongoClient()); var packetHandlerContainer = new PacketHandlersContainer(); IRpcClient rpcClient = new MqttIpcClient( new MqttClientConfigurationBuilder().ConnectTo("localhost").WithName("world-server"), new RuntimeSmartIpcRouter(new RoutingInformationFactory()), new JsonSerializer()); var rpcServer = new MqttIpcServer( new MqttServerConfigurationBuilder().ConnectTo("localhost").WithName("logging-service"), new JsonSerializer(), new RuntimeSmartIpcRouter(new RoutingInformationFactory()), packetHandlerContainer); await rpcClient.StartAsync(); await rpcServer.StartAsync(); packetHandlerContainer.Register(new LoggingMessageHandler <PlayerChatAction>(logger), typeof(LoggingMessage <PlayerChatAction>)); packetHandlerContainer.Register(new LoggingMessageHandler <GroupInvitedAction>(logger), typeof(LoggingMessage <GroupInvitedAction>)); var metricServer = new MetricServer("localhost", 3000); metricServer.Start(); await Task.Delay(2500); for (int i = 0; i < 10; i++) { PlayerChatAction chatAction = actionFactory.CreateChatAction(characterId); await rpcClient.BroadcastAsync(new LoggingMessage <PlayerChatAction>(chatAction)); await Task.Delay(1000); GroupInvitedAction groupInvitedAction = actionFactory.CreateGroupInvitedAction(characterId); await rpcClient.BroadcastAsync(new LoggingMessage <GroupInvitedAction>(groupInvitedAction)); await Task.Delay(1000); } await rpcClient.StopAsync(); await rpcServer.StopAsync(); // wait for kill to keep prometheus stats Console.ReadLine(); await metricServer.StopAsync(); }
public Task StopAsync(CancellationToken cancellationToken) { return(server.StopAsync()); }
public async Task StopAsync(CancellationToken cancellationToken) { await _metricServerInstance.StopAsync(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var port = config.GetValue <int>("MetricsPort"); var fetchInterval = TimeSpan.FromSeconds(config.GetValue <int>("FetchIntervalSeconds")); using var server = new MetricServer(port: port); server.Start(); log.LogInformation( "FHIR Server Prometheus Exporter running on port {port} for {fhirServerUrl}", port, fhirClient.Endpoint); while (!stoppingToken.IsCancellationRequested) { fhirClient.RequestHeaders.Authorization = await authHeaderProvider.GetAuthHeaderAsync(stoppingToken); using (FetchResourceCountDuration.WithLabels(fhirServerName).NewTimer()) { foreach (var customMetric in customMetrics) { log.LogInformation("Querying custom metric {name} using {query}", customMetric.Name, customMetric.Query); var resourceTypeAndFilters = customMetric.Query.Split("?"); if (resourceTypeAndFilters.Length < 2) { log.LogWarning("Parsing custom metric query string failed. " + "Should look like: <resourceType>?<name>=<value>&..."); continue; } var resourceType = resourceTypeAndFilters[0]; var kv = HttpUtility.ParseQueryString(resourceTypeAndFilters[1]); var paramList = kv.AllKeys.Select(key => Tuple.Create(key, kv[key])); var sp = SearchParams.FromUriParamList(paramList); sp.Summary = SummaryType.Count; var result = await fhirClient.SearchAsync(sp, resourceType); if (result.Total.HasValue) { customGauges[customMetric.Name] .WithLabels(resourceType, fhirServerName) .Set(result.Total.Value); } else { log.LogWarning("No 'total' returned for {query}", customMetric.Query); } } foreach (var resourceType in resourceTypes) { await UpdateResourceCountAsync(resourceType); } } await Task.Delay(fetchInterval, stoppingToken); } await server.StopAsync(); }
public void Dispose() { _metricsServer.StopAsync().Wait(); _interceptor.Dispose(); }
public void Shutdown() { _metricsServer.StopAsync().Wait(); _server.ShutdownAsync().Wait(); }
public Task StopAsync(CancellationToken cancellationToken) { // Stop server _logger.LogInformation("Stopping metrics server..."); return(_server.StopAsync()); }
public void Dispose() { _metricsServer.StopAsync().Wait(); }
static void Main(string[] args) { var exitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (sender, ev) => { exitEvent.Set(); ev.Cancel = true; }; MetricServer metricServer = new MetricServer(port: 1234); // http://localhost:1234/metrics metricServer.Start(); var conf = new ElasticSearchConfiguration() { EsIndex = "dummy-index", EsNodes = new List <string>() { "http://localhost:9200" } }; var client = GetElasticClient(conf); var id = Guid.NewGuid().ToString(); // Test Save var dummyDoc = new DummyDoc() { Id = id, Subject = "It is a dummy doc" }; var response = client.Index(new IndexRequest <DummyDoc>(dummyDoc, index: conf.EsIndex, type: typeof(DummyDoc).Name, id: dummyDoc.Id)); if (!response.IsValid) { Console.Error.WriteLine(response.OriginalException.Message); } Console.WriteLine($"Dummy doc with id {id} saved on index {conf.EsIndex}"); //Test Get var response2 = client.Get <DummyDoc>(new GetRequest(index: conf.EsIndex, type: typeof(DummyDoc).Name, id: id)); if (!response2.IsValid) { Console.Error.WriteLine(response2.OriginalException.Message); } Console.WriteLine($"Dummy doc retrieved {response2.Found}"); Console.WriteLine("curl http://localhost:1234/metrics to check elasticsearch_* metrics"); Console.WriteLine("Press Ctrl+C to exit"); exitEvent.WaitOne(); if (metricServer != null) { metricServer.StopAsync().Wait(); } }
public async Task StopAsync(CancellationToken cancellationToken) { await _server.StopAsync(); }