cs-codex-dist-tests/MetricsPlugin/PrometheusStarter.cs

64 lines
2.1 KiB
C#
Raw Normal View History

2023-09-13 07:12:18 +00:00
using Core;
using KubernetesWorkflow;
2023-09-13 09:25:08 +00:00
using System.Text;
2023-04-13 12:36:17 +00:00
2023-09-13 07:12:18 +00:00
namespace MetricsPlugin
2023-04-13 12:36:17 +00:00
{
2023-09-13 07:12:18 +00:00
public class PrometheusStarter
2023-04-13 12:36:17 +00:00
{
2023-09-13 07:12:18 +00:00
private readonly IPluginTools tools;
public PrometheusStarter(IPluginTools tools)
2023-04-13 12:36:17 +00:00
{
2023-09-13 07:12:18 +00:00
this.tools = tools;
2023-04-13 12:36:17 +00:00
}
2023-09-13 09:25:08 +00:00
public RunningContainers CollectMetricsFor(IMetricsScrapeTarget[] targets)
2023-04-13 12:36:17 +00:00
{
2023-09-13 09:25:08 +00:00
Log($"Starting metrics server for {targets.Length} targets...");
var startupConfig = new StartupConfig();
startupConfig.Add(new PrometheusStartupConfig(GeneratePrometheusConfig(targets)));
2023-04-13 12:36:17 +00:00
2023-09-13 09:25:08 +00:00
var workflow = tools.CreateWorkflow();
var runningContainers = workflow.Start(1, Location.Unspecified, new PrometheusContainerRecipe(), startupConfig);
if (runningContainers.Containers.Length != 1) throw new InvalidOperationException("Expected only 1 Prometheus container to be created.");
2023-04-13 12:36:17 +00:00
2023-09-13 09:25:08 +00:00
Log("Metrics server started.");
return runningContainers;
2023-04-13 12:36:17 +00:00
}
2023-09-13 09:25:08 +00:00
public MetricsAccess CreateAccessForTarget(RunningContainers metricsContainer, IMetricsScrapeTarget target)
{
var metricsQuery = new MetricsQuery(tools, metricsContainer);
return new MetricsAccess(metricsQuery, target);
}
private void Log(string msg)
{
tools.GetLog().Log(msg);
}
private static string GeneratePrometheusConfig(IMetricsScrapeTarget[] targets)
{
var config = "";
config += "global:\n";
config += " scrape_interval: 10s\n";
config += " scrape_timeout: 10s\n";
config += "\n";
config += "scrape_configs:\n";
config += " - job_name: services\n";
config += " metrics_path: /metrics\n";
config += " static_configs:\n";
config += " - targets:\n";
foreach (var target in targets)
{
config += $" - '{target.Ip}:{target.Port}'\n";
}
var bytes = Encoding.ASCII.GetBytes(config);
return Convert.ToBase64String(bytes);
}
2023-04-13 12:36:17 +00:00
}
}