6666import java .util .HashMap ;
6767import java .util .Map ;
6868import java .util .Objects ;
69+ import java .util .concurrent .Executors ;
70+ import java .util .concurrent .ScheduledExecutorService ;
71+ import java .util .concurrent .ScheduledFuture ;
72+ import java .util .concurrent .TimeUnit ;
73+ import java .util .function .Supplier ;
6974
7075public class PrometheusReporter implements Reporter {
7176 private static final Logger LOGGER = LoggerFactory .getLogger (PrometheusReporter .class );
7277 private static final MetricConfig METRIC_CONFIG =
7378 MetricConfigDescriptor .getInstance ().getMetricConfig ();
79+ private static final long PROMETHEUS_DEFAULT_SCRAPE_INTERVAL_SECONDS = 15 ;
7480 private final AbstractMetricManager metricManager ;
75- private DisposableServer httpServer ;
81+ private final Supplier <ScheduledExecutorService > snapshotUpdateExecutorSupplier ;
82+ private volatile ScheduledExecutorService snapshotUpdateExecutor ;
83+ private volatile DisposableServer httpServer ;
84+
85+ /** A null snapshot means that no complete scrape has been published yet. */
86+ private volatile String metricsSnapshot ;
87+
88+ private volatile ScheduledFuture <?> snapshotUpdateFuture ;
7689
7790 private static final String REALM = "metrics" ;
7891 public static final String BASIC_AUTH_PREFIX = "Basic " ;
7992 public static final char DIVIDER_BETWEEN_USERNAME_AND_DIVIDER = ':' ;
8093
94+ /**
95+ * Creates a reporter with a self-managed scheduler for compatibility with standalone users.
96+ * Server-side code should use the constructor accepting a scheduler factory.
97+ */
8198 public PrometheusReporter (AbstractMetricManager metricManager ) {
99+ this (metricManager , PrometheusReporter ::newStandaloneSnapshotUpdateExecutor );
100+ }
101+
102+ /**
103+ * Creates a reporter with a scheduler factory. The factory is invoked on every start to obtain a
104+ * fresh executor for the reporter lifecycle.
105+ */
106+ public PrometheusReporter (
107+ AbstractMetricManager metricManager ,
108+ Supplier <ScheduledExecutorService > snapshotUpdateExecutorSupplier ) {
82109 this .metricManager = metricManager ;
110+ this .snapshotUpdateExecutorSupplier = Objects .requireNonNull (snapshotUpdateExecutorSupplier );
111+ }
112+
113+ private static ScheduledExecutorService newStandaloneSnapshotUpdateExecutor () {
114+ return Executors .newSingleThreadScheduledExecutor (
115+ runnable -> {
116+ Thread thread = new Thread (runnable , "prometheus-reporter-snapshot-updater" );
117+ thread .setDaemon (true );
118+ return thread ;
119+ });
83120 }
84121
85122 @ Override
86123 @ SuppressWarnings ("java:S1181" )
87- public boolean start () {
124+ public synchronized boolean start () {
88125 if (httpServer != null ) {
89126 LOGGER .warn (MetricsMessages .PROMETHEUS_REPORTER_ALREADY_START );
90127 return false ;
91128 }
129+ // A reporter can be started again after its metric manager has been reset.
130+ metricsSnapshot = null ;
92131 try {
93132 HttpServer serverTransport =
94133 HttpServer .create ()
@@ -104,8 +143,12 @@ public boolean start() {
104143 // authenticate not pass
105144 return Mono .empty ();
106145 }
146+ String metrics =
147+ METRIC_CONFIG .isPrometheusReporterAsyncUpdate ()
148+ ? getMetricsSnapshot ()
149+ : scrape ();
107150 return res .header (HttpHeaderNames .CONTENT_TYPE , "text/plain" )
108- .sendString (Mono .just (scrape () ));
151+ .sendString (Mono .just (metrics ));
109152 }));
110153 if (METRIC_CONFIG .isEnableSSL ()) {
111154 SslContext sslContext ;
@@ -122,9 +165,20 @@ public boolean start() {
122165 serverTransport = serverTransport .secure (spec -> spec .sslContext (sslContext ));
123166 }
124167 httpServer = serverTransport .bindNow ();
168+ if (METRIC_CONFIG .isPrometheusReporterAsyncUpdate ()) {
169+ startSnapshotUpdater ();
170+ }
125171 } catch (Throwable e ) {
126172 // catch Throwable rather than Exception here because the code above might cause a
127173 // NoClassDefFoundError
174+ stopSnapshotUpdater ();
175+ if (httpServer != null ) {
176+ try {
177+ httpServer .disposeNow (Duration .ofSeconds (10 ));
178+ } catch (Exception ignored ) {
179+ // do nothing
180+ }
181+ }
128182 httpServer = null ;
129183 LOGGER .warn (MetricsMessages .PROMETHEUS_REPORTER_START_FAILED , e );
130184 return false ;
@@ -135,6 +189,63 @@ public boolean start() {
135189 return true ;
136190 }
137191
192+ @ SuppressWarnings ("unsafeThreadSchedule" )
193+ private void startSnapshotUpdater () {
194+ // Keep metric collection off Reactor HTTP threads and avoid overlapping scrapes.
195+ if (snapshotUpdateExecutor == null || snapshotUpdateExecutor .isShutdown ()) {
196+ // Create a fresh executor for every start so a stopped reporter can be started again with
197+ // the same managed thread-pool factory.
198+ snapshotUpdateExecutor = Objects .requireNonNull (snapshotUpdateExecutorSupplier .get ());
199+ }
200+ // Delay the first background scrape until metric sets have been bound by the metric service.
201+ snapshotUpdateFuture =
202+ snapshotUpdateExecutor .scheduleAtFixedRate (
203+ this ::updateSnapshot ,
204+ PROMETHEUS_DEFAULT_SCRAPE_INTERVAL_SECONDS ,
205+ PROMETHEUS_DEFAULT_SCRAPE_INTERVAL_SECONDS ,
206+ TimeUnit .SECONDS );
207+ }
208+
209+ private void updateSnapshot () {
210+ try {
211+ String snapshot = scrape ();
212+ // Do not publish an empty scrape taken before metric sets are bound. The request path will
213+ // synchronously scrape until the first complete snapshot is available. Empty snapshots are
214+ // published after initialization so removed metrics are not kept in the cache indefinitely.
215+ if (!snapshot .isEmpty () || metricsSnapshot != null ) {
216+ metricsSnapshot = snapshot ;
217+ }
218+ } catch (Throwable t ) {
219+ LOGGER .error (
220+ MetricsMessages
221+ .LOG_PROMETHEUSREPORTER_FAILED_TO_UPDATE_METRICS_SNAPSHOT_ASYNCHRONOUSLY_F19FE4E3 ,
222+ t );
223+ }
224+ }
225+
226+ private String getMetricsSnapshot () {
227+ String snapshot = metricsSnapshot ;
228+ if (snapshot == null ) {
229+ snapshot = scrape ();
230+ if (!snapshot .isEmpty ()) {
231+ metricsSnapshot = snapshot ;
232+ }
233+ }
234+ return snapshot ;
235+ }
236+
237+ private void stopSnapshotUpdater () {
238+ if (snapshotUpdateFuture != null ) {
239+ snapshotUpdateFuture .cancel (false );
240+ snapshotUpdateFuture = null ;
241+ }
242+ ScheduledExecutorService executor = snapshotUpdateExecutor ;
243+ snapshotUpdateExecutor = null ;
244+ if (executor != null ) {
245+ executor .shutdownNow ();
246+ }
247+ }
248+
138249 private boolean authenticate (HttpServerRequest req , HttpServerResponse res ) {
139250 if (!METRIC_CONFIG .prometheusNeedAuth ()) {
140251 return true ;
@@ -318,7 +429,8 @@ private SslContext createSslContext(
318429 }
319430
320431 @ Override
321- public boolean stop () {
432+ public synchronized boolean stop () {
433+ stopSnapshotUpdater ();
322434 if (httpServer != null ) {
323435 try {
324436 httpServer .disposeNow (Duration .ofSeconds (10 ));
0 commit comments