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

[Feature-1293][client] Add Column Lineage in Flink 1.15,1.16 (#1294)

parent 280911f4
......@@ -33,7 +33,6 @@ import com.dlink.model.JobInstance;
import com.dlink.model.JobInstanceCount;
import com.dlink.model.JobInstanceStatus;
import com.dlink.model.JobStatus;
import com.dlink.model.SystemConfiguration;
import com.dlink.service.ClusterConfigurationService;
import com.dlink.service.ClusterService;
import com.dlink.service.HistoryService;
......@@ -196,11 +195,7 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper,
@Override
public LineageResult getLineage(Integer id) {
History history = getJobInfoDetail(id).getHistory();
if (SystemConfiguration.getInstances().isUseLogicalPlan()) {
return LineageBuilder.getColumnLineageByLogicalPlan(history.getStatement());
} else {
return LineageBuilder.getLineage(history.getStatement());
}
return LineageBuilder.getColumnLineageByLogicalPlan(history.getStatement());
}
@Override
......
......@@ -44,7 +44,6 @@ import com.dlink.model.DataBase;
import com.dlink.model.FlinkColumn;
import com.dlink.model.Savepoints;
import com.dlink.model.Schema;
import com.dlink.model.SystemConfiguration;
import com.dlink.model.Table;
import com.dlink.model.Task;
import com.dlink.process.context.ProcessContextHolder;
......@@ -395,11 +394,7 @@ public class StudioServiceImpl implements StudioService {
}
} else {
addFlinkSQLEnv(studioCADTO);
if (SystemConfiguration.getInstances().isUseLogicalPlan()) {
return LineageBuilder.getColumnLineageByLogicalPlan(studioCADTO.getStatement());
} else {
return LineageBuilder.getLineage(studioCADTO.getStatement());
}
return LineageBuilder.getColumnLineageByLogicalPlan(studioCADTO.getStatement());
}
}
......
......@@ -36,7 +36,7 @@ import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
* FlinkStreamProgramWithoutPhysical
*
* @author wenmo
* @since 2022/8/20 23:33
* @since 2022/11/21
*/
public class FlinkStreamProgramWithoutPhysical {
......@@ -49,7 +49,6 @@ public class FlinkStreamProgramWithoutPhysical {
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();
......
......@@ -64,8 +64,8 @@ import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
* @author wenmo
* @since 2022/11/21
*/
public class LineageContext {
......
......@@ -36,7 +36,7 @@ import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
* FlinkStreamProgramWithoutPhysical
*
* @author wenmo
* @since 2022/8/20 23:33
* @since 2022/11/21
*/
public class FlinkStreamProgramWithoutPhysical {
......@@ -49,7 +49,6 @@ public class FlinkStreamProgramWithoutPhysical {
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();
......
......@@ -64,8 +64,8 @@ import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
* @author wenmo
* @since 2022/11/21
*/
public class LineageContext {
......
......@@ -19,6 +19,8 @@
package com.dlink.utils;
import com.dlink.model.LineageRel;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Snapshot;
......@@ -35,7 +37,6 @@ 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;
......@@ -47,8 +48,6 @@ 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;
......@@ -57,8 +56,8 @@ import javassist.Modifier;
/**
* LineageContext
*
* @author baisong
* @since 2022/8/6 11:06
* @author wenmo
* @since 2022/11/21
*/
public class LineageContext {
......@@ -82,9 +81,8 @@ public class LineageContext {
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
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);
......@@ -116,7 +114,7 @@ public class LineageContext {
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! only accepts a single SQL statement.");
"Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof CatalogSinkModifyOperation) {
......@@ -125,8 +123,8 @@ public class LineageContext {
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
} else {
throw new TableException("Only insert is supported now.");
}
......@@ -198,19 +196,19 @@ public class LineageContext {
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));
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();
.getResolvedSchema()
.getColumnNames();
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
......
......@@ -81,9 +81,8 @@ public class LineageContext {
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
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);
......@@ -115,7 +114,7 @@ public class LineageContext {
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! only accepts a single SQL statement.");
"Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof CatalogSinkModifyOperation) {
......@@ -124,8 +123,8 @@ public class LineageContext {
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
sinkOperation.getTableIdentifier().asSummaryString(),
relNode);
} else {
throw new TableException("Only insert is supported now.");
}
......@@ -136,6 +135,7 @@ public class LineageContext {
*/
private RelNode optimize(RelNode relNode) {
return flinkChainedProgram.optimize(relNode, new StreamOptimizeContext() {
@Override
public boolean isBatchMode() {
return false;
......@@ -164,7 +164,6 @@ public class LineageContext {
@Override
public <C> C unwrap(Class<C> clazz) {
return getPlanner().getFlinkContext().unwrap(clazz);
}
@Override
......@@ -201,19 +200,19 @@ public class LineageContext {
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));
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();
.getResolvedSchema()
.getColumnNames();
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
......
/*
*
* 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 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.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.Operation;
import org.apache.flink.table.operations.SinkModifyOperation;
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 javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
/**
* LineageContext
*
* @author wenmo
* @since 2022/11/22
*/
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 SinkModifyOperation) {
SinkModifyOperation sinkOperation = (SinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getContextResolvedTable().getIdentifier().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 boolean isBatchMode() {
return false;
}
@Override
public TableConfig getTableConfig() {
return tableEnv.getConfig();
}
@Override
public FunctionCatalog getFunctionCatalog() {
return getPlanner().getFlinkContext().getFunctionCatalog();
}
@Override
public CatalogManager getCatalogManager() {
return tableEnv.getCatalogManager();
}
@Override
public ModuleManager getModuleManager() {
return getPlanner().getFlinkContext().getModuleManager();
}
@Override
public SqlExprToRexConverterFactory getSqlExprToRexConverterFactory() {
return null;
}
@Override
public <C> C unwrap(Class<C> clazz) {
return getPlanner().getFlinkContext().unwrap(clazz);
}
@Override
public FlinkRelBuilder getFlinkRelBuilder() {
return getPlanner().getRelBuilder();
}
@Override
public boolean isUpdateBeforeRequired() {
return false;
}
@Override
public MiniBatchInterval getMiniBatchInterval() {
return MiniBatchInterval.NONE;
}
@Override
public boolean needFinalTimeIndicatorConversion() {
return true;
}
@Override
public ClassLoader getClassLoader() {
return getPlanner().getFlinkContext().getClassLoader();
}
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;
}
}
......@@ -22,6 +22,8 @@ package com.dlink.executor;
import com.dlink.assertion.Asserts;
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;
......@@ -57,6 +59,7 @@ import org.apache.flink.table.operations.Operation;
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.plan.optimize.program.FlinkChainedProgram;
import org.apache.flink.table.resource.ResourceManager;
import org.apache.flink.table.typeutils.FieldInfoUtils;
import org.apache.flink.util.FlinkUserCodeClassLoaders;
......@@ -83,6 +86,8 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
implements
CustomTableEnvironment {
private final FlinkChainedProgram flinkChainedProgram;
public CustomTableEnvironmentImpl(
CatalogManager catalogManager,
ModuleManager moduleManager,
......@@ -103,6 +108,8 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
planner,
isStreamingMode,
executionEnvironment);
this.flinkChainedProgram =
FlinkStreamProgramWithoutPhysical.buildProgram((Configuration) executionEnvironment.getConfiguration());
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
......@@ -331,7 +338,8 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
@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 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.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.Operation;
import org.apache.flink.table.operations.SinkModifyOperation;
import org.apache.flink.table.planner.calcite.FlinkRelBuilder;
import org.apache.flink.table.planner.calcite.RexFactory;
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 javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
/**
* LineageContext
*
* @author wenmo
* @since 2022/11/22
*/
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 SinkModifyOperation) {
SinkModifyOperation sinkOperation = (SinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getContextResolvedTable().getIdentifier().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 boolean isBatchMode() {
return false;
}
@Override
public TableConfig getTableConfig() {
return tableEnv.getConfig();
}
@Override
public FunctionCatalog getFunctionCatalog() {
return getPlanner().getFlinkContext().getFunctionCatalog();
}
@Override
public CatalogManager getCatalogManager() {
return tableEnv.getCatalogManager();
}
@Override
public ModuleManager getModuleManager() {
return getPlanner().getFlinkContext().getModuleManager();
}
@Override
public RexFactory getRexFactory() {
return getPlanner().getFlinkContext().getRexFactory();
}
@Override
public FlinkRelBuilder getFlinkRelBuilder() {
return getPlanner().createRelBuilder();
}
@Override
public boolean isUpdateBeforeRequired() {
return false;
}
@Override
public MiniBatchInterval getMiniBatchInterval() {
return MiniBatchInterval.NONE;
}
@Override
public boolean needFinalTimeIndicatorConversion() {
return true;
}
@Override
public ClassLoader getClassLoader() {
return getPlanner().getFlinkContext().getClassLoader();
}
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;
}
}
......@@ -42,66 +42,53 @@ public class SystemConfiguration {
}
private static final List<Configuration> CONFIGURATION_LIST = new ArrayList<Configuration>() {
{
add(systemConfiguration.sqlSubmitJarPath);
add(systemConfiguration.sqlSubmitJarParas);
add(systemConfiguration.sqlSubmitJarMainAppClass);
add(systemConfiguration.useRestAPI);
add(systemConfiguration.useLogicalPlan);
add(systemConfiguration.sqlSeparator);
add(systemConfiguration.jobIdWait);
}
};
private Configuration sqlSubmitJarPath = new Configuration(
"sqlSubmitJarPath",
"FlinkSQL提交Jar路径",
ValueType.STRING,
"hdfs:///dlink/jar/dlink-app.jar",
"用于指定Applcation模式提交FlinkSQL的Jar的路径"
);
"sqlSubmitJarPath",
"FlinkSQL提交Jar路径",
ValueType.STRING,
"hdfs:///dlink/jar/dlink-app.jar",
"用于指定Applcation模式提交FlinkSQL的Jar的路径");
private Configuration sqlSubmitJarParas = new Configuration(
"sqlSubmitJarParas",
"FlinkSQL提交Jar参数",
ValueType.STRING,
"",
"用于指定Applcation模式提交FlinkSQL的Jar的参数"
);
"sqlSubmitJarParas",
"FlinkSQL提交Jar参数",
ValueType.STRING,
"",
"用于指定Applcation模式提交FlinkSQL的Jar的参数");
private Configuration sqlSubmitJarMainAppClass = new Configuration(
"sqlSubmitJarMainAppClass",
"FlinkSQL提交Jar主类",
ValueType.STRING,
"com.dlink.app.MainApp",
"用于指定Applcation模式提交FlinkSQL的Jar的主类"
);
"sqlSubmitJarMainAppClass",
"FlinkSQL提交Jar主类",
ValueType.STRING,
"com.dlink.app.MainApp",
"用于指定Applcation模式提交FlinkSQL的Jar的主类");
private Configuration useRestAPI = new Configuration(
"useRestAPI",
"使用 RestAPI",
ValueType.BOOLEAN,
true,
"在运维 Flink 任务时是否使用 RestAPI"
);
"useRestAPI",
"使用 RestAPI",
ValueType.BOOLEAN,
true,
"在运维 Flink 任务时是否使用 RestAPI");
private Configuration sqlSeparator = new Configuration(
"sqlSeparator",
"FlinkSQL语句分割符",
ValueType.STRING,
";\n",
"Flink SQL 的语句分割符"
);
private Configuration useLogicalPlan = new Configuration(
"useLogicalPlan",
"使用逻辑计划计算血缘",
ValueType.BOOLEAN,
false,
"在计算 Flink 任务的字段血缘分析时是否基于逻辑计划进行,只支持 1.14 版本"
);
"sqlSeparator",
"FlinkSQL语句分割符",
ValueType.STRING,
";\n",
"Flink SQL 的语句分割符");
private Configuration jobIdWait = new Configuration(
"jobIdWait",
"获取 Job ID 的最大等待时间(秒)",
ValueType.INT,
30,
"提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)"
);
"jobIdWait",
"获取 Job ID 的最大等待时间(秒)",
ValueType.INT,
30,
"提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)");
public void setConfiguration(JsonNode jsonNode) {
for (Configuration item : CONFIGURATION_LIST) {
......@@ -172,16 +159,8 @@ public class SystemConfiguration {
this.sqlSeparator.setValue(sqlSeparator);
}
public boolean isUseLogicalPlan() {
return (boolean) useLogicalPlan.getValue();
}
public void setUseLogicalPlan(boolean useLogicalPlan) {
this.useLogicalPlan.setValue(useLogicalPlan);
}
public int getJobIdWait() {
return (int )jobIdWait.getValue();
return (int) jobIdWait.getValue();
}
public void setJobIdWait(Configuration jobIdWait) {
......@@ -193,6 +172,7 @@ public class SystemConfiguration {
}
public class Configuration {
private String name;
private String label;
private ValueType type;
......
......@@ -40,10 +40,12 @@ import java.util.Set;
*/
public class LineageBuilder {
@Deprecated
public static LineageResult getLineage(String statement) {
return getLineage(statement, true);
}
@Deprecated
public static LineageResult getLineage(String statement, boolean statementSet) {
FlinkSqlPlus plus = FlinkSqlPlus.build(statementSet);
List<ColumnCAResult> columnCAResults = plus.explainSqlColumnCA(statement);
......@@ -57,27 +59,27 @@ public class LineageBuilder {
Set<String> keySet = new HashSet<>();
for (NodeRel nodeRel : item.getColumnCASRelChain()) {
if (item.getColumnCASMaps().containsKey(nodeRel.getPreId())
&& item.getColumnCASMaps().containsKey(nodeRel.getSufId())
&& !item.getColumnCASMaps().get(nodeRel.getPreId()).getTableId().equals(item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId())) {
&& item.getColumnCASMaps().containsKey(nodeRel.getSufId())
&& !item.getColumnCASMaps().get(nodeRel.getPreId()).getTableId()
.equals(item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId())) {
String key = item.getColumnCASMaps().get(nodeRel.getPreId()).getTableId().toString() + "@"
+ item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId().toString() + "@"
+ item.getColumnCASMaps().get(nodeRel.getPreId()).getName() + "@"
+ item.getColumnCASMaps().get(nodeRel.getSufId()).getName();
//去重
+ item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId().toString() + "@"
+ item.getColumnCASMaps().get(nodeRel.getPreId()).getName() + "@"
+ item.getColumnCASMaps().get(nodeRel.getSufId()).getName();
// 去重
if (!keySet.contains(key)) {
index++;
relations.add(LineageRelation.build(index + "",
item.getColumnCASMaps().get(nodeRel.getPreId()).getTableId().toString(),
item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId().toString(),
item.getColumnCASMaps().get(nodeRel.getPreId()).getName(),
item.getColumnCASMaps().get(nodeRel.getSufId()).getName()
));
item.getColumnCASMaps().get(nodeRel.getPreId()).getTableId().toString(),
item.getColumnCASMaps().get(nodeRel.getSufId()).getTableId().toString(),
item.getColumnCASMaps().get(nodeRel.getPreId()).getName(),
item.getColumnCASMaps().get(nodeRel.getSufId()).getName()));
keySet.add(key);
}
}
}
}
//获取重复表集合
// 获取重复表集合
List<List<LineageTable>> repeatTablesList = new ArrayList<>();
for (int i = 0; i < tables.size() - 1; i++) {
List<LineageTable> repeatTables = new ArrayList<>();
......@@ -91,7 +93,7 @@ public class LineageBuilder {
repeatTablesList.add(repeatTables);
}
}
//重复表合并
// 重复表合并
Map<String, String> correctTableIdMap = new HashMap<>();
for (List<LineageTable> tableList : repeatTablesList) {
LineageTable newTable = new LineageTable();
......@@ -114,7 +116,7 @@ public class LineageBuilder {
}
tables.add(newTable);
}
//关系中id重新指向
// 关系中id重新指向
for (LineageRelation relation : relations) {
if (correctTableIdMap.containsKey(relation.getSrcTableId())) {
relation.setSrcTableId(correctTableIdMap.get(relation.getSrcTableId()));
......@@ -139,7 +141,8 @@ public class LineageBuilder {
String targetTableId = null;
if (tableMap.containsKey(sourceTablePath)) {
LineageTable lineageTable = tableMap.get(sourceTablePath);
LineageColumn lineageColumn = LineageColumn.build(lineageRel.getSourceColumn(), lineageRel.getSourceColumn());
LineageColumn lineageColumn =
LineageColumn.build(lineageRel.getSourceColumn(), lineageRel.getSourceColumn());
if (!lineageTable.getColumns().contains(lineageColumn)) {
lineageTable.getColumns().add(lineageColumn);
}
......@@ -147,14 +150,16 @@ public class LineageBuilder {
} else {
tableIndex++;
LineageTable lineageTable = LineageTable.build(tableIndex + "", sourceTablePath);
lineageTable.getColumns().add(LineageColumn.build(lineageRel.getSourceColumn(), lineageRel.getSourceColumn()));
lineageTable.getColumns()
.add(LineageColumn.build(lineageRel.getSourceColumn(), lineageRel.getSourceColumn()));
tableMap.put(sourceTablePath, lineageTable);
sourceTableId = lineageTable.getId();
}
String targetTablePath = lineageRel.getTargetTablePath();
if (tableMap.containsKey(targetTablePath)) {
LineageTable lineageTable = tableMap.get(targetTablePath);
LineageColumn lineageColumn = LineageColumn.build(lineageRel.getTargetColumn(), lineageRel.getTargetColumn());
LineageColumn lineageColumn =
LineageColumn.build(lineageRel.getTargetColumn(), lineageRel.getTargetColumn());
if (!lineageTable.getColumns().contains(lineageColumn)) {
lineageTable.getColumns().add(lineageColumn);
}
......@@ -162,11 +167,13 @@ public class LineageBuilder {
} else {
tableIndex++;
LineageTable lineageTable = LineageTable.build(tableIndex + "", targetTablePath);
lineageTable.getColumns().add(LineageColumn.build(lineageRel.getTargetColumn(), lineageRel.getTargetColumn()));
lineageTable.getColumns()
.add(LineageColumn.build(lineageRel.getTargetColumn(), lineageRel.getTargetColumn()));
tableMap.put(targetTablePath, lineageTable);
targetTableId = lineageTable.getId();
}
LineageRelation lineageRelation = LineageRelation.build(sourceTableId, targetTableId, lineageRel.getSourceColumn(), lineageRel.getTargetColumn());
LineageRelation lineageRelation = LineageRelation.build(sourceTableId, targetTableId,
lineageRel.getSourceColumn(), lineageRel.getTargetColumn());
if (!relations.contains(lineageRelation)) {
relIndex++;
lineageRelation.setId(relIndex + "");
......
......@@ -104,6 +104,7 @@ public class FlinkSqlPlus {
return explainer.generateTableCA(statement);
}
@Deprecated
public List<ColumnCAResult> explainSqlColumnCA(String statement) {
return explainer.explainSqlColumnCA(statement);
}
......
......@@ -49,7 +49,7 @@ public class LineageTest {
+ " 'connector' = 'print'\n"
+ ");\n"
+ "insert into TT select a||c A ,b||c B from ST";
LineageResult result = LineageBuilder.getLineage(sql);
LineageResult result = LineageBuilder.getColumnLineageByLogicalPlan(sql);
System.out.println("end");
}
}
......@@ -15,16 +15,14 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>dlink-flink</artifactId>
<groupId>com.dlink</groupId>
<artifactId>dlink-flink</artifactId>
<version>0.6.8-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dlink-flink-1.15</artifactId>
......@@ -47,17 +45,14 @@
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner-loader</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<artifactId>flink-table-api-java-bridge</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-api-scala-bridge_2.12</artifactId>
<version>${flink.version}</version>
</dependency>
<!-- You need to add this dependency before completing the dlink-connector-jdbc-1.15 module to prevent running exceptions when using version flink-1.15,
and you need to put the flink-connector-jdbc-1.15.*.jar in the /dlink/lib/ directory to replace dlink-connector-jdbc-1.13-0.6.6-SNAPSHOT.jar during deployment-->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-runtime</artifactId>
......@@ -65,15 +60,17 @@
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-jdbc</artifactId>
<artifactId>flink-table-planner_2.12</artifactId>
<version>${flink.version}</version>
</dependency>
<!-- end-->
<!-- You need to add this dependency before completing the dlink-connector-jdbc-1.15 module to prevent running exceptions when using version flink-1.15,
and you need to put the flink-connector-jdbc-1.15.*.jar in the /dlink/lib/ directory to replace dlink-connector-jdbc-1.13-0.6.6-SNAPSHOT.jar during deployment-->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-api-java-bridge</artifactId>
<artifactId>flink-connector-jdbc</artifactId>
<version>${flink.version}</version>
</dependency>
<!-- end-->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
......@@ -92,13 +89,13 @@
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
......@@ -168,4 +165,4 @@
</dependency>
</dependencies>
</project>
\ No newline at end of file
</project>
......@@ -111,11 +111,9 @@ export default {
'pages.settings.FlinkSQLJarMainClass': 'The Main Class Of The Jar That Submitted FlinkSQL',
'pages.settings.FlinkRestAPI': 'Using Rest API',
'pages.settings.FlinkURLSplit': 'FlinkSQL Statement Separator',
'pages.settings.FlinkSQLLogic': 'Calculate Consanguinity Using A Logical Plan',
'pages.settings.FlinkJobID': 'Maximum Waiting Time For Getting A Job ID (seconds)',
'pages.settings.FlinkNoSetting': 'Not Setting',
'pages.settings.FlinkNoUseSetting': 'After The Flink Task Is Enabled, Operations Such As Savepoint And Stop Are Performed Through The RestAPI Of JobManager',
'pages.settings.FlinkLogic': 'Whether The Calculation Of Field Consanguinity Analysis For Flink Tasks Is Based On A Logical Plan Is Supported Only In Version 1.14',
'pages.user.UserManger': 'User Management',
'pages.user.UserName': 'User Name',
......
......@@ -112,11 +112,9 @@ export default {
'pages.settings.FlinkSQLJarMainClass': '提交 FlinkSQL 的 Jar 的主类',
'pages.settings.FlinkRestAPI': '使用 Rest API',
'pages.settings.FlinkURLSplit': 'FlinkSQL 语句分隔符',
'pages.settings.FlinkSQLLogic': '使用逻辑计划计算血缘',
'pages.settings.FlinkJobID': '获取 Job ID 的最大等待时间(秒)',
'pages.settings.FlinkNoSetting': '未设置',
'pages.settings.FlinkNoUseSetting': '启用后,Flink 任务的 savepoint、停止等操作将通过 JobManager 的 RestAPI 进行',
'pages.settings.FlinkLogic': '在计算 Flink 任务的字段血缘分析时是否基于逻辑计划进行,只支持 1.14 版本',
'pages.user.UserManger': '用户管理',
'pages.user.UserName': '用户名',
......
......@@ -29,13 +29,11 @@ type FlinkConfigProps = {
sqlSubmitJarParas: SettingsStateType['sqlSubmitJarParas'];
sqlSubmitJarMainAppClass: SettingsStateType['sqlSubmitJarMainAppClass'];
useRestAPI: SettingsStateType['useRestAPI'];
useLogicalPlan: SettingsStateType['useLogicalPlan'];
sqlSeparator: SettingsStateType['sqlSeparator'];
jobIdWait: SettingsStateType['jobIdWait'];
dispatch: any;
};
const FlinkConfigView: React.FC<FlinkConfigProps> = (props) => {
const {
......@@ -43,7 +41,6 @@ const FlinkConfigView: React.FC<FlinkConfigProps> = (props) => {
sqlSubmitJarParas,
sqlSubmitJarMainAppClass,
useRestAPI,
useLogicalPlan,
sqlSeparator,
jobIdWait,
dispatch
......@@ -124,17 +121,6 @@ const FlinkConfigView: React.FC<FlinkConfigProps> = (props) => {
[<a onClick={({}) => handleSaveClick('sqlSeparator')}>{l('button.save')}</a>,
<a onClick={({}) => handleCancelClick()}>{l('button.cancel')}</a>],
},
{
title: l('pages.settings.FlinkSQLLogic'),
description: l('pages.settings.FlinkLogic'),
actions: [
<Form.Item
name="useLogicalPlan" valuePropName="checked"
>
<Switch checkedChildren={l('button.enable')} unCheckedChildren={l('button.disable')}
checked={useLogicalPlan}
/></Form.Item>],
},
{
title: l('pages.settings.FlinkJobID'),
description: (
......@@ -210,7 +196,6 @@ export default connect(({Settings}: { Settings: SettingsStateType }) => ({
sqlSubmitJarParas: Settings.sqlSubmitJarParas,
sqlSubmitJarMainAppClass: Settings.sqlSubmitJarMainAppClass,
useRestAPI: Settings.useRestAPI,
useLogicalPlan: Settings.useLogicalPlan,
sqlSeparator: Settings.sqlSeparator,
jobIdWait: Settings.jobIdWait,
}))(FlinkConfigView);
......@@ -24,7 +24,6 @@ export type SettingsStateType = {
sqlSubmitJarParas: string,
sqlSubmitJarMainAppClass: string,
useRestAPI: boolean,
useLogicalPlan: boolean,
sqlSeparator: string,
jobIdWait: number,
};
......@@ -45,6 +44,8 @@ const SettingsModel: ModelType = {
sqlSubmitJarParas: '',
sqlSubmitJarMainAppClass: '',
useRestAPI: true,
sqlSeparator: ',\n',
jobIdWait: 30,
},
effects: {},
......
......@@ -643,7 +643,7 @@
</eclipse>
<removeUnusedImports />
<importOrder>
<order>\#,com.dlink,org.apache,java,javax,org,com,</order>
<order>\#,com.dlink,org.apache,java,javassist,javax,org,com,</order>
</importOrder>
<licenseHeader>
<file>style/license_header</file>
......
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