2021-11-26 16:31:31 +01:00
|
|
|
package eu.dnetlib.common.metrics;
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.StringWriter;
|
|
|
|
import java.io.Writer;
|
2021-11-29 13:37:27 +01:00
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.Collections;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Map;
|
2021-11-26 16:31:31 +01:00
|
|
|
|
2021-11-29 13:37:27 +01:00
|
|
|
import javax.annotation.PostConstruct;
|
|
|
|
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
|
|
import io.micrometer.core.instrument.Metrics;
|
|
|
|
import io.prometheus.client.Collector.MetricFamilySamples;
|
|
|
|
import io.prometheus.client.GaugeMetricFamily;
|
2021-11-26 16:31:31 +01:00
|
|
|
import io.prometheus.client.exporter.common.TextFormat;
|
|
|
|
|
2021-11-29 13:37:27 +01:00
|
|
|
@Component
|
2021-11-26 16:31:31 +01:00
|
|
|
public class MetricUtils {
|
|
|
|
|
2021-11-29 13:37:27 +01:00
|
|
|
@Autowired(required = false)
|
|
|
|
private Map<String, MetricInfo> kpiMetrics;
|
2021-11-26 16:31:31 +01:00
|
|
|
|
2021-11-29 13:37:27 +01:00
|
|
|
@PostConstruct
|
|
|
|
public void registerToMainEndpoint() {
|
|
|
|
if (kpiMetrics != null) {
|
|
|
|
kpiMetrics.forEach((k, v) -> Metrics.gauge(k, v, o -> o.obtainValue()));
|
|
|
|
}
|
2021-11-26 16:31:31 +01:00
|
|
|
}
|
|
|
|
|
2021-11-29 13:37:27 +01:00
|
|
|
public String output(final String contentType) {
|
|
|
|
|
2021-11-26 16:31:31 +01:00
|
|
|
try {
|
2021-11-29 13:37:27 +01:00
|
|
|
final List<MetricFamilySamples> samples = new ArrayList<>();
|
|
|
|
if (kpiMetrics != null) {
|
|
|
|
kpiMetrics.forEach((k, v) -> samples.add(new GaugeMetricFamily(k, "", v.obtainValue())));
|
|
|
|
}
|
2021-11-26 16:31:31 +01:00
|
|
|
final Writer writer = new StringWriter();
|
2021-11-29 13:37:27 +01:00
|
|
|
TextFormat.writeFormat(contentType, writer, Collections.enumeration(samples));
|
2021-11-26 16:31:31 +01:00
|
|
|
return writer.toString();
|
|
|
|
} catch (final IOException e) {
|
|
|
|
// This actually never happens since StringWriter::write() doesn't throw any IOException
|
|
|
|
throw new RuntimeException("Writing metrics failed", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|