morningman closed pull request #456: Add routine load statement
URL: https://github.com/apache/incubator-doris/pull/456
This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:
As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):
diff --git a/fe/src/main/cup/sql_parser.cup b/fe/src/main/cup/sql_parser.cup
index 7c9ac2df..ac12c354 100644
--- a/fe/src/main/cup/sql_parser.cup
+++ b/fe/src/main/cup/sql_parser.cup
@@ -205,7 +205,9 @@ terminal String KW_ADD, KW_ADMIN, KW_AFTER, KW_AGGREGATE,
KW_ALL, KW_ALTER, KW_A
KW_INNER, KW_INSERT, KW_INT, KW_INTERVAL, KW_INTO, KW_IS, KW_ISNULL,
KW_ISOLATION,
KW_JOIN,
KW_KEY, KW_KILL,
- KW_LABEL, KW_LARGEINT, KW_LAST, KW_LEFT, KW_LESS, KW_LEVEL, KW_LIKE,
KW_LIMIT, KW_LINK, KW_LOAD, KW_LOCAL, KW_LOCATION,
+ KW_LABEL, KW_LARGEINT, KW_LAST, KW_LEFT, KW_LESS, KW_LEVEL, KW_LIKE,
KW_LIMIT, KW_LINK, KW_LOAD,
+ KW_ROUTINE, KW_PAUSE, KW_RESUME, KW_STOP,
+ KW_LOCAL, KW_LOCATION,
KW_MAX, KW_MAX_VALUE, KW_MERGE, KW_MIN, KW_MIGRATE, KW_MIGRATIONS,
KW_MODIFY,
KW_NAME, KW_NAMES, KW_NEGATIVE, KW_NO, KW_NOT, KW_NULL, KW_NULLS,
KW_OBSERVER, KW_OFFSET, KW_ON, KW_ONLY, KW_OPEN, KW_OR, KW_ORDER,
KW_OUTER, KW_OVER,
@@ -240,7 +242,9 @@ terminal String UNMATCHED_STRING_LITERAL;
terminal String COMMENTED_PLAN_HINTS;
// Statement that the result of this parser.
-nonterminal StatementBase query, stmt, show_stmt, show_param, help_stmt,
load_stmt, describe_stmt, alter_stmt,
+nonterminal StatementBase query, stmt, show_stmt, show_param, help_stmt,
load_stmt,
+ create_routine_load_stmt, pause_routine_load_stmt,
resume_routine_load_stmt, stop_routine_load_stmt, show_routine_load_stmt,
+ describe_stmt, alter_stmt,
use_stmt, kill_stmt, drop_stmt, recover_stmt, grant_stmt, revoke_stmt,
create_stmt, set_stmt, sync_stmt, cancel_stmt, cancel_param, delete_stmt,
link_stmt, migrate_stmt, enter_stmt, unsupported_stmt, export_stmt,
admin_stmt, truncate_stmt, import_columns_stmt, import_where_stmt;
@@ -294,6 +298,7 @@ nonterminal ClusterName des_cluster_name;
nonterminal TableName table_name;
nonterminal FunctionName function_name;
nonterminal Expr where_clause;
+nonterminal Expr where_clause_without_null;
nonterminal Predicate predicate, between_predicate, comparison_predicate,
compound_predicate, in_predicate, like_predicate, exists_predicate;
nonterminal ArrayList<Expr> group_by_clause, opt_partition_by_clause;
@@ -372,14 +377,19 @@ nonterminal LabelName job_label;
nonterminal String opt_system;
nonterminal String opt_cluster;
nonterminal BrokerDesc opt_broker;
-nonterminal List<String> opt_col_list, opt_dup_keys;
-nonterminal List<String> opt_partitions;
+nonterminal List<String> opt_col_list, col_list, opt_dup_keys;
+nonterminal List<String> opt_partitions, partitions;
nonterminal List<Expr> opt_col_mapping_list;
-nonterminal ColumnSeparator opt_field_term;
+nonterminal ColumnSeparator opt_field_term, column_separator;
nonterminal String opt_user_role;
nonterminal TablePattern tbl_pattern;
nonterminal String ident_or_star;
+// Routine load
+nonterminal LoadColumnsInfo load_columns_info;
+nonterminal ParseNode load_property;
+nonterminal List<ParseNode> opt_load_property_list;
+
// Boolean
nonterminal Boolean opt_negative, opt_super_user, opt_is_allow_null,
opt_is_key, opt_read_only, opt_aggregate;
nonterminal String opt_from_rollup, opt_to_rollup;
@@ -510,6 +520,16 @@ stmt ::=
{: RESULT = stmt; :}
| load_stmt : stmt
{: RESULT = stmt; :}
+ | create_routine_load_stmt : stmt
+ {: RESULT = stmt; :}
+ | pause_routine_load_stmt : stmt
+ {: RESULT = stmt; :}
+ | resume_routine_load_stmt : stmt
+ {: RESULT = stmt; :}
+ | stop_routine_load_stmt : stmt
+ {: RESULT = stmt; :}
+ | show_routine_load_stmt : stmt
+ {: RESULT = stmt; :}
| cancel_stmt : stmt
{: RESULT = stmt; :}
| delete_stmt : stmt
@@ -585,7 +605,7 @@ alter_stmt ::=
{:
RESULT = new AlterSystemStmt(clause);
:}
- | KW_ALTER KW_CLUSTER ident:name opt_properties:properties
+ | KW_ALTER KW_CLUSTER ident:name opt_properties:properties
{:
RESULT = new AlterClusterStmt(name, properties);
:}
@@ -1029,6 +1049,13 @@ opt_partitions ::=
:}
;
+partitions ::=
+ KW_PARTITION LPAREN ident_list:partitionNames RPAREN
+ {:
+ RESULT = partitionNames;
+ :}
+ ;
+
opt_negative ::=
{:
RESULT = false;
@@ -1050,6 +1077,13 @@ opt_field_term ::=
:}
;
+column_separator ::=
+ KW_COLUMNS KW_TERMINATED KW_BY STRING_LITERAL:sep
+ {:
+ RESULT = new ColumnSeparator(sep);
+ :}
+ ;
+
opt_col_list ::=
{:
RESULT = null;
@@ -1060,6 +1094,13 @@ opt_col_list ::=
:}
;
+col_list ::=
+ KW_COLUMNS LPAREN ident_list:colList RPAREN
+ {:
+ RESULT = colList;
+ :}
+ ;
+
opt_col_mapping_list ::=
/* Empty */
{:
@@ -1105,6 +1146,87 @@ opt_cluster ::=
:}
;
+// Routine load statement
+create_routine_load_stmt ::=
+ KW_CREATE KW_ROUTINE KW_LOAD ident:jobName KW_ON table_name:dbTableName
+ opt_load_property_list:loadPropertyList
+ opt_properties:properties
+ KW_FROM ident:type LPAREN key_value_map:customProperties RPAREN
+ {:
+ RESULT = new CreateRoutineLoadStmt(jobName, dbTableName,
loadPropertyList, properties, type, customProperties);
+ :}
+ ;
+
+opt_load_property_list ::=
+ {:
+ RESULT = null;
+ :}
+ | load_property:loadProperty
+ {:
+ RESULT = Lists.newArrayList(loadProperty);
+ :}
+ | opt_load_property_list:list COMMA load_property:loadProperty
+ {:
+ list.add(loadProperty);
+ RESULT = list;
+ :}
+ ;
+
+load_property ::=
+ column_separator:colSep
+ {:
+ RESULT = colSep;
+ :}
+ | load_columns_info:columnsInfo
+ {:
+ RESULT = columnsInfo;
+ :}
+ | where_clause_without_null:wherePredicate
+ {:
+ RESULT = wherePredicate;
+ :}
+ | partitions:partitionNames
+ {:
+ RESULT = new PartitionNames(partitionNames);
+ :}
+ ;
+
+load_columns_info ::=
+ col_list:colList
+ opt_col_mapping_list:colMappingList
+ {:
+ RESULT = new LoadColumnsInfo(colList, colMappingList);
+ :}
+ ;
+
+pause_routine_load_stmt ::=
+ KW_PAUSE KW_ROUTINE KW_LOAD ident:name
+ {:
+ RESULT = new PauseRoutineLoadStmt(name);
+ :}
+ ;
+
+resume_routine_load_stmt ::=
+ KW_RESUME KW_ROUTINE KW_LOAD ident:name
+ {:
+ RESULT = new ResumeRoutineLoadStmt(name);
+ :}
+ ;
+
+stop_routine_load_stmt ::=
+ KW_STOP KW_ROUTINE KW_LOAD ident:name
+ {:
+ RESULT = new StopRoutineLoadStmt(name);
+ :}
+ ;
+
+show_routine_load_stmt ::=
+ KW_SHOW KW_ROUTINE KW_LOAD ident:name
+ {:
+ RESULT = new ShowRoutineLoadStmt(name);
+ :}
+ ;
+
// Grant statement
grant_stmt ::=
KW_GRANT privilege_list:privs KW_ON tbl_pattern:tblPattern KW_TO
user_identity:userId
@@ -2873,6 +2995,11 @@ where_clause ::=
{: RESULT = null; :}
;
+where_clause_without_null ::=
+ KW_WHERE expr:e
+ {: RESULT = e; :}
+ ;
+
group_by_clause ::=
KW_GROUP KW_BY expr_list:l
{: RESULT = l; :}
diff --git a/fe/src/main/java/org/apache/doris/analysis/CastExpr.java
b/fe/src/main/java/org/apache/doris/analysis/CastExpr.java
index 3e3cd6cd..38fef935 100644
--- a/fe/src/main/java/org/apache/doris/analysis/CastExpr.java
+++ b/fe/src/main/java/org/apache/doris/analysis/CastExpr.java
@@ -164,7 +164,7 @@ public boolean isImplicit() {
return isImplicit;
}
- private void analyze() throws AnalysisException {
+ public void analyze() throws AnalysisException {
// cast was asked for in the query, check for validity of cast
Type childType = getChild(0).getType();
diff --git a/fe/src/main/java/org/apache/doris/analysis/ColumnSeparator.java
b/fe/src/main/java/org/apache/doris/analysis/ColumnSeparator.java
index 633ef794..3d2b2715 100644
--- a/fe/src/main/java/org/apache/doris/analysis/ColumnSeparator.java
+++ b/fe/src/main/java/org/apache/doris/analysis/ColumnSeparator.java
@@ -23,7 +23,7 @@
import java.io.StringWriter;
-public class ColumnSeparator {
+public class ColumnSeparator implements ParseNode {
private static final String HEX_STRING = "0123456789ABCDEF";
private final String oriSeparator;
@@ -55,6 +55,11 @@ private static byte charToByte(char c) {
}
public void analyze() throws AnalysisException {
+ analyze(null);
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException {
this.separator = convertSeparator(oriSeparator);
}
diff --git
a/fe/src/main/java/org/apache/doris/analysis/CreateRoutineLoadStmt.java
b/fe/src/main/java/org/apache/doris/analysis/CreateRoutineLoadStmt.java
new file mode 100644
index 00000000..fa115f00
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/CreateRoutineLoadStmt.java
@@ -0,0 +1,337 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import org.apache.doris.load.routineload.LoadDataSourceType;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.FeNameFormat;
+import org.apache.doris.common.UserException;
+import org.apache.doris.load.RoutineLoadDesc;
+import org.apache.doris.qe.ConnectContext;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.regex.Pattern;
+
+/*
+ Create routine Load statement, continually load data from a streaming app
+
+ syntax:
+ CREATE ROUTINE LOAD name ON database.table
+ [load properties]
+ [PROPERTIES
+ (
+ desired_concurrent_number = xxx,
+ max_error_number = xxx,
+ k1 = v1,
+ ...
+ kn = vn
+ )]
+ FROM type of routine load
+ [(
+ k1 = v1,
+ ...
+ kn = vn
+ )]
+
+ load properties:
+ load property [[,] load property] ...
+
+ load property:
+ column separator | columns | partitions | where
+
+ column separator:
+ COLUMNS TERMINATED BY xxx
+ columns:
+ COLUMNS (c1, c2, c3) set (c1, c2, c3=c1+c2)
+ partitions:
+ PARTITIONS (p1, p2, p3)
+ where:
+ WHERE xxx
+
+ type of routine load:
+ KAFKA
+*/
+public class CreateRoutineLoadStmt extends DdlStmt {
+ // routine load properties
+ public static final String DESIRED_CONCURRENT_NUMBER_PROPERTY =
"desired_concurrent_number";
+ // max error number in ten thousand records
+ public static final String MAX_ERROR_NUMBER_PROPERTY = "max_error_number";
+
+ // kafka type properties
+ public static final String KAFKA_ENDPOINT_PROPERTY = "kafka_endpoint";
+ public static final String KAFKA_TOPIC_PROPERTY = "kafka_topic";
+ // optional
+ public static final String KAFKA_PARTITIONS_PROPERTY = "kafka_partitions";
+
+ private static final String NAME_TYPE = "ROUTINE LOAD NAME";
+ private static final String ENDPOINT_REGEX = "([a-z]+\\.*)+:[0-9]+";
+ private static final String EMPTY_STRING = "";
+
+ private static final ImmutableSet<String> PROPERTIES_SET = new
ImmutableSet.Builder<String>()
+ .add(DESIRED_CONCURRENT_NUMBER_PROPERTY)
+ .add(MAX_ERROR_NUMBER_PROPERTY)
+ .build();
+
+ private static final ImmutableSet<String> KAFKA_PROPERTIES_SET = new
ImmutableSet.Builder<String>()
+ .add(KAFKA_ENDPOINT_PROPERTY)
+ .add(KAFKA_TOPIC_PROPERTY)
+ .add(KAFKA_PARTITIONS_PROPERTY)
+ .build();
+
+ private final String name;
+ private final TableName dbTableName;
+ private final List<ParseNode> loadPropertyList;
+ private final Map<String, String> properties;
+ private final String typeName;
+ private final Map<String, String> customProperties;
+
+
+ // those load properties will be initialized after analyze
+ private RoutineLoadDesc routineLoadDesc;
+ private int desiredConcurrentNum;
+ private int maxErrorNum;
+ private String kafkaEndpoint;
+ private String kafkaTopic;
+ private List<Integer> kafkaPartitions;
+
+ public CreateRoutineLoadStmt(String name, TableName dbTableName,
List<ParseNode> loadPropertyList,
+ Map<String, String> properties,
+ String typeName, Map<String, String>
customProperties) {
+ this.name = name;
+ this.dbTableName = dbTableName;
+ this.loadPropertyList = loadPropertyList;
+ this.properties = properties;
+ this.typeName = typeName;
+ this.customProperties = customProperties;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public TableName getDBTableName() {
+ return dbTableName;
+ }
+
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+
+ public Map<String, String> getCustomProperties() {
+ return customProperties;
+ }
+
+ public RoutineLoadDesc getRoutineLoadDesc() {
+ return routineLoadDesc;
+ }
+
+ public int getDesiredConcurrentNum() {
+ return desiredConcurrentNum;
+ }
+
+ public int getMaxErrorNum() {
+ return maxErrorNum;
+ }
+
+ public String getKafkaEndpoint() {
+ return kafkaEndpoint;
+ }
+
+ public String getKafkaTopic() {
+ return kafkaTopic;
+ }
+
+ public List<Integer> getKafkaPartitions() {
+ return kafkaPartitions;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException,
UserException {
+ super.analyze(analyzer);
+ // check name
+ FeNameFormat.checkCommonName(NAME_TYPE, name);
+ // check dbName and tableName
+ checkDBTableName();
+ // check load properties include column separator etc.
+ checkLoadProperties(analyzer);
+ // check routine load properties include desired concurrent number etc.
+ checkRoutineLoadProperties();
+ // check custom properties
+ checkCustomProperties();
+ }
+
+ private void checkDBTableName() throws AnalysisException {
+ if (Strings.isNullOrEmpty(dbTableName.getDb())) {
+ String dbName = ConnectContext.get().getDatabase();
+ if (Strings.isNullOrEmpty(dbName)) {
+ throw new AnalysisException("please choose a database first");
+ }
+ dbTableName.setDb(dbName);
+ }
+ if (Strings.isNullOrEmpty(dbTableName.getTbl())) {
+ throw new AnalysisException("empty table name in create routine
load statement");
+ }
+ }
+
+ private void checkLoadProperties(Analyzer analyzer) throws
AnalysisException {
+ if (loadPropertyList == null) {
+ return;
+ }
+ ColumnSeparator columnSeparator = null;
+ LoadColumnsInfo columnsInfo = null;
+ Expr wherePredicate = null;
+ PartitionNames partitionNames = null;
+ for (ParseNode parseNode : loadPropertyList) {
+ if (parseNode instanceof ColumnSeparator) {
+ // check column separator
+ if (columnSeparator != null) {
+ throw new AnalysisException("repeat setting of column
separator");
+ }
+ columnSeparator = (ColumnSeparator) parseNode;
+ columnSeparator.analyze(analyzer);
+ } else if (parseNode instanceof LoadColumnsInfo) {
+ // check columns info
+ if (columnsInfo != null) {
+ throw new AnalysisException("repeat setting of columns
info");
+ }
+ columnsInfo = (LoadColumnsInfo) parseNode;
+ columnsInfo.analyze(analyzer);
+ } else if (parseNode instanceof Expr) {
+ // check where expr
+ if (wherePredicate != null) {
+ throw new AnalysisException("repeat setting of where
predicate");
+ }
+ wherePredicate = (Expr) parseNode;
+ wherePredicate.analyze(analyzer);
+ } else if (parseNode instanceof PartitionNames) {
+ // check partition names
+ if (partitionNames != null) {
+ throw new AnalysisException("repeat setting of partition
names");
+ }
+ partitionNames = (PartitionNames) parseNode;
+ partitionNames.analyze(analyzer);
+ }
+ }
+ routineLoadDesc = new RoutineLoadDesc(columnSeparator, columnsInfo,
wherePredicate,
+
partitionNames.getPartitionNames());
+ }
+
+ private void checkRoutineLoadProperties() throws AnalysisException {
+ Optional<String> optional = properties.keySet().parallelStream()
+ .filter(entity ->
!PROPERTIES_SET.contains(entity)).findFirst();
+ if (optional.isPresent()) {
+ throw new AnalysisException(optional.get() + " is invalid
property");
+ }
+
+ // check desired concurrent number
+ final String desiredConcurrentNumberString =
properties.get(DESIRED_CONCURRENT_NUMBER_PROPERTY);
+ if (desiredConcurrentNumberString != null) {
+ desiredConcurrentNum =
getIntegerValueFromString(desiredConcurrentNumberString,
+
DESIRED_CONCURRENT_NUMBER_PROPERTY);
+ if (desiredConcurrentNum <= 0) {
+ throw new AnalysisException(DESIRED_CONCURRENT_NUMBER_PROPERTY
+ " must be greater then 0");
+ }
+ }
+
+ // check max error number
+ final String maxErrorNumberString =
properties.get(MAX_ERROR_NUMBER_PROPERTY);
+ if (maxErrorNumberString != null) {
+ maxErrorNum = getIntegerValueFromString(maxErrorNumberString,
MAX_ERROR_NUMBER_PROPERTY);
+ if (maxErrorNum < 0) {
+ throw new AnalysisException(MAX_ERROR_NUMBER_PROPERTY + " must
be greater then or equal to 0");
+ }
+
+ }
+ }
+
+ private void checkCustomProperties() throws AnalysisException {
+ LoadDataSourceType type;
+ try {
+ type = LoadDataSourceType.valueOf(typeName);
+ } catch (IllegalArgumentException e) {
+ throw new AnalysisException("routine load job does not support
this type " + typeName);
+ }
+ switch (type) {
+ case KAFKA:
+ checkKafkaCustomProperties();
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void checkKafkaCustomProperties() throws AnalysisException {
+ Optional<String> optional = customProperties.keySet().parallelStream()
+ .filter(entity ->
!KAFKA_PROPERTIES_SET.contains(entity)).findFirst();
+ if (optional.isPresent()) {
+ throw new AnalysisException(optional.get() + " is invalid kafka
custom property");
+ }
+ // check endpoint
+ kafkaEndpoint = customProperties.get(KAFKA_ENDPOINT_PROPERTY);
+ if (Strings.isNullOrEmpty(kafkaEndpoint)) {
+ throw new AnalysisException(KAFKA_ENDPOINT_PROPERTY + " is
required property");
+ }
+ if (!Pattern.matches(ENDPOINT_REGEX, kafkaEndpoint)) {
+ throw new AnalysisException(KAFKA_ENDPOINT_PROPERTY + " not match
pattern " + ENDPOINT_REGEX);
+ }
+ // check topic
+ kafkaTopic = customProperties.get(KAFKA_TOPIC_PROPERTY);
+ if (Strings.isNullOrEmpty(kafkaTopic)) {
+ throw new AnalysisException(KAFKA_TOPIC_PROPERTY + " is required
property");
+ }
+ // check partitions
+ final String kafkaPartitionsString =
customProperties.get(KAFKA_PARTITIONS_PROPERTY);
+ if (kafkaPartitionsString != null) {
+ kafkaPartitions = new ArrayList<>();
+ if (kafkaPartitionsString.equals(EMPTY_STRING)) {
+ throw new AnalysisException(KAFKA_PARTITIONS_PROPERTY + "
could not be a empty string");
+ }
+ String[] kafkaPartionsStringList =
kafkaPartitionsString.split(",");
+ for (String s : kafkaPartionsStringList) {
+ try {
+ kafkaPartitions.add(getIntegerValueFromString(s,
KAFKA_PARTITIONS_PROPERTY));
+ } catch (AnalysisException e) {
+ throw new AnalysisException(KAFKA_PARTITIONS_PROPERTY
+ + " must be a number
string with comma-separated");
+ }
+ }
+ }
+ }
+
+ private int getIntegerValueFromString(String valueString, String
propertyName) throws AnalysisException {
+ if (valueString.equals(EMPTY_STRING)) {
+ throw new AnalysisException(propertyName + " could not be a empty
string");
+ }
+ int value;
+ try {
+ value = Integer.valueOf(valueString);
+ } catch (NumberFormatException e) {
+ throw new AnalysisException(propertyName + " must be a integer");
+ }
+ return value;
+ }
+}
diff --git a/fe/src/main/java/org/apache/doris/analysis/LoadColumnsInfo.java
b/fe/src/main/java/org/apache/doris/analysis/LoadColumnsInfo.java
new file mode 100644
index 00000000..07cc6385
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/LoadColumnsInfo.java
@@ -0,0 +1,141 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.ErrorReport;
+import org.apache.doris.common.Pair;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class LoadColumnsInfo implements ParseNode {
+ private final List<String> columnNames;
+ private final List<Expr> columnMappingList;
+
+ private Map<String, Pair<String, List<String>>> columnToFunction;
+ private Map<String, Expr> parsedExprMap;
+
+ public LoadColumnsInfo(List<String> columnNames, List<Expr>
columnMappingList) {
+ this.columnNames = columnNames;
+ this.columnMappingList = columnMappingList;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException {
+ checkColumnNames();
+ checkColumnMapping();
+ }
+
+ @Override
+ public String toSql() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("COLUMNS ( ");
+ sb.append(Joiner.on(",").join(columnNames));
+ sb.append(")");
+
+ if (columnMappingList != null || columnMappingList.size() != 0) {
+ sb.append(" SET (");
+ sb.append(Joiner.on(",").join(columnMappingList.parallelStream()
+ .map(entity ->
entity.toSql()).collect(Collectors.toList())));
+ sb.append(")");
+ }
+ return sb.toString();
+ }
+
+ private void checkColumnNames() throws AnalysisException {
+ if (columnNames == null || columnNames.isEmpty()) {
+ return;
+ }
+ Set<String> columnSet = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
+ for (String col : columnNames) {
+ if (!columnSet.add(col)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_DUP_FIELDNAME, col);
+ }
+ }
+ }
+
+ private void checkColumnMapping() throws AnalysisException {
+ if (columnMappingList == null || columnMappingList.isEmpty()) {
+ return;
+ }
+
+ columnToFunction = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
+ parsedExprMap = Maps.newHashMap();
+ for (Expr expr : columnMappingList) {
+ if (!(expr instanceof BinaryPredicate)) {
+ throw new AnalysisException("Mapping function expr error.
expr: " + expr.toSql());
+ }
+
+ BinaryPredicate predicate = (BinaryPredicate) expr;
+ if (predicate.getOp() != BinaryPredicate.Operator.EQ) {
+ throw new AnalysisException("Mapping function operator error.
op: " + predicate.getOp());
+ }
+
+ Expr child0 = predicate.getChild(0);
+ if (!(child0 instanceof SlotRef)) {
+ throw new AnalysisException("Mapping column error. column: " +
child0.toSql());
+ }
+
+ String column = ((SlotRef) child0).getColumnName();
+ if (columnToFunction.containsKey(column)) {
+ throw new AnalysisException("Duplicate column mapping: " +
column);
+ }
+
+ Expr child1 = predicate.getChild(1);
+ if (!(child1 instanceof FunctionCallExpr)) {
+ throw new AnalysisException("Mapping function error, function:
" + child1.toSql());
+ }
+
+ if (!child1.supportSerializable()) {
+ throw new AnalysisException("Expr do not support
serializable." + child1.toSql());
+ }
+
+ parsedExprMap.put(column, child1);
+
+ FunctionCallExpr functionCallExpr = (FunctionCallExpr) child1;
+ String functionName = functionCallExpr.getFnName().getFunction();
+ List<Expr> paramExprs = functionCallExpr.getParams().exprs();
+ List<String> args = Lists.newArrayList();
+ for (Expr paramExpr : paramExprs) {
+ if (paramExpr instanceof SlotRef) {
+ SlotRef slot = (SlotRef) paramExpr;
+ args.add(slot.getColumnName());
+ } else if (paramExpr instanceof StringLiteral) {
+ StringLiteral literal = (StringLiteral) paramExpr;
+ args.add(literal.getValue());
+ } else if (paramExpr instanceof NullLiteral) {
+ args.add(null);
+ } else {
+ throw new AnalysisException("Mapping function args error,
arg: " + paramExpr.toSql());
+ }
+ }
+
+ Pair<String, List<String>> functionPair = new Pair<String,
List<String>>(functionName, args);
+ columnToFunction.put(column, functionPair);
+ }
+ }
+}
diff --git a/fe/src/main/java/org/apache/doris/analysis/PartitionNames.java
b/fe/src/main/java/org/apache/doris/analysis/PartitionNames.java
new file mode 100644
index 00000000..4053b1bc
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/PartitionNames.java
@@ -0,0 +1,54 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Strings;
+import org.apache.doris.common.AnalysisException;
+
+import java.util.List;
+
+public class PartitionNames implements ParseNode {
+
+ private final List<String> partitionNames;
+
+ public PartitionNames(List<String> partitionNames) {
+ this.partitionNames = partitionNames;
+ }
+
+ public List<String> getPartitionNames() {
+ return partitionNames;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException {
+ // check if partiton name is not empty string
+ if (partitionNames.parallelStream().anyMatch(entity ->
Strings.isNullOrEmpty(entity))) {
+ throw new AnalysisException("there are empty partition name");
+ }
+ }
+
+ @Override
+ public String toSql() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("PARTITIONS (");
+ sb.append(Joiner.on(",").join(partitionNames));
+ sb.append(")");
+ return sb.toString();
+ }
+}
diff --git
a/fe/src/main/java/org/apache/doris/analysis/PauseRoutineLoadStmt.java
b/fe/src/main/java/org/apache/doris/analysis/PauseRoutineLoadStmt.java
new file mode 100644
index 00000000..a7227211
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/PauseRoutineLoadStmt.java
@@ -0,0 +1,50 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Strings;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.UserException;
+
+/*
+ Pause routine load by name
+
+ syntax:
+ PAUSE ROUTINE LOAD name
+ */
+public class PauseRoutineLoadStmt extends DdlStmt {
+
+ private final String name;
+
+ public PauseRoutineLoadStmt(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException,
UserException {
+ super.analyze(analyzer);
+
+ if (Strings.isNullOrEmpty(name)) {
+ throw new AnalysisException("routine load name could not be empty
or null");
+ }
+ }
+}
diff --git
a/fe/src/main/java/org/apache/doris/analysis/ResumeRoutineLoadStmt.java
b/fe/src/main/java/org/apache/doris/analysis/ResumeRoutineLoadStmt.java
new file mode 100644
index 00000000..28bd4ae6
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/ResumeRoutineLoadStmt.java
@@ -0,0 +1,49 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Strings;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.UserException;
+
+/*
+ Resume routine load job by name
+
+ syntax:
+ RESUME ROUTINE LOAD name
+ */
+public class ResumeRoutineLoadStmt extends DdlStmt{
+
+ private final String name;
+
+ public ResumeRoutineLoadStmt(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException,
UserException {
+ super.analyze(analyzer);
+ if (Strings.isNullOrEmpty(name)) {
+ throw new AnalysisException("routine load name could not be empty
or null");
+ }
+ }
+}
diff --git
a/fe/src/main/java/org/apache/doris/analysis/ShowRoutineLoadStmt.java
b/fe/src/main/java/org/apache/doris/analysis/ShowRoutineLoadStmt.java
new file mode 100644
index 00000000..3ff0d283
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/ShowRoutineLoadStmt.java
@@ -0,0 +1,76 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.ScalarType;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.UserException;
+import org.apache.doris.qe.ShowResultSetMetaData;
+
+/*
+ Show routine load progress by routine load name
+
+ syntax:
+ SHOW ROUTINE LOAD name
+ */
+public class ShowRoutineLoadStmt extends ShowStmt {
+
+ private static final ImmutableList<String> TITLE_NAMES =
+ new ImmutableList.Builder<String>()
+ .add("id")
+ .add("name")
+ .add("db_id")
+ .add("table_id")
+ .add("partitions")
+ .add("state")
+
.add(CreateRoutineLoadStmt.DESIRED_CONCURRENT_NUMBER_PROPERTY)
+ .add("progress")
+ .build();
+
+ private final String name;
+
+ public ShowRoutineLoadStmt(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException,
UserException {
+ super.analyze(analyzer);
+ if (Strings.isNullOrEmpty(name)) {
+ throw new AnalysisException("routine load name could not be empty
or null");
+ }
+ }
+
+ @Override
+ public ShowResultSetMetaData getMetaData() {
+ ShowResultSetMetaData.Builder builder =
ShowResultSetMetaData.builder();
+
+ for (String title : TITLE_NAMES) {
+ builder.addColumn(new Column(title, ScalarType.createVarchar(30)));
+ }
+ return builder.build();
+ }
+}
diff --git
a/fe/src/main/java/org/apache/doris/analysis/StopRoutineLoadStmt.java
b/fe/src/main/java/org/apache/doris/analysis/StopRoutineLoadStmt.java
new file mode 100644
index 00000000..a8f15e41
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/analysis/StopRoutineLoadStmt.java
@@ -0,0 +1,50 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+
+package org.apache.doris.analysis;
+
+import com.google.common.base.Strings;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.UserException;
+
+/*
+ Stop routine load job by name
+
+ syntax:
+ STOP ROUTINE LOAD name
+ */
+public class StopRoutineLoadStmt extends DdlStmt {
+
+ private final String name;
+
+ public StopRoutineLoadStmt(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException,
UserException {
+ super.analyze(analyzer);
+ if (Strings.isNullOrEmpty(name)) {
+ throw new AnalysisException("routine load name could not be empty
or null");
+ }
+ }
+}
diff --git a/fe/src/main/java/org/apache/doris/catalog/Catalog.java
b/fe/src/main/java/org/apache/doris/catalog/Catalog.java
index 4ad35d87..93564a7e 100644
--- a/fe/src/main/java/org/apache/doris/catalog/Catalog.java
+++ b/fe/src/main/java/org/apache/doris/catalog/Catalog.java
@@ -4448,7 +4448,7 @@ public Load getLoadInstance() {
return this.load;
}
- public RoutineLoadManager getRoutineLoadInstance() {
+ public RoutineLoadManager getRoutineLoadManager() {
return routineLoadManager;
}
diff --git a/fe/src/main/java/org/apache/doris/load/RoutineLoadDesc.java
b/fe/src/main/java/org/apache/doris/load/RoutineLoadDesc.java
new file mode 100644
index 00000000..c0b8e8b8
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/load/RoutineLoadDesc.java
@@ -0,0 +1,56 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+
+package org.apache.doris.load;
+
+import org.apache.doris.analysis.ColumnSeparator;
+import org.apache.doris.analysis.Expr;
+import org.apache.doris.analysis.LoadColumnsInfo;
+
+import java.util.List;
+
+public class RoutineLoadDesc {
+ private final ColumnSeparator columnSeparator;
+ private final LoadColumnsInfo columnsInfo;
+ private final Expr wherePredicate;
+ private final List<String> partitionNames;
+
+ public RoutineLoadDesc(ColumnSeparator columnSeparator, LoadColumnsInfo
columnsInfo,
+ Expr wherePredicate, List<String> partitionNames) {
+ this.columnSeparator = columnSeparator;
+ this.columnsInfo = columnsInfo;
+ this.wherePredicate = wherePredicate;
+ this.partitionNames = partitionNames;
+ }
+
+ public ColumnSeparator getColumnSeparator() {
+ return columnSeparator;
+ }
+
+ public LoadColumnsInfo getColumnsInfo() {
+ return columnsInfo;
+ }
+
+ public Expr getWherePredicate() {
+ return wherePredicate;
+ }
+
+ public List<String> getPartitionNames() {
+ return partitionNames;
+ }
+}
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
b/fe/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
index 4ab3d041..6cfa5717 100644
---
a/fe/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
+++
b/fe/src/main/java/org/apache/doris/load/routineload/KafkaRoutineLoadJob.java
@@ -17,16 +17,18 @@
package org.apache.doris.load.routineload;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
+import org.apache.doris.analysis.CreateRoutineLoadStmt;
+import org.apache.doris.common.LoadException;
+import org.apache.doris.load.RoutineLoadDesc;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Table;
import org.apache.doris.common.AnalysisException;
-import org.apache.doris.common.LoadException;
import org.apache.doris.common.MetaNotFoundException;
-import org.apache.doris.common.SystemIdGenerator;
import org.apache.doris.common.UserException;
import org.apache.doris.system.SystemInfoService;
-import org.apache.doris.thrift.TResourceInfo;
import org.apache.doris.transaction.BeginTransactionException;
import org.apache.doris.transaction.LabelAlreadyExistsException;
import org.apache.kafka.clients.consumer.KafkaConsumer;
@@ -55,21 +57,39 @@
// optional, user want to load partitions.
private List<Integer> kafkaPartitions;
- public KafkaRoutineLoadJob() {
+ public KafkaRoutineLoadJob(String name, long dbId, long tableId, String
serverAddress, String topic) {
+ super(name, dbId, tableId, LoadDataSourceType.KAFKA);
+ this.serverAddress = serverAddress;
+ this.topic = topic;
+ this.progress = new KafkaProgress();
}
- public KafkaRoutineLoadJob(String id, String name, String userName, long
dbId, long tableId,
- String partitions, String columns, String
where, String columnSeparator,
- int desireTaskConcurrentNum, JobState state,
DataSourceType dataSourceType,
- int maxErrorNum, TResourceInfo resourceInfo,
String serverAddress, String topic,
- KafkaProgress kafkaProgress) {
- super(id, name, userName, dbId, tableId, partitions, columns, where,
- columnSeparator, desireTaskConcurrentNum, state,
dataSourceType, maxErrorNum, resourceInfo);
+ // TODO(ml): I will change it after ut.
+ @VisibleForTesting
+ public KafkaRoutineLoadJob(String id, String name, long dbId, long tableId,
+ RoutineLoadDesc routineLoadDesc,
+ int desireTaskConcurrentNum, int maxErrorNum,
+ String serverAddress, String topic,
KafkaProgress kafkaProgress) {
+ super(id, name, dbId, tableId, routineLoadDesc,
+ desireTaskConcurrentNum, LoadDataSourceType.KAFKA,
+ maxErrorNum);
this.serverAddress = serverAddress;
this.topic = topic;
this.progress = kafkaProgress;
}
+ private void setKafkaPartitions(List<Integer> kafkaPartitions) throws
LoadException {
+ writeLock();
+ try {
+ if (this.kafkaPartitions != null) {
+ throw new LoadException("Kafka partitions have been
initialized");
+ }
+ this.kafkaPartitions = kafkaPartitions;
+ } finally {
+ writeUnlock();
+ }
+ }
+
@Override
public List<RoutineLoadTaskInfo> divideRoutineLoadJob(int
currentConcurrentTaskNum) {
List<RoutineLoadTaskInfo> result = new ArrayList<>();
@@ -124,10 +144,13 @@ public int calculateCurrentConcurrentTaskNum() throws
MetaNotFoundException {
}
int aliveBeNum = systemInfoService.getClusterBackendIds(clusterName,
true).size();
int partitionNum = kafkaPartitions.size();
+ if (desireTaskConcurrentNum == 0) {
+ desireTaskConcurrentNum = partitionNum;
+ }
LOG.info("current concurrent task number is min "
- + "(current size of partition {}, desire task
concurrent num {}, alive be num {})",
- partitionNum, desireTaskConcurrentNum, aliveBeNum);
+ + "(current size of partition {}, desire task
concurrent num {}, alive be num {})",
+ partitionNum, desireTaskConcurrentNum, aliveBeNum);
return Math.min(partitionNum, Math.min(desireTaskConcurrentNum,
aliveBeNum));
}
@@ -149,6 +172,39 @@ protected RoutineLoadTaskInfo
reNewTask(RoutineLoadTaskInfo routineLoadTaskInfo)
return kafkaTaskInfo;
}
+ public static KafkaRoutineLoadJob fromCreateStmt(CreateRoutineLoadStmt
stmt) throws AnalysisException,
+ LoadException {
+ checkCreate(stmt);
+ // find dbId
+ Database database =
Catalog.getCurrentCatalog().getDb(stmt.getDBTableName().getDb());
+ Table table;
+ database.readLock();
+ try {
+ table = database.getTable(stmt.getDBTableName().getTbl());
+ } finally {
+ database.readUnlock();
+ }
+ List<Integer> kafkaPartitionList = new ArrayList<>();
+ if
(stmt.getCustomProperties().get(CreateRoutineLoadStmt.KAFKA_PARTITIONS_PROPERTY)
!= null) {
+ String[] kafkaPartitionStringList = stmt.getCustomProperties()
+
.get(CreateRoutineLoadStmt.KAFKA_PARTITIONS_PROPERTY).split(",");
+ for (String s : kafkaPartitionStringList) {
+ kafkaPartitionList.add(Integer.valueOf(s));
+ }
+ } else {
+ LOG.debug("All of partitions which belong to topic will be load
for {} routine load job", stmt.getName());
+ }
+
+ // init kafka routine load job
+ KafkaRoutineLoadJob kafkaRoutineLoadJob =
+ new KafkaRoutineLoadJob(stmt.getName(), database.getId(),
table.getId(),
+ stmt.getKafkaEndpoint(),
+ stmt.getKafkaTopic());
+ kafkaRoutineLoadJob.setOptional(stmt);
+
+ return kafkaRoutineLoadJob;
+ }
+
private void updatePartitions() {
// fetch all of kafkaPartitions in topic
if (kafkaPartitions == null || kafkaPartitions.size() == 0) {
@@ -166,4 +222,19 @@ private void updatePartitions() {
}
}
}
+
+ private void setOptional(CreateRoutineLoadStmt stmt) throws LoadException {
+ if (stmt.getRoutineLoadDesc() != null) {
+ setRoutineLoadDesc(stmt.getRoutineLoadDesc());
+ }
+ if (stmt.getDesiredConcurrentNum() != 0) {
+ setDesireTaskConcurrentNum(stmt.getDesiredConcurrentNum());
+ }
+ if (stmt.getMaxErrorNum() != 0) {
+ setMaxErrorNum(stmt.getMaxErrorNum());
+ }
+ if (stmt.getKafkaPartitions() != null) {
+ setKafkaPartitions(stmt.getKafkaPartitions());
+ }
+ }
}
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
b/fe/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
index f812796b..63b7a3f9 100644
--- a/fe/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
+++ b/fe/src/main/java/org/apache/doris/load/routineload/KafkaTaskInfo.java
@@ -17,8 +17,10 @@
package org.apache.doris.load.routineload;
+import com.google.common.collect.Maps;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.LoadException;
import org.apache.doris.task.KafkaRoutineLoadTask;
import org.apache.doris.task.RoutineLoadTask;
import org.apache.doris.transaction.BeginTransactionException;
@@ -26,11 +28,12 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
public class KafkaTaskInfo extends RoutineLoadTaskInfo {
- private RoutineLoadManager routineLoadManager =
Catalog.getCurrentCatalog().getRoutineLoadInstance();
+ private RoutineLoadManager routineLoadManager =
Catalog.getCurrentCatalog().getRoutineLoadManager();
private List<Integer> partitions;
@@ -55,12 +58,19 @@ public void addKafkaPartition(int partition) {
}
@Override
- public RoutineLoadTask createStreamLoadTask(long beId) {
+ public RoutineLoadTask createStreamLoadTask(long beId) throws
LoadException {
RoutineLoadJob routineLoadJob = routineLoadManager.getJob(jobId);
- return new KafkaRoutineLoadTask(routineLoadJob.getResourceInfo(),
- beId, routineLoadJob.getDbId(), routineLoadJob.getTableId(),
- 0L, 0L, 0L, routineLoadJob.getColumns(),
routineLoadJob.getWhere(),
- routineLoadJob.getColumnSeparator(), this, (KafkaProgress)
routineLoadJob.getProgress(),
- txnId);
+ Map<Integer, Long> partitionIdToOffset = Maps.newHashMap();
+ this.getPartitions().parallelStream()
+ .forEach(entity -> partitionIdToOffset.put(entity,
((KafkaProgress) routineLoadJob.getProgress())
+ .getPartitionIdToOffset().get(entity)));
+ RoutineLoadTask routineLoadTask = new
KafkaRoutineLoadTask(routineLoadJob.getResourceInfo(),
+ beId,
routineLoadJob.getDbId(),
+
routineLoadJob.getTableId(),
+ id, txnId,
partitionIdToOffset);
+ if (routineLoadJob.getRoutineLoadDesc() != null) {
+
routineLoadTask.setRoutineLoadDesc(routineLoadJob.getRoutineLoadDesc());
+ }
+ return routineLoadTask;
}
}
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/LoadDataSourceType.java
b/fe/src/main/java/org/apache/doris/load/routineload/LoadDataSourceType.java
new file mode 100644
index 00000000..b2ded5a7
--- /dev/null
+++ b/fe/src/main/java/org/apache/doris/load/routineload/LoadDataSourceType.java
@@ -0,0 +1,23 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+
+package org.apache.doris.load.routineload;
+
+public enum LoadDataSourceType {
+ KAFKA
+}
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
index 42b72d01..8d15afec 100644
--- a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
+++ b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadJob.java
@@ -17,14 +17,22 @@
package org.apache.doris.load.routineload;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
+import org.apache.doris.analysis.CreateRoutineLoadStmt;
+import org.apache.doris.common.LoadException;
+import org.apache.doris.load.RoutineLoadDesc;
+import org.apache.doris.analysis.TableName;
import org.apache.doris.catalog.Catalog;
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.Table;
import org.apache.doris.common.AnalysisException;
-import org.apache.doris.common.LoadException;
import org.apache.doris.common.MetaNotFoundException;
import org.apache.doris.common.UserException;
import org.apache.doris.common.io.Writable;
import org.apache.doris.load.TxnStateChangeListener;
+import org.apache.doris.qe.ConnectContext;
import org.apache.doris.service.ExecuteEnv;
import org.apache.doris.service.FrontendServiceImpl;
import org.apache.doris.task.AgentTaskQueue;
@@ -45,6 +53,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import java.util.UUID;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
@@ -55,141 +64,234 @@
* The routine load job support different streaming medium such as KAFKA
*/
public abstract class RoutineLoadJob implements Writable,
TxnStateChangeListener {
-
+
private static final Logger LOG =
LogManager.getLogger(RoutineLoadJob.class);
-
+
private static final int DEFAULT_TASK_TIMEOUT_SECONDS = 10;
private static final int BASE_OF_ERROR_RATE = 10000;
-
+ private static final String STAR_STRING = "*";
+
+ /**
+ +-----------------+
+ fe scheduler job | NEED_SCHEDULER | user resume job
+ +----------- + | <---------+
+ | | | |
+ v +-----------------+ ^
+ |
+ +------------+ user pause job +-------+----+
+ | RUNNING | | PAUSED |
+ | +-----------------------> | |
+ +----+-------+ +-------+----+
+ | |
+ | +---------------+ |
+ | | STOPPED | |
+ +--------------> | | <-----------+
+ user stop job +---------------+ user stop| job
+ | |
+ | |
+ | +---------------+ |
+ | | CANCELLED | |
+ +---------------> | | <----------+
+ system error +---------------+ system error
+
+ */
public enum JobState {
NEED_SCHEDULER,
RUNNING,
PAUSED,
STOPPED,
- CANCELLED
- }
-
- public enum DataSourceType {
- KAFKA
+ CANCELLED;
+
+ public boolean isFinalState() {
+ return this == STOPPED || this == CANCELLED;
+ }
+
}
-
+
protected String id;
protected String name;
- protected String userName;
protected long dbId;
protected long tableId;
- protected String partitions;
- protected String columns;
- protected String where;
- protected String columnSeparator;
- protected int desireTaskConcurrentNum;
+ protected RoutineLoadDesc routineLoadDesc; // optional
+ protected int desireTaskConcurrentNum; // optional
protected JobState state;
- protected DataSourceType dataSourceType;
+ protected LoadDataSourceType dataSourceType;
// max number of error data in ten thousand data
// maxErrorNum / BASE_OF_ERROR_RATE = max error rate of routine load job
// if current error rate is more then max error rate, the job will be
paused
- protected int maxErrorNum;
+ protected int maxErrorNum; // optional
+ // thrift object
+ protected TResourceInfo resourceInfo;
+
protected RoutineLoadProgress progress;
protected String pausedReason;
-
+
// currentErrorNum and currentTotalNum will be update
// when currentTotalNum is more then ten thousand or currentErrorNum is
more then maxErrorNum
protected int currentErrorNum;
protected int currentTotalNum;
-
+
// The tasks belong to this job
protected List<RoutineLoadTaskInfo> routineLoadTaskInfoList;
protected List<RoutineLoadTaskInfo> needSchedulerTaskInfoList;
-
+
protected ReentrantReadWriteLock lock;
// TODO(ml): error sample
-
-
- public RoutineLoadJob() {
- }
-
- public RoutineLoadJob(String id, String name, String userName, long dbId,
long tableId,
- String partitions, String columns, String where,
String columnSeparator,
- int desireTaskConcurrentNum, JobState state,
DataSourceType dataSourceType,
- int maxErrorNum, TResourceInfo resourceInfo) {
+
+ public RoutineLoadJob(String name, long dbId, long tableId,
LoadDataSourceType dataSourceType) {
+ this.id = UUID.randomUUID().toString();
+ this.name = name;
+ this.dbId = dbId;
+ this.tableId = tableId;
+ this.state = JobState.NEED_SCHEDULER;
+ this.dataSourceType = dataSourceType;
+ this.resourceInfo = ConnectContext.get().toResourceCtx();
+ this.routineLoadTaskInfoList = new ArrayList<>();
+ this.needSchedulerTaskInfoList = new ArrayList<>();
+ lock = new ReentrantReadWriteLock(true);
+ }
+
+ // TODO(ml): I will change it after ut.
+ @VisibleForTesting
+ public RoutineLoadJob(String id, String name, long dbId, long tableId,
+ RoutineLoadDesc routineLoadDesc,
+ int desireTaskConcurrentNum, LoadDataSourceType
dataSourceType,
+ int maxErrorNum) {
this.id = id;
this.name = name;
- this.userName = userName;
this.dbId = dbId;
this.tableId = tableId;
- this.partitions = partitions;
- this.columns = columns;
- this.where = where;
- this.columnSeparator = columnSeparator;
+ this.routineLoadDesc = routineLoadDesc;
this.desireTaskConcurrentNum = desireTaskConcurrentNum;
- this.state = state;
+ this.state = JobState.NEED_SCHEDULER;
this.dataSourceType = dataSourceType;
this.maxErrorNum = maxErrorNum;
- this.resourceInfo = resourceInfo;
+ this.resourceInfo = ConnectContext.get().toResourceCtx();
this.routineLoadTaskInfoList = new ArrayList<>();
this.needSchedulerTaskInfoList = new ArrayList<>();
lock = new ReentrantReadWriteLock(true);
}
-
+
public void readLock() {
lock.readLock().lock();
}
-
+
public void readUnlock() {
lock.readLock().unlock();
}
-
+
public void writeLock() {
lock.writeLock().lock();
}
-
+
public void writeUnlock() {
lock.writeLock().unlock();
}
-
- // thrift object
- private TResourceInfo resourceInfo;
-
+
public String getId() {
return id;
}
-
+
+ public String getName() {
+ return name;
+ }
+
public long getDbId() {
return dbId;
}
-
+
+ public String getDbFullName() {
+ Database database = Catalog.getCurrentCatalog().getDb(dbId);
+ return database.getFullName();
+ }
+
public long getTableId() {
return tableId;
}
-
- public String getColumns() {
- return columns;
- }
-
- public String getWhere() {
- return where;
- }
-
- public String getColumnSeparator() {
- return columnSeparator;
+
+ public String getTableName() {
+ Database database = Catalog.getCurrentCatalog().getDb(dbId);
+ database.readLock();
+ try {
+ Table table = database.getTable(tableId);
+ return table.getName();
+ } finally {
+ database.readUnlock();
+ }
}
-
+
public JobState getState() {
return state;
}
-
+
public void setState(JobState state) {
this.state = state;
}
-
+
+ protected void setRoutineLoadDesc(RoutineLoadDesc routineLoadDesc) throws
LoadException {
+ writeLock();
+ try {
+ if (this.routineLoadDesc != null) {
+ throw new LoadException("Routine load desc has been
initialized");
+ }
+ this.routineLoadDesc = routineLoadDesc;
+ } finally {
+ writeUnlock();
+ }
+ }
+
+ public RoutineLoadDesc getRoutineLoadDesc() {
+ return routineLoadDesc;
+ }
+
public TResourceInfo getResourceInfo() {
return resourceInfo;
}
-
+
public RoutineLoadProgress getProgress() {
return progress;
}
-
+
+ public String getPartitions() {
+ if (routineLoadDesc.getPartitionNames() == null ||
routineLoadDesc.getPartitionNames().size() == 0) {
+ return STAR_STRING;
+ } else {
+ return String.join(",", routineLoadDesc.getPartitionNames());
+ }
+ }
+
+ protected void setDesireTaskConcurrentNum(int desireTaskConcurrentNum)
throws LoadException {
+ writeLock();
+ try {
+ if (this.desireTaskConcurrentNum != 0) {
+ throw new LoadException("Desired task concurrent num has been
initialized");
+ }
+ this.desireTaskConcurrentNum = desireTaskConcurrentNum;
+ } finally {
+ writeUnlock();
+ }
+ }
+
+ public String getDesiredConcurrentNumber() {
+ if (desireTaskConcurrentNum == 0) {
+ return "";
+ } else {
+ return String.valueOf(desireTaskConcurrentNum);
+ }
+ }
+
+ protected void setMaxErrorNum(int maxErrorNum) throws LoadException {
+ writeLock();
+ try {
+ if (this.maxErrorNum != 0) {
+ throw new LoadException("Max error num has been initialized");
+ }
+ this.maxErrorNum = maxErrorNum;
+ } finally {
+ writeUnlock();
+ }
+ }
+
public int getSizeOfRoutineLoadTaskInfoList() {
readLock();
try {
@@ -197,13 +299,13 @@ public int getSizeOfRoutineLoadTaskInfoList() {
} finally {
readUnlock();
}
-
+
}
-
+
public List<RoutineLoadTaskInfo> getNeedSchedulerTaskInfoList() {
return needSchedulerTaskInfoList;
}
-
+
public void updateState(JobState jobState) {
writeLock();
try {
@@ -212,14 +314,14 @@ public void updateState(JobState jobState) {
writeUnlock();
}
}
-
+
public List<RoutineLoadTaskInfo> processTimeoutTasks() {
List<RoutineLoadTaskInfo> result = new ArrayList<>();
writeLock();
try {
List<RoutineLoadTaskInfo> runningTasks = new
ArrayList<>(routineLoadTaskInfoList);
runningTasks.removeAll(needSchedulerTaskInfoList);
-
+
for (RoutineLoadTaskInfo routineLoadTaskInfo : runningTasks) {
if ((System.currentTimeMillis() -
routineLoadTaskInfo.getLoadStartTimeMs())
> DEFAULT_TASK_TIMEOUT_SECONDS * 1000) {
@@ -234,7 +336,7 @@ public void updateState(JobState jobState) {
continue;
}
}
-
+
try {
result.add(reNewTask(routineLoadTaskInfo));
LOG.debug("Task {} was ran more then {} minutes. It
was removed and rescheduled",
@@ -251,24 +353,24 @@ public void updateState(JobState jobState) {
}
return result;
}
-
+
abstract List<RoutineLoadTaskInfo> divideRoutineLoadJob(int
currentConcurrentTaskNum);
-
+
public int calculateCurrentConcurrentTaskNum() throws
MetaNotFoundException {
return 0;
}
-
+
@Override
public void write(DataOutput out) throws IOException {
// TODO(ml)
}
-
+
@Override
public void readFields(DataInput in) throws IOException {
// TODO(ml)
}
-
-
+
+
public void removeNeedSchedulerTask(RoutineLoadTaskInfo
routineLoadTaskInfo) {
writeLock();
try {
@@ -277,9 +379,9 @@ public void removeNeedSchedulerTask(RoutineLoadTaskInfo
routineLoadTaskInfo) {
writeUnlock();
}
}
-
+
abstract void updateProgress(RoutineLoadProgress progress);
-
+
public boolean containsTask(String taskId) {
readLock();
try {
@@ -289,23 +391,34 @@ public boolean containsTask(String taskId) {
readUnlock();
}
}
-
+
// All of private method could not be call without lock
- private void checkStateTransform(RoutineLoadJob.JobState currentState,
RoutineLoadJob.JobState desireState)
- throws LoadException {
- if (currentState == RoutineLoadJob.JobState.PAUSED && desireState ==
RoutineLoadJob.JobState.NEED_SCHEDULER) {
- throw new LoadException("could not transform " + currentState + "
to " + desireState);
- } else if (currentState == RoutineLoadJob.JobState.CANCELLED ||
- currentState == RoutineLoadJob.JobState.STOPPED) {
- throw new LoadException("could not transform " + currentState + "
to " + desireState);
+ private void checkStateTransform(RoutineLoadJob.JobState desireState)
+ throws UnsupportedOperationException {
+ switch (state) {
+ case RUNNING:
+ if (desireState == JobState.NEED_SCHEDULER) {
+ throw new UnsupportedOperationException("Could not
transform " + state + " to " + desireState);
+ }
+ break;
+ case PAUSED:
+ if (desireState == JobState.PAUSED) {
+ throw new UnsupportedOperationException("Could not
transform " + state + " to " + desireState);
+ }
+ break;
+ case STOPPED:
+ case CANCELLED:
+ throw new UnsupportedOperationException("Could not transfrom "
+ state + " to " + desireState);
+ default:
+ break;
}
}
-
+
private void loadTxnCommit(TLoadTxnCommitRequest request) throws
TException {
FrontendServiceImpl frontendService = new
FrontendServiceImpl(ExecuteEnv.getInstance());
frontendService.loadTxnCommit(request);
}
-
+
private void updateNumOfData(int numOfErrorData, int numOfTotalData) {
currentErrorNum += numOfErrorData;
currentTotalNum += numOfTotalData;
@@ -314,9 +427,9 @@ private void updateNumOfData(int numOfErrorData, int
numOfTotalData) {
LOG.info("current error num {} of job {} is more then max
error num {}. begin to pause job",
currentErrorNum, id, maxErrorNum);
// remove all of task in jobs and change job state to paused
- pausedJob("current error num of job is more then max error
num");
+ executePause("current error num of job is more then max error
num");
}
-
+
// reset currentTotalNum and currentErrorNum
currentErrorNum = 0;
currentTotalNum = 0;
@@ -324,16 +437,16 @@ private void updateNumOfData(int numOfErrorData, int
numOfTotalData) {
LOG.info("current error num {} of job {} is more then max error
num {}. begin to pause job",
currentErrorNum, id, maxErrorNum);
// remove all of task in jobs and change job state to paused
- pausedJob("current error num is more then max error num");
+ executePause("current error num is more then max error num");
// reset currentTotalNum and currentErrorNum
currentErrorNum = 0;
currentTotalNum = 0;
}
}
-
+
abstract RoutineLoadTaskInfo reNewTask(RoutineLoadTaskInfo
routineLoadTaskInfo) throws AnalysisException,
LabelAlreadyExistsException, BeginTransactionException;
-
+
@Override
public void beforeAborted(TransactionState txnState,
TransactionState.TxnStatusChangeReason txnStatusChangeReason)
throws AbortTransactionException {
@@ -355,12 +468,12 @@ public void beforeAborted(TransactionState txnState,
TransactionState.TxnStatusC
readUnlock();
}
}
-
+
@Override
public void onCommitted(TransactionState txnState) {
// step0: get progress from transaction state
RLTaskTxnCommitAttachment rlTaskTxnCommitAttachment =
(RLTaskTxnCommitAttachment) txnState.getTxnCommitAttachment();
-
+
writeLock();
try {
// step1: find task in job
@@ -368,42 +481,98 @@ public void onCommitted(TransactionState txnState) {
routineLoadTaskInfoList.parallelStream()
.filter(entity ->
entity.getId().equals(txnState.getLabel())).findFirst();
RoutineLoadTaskInfo routineLoadTaskInfo =
routineLoadTaskInfoOptional.get();
-
+
// step2: update job progress
updateProgress(rlTaskTxnCommitAttachment.getProgress());
-
+
// step3: remove task in agentTaskQueue
AgentTaskQueue.removeTask(rlTaskTxnCommitAttachment.getBackendId(),
TTaskType.STREAM_LOAD,
rlTaskTxnCommitAttachment.getTaskSignature());
-
- // step4: if rate of error data is more then max_filter_ratio,
paused job
+
+ // step4: if rate of error data is more then max_filter_ratio,
pause job
updateNumOfData(rlTaskTxnCommitAttachment.getNumOfErrorData(),
rlTaskTxnCommitAttachment.getNumOfTotalData());
-
+
if (state == JobState.RUNNING) {
// step5: create a new task for partitions
RoutineLoadTaskInfo newRoutineLoadTaskInfo =
reNewTask(routineLoadTaskInfo);
- Catalog.getCurrentCatalog().getRoutineLoadInstance()
+ Catalog.getCurrentCatalog().getRoutineLoadManager()
.getNeedSchedulerTasksQueue().addAll(Lists.newArrayList(newRoutineLoadTaskInfo));
}
} catch (Throwable e) {
LOG.error("failed to update offset in routine load task {} when
transaction {} has been committed. "
+ "change job to paused",
rlTaskTxnCommitAttachment.getTaskId(),
txnState.getTransactionId());
- pausedJob("failed to update offset when transaction "
- + txnState.getTransactionId() + " has been
committed");
+ executePause("failed to update offset when transaction "
+ + txnState.getTransactionId() + " has been
committed");
} finally {
writeUnlock();
}
}
-
+
@Override
public void onAborted(TransactionState txnState,
TransactionState.TxnStatusChangeReason txnStatusChangeReason) {
- pausedJob(txnStatusChangeReason.name());
- LOG.debug("job {} need to be paused while txn {} abort with reason {}",
+ pause(txnStatusChangeReason.name());
+ LOG.debug("job {} need to be pause while txn {} abort with reason {}",
id, txnState.getTransactionId(),
txnStatusChangeReason.name());
}
-
- private void pausedJob(String reason) {
+
+ protected static void checkCreate(CreateRoutineLoadStmt stmt) throws
AnalysisException {
+ // check table belong to db, partitions belong to table
+ if (stmt.getRoutineLoadDesc() == null) {
+ checkDBSemantics(stmt.getDBTableName(), null);
+ } else {
+ checkDBSemantics(stmt.getDBTableName(),
stmt.getRoutineLoadDesc().getPartitionNames());
+ }
+ }
+
+ private static void checkDBSemantics(TableName dbTableName, List<String>
partitionNames)
+ throws AnalysisException {
+ String tableName = dbTableName.getTbl();
+ String dbName = dbTableName.getDb();
+ // check database
+ Database database = Catalog.getCurrentCatalog().getDb(dbName);
+ if (database == null) {
+ throw new AnalysisException("There is no database named " +
dbName);
+ }
+
+ database.readLock();
+ try {
+ Table table = database.getTable(tableName);
+ // check table belong to database
+ if (table == null) {
+ throw new AnalysisException("There is no table named " +
tableName + " in " + dbName);
+ }
+ // check table type
+ if (table.getType() != Table.TableType.OLAP) {
+ throw new AnalysisException("Only doris table support routine
load");
+ }
+
+ if (partitionNames == null || partitionNames.size() == 0) {
+ return;
+ }
+ // check partitions belong to table
+ Optional<String> partitionNotInTable =
partitionNames.parallelStream()
+ .filter(entity -> ((OlapTable) table).getPartition(entity)
== null).findFirst();
+ if (partitionNotInTable != null &&
partitionNotInTable.isPresent()) {
+ throw new AnalysisException("Partition " +
partitionNotInTable.get()
+ + " does not belong to
table " + tableName);
+ }
+ } finally {
+ database.readUnlock();
+ }
+ }
+
+ public void pause(String reason) {
+ writeLock();
+ try {
+ checkStateTransform(JobState.PAUSED);
+ executePause(reason);
+ } finally {
+ writeUnlock();
+ }
+ }
+
+ private void executePause(String reason) {
// TODO(ml): edit log
// remove all of task in jobs and change job state to paused
pausedReason = reason;
@@ -411,4 +580,28 @@ private void pausedJob(String reason) {
routineLoadTaskInfoList.clear();
needSchedulerTaskInfoList.clear();
}
+
+ public void resume() {
+ // TODO(ml): edit log
+ writeLock();
+ try {
+ checkStateTransform(JobState.NEED_SCHEDULER);
+ state = JobState.NEED_SCHEDULER;
+ } finally {
+ writeUnlock();
+ }
+ }
+
+ public void stop() {
+ // TODO(ml): edit log
+ writeLock();
+ try {
+ checkStateTransform(JobState.STOPPED);
+ state = JobState.STOPPED;
+ routineLoadTaskInfoList.clear();
+ needSchedulerTaskInfoList.clear();
+ } finally {
+ writeUnlock();
+ }
+ }
}
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadManager.java
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadManager.java
index c2e4e100..3b22d891 100644
--- a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadManager.java
+++ b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadManager.java
@@ -17,11 +17,23 @@
package org.apache.doris.load.routineload;
+import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
+import org.apache.doris.analysis.CreateRoutineLoadStmt;
+import org.apache.doris.analysis.PauseRoutineLoadStmt;
+import org.apache.doris.analysis.ResumeRoutineLoadStmt;
+import org.apache.doris.analysis.StopRoutineLoadStmt;
import org.apache.doris.catalog.Catalog;
+import org.apache.doris.catalog.Database;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.LoadException;
import org.apache.doris.common.MetaNotFoundException;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.qe.ConnectContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -29,6 +41,7 @@
import java.util.Collection;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
@@ -43,6 +56,7 @@
// stream load job meta
private Map<String, RoutineLoadJob> idToRoutineLoadJob;
+ private Map<Long, Map<String, List<RoutineLoadJob>>>
dbToNameToRoutineLoadJob;
private Queue<RoutineLoadTaskInfo> needSchedulerTasksQueue;
@@ -66,6 +80,7 @@ private void writeUnlock() {
public RoutineLoadManager() {
idToRoutineLoadJob = Maps.newConcurrentMap();
+ dbToNameToRoutineLoadJob = Maps.newConcurrentMap();
beIdToConcurrentTasks = Maps.newHashMap();
needSchedulerTasksQueue = Queues.newLinkedBlockingQueue();
lock = new ReentrantReadWriteLock(true);
@@ -110,8 +125,8 @@ public void updateBeIdTaskMaps() {
beIdToConcurrentTasks.remove(beId);
}
LOG.info("There are {} backends which participate in routine load
scheduler. "
- + "There are {} new backends and {} unavailable
backends for routine load",
- beIdToMaxConcurrentTasks.size(), newBeIds.size(),
unavailableBeIds.size());
+ + "There are {} new backends and {} unavailable
backends for routine load",
+ beIdToMaxConcurrentTasks.size(), newBeIds.size(),
unavailableBeIds.size());
} finally {
writeUnlock();
}
@@ -132,8 +147,140 @@ public void addNumOfConcurrentTasksByBeId(long beId) {
}
}
- public void addRoutineLoadJob(RoutineLoadJob routineLoadJob) {
- idToRoutineLoadJob.put(routineLoadJob.getId(), routineLoadJob);
+ public void addRoutineLoadJob(CreateRoutineLoadStmt createRoutineLoadStmt)
+ throws AnalysisException, DdlException, LoadException {
+ // check load auth
+ if
(!Catalog.getCurrentCatalog().getAuth().checkTblPriv(ConnectContext.get(),
+
createRoutineLoadStmt.getDBTableName().getDb(),
+
createRoutineLoadStmt.getDBTableName().getTbl(),
+
PrivPredicate.LOAD)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR,
"LOAD",
+
ConnectContext.get().getQualifiedUser(),
+
ConnectContext.get().getRemoteIP(),
+
createRoutineLoadStmt.getDBTableName());
+ }
+ RoutineLoadJob routineLoadJob = null;
+ LoadDataSourceType type =
LoadDataSourceType.valueOf(createRoutineLoadStmt.getTypeName());
+ switch (type) {
+ case KAFKA:
+ routineLoadJob =
KafkaRoutineLoadJob.fromCreateStmt(createRoutineLoadStmt);
+ break;
+ default:
+ break;
+ }
+ if (routineLoadJob != null) {
+ addRoutineLoadJob(routineLoadJob);
+ }
+ }
+
+ public void addRoutineLoadJob(RoutineLoadJob routineLoadJob) throws
DdlException {
+ writeLock();
+ try {
+ // check if db.routineLoadName has been used
+ if (isNameUsed(routineLoadJob.dbId, routineLoadJob.getName())) {
+ throw new DdlException("Name " + routineLoadJob.getName() + "
already used in db "
+ + routineLoadJob.getDbId());
+ }
+ idToRoutineLoadJob.put(routineLoadJob.getId(), routineLoadJob);
+ addJobToDbToNameToRoutineLoadJob(routineLoadJob);
+ // TODO(ml): edit log
+ } finally {
+ writeUnlock();
+ }
+
+ }
+
+ // TODO(ml): Idempotency
+ private boolean isNameUsed(Long dbId, String name) {
+ if (dbToNameToRoutineLoadJob.containsKey(dbId)) {
+ Map<String, List<RoutineLoadJob>> labelToRoutineLoadJob =
dbToNameToRoutineLoadJob.get(dbId);
+ if (labelToRoutineLoadJob.containsKey(name)) {
+ List<RoutineLoadJob> routineLoadJobList =
labelToRoutineLoadJob.get(name);
+ Optional<RoutineLoadJob> optional =
routineLoadJobList.parallelStream()
+ .filter(entity -> entity.getName().equals(name))
+ .filter(entity ->
!entity.getState().isFinalState()).findFirst();
+ if (!optional.isPresent()) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private void addJobToDbToNameToRoutineLoadJob(RoutineLoadJob
routineLoadJob) {
+ if (dbToNameToRoutineLoadJob.containsKey(routineLoadJob.getDbId())) {
+ Map<String, List<RoutineLoadJob>> nameToRoutineLoadJob =
+ dbToNameToRoutineLoadJob.get(routineLoadJob.getDbId());
+ if (nameToRoutineLoadJob.containsKey(routineLoadJob.getName())) {
+
nameToRoutineLoadJob.get(routineLoadJob.getName()).add(routineLoadJob);
+ } else {
+ List<RoutineLoadJob> routineLoadJobList = Lists.newArrayList();
+ routineLoadJobList.add(routineLoadJob);
+ nameToRoutineLoadJob.put(routineLoadJob.getName(),
routineLoadJobList);
+ }
+ } else {
+ List<RoutineLoadJob> routineLoadJobList = Lists.newArrayList();
+ routineLoadJobList.add(routineLoadJob);
+ Map<String, List<RoutineLoadJob>> nameToRoutineLoadJob =
Maps.newConcurrentMap();
+ nameToRoutineLoadJob.put(routineLoadJob.getName(),
routineLoadJobList);
+ dbToNameToRoutineLoadJob.put(routineLoadJob.getDbId(),
nameToRoutineLoadJob);
+ }
+ }
+
+ public void pauseRoutineLoadJob(PauseRoutineLoadStmt pauseRoutineLoadStmt)
throws DdlException, AnalysisException {
+ RoutineLoadJob routineLoadJob =
getJobByName(pauseRoutineLoadStmt.getName());
+ if (routineLoadJob == null) {
+ throw new DdlException("There is not routine load job with name "
+ pauseRoutineLoadStmt.getName());
+ }
+ // check auth
+ if
(!Catalog.getCurrentCatalog().getAuth().checkTblPriv(ConnectContext.get(),
+
routineLoadJob.getDbFullName(),
+
routineLoadJob.getTableName(),
+
PrivPredicate.LOAD)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR,
"LOAD",
+
ConnectContext.get().getQualifiedUser(),
+
ConnectContext.get().getRemoteIP(),
+ routineLoadJob.getTableName());
+ }
+
+ routineLoadJob.pause("User " + ConnectContext.get().getQualifiedUser()
+ "pauses routine load job");
+ }
+
+ public void resumeRoutineLoadJob(ResumeRoutineLoadStmt
resumeRoutineLoadStmt) throws DdlException,
+ AnalysisException {
+ RoutineLoadJob routineLoadJob =
getJobByName(resumeRoutineLoadStmt.getName());
+ if (routineLoadJob == null) {
+ throw new DdlException("There is not routine load job with name "
+ resumeRoutineLoadStmt.getName());
+ }
+ // check auth
+ if
(!Catalog.getCurrentCatalog().getAuth().checkTblPriv(ConnectContext.get(),
+
routineLoadJob.getDbFullName(),
+
routineLoadJob.getTableName(),
+
PrivPredicate.LOAD)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR,
"LOAD",
+
ConnectContext.get().getQualifiedUser(),
+
ConnectContext.get().getRemoteIP(),
+ routineLoadJob.getTableName());
+ }
+ routineLoadJob.resume();
+ }
+
+ public void stopRoutineLoadJob(StopRoutineLoadStmt stopRoutineLoadStmt)
throws DdlException, AnalysisException {
+ RoutineLoadJob routineLoadJob =
getJobByName(stopRoutineLoadStmt.getName());
+ if (routineLoadJob == null) {
+ throw new DdlException("There is not routine load job with name "
+ stopRoutineLoadStmt.getName());
+ }
+ // check auth
+ if
(!Catalog.getCurrentCatalog().getAuth().checkTblPriv(ConnectContext.get(),
+
routineLoadJob.getDbFullName(),
+
routineLoadJob.getTableName(),
+
PrivPredicate.LOAD)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR,
"LOAD",
+
ConnectContext.get().getQualifiedUser(),
+
ConnectContext.get().getRemoteIP(),
+ routineLoadJob.getTableName());
+ }
+ routineLoadJob.stop();
}
public int getSizeOfIdToRoutineLoadTask() {
@@ -191,6 +338,33 @@ public RoutineLoadJob getJob(String jobId) {
return idToRoutineLoadJob.get(jobId);
}
+ public RoutineLoadJob getJobByName(String jobName) {
+ String dbfullName = ConnectContext.get().getDatabase();
+ Database database = Catalog.getCurrentCatalog().getDb(dbfullName);
+ if (database == null) {
+ return null;
+ }
+ readLock();
+ try {
+ Map<String, List<RoutineLoadJob>> nameToRoutineLoadJob =
dbToNameToRoutineLoadJob.get(database.getId());
+ if (nameToRoutineLoadJob == null) {
+ return null;
+ }
+ List<RoutineLoadJob> routineLoadJobList =
nameToRoutineLoadJob.get(jobName);
+ if (routineLoadJobList == null) {
+ return null;
+ }
+ Optional<RoutineLoadJob> optional =
routineLoadJobList.parallelStream()
+ .filter(entity ->
!entity.getState().isFinalState()).findFirst();
+ if (optional.isPresent()) {
+ return null;
+ }
+ return optional.get();
+ } finally {
+ readUnlock();
+ }
+ }
+
public RoutineLoadJob getJobByTaskId(String taskId) throws
MetaNotFoundException {
for (RoutineLoadJob routineLoadJob : idToRoutineLoadJob.values()) {
if (routineLoadJob.containsTask(taskId)) {
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadScheduler.java
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadScheduler.java
index b56cd4e3..db56c086 100644
---
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadScheduler.java
+++
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadScheduler.java
@@ -30,7 +30,7 @@
private static final Logger LOG =
LogManager.getLogger(RoutineLoadScheduler.class);
- private RoutineLoadManager routineLoadManager =
Catalog.getInstance().getRoutineLoadInstance();
+ private RoutineLoadManager routineLoadManager =
Catalog.getInstance().getRoutineLoadManager();
@Override
protected void runOneCycle() {
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
index 33bbd05d..4cec7024 100644
---
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
+++
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskInfo.java
@@ -20,6 +20,7 @@
import org.apache.doris.catalog.Catalog;
import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.LoadException;
import org.apache.doris.task.RoutineLoadTask;
import org.apache.doris.transaction.BeginTransactionException;
import org.apache.doris.transaction.LabelAlreadyExistsException;
@@ -33,7 +34,7 @@
*/
public abstract class RoutineLoadTaskInfo {
- private RoutineLoadManager routineLoadManager =
Catalog.getCurrentCatalog().getRoutineLoadInstance();
+ private RoutineLoadManager routineLoadManager =
Catalog.getCurrentCatalog().getRoutineLoadManager();
protected String id;
protected long txnId;
@@ -73,7 +74,7 @@ public long getTxnId() {
return txnId;
}
- abstract RoutineLoadTask createStreamLoadTask(long beId);
+ abstract RoutineLoadTask createStreamLoadTask(long beId) throws
LoadException;
@Override
public boolean equals(Object obj) {
diff --git
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
index 157ada0c..63484c3d 100644
---
a/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
+++
b/fe/src/main/java/org/apache/doris/load/routineload/RoutineLoadTaskScheduler.java
@@ -41,7 +41,7 @@
private static final Logger LOG =
LogManager.getLogger(RoutineLoadTaskScheduler.class);
- private RoutineLoadManager routineLoadManager =
Catalog.getInstance().getRoutineLoadInstance();
+ private RoutineLoadManager routineLoadManager =
Catalog.getInstance().getRoutineLoadManager();
@Override
protected void runOneCycle() {
diff --git a/fe/src/main/java/org/apache/doris/qe/DdlExecutor.java
b/fe/src/main/java/org/apache/doris/qe/DdlExecutor.java
index 8f93b71c..46eed505 100644
--- a/fe/src/main/java/org/apache/doris/qe/DdlExecutor.java
+++ b/fe/src/main/java/org/apache/doris/qe/DdlExecutor.java
@@ -32,6 +32,7 @@
import org.apache.doris.analysis.CreateFunctionStmt;
import org.apache.doris.analysis.CreateRepositoryStmt;
import org.apache.doris.analysis.CreateRoleStmt;
+import org.apache.doris.analysis.CreateRoutineLoadStmt;
import org.apache.doris.analysis.CreateTableStmt;
import org.apache.doris.analysis.CreateUserStmt;
import org.apache.doris.analysis.CreateViewStmt;
@@ -48,12 +49,15 @@
import org.apache.doris.analysis.LinkDbStmt;
import org.apache.doris.analysis.LoadStmt;
import org.apache.doris.analysis.MigrateDbStmt;
+import org.apache.doris.analysis.PauseRoutineLoadStmt;
import org.apache.doris.analysis.RecoverDbStmt;
import org.apache.doris.analysis.RecoverPartitionStmt;
import org.apache.doris.analysis.RecoverTableStmt;
import org.apache.doris.analysis.RestoreStmt;
+import org.apache.doris.analysis.ResumeRoutineLoadStmt;
import org.apache.doris.analysis.RevokeStmt;
import org.apache.doris.analysis.SetUserPropertyStmt;
+import org.apache.doris.analysis.StopRoutineLoadStmt;
import org.apache.doris.analysis.SyncStmt;
import org.apache.doris.analysis.TruncateTableStmt;
import org.apache.doris.catalog.Catalog;
@@ -108,7 +112,15 @@ public static void execute(Catalog catalog, DdlStmt
ddlStmt) throws DdlException
catalog.getLoadInstance().addLoadJob(loadStmt, jobType,
System.currentTimeMillis());
} else if (ddlStmt instanceof CancelLoadStmt) {
catalog.getLoadInstance().cancelLoadJob((CancelLoadStmt) ddlStmt);
- } else if (ddlStmt instanceof DeleteStmt) {
+ } else if (ddlStmt instanceof CreateRoutineLoadStmt) {
+
catalog.getRoutineLoadManager().addRoutineLoadJob((CreateRoutineLoadStmt)
ddlStmt);
+ } else if (ddlStmt instanceof PauseRoutineLoadStmt) {
+
catalog.getRoutineLoadManager().pauseRoutineLoadJob((PauseRoutineLoadStmt)
ddlStmt);
+ } else if (ddlStmt instanceof ResumeRoutineLoadStmt) {
+
catalog.getRoutineLoadManager().resumeRoutineLoadJob((ResumeRoutineLoadStmt)
ddlStmt);
+ } else if (ddlStmt instanceof StopRoutineLoadStmt) {
+
catalog.getRoutineLoadManager().stopRoutineLoadJob((StopRoutineLoadStmt)
ddlStmt);
+ } else if (ddlStmt instanceof DeleteStmt) {
catalog.getLoadInstance().delete((DeleteStmt) ddlStmt);
} else if (ddlStmt instanceof CreateUserStmt) {
CreateUserStmt stmt = (CreateUserStmt) ddlStmt;
diff --git a/fe/src/main/java/org/apache/doris/qe/ShowExecutor.java
b/fe/src/main/java/org/apache/doris/qe/ShowExecutor.java
index 992c9ae1..007796be 100644
--- a/fe/src/main/java/org/apache/doris/qe/ShowExecutor.java
+++ b/fe/src/main/java/org/apache/doris/qe/ShowExecutor.java
@@ -48,6 +48,7 @@
import org.apache.doris.analysis.ShowRestoreStmt;
import org.apache.doris.analysis.ShowRolesStmt;
import org.apache.doris.analysis.ShowRollupStmt;
+import org.apache.doris.analysis.ShowRoutineLoadStmt;
import org.apache.doris.analysis.ShowSnapshotStmt;
import org.apache.doris.analysis.ShowStmt;
import org.apache.doris.analysis.ShowTableStatusStmt;
@@ -91,6 +92,7 @@
import org.apache.doris.load.LoadErrorHub.HubType;
import org.apache.doris.load.LoadJob;
import org.apache.doris.load.LoadJob.JobState;
+import org.apache.doris.load.routineload.RoutineLoadJob;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.system.Backend;
import org.apache.doris.system.SystemInfoService;
@@ -163,6 +165,8 @@ public ShowResultSet execute() throws AnalysisException {
handleShowLoad();
} else if (stmt instanceof ShowLoadWarningsStmt) {
handleShowLoadWarnings();
+ } else if (stmt instanceof ShowRoutineLoadStmt) {
+ handleShowRoutineLoad();
} else if (stmt instanceof ShowDeleteStmt) {
handleShowDelete();
} else if (stmt instanceof ShowAlterStmt) {
@@ -308,7 +312,7 @@ private void handleShowMigrations() throws
AnalysisException {
for (BaseParam param : infos) {
final int percent = (int) (param.getFloatParam(0) * 100f);
rows.add(Lists.newArrayList(param.getStringParam(0),
param.getStringParam(1), param.getStringParam(2),
- String.valueOf(percent + "%")));
+ String.valueOf(percent + "%")));
}
resultSet = new ShowResultSet(showStmt.getMetaData(), rows);
@@ -489,7 +493,7 @@ private void handleShowCreateTable() throws
AnalysisException {
} else {
if (showStmt.isView()) {
ErrorReport.reportAnalysisException(ErrorCode.ERR_WRONG_OBJECT,
showStmt.getDb(),
- showStmt.getTable(), "VIEW");
+ showStmt.getTable(),
"VIEW");
}
rows.add(Lists.newArrayList(table.getName(),
createTableStmt.get(0)));
resultSet = new ShowResultSet(showStmt.getMetaData(), rows);
@@ -535,22 +539,22 @@ private void handleShowColumn() throws AnalysisException {
// Field Type Collation Null Key Default Extra
// Privileges Comment
rows.add(Lists.newArrayList(columnName,
- columnType,
- "",
- isAllowNull,
- isKey,
- defaultValue,
- aggType,
- "",
- col.getComment()));
+ columnType,
+ "",
+ isAllowNull,
+ isKey,
+ defaultValue,
+ aggType,
+ "",
+ col.getComment()));
} else {
// Field Type Null Key Default Extra
rows.add(Lists.newArrayList(columnName,
- columnType,
- isAllowNull,
- isKey,
- defaultValue,
- aggType));
+ columnType,
+ isAllowNull,
+ isKey,
+ defaultValue,
+ aggType));
}
}
}
@@ -592,7 +596,7 @@ private void handleHelp() {
}
}
if (topic != null) {
- resultSet = new ShowResultSet(helpStmt.getMetaData(),
Lists.<List<String>> newArrayList(
+ resultSet = new ShowResultSet(helpStmt.getMetaData(),
Lists.<List<String>>newArrayList(
Lists.newArrayList(topic.getName(),
topic.getDescription(), topic.getExample())));
} else {
List<String> categories = module.listCategoryByName(mark);
@@ -602,7 +606,7 @@ private void handleHelp() {
} else if (categories.size() > 1) {
// Send category list
resultSet = new ShowResultSet(helpStmt.getCategoryMetaData(),
- Lists.<List<String>> newArrayList(categories));
+
Lists.<List<String>>newArrayList(categories));
} else {
// Send topic list and sub-category list
List<List<String>> rows = Lists.newArrayList();
@@ -704,8 +708,8 @@ private void handleShowLoadWarnings() throws
AnalysisException {
if
(!Catalog.getCurrentCatalog().getAuth().checkDbPriv(ConnectContext.get(),
db.getFullName(),
PrivPredicate.SHOW)) {
ErrorReport.reportAnalysisException(ErrorCode.ERR_DB_ACCESS_DENIED,
-
ConnectContext.get().getQualifiedUser(),
- db.getFullName());
+
ConnectContext.get().getQualifiedUser(),
+ db.getFullName());
}
} else {
for (String tblName : tableNames) {
@@ -780,10 +784,45 @@ private void
handleShowLoadWarningsFromURL(ShowLoadWarningsStmt showWarningsStmt
throw new AnalysisException(
"failed to get error log from url: " + url + ". reason: "
+ e.getMessage());
}
-
+
resultSet = new ShowResultSet(showWarningsStmt.getMetaData(), rows);
}
+ private void handleShowRoutineLoad() throws AnalysisException {
+ ShowRoutineLoadStmt showRoutineLoadStmt = (ShowRoutineLoadStmt) stmt;
+ // if job exists
+ RoutineLoadJob routineLoadJob =
+
Catalog.getCurrentCatalog().getRoutineLoadManager().getJobByName(showRoutineLoadStmt.getName());
+ if (routineLoadJob == null) {
+ throw new AnalysisException("There is no routine load job with id
" + showRoutineLoadStmt.getName());
+ }
+
+ // check auth
+ if
(!Catalog.getCurrentCatalog().getAuth().checkTblPriv(ConnectContext.get(),
+
routineLoadJob.getDbFullName(),
+
routineLoadJob.getTableName(),
+
PrivPredicate.LOAD)) {
+
ErrorReport.reportAnalysisException(ErrorCode.ERR_TABLEACCESS_DENIED_ERROR,
"LOAD",
+
ConnectContext.get().getQualifiedUser(),
+
ConnectContext.get().getRemoteIP(),
+ routineLoadJob.getTableName());
+ }
+
+ // get routine load info
+ List<List<String>> rows = Lists.newArrayList();
+ List<String> row = Lists.newArrayList();
+ row.add(routineLoadJob.getId());
+ row.add(routineLoadJob.getName());
+ row.add(String.valueOf(routineLoadJob.getDbId()));
+ row.add(String.valueOf(routineLoadJob.getTableId()));
+ row.add(routineLoadJob.getPartitions());
+ row.add(routineLoadJob.getState().name());
+ row.add(routineLoadJob.getDesiredConcurrentNumber());
+ row.add(routineLoadJob.getProgress().toString());
+
+ resultSet = new ShowResultSet(showRoutineLoadStmt.getMetaData(), rows);
+ }
+
// Show user property statement
private void handleShowUserProperty() throws AnalysisException {
ShowUserPropertyStmt showStmt = (ShowUserPropertyStmt) stmt;
diff --git a/fe/src/main/java/org/apache/doris/task/KafkaRoutineLoadTask.java
b/fe/src/main/java/org/apache/doris/task/KafkaRoutineLoadTask.java
index 7c0d84ba..92212738 100644
--- a/fe/src/main/java/org/apache/doris/task/KafkaRoutineLoadTask.java
+++ b/fe/src/main/java/org/apache/doris/task/KafkaRoutineLoadTask.java
@@ -17,13 +17,9 @@
package org.apache.doris.task;
-import org.apache.doris.load.routineload.KafkaProgress;
-import org.apache.doris.load.routineload.KafkaTaskInfo;
-import org.apache.doris.load.routineload.RoutineLoadJob;
+import org.apache.doris.load.routineload.LoadDataSourceType;
import org.apache.doris.thrift.TResourceInfo;
-import org.apache.doris.thrift.TTaskType;
-import java.util.HashMap;
import java.util.Map;
@@ -32,14 +28,10 @@
private Map<Integer, Long> partitionIdToOffset;
public KafkaRoutineLoadTask(TResourceInfo resourceInfo, long backendId,
- long dbId, long tableId, long partitionId,
long indexId, long tabletId,
- String columns, String where, String
columnSeparator,
- KafkaTaskInfo kafkaTaskInfo, KafkaProgress
kafkaProgress, long txnId) {
- super(resourceInfo, backendId, TTaskType.STREAM_LOAD, dbId, tableId,
partitionId, indexId, tabletId,
- kafkaTaskInfo.getId(), columns, where, columnSeparator,
RoutineLoadJob.DataSourceType.KAFKA, txnId);
- this.partitionIdToOffset = new HashMap<>();
- kafkaTaskInfo.getPartitions().parallelStream().forEach(entity ->
- partitionIdToOffset.put(entity,
kafkaProgress.getPartitionIdToOffset().get(entity)));
+ long dbId, long tableId, String taskId,
+ long txnId, Map<Integer, Long>
partitionIdToOffset) {
+ super(resourceInfo, backendId, dbId, tableId, taskId,
LoadDataSourceType.KAFKA, txnId);
+ this.partitionIdToOffset = partitionIdToOffset;
}
public Map<Integer, Long> getPartitionIdToOffset() {
diff --git a/fe/src/main/java/org/apache/doris/task/RoutineLoadTask.java
b/fe/src/main/java/org/apache/doris/task/RoutineLoadTask.java
index 03e1cb83..5e1decde 100644
--- a/fe/src/main/java/org/apache/doris/task/RoutineLoadTask.java
+++ b/fe/src/main/java/org/apache/doris/task/RoutineLoadTask.java
@@ -18,10 +18,9 @@
package org.apache.doris.task;
import org.apache.doris.catalog.Catalog;
-import org.apache.doris.catalog.CatalogIdGenerator;
-import org.apache.doris.common.SystemIdGenerator;
-import org.apache.doris.load.routineload.RoutineLoadJob;
-import org.apache.doris.task.AgentTask;
+import org.apache.doris.load.routineload.LoadDataSourceType;
+import org.apache.doris.common.LoadException;
+import org.apache.doris.load.RoutineLoadDesc;
import org.apache.doris.thrift.TResourceInfo;
import org.apache.doris.thrift.TTaskType;
@@ -29,23 +28,26 @@
private String id;
private long txnId;
- private String columns;
- private String where;
- private String columnSeparator;
- private RoutineLoadJob.DataSourceType dataSourceType;
+ private RoutineLoadDesc routineLoadDesc;
+ private LoadDataSourceType dataSourceType;
- public RoutineLoadTask(TResourceInfo resourceInfo, long backendId,
TTaskType taskType,
- long dbId, long tableId, long partitionId, long
indexId, long tabletId, String id,
- String columns, String where, String
columnSeparator,
- RoutineLoadJob.DataSourceType dataSourceType, long
txnId) {
- super(resourceInfo, backendId, taskType, dbId, tableId, partitionId,
indexId, tabletId,
- Catalog.getCurrentCatalog().getNextId());
+ public RoutineLoadTask(TResourceInfo resourceInfo, long backendId, long
dbId, long tableId, String id,
+ LoadDataSourceType dataSourceType, long txnId) {
+ super(resourceInfo, backendId, TTaskType.STREAM_LOAD, dbId, tableId,
0L, 0L, 0L,
+ Catalog.getCurrentCatalog().getNextId());
this.id = id;
this.txnId = txnId;
- this.columns = columns;
- this.where = where;
- this.columnSeparator = columnSeparator;
this.dataSourceType = dataSourceType;
}
+
+ public void setRoutineLoadDesc(RoutineLoadDesc routineLoadDesc) throws
LoadException {
+ if (this.routineLoadDesc != null) {
+ throw new LoadException("Column separator has been initialized");
+ }
+ this.routineLoadDesc = new
RoutineLoadDesc(routineLoadDesc.getColumnSeparator(),
+
routineLoadDesc.getColumnsInfo(),
+
routineLoadDesc.getWherePredicate(),
+ null);
+ }
}
diff --git a/fe/src/main/jflex/sql_scanner.flex
b/fe/src/main/jflex/sql_scanner.flex
index 425bdda8..d7d31650 100644
--- a/fe/src/main/jflex/sql_scanner.flex
+++ b/fe/src/main/jflex/sql_scanner.flex
@@ -192,6 +192,10 @@ import org.apache.doris.common.util.SqlUtils;
keywordMap.put("like", new Integer(SqlParserSymbols.KW_LIKE));
keywordMap.put("limit", new Integer(SqlParserSymbols.KW_LIMIT));
keywordMap.put("load", new Integer(SqlParserSymbols.KW_LOAD));
+ keywordMap.put("routine", new Integer(SqlParserSymbols.KW_ROUTINE));
+ keywordMap.put("pause", new Integer(SqlParserSymbols.KW_PAUSE));
+ keywordMap.put("resume", new Integer(SqlParserSymbols.KW_RESUME));
+ keywordMap.put("stop", new Integer(SqlParserSymbols.KW_STOP));
keywordMap.put("local", new Integer(SqlParserSymbols.KW_LOCAL));
keywordMap.put("location", new Integer(SqlParserSymbols.KW_LOCATION));
keywordMap.put("max", new Integer(SqlParserSymbols.KW_MAX));
diff --git
a/fe/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java
b/fe/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java
index 00d42d2d..c3817354 100644
---
a/fe/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java
+++
b/fe/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java
@@ -25,11 +25,13 @@
import mockit.MockUp;
import mockit.Mocked;
import mockit.Verifications;
+import org.apache.doris.load.RoutineLoadDesc;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.MetaNotFoundException;
import org.apache.doris.common.SystemIdGenerator;
+import org.apache.doris.qe.ConnectContext;
import org.apache.doris.system.SystemInfoService;
import org.apache.doris.thrift.TResourceInfo;
import org.apache.doris.transaction.BeginTransactionException;
@@ -45,20 +47,24 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.Map;
-import java.util.Queue;
public class KafkaRoutineLoadJobTest {
private static final int DEFAULT_TASK_TIMEOUT_SECONDS = 10;
+ @Mocked
+ ConnectContext connectContext;
+ @Mocked
+ TResourceInfo tResourceInfo;
+
@Test
public void testBeNumMin(@Mocked KafkaConsumer kafkaConsumer,
@Injectable PartitionInfo partitionInfo1,
@Injectable PartitionInfo partitionInfo2,
@Mocked Catalog catalog,
@Mocked SystemInfoService systemInfoService,
- @Mocked Database database) throws
MetaNotFoundException {
+ @Mocked Database database,
+ @Mocked RoutineLoadDesc routineLoadDesc) throws
MetaNotFoundException {
List<PartitionInfo> partitionInfoList = new ArrayList<>();
partitionInfoList.add(partitionInfo1);
partitionInfoList.add(partitionInfo2);
@@ -80,13 +86,15 @@ public void testBeNumMin(@Mocked KafkaConsumer
kafkaConsumer,
result = clusterName;
systemInfoService.getClusterBackendIds(clusterName, true);
result = beIds;
+ connectContext.toResourceCtx();
+ result = tResourceInfo;
}
};
- KafkaRoutineLoadJob kafkaRoutineLoadJob = new KafkaRoutineLoadJob("1",
"kafka_routine_load_job", "miaoling", 1L,
- 1L, "1L", "v1", "", "", 3,
- RoutineLoadJob.JobState.NEED_SCHEDULER,
RoutineLoadJob.DataSourceType.KAFKA, 0, new TResourceInfo(),
- "", "", null);
+ KafkaRoutineLoadJob kafkaRoutineLoadJob =
+ new KafkaRoutineLoadJob("1", "kafka_routine_load_job", 1L,
+ 1L, routineLoadDesc ,3, 0,
+ "", "", null);
Assert.assertEquals(1,
kafkaRoutineLoadJob.calculateCurrentConcurrentTaskNum());
}
@@ -94,20 +102,28 @@ public void testBeNumMin(@Mocked KafkaConsumer
kafkaConsumer,
@Test
public void testDivideRoutineLoadJob(@Injectable GlobalTransactionMgr
globalTransactionMgr,
@Mocked Catalog catalog,
- @Injectable RoutineLoadManager
routineLoadManager)
+ @Injectable RoutineLoadManager
routineLoadManager,
+ @Mocked RoutineLoadDesc
routineLoadDesc)
throws BeginTransactionException, LabelAlreadyExistsException,
AnalysisException {
- KafkaRoutineLoadJob kafkaRoutineLoadJob = new KafkaRoutineLoadJob("1",
"kafka_routine_load_job", "miaoling", 1L,
- 1L, "1L", "v1", "", "", 3,
- RoutineLoadJob.JobState.NEED_SCHEDULER,
RoutineLoadJob.DataSourceType.KAFKA, 0, new TResourceInfo(),
- "", "", null);
+ new Expectations(){
+ {
+ connectContext.toResourceCtx();
+ result = tResourceInfo;
+ }
+ };
+
+ KafkaRoutineLoadJob kafkaRoutineLoadJob =
+ new KafkaRoutineLoadJob("1", "kafka_routine_load_job", 1L,
+ 1L, routineLoadDesc , 3, 0,
+ "", "", null);
new Expectations() {
{
globalTransactionMgr.beginTransaction(anyLong, anyString,
anyString,
- TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK,
(KafkaRoutineLoadJob) any);
+
TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK, (KafkaRoutineLoadJob)
any);
result = 0L;
- catalog.getRoutineLoadInstance();
+ catalog.getRoutineLoadManager();
result = routineLoadManager;
}
};
@@ -134,20 +150,28 @@ public void testDivideRoutineLoadJob(@Injectable
GlobalTransactionMgr globalTran
@Test
public void testProcessTimeOutTasks(@Injectable GlobalTransactionMgr
globalTransactionMgr,
@Mocked Catalog catalog,
- @Injectable RoutineLoadManager
routineLoadManager)
+ @Injectable RoutineLoadManager
routineLoadManager,
+ @Mocked RoutineLoadDesc
routineLoadDesc)
throws AnalysisException, LabelAlreadyExistsException,
BeginTransactionException {
- RoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob("1",
"kafka_routine_load_job", "miaoling", 1L,
- 1L, "1L", "v1", "", "", 3,
- RoutineLoadJob.JobState.NEED_SCHEDULER,
RoutineLoadJob.DataSourceType.KAFKA, 0, new TResourceInfo(),
- "", "", null);
+ new Expectations(){
+ {
+ connectContext.toResourceCtx();
+ result = tResourceInfo;
+ }
+ };
+
+ RoutineLoadJob routineLoadJob =
+ new KafkaRoutineLoadJob("1", "kafka_routine_load_job", 1L,
+ 1L, routineLoadDesc ,3, 0,
+ "", "", null);
new Expectations() {
{
globalTransactionMgr.beginTransaction(anyLong, anyString,
anyString,
- TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK,
routineLoadJob);
+
TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK, routineLoadJob);
result = 0L;
- catalog.getRoutineLoadInstance();
+ catalog.getRoutineLoadManager();
result = routineLoadManager;
}
};
diff --git
a/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java
b/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java
index a9e0ff43..37f21397 100644
---
a/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java
+++
b/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java
@@ -21,36 +21,35 @@
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Injectable;
-import mockit.Mock;
-import mockit.MockUp;
import mockit.Mocked;
+import org.apache.doris.load.RoutineLoadDesc;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
import org.apache.doris.common.LoadException;
import org.apache.doris.common.MetaNotFoundException;
+import org.apache.doris.qe.ConnectContext;
import org.apache.doris.system.SystemInfoService;
import org.apache.doris.thrift.TResourceInfo;
-import com.google.common.collect.Lists;
-
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
-import mockit.Deencapsulation;
-import mockit.Expectations;
-import mockit.Injectable;
-import mockit.Mocked;
-
public class RoutineLoadSchedulerTest {
+ @Mocked
+ ConnectContext connectContext;
+ @Mocked
+ TResourceInfo tResourceInfo;
+
@Test
public void testNormalRunOneCycle(@Mocked Catalog catalog,
@Injectable RoutineLoadManager
routineLoadManager,
@Injectable SystemInfoService
systemInfoService,
- @Injectable Database database)
+ @Injectable Database database,
+ @Injectable RoutineLoadDesc
routineLoadDesc)
throws LoadException, MetaNotFoundException {
String clusterName = "cluster1";
List<Long> beIds = Lists.newArrayList();
@@ -61,10 +60,18 @@ public void testNormalRunOneCycle(@Mocked Catalog catalog,
partitions.add(100);
partitions.add(200);
partitions.add(300);
- RoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob("1",
"kafka_routine_load_job", "miaoling", 1L,
- 1L, "1L", "v1", "", "", 3,
- RoutineLoadJob.JobState.NEED_SCHEDULER,
RoutineLoadJob.DataSourceType.KAFKA, 0, new TResourceInfo(),
- "", "", null);
+
+ new Expectations(){
+ {
+ connectContext.toResourceCtx();
+ result = tResourceInfo;
+ }
+ };
+
+ RoutineLoadJob routineLoadJob =
+ new KafkaRoutineLoadJob("1", "kafka_routine_load_job", 1L,
+ 1L, routineLoadDesc ,3, 0,
+ "", "", null);
routineLoadJob.setState(RoutineLoadJob.JobState.NEED_SCHEDULER);
List<RoutineLoadJob> routineLoadJobList = new ArrayList<>();
routineLoadJobList.add(routineLoadJob);
@@ -74,7 +81,7 @@ public void testNormalRunOneCycle(@Mocked Catalog catalog,
new Expectations() {
{
- catalog.getRoutineLoadInstance();
+ catalog.getRoutineLoadManager();
result = routineLoadManager;
routineLoadManager.getRoutineLoadJobByState(RoutineLoadJob.JobState.NEED_SCHEDULER);
result = routineLoadJobList;
diff --git
a/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java
b/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java
index e3e5eec5..48f49fe5 100644
---
a/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java
+++
b/fe/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java
@@ -24,6 +24,8 @@
import mockit.Injectable;
import mockit.Mocked;
import mockit.Verifications;
+import org.apache.doris.analysis.LoadColumnsInfo;
+import org.apache.doris.load.RoutineLoadDesc;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.LoadException;
@@ -52,7 +54,9 @@
@Test
public void testRunOneCycle(@Injectable KafkaRoutineLoadJob
kafkaRoutineLoadJob1,
- @Injectable KafkaRoutineLoadJob
routineLoadJob) throws LoadException,
+ @Injectable KafkaRoutineLoadJob routineLoadJob,
+ @Injectable RoutineLoadDesc routineLoadDesc,
+ @Injectable LoadColumnsInfo loadColumnsInfo)
throws LoadException,
MetaNotFoundException, AnalysisException,
LabelAlreadyExistsException, BeginTransactionException {
long beId = 100L;
@@ -81,7 +85,7 @@ public void testRunOneCycle(@Injectable KafkaRoutineLoadJob
kafkaRoutineLoadJob1
{
Catalog.getInstance();
result = catalog;
- catalog.getRoutineLoadInstance();
+ catalog.getRoutineLoadManager();
result = routineLoadManager;
Catalog.getCurrentCatalog();
result = catalog;
@@ -95,9 +99,9 @@ public void testRunOneCycle(@Injectable KafkaRoutineLoadJob
kafkaRoutineLoadJob1
result = 1L;
kafkaRoutineLoadJob1.getTableId();
result = 1L;
- kafkaRoutineLoadJob1.getColumns();
- result = "columns";
- kafkaRoutineLoadJob1.getColumnSeparator();
+ routineLoadDesc.getColumnsInfo();
+ result = loadColumnsInfo;
+ routineLoadDesc.getColumnSeparator();
result = "";
kafkaRoutineLoadJob1.getProgress();
result = kafkaProgress;
@@ -115,10 +119,7 @@ public void testRunOneCycle(@Injectable
KafkaRoutineLoadJob kafkaRoutineLoadJob1
KafkaRoutineLoadTask kafkaRoutineLoadTask = new
KafkaRoutineLoadTask(kafkaRoutineLoadJob1.getResourceInfo(),
beId, kafkaRoutineLoadJob1.getDbId(),
kafkaRoutineLoadJob1.getTableId(),
- 0L, 0L, 0L, kafkaRoutineLoadJob1.getColumns(),
kafkaRoutineLoadJob1.getWhere(),
- kafkaRoutineLoadJob1.getColumnSeparator(),
- (KafkaTaskInfo) routineLoadTaskInfo1,
- (KafkaProgress) kafkaRoutineLoadJob1.getProgress(), 0L);
+ "", 0L, partitionIdToOffset);
//
// new Expectations() {
// {
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]