-
Notifications
You must be signed in to change notification settings - Fork 53
Add metrics for prometheus observability #661
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
906de11
initial hooks for metrics endpoint
danielhep eb39907
record job metric properly
danielhep c08c7e2
track server start tie
danielhep 4ad6292
use counter for refresh
danielhep 550d95d
respect config enabled for metrics refresh thread
danielhep 142e3f8
use string formatting
danielhep 5c612db
add api key parameter/header
danielhep 1780793
fix formatting, move metrics secret to env
danielhep 5127f3c
improve comment
danielhep File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
src/main/java/com/conveyal/datatools/manager/controllers/api/MetricsController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package com.conveyal.datatools.manager.controllers.api; | ||
|
|
||
| import com.conveyal.datatools.manager.metrics.MetricsService; | ||
|
|
||
| import spark.Request; | ||
| import spark.Response; | ||
|
|
||
| import static com.conveyal.datatools.common.utils.SparkUtils.logMessageAndHalt; | ||
| import static com.conveyal.datatools.manager.DataManager.getConfigPropertyAsText; | ||
| import static spark.Spark.get; | ||
|
|
||
| public class MetricsController { | ||
| private static final String METRICS_API_KEY_CONFIG = "METRICS_API_KEY"; | ||
|
|
||
| /** GET /metrics — Prometheus scrape endpoint. */ | ||
| private static String getMetrics(Request req, Response res) { | ||
| String apiKey = getConfigPropertyAsText(METRICS_API_KEY_CONFIG); | ||
| if (apiKey != null && !apiKey.isEmpty()) { | ||
| String providedKey = req.headers("X-API-Key"); | ||
| if (providedKey == null) { | ||
| providedKey = req.queryParams("api_key"); | ||
| } | ||
| if (!apiKey.equals(providedKey)) { | ||
| logMessageAndHalt(req, 401, "Invalid or missing API key"); | ||
| } | ||
| } | ||
| res.type("text/plain; version=0.0.4; charset=utf-8"); | ||
| return MetricsService.registry().scrape(); | ||
| } | ||
|
|
||
| public static void register() { | ||
| get("/metrics", MetricsController::getMetrics); | ||
| } | ||
| } | ||
140 changes: 140 additions & 0 deletions
140
src/main/java/com/conveyal/datatools/manager/metrics/MetricsService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package com.conveyal.datatools.manager.metrics; | ||
|
|
||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.ConcurrentMap; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicLong; | ||
|
|
||
| import org.bson.Document; | ||
|
|
||
| import com.conveyal.datatools.common.status.MonitorableJob.JobType; | ||
| import com.conveyal.datatools.manager.DataManager; | ||
| import com.conveyal.datatools.manager.persistence.Persistence; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import io.micrometer.core.instrument.Counter; | ||
| import io.micrometer.core.instrument.Gauge; | ||
| import io.micrometer.core.instrument.Timer; | ||
| import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics; | ||
| import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics; | ||
| import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics; | ||
| import io.micrometer.core.instrument.binder.jvm.JvmThreadDeadlockMetrics; | ||
| import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics; | ||
| import io.micrometer.core.instrument.binder.system.ProcessorMetrics; | ||
| import io.micrometer.prometheusmetrics.PrometheusConfig; | ||
| import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; | ||
|
|
||
| public class MetricsService { | ||
| private static final Logger LOG = LoggerFactory.getLogger(MetricsService.class); | ||
|
|
||
| private static final PrometheusMeterRegistry registry; | ||
|
|
||
| private static final AtomicLong feedSourceCount = new AtomicLong(0); | ||
| private static final AtomicLong feedVersionCount = new AtomicLong(0); | ||
| private static final AtomicLong projectCount = new AtomicLong(0); | ||
| private static final AtomicLong organizationCount = new AtomicLong(0); | ||
| private static final AtomicLong lastRefreshEpoch = new AtomicLong(0); | ||
| private static final Counter refreshFailures; | ||
|
|
||
| private static final ConcurrentMap<JobType, Counter> failedJobsByType = new ConcurrentHashMap<>(); | ||
| private static final ConcurrentMap<JobType, Counter> completedJobsByType = new ConcurrentHashMap<>(); | ||
| private static final ConcurrentMap<JobType, Timer> jobDurationByType = new ConcurrentHashMap<>(); | ||
| private static Timer jobDuration; | ||
|
|
||
| static { | ||
| registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); | ||
| populateAndRegisterJobMetricsByType(); | ||
|
|
||
| new ClassLoaderMetrics().bindTo(registry); | ||
| new JvmMemoryMetrics().bindTo(registry); | ||
| new JvmGcMetrics().bindTo(registry); | ||
| new ProcessorMetrics().bindTo(registry); | ||
| new JvmThreadMetrics().bindTo(registry); | ||
| new JvmThreadDeadlockMetrics().bindTo(registry); | ||
|
|
||
| Gauge.builder("datatools.feed.sources", feedSourceCount, AtomicLong::get) | ||
| .description("Total number of Feed Sources") | ||
| .strongReference(true) | ||
| .register(registry); | ||
| Gauge.builder("datatools.feed.versions", feedVersionCount, AtomicLong::get) | ||
| .description("Total number of Feed Versions") | ||
| .strongReference(true) | ||
| .register(registry); | ||
| Gauge.builder("datatools.projects", projectCount, AtomicLong::get) | ||
| .description("Total number of Projects") | ||
| .strongReference(true) | ||
| .register(registry); | ||
| Gauge.builder("datatools.organizations", organizationCount, AtomicLong::get) | ||
| .description("Total number of Organizations") | ||
| .strongReference(true) | ||
| .register(registry); | ||
| Gauge.builder("datatools.inventory.refresh.age.seconds", | ||
| lastRefreshEpoch, e -> e.get() == 0 | ||
| ? Double.NaN | ||
| : (System.currentTimeMillis() - e.get()) / 1000.0) | ||
| .description("Seconds since last inventory refresh") | ||
| .strongReference(true) | ||
| .register(registry); | ||
| refreshFailures = Counter.builder("datatools.inventory.refresh.failures") | ||
| .description("Total number of failed Refreshes") | ||
| .register(registry); | ||
| Gauge.builder("datatools.uptime.seconds", | ||
| DataManager.serverStartTime, | ||
| start -> (System.currentTimeMillis() - start) / 1000.0) | ||
| .description("Server uptime in seconds") | ||
| .register(registry); | ||
| } | ||
|
|
||
| private static void populateAndRegisterJobMetricsByType() { | ||
| for(JobType type : JobType.values()) { | ||
| failedJobsByType.put(type, Counter.builder(String.format("datatools.jobs.%s.failed", type.name())) | ||
| .description(String.format("Number of failed jobs of type %s", type.name())) | ||
| .register(registry)); | ||
| completedJobsByType.put(type, Counter.builder(String.format("datatools.jobs.%s.completed", type.name())) | ||
| .description(String.format("Number of completed jobs of type %s", type.name())) | ||
| .register(registry)); | ||
| jobDurationByType.put(type, Timer.builder(String.format("datatools.jobs.%s.duration", type.name())) | ||
| .description(String.format("Execution duration of jobs of type %s", type.name())) | ||
| .register(registry)); | ||
| } | ||
|
|
||
| Gauge.builder("datatools.jobs.failed", failedJobsByType, | ||
| map -> map.values().stream().mapToDouble(Counter::count).sum()) | ||
| .description("Number of failed jobs") | ||
| .register(registry); | ||
| Gauge.builder("datatools.jobs.completed", completedJobsByType, | ||
| map -> map.values().stream().mapToDouble(Counter::count).sum()) | ||
| .description("Number of completed jobs") | ||
| .register(registry); | ||
| jobDuration = Timer.builder("datatools.jobs.duration") | ||
| .description("Job execution duration") | ||
| .register(registry); | ||
| } | ||
|
|
||
| public static PrometheusMeterRegistry registry() { | ||
| return registry; | ||
| } | ||
|
|
||
| public static void refreshInventory() { | ||
| try { | ||
| Document allDocuments = new Document(); | ||
| feedSourceCount.set(Persistence.feedSources.count(allDocuments)); | ||
| feedVersionCount.set(Persistence.feedVersions.count(allDocuments)); | ||
| projectCount.set(Persistence.projects.count(allDocuments)); | ||
| organizationCount.set(Persistence.organizations.count(allDocuments)); | ||
| lastRefreshEpoch.set(System.currentTimeMillis()); | ||
| } catch (Exception e) { | ||
| refreshFailures.increment(); | ||
| LOG.warn("Inventory refresh failed", e); | ||
| } | ||
| } | ||
|
|
||
| public static void recordJobOutcome(JobType type, boolean error, long duration) { | ||
| ConcurrentMap<JobType, Counter> outcomeCountersByType = error ? failedJobsByType : completedJobsByType; | ||
|
|
||
| outcomeCountersByType.get(type).increment(); | ||
| jobDuration.record(duration, TimeUnit.MILLISECONDS); | ||
| jobDurationByType.get(type).record(duration, TimeUnit.MILLISECONDS); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.