You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@inlong.apache.org by GitBox <gi...@apache.org> on 2022/07/27 02:34:27 UTC

[GitHub] [inlong] gong commented on a diff in pull request #5200: [INLONG-5100][Sort] Add reporting metrics for JDBC

gong commented on code in PR #5200:
URL: https://github.com/apache/inlong/pull/5200#discussion_r930564312


##########
inlong-sort/sort-connectors/jdbc/src/main/java/org/apache/inlong/sort/jdbc/internal/JdbcBatchingOutputFormat.java:
##########
@@ -0,0 +1,463 @@
+/*
+ * 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.inlong.sort.jdbc.internal;
+
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
+import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
+import org.apache.flink.connector.jdbc.internal.AbstractJdbcOutputFormat;
+import org.apache.flink.connector.jdbc.internal.connection.JdbcConnectionProvider;
+import org.apache.flink.connector.jdbc.internal.connection.SimpleJdbcConnectionProvider;
+import org.apache.flink.connector.jdbc.internal.executor.JdbcBatchStatementExecutor;
+import org.apache.flink.connector.jdbc.internal.options.JdbcDmlOptions;
+import org.apache.flink.connector.jdbc.internal.options.JdbcOptions;
+import org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatementImpl;
+import org.apache.flink.connector.jdbc.utils.JdbcUtils;
+import org.apache.flink.runtime.util.ExecutorThreadFactory;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.Preconditions;
+import org.apache.inlong.sort.jdbc.metric.MetricData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+
+import static org.apache.flink.connector.jdbc.utils.JdbcUtils.setRecordToStatement;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * A JDBC outputFormat that supports batching records before writing records to database.
+ */
+public class JdbcBatchingOutputFormat<
+        In, JdbcIn, JdbcExec extends JdbcBatchStatementExecutor<JdbcIn>>
+        extends AbstractJdbcOutputFormat<In> {
+
+    private static final long serialVersionUID = 1L;
+    private static final Logger LOG = LoggerFactory.getLogger(JdbcBatchingOutputFormat.class);
+    private final JdbcExecutionOptions executionOptions;
+    private final StatementExecutorFactory<JdbcExec> statementExecutorFactory;
+    private final RecordExtractor<In, JdbcIn> jdbcRecordExtractor;
+    private final String inLongMetric;
+    private transient JdbcExec jdbcStatementExecutor;
+    private transient int batchCount = 0;
+    private transient volatile boolean closed = false;
+    private transient ScheduledExecutorService scheduler;
+    private transient ScheduledFuture<?> scheduledFuture;
+    private transient volatile Exception flushException;
+    private transient RuntimeContext runtimeContext;
+
+    private MetricData metricData;
+    private Long dataSize = 0L;
+    private Long rowSize = 0L;
+
+    public JdbcBatchingOutputFormat(
+            @Nonnull JdbcConnectionProvider connectionProvider,
+            @Nonnull JdbcExecutionOptions executionOptions,
+            @Nonnull StatementExecutorFactory<JdbcExec> statementExecutorFactory,
+            @Nonnull RecordExtractor<In, JdbcIn> recordExtractor,
+            String inLongMetric) {
+        super(connectionProvider);
+        this.executionOptions = checkNotNull(executionOptions);
+        this.statementExecutorFactory = checkNotNull(statementExecutorFactory);
+        this.jdbcRecordExtractor = checkNotNull(recordExtractor);
+        this.inLongMetric = inLongMetric;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    static JdbcBatchStatementExecutor<Row> createSimpleRowExecutor(
+            String sql, int[] fieldTypes, boolean objectReuse) {
+        return JdbcBatchStatementExecutor.simple(
+                sql,
+                createRowJdbcStatementBuilder(fieldTypes),
+                objectReuse ? Row::copy : Function.identity());
+    }
+
+    /**
+     * Creates a {@link JdbcStatementBuilder} for {@link Row} using the provided SQL types array.
+     * Uses {@link JdbcUtils#setRecordToStatement}
+     */
+    static JdbcStatementBuilder<Row> createRowJdbcStatementBuilder(int[] types) {
+        return (st, record) -> setRecordToStatement(st, types, record);
+    }
+
+    /**
+     * Connects to the target database and initializes the prepared statement.
+     *
+     * @param taskNumber The number of the parallel instance.
+     */
+    @Override
+    public void open(int taskNumber, int numTasks) throws IOException {
+        super.open(taskNumber, numTasks);
+        this.runtimeContext = getRuntimeContext();
+        metricData = new MetricData(runtimeContext.getMetricGroup());
+        if (inLongMetric != null && !inLongMetric.isEmpty()) {
+            String[] inLongMetricArray = inLongMetric.split("_");
+            String groupId = inLongMetricArray[0];
+            String streamId = inLongMetricArray[1];
+            String nodeId = inLongMetricArray[2];
+            metricData.registerMetricsForDirtyBytes(groupId, streamId, nodeId, "dirtyBytes");
+            metricData.registerMetricsForDirtyRecords(groupId, streamId, nodeId, "dirtyRecords");
+            metricData.registerMetricsForNumBytesOut(groupId, streamId, nodeId, "numBytesOut");
+            metricData.registerMetricsForNumRecordsOut(groupId, streamId, nodeId, "numRecordsOut");
+            metricData.registerMetricsForNumBytesOutPerSecond(groupId, streamId, nodeId, "numBytesOutPerSecond");
+            metricData.registerMetricsForNumRecordsOutPerSecond(groupId, streamId, nodeId,
+                    "numRecordsOutPerSecond");
+        }
+        jdbcStatementExecutor = createAndOpenStatementExecutor(statementExecutorFactory);
+        if (executionOptions.getBatchIntervalMs() != 0 && executionOptions.getBatchSize() != 1) {
+            this.scheduler =
+                    Executors.newScheduledThreadPool(
+                            1, new ExecutorThreadFactory("jdbc-upsert-output-format"));
+            this.scheduledFuture =
+                    this.scheduler.scheduleWithFixedDelay(
+                            () -> {
+                                synchronized (JdbcBatchingOutputFormat.this) {
+                                    if (!closed) {
+                                        try {
+                                            flush();
+                                            if (metricData.getNumRecordsOut() != null) {
+                                                metricData.getNumRecordsOut().inc(rowSize);
+                                            }
+                                            if (metricData.getNumRecordsOut() != null) {

Review Comment:
   `metricData.getNumRecordsOut() != null` should be `metricData.getNumBytesOut()`  



-- 
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: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org