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
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus())
&& (Asserts.isNull(jobHistory.getJob()) || jobHistory.isError())) {
checkStatus = checkJobStatus(jobInfoDetail);
log.debug("YarnState: " + checkStatus.getValue());
if (checkStatus.isDone()) {
jobInfoDetail.getInstance().setStatus(checkStatus.getValue());
jobInstanceService.updateById(jobInfoDetail.getInstance());
......
......@@ -21,6 +21,8 @@ package com.dlink.executor;
import com.dlink.model.LineageRel;
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.dag.Transformation;
......@@ -58,6 +60,7 @@ import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
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.typeutils.FieldInfoUtils;
......@@ -81,27 +84,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment {
private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl(
CatalogManager catalogManager,
ModuleManager moduleManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode,
ClassLoader userClassLoader) {
CatalogManager catalogManager,
ModuleManager moduleManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode,
ClassLoader userClassLoader) {
super(
catalogManager,
moduleManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
userClassLoader);
catalogManager,
moduleManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
userClassLoader);
this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
......@@ -113,21 +118,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
configuration.setString("execution.runtime-mode", "BATCH");
TableConfig tableConfig = new TableConfig();
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());
}
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings,
TableConfig tableConfig) {
StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings,
TableConfig tableConfig) {
if (!settings.isStreamingMode()) {
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
......@@ -136,62 +143,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
ModuleManager moduleManager = new ModuleManager();
CatalogManager catalogManager =
CatalogManager.newBuilder()
.classLoader(classLoader)
.config(tableConfig.getConfiguration())
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
CatalogManager.newBuilder()
.classLoader(classLoader)
.config(tableConfig.getConfiguration())
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, catalogManager, moduleManager);
new FunctionCatalog(tableConfig, catalogManager, moduleManager);
Map<String, String> executorProperties = settings.toExecutorProperties();
Executor executor = lookupExecutor(executorProperties, executionEnvironment);
Map<String, String> plannerProperties = settings.toPlannerProperties();
Planner planner =
ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create(
plannerProperties,
executor,
tableConfig,
functionCatalog,
catalogManager);
ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create(
plannerProperties,
executor,
tableConfig,
functionCatalog,
catalogManager);
return new CustomTableEnvironmentImpl(
catalogManager,
moduleManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode(),
classLoader);
catalogManager,
moduleManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode(),
classLoader);
}
private static Executor lookupExecutor(
Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) {
Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) {
try {
ExecutorFactory executorFactory =
ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
Method createMethod =
executorFactory
.getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class);
executorFactory
.getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class);
return (Executor)
createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
return (Executor) createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
} catch (Exception e) {
throw new TableException(
"Could not instantiate the executor. Make sure a planner module is on the classpath",
e);
"Could not instantiate the executor. Make sure a planner module is on the classpath",
e);
}
}
......@@ -208,7 +214,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
}
List<Transformation<?>> trans = super.planner.translate(modifyOperations);
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);
String json = jsonGenerator.getJSON();
ObjectMapper mapper = new ObjectMapper();
......@@ -247,7 +254,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
}
List<Transformation<?>> trans = getPlanner().translate(modifyOperations);
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())) {
streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME));
}
......@@ -267,7 +275,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
record.setParseTrue(true);
if (operations.size() != 1) {
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);
if (operation instanceof ModifyOperation) {
......@@ -288,13 +296,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
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;
}
public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) {
JavaDataStreamQueryOperation<T> queryOperation =
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
return createTable(queryOperation);
}
......@@ -311,45 +320,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override
public List<LineageRel> getLineage(String statement) {
return null;
LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
}
@Override
public <T> void createTemporaryView(
String path, DataStream<T> dataStream, Expression... fields) {
String path, DataStream<T> dataStream, Expression... fields) {
createTemporaryView(path, fromDataStream(dataStream, fields));
}
private <T> JavaDataStreamQueryOperation<T> asQueryOperation(
DataStream<T> dataStream, Optional<List<Expression>> fields) {
DataStream<T> dataStream,
Optional<List<Expression>> fields) {
TypeInformation<T> streamType = dataStream.getType();
// get field names and types for all non-replaced fields
FieldInfoUtils.TypeInfoSchema typeInfoSchema =
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
return new JavaDataStreamQueryOperation<>(
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
}
private void validateTimeCharacteristic(boolean isRowtimeDefined) {
if (isRowtimeDefined
&& executionEnvironment.getStreamTimeCharacteristic()
!= TimeCharacteristic.EventTime) {
&& executionEnvironment.getStreamTimeCharacteristic() != TimeCharacteristic.EventTime) {
throw new ValidationException(
String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
executionEnvironment.getStreamTimeCharacteristic()));
String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
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;
import com.dlink.model.LineageRel;
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.typeinfo.TypeInformation;
......@@ -60,6 +62,7 @@ import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
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.typeutils.FieldInfoUtils;
......@@ -83,27 +86,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements CustomTableEnvironment {
private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl(
CatalogManager catalogManager,
ModuleManager moduleManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode,
ClassLoader userClassLoader) {
CatalogManager catalogManager,
ModuleManager moduleManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode,
ClassLoader userClassLoader) {
super(
catalogManager,
moduleManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
userClassLoader);
catalogManager,
moduleManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
userClassLoader);
this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
......@@ -115,21 +120,23 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
configuration.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH);
TableConfig tableConfig = new TableConfig();
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());
}
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings,
TableConfig tableConfig) {
StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings,
TableConfig tableConfig) {
if (!settings.isStreamingMode()) {
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
......@@ -138,62 +145,61 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
ModuleManager moduleManager = new ModuleManager();
CatalogManager catalogManager =
CatalogManager.newBuilder()
.classLoader(classLoader)
.config(tableConfig.getConfiguration())
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
CatalogManager.newBuilder()
.classLoader(classLoader)
.config(tableConfig.getConfiguration())
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, catalogManager, moduleManager);
new FunctionCatalog(tableConfig, catalogManager, moduleManager);
Map<String, String> executorProperties = settings.toExecutorProperties();
Executor executor = lookupExecutor(executorProperties, executionEnvironment);
Map<String, String> plannerProperties = settings.toPlannerProperties();
Planner planner =
ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create(
plannerProperties,
executor,
tableConfig,
functionCatalog,
catalogManager);
ComponentFactoryService.find(PlannerFactory.class, plannerProperties)
.create(
plannerProperties,
executor,
tableConfig,
functionCatalog,
catalogManager);
return new CustomTableEnvironmentImpl(
catalogManager,
moduleManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode(),
classLoader);
catalogManager,
moduleManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode(),
classLoader);
}
private static Executor lookupExecutor(
Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) {
Map<String, String> executorProperties,
StreamExecutionEnvironment executionEnvironment) {
try {
ExecutorFactory executorFactory =
ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
ComponentFactoryService.find(ExecutorFactory.class, executorProperties);
Method createMethod =
executorFactory
.getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class);
executorFactory
.getClass()
.getMethod("create", Map.class, StreamExecutionEnvironment.class);
return (Executor)
createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
return (Executor) createMethod.invoke(executorFactory, executorProperties, executionEnvironment);
} catch (Exception e) {
throw new TableException(
"Could not instantiate the executor. Make sure a planner module is on the classpath",
e);
"Could not instantiate the executor. Make sure a planner module is on the classpath",
e);
}
}
......@@ -210,7 +216,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
}
List<Transformation<?>> trans = super.planner.translate(modifyOperations);
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);
String json = jsonGenerator.getJSON();
ObjectMapper mapper = new ObjectMapper();
......@@ -249,7 +256,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
}
List<Transformation<?>> trans = getPlanner().translate(modifyOperations);
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())) {
streamGraph.setJobName(tableConfig.getConfiguration().getString(PipelineOptions.NAME));
}
......@@ -269,7 +277,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
record.setParseTrue(true);
if (operations.size() != 1) {
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);
if (operation instanceof ModifyOperation) {
......@@ -290,13 +298,14 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
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;
}
public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) {
JavaDataStreamQueryOperation<T> queryOperation =
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)));
return createTable(queryOperation);
}
......@@ -313,45 +322,46 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override
public List<LineageRel> getLineage(String statement) {
return null;
LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
}
@Override
public <T> void createTemporaryView(
String path, DataStream<T> dataStream, Expression... fields) {
String path, DataStream<T> dataStream, Expression... fields) {
createTemporaryView(path, fromDataStream(dataStream, fields));
}
private <T> JavaDataStreamQueryOperation<T> asQueryOperation(
DataStream<T> dataStream, Optional<List<Expression>> fields) {
DataStream<T> dataStream,
Optional<List<Expression>> fields) {
TypeInformation<T> streamType = dataStream.getType();
// get field names and types for all non-replaced fields
FieldInfoUtils.TypeInfoSchema typeInfoSchema =
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
return new JavaDataStreamQueryOperation<>(
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toTableSchema());
}
private void validateTimeCharacteristic(boolean isRowtimeDefined) {
if (isRowtimeDefined
&& executionEnvironment.getStreamTimeCharacteristic()
!= TimeCharacteristic.EventTime) {
&& executionEnvironment.getStreamTimeCharacteristic() != TimeCharacteristic.EventTime) {
throw new ValidationException(
String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
executionEnvironment.getStreamTimeCharacteristic()));
String.format(
"A rowtime attribute requires an EventTime time characteristic in stream environment. But is: %s",
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;
import org.apache.flink.table.operations.command.ResetOperation;
import org.apache.flink.table.operations.command.SetOperation;
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.typeutils.FieldInfoUtils;
......@@ -74,6 +75,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.dlink.utils.FlinkStreamProgramWithoutPhysical;
import com.dlink.utils.LineageContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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 {
private final StreamExecutionEnvironment executionEnvironment;
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl(
CatalogManager catalogManager,
......@@ -108,6 +112,7 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
isStreamingMode,
userClassLoader);
this.executionEnvironment = executionEnvironment;
this.flinkChainedProgram = FlinkStreamProgramWithoutPhysical.buildProgram(tableConfig.getConfiguration());
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
......@@ -360,7 +365,8 @@ public class CustomTableEnvironmentImpl extends TableEnvironmentImpl implements
@Override
public List<LineageRel> getLineage(String statement) {
return null;
LineageContext lineageContext = new LineageContext(flinkChainedProgram, this);
return lineageContext.getLineage(statement);
}
@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 @@
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner_${scala.binary.version}</artifactId>
<artifactId>flink-table-planner_2.12</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
......@@ -54,7 +54,7 @@
</dependency>
<dependency>
<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>
</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