You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2020/05/09 05:16:22 UTC

[GitHub] [flink] JingsongLi commented on a change in pull request #12004: [FLINK-17434][core][hive] Hive partitioned source support streaming read

JingsongLi commented on a change in pull request #12004:
URL: https://github.com/apache/flink/pull/12004#discussion_r422454432



##########
File path: flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/read/HiveContinuousMonitoringFunction.java
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.PartitionStrategy.PartitionStrategyFactory;
+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.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;
+
+/**
+ * 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 long startupTimestampMillis;
+
+	private final PartitionStrategyFactory partStrategyFactory;
+
+	private volatile boolean isRunning = true;
+
+	/** The maximum partition read time seen so far. */
+	private volatile long currentReadTime;
+
+	private transient PartitionStrategy strategy;
+
+	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,
+			long startupTimestampMillis,
+			PartitionStrategyFactory partStrategyFactory,
+			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.startupTimestampMillis = startupTimestampMillis;
+		this.partStrategyFactory = partStrategyFactory;
+
+		this.interval = interval;
+		this.readerParallelism = Math.max(readerParallelism, 1);
+		this.currentReadTime = Long.MIN_VALUE;
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		this.strategy = partStrategyFactory.createStrategy(getRuntimeContext().getUserCodeClassLoader());
+
+		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.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());
+			this.currentReadTime = this.startupTimestampMillis;
+		}
+	}
+
+	@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 IOException, TException {
+		assert (Thread.holdsLock(checkpointLock));
+
+		List<Partition> partitions = client.listPartitionsByFilter(
+				tablePath.getDatabaseName(),
+				tablePath.getObjectName(),
+				strategy.generateFetchFilter(partitionKeys, currentReadTime),
+				(short) -1);
+
+		if (partitions.isEmpty()) {
+			return;
+		}
+
+		long maxTime = Long.MIN_VALUE;
+		for (Partition partition : partitions) {
+			List<String> partSpec = partition.getValues();
+			if (!this.distinctPartitions.contains(partSpec)) {
+				this.distinctPartitions.add(partition.getValues());
+				long time = this.strategy.extractPartTime(partitionKeys, partition.getValues());
+				if (time > maxTime) {
+					maxTime = time;
+				}
+				HiveTableInputSplit[] splits = HiveTableInputFormat.createInputSplits(
+						this.readerParallelism,
+						Collections.singletonList(toHiveTablePartition(partition)),
+						this.conf.conf());
+				for (HiveTableInputSplit split : splits) {
+					context.collect(new TimestampedHiveInputSplit(time, split));
+				}
+			}
+		}
+		this.currentReadTime = maxTime;
+
+		this.distinctPartitions.removeIf(partSpec -> this.strategy.canExpireForDistinct(
+				this.strategy.extractPartTime(partitionKeys, partSpec),
+				this.currentReadTime));
+	}
+
+	private HiveTablePartition toHiveTablePartition(Partition p) {
+		return HiveTableSource.toHiveTablePartition(
+				partitionKeys, fieldNames, fieldTypes, hiveShim, tableProps, defaultPartitionName, p);
+	}
+
+	@Override
+	public void snapshotState(FunctionSnapshotContext context) throws Exception {
+		Preconditions.checkState(this.currReadTimeState != null,
+				"The " + getClass().getSimpleName() + " state has not been properly initialized.");
+
+		this.currReadTimeState.clear();
+		this.currReadTimeState.add(this.currentReadTime);
+
+		this.distinctPartsState.clear();
+		this.distinctPartsState.add(new ArrayList<>(this.distinctPartitions));
+
+		if (LOG.isDebugEnabled()) {
+			LOG.debug("{} checkpointed {}.", getClass().getSimpleName(), currentReadTime);
+		}
+	}
+
+	@Override
+	public void close() throws Exception {
+		super.close();
+
+		if (checkpointLock != null) {
+			synchronized (checkpointLock) {
+				currentReadTime = Long.MAX_VALUE;
+				isRunning = false;
+			}
+		}
+	}
+
+	@Override
+	public void cancel() {
+		if (checkpointLock != null) {
+			// this is to cover the case where cancel() is called before the run()

Review comment:
       this is from another thread.




----------------------------------------------------------------
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:
users@infra.apache.org