001package com.nimbusds.common.servlet; 002 003 004import java.io.IOException; 005import javax.servlet.ServletConfig; 006import javax.servlet.ServletException; 007import javax.servlet.http.HttpServletRequest; 008import javax.servlet.http.HttpServletResponse; 009 010import io.prometheus.client.CollectorRegistry; 011import io.prometheus.client.dropwizard.DropwizardExports; 012import io.prometheus.client.exporter.MetricsServlet; 013import org.apache.logging.log4j.LogManager; 014 015import com.nimbusds.common.monitor.MonitorRegistries; 016import com.nimbusds.common.oauth2.MasterAccessTokenValidator; 017 018 019/** 020 * Monitor servlet for exposing Dropwizard metrics in Prometheus TSDB format, 021 * requires an OAuth 2.0 bearer token for access. 022 */ 023public class PrometheusMonitorServlet extends MetricsServlet { 024 025 026 /** 027 * The access token validator. 028 */ 029 protected MasterAccessTokenValidator tokenValidator; 030 031 032 /** 033 * Returns a configured Prometheus collector registry based on a 034 * Dropwizard metric registry. 035 * 036 * @return The Prometheus collector registry. 037 */ 038 static CollectorRegistry getConfiguredCollectorRegistry() { 039 040 CollectorRegistry r = new CollectorRegistry(); 041 r.register(new DropwizardExports(MonitorRegistries.getMetricRegistry())); 042 return r; 043 } 044 045 046 /** 047 * Monitor servlet for exposing Dropwizard metrics in Prometheus TSDB 048 * format. 049 */ 050 public PrometheusMonitorServlet() { 051 052 super(getConfiguredCollectorRegistry()); 053 } 054 055 056 @Override 057 public void init(final ServletConfig config) throws ServletException { 058 059 super.init(config); 060 061 tokenValidator = MonitorServlet.createAccessTokenValidator(config); 062 063 LogManager.getLogger("MAIN").info("[CM7111] Loaded Prometheus monitor API servlet"); 064 } 065 066 067 @Override 068 protected void doGet(final HttpServletRequest req, 069 final HttpServletResponse resp) 070 throws IOException { 071 072 if (! tokenValidator.validateBearerAccessToken(req, resp)) { 073 return; // invalid or missing token 074 } 075 076 super.doGet(req, resp); 077 } 078 079 080 @Override 081 protected void service(final HttpServletRequest req, 082 final HttpServletResponse resp) 083 throws ServletException, IOException { 084 085 if (! tokenValidator.validateBearerAccessToken(req, resp)) { 086 return; // invalid or missing token 087 } 088 089 super.service(req, resp); 090 } 091}