AnatolyPopov commented on code in PR #17025: URL: https://github.com/apache/iceberg/pull/17025#discussion_r3683052457
########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/ChannelMetrics.java: ########## @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.connect.channel; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Supplier; +import org.apache.kafka.common.MetricName; +import org.apache.kafka.common.metrics.Gauge; +import org.apache.kafka.common.metrics.JmxReporter; +import org.apache.kafka.common.metrics.KafkaMetricsContext; +import org.apache.kafka.common.metrics.MetricConfig; +import org.apache.kafka.common.metrics.Metrics; +import org.apache.kafka.common.metrics.Sensor; +import org.apache.kafka.common.metrics.stats.Avg; +import org.apache.kafka.common.metrics.stats.CumulativeCount; +import org.apache.kafka.common.metrics.stats.CumulativeSum; +import org.apache.kafka.common.metrics.stats.Max; +import org.apache.kafka.common.utils.Time; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base for the per-task/per-connector JMX metric registries. Owns the {@link Metrics} registry, the + * sensor-creation helpers shared by the worker and coordinator, and the two channel-level timers + * that every {@link Channel} feeds while draining the control topic. + */ +abstract class ChannelMetrics implements AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(ChannelMetrics.class); + + /** JMX domain; dotted to sit alongside Kafka's own {@code kafka.connect.*} beans in jconsole. */ + static final String NAMESPACE = "iceberg.kafka.connect"; + + private final Metrics metrics; + private final String group; + + private final Sensor messageReadTime; + private final Sensor messageProcessTime; + + ChannelMetrics(String group, String connector, String task) { + this.group = group; + this.metrics = + new Metrics( + new MetricConfig(), Review Comment: I think the default time window with default metric config is 30 seconds + default number of samples is 2. So by default it will cover only 1 minute out 5 min default commit interval. So commit-time-avg/commit-time-max metrics will be showing NaN during 4 out of 5 min commit interval since the obsolete samples are purged when the metrics are read and 30 sec * 2 samples is expired. I think the time window should be tied to commit interval. ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/Coordinator.java: ########## @@ -192,6 +205,7 @@ private void commit(boolean partialCommit) { e); } finally { commitState.endCurrentCommit(); + coordinatorMetrics.recordCommit(partialCommit, (System.nanoTime() - start) / 1_000L); Review Comment: Here we are counting together both successful and unsuccessful commits, correct? Should they be separate? ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/WorkerMetrics.java: ########## @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.connect.channel; + +import java.util.Map; +import org.apache.kafka.common.metrics.Sensor; + +class WorkerMetrics extends ChannelMetrics { + + private static final String GROUP = "worker-metrics"; + + private final Sensor saveTime; + private final Sensor dataWritten; + private final Sensor dataComplete; + + WorkerMetrics(String connector, String task) { + super(GROUP, connector, task); + Map<String, String> tags = metricTags(connector, task, null); + try { + this.saveTime = + createTimerSensor("save-time", "Time spent in Worker.save() in microseconds", tags); + // Counters are bumped only after send() succeeds, so they count events successfully emitted; + // a failed send leaves them unmoved even though the files are already on disk. + this.dataWritten = + createCounterSensor( + "data-written", Review Comment: I think in other places in Iceberg the naming convention is slightly different like `added-data-files`, can we do similar thing here or am I misunderstanding something? For example `data-files-written-total` and maybe even separating delete files into separate counter ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/Coordinator.java: ########## @@ -440,4 +455,13 @@ void terminate() { throw new ConnectException("Interrupted while waiting for coordinator shutdown", e); } } + + @Override + void stop() { + // stop() runs at the very end of the CoordinatorThread run loop, after process() (and any + // commit() recording) can no longer fire, so closing the registry here avoids racing a + // record* call against a closed Metrics instance. + super.stop(); Review Comment: Could coordinator re-election cause the old coordinator to unregister the replacement MBeans here? stopCoordinator() calls terminate() without waiting for CoordinatorThread to reach this stop(). A newly elected coordinator in the same Connect JVM can therefore register the same connector-level ObjectName first. Kafka’s JmxReporter replaces the existing MBean during registration, but the old reporter still retains that ObjectName and unregisters the replacement when it eventually closes. The replacement registered successfully, but closing the first instance removed it. Should coordinator shutdown wait for the old thread to finish? ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/ChannelMetrics.java: ########## @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.connect.channel; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Supplier; +import org.apache.kafka.common.MetricName; +import org.apache.kafka.common.metrics.Gauge; +import org.apache.kafka.common.metrics.JmxReporter; +import org.apache.kafka.common.metrics.KafkaMetricsContext; +import org.apache.kafka.common.metrics.MetricConfig; +import org.apache.kafka.common.metrics.Metrics; +import org.apache.kafka.common.metrics.Sensor; +import org.apache.kafka.common.metrics.stats.Avg; +import org.apache.kafka.common.metrics.stats.CumulativeCount; +import org.apache.kafka.common.metrics.stats.CumulativeSum; +import org.apache.kafka.common.metrics.stats.Max; +import org.apache.kafka.common.utils.Time; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base for the per-task/per-connector JMX metric registries. Owns the {@link Metrics} registry, the + * sensor-creation helpers shared by the worker and coordinator, and the two channel-level timers + * that every {@link Channel} feeds while draining the control topic. + */ +abstract class ChannelMetrics implements AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(ChannelMetrics.class); + + /** JMX domain; dotted to sit alongside Kafka's own {@code kafka.connect.*} beans in jconsole. */ + static final String NAMESPACE = "iceberg.kafka.connect"; + + private final Metrics metrics; + private final String group; + + private final Sensor messageReadTime; + private final Sensor messageProcessTime; + + ChannelMetrics(String group, String connector, String task) { + this.group = group; + this.metrics = + new Metrics( + new MetricConfig(), + Collections.singletonList(new JmxReporter()), + Time.SYSTEM, + new KafkaMetricsContext(NAMESPACE)); + Map<String, String> tags = metricTags(connector, task, null); + try { + this.messageReadTime = + createTimerSensor( + "channel-message-read-time", + "Time to Avro-decode one control message in microseconds", + tags); + this.messageProcessTime = + createTimerSensor( + "channel-message-process-time", + "Time to process one control message in microseconds", + tags); + } catch (RuntimeException e) { + closeQuietly(e); + throw e; + } + } + + void recordMessageRead(long elapsedMs) { + messageReadTime.record((double) elapsedMs); + } + + void recordMessageProcess(long elapsedMs) { + messageProcessTime.record((double) elapsedMs); + } + + @Override + public void close() { + try { + metrics.close(); + } catch (Exception e) { + LOG.warn("Error closing {}", getClass().getSimpleName(), e); + } + } + + /** + * Closes the registry while an in-flight constructor failure is unwinding, to avoid MBean leaks. + */ + protected void closeQuietly(RuntimeException failure) { + try { + metrics.close(); + } catch (Exception suppressed) { + failure.addSuppressed(suppressed); + } + } + + /** Registers a lazily-evaluated gauge that reads {@code supplier} each time JMX polls it. */ + protected void addGauge( + String name, String description, Map<String, String> tags, Supplier<Long> supplier) { + metrics.addMetric( + new MetricName(name, group, description, tags), + (Gauge<Long>) (config, now) -> supplier.get()); + } + + protected Sensor createTimerSensor( + String baseName, String description, Map<String, String> tags) { + Sensor sensor = metrics.sensor(sensorName(baseName, tags)); + sensor.add(new MetricName(baseName + "-avg", group, description + " (avg)", tags), new Avg()); + sensor.add(new MetricName(baseName + "-max", group, description + " (max)", tags), new Max()); + sensor.add( + new MetricName(baseName + "-total", group, description + " (total)", tags), + new CumulativeSum()); + sensor.add( + new MetricName(baseName + "-count", group, description + " (count)", tags), + new CumulativeCount()); Review Comment: The description is borrowed from the sensor description, right? So we will get something like `Time to process one control message in microseconds (count)` if I understand correctly. And this looks a bit unclear what is the actual unit of measurement if read just the description without looking into the code. ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/CoordinatorMetrics.java: ########## @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.connect.channel; + +import java.util.function.Supplier; +import org.apache.kafka.common.metrics.Sensor; + +class CoordinatorMetrics extends ChannelMetrics { + + private static final String GROUP = "coordinator-metrics"; + // The coordinator is a single per-connector task, so it reports a fixed task tag. + private static final String TASK = "coordinator"; + private static final String FULL = "full"; + private static final String PARTIAL = "partial"; + + // Commit timers are tagged by commitMode (partial vs full) so the two paths stay separable. + private final Sensor fullCommitTime; + private final Sensor partialCommitTime; + private final Sensor startCommit; + private final Sensor commitComplete; + + CoordinatorMetrics( + String connector, Supplier<Long> commitBufferSize, Supplier<Long> readyBufferSize) { + super(GROUP, connector, TASK); + try { + this.fullCommitTime = + createTimerSensor( + "commit-time", + "Time spent in Coordinator.commit() in microseconds", + metricTags(connector, TASK, FULL)); + this.partialCommitTime = + createTimerSensor( + "commit-time", + "Time spent in Coordinator.commit() in microseconds", + metricTags(connector, TASK, PARTIAL)); + // Counters are bumped only after send() succeeds, so they count events successfully emitted; + // a failed send leaves them unmoved even though the commit is already in progress. + this.startCommit = + createCounterSensor( + "start-commit", + "Number of successfully emitted START_COMMIT events", + metricTags(connector, TASK, null)); + this.commitComplete = + createCounterSensor( + "commit-complete", + "Number of successfully emitted COMMIT_COMPLETE events", + metricTags(connector, TASK, null)); + + addGauge( + "commit-buffer-size", + "Current size of CommitState.commitBuffer", + metricTags(connector, TASK, null), + commitBufferSize); + addGauge( + "ready-buffer-size", + "Current size of CommitState.readyBuffer", + metricTags(connector, TASK, null), + readyBufferSize); + } catch (RuntimeException e) { + closeQuietly(e); + throw e; + } + } + + void recordCommit(boolean partialCommit, long elapsedMs) { Review Comment: I think the at least the argument name is misleading since we seem to record microseconds, not milliseconds, right? ########## kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/channel/ChannelMetrics.java: ########## @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.connect.channel; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Supplier; +import org.apache.kafka.common.MetricName; +import org.apache.kafka.common.metrics.Gauge; +import org.apache.kafka.common.metrics.JmxReporter; +import org.apache.kafka.common.metrics.KafkaMetricsContext; +import org.apache.kafka.common.metrics.MetricConfig; +import org.apache.kafka.common.metrics.Metrics; +import org.apache.kafka.common.metrics.Sensor; +import org.apache.kafka.common.metrics.stats.Avg; +import org.apache.kafka.common.metrics.stats.CumulativeCount; +import org.apache.kafka.common.metrics.stats.CumulativeSum; +import org.apache.kafka.common.metrics.stats.Max; +import org.apache.kafka.common.utils.Time; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base for the per-task/per-connector JMX metric registries. Owns the {@link Metrics} registry, the + * sensor-creation helpers shared by the worker and coordinator, and the two channel-level timers + * that every {@link Channel} feeds while draining the control topic. + */ +abstract class ChannelMetrics implements AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(ChannelMetrics.class); + + /** JMX domain; dotted to sit alongside Kafka's own {@code kafka.connect.*} beans in jconsole. */ + static final String NAMESPACE = "iceberg.kafka.connect"; + + private final Metrics metrics; + private final String group; + + private final Sensor messageReadTime; + private final Sensor messageProcessTime; + + ChannelMetrics(String group, String connector, String task) { + this.group = group; + this.metrics = + new Metrics( + new MetricConfig(), + Collections.singletonList(new JmxReporter()), + Time.SYSTEM, + new KafkaMetricsContext(NAMESPACE)); + Map<String, String> tags = metricTags(connector, task, null); + try { + this.messageReadTime = + createTimerSensor( + "channel-message-read-time", + "Time to Avro-decode one control message in microseconds", + tags); + this.messageProcessTime = + createTimerSensor( + "channel-message-process-time", + "Time to process one control message in microseconds", + tags); + } catch (RuntimeException e) { + closeQuietly(e); + throw e; + } + } + + void recordMessageRead(long elapsedMs) { + messageReadTime.record((double) elapsedMs); + } + + void recordMessageProcess(long elapsedMs) { + messageProcessTime.record((double) elapsedMs); + } + + @Override + public void close() { + try { + metrics.close(); + } catch (Exception e) { + LOG.warn("Error closing {}", getClass().getSimpleName(), e); + } + } + + /** + * Closes the registry while an in-flight constructor failure is unwinding, to avoid MBean leaks. + */ + protected void closeQuietly(RuntimeException failure) { + try { + metrics.close(); + } catch (Exception suppressed) { + failure.addSuppressed(suppressed); + } + } + + /** Registers a lazily-evaluated gauge that reads {@code supplier} each time JMX polls it. */ + protected void addGauge( + String name, String description, Map<String, String> tags, Supplier<Long> supplier) { + metrics.addMetric( + new MetricName(name, group, description, tags), + (Gauge<Long>) (config, now) -> supplier.get()); + } + + protected Sensor createTimerSensor( + String baseName, String description, Map<String, String> tags) { + Sensor sensor = metrics.sensor(sensorName(baseName, tags)); + sensor.add(new MetricName(baseName + "-avg", group, description + " (avg)", tags), new Avg()); + sensor.add(new MetricName(baseName + "-max", group, description + " (max)", tags), new Max()); + sensor.add( + new MetricName(baseName + "-total", group, description + " (total)", tags), + new CumulativeSum()); + sensor.add( + new MetricName(baseName + "-count", group, description + " (count)", tags), + new CumulativeCount()); + return sensor; + } + + protected Sensor createCounterSensor( + String baseName, String description, Map<String, String> tags) { + Sensor sensor = metrics.sensor(sensorName(baseName, tags)); + sensor.add(new MetricName(baseName + "-total", group, description, tags), new CumulativeSum()); + return sensor; + } + + /** + * Builds the JMX tag map shared by worker and coordinator metrics. {@code commitMode} is only set + * on the coordinator's per-commit sensors ({@code full}/{@code partial}); pass {@code null} to + * omit it. + */ + static Map<String, String> metricTags(String connector, String task, String commitMode) { + Map<String, String> tags = new LinkedHashMap<>(); + tags.put("connector", connector); + tags.put("task", task); + if (commitMode != null) { + tags.put("commitMode", commitMode); Review Comment: Should it be commit-mode or similar in kebab-case? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
