Unverified Commit e52d78c7 authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Feature-1285][client] Add Column Lineage in Flink 1.11,1.12,1.13 (#1286)

parent ab5829b5
...@@ -912,7 +912,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -912,7 +912,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus()) if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus())
&& (Asserts.isNull(jobHistory.getJob()) || jobHistory.isError())) { && (Asserts.isNull(jobHistory.getJob()) || jobHistory.isError())) {
checkStatus = checkJobStatus(jobInfoDetail); checkStatus = checkJobStatus(jobInfoDetail);
log.debug("YarnState: " + checkStatus.getValue());
if (checkStatus.isDone()) { if (checkStatus.isDone()) {
jobInfoDetail.getInstance().setStatus(checkStatus.getValue()); jobInfoDetail.getInstance().setStatus(checkStatus.getValue());
jobInstanceService.updateById(jobInfoDetail.getInstance()); jobInstanceService.updateById(jobInfoDetail.getInstance());
......
...@@ -21,6 +21,8 @@ package com.dlink.executor; ...@@ -21,6 +21,8 @@ package com.dlink.executor;
import com.dlink.model.LineageRel; import com.dlink.model.LineageRel;
import com.dlink.result.SqlExplainResult; import com.dlink.result.SqlExplainResult;
import com.dlink.utils.FlinkStreamProgramWithoutPhysical;
import com.dlink.utils.LineageContext;
import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.dag.Transformation; import org.apache.flink.api.dag.Transformation;
...@@ -58,6 +60,7 @@ import org.apache.flink.table.operations.ModifyOperation; ...@@ -58,6 +60,7 @@ import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation; import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation; import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.planner.delegation.ExecutorBase; import org.apache.flink.table.planner.delegation.ExecutorBase;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.utils.ExecutorUtils; import org.apache.flink.table.planner.utils.ExecutorUtils;
import org.apache.flink.table.typeutils.FieldInfoUtils; import org.apache.flink.table.typeutils.FieldInfoUtils;
...@@ -81,27 +84,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -81,27 +84,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment { public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment {
private final StreamExecutionEnvironment executionEnvironment; private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl( public CustomTableEnvironmentImpl(
CatalogManager catalogManager, CatalogManager catalogManager,
ModuleManager moduleManager, ModuleManager moduleManager,
FunctionCatalog functionCatalog, FunctionCatalog functionCatalog,
TableConfig tableConfig, TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment, StreamExecutionEnvironment executionEnvironment,
Planner planner, Planner planner,
Executor executor, Executor executor,
boolean isStreamingMode, boolean isStreamingMode,
ClassLoader userClassLoader) { ClassLoader userClassLoader) {
super( super(
catalogManager, catalogManager,
moduleManager, moduleManager,
tableConfig, tableConfig,
executor, executor,
functionCatalog, functionCatalog,
planner, planner,
isStreamingMode, isStreamingMode,
userClassLoader); userClassLoader);
this.executionEnvironment = executionEnvironment; this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
} }
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) { public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
...@@ -113,21 +118,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -113,21 +118,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
configuration.setString("execution.runtime-mode", "BATCH"); configuration.setString("execution.runtime-mode", "BATCH");
TableConfig tableConfig = new TableConfig(); TableConfig tableConfig = new TableConfig();
tableConfig.addConfiguration(configuration); tableConfig.addConfiguration(configuration);
return create(executionEnvironment, EnvironmentSettings.newInstance().useBlinkPlanner().inBatchMode().build(), tableConfig); return create(executionEnvironment, EnvironmentSettings.newInstance().useBlinkPlanner().inBatchMode().build(),
tableConfig);
} }
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment, EnvironmentSettings settings) { public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings) {
return create(executionEnvironment, settings, new TableConfig()); return create(executionEnvironment, settings, new TableConfig());
} }
public static CustomTableEnvironmentImpl create( public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings, EnvironmentSettings settings,
TableConfig tableConfig) { TableConfig tableConfig) {
if (!settings.isStreamingMode()) { if (!settings.isStreamingMode()) {
throw new TableException( throw new TableException(
"StreamTableEnvironment can not run in batch mode for now, please use TableEnvironment."); "StreamTableEnvironment can not run in batch mode for now, please use TableEnvironment.");
} }
// temporary solution until FLINK-15635 is fixed // temporary solution until FLINK-15635 is fixed
...@@ -136,62 +143,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -136,62 +143,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
ModuleManager moduleManager = new ModuleManager(); ModuleManager moduleManager = new ModuleManager();
CatalogManager catalogManager = CatalogManager catalogManager =
CatalogManager.newBuilder() CatalogManager.newBuilder()
.classLoader(classLoader) .classLoader(classLoader)
.config(tableConfig.getConfiguration()) .config(tableConfig.getConfiguration())
.defaultCatalog( .defaultCatalog(
settings.getBuiltInCatalogName(), settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog( new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(), settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName())) settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig()) .executionConfig(executionEnvironment.getConfig())
.build(); .build();
FunctionCatalog functionCatalog = FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, catalogManager, moduleManager); new FunctionCatalog(tableConfig, catalogManager, moduleManager);
Map<String, String> executorProperties = settings.toExecutorProperties(); Map<String, String> executorProperties = settings.toExecutorProperties();
Executor executor = lookupExecutor(executorProperties, executionEnvironment); Executor executor = lookupExecutor(executorProperties, executionEnvironment);
Map<String, String> plannerProperties = settings.toPlannerProperties(); Map<String, String> plannerProperties = settings.toPlannerProperties();
Planner planner = Planner planner =
ComponentFactoryService.find(PlannerFactory.class, plannerProperties) ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create( .create(
plannerProperties, plannerProperties,
executor, executor,
tableConfig, tableConfig,
functionCatalog, functionCatalog,
catalogManager); catalogManager);
return new CustomTableEnvironmentImpl( return new CustomTableEnvironmentImpl(
catalogManager, catalogManager,
moduleManager, moduleManager,
functionCatalog, functionCatalog,
tableConfig, tableConfig,
executionEnvironment, executionEnvironment,
planner, planner,
executor, executor,
settings.isStreamingMode(), settings.isStreamingMode(),
classLoader); classLoader);
} }
private static Executor lookupExecutor( private static Executor lookupExecutor(
Map<String, String> executorProperties, Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) { StreamExecutionEnvironment executionEnvironment) {
try { try {
ExecutorFactory executorFactory = ExecutorFactory executorFactory =
ComponentFactoryService.find(ExecutorFactory.class, executorProperties); ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
Method createMethod = Method createMethod =
executorFactory executorFactory
.getClass() .getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class); .getMethod("create", Map.class, StreamExecutionEnvironment.class);
return (Executor) return (Executor) createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
} catch (Exception e) { } catch (Exception e) {
throw new TableException( throw new TableException(
"Could not instantiate the executor. Make sure a planner module is on the classpath", "Could not instantiate the executor. Make sure a planner module is on the classpath",
e); e);
} }
} }
...@@ -208,7 +214,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -208,7 +214,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
} }
List<Transformation<?>> trans = super.planner.translate(modifyOperations); List<Transformation<?>> trans = super.planner.translate(modifyOperations);
if (execEnv instanceof ExecutorBase) { if (execEnv instanceof ExecutorBase) {
StreamGraph streamGraph = ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans); StreamGraph streamGraph =
ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans);
JSONGenerator jsonGenerator = new JSONGenerator(streamGraph); JSONGenerator jsonGenerator = new JSONGenerator(streamGraph);
String json = jsonGenerator.getJSON(); String json = jsonGenerator.getJSON();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
...@@ -247,7 +254,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -247,7 +254,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
} }
List<Transformation<?>> trans = getPlanner().translate(modifyOperations); List<Transformation<?>> trans = getPlanner().translate(modifyOperations);
if (execEnv instanceof ExecutorBase) { if (execEnv instanceof ExecutorBase) {
StreamGraph streamGraph = ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans); StreamGraph streamGraph =
ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans);
if (tableConfig.getConfiguration().containsKey(PipelineOptions.NAME.key())) { if (tableConfig.getConfiguration().containsKey(PipelineOptions.NAME.key())) {
streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME)); streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME));
} }
...@@ -267,7 +275,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -267,7 +275,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
record.setParseTrue(true); record.setParseTrue(true);
if (operations.size() != 1) { if (operations.size() != 1) {
throw new TableException( throw new TableException(
"Unsupported SQL query! explainSql() only accepts a single SQL query."); "Unsupported SQL query! explainSql() only accepts a single SQL query.");
} }
Operation operation = operations.get(0); Operation operation = operations.get(0);
if (operation instanceof ModifyOperation) { if (operation instanceof ModifyOperation) {
...@@ -288,13 +296,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -288,13 +296,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
return record; return record;
} }
public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment, Map<String, Object> setMap) { public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment,
Map<String, Object> setMap) {
return false; return false;
} }
public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) { public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) {
JavaDataStreamQueryOperation<T> queryOperation = JavaDataStreamQueryOperation<T> queryOperation =
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields))); asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
return createTable(queryOperation); return createTable(queryOperation);
} }
...@@ -311,45 +320,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -311,45 +320,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override @Override
public List<LineageRel> getLineage(String statement) { public List<LineageRel> getLineage(String statement) {
return null; LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
} }
@Override @Override
public <T> void createTemporaryView( public <T> void createTemporaryView(
String path, DataStream<T> dataStream, Expression... fields) { String path, DataStream<T> dataStream, Expression... fields) {
createTemporaryView(path, fromDataStream(dataStream, fields)); createTemporaryView(path, fromDataStream(dataStream, fields));
} }
private <T> JavaDataStreamQueryOperation<T> asQueryOperation( private <T> JavaDataStreamQueryOperation<T> asQueryOperation(
DataStream<T> dataStream, Optional<List<Expression>> fields) { DataStream<T> dataStream,
Optional<List<Expression>> fields) {
TypeInformation<T> streamType = dataStream.getType(); TypeInformation<T> streamType = dataStream.getType();
// get field names and types for all non-replaced fields // get field names and types for all non-replaced fields
FieldInfoUtils.TypeInfoSchema typeInfoSchema = FieldInfoUtils.TypeInfoSchema typeInfoSchema =
fields.map( fields.map(
f -> { f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo = FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo( FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0])); streamType, f.toArray(new Expression[0]));
// check if event-time is enabled // check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined()); validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo; return fieldsInfo;
}) })
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType)); .orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
return new JavaDataStreamQueryOperation<>( return new JavaDataStreamQueryOperation<>(
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema()); dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
} }
private void validateTimeCharacteristic(boolean isRowtimeDefined) { private void validateTimeCharacteristic(boolean isRowtimeDefined) {
if (isRowtimeDefined if (isRowtimeDefined
&& executionEnvironment.getStreamTimeCharacteristic() && executionEnvironment.getStreamTimeCharacteristic() != TimeCharacteristic.EventTime) {
!= TimeCharacteristic.EventTime) {
throw new ValidationException( throw new ValidationException(
String.format( String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s", "A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
executionEnvironment.getStreamTimeCharacteristic())); executionEnvironment.getStreamTimeCharacteristic()));
} }
} }
} }
/*
*
* 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 com.dlink.utils;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.hep.HepMatchOrder;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.config.OptimizerConfigOptions;
import org.apache.flink.table.planner.plan.nodes.FlinkConventions;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkDecorrelateProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkGroupProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkVolcanoProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.HEP_RULES_EXECUTION_TYPE;
import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
/**
* FlinkStreamProgramWithoutPhysical
*
* @author wenmo
* @since 2022/8/20 23:33
*/
public class FlinkStreamProgramWithoutPhysical {
private static final String SUBQUERY_REWRITE = "subquery_rewrite";
private static final String TEMPORAL_JOIN_REWRITE = "temporal_join_rewrite";
private static final String DECORRELATE = "decorrelate";
private static final String DEFAULT_REWRITE = "default_rewrite";
private static final String PREDICATE_PUSHDOWN = "predicate_pushdown";
private static final String JOIN_REORDER = "join_reorder";
private static final String PROJECT_REWRITE = "project_rewrite";
private static final String LOGICAL = "logical";
private static final String LOGICAL_REWRITE = "logical_rewrite";
private static final String TIME_INDICATOR = "time_indicator";
public static FlinkChainedProgram buildProgram(Configuration config) {
FlinkChainedProgram chainedProgram = new FlinkChainedProgram();
// rewrite sub-queries to joins
chainedProgram.addLast(
SUBQUERY_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite QueryOperationCatalogViewTable before rewriting sub-queries
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references before rewriting sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.SEMI_JOIN_RULES())
.build(), "rewrite sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_SUBQUERY_RULES())
.build(), "sub-queries remove")
// convert RelOptTableImpl (which exists in SubQuery before) to FlinkRelOptTable
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references after sub-queries removed")
.build());
// rewrite special temporal join plan
chainedProgram.addLast(
TEMPORAL_JOIN_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.EXPAND_PLAN_RULES())
.build(),
"convert correlate to temporal table join")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.POST_EXPAND_CLEAN_UP_RULES())
.build(),
"convert enumerable table scan")
.build());
// query decorrelation
chainedProgram.addLast(DECORRELATE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite before decorrelation
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_RULES())
.build(),
"pre-rewrite before decorrelation")
.addProgram(new FlinkDecorrelateProgram(), "")
.build());
// default rewrite, includes: predicate simplification, expression reduction, window
// properties rewrite, etc.
chainedProgram.addLast(
DEFAULT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.DEFAULT_REWRITE_RULES())
.build());
// rule based optimization: push down predicate(s) in where clause, so it only needs to read
// the required data
chainedProgram.addLast(
PREDICATE_PUSHDOWN,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_PREPARE_RULES())
.build(),
"filter rules")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_TABLESCAN_PUSHDOWN_RULES())
.build(),
"push predicate into table scan")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PRUNE_EMPTY_RULES())
.build(),
"prune empty after predicate push down")
.build());
// join reorder
if (config.getBoolean(OptimizerConfigOptions.TABLE_OPTIMIZER_JOIN_REORDER_ENABLED)) {
chainedProgram.addLast(
JOIN_REORDER,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_PREPARE_RULES())
.build(), "merge join into MultiJoin")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_RULES())
.build(), "do join reorder")
.build());
}
// project rewrite
chainedProgram.addLast(
PROJECT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PROJECT_RULES())
.build());
// optimize the logical plan
chainedProgram.addLast(
LOGICAL,
FlinkVolcanoProgramBuilder.newBuilder()
.add(FlinkStreamRuleSets.LOGICAL_OPT_RULES())
.setRequiredOutputTraits(new Convention.Impl[]{
FlinkConventions.LOGICAL()
})
.build());
// logical rewrite
chainedProgram.addLast(
LOGICAL_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.LOGICAL_REWRITE())
.build());
return chainedProgram;
}
}
/*
*
* 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 com.dlink.utils;
import static org.apache.calcite.jdbc.CalciteSchemaBuilder.asRootSchema;
import com.dlink.model.LineageRel;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Snapshot;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.module.ModuleManager;
import org.apache.flink.table.operations.CatalogSinkModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.catalog.CatalogManagerCalciteSchema;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.delegation.PlannerContext;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.StreamOptimizeContext;
import org.apache.flink.table.planner.plan.trait.MiniBatchInterval;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
*/
public class LineageContext {
private final FlinkChainedProgram flinkChainedProgram;
private final TableEnvironmentImpl tableEnv;
public LineageContext(FlinkChainedProgram flinkChainedProgram, TableEnvironmentImpl tableEnv) {
this.flinkChainedProgram = flinkChainedProgram;
this.tableEnv = tableEnv;
}
/**
* Dynamic add getColumnOrigins method to class RelMdColumnOrigins by javassist:
*
* public Set<RelColumnOrigin> getColumnOrigins(Snapshot rel,RelMetadataQuery mq, int iOutputColumn) {
* return mq.getColumnOrigins(rel.getInput(), iOutputColumn);
* }
*/
static {
try {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.getCtClass("org.apache.calcite.rel.metadata.RelMdColumnOrigins");
CtClass[] parameters = new CtClass[]{classPool.get(Snapshot.class.getName()),
classPool.get(RelMetadataQuery.class.getName()), CtClass.intType
};
// add method
CtMethod ctMethod = new CtMethod(classPool.get("java.util.Set"), "getColumnOrigins", parameters, ctClass);
ctMethod.setModifiers(Modifier.PUBLIC);
ctMethod.setBody("{return $2.getColumnOrigins($1.getInput(), $3);}");
ctClass.addMethod(ctMethod);
// load the class
ctClass.toClass();
} catch (Exception e) {
throw new TableException("Dynamic add getColumnOrigins() method exception.", e);
}
}
public List<LineageRel> getLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Optimize original relNode to generate Optimized Logical Plan
RelNode optRelNode = optimize(oriRelNode);
// 3. Build lineage based from RelMetadataQuery
return buildFiledLineageResult(sinkTable, optRelNode);
}
private Tuple2<String, RelNode> parseStatement(String sql) {
List<Operation> operations = tableEnv.getParser().parse(sql);
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof CatalogSinkModifyOperation) {
CatalogSinkModifyOperation sinkOperation = (CatalogSinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
} else {
throw new TableException("Only insert is supported now.");
}
}
/**
* Calling each program's optimize method in sequence.
*/
private RelNode optimize(RelNode relNode) {
return flinkChainedProgram.optimize(relNode, new StreamOptimizeContext() {
@Override
public TableConfig getTableConfig() {
return tableEnv.getConfig();
}
@Override
public FunctionCatalog getFunctionCatalog() {
return new FunctionCatalog(tableEnv.getConfig(), tableEnv.getCatalogManager(), new ModuleManager());
}
@Override
public CatalogManager getCatalogManager() {
return tableEnv.getCatalogManager();
}
@Override
public SqlExprToRexConverterFactory getSqlExprToRexConverterFactory() {
return new SqlExprToRexConverterFactory() {
@Override
public SqlExprToRexConverter create(RelDataType relDataType) {
return new PlannerContext(
tableEnv.getConfig(),
new FunctionCatalog(tableEnv.getConfig(), tableEnv.getCatalogManager(),
new ModuleManager()),
tableEnv.getCatalogManager(),
asRootSchema(new CatalogManagerCalciteSchema(tableEnv.getCatalogManager(), true)),
new ArrayList<>()).createSqlExprToRexConverter(relDataType);
}
};
}
@Override
public <C> C unwrap(Class<C> clazz) {
return StreamOptimizeContext.super.unwrap(clazz);
}
@Override
public RexBuilder getRexBuilder() {
return getPlanner().getRelBuilder().getRexBuilder();
}
@Override
public boolean needFinalTimeIndicatorConversion() {
return true;
}
@Override
public boolean isUpdateBeforeRequired() {
return false;
}
@Override
public MiniBatchInterval getMiniBatchInterval() {
return MiniBatchInterval.NONE();
}
private PlannerBase getPlanner() {
return (PlannerBase) tableEnv.getPlanner();
}
});
}
/**
* Check the size of query and sink fields match
*/
private void validateSchema(String sinkTable, RelNode relNode, List<String> sinkFieldList) {
List<String> queryFieldList = relNode.getRowType().getFieldNames();
if (queryFieldList.size() != sinkFieldList.size()) {
throw new ValidationException(
String.format(
"Column types of query result and sink for %s do not match.\n"
+ "Query schema: %s\n"
+ "Sink schema: %s",
sinkTable, queryFieldList, sinkFieldList));
}
}
private List<LineageRel> buildFiledLineageResult(String sinkTable, RelNode optRelNode) {
// target columns
List<String> targetColumnList = tableEnv.from(sinkTable).getSchema().getTableColumns()
.stream().map(tableColumn -> tableColumn.getName()).collect(Collectors.toList());
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
RelMetadataQuery metadataQuery = optRelNode.getCluster().getMetadataQuery();
List<LineageRel> resultList = new ArrayList<>();
for (int index = 0; index < targetColumnList.size(); index++) {
String targetColumn = targetColumnList.get(index);
Set<RelColumnOrigin> relColumnOriginSet = metadataQuery.getColumnOrigins(optRelNode, index);
if (CollectionUtils.isNotEmpty(relColumnOriginSet)) {
for (RelColumnOrigin relColumnOrigin : relColumnOriginSet) {
// table
RelOptTable table = relColumnOrigin.getOriginTable();
String sourceTable = String.join(".", table.getQualifiedName());
// filed
int ordinal = relColumnOrigin.getOriginColumnOrdinal();
List<String> fieldNames = table.getRowType().getFieldNames();
String sourceColumn = fieldNames.get(ordinal);
// add record
resultList.add(LineageRel.build(sourceTable, sourceColumn, sinkTable, targetColumn));
}
}
}
return resultList;
}
}
...@@ -21,6 +21,8 @@ package com.dlink.executor; ...@@ -21,6 +21,8 @@ package com.dlink.executor;
import com.dlink.model.LineageRel; import com.dlink.model.LineageRel;
import com.dlink.result.SqlExplainResult; import com.dlink.result.SqlExplainResult;
import com.dlink.utils.FlinkStreamProgramWithoutPhysical;
import com.dlink.utils.LineageContext;
import org.apache.flink.api.common.RuntimeExecutionMode; import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.TypeInformation;
...@@ -60,6 +62,7 @@ import org.apache.flink.table.operations.ModifyOperation; ...@@ -60,6 +62,7 @@ import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation; import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation; import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.planner.delegation.ExecutorBase; import org.apache.flink.table.planner.delegation.ExecutorBase;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.utils.ExecutorUtils; import org.apache.flink.table.planner.utils.ExecutorUtils;
import org.apache.flink.table.typeutils.FieldInfoUtils; import org.apache.flink.table.typeutils.FieldInfoUtils;
...@@ -83,27 +86,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -83,27 +86,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment { public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment {
private final StreamExecutionEnvironment executionEnvironment; private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl( public CustomTableEnvironmentImpl(
CatalogManager catalogManager, CatalogManager catalogManager,
ModuleManager moduleManager, ModuleManager moduleManager,
FunctionCatalog functionCatalog, FunctionCatalog functionCatalog,
TableConfig tableConfig, TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment, StreamExecutionEnvironment executionEnvironment,
Planner planner, Planner planner,
Executor executor, Executor executor,
boolean isStreamingMode, boolean isStreamingMode,
ClassLoader userClassLoader) { ClassLoader userClassLoader) {
super( super(
catalogManager, catalogManager,
moduleManager, moduleManager,
tableConfig, tableConfig,
executor, executor,
functionCatalog, functionCatalog,
planner, planner,
isStreamingMode, isStreamingMode,
userClassLoader); userClassLoader);
this.executionEnvironment = executionEnvironment; this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
} }
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) { public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
...@@ -115,21 +120,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -115,21 +120,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
configuration.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); configuration.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH);
TableConfig tableConfig = new TableConfig(); TableConfig tableConfig = new TableConfig();
tableConfig.addConfiguration(configuration); tableConfig.addConfiguration(configuration);
return create(executionEnvironment, EnvironmentSettings.newInstance().useBlinkPlanner().inBatchMode().build(), tableConfig); return create(executionEnvironment, EnvironmentSettings.newInstance().useBlinkPlanner().inBatchMode().build(),
tableConfig);
} }
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment, EnvironmentSettings settings) { public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings) {
return create(executionEnvironment, settings, new TableConfig()); return create(executionEnvironment, settings, new TableConfig());
} }
public static CustomTableEnvironmentImpl create( public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings, EnvironmentSettings settings,
TableConfig tableConfig) { TableConfig tableConfig) {
if (!settings.isStreamingMode()) { if (!settings.isStreamingMode()) {
throw new TableException( throw new TableException(
"StreamTableEnvironment can not run in batch mode for now, please use TableEnvironment."); "StreamTableEnvironment can not run in batch mode for now, please use TableEnvironment.");
} }
// temporary solution until FLINK-15635 is fixed // temporary solution until FLINK-15635 is fixed
...@@ -138,62 +145,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -138,62 +145,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
ModuleManager moduleManager = new ModuleManager(); ModuleManager moduleManager = new ModuleManager();
CatalogManager catalogManager = CatalogManager catalogManager =
CatalogManager.newBuilder() CatalogManager.newBuilder()
.classLoader(classLoader) .classLoader(classLoader)
.config(tableConfig.getConfiguration()) .config(tableConfig.getConfiguration())
.defaultCatalog( .defaultCatalog(
settings.getBuiltInCatalogName(), settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog( new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(), settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName())) settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig()) .executionConfig(executionEnvironment.getConfig())
.build(); .build();
FunctionCatalog functionCatalog = FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, catalogManager, moduleManager); new FunctionCatalog(tableConfig, catalogManager, moduleManager);
Map<String, String> executorProperties = settings.toExecutorProperties(); Map<String, String> executorProperties = settings.toExecutorProperties();
Executor executor = lookupExecutor(executorProperties, executionEnvironment); Executor executor = lookupExecutor(executorProperties, executionEnvironment);
Map<String, String> plannerProperties = settings.toPlannerProperties(); Map<String, String> plannerProperties = settings.toPlannerProperties();
Planner planner = Planner planner =
ComponentFactoryService.find(PlannerFactory.class, plannerProperties) ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create( .create(
plannerProperties, plannerProperties,
executor, executor,
tableConfig, tableConfig,
functionCatalog, functionCatalog,
catalogManager); catalogManager);
return new CustomTableEnvironmentImpl( return new CustomTableEnvironmentImpl(
catalogManager, catalogManager,
moduleManager, moduleManager,
functionCatalog, functionCatalog,
tableConfig, tableConfig,
executionEnvironment, executionEnvironment,
planner, planner,
executor, executor,
settings.isStreamingMode(), settings.isStreamingMode(),
classLoader); classLoader);
} }
private static Executor lookupExecutor( private static Executor lookupExecutor(
Map<String, String> executorProperties, Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) { StreamExecutionEnvironment executionEnvironment) {
try { try {
ExecutorFactory executorFactory = ExecutorFactory executorFactory =
ComponentFactoryService.find(ExecutorFactory.class, executorProperties); ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
Method createMethod = Method createMethod =
executorFactory executorFactory
.getClass() .getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class); .getMethod("create", Map.class, StreamExecutionEnvironment.class);
return (Executor) return (Executor) createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
} catch (Exception e) { } catch (Exception e) {
throw new TableException( throw new TableException(
"Could not instantiate the executor. Make sure a planner module is on the classpath", "Could not instantiate the executor. Make sure a planner module is on the classpath",
e); e);
} }
} }
...@@ -210,7 +216,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -210,7 +216,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
} }
List<Transformation<?>> trans = super.planner.translate(modifyOperations); List<Transformation<?>> trans = super.planner.translate(modifyOperations);
if (execEnv instanceof ExecutorBase) { if (execEnv instanceof ExecutorBase) {
StreamGraph streamGraph = ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans); StreamGraph streamGraph =
ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans);
JSONGenerator jsonGenerator = new JSONGenerator(streamGraph); JSONGenerator jsonGenerator = new JSONGenerator(streamGraph);
String json = jsonGenerator.getJSON(); String json = jsonGenerator.getJSON();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
...@@ -249,7 +256,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -249,7 +256,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
} }
List<Transformation<?>> trans = getPlanner().translate(modifyOperations); List<Transformation<?>> trans = getPlanner().translate(modifyOperations);
if (execEnv instanceof ExecutorBase) { if (execEnv instanceof ExecutorBase) {
StreamGraph streamGraph = ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans); StreamGraph streamGraph =
ExecutorUtils.generateStreamGraph(((ExecutorBase) execEnv).getExecutionEnvironment(), trans);
if (tableConfig.getConfiguration().containsKey(PipelineOptions.NAME.key())) { if (tableConfig.getConfiguration().containsKey(PipelineOptions.NAME.key())) {
streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME)); streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME));
} }
...@@ -269,7 +277,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -269,7 +277,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
record.setParseTrue(true); record.setParseTrue(true);
if (operations.size() != 1) { if (operations.size() != 1) {
throw new TableException( throw new TableException(
"Unsupported SQL query! explainSql() only accepts a single SQL query."); "Unsupported SQL query! explainSql() only accepts a single SQL query.");
} }
Operation operation = operations.get(0); Operation operation = operations.get(0);
if (operation instanceof ModifyOperation) { if (operation instanceof ModifyOperation) {
...@@ -290,13 +298,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -290,13 +298,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
return record; return record;
} }
public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment, Map<String, Object> setMap) { public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment,
Map<String, Object> setMap) {
return false; return false;
} }
public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) { public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) {
JavaDataStreamQueryOperation<T> queryOperation = JavaDataStreamQueryOperation<T> queryOperation =
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields))); asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
return createTable(queryOperation); return createTable(queryOperation);
} }
...@@ -313,45 +322,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -313,45 +322,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override @Override
public List<LineageRel> getLineage(String statement) { public List<LineageRel> getLineage(String statement) {
return null; LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
} }
@Override @Override
public <T> void createTemporaryView( public <T> void createTemporaryView(
String path, DataStream<T> dataStream, Expression... fields) { String path, DataStream<T> dataStream, Expression... fields) {
createTemporaryView(path, fromDataStream(dataStream, fields)); createTemporaryView(path, fromDataStream(dataStream, fields));
} }
private <T> JavaDataStreamQueryOperation<T> asQueryOperation( private <T> JavaDataStreamQueryOperation<T> asQueryOperation(
DataStream<T> dataStream, Optional<List<Expression>> fields) { DataStream<T> dataStream,
Optional<List<Expression>> fields) {
TypeInformation<T> streamType = dataStream.getType(); TypeInformation<T> streamType = dataStream.getType();
// get field names and types for all non-replaced fields // get field names and types for all non-replaced fields
FieldInfoUtils.TypeInfoSchema typeInfoSchema = FieldInfoUtils.TypeInfoSchema typeInfoSchema =
fields.map( fields.map(
f -> { f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo = FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo( FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0])); streamType, f.toArray(new Expression[0]));
// check if event-time is enabled // check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined()); validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo; return fieldsInfo;
}) })
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType)); .orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
return new JavaDataStreamQueryOperation<>( return new JavaDataStreamQueryOperation<>(
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema()); dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
} }
private void validateTimeCharacteristic(boolean isRowtimeDefined) { private void validateTimeCharacteristic(boolean isRowtimeDefined) {
if (isRowtimeDefined if (isRowtimeDefined
&& executionEnvironment.getStreamTimeCharacteristic() && executionEnvironment.getStreamTimeCharacteristic() != TimeCharacteristic.EventTime) {
!= TimeCharacteristic.EventTime) {
throw new ValidationException( throw new ValidationException(
String.format( String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s", "A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
executionEnvironment.getStreamTimeCharacteristic())); executionEnvironment.getStreamTimeCharacteristic()));
} }
} }
} }
/*
*
* 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 com.dlink.utils;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.hep.HepMatchOrder;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.config.OptimizerConfigOptions;
import org.apache.flink.table.planner.plan.nodes.FlinkConventions;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkDecorrelateProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkGroupProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkVolcanoProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.HEP_RULES_EXECUTION_TYPE;
import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
/**
* FlinkStreamProgramWithoutPhysical
*
* @author wenmo
* @since 2022/8/20 23:33
*/
public class FlinkStreamProgramWithoutPhysical {
private static final String SUBQUERY_REWRITE = "subquery_rewrite";
private static final String TEMPORAL_JOIN_REWRITE = "temporal_join_rewrite";
private static final String DECORRELATE = "decorrelate";
private static final String DEFAULT_REWRITE = "default_rewrite";
private static final String PREDICATE_PUSHDOWN = "predicate_pushdown";
private static final String JOIN_REORDER = "join_reorder";
private static final String PROJECT_REWRITE = "project_rewrite";
private static final String LOGICAL = "logical";
private static final String LOGICAL_REWRITE = "logical_rewrite";
private static final String TIME_INDICATOR = "time_indicator";
public static FlinkChainedProgram buildProgram(Configuration config) {
FlinkChainedProgram chainedProgram = new FlinkChainedProgram();
// rewrite sub-queries to joins
chainedProgram.addLast(
SUBQUERY_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite QueryOperationCatalogViewTable before rewriting sub-queries
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references before rewriting sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.SEMI_JOIN_RULES())
.build(), "rewrite sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_SUBQUERY_RULES())
.build(), "sub-queries remove")
// convert RelOptTableImpl (which exists in SubQuery before) to FlinkRelOptTable
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references after sub-queries removed")
.build());
// rewrite special temporal join plan
chainedProgram.addLast(
TEMPORAL_JOIN_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.EXPAND_PLAN_RULES())
.build(),
"convert correlate to temporal table join")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.POST_EXPAND_CLEAN_UP_RULES())
.build(),
"convert enumerable table scan")
.build());
// query decorrelation
chainedProgram.addLast(DECORRELATE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite before decorrelation
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PRE_DECORRELATION_RULES())
.build(),
"pre-rewrite before decorrelation")
.addProgram(new FlinkDecorrelateProgram(), "")
.build());
// default rewrite, includes: predicate simplification, expression reduction, window
// properties rewrite, etc.
chainedProgram.addLast(
DEFAULT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.DEFAULT_REWRITE_RULES())
.build());
// rule based optimization: push down predicate(s) in where clause, so it only needs to read
// the required data
chainedProgram.addLast(
PREDICATE_PUSHDOWN,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_PREPARE_RULES())
.build(),
"filter rules")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_TABLESCAN_PUSHDOWN_RULES())
.build(),
"push predicate into table scan")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PRUNE_EMPTY_RULES())
.build(),
"prune empty after predicate push down")
.build());
// join reorder
if (config.getBoolean(OptimizerConfigOptions.TABLE_OPTIMIZER_JOIN_REORDER_ENABLED)) {
chainedProgram.addLast(
JOIN_REORDER,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_PREPARE_RULES())
.build(), "merge join into MultiJoin")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_RULES())
.build(), "do join reorder")
.build());
}
// project rewrite
chainedProgram.addLast(
PROJECT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PROJECT_RULES())
.build());
// optimize the logical plan
chainedProgram.addLast(
LOGICAL,
FlinkVolcanoProgramBuilder.newBuilder()
.add(FlinkStreamRuleSets.LOGICAL_OPT_RULES())
.setRequiredOutputTraits(new Convention.Impl[]{
FlinkConventions.LOGICAL()
})
.build());
// logical rewrite
chainedProgram.addLast(
LOGICAL_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.LOGICAL_REWRITE())
.build());
return chainedProgram;
}
}
/*
*
* 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 com.dlink.utils;
import static org.apache.calcite.jdbc.CalciteSchemaBuilder.asRootSchema;
import com.dlink.model.LineageRel;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Snapshot;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.module.ModuleManager;
import org.apache.flink.table.operations.CatalogSinkModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.catalog.CatalogManagerCalciteSchema;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.delegation.PlannerContext;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.StreamOptimizeContext;
import org.apache.flink.table.planner.plan.trait.MiniBatchInterval;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
*/
public class LineageContext {
private final FlinkChainedProgram flinkChainedProgram;
private final TableEnvironmentImpl tableEnv;
public LineageContext(FlinkChainedProgram flinkChainedProgram, TableEnvironmentImpl tableEnv) {
this.flinkChainedProgram = flinkChainedProgram;
this.tableEnv = tableEnv;
}
/**
* Dynamic add getColumnOrigins method to class RelMdColumnOrigins by javassist:
*
* public Set<RelColumnOrigin> getColumnOrigins(Snapshot rel,RelMetadataQuery mq, int iOutputColumn) {
* return mq.getColumnOrigins(rel.getInput(), iOutputColumn);
* }
*/
static {
try {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.getCtClass("org.apache.calcite.rel.metadata.RelMdColumnOrigins");
CtClass[] parameters = new CtClass[]{classPool.get(Snapshot.class.getName()),
classPool.get(RelMetadataQuery.class.getName()), CtClass.intType
};
// add method
CtMethod ctMethod = new CtMethod(classPool.get("java.util.Set"), "getColumnOrigins", parameters, ctClass);
ctMethod.setModifiers(Modifier.PUBLIC);
ctMethod.setBody("{return $2.getColumnOrigins($1.getInput(), $3);}");
ctClass.addMethod(ctMethod);
// load the class
ctClass.toClass();
} catch (Exception e) {
throw new TableException("Dynamic add getColumnOrigins() method exception.", e);
}
}
public List<LineageRel> getLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Optimize original relNode to generate Optimized Logical Plan
RelNode optRelNode = optimize(oriRelNode);
// 3. Build lineage based from RelMetadataQuery
return buildFiledLineageResult(sinkTable, optRelNode);
}
private Tuple2<String, RelNode> parseStatement(String sql) {
List<Operation> operations = tableEnv.getParser().parse(sql);
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof CatalogSinkModifyOperation) {
CatalogSinkModifyOperation sinkOperation = (CatalogSinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
} else {
throw new TableException("Only insert is supported now.");
}
}
/**
* Calling each program's optimize method in sequence.
*/
private RelNode optimize(RelNode relNode) {
return flinkChainedProgram.optimize(relNode, new StreamOptimizeContext() {
@Override
public TableConfig getTableConfig() {
return tableEnv.getConfig();
}
@Override
public FunctionCatalog getFunctionCatalog() {
return new FunctionCatalog(tableEnv.getConfig(), tableEnv.getCatalogManager(), new ModuleManager());
}
@Override
public CatalogManager getCatalogManager() {
return tableEnv.getCatalogManager();
}
@Override
public SqlExprToRexConverterFactory getSqlExprToRexConverterFactory() {
return new SqlExprToRexConverterFactory() {
@Override
public SqlExprToRexConverter create(RelDataType relDataType) {
return new PlannerContext(
tableEnv.getConfig(),
new FunctionCatalog(tableEnv.getConfig(), tableEnv.getCatalogManager(),
new ModuleManager()),
tableEnv.getCatalogManager(),
asRootSchema(new CatalogManagerCalciteSchema(tableEnv.getCatalogManager(), true)),
new ArrayList<>()).createSqlExprToRexConverter(relDataType);
}
};
}
@Override
public <C> C unwrap(Class<C> clazz) {
return StreamOptimizeContext.super.unwrap(clazz);
}
@Override
public RexBuilder getRexBuilder() {
return getPlanner().getRelBuilder().getRexBuilder();
}
@Override
public boolean needFinalTimeIndicatorConversion() {
return true;
}
@Override
public boolean isUpdateBeforeRequired() {
return false;
}
@Override
public MiniBatchInterval getMiniBatchInterval() {
return MiniBatchInterval.NONE();
}
private PlannerBase getPlanner() {
return (PlannerBase) tableEnv.getPlanner();
}
});
}
/**
* Check the size of query and sink fields match
*/
private void validateSchema(String sinkTable, RelNode relNode, List<String> sinkFieldList) {
List<String> queryFieldList = relNode.getRowType().getFieldNames();
if (queryFieldList.size() != sinkFieldList.size()) {
throw new ValidationException(
String.format(
"Column types of query result and sink for %s do not match.\n"
+ "Query schema: %s\n"
+ "Sink schema: %s",
sinkTable, queryFieldList, sinkFieldList));
}
}
private List<LineageRel> buildFiledLineageResult(String sinkTable, RelNode optRelNode) {
// target columns
List<String> targetColumnList = tableEnv.from(sinkTable).getSchema().getTableColumns()
.stream().map(tableColumn -> tableColumn.getName()).collect(Collectors.toList());
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
RelMetadataQuery metadataQuery = optRelNode.getCluster().getMetadataQuery();
List<LineageRel> resultList = new ArrayList<>();
for (int index = 0; index < targetColumnList.size(); index++) {
String targetColumn = targetColumnList.get(index);
Set<RelColumnOrigin> relColumnOriginSet = metadataQuery.getColumnOrigins(optRelNode, index);
if (CollectionUtils.isNotEmpty(relColumnOriginSet)) {
for (RelColumnOrigin relColumnOrigin : relColumnOriginSet) {
// table
RelOptTable table = relColumnOrigin.getOriginTable();
String sourceTable = String.join(".", table.getQualifiedName());
// filed
int ordinal = relColumnOrigin.getOriginColumnOrdinal();
List<String> fieldNames = table.getRowType().getFieldNames();
String sourceColumn = fieldNames.get(ordinal);
// add record
resultList.add(LineageRel.build(sourceTable, sourceColumn, sinkTable, targetColumn));
}
}
}
return resultList;
}
}
...@@ -63,6 +63,7 @@ import org.apache.flink.table.operations.QueryOperation; ...@@ -63,6 +63,7 @@ import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.operations.command.ResetOperation; import org.apache.flink.table.operations.command.ResetOperation;
import org.apache.flink.table.operations.command.SetOperation; import org.apache.flink.table.operations.command.SetOperation;
import org.apache.flink.table.planner.delegation.ExecutorBase; import org.apache.flink.table.planner.delegation.ExecutorBase;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.utils.ExecutorUtils; import org.apache.flink.table.planner.utils.ExecutorUtils;
import org.apache.flink.table.typeutils.FieldInfoUtils; import org.apache.flink.table.typeutils.FieldInfoUtils;
...@@ -74,6 +75,8 @@ import java.util.List; ...@@ -74,6 +75,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import com.dlink.utils.FlinkStreamProgramWithoutPhysical;
import com.dlink.utils.LineageContext;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
...@@ -87,6 +90,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -87,6 +90,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment { public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment {
private final StreamExecutionEnvironment executionEnvironment; private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl( public CustomTableEnvironmentImpl(
CatalogManager catalogManager, CatalogManager catalogManager,
...@@ -108,6 +112,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -108,6 +112,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
isStreamingMode, isStreamingMode,
userClassLoader); userClassLoader);
this.executionEnvironment = executionEnvironment; this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
} }
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) { public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
...@@ -360,7 +365,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements ...@@ -360,7 +365,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override @Override
public List<LineageRel> getLineage(String statement) { public List<LineageRel> getLineage(String statement) {
return null; LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
} }
@Override @Override
......
/*
*
* 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 com.dlink.utils;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.hep.HepMatchOrder;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.config.OptimizerConfigOptions;
import org.apache.flink.table.planner.plan.nodes.FlinkConventions;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkDecorrelateProgram;
import org.apache.flink.table.planner.plan.optimize.program.FlinkGroupProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.FlinkVolcanoProgramBuilder;
import org.apache.flink.table.planner.plan.optimize.program.HEP_RULES_EXECUTION_TYPE;
import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
/**
* FlinkStreamProgramWithoutPhysical
*
* @author wenmo
* @since 2022/8/20 23:33
*/
public class FlinkStreamProgramWithoutPhysical {
private static final String SUBQUERY_REWRITE = "subquery_rewrite";
private static final String TEMPORAL_JOIN_REWRITE = "temporal_join_rewrite";
private static final String DECORRELATE = "decorrelate";
private static final String DEFAULT_REWRITE = "default_rewrite";
private static final String PREDICATE_PUSHDOWN = "predicate_pushdown";
private static final String JOIN_REORDER = "join_reorder";
private static final String PROJECT_REWRITE = "project_rewrite";
private static final String LOGICAL = "logical";
private static final String LOGICAL_REWRITE = "logical_rewrite";
private static final String TIME_INDICATOR = "time_indicator";
public static FlinkChainedProgram buildProgram(Configuration config) {
FlinkChainedProgram chainedProgram = new FlinkChainedProgram();
// rewrite sub-queries to joins
chainedProgram.addLast(
SUBQUERY_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite QueryOperationCatalogViewTable before rewriting sub-queries
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references before rewriting sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.SEMI_JOIN_RULES())
.build(), "rewrite sub-queries to semi-join")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_SUBQUERY_RULES())
.build(), "sub-queries remove")
// convert RelOptTableImpl (which exists in SubQuery before) to FlinkRelOptTable
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.TABLE_REF_RULES())
.build(), "convert table references after sub-queries removed")
.build());
// rewrite special temporal join plan
chainedProgram.addLast(
TEMPORAL_JOIN_REWRITE,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.EXPAND_PLAN_RULES())
.build(), "convert correlate to temporal table join")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.POST_EXPAND_CLEAN_UP_RULES())
.build(), "convert enumerable table scan")
.build());
// query decorrelation
chainedProgram.addLast(DECORRELATE,
FlinkGroupProgramBuilder.newBuilder()
// rewrite before decorrelation
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PRE_DECORRELATION_RULES())
.build(), "pre-rewrite before decorrelation")
.addProgram(new FlinkDecorrelateProgram(), "")
.build());
// default rewrite, includes: predicate simplification, expression reduction, window
// properties rewrite, etc.
chainedProgram.addLast(
DEFAULT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.DEFAULT_REWRITE_RULES())
.build());
// rule based optimization: push down predicate(s) in where clause, so it only needs to read
// the required data
chainedProgram.addLast(
PREDICATE_PUSHDOWN,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_PREPARE_RULES())
.build(), "filter rules")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.FILTER_TABLESCAN_PUSHDOWN_RULES())
.build(), "push predicate into table scan")
.addProgram(
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PRUNE_EMPTY_RULES())
.build(), "prune empty after predicate push down")
.build());
// join reorder
if (config.getBoolean(OptimizerConfigOptions.TABLE_OPTIMIZER_JOIN_REORDER_ENABLED)) {
chainedProgram.addLast(
JOIN_REORDER,
FlinkGroupProgramBuilder.newBuilder()
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_PREPARE_RULES())
.build(), "merge join into MultiJoin")
.addProgram(FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.JOIN_REORDER_RULES())
.build(), "do join reorder")
.build());
}
// project rewrite
chainedProgram.addLast(
PROJECT_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.PROJECT_RULES())
.build());
// optimize the logical plan
chainedProgram.addLast(
LOGICAL,
FlinkVolcanoProgramBuilder.newBuilder()
.add(FlinkStreamRuleSets.LOGICAL_OPT_RULES())
.setRequiredOutputTraits(new Convention.Impl[] {
FlinkConventions.LOGICAL()
})
.build());
// logical rewrite
chainedProgram.addLast(
LOGICAL_REWRITE,
FlinkHepRuleSetProgramBuilder.newBuilder()
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(FlinkStreamRuleSets.LOGICAL_REWRITE())
.build());
return chainedProgram;
}
}
/*
*
* 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 com.dlink.utils;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Snapshot;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rex.RexBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.operations.CatalogSinkModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkRelBuilder;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.planner.plan.optimize.program.StreamOptimizeContext;
import org.apache.flink.table.planner.plan.trait.MiniBatchInterval;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.dlink.model.LineageRel;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
*/
public class LineageContext {
private final FlinkChainedProgram flinkChainedProgram;
private final TableEnvironmentImpl tableEnv;
public LineageContext(FlinkChainedProgram flinkChainedProgram, TableEnvironmentImpl tableEnv) {
this.flinkChainedProgram = flinkChainedProgram;
this.tableEnv = tableEnv;
}
/**
* Dynamic add getColumnOrigins method to class RelMdColumnOrigins by javassist:
*
* public Set<RelColumnOrigin> getColumnOrigins(Snapshot rel,RelMetadataQuery mq, int iOutputColumn) {
* return mq.getColumnOrigins(rel.getInput(), iOutputColumn);
* }
*/
static {
try {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.getCtClass("org.apache.calcite.rel.metadata.RelMdColumnOrigins");
CtClass[] parameters = new CtClass[] {classPool.get(Snapshot.class.getName())
, classPool.get(RelMetadataQuery.class.getName())
, CtClass.intType
};
// add method
CtMethod ctMethod = new CtMethod(classPool.get("java.util.Set"), "getColumnOrigins", parameters, ctClass);
ctMethod.setModifiers(Modifier.PUBLIC);
ctMethod.setBody("{return $2.getColumnOrigins($1.getInput(), $3);}");
ctClass.addMethod(ctMethod);
// load the class
ctClass.toClass();
} catch (Exception e) {
throw new TableException("Dynamic add getColumnOrigins() method exception.", e);
}
}
public List<LineageRel> getLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Optimize original relNode to generate Optimized Logical Plan
RelNode optRelNode = optimize(oriRelNode);
// 3. Build lineage based from RelMetadataQuery
return buildFiledLineageResult(sinkTable, optRelNode);
}
private Tuple2<String, RelNode> parseStatement(String sql) {
List<Operation> operations = tableEnv.getParser().parse(sql);
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof CatalogSinkModifyOperation) {
CatalogSinkModifyOperation sinkOperation = (CatalogSinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
} else {
throw new TableException("Only insert is supported now.");
}
}
/**
* Calling each program's optimize method in sequence.
*/
private RelNode optimize(RelNode relNode) {
return flinkChainedProgram.optimize(relNode, new StreamOptimizeContext() {
@Override
public TableConfig getTableConfig() {
return tableEnv.getConfig();
}
@Override
public FunctionCatalog getFunctionCatalog() {
return getPlanner().getFlinkContext().getFunctionCatalog();
}
@Override
public CatalogManager getCatalogManager() {
return tableEnv.getCatalogManager();
}
@Override
public SqlExprToRexConverterFactory getSqlExprToRexConverterFactory() {
return getPlanner().getFlinkContext().getSqlExprToRexConverterFactory();
}
@Override
public <C> C unwrap(Class<C> clazz) {
return getPlanner().getFlinkContext().unwrap(clazz);
}
@Override
public RexBuilder getRexBuilder() {
return getPlanner().getRelBuilder().getRexBuilder();
}
@Override
public boolean needFinalTimeIndicatorConversion() {
return true;
}
@Override
public boolean isUpdateBeforeRequired() {
return false;
}
@Override
public MiniBatchInterval getMiniBatchInterval() {
return MiniBatchInterval.NONE;
}
private PlannerBase getPlanner() {
return (PlannerBase) tableEnv.getPlanner();
}
});
}
/**
* Check the size of query and sink fields match
*/
private void validateSchema(String sinkTable, RelNode relNode, List<String> sinkFieldList) {
List<String> queryFieldList = relNode.getRowType().getFieldNames();
if (queryFieldList.size() != sinkFieldList.size()) {
throw new ValidationException(
String.format(
"Column types of query result and sink for %s do not match.\n"
+ "Query schema: %s\n"
+ "Sink schema: %s",
sinkTable, queryFieldList, sinkFieldList));
}
}
private List<LineageRel> buildFiledLineageResult(String sinkTable, RelNode optRelNode) {
// target columns
List<String> targetColumnList = tableEnv.from(sinkTable)
.getResolvedSchema()
.getColumnNames();
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
RelMetadataQuery metadataQuery = optRelNode.getCluster().getMetadataQuery();
List<LineageRel> resultList = new ArrayList<>();
for (int index = 0; index < targetColumnList.size(); index++) {
String targetColumn = targetColumnList.get(index);
Set<RelColumnOrigin> relColumnOriginSet = metadataQuery.getColumnOrigins(optRelNode, index);
if (CollectionUtils.isNotEmpty(relColumnOriginSet)) {
for (RelColumnOrigin relColumnOrigin : relColumnOriginSet) {
// table
RelOptTable table = relColumnOrigin.getOriginTable();
String sourceTable = String.join(".", table.getQualifiedName());
// filed
int ordinal = relColumnOrigin.getOriginColumnOrdinal();
List<String> fieldNames = table.getRowType().getFieldNames();
String sourceColumn = fieldNames.get(ordinal);
// add record
resultList.add(LineageRel.build(sourceTable, sourceColumn, sinkTable, targetColumn));
}
}
}
return resultList;
}
}
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.flink</groupId> <groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner_${scala.binary.version}</artifactId> <artifactId>flink-table-planner_2.12</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
...@@ -54,7 +54,7 @@ ...@@ -54,7 +54,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.flink</groupId> <groupId>org.apache.flink</groupId>
<artifactId>flink-table-api-scala-bridge_${scala.binary.version}</artifactId> <artifactId>flink-table-api-scala-bridge_2.12</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency> <dependency>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment