openinx commented on a change in pull request #12004:
URL: https://github.com/apache/flink/pull/12004#discussion_r422124325
##########
File path:
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/HiveTableSource.java
##########
@@ -181,6 +214,47 @@ public boolean isBounded() {
return source.name(explainSource());
}
+ private DataStream<RowData> createStreamSource(
+ StreamExecutionEnvironment execEnv,
+ TypeInformation<RowData> typeInfo,
+ HiveTableInputFormat inputFormat) {
+ final Map<String, String> properties =
catalogTable.getProperties();
+ PartitionFetcherFactory strategyFactory = cl ->
PartitionFetcher.createStrategy(
+
properties.get(HIVE_STREAMING_SOURCE_PARTITION_STRATEGY.key()),
+
properties.get(HIVE_STREAMING_SOURCE_PARTITION_STRATEGY_CLASS.key()),
+ cl);
+
+ String monitorIntervalStr =
properties.get(HIVE_STREAMING_SOURCE_MONITOR_INTERVAL.key());
+ Duration monitorInterval = monitorIntervalStr != null ?
+ TimeUtils.parseDuration(monitorIntervalStr) :
+
HIVE_STREAMING_SOURCE_MONITOR_INTERVAL.defaultValue();
+
+ HiveContinuousMonitoringFunction monitoringFunction = new
HiveContinuousMonitoringFunction(
+ hiveShim,
+ jobConf,
+ tablePath,
+ catalogTable,
+ getStartupPartition(),
+ strategyFactory,
+ execEnv.getParallelism(),
+ monitorInterval.toMillis());
+
+ ContinuousFileReaderOperatorFactory<RowData,
TimestampedHiveInputSplit> factory =
+ new
ContinuousFileReaderOperatorFactory<>(inputFormat);
Review comment:
Besides seems we don't do any split inside the file which may introduce
the unbalanced data consuming in the upstream operator ? Iceberg seems handle
this well because it will split the larger data file into small balanced tasks
and dispatch to the executing task..
##########
File path:
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/HiveTableSource.java
##########
@@ -181,6 +214,47 @@ public boolean isBounded() {
return source.name(explainSource());
}
+ private DataStream<RowData> createStreamSource(
+ StreamExecutionEnvironment execEnv,
+ TypeInformation<RowData> typeInfo,
+ HiveTableInputFormat inputFormat) {
+ final Map<String, String> properties =
catalogTable.getProperties();
+ PartitionFetcherFactory strategyFactory = cl ->
PartitionFetcher.createStrategy(
+
properties.get(HIVE_STREAMING_SOURCE_PARTITION_STRATEGY.key()),
+
properties.get(HIVE_STREAMING_SOURCE_PARTITION_STRATEGY_CLASS.key()),
+ cl);
+
+ String monitorIntervalStr =
properties.get(HIVE_STREAMING_SOURCE_MONITOR_INTERVAL.key());
+ Duration monitorInterval = monitorIntervalStr != null ?
+ TimeUtils.parseDuration(monitorIntervalStr) :
+
HIVE_STREAMING_SOURCE_MONITOR_INTERVAL.defaultValue();
+
+ HiveContinuousMonitoringFunction monitoringFunction = new
HiveContinuousMonitoringFunction(
+ hiveShim,
+ jobConf,
+ tablePath,
+ catalogTable,
+ getStartupPartition(),
+ strategyFactory,
+ execEnv.getParallelism(),
+ monitorInterval.toMillis());
+
+ ContinuousFileReaderOperatorFactory<RowData,
TimestampedHiveInputSplit> factory =
+ new
ContinuousFileReaderOperatorFactory<>(inputFormat);
Review comment:
I've one question here, what's the parallelism of the
ContinuousFileReaderOperator will be ? should we use the default parallelism
in ExecutionConfig ?
OK, seems the InputFormat will generate the expected parallelism...
##########
File path:
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/HiveTableSource.java
##########
@@ -150,6 +164,25 @@ public boolean isBounded() {
allHivePartitions,
flinkConf.get(HiveOptions.TABLE_EXEC_HIVE_FALLBACK_MAPRED_READER));
+ if (isStreamingSource()) {
+ if (catalogTable.getPartitionKeys().isEmpty()) {
+ throw new UnsupportedOperationException(
+ "Non-partition table not
support streaming read now.");
Review comment:
not -> does not .
##########
File path:
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/read/HiveContinuousMonitoringFunction.java
##########
@@ -0,0 +1,331 @@
+/*
+ * 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.flink.connectors.hive.read;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.typeutils.base.ListSerializer;
+import org.apache.flink.api.common.typeutils.base.LongSerializer;
+import org.apache.flink.api.common.typeutils.base.StringSerializer;
+import org.apache.flink.connectors.hive.HiveTablePartition;
+import org.apache.flink.connectors.hive.HiveTableSource;
+import org.apache.flink.connectors.hive.JobConfWrapper;
+import
org.apache.flink.connectors.hive.read.PartitionFetcher.PartitionFetcherFactory;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import
org.apache.flink.streaming.api.functions.source.ContinuousFileReaderOperator;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+import org.apache.flink.table.catalog.CatalogTable;
+import org.apache.flink.table.catalog.ObjectPath;
+import org.apache.flink.table.catalog.hive.client.HiveShim;
+import org.apache.flink.table.catalog.hive.util.HiveReflectionUtils;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
Review comment:
Seems the useless imported class can be removed
##########
File path:
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/read/HiveContinuousMonitoringFunction.java
##########
@@ -0,0 +1,331 @@
+/*
+ * 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.flink.connectors.hive.read;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.typeutils.base.ListSerializer;
+import org.apache.flink.api.common.typeutils.base.LongSerializer;
+import org.apache.flink.api.common.typeutils.base.StringSerializer;
+import org.apache.flink.connectors.hive.HiveTablePartition;
+import org.apache.flink.connectors.hive.HiveTableSource;
+import org.apache.flink.connectors.hive.JobConfWrapper;
+import
org.apache.flink.connectors.hive.read.PartitionFetcher.PartitionFetcherFactory;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import
org.apache.flink.streaming.api.functions.source.ContinuousFileReaderOperator;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+import org.apache.flink.table.catalog.CatalogTable;
+import org.apache.flink.table.catalog.ObjectPath;
+import org.apache.flink.table.catalog.hive.client.HiveShim;
+import org.apache.flink.table.catalog.hive.util.HiveReflectionUtils;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import static
org.apache.flink.table.filesystem.PartitionPathUtils.escapePathName;
+
+/**
+ * This is the single (non-parallel) monitoring task which takes a {@link
HiveTableInputFormat},
+ * it is responsible for:
+ *
+ * <ol>
+ * <li>Monitoring partitions of hive meta store.</li>
+ * <li>Deciding which partitions should be further read and processed.</li>
+ * <li>Creating the {@link HiveTableInputSplit splits} corresponding to
those partitions.</li>
+ * <li>Assigning them to downstream tasks for further processing.</li>
+ * </ol>
+ *
+ * <p>The splits to be read are forwarded to the downstream {@link
ContinuousFileReaderOperator}
+ * which can have parallelism greater than one.
+ *
+ * <p><b>IMPORTANT NOTE: </b> Splits are forwarded downstream for reading in
ascending partition time order,
+ * based on the partition time of the partitions they belong to.
+ */
+public class HiveContinuousMonitoringFunction
+ extends RichSourceFunction<TimestampedHiveInputSplit>
+ implements CheckpointedFunction {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG =
LoggerFactory.getLogger(HiveContinuousMonitoringFunction.class);
+
+ /** The parallelism of the downstream readers. */
+ private final int readerParallelism;
+
+ /** The interval between consecutive path scans. */
+ private final long interval;
+
+ private final HiveShim hiveShim;
+
+ private final JobConfWrapper conf;
+
+ private final ObjectPath tablePath;
+
+ private final List<String> partitionKeys;
+
+ private final String[] fieldNames;
+
+ private final DataType[] fieldTypes;
+
+ private final String startupPartition;
+
+ private final PartitionFetcherFactory fetcherFactory;
+
+ private volatile boolean isRunning = true;
+
+ /** The maximum partition read time seen so far. */
+ private volatile long currentReadTime;
+
+ private transient PartitionFetcher.Context fetcherContext;
+
+ private transient PartitionFetcher fetcher;
+
+ private transient Object checkpointLock;
+
+ private transient ListState<Long> currReadTimeState;
+
+ private transient ListState<List<List<String>>> distinctPartsState;
+
+ private transient IMetaStoreClient client;
+
+ private transient Properties tableProps;
+
+ private transient String defaultPartitionName;
+
+ private transient Set<List<String>> distinctPartitions;
+
+ public HiveContinuousMonitoringFunction(
+ HiveShim hiveShim,
+ JobConf conf,
+ ObjectPath tablePath,
+ CatalogTable catalogTable,
+ String startupPartition,
+ PartitionFetcherFactory fetcherFactory,
+ int readerParallelism,
+ long interval) {
+ this.hiveShim = hiveShim;
+ this.conf = new JobConfWrapper(conf);
+ this.tablePath = tablePath;
+ this.partitionKeys = catalogTable.getPartitionKeys();
+ this.fieldNames = catalogTable.getSchema().getFieldNames();
+ this.fieldTypes = catalogTable.getSchema().getFieldDataTypes();
+ this.startupPartition = startupPartition;
+ this.fetcherFactory = fetcherFactory;
+
+ this.interval = interval;
+ this.readerParallelism = Math.max(readerParallelism, 1);
+ this.currentReadTime = 0;
+ }
+
+ @Override
+ public void initializeState(FunctionInitializationContext context)
throws Exception {
+ this.currReadTimeState =
context.getOperatorStateStore().getListState(
+ new ListStateDescriptor<>(
+ "partition-monitoring-state",
+ LongSerializer.INSTANCE
+ )
+ );
+ this.distinctPartsState =
context.getOperatorStateStore().getListState(
+ new ListStateDescriptor<>(
+ "partition-monitoring-state",
+ new ListSerializer<>(new
ListSerializer<>(StringSerializer.INSTANCE))
+ )
+ );
+
+ this.client = this.hiveShim.getHiveMetastoreClient(new
HiveConf(conf.conf(), HiveConf.class));
+
+ Table hiveTable = client.getTable(tablePath.getDatabaseName(),
tablePath.getObjectName());
+ this.tableProps =
HiveReflectionUtils.getTableMetadata(hiveShim, hiveTable);
+ this.defaultPartitionName =
conf.conf().get(HiveConf.ConfVars.DEFAULTPARTITIONNAME.varname,
+
HiveConf.ConfVars.DEFAULTPARTITIONNAME.defaultStrVal);
+
+ this.fetcher =
fetcherFactory.createStrategy(getRuntimeContext().getUserCodeClassLoader());
+
+ Path location = new Path(hiveTable.getSd().getLocation());
+ FileSystem fs = location.getFileSystem(conf.conf());
+ this.fetcherContext = new PartitionFetcher.Context() {
+
+ @Override
+ public List<String> partitionKeys() {
+ return partitionKeys;
+ }
+
+ @Override
+ public Partition getPartition(String escapeName) throws
TException {
+ return client.getPartition(
+ tablePath.getDatabaseName(),
+ tablePath.getObjectName(),
+ escapeName);
+ }
+
+ @Override
+ public List<Partition> listPartitionsByFilter(String
filter) throws TException {
+ return client.listPartitionsByFilter(
+ tablePath.getDatabaseName(),
+ tablePath.getObjectName(),
+ filter,
+ (short) -1);
+ }
+
+ @Override
+ public FileSystem fileSystem() {
+ return fs;
+ }
+
+ @Override
+ public Path tableLocation() {
+ return new
Path(hiveTable.getSd().getLocation());
+ }
+ };
+
+ this.distinctPartitions = new HashSet<>();
+ if (context.isRestored()) {
+ LOG.info("Restoring state for the {}.",
getClass().getSimpleName());
+ this.currentReadTime =
this.currReadTimeState.get().iterator().next();
+
this.distinctPartitions.addAll(this.distinctPartsState.get().iterator().next());
+ } else {
+ LOG.info("No state to restore for the {}.",
getClass().getSimpleName());
+ if (startupPartition != null) {
+ this.currentReadTime = fetcher.extractTimestamp(
+ fetcherContext,
+ client.getPartition(
+
tablePath.getDatabaseName(),
+
tablePath.getObjectName(),
+
escapePathName(startupPartition)));
+ }
+ }
+ }
+
+ @Override
+ public void run(SourceContext<TimestampedHiveInputSplit> context)
throws Exception {
+ checkpointLock = context.getCheckpointLock();
+ while (isRunning) {
+ synchronized (checkpointLock) {
+ monitorAndForwardSplits(context);
+ }
+ Thread.sleep(interval);
+ }
+ }
+
+ private void monitorAndForwardSplits(
+ SourceContext<TimestampedHiveInputSplit> context)
throws Exception {
+ assert (Thread.holdsLock(checkpointLock));
+
+ List<Partition> partitions =
fetcher.fetchPartitions(fetcherContext, currentReadTime);
+
+ if (partitions.isEmpty()) {
+ return;
+ }
+
+ long maxTimestamp = Long.MIN_VALUE;
+ Set<List<String>> nextDistinctParts = new HashSet<>();
+ for (Partition partition : partitions) {
+ List<String> partSpec = partition.getValues();
+ if (!this.distinctPartitions.contains(partSpec)) {
+
this.distinctPartitions.add(partition.getValues());
+ long timestamp =
this.fetcher.extractTimestamp(fetcherContext, partition);
+ if (timestamp > currentReadTime) {
+ nextDistinctParts.add(partSpec);
+ }
+ if (timestamp > maxTimestamp) {
+ maxTimestamp = timestamp;
+ }
+ HiveTableInputSplit[] splits =
HiveTableInputFormat.createInputSplits(
+ this.readerParallelism,
+
Collections.singletonList(toHiveTablePartition(partition)),
+ this.conf.conf());
+ for (HiveTableInputSplit split : splits) {
+ context.collect(new
TimestampedHiveInputSplit(timestamp, split));
+ }
+ }
+ }
+
+ if (maxTimestamp > currentReadTime) {
Review comment:
Just ask the similar question as @lirui-apache said, if the partitions
is not sorted by timestamp ascending, then it seems have problems, say we have
partitions with timestamp like `[(p0, 5), (p1, 1), (p2, 3)]` ( the first part
of (p0, 5) is partition name and the second is timestamp ), now we have
emitted the timestamp=5 successfully, then we will update the currentReadTime =
5 I think. Once the operator restored, we will just start from the timestamp
= 5 to read the following partitions...it mistakenly skipped other timestamps
such as 1 and 3 , finally we will lost part of the data to consume....
Pls correct me if I'm wrong.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
[email protected]