Skip to content

Commit e9dd92d

Browse files
authored
Optimize Prometheus reporter snapshot updates (#18562)
* Optimize Prometheus reporter snapshot updates * fix compilation * Fix Prometheus reporter initial snapshot race * Fix Prometheus scheduler lifecycle and duplicate allocation
1 parent 9d91245 commit e9dd92d

11 files changed

Lines changed: 267 additions & 5 deletions

File tree

‎iotdb-core/metrics/ReadMe.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ Configure the metrics module through `iotdb-system.properties`. The main options
6363
| `dn(cn)_metric_level` | Initial metric level. | `OFF`, `CORE`, `IMPORTANT`, `NORMAL`, `ALL` |
6464
| `cn_metric_prometheus_reporter_port` | Prometheus HTTP port for ConfigNode. | `9091` |
6565
| `dn_metric_prometheus_reporter_port` | Prometheus HTTP port for DataNode. | `9092` |
66+
| `prometheus_reporter_async_update` | Serve a cached Prometheus snapshot refreshed every 15 seconds. | `true` |
6667

6768
More details, see the User Guide and the `iotdb-system.properties.template` file.
6869

‎iotdb-core/metrics/interface/src/main/i18n/en/org/apache/iotdb/metrics/i18n/MetricsMessages.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,5 +128,6 @@ private MetricsMessages() {}
128128
public static final String LOG_IOTDBSESSIONREPORTER_START_WRITE_ARG_ARG_E79CDDAE = "IoTDBSessionReporter start, write to {}:{}";
129129
public static final String LOG_PROMETHEUSREPORTER_STARTED_USE_PORT_ARG_A688FFC8 = "PrometheusReporter started, use port {}";
130130
public static final String LOG_DETECTED_ERROR_TAKING_METRIC_TIMER_SNAPSHOT_WILL_DISCARD_METRIC_B7154169 = "Detected an error when taking metric timer snapshot, will discard this metric";
131+
public static final String LOG_PROMETHEUSREPORTER_FAILED_TO_UPDATE_METRICS_SNAPSHOT_ASYNCHRONOUSLY_F19FE4E3 = "PrometheusReporter failed to update metrics snapshot asynchronously";
131132

132133
}

‎iotdb-core/metrics/interface/src/main/i18n/zh/org/apache/iotdb/metrics/i18n/MetricsMessages.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,5 +124,6 @@ private MetricsMessages() {}
124124
public static final String LOG_IOTDBSESSIONREPORTER_START_WRITE_ARG_ARG_E79CDDAE = "IoTDBSessionReporter 启动,写入 {}:{}";
125125
public static final String LOG_PROMETHEUSREPORTER_STARTED_USE_PORT_ARG_A688FFC8 = "PrometheusReporter 已启动,使用端口 {}";
126126
public static final String LOG_DETECTED_ERROR_TAKING_METRIC_TIMER_SNAPSHOT_WILL_DISCARD_METRIC_B7154169 = "获取 metric timer 快照时检测到错误,将丢弃该 metric";
127+
public static final String LOG_PROMETHEUSREPORTER_FAILED_TO_UPDATE_METRICS_SNAPSHOT_ASYNCHRONOUSLY_F19FE4E3 = "PrometheusReporter 异步更新监控项快照失败";
127128

128129
}

‎iotdb-core/metrics/interface/src/main/java/org/apache/iotdb/metrics/config/MetricConfig.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ public class MetricConfig {
5252
/** The export port for prometheus to get metrics. */
5353
private Integer prometheusReporterPort = 9091;
5454

55+
/** Whether Prometheus metrics are collected asynchronously into a cached snapshot. */
56+
private boolean prometheusReporterAsyncUpdate = true;
57+
5558
private String prometheusReporterUsername = "";
5659

5760
private String prometheusReporterPassword = "";
@@ -140,6 +143,14 @@ public void setPrometheusReporterPort(Integer prometheusReporterPort) {
140143
this.prometheusReporterPort = prometheusReporterPort;
141144
}
142145

146+
public boolean isPrometheusReporterAsyncUpdate() {
147+
return prometheusReporterAsyncUpdate;
148+
}
149+
150+
public void setPrometheusReporterAsyncUpdate(boolean prometheusReporterAsyncUpdate) {
151+
this.prometheusReporterAsyncUpdate = prometheusReporterAsyncUpdate;
152+
}
153+
143154
public boolean prometheusNeedAuth() {
144155
return prometheusReporterUsername != null && !prometheusReporterUsername.isEmpty();
145156
}
@@ -264,6 +275,7 @@ public void copy(MetricConfig newMetricConfig) {
264275
metricLevel = newMetricConfig.getMetricLevel();
265276
asyncCollectPeriodInSecond = newMetricConfig.getAsyncCollectPeriodInSecond();
266277
prometheusReporterPort = newMetricConfig.getPrometheusReporterPort();
278+
prometheusReporterAsyncUpdate = newMetricConfig.isPrometheusReporterAsyncUpdate();
267279
prometheusReporterUsername = newMetricConfig.getPrometheusReporterUsername();
268280
prometheusReporterPassword = newMetricConfig.getPrometheusReporterPassword();
269281
internalReporterType = newMetricConfig.getInternalReportType();
@@ -287,6 +299,7 @@ public boolean equals(Object obj) {
287299
&& metricLevel.equals(anotherMetricConfig.getMetricLevel())
288300
&& asyncCollectPeriodInSecond.equals(anotherMetricConfig.getAsyncCollectPeriodInSecond())
289301
&& prometheusReporterPort.equals(anotherMetricConfig.getPrometheusReporterPort())
302+
&& prometheusReporterAsyncUpdate == anotherMetricConfig.isPrometheusReporterAsyncUpdate()
290303
&& iotdbReporterConfig.equals(anotherMetricConfig.getIoTDBReporterConfig())
291304
&& internalReporterType.equals(anotherMetricConfig.getInternalReportType());
292305
}
@@ -298,6 +311,7 @@ public int hashCode() {
298311
metricLevel,
299312
asyncCollectPeriodInSecond,
300313
prometheusReporterPort,
314+
prometheusReporterAsyncUpdate,
301315
iotdbReporterConfig,
302316
internalReporterType);
303317
}

‎iotdb-core/metrics/interface/src/main/java/org/apache/iotdb/metrics/config/MetricConfigDescriptor.java‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,11 @@ private MetricConfig generateFromProperties(Properties properties, String prefix
129129
properties,
130130
prefix)));
131131

132+
loadConfig.setPrometheusReporterAsyncUpdate(
133+
Boolean.parseBoolean(
134+
getPrometheusReporterAsyncUpdateProperty(
135+
properties, prefix, loadConfig.isPrometheusReporterAsyncUpdate())));
136+
132137
loadConfig.setPrometheusReporterUsername(
133138
getPropertyWithoutPrefix(
134139
"metric_prometheus_reporter_username",
@@ -222,6 +227,22 @@ private String getPropertyWithoutPrefix(
222227
.orElse(defaultValue);
223228
}
224229

230+
private String getPrometheusReporterAsyncUpdateProperty(
231+
Properties properties, String prefix, boolean defaultValue) {
232+
String value = properties.getProperty("prometheus_reporter_async_update");
233+
if (value == null) {
234+
// Keep accepting the metric-prefixed forms for compatibility with node-specific configs.
235+
value = properties.getProperty("metric_prometheus_reporter_async_update");
236+
}
237+
if (value == null) {
238+
value = properties.getProperty(prefix + "prometheus_reporter_async_update");
239+
}
240+
if (value == null) {
241+
value = properties.getProperty(prefix + "metric_prometheus_reporter_async_update");
242+
}
243+
return value == null ? String.valueOf(defaultValue) : value.trim();
244+
}
245+
225246
private static class MetricConfigDescriptorHolder {
226247
private static final MetricConfigDescriptor INSTANCE = new MetricConfigDescriptor();
227248
}

‎iotdb-core/metrics/interface/src/main/java/org/apache/iotdb/metrics/reporter/prometheus/PrometheusReporter.java‎

Lines changed: 116 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,29 +66,68 @@
6666
import java.util.HashMap;
6767
import java.util.Map;
6868
import 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

7075
public 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));

‎iotdb-core/metrics/interface/src/test/java/org/apache/iotdb/metrics/config/MetricConfigTest.java‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public void testConfigNodeMetricConfig() {
3939
properties.setProperty("cn_metric_level", "ALL");
4040
properties.setProperty("cn_metric_async_collect_period", "10");
4141
properties.setProperty("cn_metric_prometheus_reporter_port", "9090");
42+
properties.setProperty("prometheus_reporter_async_update", "false");
4243
properties.setProperty("cn_metric_iotdb_reporter_host", "0.0.0.0");
4344
properties.setProperty("cn_metric_iotdb_reporter_port", "6669");
4445
properties.setProperty("cn_metric_iotdb_reporter_username", "user");
@@ -55,6 +56,7 @@ public void testConfigNodeMetricConfig() {
5556
assertEquals(MetricLevel.ALL, metricConfig.getMetricLevel());
5657
assertEquals(10, (int) metricConfig.getAsyncCollectPeriodInSecond());
5758
assertEquals(9090, (int) metricConfig.getPrometheusReporterPort());
59+
assertEquals(false, metricConfig.isPrometheusReporterAsyncUpdate());
5860

5961
IoTDBReporterConfig reporterConfig = metricConfig.getIoTDBReporterConfig();
6062
assertEquals("0.0.0.0", reporterConfig.getHost());
@@ -75,6 +77,7 @@ public void testDataNodeMetricConfig() {
7577
properties.setProperty("dn_metric_level", "ALL");
7678
properties.setProperty("dn_metric_async_collect_period", "10");
7779
properties.setProperty("dn_metric_prometheus_reporter_port", "9090");
80+
properties.setProperty("metric_prometheus_reporter_async_update", "true");
7881
properties.setProperty("dn_metric_iotdb_reporter_host", "0.0.0.0");
7982
properties.setProperty("dn_metric_iotdb_reporter_port", "6669");
8083
properties.setProperty("dn_metric_iotdb_reporter_username", "user");
@@ -92,6 +95,7 @@ public void testDataNodeMetricConfig() {
9295
assertEquals(MetricLevel.ALL, metricConfig.getMetricLevel());
9396
assertEquals(10, (int) metricConfig.getAsyncCollectPeriodInSecond());
9497
assertEquals(9090, (int) metricConfig.getPrometheusReporterPort());
98+
assertEquals(true, metricConfig.isPrometheusReporterAsyncUpdate());
9599

96100
IoTDBReporterConfig reporterConfig = metricConfig.getIoTDBReporterConfig();
97101
assertEquals("0.0.0.0", reporterConfig.getHost());
@@ -103,4 +107,16 @@ public void testDataNodeMetricConfig() {
103107
assertEquals(5, (int) reporterConfig.getPushPeriodInSecond());
104108
assertEquals(InternalReporterType.IOTDB, metricConfig.getInternalReportType());
105109
}
110+
111+
@Test
112+
public void testMetricConfigWithCustomNodePrefix() {
113+
Properties properties = new Properties();
114+
properties.setProperty("sn_metric_prometheus_reporter_async_update", "false");
115+
116+
MetricConfigDescriptor.getInstance().loadProps(properties, "sn_");
117+
118+
assertEquals(
119+
false,
120+
MetricConfigDescriptor.getInstance().getMetricConfig().isPrometheusReporterAsyncUpdate());
121+
}
106122
}

0 commit comments

Comments
 (0)