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/01/22 08:37:40 UTC

[GitHub] [flink] dianfu commented on a change in pull request #10913: [FLINK-15636][python] Supports Python UDF in old planner under batch mode

dianfu commented on a change in pull request #10913: [FLINK-15636][python] Supports Python UDF in old planner under batch mode
URL: https://github.com/apache/flink/pull/10913#discussion_r369413656
 
 

 ##########
 File path: flink-python/src/main/java/org/apache/flink/table/runtime/functions/python/PythonScalarFunctionFlatMap.java
 ##########
 @@ -0,0 +1,319 @@
+/*
+ * 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.table.runtime.functions.python;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.functions.RichFlatMapFunction;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.ConfigurationUtils;
+import org.apache.flink.python.PythonConfig;
+import org.apache.flink.python.PythonFunctionRunner;
+import org.apache.flink.python.PythonOptions;
+import org.apache.flink.python.env.ProcessPythonEnvironmentManager;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.python.env.PythonEnvironmentManager;
+import org.apache.flink.table.functions.ScalarFunction;
+import org.apache.flink.table.functions.python.PythonEnv;
+import org.apache.flink.table.functions.python.PythonFunctionInfo;
+import org.apache.flink.table.runtime.runners.python.PythonScalarFunctionRunner;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.utils.LegacyTypeInfoDataTypeConverter;
+import org.apache.flink.table.types.utils.LogicalTypeDataTypeConverter;
+import org.apache.flink.table.types.utils.TypeConversions;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.beam.sdk.fn.data.FnDataReceiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+/**
+ * The {@link RichFlatMapFunction} used to invoke Python {@link ScalarFunction} functions for the
+ * old planner.
+ */
+@Internal
+public final class PythonScalarFunctionFlatMap
+		extends RichFlatMapFunction<Row, Row> implements ResultTypeQueryable<Row> {
+
+	private static final long serialVersionUID = 1L;
+
+	protected static final Logger LOG = LoggerFactory.getLogger(PythonScalarFunctionFlatMap.class);
+
+	/**
+	 * The type serializer for the forwarded fields.
+	 */
+	private transient TypeSerializer<Row> forwardedInputSerializer;
+
+	/**
+	 * The Python {@link ScalarFunction}s to be executed.
+	 */
+	protected final PythonFunctionInfo[] scalarFunctions;
+
+	/**
+	 * The input logical type.
+	 */
+	protected final RowType inputType;
+
+	/**
+	 * The output logical type.
+	 */
+	protected final RowType outputType;
+
+	/**
+	 * The offsets of udf inputs.
+	 */
+	protected final int[] udfInputOffsets;
+
+	/**
+	 * The offset of the fields which should be forwarded.
+	 */
+	protected final int[] forwardedFields;
+
+	/**
+	 * The udf input logical type.
+	 */
+	protected transient RowType udfInputType;
+
+	/**
+	 * The udf output logical type.
+	 */
+	protected transient RowType udfOutputType;
+
+	/**
+	 * The queue holding the input elements for which the execution results have not been received.
+	 */
+	protected transient LinkedBlockingQueue<Row> forwardedInputQueue;
+
+	/**
+	 * The queue holding the user-defined function execution results. The execution results are in
+	 * the same order as the input elements.
+	 */
+	protected transient LinkedBlockingQueue<Row> udfResultQueue;
+
+	/**
+	 * The python config.
+	 */
+	private final PythonConfig config;
+
+	/**
+	 * Use an AtomicBoolean because we start/stop bundles by a timer thread.
+	 */
+	private transient AtomicBoolean bundleStarted;
+
+	/**
+	 * Max number of elements to include in a bundle.
+	 */
+	private transient int maxBundleSize;
+
+	/**
+	 * The collector used to collect records.
+	 */
+	private transient Collector<Row> resultCollector;
+
+	/**
+	 * Number of processed elements in the current bundle.
+	 */
+	private transient int elementCount;
+
+	/**
+	 * The {@link PythonFunctionRunner} which is responsible for Python user-defined function execution.
+	 */
+	private transient PythonFunctionRunner<Row> pythonFunctionRunner;
+
+	public PythonScalarFunctionFlatMap(
+		Configuration config,
+		PythonFunctionInfo[] scalarFunctions,
+		RowType inputType,
+		RowType outputType,
+		int[] udfInputOffsets,
+		int[] forwardedFields) {
+		this.scalarFunctions = Preconditions.checkNotNull(scalarFunctions);
+		this.inputType = Preconditions.checkNotNull(inputType);
+		this.outputType = Preconditions.checkNotNull(outputType);
+		this.udfInputOffsets = Preconditions.checkNotNull(udfInputOffsets);
+		this.forwardedFields = Preconditions.checkNotNull(forwardedFields);
+		this.config = new PythonConfig(Preconditions.checkNotNull(config));
+	}
+
+	@Override
+	public void open(Configuration parameters) throws Exception {
+		super.open(parameters);
+
+		this.elementCount = 0;
+		this.bundleStarted = new AtomicBoolean(false);
+		this.maxBundleSize = config.getMaxBundleSize();
+		if (this.maxBundleSize <= 0) {
+			this.maxBundleSize = PythonOptions.MAX_BUNDLE_SIZE.defaultValue();
+			LOG.error("Invalid value for the maximum bundle size. Using default value of " +
+				this.maxBundleSize + '.');
+		} else {
+			LOG.info("The maximum bundle size is configured to {}.", this.maxBundleSize);
+		}
+
+		if (config.getMaxBundleTimeMills() != PythonOptions.MAX_BUNDLE_TIME_MILLS.defaultValue()) {
+			LOG.info("Maximum bundle time takes no effect in old planner under batch mode. " +
+				"Config maximum bundle size instead! " +
+				"Under batch mode, bundle size should be enough to control both throughput and latency.");
+		}
+
+		forwardedInputQueue = new LinkedBlockingQueue<>();
+		udfResultQueue = new LinkedBlockingQueue<>();
+		udfInputType = new RowType(
+			Arrays.stream(udfInputOffsets)
+				.mapToObj(i -> inputType.getFields().get(i))
+				.collect(Collectors.toList()));
+		udfOutputType = new RowType(outputType.getFields().subList(forwardedFields.length, outputType.getFieldCount()));
+
+		RowTypeInfo forwardedInputTypeInfo = new RowTypeInfo(
+			Arrays.stream(forwardedFields)
+				.mapToObj(i -> inputType.getFields().get(i))
+				.map(RowType.RowField::getType)
+				.map(TypeConversions::fromLogicalToDataType)
+				.map(TypeConversions::fromDataTypeToLegacyInfo)
+				.toArray(TypeInformation[]::new));
+		forwardedInputSerializer = forwardedInputTypeInfo.createSerializer(getRuntimeContext().getExecutionConfig());
+
+		this.pythonFunctionRunner = createPythonFunctionRunner();
+		this.pythonFunctionRunner.open();
+		this.resultCollector = null;
+	}
+
+	@Override
+	public void flatMap(Row value, Collector<Row> out) throws Exception {
+		this.resultCollector = out;
+		bufferInput(value);
+
+		checkInvokeStartBundle();
+		pythonFunctionRunner.processElement(getUdfInput(value));
+		checkInvokeFinishBundleByCount();
+		emitResults();
+	}
+
+	/**
+	 * Checks whether to invoke startBundle.
+	 */
+	private void checkInvokeStartBundle() throws Exception {
+		if (bundleStarted.compareAndSet(false, true)) {
+			pythonFunctionRunner.startBundle();
+		}
+	}
+
+	/**
+	 * Checks whether to invoke finishBundle by elements count. Called in processElement.
 
 Review comment:
   Correct the Java doc: Called in processElement -> Called in flatMap

----------------------------------------------------------------
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


With regards,
Apache Git Services