From 57607406041181a7632fad6988e006b64b3132b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Sat, 24 Apr 2021 16:25:11 +0800 Subject: [PATCH 01/25] =?UTF-8?q?update:=E6=B7=BB=E5=8A=A0=E5=AF=B9?= =?UTF-8?q?=E8=BE=BE=E6=A2=A6=E6=95=B0=E6=8D=AE=E5=BA=93=E7=9A=84=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../datasource/exec/dm/DmInsertExecutor.java | 99 +++ .../exec/mysql/MySQLInsertExecutor.java | 1 + .../sql/struct/cache/DmTableMetaCache.java | 165 ++++ .../undo/dm/DmUndoDeleteExecutor.java | 79 ++ .../undo/dm/DmUndoExecutorHolder.java | 46 + .../undo/dm/DmUndoInsertExecutor.java | 86 ++ .../datasource/undo/dm/DmUndoLogManager.java | 100 +++ .../undo/dm/DmUndoUpdateExecutor.java | 80 ++ .../undo/dm/keyword/DmKeywordChecker.java | 827 ++++++++++++++++++ ...io.seata.rm.datasource.exec.InsertExecutor | 3 +- ...ta.rm.datasource.sql.struct.TableMetaCache | 3 +- ...io.seata.rm.datasource.undo.KeywordChecker | 3 +- ...eata.rm.datasource.undo.UndoExecutorHolder | 3 +- ...io.seata.rm.datasource.undo.UndoLogManager | 3 +- .../seata/sqlparser/util/JdbcConstants.java | 2 + .../sqlparser/druid/dm/BaseDmRecognizer.java | 85 ++ .../druid/dm/DmDeleteRecognizer.java | 109 +++ .../druid/dm/DmInsertRecognizer.java | 139 +++ .../druid/dm/DmOperateRecognizerHolder.java | 54 ++ .../druid/dm/DmSelectForUpdateRecognizer.java | 106 +++ .../druid/dm/DmUpdateRecognizer.java | 150 ++++ ...sqlparser.druid.SQLOperateRecognizerHolder | 3 +- 22 files changed, 2140 insertions(+), 6 deletions(-) create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/exec/dm/DmInsertExecutor.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoExecutorHolder.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoUpdateExecutor.java create mode 100644 rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java create mode 100644 sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/exec/dm/DmInsertExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/exec/dm/DmInsertExecutor.java new file mode 100644 index 00000000000..7e3d1cac5d3 --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/exec/dm/DmInsertExecutor.java @@ -0,0 +1,99 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.exec.dm; + +import io.seata.common.exception.NotSupportYetException; +import io.seata.common.loader.LoadLevel; +import io.seata.common.loader.Scope; +import io.seata.rm.datasource.StatementProxy; +import io.seata.rm.datasource.exec.BaseInsertExecutor; +import io.seata.rm.datasource.exec.StatementCallback; +import io.seata.sqlparser.SQLRecognizer; +import io.seata.sqlparser.struct.Null; +import io.seata.sqlparser.struct.Sequenceable; +import io.seata.sqlparser.struct.SqlMethodExpr; +import io.seata.sqlparser.struct.SqlSequenceExpr; +import io.seata.sqlparser.util.JdbcConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * The type DM insert executor. + * + * @author chengxiaoxiao + */ +@LoadLevel(name = JdbcConstants.DM, scope = Scope.PROTOTYPE) +public class DmInsertExecutor extends BaseInsertExecutor implements Sequenceable { + + private static final Logger LOGGER = LoggerFactory.getLogger(DmInsertExecutor.class); + + /** + * Instantiates a new Abstract dml base executor. + * + * @param statementProxy the statement proxy + * @param statementCallback the statement callback + * @param sqlRecognizer the sql recognizer + */ + public DmInsertExecutor(StatementProxy statementProxy, StatementCallback statementCallback, + SQLRecognizer sqlRecognizer) { + super(statementProxy, statementCallback, sqlRecognizer); + } + + @Override + public Map> getPkValues() throws SQLException { + Map> pkValuesMap = null; + Boolean isContainsPk = containsPK(); + //when there is only one pk in the table + if (isContainsPk) { + pkValuesMap = getPkValuesByColumn(); + } + else if (containsColumns()) { + String columnName = getTableMeta().getPrimaryKeyOnlyName().get(0); + pkValuesMap = Collections.singletonMap(columnName, getGeneratedKeys()); + } + else { + pkValuesMap = getPkValuesByColumn(); + } + return pkValuesMap; + } + + @Override + public Map> getPkValuesByColumn() throws SQLException { + Map> pkValuesMap = parsePkValuesFromStatement(); + String pkKey = pkValuesMap.keySet().iterator().next(); + List pkValues = pkValuesMap.get(pkKey); + + if (!pkValues.isEmpty() && pkValues.get(0) instanceof SqlSequenceExpr) { + pkValuesMap.put(pkKey,getPkValuesBySequence((SqlSequenceExpr) pkValues.get(0))); + } else if (pkValues.size() == 1 && pkValues.get(0) instanceof SqlMethodExpr) { + pkValuesMap.put(pkKey,getGeneratedKeys()); + } else if (pkValues.size() == 1 && pkValues.get(0) instanceof Null) { + throw new NotSupportYetException("dm not support null"); + } + + return pkValuesMap; + } + + @Override + public String getSequenceSql(SqlSequenceExpr expr) { + return "SELECT " + expr.getSequence() + ".currval"; + } +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/exec/mysql/MySQLInsertExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/exec/mysql/MySQLInsertExecutor.java index 710ff546089..89114fd133c 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/exec/mysql/MySQLInsertExecutor.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/exec/mysql/MySQLInsertExecutor.java @@ -226,4 +226,5 @@ protected boolean canAutoIncrement(Map primaryKeyMap) { } return false; } + } diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java new file mode 100644 index 00000000000..48779cb3d01 --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java @@ -0,0 +1,165 @@ +package io.seata.rm.datasource.sql.struct.cache; + +import io.seata.common.exception.ShouldNeverHappenException; +import io.seata.common.loader.LoadLevel; +import io.seata.common.util.StringUtils; +import io.seata.rm.datasource.sql.struct.ColumnMeta; +import io.seata.rm.datasource.sql.struct.IndexMeta; +import io.seata.rm.datasource.sql.struct.IndexType; +import io.seata.rm.datasource.sql.struct.TableMeta; +import io.seata.sqlparser.util.JdbcConstants; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * The type Table meta cache. + * + * @author chengxiaoxiao + */ +@LoadLevel(name = JdbcConstants.DM) +public class DmTableMetaCache extends OracleTableMetaCache { + public static class TableNameMeta { + private String schema; + private String tableName; + + public TableNameMeta(String schema, String tableName) { + this.schema = schema; + this.tableName = tableName; + } + + public String getSchema() { + return schema; + } + + public String getTableName() { + return tableName; + } + } + + @Override + protected TableMeta fetchSchema(Connection connection, String tableName) throws SQLException { + try { + return resultSetMetaToSchema(connection.getMetaData(), tableName); + } catch (SQLException sqlEx) { + throw sqlEx; + } catch (Exception e) { + throw new SQLException(String.format("Failed to fetch schema of %s", tableName), e); + } + } + + protected TableMeta resultSetMetaToSchema(DatabaseMetaData dbmd, String tableName) throws SQLException { + TableMeta result = new TableMeta(); + result.setTableName(tableName); + + TableNameMeta tableNameMeta = toTableNameMeta(tableName, dbmd.getUserName()); + try (ResultSet rsColumns = dbmd.getColumns("", tableNameMeta.getSchema(), tableNameMeta.getTableName(), "%"); + ResultSet rsIndex = dbmd.getIndexInfo(null, tableNameMeta.getSchema(), tableNameMeta.getTableName(), false, true); + ResultSet rsPrimary = dbmd.getPrimaryKeys(null, tableNameMeta.getSchema(), tableNameMeta.getTableName())) { + processColumns(result, rsColumns); + + processIndexs(result, rsIndex); + + processPrimaries(result, rsPrimary); + + if (result.getAllIndexes().isEmpty()) { + throw new ShouldNeverHappenException(String.format("Could not found any index in the table: %s", tableName)); + } + } + + return result; + } + + protected TableNameMeta toTableNameMeta(String tableName, String username) { + String[] schemaTable = tableName.split("\\."); + + String schema = schemaTable.length > 1 ? schemaTable[0] : username; + if (schema != null) { + schema = schema.contains("\"") ? schema.replace("\"", "") : schema.toUpperCase(); + } + + tableName = schemaTable.length > 1 ? schemaTable[1] : tableName; + tableName = tableName.contains("\"") ? tableName.replace("\"", "") : tableName.toUpperCase(); + + return new TableNameMeta(schema, tableName); + } + + protected void processColumns(TableMeta tableMeta, ResultSet rs) throws SQLException { + while (rs.next()) { + ColumnMeta col = toColumnMeta(rs); + tableMeta.getAllColumns().put(col.getColumnName(), col); + } + } + + protected void processIndexs(TableMeta tableMeta, ResultSet rs) throws SQLException { + while (rs.next()) { + String indexName = rs.getString("INDEX_NAME"); + if (StringUtils.isNullOrEmpty(indexName)) { + continue; + } + + String colName = rs.getString("COLUMN_NAME"); + ColumnMeta col = tableMeta.getAllColumns().get(colName); + if (tableMeta.getAllIndexes().containsKey(indexName)) { + IndexMeta index = tableMeta.getAllIndexes().get(indexName); + index.getValues().add(col); + continue; + } + + tableMeta.getAllIndexes().put(indexName, toIndexMeta(rs, indexName, col)); + } + } + + protected void processPrimaries(TableMeta tableMeta, ResultSet rs) throws SQLException { + while (rs.next()) { + String colName = rs.getString("COLUMN_NAME"); + for (IndexMeta i : tableMeta.getAllIndexes().values()) { + i.getValues().stream() + .filter(c -> colName.equals(c.getColumnName())) + .forEach(c -> i.setIndextype(IndexType.PRIMARY)); + } + } + } + + protected ColumnMeta toColumnMeta(ResultSet rs) throws SQLException { + ColumnMeta result = new ColumnMeta(); + result.setTableCat(rs.getString("TABLE_CAT")); + result.setTableSchemaName(rs.getString("TABLE_SCHEM")); + result.setTableName(rs.getString("TABLE_NAME")); + result.setColumnName(rs.getString("COLUMN_NAME")); + result.setDataType(rs.getInt("DATA_TYPE")); + result.setDataTypeName(rs.getString("TYPE_NAME")); + result.setColumnSize(rs.getInt("COLUMN_SIZE")); + result.setDecimalDigits(rs.getInt("DECIMAL_DIGITS")); + result.setNumPrecRadix(rs.getInt("NUM_PREC_RADIX")); + result.setNullAble(rs.getInt("NULLABLE")); + result.setRemarks(rs.getString("REMARKS")); + result.setColumnDef(rs.getString("COLUMN_DEF")); + result.setSqlDataType(rs.getInt("SQL_DATA_TYPE")); + result.setSqlDatetimeSub(rs.getInt("SQL_DATETIME_SUB")); + result.setCharOctetLength(rs.getInt("CHAR_OCTET_LENGTH")); + result.setOrdinalPosition(rs.getInt("ORDINAL_POSITION")); + result.setIsNullAble(rs.getString("IS_NULLABLE")); + return result; + } + + protected IndexMeta toIndexMeta(ResultSet rs, String indexName, ColumnMeta columnMeta) throws SQLException { + IndexMeta result = new IndexMeta(); + result.setIndexName(indexName); + result.setNonUnique(rs.getBoolean("NON_UNIQUE")); + result.setIndexQualifier(rs.getString("INDEX_QUALIFIER")); + result.setType(rs.getShort("TYPE")); + result.setOrdinalPosition(rs.getShort("ORDINAL_POSITION")); + result.setAscOrDesc(rs.getString("ASC_OR_DESC")); + result.setCardinality(rs.getInt("CARDINALITY")); + result.getValues().add(columnMeta); + if (!result.isNonUnique()) { + result.setIndextype(IndexType.UNIQUE); + } else { + result.setIndextype(IndexType.NORMAL); + } + return result; + } +} \ No newline at end of file diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java new file mode 100644 index 00000000000..c2496a72c7c --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java @@ -0,0 +1,79 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm; + +import io.seata.common.exception.ShouldNeverHappenException; +import io.seata.common.util.CollectionUtils; +import io.seata.rm.datasource.ColumnUtils; +import io.seata.rm.datasource.sql.struct.Field; +import io.seata.rm.datasource.sql.struct.Row; +import io.seata.rm.datasource.sql.struct.TableRecords; +import io.seata.rm.datasource.undo.AbstractUndoExecutor; +import io.seata.rm.datasource.undo.SQLUndoLog; +import io.seata.sqlparser.util.JdbcConstants; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The type oracle undo delete executor. + * + * @author chengxiaoxiao + */ +public class DmUndoDeleteExecutor extends AbstractUndoExecutor { + + /** + * INSERT INTO a (x, y, z, pk) VALUES (?, ?, ?, ?) + */ + private static final String INSERT_SQL_TEMPLATE = "INSERT INTO %s (%s) VALUES (%s)"; + + /** + * Instantiates a new oracle undo delete executor. + * + * @param sqlUndoLog the sql undo log + */ + public DmUndoDeleteExecutor(SQLUndoLog sqlUndoLog) { + super(sqlUndoLog); + } + + @Override + protected String buildUndoSQL() { + TableRecords beforeImage = sqlUndoLog.getBeforeImage(); + List beforeImageRows = beforeImage.getRows(); + if (CollectionUtils.isEmpty(beforeImageRows)) { + throw new ShouldNeverHappenException("Invalid UNDO LOG"); + } + Row row = beforeImageRows.get(0); + List fields = new ArrayList<>(row.nonPrimaryKeys()); + fields.addAll(getOrderedPkList(beforeImage,row,JdbcConstants.DM)); + + // delete sql undo log before image all field come from table meta, need add escape. + // see BaseTransactionalExecutor#buildTableRecords + String insertColumns = fields.stream() + .map(field -> ColumnUtils.addEscape(field.getName(), JdbcConstants.DM)) + .collect(Collectors.joining(", ")); + String insertValues = fields.stream().map(field -> "?") + .collect(Collectors.joining(", ")); + + return String.format(INSERT_SQL_TEMPLATE, sqlUndoLog.getTableName(), insertColumns, insertValues); + } + + @Override + protected TableRecords getUndoRows() { + return sqlUndoLog.getBeforeImage(); + } +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoExecutorHolder.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoExecutorHolder.java new file mode 100644 index 00000000000..1d015c08f71 --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoExecutorHolder.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm; + +import io.seata.common.loader.LoadLevel; +import io.seata.rm.datasource.undo.AbstractUndoExecutor; +import io.seata.rm.datasource.undo.SQLUndoLog; +import io.seata.rm.datasource.undo.UndoExecutorHolder; +import io.seata.sqlparser.util.JdbcConstants; + +/** + * The Type DmUndoExecutorHolder + * + * @author: chengxiaoxiao + */ +@LoadLevel(name = JdbcConstants.DM) +public class DmUndoExecutorHolder implements UndoExecutorHolder { + + @Override + public AbstractUndoExecutor getInsertExecutor(SQLUndoLog sqlUndoLog) { + return new DmUndoInsertExecutor(sqlUndoLog); + } + + @Override + public AbstractUndoExecutor getUpdateExecutor(SQLUndoLog sqlUndoLog) { + return new DmUndoUpdateExecutor(sqlUndoLog); + } + + @Override + public AbstractUndoExecutor getDeleteExecutor(SQLUndoLog sqlUndoLog) { + return new DmUndoDeleteExecutor(sqlUndoLog); + } +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java new file mode 100644 index 00000000000..31adf01d6df --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java @@ -0,0 +1,86 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm; + +import io.seata.common.exception.ShouldNeverHappenException; +import io.seata.common.util.CollectionUtils; +import io.seata.rm.datasource.SqlGenerateUtils; +import io.seata.rm.datasource.sql.struct.Field; +import io.seata.rm.datasource.sql.struct.Row; +import io.seata.rm.datasource.sql.struct.TableRecords; +import io.seata.rm.datasource.undo.AbstractUndoExecutor; +import io.seata.rm.datasource.undo.SQLUndoLog; +import io.seata.sqlparser.util.JdbcConstants; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The type oralce undo insert executor. + * + * @author chengxiaoxiao + */ +public class DmUndoInsertExecutor extends AbstractUndoExecutor { + + /** + * DELETE FROM a WHERE pk = ? + */ + private static final String DELETE_SQL_TEMPLATE = "DELETE FROM %s WHERE %s "; + + @Override + protected String buildUndoSQL() { + TableRecords afterImage = sqlUndoLog.getAfterImage(); + List afterImageRows = afterImage.getRows(); + if (CollectionUtils.isEmpty(afterImageRows)) { + throw new ShouldNeverHappenException("Invalid UNDO LOG"); + } + return generateDeleteSql(afterImageRows,afterImage); + } + + @Override + protected void undoPrepare(PreparedStatement undoPST, ArrayList undoValues, List pkValueList) + throws SQLException { + int undoIndex = 0; + for (Field pkField:pkValueList) { + undoIndex++; + undoPST.setObject(undoIndex, pkField.getValue(), pkField.getType()); + } + } + + private String generateDeleteSql(List rows, TableRecords afterImage) { + List pkNameList = getOrderedPkList(afterImage, rows.get(0), JdbcConstants.DM).stream().map( + e -> e.getName()).collect(Collectors.toList()); + String whereSql = SqlGenerateUtils.buildWhereConditionByPKs(pkNameList, JdbcConstants.DM); + return String.format(DELETE_SQL_TEMPLATE, sqlUndoLog.getTableName(), whereSql); + } + + /** + * Instantiates a new My sql undo insert executor. + * + * @param sqlUndoLog the sql undo log + */ + public DmUndoInsertExecutor(SQLUndoLog sqlUndoLog) { + super(sqlUndoLog); + } + + @Override + protected TableRecords getUndoRows() { + return sqlUndoLog.getAfterImage(); + } +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java new file mode 100644 index 00000000000..ab16095c898 --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java @@ -0,0 +1,100 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm; + + +import io.seata.common.loader.LoadLevel; +import io.seata.core.compressor.CompressorType; +import io.seata.core.constants.ClientTableColumnsName; +import io.seata.rm.datasource.undo.AbstractUndoLogManager; +import io.seata.rm.datasource.undo.UndoLogParser; +import io.seata.sqlparser.util.JdbcConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Date; + +/** + * @author chengxiaoxiao + */ +@LoadLevel(name = JdbcConstants.DM) +public class DmUndoLogManager extends AbstractUndoLogManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(DmUndoLogManager.class); + + + private static final String INSERT_UNDO_LOG_SQL = "INSERT INTO " + UNDO_LOG_TABLE_NAME + + " (" + ClientTableColumnsName.UNDO_LOG_BRANCH_XID + ", " + + ClientTableColumnsName.UNDO_LOG_XID + ", " + ClientTableColumnsName.UNDO_LOG_CONTEXT + ", " + + ClientTableColumnsName.UNDO_LOG_ROLLBACK_INFO + ", " + ClientTableColumnsName.UNDO_LOG_LOG_STATUS + ", " + + ClientTableColumnsName.UNDO_LOG_LOG_CREATED + ", " + ClientTableColumnsName.UNDO_LOG_LOG_MODIFIED + ")" + + "VALUES (?, ?, ?, ?, ?, sysdate, sysdate)"; + + private static final String DELETE_UNDO_LOG_BY_CREATE_SQL = "DELETE FROM " + UNDO_LOG_TABLE_NAME + + " WHERE " + ClientTableColumnsName.UNDO_LOG_LOG_CREATED + " <= ? and ROWNUM <= ?"; + + @Override + public int deleteUndoLogByLogCreated(Date logCreated, int limitRows, Connection conn) throws SQLException { + try (PreparedStatement deletePST = conn.prepareStatement(DELETE_UNDO_LOG_BY_CREATE_SQL)) { + deletePST.setDate(1, new java.sql.Date(logCreated.getTime())); + deletePST.setInt(2, limitRows); + int deleteRows = deletePST.executeUpdate(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("batch delete undo log size {}", deleteRows); + } + return deleteRows; + } catch (Exception e) { + if (!(e instanceof SQLException)) { + e = new SQLException(e); + } + throw (SQLException) e; + } + } + + @Override + protected void insertUndoLogWithNormal(String xid, long branchId, String rollbackCtx, byte[] undoLogContent, + Connection conn) throws SQLException { + insertUndoLog(xid, branchId,rollbackCtx, undoLogContent, State.Normal, conn); + } + + @Override + protected void insertUndoLogWithGlobalFinished(String xid, long branchId, UndoLogParser parser, Connection conn) throws SQLException { + insertUndoLog(xid, branchId, buildContext(parser.getName(), CompressorType.NONE), parser.getDefaultContent(), + State.GlobalFinished, conn); + } + + + private void insertUndoLog(String xid, long branchID, String rollbackCtx, byte[] undoLogContent, + State state, Connection conn) throws SQLException { + try (PreparedStatement pst = conn.prepareStatement(INSERT_UNDO_LOG_SQL)) { + pst.setLong(1, branchID); + pst.setString(2, xid); + pst.setString(3, rollbackCtx); + pst.setBytes(4, undoLogContent); + pst.setInt(5, state.getValue()); + pst.executeUpdate(); + } catch (Exception e) { + if (!(e instanceof SQLException)) { + e = new SQLException(e); + } + throw (SQLException) e; + } + } + +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoUpdateExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoUpdateExecutor.java new file mode 100644 index 00000000000..9b7ba022daa --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoUpdateExecutor.java @@ -0,0 +1,80 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm; + +import io.seata.common.exception.ShouldNeverHappenException; +import io.seata.common.util.CollectionUtils; +import io.seata.rm.datasource.ColumnUtils; +import io.seata.rm.datasource.SqlGenerateUtils; +import io.seata.rm.datasource.sql.struct.Field; +import io.seata.rm.datasource.sql.struct.Row; +import io.seata.rm.datasource.sql.struct.TableRecords; +import io.seata.rm.datasource.undo.AbstractUndoExecutor; +import io.seata.rm.datasource.undo.SQLUndoLog; +import io.seata.sqlparser.util.JdbcConstants; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * The type dm undo update executor. + * + * @author chengxiaoxiao + */ +public class DmUndoUpdateExecutor extends AbstractUndoExecutor { + + /** + * UPDATE a SET x = ?, y = ?, z = ? WHERE pk1 = ? and pk2 = ? + */ + private static final String UPDATE_SQL_TEMPLATE = "UPDATE %s SET %s WHERE %s "; + + @Override + protected String buildUndoSQL() { + TableRecords beforeImage = sqlUndoLog.getBeforeImage(); + List beforeImageRows = beforeImage.getRows(); + if (CollectionUtils.isEmpty(beforeImageRows)) { + throw new ShouldNeverHappenException("Invalid UNDO LOG"); + } + Row row = beforeImageRows.get(0); + + List nonPkFields = row.nonPrimaryKeys(); + // update sql undo log before image all field come from table meta. need add escape. + // see BaseTransactionalExecutor#buildTableRecords + String updateColumns = nonPkFields.stream().map( + field -> ColumnUtils.addEscape(field.getName(), JdbcConstants.DM) + " = ?").collect( + Collectors.joining(", ")); + + List pkNameList = getOrderedPkList(beforeImage, row, JdbcConstants.DM).stream().map( + e -> e.getName()).collect(Collectors.toList()); + String whereSql = SqlGenerateUtils.buildWhereConditionByPKs(pkNameList, JdbcConstants.DM); + + return String.format(UPDATE_SQL_TEMPLATE, sqlUndoLog.getTableName(), updateColumns, whereSql); + } + + /** + * Instantiates a new My sql undo update executor. + * + * @param sqlUndoLog the sql undo log + */ + public DmUndoUpdateExecutor(SQLUndoLog sqlUndoLog) { + super(sqlUndoLog); + } + + @Override + protected TableRecords getUndoRows() { + return sqlUndoLog.getBeforeImage(); + } +} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java new file mode 100644 index 00000000000..fc211aa8492 --- /dev/null +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java @@ -0,0 +1,827 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.undo.dm.keyword; + +import io.seata.common.loader.LoadLevel; +import io.seata.rm.datasource.undo.KeywordChecker; +import io.seata.sqlparser.util.JdbcConstants; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The type dm sql keyword checker. + * + * @author chengxiaoxiao + */ +@LoadLevel(name = JdbcConstants.DM) +public class DmKeywordChecker implements KeywordChecker { + + private Set keywordSet = Arrays.stream(DmKeyword.values()).map(DmKeyword::name).collect(Collectors.toSet()); + + /** + * dm keyword + */ + private enum DmKeyword { + + ABORT("ABORT"), + ABSOLUTE("ABSOLUTE"), + ABSTRACT("ABSTRACT"), + ACCESSED("ACCESSED"), + ACCOUNT("ACCOUNT"), + ACROSS("ACROSS"), + ACTION("ACTION"), + ADD("ADD"), + + ADMIN("ADMIN"), + AFTER("AFTER"), + AGGREGATE("AGGREGATE"), + ALL("ALL"), + ALLOW_DATETIME("ALLOW_DATETIME"), + ALLOW_IP("ALLOW_IP"), + ALTER("ALTER"), + ANALYZE("ANALYZE"), + + AND("AND"), + ANY("ANY"), + ARCHIVE("ARCHIVE"), + ARCHIVEDIR("ARCHIVEDIR"), + ARCHIVELOG("ARCHIVELOG"), + ARCHIVESTYLE("ARCHIVESTYLE"), + ARRAY("ARRAY"), + + ARRAYLEN("ARRAYLEN"), + AS("AS"), + ASC("ASC"), + ASENSITIVE("ASENSITIVE"), + ASSIGN("ASSIGN"), + ASYNCHRONOUS("ASYNCHRONOUS"), + AT("AT"), + ATTACH("ATTACH"), + + AUDIT("AUDIT"), + AUTHID("AUTHID"), + AUTHORIZATION("AUTHORIZATION"), + AUTO("AUTO"), + AUTOEXTEND("AUTOEXTEND"), + + AUTONOMOUS_TRANSACTION("AUTONOMOUS_TRANSACTION"), + AVG("AVG"), + + BACKED("BACKED"), + BACKUP("BACKUP"), + BACKUPDIR("BACKUPDIR"), + BACKUPINFO("BACKUPINFO"), + BACKSET("BACKSET"), + BADFILE("BADFILE"), + BAKFILE("BAKFILE"), + + BASE("BASE"), + BEFORE("BEFORE"), + BEGIN("BEGIN"), + BETWEEN("BETWEEN"), + BIGDATEDIFF("BIGDATEDIFF"), + BIGINT("BIGINT"), + BINARY("BINARY"), + BIT("BIT"), + BITMAP("BITMAP"), + + BLOB("BLOB"), + BLOCK("BLOCK"), + BOOL("BOOL"), + BOOLEAN("BOOLEAN"), + BOTH("BOTH"), + BRANCH("BRANCH"), + BREAK("BREAK"), + BSTRING("BSTRING"), + BTREE("BTREE"), + + BUFFER("BUFFER"), + BUILD("BUILD"), + BULK("BULK"), + BY("BY"), + BYTE("BYTE"), + C("C"), + CACHE("CACHE"), + CALCULATE("CALCULATE"), + CALL("CALL"), + CASCADE("CASCADE"), + CASCADED("CASCADED"), + CASE("CASE"), + CAST("CAST"), + CATALOG("CATALOG"), + + CATCH("CATCH"), + CHAIN("CHAIN"), + CHAR("CHAR"), + CHARACTER("CHARACTER"), + CHARACTERISTICS("CHARACTERISTICS"), + CHECK("CHECK"), + CIPHER("CIPHER"), + CLASS("CLASS"), + + CLOB("CLOB"), + CLOSE("CLOSE"), + CLUSTER("CLUSTER"), + CLUSTERBTR("CLUSTERBTR"), + COLLATE("COLLATE"), + COLLATION("COLLATION"), + COLLECT("COLLECT"), + COLUMN("COLUMN"), + + COLUMNS("COLUMNS"), + COMMENT("COMMENT"), + COMMIT("COMMIT"), + COMMITTED("COMMITTED"), + COMMITWORK("COMMITWORK"), + COMPILE("COMPILE"), + COMPLETE("COMPLETE"), + + COMPRESS("COMPRESS"), + COMPRESSED("COMPRESSED"), + CONNECT("CONNECT"), + CONNECT_BY_IS_CYCLE("CONNECT_BY_IS_CYCLE"), + + CONNECT_BY_ISLEAF("CONNECT_BY_ISLEAF"), + CONNECT_BY_ROOT("CONNECT_BY_ROOT"), + CONNECT_IDLE_TIME("CONNECT_IDLE_TIME"), + CONNECT_TIME("CONNECT_TIME"), + + CONST("CONST"), + CONSTANT("CONSTANT"), + CONSTRAINT("CONSTRAINT"), + CONSTRAINTS("CONSTRAINTS"), + CONSTRUCTOR("CONSTRUCTOR"), + CONTAINS("CONTAINS"), + + CONTEXT("CONTEXT"), + CONTINUE("CONTINUE"), + CONVERT("CONVERT"), + COPY("COPY"), + CORRESPONDING("CORRESPONDING"), + COUNT("COUNT"), + COUNTER("COUNTER"), + + CPU_PER_CALL("CPU_PER_CALL"), + CPU_PER_SESSION("CPU_PER_SESSION"), + CREATE("CREATE"), + CROSS("CROSS"), + CRYPTO("CRYPTO"), + CTLFILE("CTLFILE"), + CUBE("CUBE"), + + CUMULATIVE("CUMULATIVE"), + CURRENT("CURRENT"), + CURRENT_SCHEMA("CURRENT_SCHEMA"), + CURRENT_USER("CURRENT_USER"), + CURSOR("CURSOR"), + CYCLE("CYCLE"), + D("D"), + DANGLING("DANGLING"), + DATA("DATA"), + DATABASE("DATABASE"), + DATAFILE("DATAFILE"), + DATE("DATE"), + DATEADD("DATEADD"), + DATEDIFF("DATEDIFF"), + + DATEPART("DATEPART"), + DATETIME("DATETIME"), + DAY("DAY"), + DBFILE("DBFILE"), + DDL("DDL"), + DDL_CLONE("DDL_CLONE"), + DEBUG("DEBUG"), + DEC("DEC"), + DECIMAL("DECIMAL"), + + DECLARE("DECLARE"), + DECODE("DECODE"), + DEFAULT("DEFAULT"), + DEFERRABLE("DEFERRABLE"), + DEFERRED("DEFERRED"), + DEFINER("DEFINER"), + DELETE("DELETE"), + + DELETING("DELETING"), + DELIMITED("DELIMITED"), + DELTA("DELTA"), + DEMAND("DEMAND"), + DENSE_RANK("DENSE_RANK"), + DEREF("DEREF"), + DESC("DESC"), + DETACH("DETACH"), + + DETERMINISTIC("DETERMINISTIC"), + DEVICE("DEVICE"), + DIAGNOSTICS("DIAGNOSTICS"), + DICTIONARY("DICTIONARY"), + DISABLE("DISABLE"), + DISCONNECT("DISCONNECT"), + + DISKSPACE("DISKSPACE"), + DISTINCT("DISTINCT"), + DISTRIBUTED("DISTRIBUTED"), + DO("DO"), + DOMAIN("DOMAIN"), + DOUBLE("DOUBLE"), + DOWN("DOWN"), + DROP("DROP"), + + DUMP("DUMP"), + E("E"), + EACH("EACH"), + ELSE("ELSE"), + ELSEIF("ELSEIF"), + ELSIF("ELSIF"), + ENABLE("ENABLE"), + ENCRYPT("ENCRYPT"), + ENCRYPTION("ENCRYPTION"), + END("END"), + + EQU("EQU"), + ERROR("ERROR"), + ERRORS("ERRORS"), + ESCAPE("ESCAPE"), + EVENTINFO("EVENTINFO"), + EVENTS("EVENTS"), + EXCEPT("EXCEPT"), + EXCEPTION("EXCEPTION"), + + EXCEPTIONS("EXCEPTIONS"), + EXCEPTION_INIT("EXCEPTION_INIT"), + EXCHANGE("EXCHANGE"), + EXCLUDE("EXCLUDE"), + EXCLUDING("EXCLUDING"), + EXCLUSIVE("EXCLUSIVE"), + + EXEC("EXEC"), + EXECUTE("EXECUTE"), + EXISTS("EXISTS"), + EXIT("EXIT"), + EXPLAIN("EXPLAIN"), + EXTENDS("EXTENDS"), + EXTERN("EXTERN"), + EXTERNAL("EXTERNAL"), + + EXTERNALLY("EXTERNALLY"), + EXTRACT("EXTRACT"), + F("F"), + FAILED_LOGIN_ATTEMPS("FAILED_LOGIN_ATTEMPS"), + FAST("FAST"), + FETCH("FETCH"), + FIELDS("FIELDS"), + FILE("FILE"), + FILEGROUP("FILEGROUP"), + + FILESIZE("FILESIZE"), + FILLFACTOR("FILLFACTOR"), + FINAL("FINAL"), + FINALLY("FINALLY"), + FIRST("FIRST"), + FLOAT("FLOAT"), + FOLLOWING("FOLLOWING"), + FOR("FOR"), + + FORALL("FORALL"), + FORCE("FORCE"), + FOREIGN("FOREIGN"), + FREQUENCE("FREQUENCE"), + FROM("FROM"), + FULL("FULL"), + FULLY("FULLY"), + FUNCTION("FUNCTION"), + + GET("GET"), + GLOBAL("GLOBAL"), + GLOBALLY("GLOBALLY"), + GOTO("GOTO"), + GRANT("GRANT"), + GROUP("GROUP"), + GROUPING("GROUPING"), + + HASH("HASH"), + HAVING("HAVING"), + HEXTORAW("HEXTORAW"), + HOLD("HOLD"), + HOUR("HOUR"), + HUGE("HUGE"), + + IDENTIFIED("IDENTIFIED"), + IDENTITY("IDENTITY"), + IDENTITY_INSERT("IDENTITY_INSERT"), + IF("IF"), + IMAGE("IMAGE"), + IMMEDIATE("IMMEDIATE"), + + IN("IN"), + INCLUDE("INCLUDE"), + INCLUDING("INCLUDING"), + INCREASE("INCREASE"), + INCREMENT("INCREMENT"), + INDEX("INDEX"), + INDEXES("INDEXES"), + INDICES("INDICES"), + + INITIAL("INITIAL"), + INITIALIZED("INITIALIZED"), + INITIALLY("INITIALLY"), + INLINE("INLINE"), + INNER("INNER"), + INNERID("INNERID"), + INPUT("INPUT"), + + INSENSITIVE("INSENSITIVE"), + INSERT("INSERT"), + INSERTING("INSERTING"), + INSTANTIABLE("INSTANTIABLE"), + INSTEAD("INSTEAD"), + INT("INT"), + INTEGER("INTEGER"), + + INTENT("INTENT"), + INTERNAL("INTERNAL"), + INTERSECT("INTERSECT"), + INTERVAL("INTERVAL"), + INTO("INTO"), + INVISIBLE("INVISIBLE"), + IS("IS"), + ISOLATION("ISOLATION"), + + JAVA("JAVA"), + JOB("JOB"), + JOIN("JOIN"), + + KEEP("KEEP"), + KEY("KEY"), + + LABEL("LABEL"), + LARGE("LARGE"), + LAST("LAST"), + LEADING("LEADING"), + LEFT("LEFT"), + LESS("LESS"), + LEVEL("LEVEL"), + LEXER("LEXER"), + LIKE("LIKE"), + LIMIT("LIMIT"), + + LINK("LINK"), + LIST("LIST"), + LNNVL("LNNVL"), + LOB("LOB"), + LOCAL("LOCAL"), + LOCALLY("LOCALLY"), + LOCK("LOCK"), + LOCKED("LOCKED"), + LOG("LOG"), + LOGFILE("LOGFILE"), + + LOGGING("LOGGING"), + LOGIN("LOGIN"), + LOGOFF("LOGOFF"), + LOGON("LOGON"), + LOGOUT("LOGOUT"), + LONG("LONG"), + LONGVARBINARY("LONGVARBINARY"), + LONGVARCHAR("LONGVARCHAR"), + + LOOP("LOOP"), + LSN("LSN"), + + MANUAL("MANUAL"), + MAP("MAP"), + MAPPED("MAPPED"), + MATCH("MATCH"), + MATCHED("MATCHED"), + MATERIALIZED("MATERIALIZED"), + MAX("MAX"), + MAXPIECESIZE("MAXPIECESIZE"), + + MAXSIZE("MAXSIZE"), + MAXVALUE("MAXVALUE"), + MEMBER("MEMBER"), + MEMORY("MEMORY"), + MEM_SPACE("MEM_SPACE"), + MERGE("MERGE"), + MIN("MIN"), + MINEXTENTS("MINEXTENTS"), + + MINUS("MINUS"), + MINUTE("MINUTE"), + MINVALUE("MINVALUE"), + MIRROR("MIRROR"), + MOD("MOD"), + MODE("MODE"), + MODIFY("MODIFY"), + MONEY("MONEY"), + MONITORING("MONITORING"), + + MONTH("MONTH"), + MOUNT("MOUNT"), + MOVEMENT("MOVEMENT"), + + NATIONAL("NATIONAL"), + NATURAL("NATURAL"), + NCHAR("NCHAR"), + NCHARACTER("NCHARACTER"), + NEVER("NEVER"), + NEW("NEW"), + NEXT("NEXT"), + NO("NO"), + + NOARCHIVELOG("NOARCHIVELOG"), + NOAUDIT("NOAUDIT"), + NOBRANCH("NOBRANCH"), + NOCACHE("NOCACHE"), + NOCOPY("NOCOPY"), + NOCYCLE("NOCYCLE"), + NOLOGGING("NOLOGGING"), + + NOMAXVALUE("NOMAXVALUE"), + NOMINVALUE("NOMINVALUE"), + NOMONITORING("NOMONITORING"), + NONE("NONE"), + NOORDER("NOORDER"), + NORMAL("NORMAL"), + NOSORT("NOSORT"), + + NOT("NOT"), + NOT_ALLOW_DATETIME("NOT_ALLOW_DATETIME"), + NOT_ALLOW_IP("NOT_ALLOW_IP"), + NOWAIT("NOWAIT"), + NULL("NULL"), + NULLS("NULLS"), + NUMBER("NUMBER"), + + NUMERIC("NUMERIC"), + + OBJECT("OBJECT"), + OF("OF"), + OFF("OFF"), + OFFLINE("OFFLINE"), + OFFSET("OFFSET"), + OLD("OLD"), + ON("ON"), + ONCE("ONCE"), + ONLINE("ONLINE"), + ONLY("ONLY"), + + OPEN("OPEN"), + OPTIMIZE("OPTIMIZE"), + OPTION("OPTION"), + OR("OR"), + ORDER("ORDER"), + OUT("OUT"), + OUTER("OUTER"), + OVER("OVER"), + OVERLAPS("OVERLAPS"), + + OVERLAY("OVERLAY"), + OVERRIDE("OVERRIDE"), + OVERRIDING("OVERRIDING"), + + PACKAGE("PACKAGE"), + PAD("PAD"), + PAGE("PAGE"), + PARALLEL("PARALLEL"), + PARALLEL_ENABLE("PARALLEL_ENABLE"), + PARMS("PARMS"), + PARTIAL("PARTIAL"), + + PARTITION("PARTITION"), + PARTITIONS("PARTITIONS"), + PASSWORD_GRACE_TIME("PASSWORD_GRACE_TIME"), + PASSWORD_LIFE_TIME("PASSWORD_LIFE_TIME"), + + + PASSWORD_LOCK_TIME("PASSWORD_LOCK_TIME"), + PASSWORD_POLICY("PASSWORD_POLICY"), + PASSWORD_REUSE_MAX("PASSWORD_REUSE_MAX"), + + PASSWORD_REUSE_TIME("PASSWORD_REUSE_TIME"), + PATH("PATH"), + PENDANT("PENDANT"), + PERCENT("PERCENT"), + PIPE("PIPE"), + PIPELINED("PIPELINED"), + PIVOT("PIVOT"), + + PLACING("PLACING"), + PLS_INTEGER("PLS_INTEGER"), + PRAGMA("PRAGMA"), + PRECEDING("PRECEDING"), + PRECISION("PRECISION"), + PRESERVE("PRESERVE"), + PRIMARY("PRIMARY"), + + PRINT("PRINT"), + PRIOR("PRIOR"), + PRIVATE("PRIVATE"), + PRIVILEGE("PRIVILEGE"), + PRIVILEGES("PRIVILEGES"), + PROCEDURE("PROCEDURE"), + PROTECTED("PROTECTED"), + + PUBLIC("PUBLIC"), + PURGE("PURGE"), + + QUERY_REWRITE_INTEGRITY("QUERY_REWRITE_INTEGRITY"), + + RAISE("RAISE"), + RANDOMLY("RANDOMLY"), + RANGE("RANGE"), + RAWTOHEX("RAWTOHEX"), + READ("READ"), + READONLY("READONLY"), + READ_PER_CALL("READ_PER_CALL"), + + READ_PER_SESSION("READ_PER_SESSION"), + REAL("REAL"), + REBUILD("REBUILD"), + RECORD("RECORD"), + RECORDS("RECORDS"), + REF("REF"), + REFERENCE("REFERENCE"), + + REFERENCES("REFERENCES"), + REFERENCING("REFERENCING"), + REFRESH("REFRESH"), + RELATED("RELATED"), + RELATIVE("RELATIVE"), + RENAME("RENAME"), + REPEAT("REPEAT"), + + REPEATABLE("REPEATABLE"), + REPLACE("REPLACE"), + REPLAY("REPLAY"), + REPLICATE("REPLICATE"), + RESIZE("RESIZE"), + RESTORE("RESTORE"), + RESTRICT("RESTRICT"), + + RESULT("RESULT"), + RESULT_CACHE("RESULT_CACHE"), + RETURN("RETURN"), + RETURNING("RETURNING"), + REVERSE("REVERSE"), + REVOKE("REVOKE"), + RIGHT("RIGHT"), + + ROLE("ROLE"), + ROLLBACK("ROLLBACK"), + ROLLFILE("ROLLFILE"), + ROLLUP("ROLLUP"), + ROOT("ROOT"), + ROW("ROW"), + ROWCOUNT("ROWCOUNT"), + ROWID("ROWID"), + ROWNUM("ROWNUM"), + + ROWS("ROWS"), + RULE("RULE"), + + SALT("SALT"), + SAMPLE("SAMPLE"), + SAVE("SAVE"), + SAVEPOINT("SAVEPOINT"), + SBYTE("SBYTE"), + SCHEMA("SCHEMA"), + SCOPE("SCOPE"), + SCROLL("SCROLL"), + SEALED("SEALED"), + + SECOND("SECOND"), + SECTION("SECTION"), + SEED("SEED"), + SELECT("SELECT"), + SELF("SELF"), + SENSITIVE("SENSITIVE"), + SEQUENCE("SEQUENCE"), + SERERR("SERERR"), + + SERIALIZABLE("SERIALIZABLE"), + SERVER("SERVER"), + SESSION("SESSION"), + SESSION_PER_USER("SESSION_PER_USER"), + SET("SET"), + SETS("SETS"), + SHARE("SHARE"), + + SHORT("SHORT"), + SHUTDOWN("SHUTDOWN"), + SIBLINGS("SIBLINGS"), + SIMPLE("SIMPLE"), + SINCE("SINCE"), + SIZE("SIZE"), + SIZEOF("SIZEOF"), + SKIP("SKIP"), + SMALLINT("SMALLINT"), + + SNAPSHOT("SNAPSHOT"), + SOME("SOME"), + SOUND("SOUND"), + SPACE("SPACE"), + SPATIAL("SPATIAL"), + SPFILE("SPFILE"), + SPLIT("SPLIT"), + SQL("SQL"), + STANDBY("STANDBY"), + + STARTUP("STARTUP"), + STAT("STAT"), + STATEMENT("STATEMENT"), + STATIC("STATIC"), + STDDEV("STDDEV"), + STORAGE("STORAGE"), + STORE("STORE"), + STRING("STRING"), + + STRUCT("STRUCT"), + STYLE("STYLE"), + SUBPARTITION("SUBPARTITION"), + SUBPARTITIONS("SUBPARTITIONS"), + SUBSTRING("SUBSTRING"), + SUBTYPE("SUBTYPE"), + + SUCCESSFUL("SUCCESSFUL"), + SUM("SUM"), + SUSPEND("SUSPEND"), + SWITCH("SWITCH"), + SYNC("SYNC"), + SYNCHRONOUS("SYNCHRONOUS"), + SYNONYM("SYNONYM"), + SYSTEM("SYSTEM"), + + SYS_CONNECT_BY_PATH("SYS_CONNECT_BY_PATH"), + + TABLE("TABLE"), + TABLESPACE("TABLESPACE"), + TASK("TASK"), + TEMPLATE("TEMPLATE"), + TEMPORARY("TEMPORARY"), + TEXT("TEXT"), + THAN("THAN"), + THEN("THEN"), + + THREAD("THREAD"), + THROW("THROW"), + TIES("TIES"), + TIME("TIME"), + TIMER("TIMER"), + TIMES("TIMES"), + TIMESTAMP("TIMESTAMP"), + TIMESTAMPADD("TIMESTAMPADD"), + + TIMESTAMPDIFF("TIMESTAMPDIFF"), + TIME_ZONE("TIME_ZONE"), + TINYINT("TINYINT"), + TO("TO"), + TOP("TOP"), + TRACE("TRACE"), + TRAILING("TRAILING"), + + TRANSACTION("TRANSACTION"), + TRANSACTIONAL("TRANSACTIONAL"), + TRIGGER("TRIGGER"), + TRIGGERS("TRIGGERS"), + TRIM("TRIM"), + TRUNCATE("TRUNCATE"), + + TRUNCSIZE("TRUNCSIZE"), + TRXID("TRXID"), + TRY("TRY"), + TYPE("TYPE"), + TYPEDEF("TYPEDEF"), + TYPEOF("TYPEOF"), + + UINT("UINT"), + ULONG("ULONG"), + UNBOUNDED("UNBOUNDED"), + UNCOMMITTED("UNCOMMITTED"), + UNDER("UNDER"), + UNION("UNION"), + UNIQUE("UNIQUE"), + + UNLIMITED("UNLIMITED"), + UNLOCK("UNLOCK"), + UNPIVOT("UNPIVOT"), + UNTIL("UNTIL"), + UNUSABLE("UNUSABLE"), + UP("UP"), + UPDATE("UPDATE"), + UPDATING("UPDATING"), + + USAGE("USAGE"), + USER("USER"), + USE_HASH("USE_HASH"), + USE_MERGE("USE_MERGE"), + USE_NL("USE_NL"), + USE_NL_WITH_INDEX("USE_NL_WITH_INDEX"), + + USHORT("USHORT"), + USING("USING"), + + VALUE("VALUE"), + VALUES("VALUES"), + VARBINARY("VARBINARY"), + VARCHAR("VARCHAR"), + VARCHAR2("VARCHAR2"), + VARIANCE("VARIANCE"), + VARRAY("VARRAY"), + + VARYING("VARYING"), + VERIFY("VERIFY"), + VERSIONS("VERSIONS"), + VERSIONS_STARTTIME("VERSIONS_STARTTIME"), + VERSIONS_ENDTIME("VERSIONS_ENDTIME"), + + VERSIONS_STARTTRXID("VERSIONS_STARTTRXID"), + VERSIONS_ENDTRXID("VERSIONS_ENDTRXID"), + VERSIONS_OPERATION("VERSIONS_OPERATION"), + VERTICAL("VERTICAL"), + + VIEW("VIEW"), + VIRTUAL("VIRTUAL"), + VISIBLE("VISIBLE"), + VOID("VOID"), + VOLATILE("VOLATILE"), + VSIZE("VSIZE"), + + WAIT("WAIT"), + WEEK("WEEK"), + WHEN("WHEN"), + WHENEVER("WHENEVER"), + WHERE("WHERE"), + WHILE("WHILE"), + WITH("WITH"), + WITHIN("WITHIN"), + WITHOUT("WITHOUT"), + + WORK("WORK"), + WRAPPED("WRAPPED"), + WRITE("WRITE"), + XML("XML"), + YEAR("YEAR"), + ZONE("ZONE"); + /** + * The Name. + */ + public final String name; + + DmKeyword(String name) { + this.name = name; + } + } + + @Override + public boolean check(String fieldOrTableName) { + if (keywordSet.contains(fieldOrTableName)) { + return true; + } + if (fieldOrTableName != null) { + fieldOrTableName = fieldOrTableName.toUpperCase(); + } + return keywordSet.contains(fieldOrTableName); + + } + + @Override + public boolean checkEscape(String fieldOrTableName) { + boolean check = check(fieldOrTableName); + // oracle + // we are recommend table name and column name must uppercase. + // if exists full uppercase, the table name or column name does't bundle escape symbol. + if (!check && isUppercase(fieldOrTableName)) { + return false; + } + return true; + } + + private static boolean isUppercase(String fieldOrTableName) { + if (fieldOrTableName == null) { + return false; + } + char[] chars = fieldOrTableName.toCharArray(); + for (char ch : chars) { + if (ch >= 'a' && ch <= 'z') { + return false; + } + } + return true; + } +} diff --git a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.exec.InsertExecutor b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.exec.InsertExecutor index 2169a3978d0..03c47fbe9c8 100644 --- a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.exec.InsertExecutor +++ b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.exec.InsertExecutor @@ -16,4 +16,5 @@ io.seata.rm.datasource.exec.mysql.MySQLInsertExecutor io.seata.rm.datasource.exec.oracle.OracleInsertExecutor -io.seata.rm.datasource.exec.postgresql.PostgresqlInsertExecutor \ No newline at end of file +io.seata.rm.datasource.exec.postgresql.PostgresqlInsertExecutor +io.seata.rm.datasource.exec.dm.DmInsertExecutor \ No newline at end of file diff --git a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.sql.struct.TableMetaCache b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.sql.struct.TableMetaCache index f3838d8b5ba..b43a3500c8d 100644 --- a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.sql.struct.TableMetaCache +++ b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.sql.struct.TableMetaCache @@ -1,3 +1,4 @@ io.seata.rm.datasource.sql.struct.cache.MysqlTableMetaCache io.seata.rm.datasource.sql.struct.cache.OracleTableMetaCache -io.seata.rm.datasource.sql.struct.cache.PostgresqlTableMetaCache \ No newline at end of file +io.seata.rm.datasource.sql.struct.cache.PostgresqlTableMetaCache +io.seata.rm.datasource.sql.struct.cache.DmTableMetaCache \ No newline at end of file diff --git a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.KeywordChecker b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.KeywordChecker index 6d674d92bc4..07cfe22ddfa 100644 --- a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.KeywordChecker +++ b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.KeywordChecker @@ -1,3 +1,4 @@ io.seata.rm.datasource.undo.oracle.keyword.OracleKeywordChecker io.seata.rm.datasource.undo.mysql.keyword.MySQLKeywordChecker -io.seata.rm.datasource.undo.postgresql.keyword.PostgresqlKeywordChecker \ No newline at end of file +io.seata.rm.datasource.undo.postgresql.keyword.PostgresqlKeywordChecker +io.seata.rm.datasource.undo.dm.keyword.DmKeywordChecker \ No newline at end of file diff --git a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoExecutorHolder b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoExecutorHolder index ddc7a352f57..f4c911fb772 100644 --- a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoExecutorHolder +++ b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoExecutorHolder @@ -1,3 +1,4 @@ io.seata.rm.datasource.undo.mysql.MySQLUndoExecutorHolder io.seata.rm.datasource.undo.oracle.OracleUndoExecutorHolder -io.seata.rm.datasource.undo.postgresql.PostgresqlUndoExecutorHolder \ No newline at end of file +io.seata.rm.datasource.undo.postgresql.PostgresqlUndoExecutorHolder +io.seata.rm.datasource.undo.dm.DmUndoExecutorHolder \ No newline at end of file diff --git a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoLogManager b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoLogManager index a9de44626bc..d97a01485c5 100644 --- a/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoLogManager +++ b/rm-datasource/src/main/resources/META-INF/services/io.seata.rm.datasource.undo.UndoLogManager @@ -1,3 +1,4 @@ io.seata.rm.datasource.undo.mysql.MySQLUndoLogManager io.seata.rm.datasource.undo.oracle.OracleUndoLogManager -io.seata.rm.datasource.undo.postgresql.PostgresqlUndoLogManager \ No newline at end of file +io.seata.rm.datasource.undo.postgresql.PostgresqlUndoLogManager +io.seata.rm.datasource.undo.dm.DmUndoLogManager \ No newline at end of file diff --git a/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/util/JdbcConstants.java b/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/util/JdbcConstants.java index 09020c4e9c3..0c6bba0e109 100644 --- a/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/util/JdbcConstants.java +++ b/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/util/JdbcConstants.java @@ -30,4 +30,6 @@ public interface JdbcConstants { String MARIADB = "mariadb"; String POSTGRESQL = "postgresql"; + + String DM = "dm"; } diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java new file mode 100644 index 00000000000..ca0d0ec68d9 --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java @@ -0,0 +1,85 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; +import io.seata.common.util.StringUtils; +import io.seata.sqlparser.ParametersHolder; +import io.seata.sqlparser.druid.BaseRecognizer; +import io.seata.sqlparser.struct.Null; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author will + */ +public abstract class BaseDmRecognizer extends BaseRecognizer { + + /** + * Instantiates a new oracle base recognizer + * + * @param originalSql the original sql + */ + public BaseDmRecognizer(String originalSql) { + super(originalSql); + } + + public OracleOutputVisitor createOutputVisitor(final ParametersHolder parametersHolder, + final ArrayList> paramAppenderList, + final StringBuilder sb) { + + return new OracleOutputVisitor(sb) { + @Override + public boolean visit(SQLVariantRefExpr x) { + if ("?".equals(x.getName())) { + ArrayList oneParamValues = parametersHolder.getParameters().get(x.getIndex() + 1); + if (paramAppenderList.isEmpty()) { + oneParamValues.forEach(t -> paramAppenderList.add(new ArrayList<>())); + } + for (int i = 0; i < oneParamValues.size(); i++) { + Object o = oneParamValues.get(i); + paramAppenderList.get(i).add(o instanceof Null ? null : o); + } + } + return super.visit(x); + } + }; + } + + public String getWhereCondition(SQLExpr where, final ParametersHolder parametersHolder, final ArrayList> paramAppenderList) { + if (Objects.isNull(where)) { + return StringUtils.EMPTY; + } + + StringBuilder sb = new StringBuilder(); + executeVisit(where, createOutputVisitor(parametersHolder, paramAppenderList, sb)); + return sb.toString(); + } + + public String getWhereCondition(SQLExpr where) { + if (Objects.isNull(where)) { + return StringUtils.EMPTY; + } + + StringBuilder sb = new StringBuilder(); + executeVisit(where, new OracleOutputVisitor(sb)); + return sb.toString(); + } +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java new file mode 100644 index 00000000000..29c0ac230f6 --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java @@ -0,0 +1,109 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; +import com.alibaba.druid.sql.ast.statement.SQLTableSource; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleDeleteStatement; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; +import io.seata.common.exception.NotSupportYetException; +import io.seata.sqlparser.ParametersHolder; +import io.seata.sqlparser.SQLDeleteRecognizer; +import io.seata.sqlparser.SQLType; + +import java.util.ArrayList; +import java.util.List; + +/** + * The type oracle delete recognizer. + * + * @author ccg + */ +public class DmDeleteRecognizer extends BaseDmRecognizer implements SQLDeleteRecognizer { + + private final OracleDeleteStatement ast; + + /** + * Instantiates a new My sql delete recognizer. + * + * @param originalSQL the original sql + * @param ast the ast + */ + public DmDeleteRecognizer(String originalSQL, SQLStatement ast) { + super(originalSQL); + this.ast = (OracleDeleteStatement)ast; + } + + @Override + public SQLType getSQLType() { + return SQLType.DELETE; + } + + @Override + public String getTableAlias() { + return ast.getTableSource().getAlias(); + } + + @Override + public String getTableName() { + StringBuilder sb = new StringBuilder(); + OracleOutputVisitor visitor = new OracleOutputVisitor(sb) { + + @Override + public boolean visit(SQLExprTableSource x) { + printTableSourceExpr(x.getExpr()); + return false; + } + + @Override + public boolean visit(SQLJoinTableSource x) { + throw new NotSupportYetException("not support the syntax of delete with join table"); + } + }; + SQLTableSource tableSource; + if (ast.getFrom() == null) { + tableSource = ast.getTableSource(); + } else { + tableSource = ast.getFrom(); + } + + if (tableSource instanceof SQLExprTableSource) { + visitor.visit((SQLExprTableSource) tableSource); + } else if (tableSource instanceof SQLJoinTableSource) { + visitor.visit((SQLJoinTableSource) tableSource); + } else { + throw new NotSupportYetException("not support the syntax of delete with unknow"); + } + return sb.toString(); + } + + @Override + public String getWhereCondition(final ParametersHolder parametersHolder, + final ArrayList> paramAppenderList) { + SQLExpr where = ast.getWhere(); + return super.getWhereCondition(where, parametersHolder, paramAppenderList); + } + + @Override + public String getWhereCondition() { + SQLExpr where = ast.getWhere(); + return super.getWhereCondition(where); + } + +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java new file mode 100644 index 00000000000..a6e1a043cc1 --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java @@ -0,0 +1,139 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.expr.*; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleInsertStatement; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; +import io.seata.common.util.CollectionUtils; +import io.seata.sqlparser.SQLInsertRecognizer; +import io.seata.sqlparser.SQLParsingException; +import io.seata.sqlparser.SQLType; +import io.seata.sqlparser.struct.NotPlaceholderExpr; +import io.seata.sqlparser.struct.Null; +import io.seata.sqlparser.struct.SqlMethodExpr; +import io.seata.sqlparser.struct.SqlSequenceExpr; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * The type racle insert recognizer. + * + * @author ccg + */ +public class DmInsertRecognizer extends BaseDmRecognizer implements SQLInsertRecognizer { + + private final OracleInsertStatement ast; + + /** + * Instantiates a new My sql insert recognizer. + * + * @param originalSQL the original sql + * @param ast the ast + */ + public DmInsertRecognizer(String originalSQL, SQLStatement ast) { + super(originalSQL); + this.ast = (OracleInsertStatement)ast; + } + + @Override + public SQLType getSQLType() { + return SQLType.INSERT; + } + + @Override + public String getTableAlias() { + return ast.getTableSource().getAlias(); + } + + @Override + public String getTableName() { + StringBuilder sb = new StringBuilder(); + OracleOutputVisitor visitor = new OracleOutputVisitor(sb) { + + @Override + public boolean visit(SQLExprTableSource x) { + printTableSourceExpr(x.getExpr()); + return false; + } + }; + visitor.visit(ast.getTableSource()); + return sb.toString(); + } + + @Override + public boolean insertColumnsIsEmpty() { + return CollectionUtils.isEmpty(ast.getColumns()); + } + + @Override + public List getInsertColumns() { + List columnSQLExprs = ast.getColumns(); + if (columnSQLExprs.isEmpty()) { + // INSERT INTO ta VALUES (...), without fields clarified + return null; + } + List list = new ArrayList<>(columnSQLExprs.size()); + for (SQLExpr expr : columnSQLExprs) { + if (expr instanceof SQLIdentifierExpr) { + list.add(((SQLIdentifierExpr)expr).getName()); + } else { + throw new SQLParsingException("Unknown SQLExpr: " + expr.getClass() + " " + expr); + } + } + return list; + } + + @Override + public List> getInsertRows(Collection primaryKeyIndex) { + List valuesClauses = ast.getValuesList(); + List> rows = new ArrayList<>(valuesClauses.size()); + for (SQLInsertStatement.ValuesClause valuesClause : valuesClauses) { + List exprs = valuesClause.getValues(); + List row = new ArrayList<>(exprs.size()); + rows.add(row); + for (int i = 0, len = exprs.size(); i < len; i++) { + SQLExpr expr = exprs.get(i); + if (expr instanceof SQLNullExpr) { + row.add(Null.get()); + } else if (expr instanceof SQLValuableExpr) { + row.add(((SQLValuableExpr) expr).getValue()); + } else if (expr instanceof SQLVariantRefExpr) { + row.add(((SQLVariantRefExpr) expr).getName()); + } else if (expr instanceof SQLMethodInvokeExpr) { + row.add(SqlMethodExpr.get()); + } else if (expr instanceof SQLSequenceExpr) { + SQLSequenceExpr sequenceExpr = (SQLSequenceExpr) expr; + String sequence = sequenceExpr.getSequence().getSimpleName(); + String function = sequenceExpr.getFunction().name; + row.add(new SqlSequenceExpr(sequence, function)); + } else { + if (primaryKeyIndex.contains(i)) { + throw new SQLParsingException("Unknown SQLExpr: " + expr.getClass() + " " + expr); + } + row.add(NotPlaceholderExpr.get()); + } + } + } + return rows; + } +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java new file mode 100644 index 00000000000..f4f2aa011b6 --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java @@ -0,0 +1,54 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import io.seata.common.loader.LoadLevel; +import io.seata.sqlparser.SQLRecognizer; +import io.seata.sqlparser.druid.SQLOperateRecognizerHolder; +import io.seata.sqlparser.util.JdbcConstants; + +/** * The Type OracleOperateRecognizerHolder + * + * @author: Zhibei Hao + */ +@LoadLevel(name = JdbcConstants.DM) +public class DmOperateRecognizerHolder implements SQLOperateRecognizerHolder { + + @Override + public SQLRecognizer getDeleteRecognizer(String sql, SQLStatement ast) { + return new DmDeleteRecognizer(sql, ast); + } + + @Override + public SQLRecognizer getInsertRecognizer(String sql, SQLStatement ast) { + return new DmDeleteRecognizer(sql, ast); + } + + @Override + public SQLRecognizer getUpdateRecognizer(String sql, SQLStatement ast) { + return new DmDeleteRecognizer(sql, ast); + } + + @Override + public SQLRecognizer getSelectForUpdateRecognizer(String sql, SQLStatement ast) { + if (((SQLSelectStatement) ast).getSelect().getFirstQueryBlock().isForUpdate()) { + return new DmSelectForUpdateRecognizer(sql, ast); + } + return null; + } +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java new file mode 100644 index 00000000000..f921227f4e5 --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java @@ -0,0 +1,106 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.*; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; +import io.seata.sqlparser.ParametersHolder; +import io.seata.sqlparser.SQLParsingException; +import io.seata.sqlparser.SQLSelectRecognizer; +import io.seata.sqlparser.SQLType; + +import java.util.ArrayList; +import java.util.List; + +/** + * The type oracle select for update recognizer. + * + * @author ccg + */ +public class DmSelectForUpdateRecognizer extends BaseDmRecognizer implements SQLSelectRecognizer { + + private final SQLSelectStatement ast; + + /** + * Instantiates a new My sql select for update recognizer. + * + * @param originalSQL the original sql + * @param ast the ast + */ + public DmSelectForUpdateRecognizer(String originalSQL, SQLStatement ast) { + super(originalSQL); + this.ast = (SQLSelectStatement)ast; + } + + @Override + public SQLType getSQLType() { + return SQLType.SELECT_FOR_UPDATE; + } + + @Override + public String getWhereCondition(final ParametersHolder parametersHolder, + final ArrayList> paramAppenderList) { + SQLSelectQueryBlock selectQueryBlock = getSelect(); + SQLExpr where = selectQueryBlock.getWhere(); + return super.getWhereCondition(where, parametersHolder, paramAppenderList); + } + + @Override + public String getWhereCondition() { + SQLSelectQueryBlock selectQueryBlock = getSelect(); + SQLExpr where = selectQueryBlock.getWhere(); + return super.getWhereCondition(where); + } + + private SQLSelectQueryBlock getSelect() { + SQLSelect select = ast.getSelect(); + if (select == null) { + throw new SQLParsingException("should never happen!"); + } + SQLSelectQueryBlock selectQueryBlock = select.getQueryBlock(); + if (selectQueryBlock == null) { + throw new SQLParsingException("should never happen!"); + } + return selectQueryBlock; + } + + @Override + public String getTableAlias() { + SQLSelectQueryBlock selectQueryBlock = getSelect(); + SQLTableSource tableSource = selectQueryBlock.getFrom(); + return tableSource.getAlias(); + } + + @Override + public String getTableName() { + SQLSelectQueryBlock selectQueryBlock = getSelect(); + SQLTableSource tableSource = selectQueryBlock.getFrom(); + StringBuilder sb = new StringBuilder(); + OracleOutputVisitor visitor = new OracleOutputVisitor(sb) { + + @Override + public boolean visit(SQLExprTableSource x) { + printTableSourceExpr(x.getExpr()); + return false; + } + }; + visitor.visit((SQLExprTableSource)tableSource); + return sb.toString(); + } + +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java new file mode 100644 index 00000000000..f016f888a8e --- /dev/null +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java @@ -0,0 +1,150 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.sqlparser.druid.dm; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; +import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; +import com.alibaba.druid.sql.ast.expr.SQLValuableExpr; +import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; +import com.alibaba.druid.sql.ast.statement.SQLTableSource; +import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleUpdateStatement; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; +import io.seata.common.exception.NotSupportYetException; +import io.seata.sqlparser.ParametersHolder; +import io.seata.sqlparser.SQLParsingException; +import io.seata.sqlparser.SQLType; +import io.seata.sqlparser.SQLUpdateRecognizer; + +import java.util.ArrayList; +import java.util.List; + +/** + * The type oracle update recognizer. + * + * @author ccg + */ +public class DmUpdateRecognizer extends BaseDmRecognizer implements SQLUpdateRecognizer { + + private OracleUpdateStatement ast; + + /** + * Instantiates a new My sql update recognizer. + * + * @param originalSQL the original sql + * @param ast the ast + */ + public DmUpdateRecognizer(String originalSQL, SQLStatement ast) { + super(originalSQL); + this.ast = (OracleUpdateStatement)ast; + } + + @Override + public SQLType getSQLType() { + return SQLType.UPDATE; + } + + @Override + public List getUpdateColumns() { + List updateSetItems = ast.getItems(); + List list = new ArrayList<>(updateSetItems.size()); + for (SQLUpdateSetItem updateSetItem : updateSetItems) { + SQLExpr expr = updateSetItem.getColumn(); + if (expr instanceof SQLIdentifierExpr) { + list.add(((SQLIdentifierExpr)expr).getName()); + } else if (expr instanceof SQLPropertyExpr) { + // This is alias case, like UPDATE xxx_tbl a SET a.name = ? WHERE a.id = ? + SQLExpr owner = ((SQLPropertyExpr)expr).getOwner(); + if (owner instanceof SQLIdentifierExpr) { + list.add(((SQLIdentifierExpr)owner).getName() + "." + ((SQLPropertyExpr)expr).getName()); + //This is table Field Full path, like update xxx_database.xxx_tbl set xxx_database.xxx_tbl.xxx_field... + } else if (((SQLPropertyExpr) expr).getOwnernName().split("\\.").length > 1) { + list.add(((SQLPropertyExpr)expr).getOwnernName() + "." + ((SQLPropertyExpr)expr).getName()); + } + } else { + throw new SQLParsingException("Unknown SQLExpr: " + expr.getClass() + " " + expr); + } + } + return list; + } + + @Override + public List getUpdateValues() { + List updateSetItems = ast.getItems(); + List list = new ArrayList<>(updateSetItems.size()); + for (SQLUpdateSetItem updateSetItem : updateSetItems) { + SQLExpr expr = updateSetItem.getValue(); + if (expr instanceof SQLValuableExpr) { + list.add(((SQLValuableExpr)expr).getValue()); + } else if (expr instanceof SQLVariantRefExpr) { + list.add(new VMarker()); + } else { + throw new SQLParsingException("Unknown SQLExpr: " + expr.getClass() + " " + expr); + } + } + return list; + } + + @Override + public String getWhereCondition(final ParametersHolder parametersHolder, + final ArrayList> paramAppenderList) { + SQLExpr where = ast.getWhere(); + return super.getWhereCondition(where, parametersHolder, paramAppenderList); + } + + @Override + public String getWhereCondition() { + SQLExpr where = ast.getWhere(); + return super.getWhereCondition(where); + } + + @Override + public String getTableAlias() { + return ast.getTableSource().getAlias(); + } + + @Override + public String getTableName() { + StringBuilder sb = new StringBuilder(); + OracleOutputVisitor visitor = new OracleOutputVisitor(sb) { + + @Override + public boolean visit(SQLExprTableSource x) { + printTableSourceExpr(x.getExpr()); + return false; + } + + @Override + public boolean visit(SQLJoinTableSource x) { + throw new NotSupportYetException("not support the syntax of update with join table"); + } + }; + SQLTableSource tableSource = ast.getTableSource(); + if (tableSource instanceof SQLExprTableSource) { + visitor.visit((SQLExprTableSource) tableSource); + } else if (tableSource instanceof SQLJoinTableSource) { + visitor.visit((SQLJoinTableSource) tableSource); + } else { + throw new NotSupportYetException("not support the syntax of update with unknow"); + } + return sb.toString(); + } + +} diff --git a/sqlparser/seata-sqlparser-druid/src/main/resources/META-INF/services/io.seata.sqlparser.druid.SQLOperateRecognizerHolder b/sqlparser/seata-sqlparser-druid/src/main/resources/META-INF/services/io.seata.sqlparser.druid.SQLOperateRecognizerHolder index 0e290f5bd49..c22e1e86a4d 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/resources/META-INF/services/io.seata.sqlparser.druid.SQLOperateRecognizerHolder +++ b/sqlparser/seata-sqlparser-druid/src/main/resources/META-INF/services/io.seata.sqlparser.druid.SQLOperateRecognizerHolder @@ -1,3 +1,4 @@ io.seata.sqlparser.druid.mysql.MySQLOperateRecognizerHolder io.seata.sqlparser.druid.oracle.OracleOperateRecognizerHolder -io.seata.sqlparser.druid.postgresql.PostgresqlOperateRecognizerHolder \ No newline at end of file +io.seata.sqlparser.druid.postgresql.PostgresqlOperateRecognizerHolder +io.seata.sqlparser.druid.dm.DmOperateRecognizerHolder \ No newline at end of file From 4a158a29c4c3cdceaf65fb47e4eb7d354ab092a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Tue, 11 May 2021 22:01:04 +0800 Subject: [PATCH 02/25] update: support dm database. fix global transaction function. add some comments --- .../datasource/undo/dm/DmUndoLogManager.java | 13 +++++++++---- .../undo/dm/keyword/DmKeywordChecker.java | 3 +++ script/client/at/db/dm.sql | 15 +++++++++++++++ .../druid/dm/DmDeleteRecognizer.java | 10 +++++----- .../druid/dm/DmInsertRecognizer.java | 19 ++++++++++++++----- .../druid/dm/DmOperateRecognizerHolder.java | 8 ++++---- .../druid/dm/DmUpdateRecognizer.java | 14 +++++--------- 7 files changed, 55 insertions(+), 27 deletions(-) create mode 100644 script/client/at/db/dm.sql diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java index ab16095c898..3db7faf2a2e 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java @@ -17,6 +17,7 @@ import io.seata.common.loader.LoadLevel; +import io.seata.common.util.BlobUtils; import io.seata.core.compressor.CompressorType; import io.seata.core.constants.ClientTableColumnsName; import io.seata.rm.datasource.undo.AbstractUndoLogManager; @@ -25,9 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; +import java.sql.*; import java.util.Date; /** @@ -41,7 +40,7 @@ public class DmUndoLogManager extends AbstractUndoLogManager { private static final String INSERT_UNDO_LOG_SQL = "INSERT INTO " + UNDO_LOG_TABLE_NAME + " (" + ClientTableColumnsName.UNDO_LOG_BRANCH_XID + ", " - + ClientTableColumnsName.UNDO_LOG_XID + ", " + ClientTableColumnsName.UNDO_LOG_CONTEXT + ", " + + ClientTableColumnsName.UNDO_LOG_XID + ", \"" + ClientTableColumnsName.UNDO_LOG_CONTEXT.toUpperCase() + "\", " + ClientTableColumnsName.UNDO_LOG_ROLLBACK_INFO + ", " + ClientTableColumnsName.UNDO_LOG_LOG_STATUS + ", " + ClientTableColumnsName.UNDO_LOG_LOG_CREATED + ", " + ClientTableColumnsName.UNDO_LOG_LOG_MODIFIED + ")" + "VALUES (?, ?, ?, ?, ?, sysdate, sysdate)"; @@ -79,6 +78,12 @@ protected void insertUndoLogWithGlobalFinished(String xid, long branchId, UndoLo State.GlobalFinished, conn); } + @Override + protected byte[] getRollbackInfo(ResultSet rs) throws SQLException { + Blob b = rs.getBlob(ClientTableColumnsName.UNDO_LOG_ROLLBACK_INFO); + byte[] rollbackInfo = BlobUtils.blob2Bytes(b); + return rollbackInfo; + } private void insertUndoLog(String xid, long branchID, String rollbackCtx, byte[] undoLogContent, State state, Connection conn) throws SQLException { diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java index fc211aa8492..8cf0f9efeb5 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java @@ -38,6 +38,9 @@ public class DmKeywordChecker implements KeywordChecker { */ private enum DmKeyword { + /** + * ABORT + */ ABORT("ABORT"), ABSOLUTE("ABSOLUTE"), ABSTRACT("ABSTRACT"), diff --git a/script/client/at/db/dm.sql b/script/client/at/db/dm.sql new file mode 100644 index 00000000000..d6f4512705e --- /dev/null +++ b/script/client/at/db/dm.sql @@ -0,0 +1,15 @@ +CREATE TABLE "UNDO_LOG" +( +"ID" BIGINT IDENTITY(1, 1) NOT NULL, +"BRANCH_ID" BIGINT NOT NULL, +"XID" VARCHAR(100) NOT NULL, +"CONTEXT" VARCHAR(128) NOT NULL, +"ROLLBACK_INFO" BLOB NOT NULL, +"LOG_STATUS" INT NOT NULL, +"LOG_CREATED" TIMESTAMP(0) NOT NULL, +"LOG_MODIFIED" TIMESTAMP(0) NOT NULL, +"EXT" VARCHAR(100), +NOT CLUSTER PRIMARY KEY("ID"), +CONSTRAINT "UX_UNDO_LOG" UNIQUE("XID", "BRANCH_ID")) STORAGE(ON "MAIN", CLUSTERBTR) ; + +CREATE UNIQUE INDEX "PRIMARY" ON "UNDO_LOG"("ID" ASC) STORAGE(ON "MAIN", CLUSTERBTR) ; \ No newline at end of file diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java index 29c0ac230f6..38b9803d9f6 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmDeleteRecognizer.java @@ -17,10 +17,10 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; import com.alibaba.druid.sql.ast.statement.SQLTableSource; -import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleDeleteStatement; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; import io.seata.common.exception.NotSupportYetException; import io.seata.sqlparser.ParametersHolder; @@ -31,13 +31,13 @@ import java.util.List; /** - * The type oracle delete recognizer. + * The type dm delete recognizer. * - * @author ccg + * @author chengxiaoxiao */ public class DmDeleteRecognizer extends BaseDmRecognizer implements SQLDeleteRecognizer { - private final OracleDeleteStatement ast; + private final SQLDeleteStatement ast; /** * Instantiates a new My sql delete recognizer. @@ -47,7 +47,7 @@ public class DmDeleteRecognizer extends BaseDmRecognizer implements SQLDeleteRec */ public DmDeleteRecognizer(String originalSQL, SQLStatement ast) { super(originalSQL); - this.ast = (OracleDeleteStatement)ast; + this.ast = (SQLDeleteStatement)ast; } @Override diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java index a6e1a043cc1..80fe4e758b6 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java @@ -20,7 +20,6 @@ import com.alibaba.druid.sql.ast.expr.*; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; -import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleInsertStatement; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; import io.seata.common.util.CollectionUtils; import io.seata.sqlparser.SQLInsertRecognizer; @@ -36,13 +35,13 @@ import java.util.List; /** - * The type racle insert recognizer. + * The type dm insert recognizer. * - * @author ccg + * @author chengxiaoxiao */ public class DmInsertRecognizer extends BaseDmRecognizer implements SQLInsertRecognizer { - private final OracleInsertStatement ast; + private final SQLInsertStatement ast; /** * Instantiates a new My sql insert recognizer. @@ -52,7 +51,7 @@ public class DmInsertRecognizer extends BaseDmRecognizer implements SQLInsertRec */ public DmInsertRecognizer(String originalSQL, SQLStatement ast) { super(originalSQL); - this.ast = (OracleInsertStatement)ast; + this.ast = (SQLInsertStatement)ast; } @Override @@ -136,4 +135,14 @@ public List> getInsertRows(Collection primaryKeyIndex) { } return rows; } + + @Override + public List getInsertParamsValue() { + return null; + } + + @Override + public List getDuplicateKeyUpdate() { + return null; + } } diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java index f4f2aa011b6..4b4b25aaf32 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmOperateRecognizerHolder.java @@ -22,9 +22,9 @@ import io.seata.sqlparser.druid.SQLOperateRecognizerHolder; import io.seata.sqlparser.util.JdbcConstants; -/** * The Type OracleOperateRecognizerHolder +/** * The Type DmOperateRecognizerHolder * - * @author: Zhibei Hao + * @author: chengxiaoxiao */ @LoadLevel(name = JdbcConstants.DM) public class DmOperateRecognizerHolder implements SQLOperateRecognizerHolder { @@ -36,12 +36,12 @@ public SQLRecognizer getDeleteRecognizer(String sql, SQLStatement ast) { @Override public SQLRecognizer getInsertRecognizer(String sql, SQLStatement ast) { - return new DmDeleteRecognizer(sql, ast); + return new DmInsertRecognizer(sql, ast); } @Override public SQLRecognizer getUpdateRecognizer(String sql, SQLStatement ast) { - return new DmDeleteRecognizer(sql, ast); + return new DmUpdateRecognizer(sql, ast); } @Override diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java index f016f888a8e..5c38d194d9c 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java @@ -21,11 +21,7 @@ import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLValuableExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; -import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; -import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; -import com.alibaba.druid.sql.ast.statement.SQLTableSource; -import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem; -import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleUpdateStatement; +import com.alibaba.druid.sql.ast.statement.*; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; import io.seata.common.exception.NotSupportYetException; import io.seata.sqlparser.ParametersHolder; @@ -37,13 +33,13 @@ import java.util.List; /** - * The type oracle update recognizer. + * The type dm update recognizer. * - * @author ccg + * @author chengxiaoxiao */ public class DmUpdateRecognizer extends BaseDmRecognizer implements SQLUpdateRecognizer { - private OracleUpdateStatement ast; + private SQLUpdateStatement ast; /** * Instantiates a new My sql update recognizer. @@ -53,7 +49,7 @@ public class DmUpdateRecognizer extends BaseDmRecognizer implements SQLUpdateRec */ public DmUpdateRecognizer(String originalSQL, SQLStatement ast) { super(originalSQL); - this.ast = (OracleUpdateStatement)ast; + this.ast = (SQLUpdateStatement)ast; } @Override From eb3eca8a1d28dffac14726e95b35a94dc17c5b1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Tue, 11 May 2021 22:19:28 +0800 Subject: [PATCH 03/25] update: fix file line --- core/src/main/log4j.properties | 24 ++++++++++----------- script/client/spring/application.properties | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/core/src/main/log4j.properties b/core/src/main/log4j.properties index 05ba0e365a1..5e9e109004a 100644 --- a/core/src/main/log4j.properties +++ b/core/src/main/log4j.properties @@ -16,16 +16,16 @@ log4j.rootCategory=info,R -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=info -log4j.appender.console.layout=org.apache.log4j.PatternLayout -log4j.appender.console.layout.ConversionPattern=- %m%n +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.Threshold=info +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=- %m%n -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.Append=true -log4j.appender.R.Threshold=info -log4j.appender.R.MaxFileSize=102400KB -log4j.appender.R.MaxBackupIndex=10 -log4j.appender.R.File=${WORKDIR}/logs/biz.log -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.Append=true +log4j.appender.R.Threshold=info +log4j.appender.R.MaxFileSize=102400KB +log4j.appender.R.MaxBackupIndex=10 +log4j.appender.R.File=${WORKDIR}/logs/biz.log +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n diff --git a/script/client/spring/application.properties b/script/client/spring/application.properties index 48c020726aa..61e835897fc 100755 --- a/script/client/spring/application.properties +++ b/script/client/spring/application.properties @@ -133,4 +133,4 @@ seata.registry.zk.connect-timeout=2000 seata.registry.zk.username= seata.registry.zk.password= -seata.registry.custom.name= \ No newline at end of file +seata.registry.custom.name= From 419bdc9fc31e8c409c7180204f0c3f3a539bc0cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Tue, 11 May 2021 22:42:47 +0800 Subject: [PATCH 04/25] update: Optimize import format --- .../io/seata/sqlparser/druid/dm/BaseDmRecognizer.java | 2 +- .../seata/sqlparser/druid/dm/DmInsertRecognizer.java | 7 ++++++- .../druid/dm/DmSelectForUpdateRecognizer.java | 10 +++++++--- .../seata/sqlparser/druid/dm/DmUpdateRecognizer.java | 6 +++++- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java index ca0d0ec68d9..40a51bce6fa 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java @@ -28,7 +28,7 @@ import java.util.Objects; /** - * @author will + * @author chengxiaoxiao */ public abstract class BaseDmRecognizer extends BaseRecognizer { diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java index 80fe4e758b6..7688a8ce984 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmInsertRecognizer.java @@ -17,7 +17,12 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLStatement; -import com.alibaba.druid.sql.ast.expr.*; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.ast.expr.SQLNullExpr; +import com.alibaba.druid.sql.ast.expr.SQLSequenceExpr; +import com.alibaba.druid.sql.ast.expr.SQLValuableExpr; +import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java index f921227f4e5..60eafcd209f 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmSelectForUpdateRecognizer.java @@ -17,7 +17,11 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLStatement; -import com.alibaba.druid.sql.ast.statement.*; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLSelect; +import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import com.alibaba.druid.sql.ast.statement.SQLTableSource; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; import io.seata.sqlparser.ParametersHolder; import io.seata.sqlparser.SQLParsingException; @@ -28,9 +32,9 @@ import java.util.List; /** - * The type oracle select for update recognizer. + * The type dm select for update recognizer. * - * @author ccg + * @author chengxiaoxiao */ public class DmSelectForUpdateRecognizer extends BaseDmRecognizer implements SQLSelectRecognizer { diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java index 5c38d194d9c..00bfdefef76 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java @@ -21,7 +21,11 @@ import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLValuableExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; -import com.alibaba.druid.sql.ast.statement.*; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; +import com.alibaba.druid.sql.ast.statement.SQLTableSource; +import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem; +import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor; import io.seata.common.exception.NotSupportYetException; import io.seata.sqlparser.ParametersHolder; From 33f941ae2855a5eb10618e3488df46552dec24e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Tue, 11 May 2021 22:51:21 +0800 Subject: [PATCH 05/25] update: Optimize import format --- .../sql/struct/cache/DmTableMetaCache.java | 15 +++++++++++++++ .../rm/datasource/undo/dm/DmUndoLogManager.java | 6 +++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java index 48779cb3d01..aafdbeb0071 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java @@ -1,3 +1,18 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.rm.datasource.sql.struct.cache; import io.seata.common.exception.ShouldNeverHappenException; diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java index 3db7faf2a2e..39053e8b173 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoLogManager.java @@ -26,7 +26,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.*; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.Date; /** From c49429e790edb86419a5705e79178428fc43f9c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=81=9A=E5=85=A8=E6=A0=88=E6=94=BB=E5=9F=8E=E7=8B=AE?= Date: Thu, 13 May 2021 22:15:16 +0800 Subject: [PATCH 06/25] update: fix comments --- .../io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java | 4 ++-- .../io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java | 2 +- .../seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java | 2 +- .../java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java index c2496a72c7c..9ddd6bd0cdb 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoDeleteExecutor.java @@ -30,7 +30,7 @@ import java.util.stream.Collectors; /** - * The type oracle undo delete executor. + * The type dm undo delete executor. * * @author chengxiaoxiao */ @@ -42,7 +42,7 @@ public class DmUndoDeleteExecutor extends AbstractUndoExecutor { private static final String INSERT_SQL_TEMPLATE = "INSERT INTO %s (%s) VALUES (%s)"; /** - * Instantiates a new oracle undo delete executor. + * Instantiates a new dm undo delete executor. * * @param sqlUndoLog the sql undo log */ diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java index 31adf01d6df..9f60369ff69 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/DmUndoInsertExecutor.java @@ -32,7 +32,7 @@ import java.util.stream.Collectors; /** - * The type oralce undo insert executor. + * The type dm undo insert executor. * * @author chengxiaoxiao */ diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java index 8cf0f9efeb5..2d7d549e65d 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/dm/keyword/DmKeywordChecker.java @@ -806,7 +806,7 @@ public boolean check(String fieldOrTableName) { @Override public boolean checkEscape(String fieldOrTableName) { boolean check = check(fieldOrTableName); - // oracle + // dm // we are recommend table name and column name must uppercase. // if exists full uppercase, the table name or column name does't bundle escape symbol. if (!check && isUppercase(fieldOrTableName)) { diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java index 40a51bce6fa..fe8f639a754 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/BaseDmRecognizer.java @@ -33,7 +33,7 @@ public abstract class BaseDmRecognizer extends BaseRecognizer { /** - * Instantiates a new oracle base recognizer + * Instantiates a new dm base recognizer * * @param originalSql the original sql */ From 5fdc335b6f49bccae227e12883fab2579c9494e7 Mon Sep 17 00:00:00 2001 From: a364176773 <364176773@qq.com> Date: Tue, 15 Aug 2023 14:50:19 +0800 Subject: [PATCH 07/25] rollback --- build/pom.xml | 4 +- .../io/seata/common/ConfigurationKeys.java | 281 ++++-- .../java/io/seata/common/aot/NativeUtils.java | 5 +- .../common/loader/ExtensionDefinition.java | 14 +- .../io/seata/common/util/ReflectionUtil.java | 15 +- .../io/seata/common/util/StringUtils.java | 11 +- .../seata/common/util/ReflectionUtilTest.java | 6 +- .../io/seata/common/util/StringUtilsTest.java | 8 +- compressor/seata-compressor-zstd/pom.xml | 4 +- .../config/apollo/ApolloConfiguration.java | 22 +- .../config/consul/ConsulConfiguration.java | 140 +-- .../io/seata/config/ConfigurationCache.java | 40 +- .../seata/config/etcd3/EtcdConfiguration.java | 222 +++-- .../config/nacos/NacosConfiguration.java | 130 +-- .../config/zk/ZookeeperConfiguration.java | 64 +- console/pom.xml | 4 +- .../java/io/seata/console/constant/Code.java | 32 +- .../io/seata/console/result/PageResult.java | 28 +- .../java/io/seata/console/result/Result.java | 4 +- .../static/console-fe/public/index.html | 14 +- .../resources/static/console-fe/src/app.tsx | 12 +- console/src/main/resources/static/index.html | 12 +- .../saga-statemachine-designer/designer.html | 6 +- .../core/rpc/netty/NettyServerBootstrap.java | 24 +- .../server/ServerOnRequestProcessor.java | 99 +- .../serializer/SerializerServiceLoader.java | 6 +- .../db/sql/lock/AbstractLockStoreSql.java | 19 +- core/src/main/log4j.properties | 24 +- dependencies/pom.xml | 4 +- .../loadbalance/LoadBalanceTest.java | 52 +- .../etcd3/EtcdRegistryServiceImpl.java | 84 +- .../nacos/NacosRegistryServiceImpl.java | 138 +-- .../redis/RedisRegistryServiceImpl.java | 50 +- integration/brpc/pom.xml | 4 +- .../brpc/TransactionInterceptorTest.java | 28 +- .../io/seata/integration/brpc/dto/Echo.java | 906 ++++++++---------- integration/hsf/pom.xml | 4 +- integration/http-jakarta/pom.xml | 4 +- .../http/AbstractHttpExecutor.java | 76 +- .../prometheus/PrometheusExporter.java | 50 +- .../index.html | 2 +- script/client/spring/application.properties | 2 +- .../client/LoadBalancePropertiesTest.java | 10 +- .../SeataCoreEnvironmentPostProcessor.java | 20 +- .../autoconfigure/BasePropertiesTest.java | 3 +- .../SeataServerEnvironmentPostProcessor.java | 20 +- .../BatchResultMessageConvertor.java | 10 +- .../java/io/seata/server/ServerRunner.java | 4 +- .../server/console/vo/BranchSessionVO.java | 44 +- .../seata/server/console/vo/GlobalLockVO.java | 39 +- .../server/console/vo/GlobalSessionVO.java | 44 +- .../coordinator/DefaultCoordinator.java | 14 +- .../seata/server/session/GlobalSession.java | 270 +++--- .../db/lock/DataBaseDistributedLocker.java | 16 +- .../store/RedisTransactionStoreManager.java | 24 +- .../io/seata/server/store/StoreConfig.java | 24 +- .../coordinator/DefaultCoordinatorTest.java | 36 +- .../event/DefaultCoreForEventBusTest.java | 20 +- .../io/seata/server/lock/LockManagerTest.java | 196 ++-- .../session/FileSessionManagerTest.java | 184 ++-- .../server/session/GlobalSessionTest.java | 102 +- .../db/DataBaseSessionManagerTest.java | 13 +- .../server/session/redis/MockRedisServer.java | 8 +- .../redis/RedisDistributedLockerTest.java | 20 +- .../RedisTransactionStoreManagerTest.java | 10 +- spring-aot/pom.xml | 4 +- spring-aot/seata-spring-aot-client/pom.xml | 4 +- spring-aot/seata-spring-aot-core/pom.xml | 4 +- spring-framework-fake-for-java8/pom.xml | 4 +- .../annotation/AspectTransactional.java | 41 +- .../annotation/GlobalTransactionScanner.java | 187 ++-- .../GlobalTransactionalInterceptor.java | 116 +-- .../java/io/seata/rm/tcc/TCCFenceHandler.java | 23 +- .../seata/rm/tcc/config/TCCFenceConfig.java | 4 +- .../tcc/store/db/sql/TCCFenceStoreSqls.java | 42 +- .../at/ATModeSupportDataBaseDataTypeTest.java | 66 +- .../io/seata/at/DruidDataSourceUtils.java | 5 +- .../seata/at/mysql/MysqlUpdateJoinTest.java | 44 +- 78 files changed, 2242 insertions(+), 2087 deletions(-) diff --git a/build/pom.xml b/build/pom.xml index d586f504661..a62a445e1bc 100644 --- a/build/pom.xml +++ b/build/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - 4.0.0 diff --git a/common/src/main/java/io/seata/common/ConfigurationKeys.java b/common/src/main/java/io/seata/common/ConfigurationKeys.java index b3fcd934255..037ac246f4b 100644 --- a/common/src/main/java/io/seata/common/ConfigurationKeys.java +++ b/common/src/main/java/io/seata/common/ConfigurationKeys.java @@ -67,79 +67,77 @@ public interface ConfigurationKeys { * The constant SEATA_PREFIX. */ String SEATA_PREFIX = SEATA_FILE_ROOT_CONFIG + "."; - /** - * The constant SERVER_STORE_MODE. - */ - String SERVER_STORE_MODE = SEATA_PREFIX + STORE_PREFIX + MODE; - /** - * The constant SERVER_STORE_LOCK_MODE. - */ - String SERVER_STORE_LOCK_MODE = SEATA_PREFIX + STORE_PREFIX + "lock." + MODE; - /** - * The constant SERVER_SERVICE_PORT_CONFIG. - */ - String SERVER_SERVICE_PORT_CONFIG = SEATA_PREFIX + SERVER_PREFIX + "service-port"; - /** - * The constant SEATA_ACCESS_KEY. - */ - String SEATA_ACCESS_KEY = SEATA_PREFIX + ACCESS_KEY; - /** - * The constant SEATA_SECRET_KEY. - */ - String SEATA_SECRET_KEY = SEATA_PREFIX + SECRET_KEY; + /** * The constant SERVICE_PREFIX. */ String SERVICE_PREFIX = "service."; + /** * The constant STORE_PREFIX. */ String STORE_PREFIX = "store."; + /** * The constant SESSION_PREFIX. */ String SESSION_PREFIX = "session."; + /** * The constant STORE_SESSION_PREFIX. */ String STORE_SESSION_PREFIX = STORE_PREFIX + SESSION_PREFIX; - /** - * The constant STORE_SESSION_MODE. - */ - String STORE_SESSION_MODE = STORE_SESSION_PREFIX + MODE; - /** - * The constant SERVER_STORE_SESSION_MODE. - */ - String SERVER_STORE_SESSION_MODE = SEATA_PREFIX + STORE_SESSION_PREFIX + MODE; /** * The constant MODE. */ String MODE = "mode"; + /** * The constant STORE_MODE. */ String STORE_MODE = STORE_PREFIX + MODE; + + /** + * The constant SERVER_STORE_MODE. + */ + String SERVER_STORE_MODE = SEATA_PREFIX + STORE_PREFIX + MODE; + /** * The constant STORE_LOCK_MODE. */ String STORE_LOCK_MODE = STORE_PREFIX + "lock." + MODE; + + /** + * The constant SERVER_STORE_LOCK_MODE. + */ + String SERVER_STORE_LOCK_MODE = SEATA_PREFIX + STORE_PREFIX + "lock." + MODE; + + /** + * The constant STORE_SESSION_MODE. + */ + String STORE_SESSION_MODE = STORE_SESSION_PREFIX + MODE; + + /** + * The constant SERVER_STORE_SESSION_MODE. + */ + String SERVER_STORE_SESSION_MODE = SEATA_PREFIX + STORE_SESSION_PREFIX + MODE; + /** * The constant STORE_PUBLIC_KEY. */ String STORE_PUBLIC_KEY = STORE_PREFIX + "publicKey"; + /** * The constant STORE_FILE_PREFIX */ String STORE_FILE_PREFIX = STORE_PREFIX + "file."; + /** * The constant STORE_FILE_DIR */ String STORE_FILE_DIR = STORE_FILE_PREFIX + "dir"; - /** - * The constant SERVICE_SESSION_RELOAD_READ_SIZE - */ - String SERVICE_SESSION_RELOAD_READ_SIZE = STORE_FILE_PREFIX + "sessionReloadReadSize"; + /** * The constant SERVICE_GROUP_MAPPING_PREFIX. */ @@ -152,26 +150,32 @@ public interface ConfigurationKeys { * The constant SERVER_NODE_SPLIT_CHAR. */ String SERVER_NODE_SPLIT_CHAR = System.getProperty("line.separator"); + /** * The constant ENABLE_DEGRADE_POSTFIX. */ String ENABLE_DEGRADE_POSTFIX = "enableDegrade"; + /** * The constant CLIENT_PREFIX. */ String CLIENT_PREFIX = "client."; + /** * The constant SERVER_PREFIX. */ String SERVER_PREFIX = "server."; + /** * The constant TRANSPORT_PREFIX. */ String TRANSPORT_PREFIX = "transport."; + /** * The constant CLIENT_RM_PREFIX. */ String CLIENT_RM_PREFIX = CLIENT_PREFIX + "rm."; + /** * The constant CLIENT_ASYNC_COMMIT_BUFFER_LIMIT. */ @@ -180,6 +184,7 @@ public interface ConfigurationKeys { * The constant CLIENT_RM_LOCK_PREFIX. */ String CLIENT_RM_LOCK_PREFIX = CLIENT_RM_PREFIX + "lock."; + /** * The constant CLIENT_LOCK_RETRY_TIMES. */ @@ -192,54 +197,57 @@ public interface ConfigurationKeys { * The constant CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT. */ String CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT = CLIENT_RM_LOCK_PREFIX + "retryPolicyBranchRollbackOnConflict"; + + /** + * The constant SERVICE_SESSION_RELOAD_READ_SIZE + */ + String SERVICE_SESSION_RELOAD_READ_SIZE = STORE_FILE_PREFIX + "sessionReloadReadSize"; + /** * The constant CLIENT_REPORT_SUCCESS_ENABLE. */ String CLIENT_REPORT_SUCCESS_ENABLE = CLIENT_RM_PREFIX + "reportSuccessEnable"; + /** * The constant CLIENT_SAGA_BRANCH_REGISTER_ENABLE. */ String CLIENT_SAGA_BRANCH_REGISTER_ENABLE = CLIENT_RM_PREFIX + "sagaBranchRegisterEnable"; + /** * The constant CLIENT_SAGA_JSON_PARSER. */ String CLIENT_SAGA_JSON_PARSER = CLIENT_RM_PREFIX + "sagaJsonParser"; + /** * The constant CLIENT_SAGA_RETRY_PERSIST_MODE_UPDATE. */ String CLIENT_SAGA_RETRY_PERSIST_MODE_UPDATE = CLIENT_RM_PREFIX + "sagaRetryPersistModeUpdate"; + /** * The constant CLIENT_SAGA_COMPENSATE_PERSIST_MODE_UPDATE. */ String CLIENT_SAGA_COMPENSATE_PERSIST_MODE_UPDATE = CLIENT_RM_PREFIX + "sagaCompensatePersistModeUpdate"; + /** * The constant CLIENT_REPORT_RETRY_COUNT. */ String CLIENT_REPORT_RETRY_COUNT = CLIENT_RM_PREFIX + "reportRetryCount"; + /** * The constant CLIENT_TABLE_META_CHECK_ENABLE. */ String CLIENT_TABLE_META_CHECK_ENABLE = CLIENT_RM_PREFIX + "tableMetaCheckEnable"; + /** * The constant CLIENT_TABLE_META_CHECKER_INTERVAL. */ String CLIENT_TABLE_META_CHECKER_INTERVAL = CLIENT_RM_PREFIX + "tableMetaCheckerInterval"; + /** * The constant TCC_ACTION_INTERCEPTOR_ORDER. */ String TCC_ACTION_INTERCEPTOR_ORDER = CLIENT_RM_PREFIX + "tccActionInterceptorOrder"; - /** - * The constant SQL_PARSER_TYPE. - */ - String SQL_PARSER_TYPE = CLIENT_RM_PREFIX + "sqlParserType"; - /** - * The constant XA_BRANCH_EXECUTION_TIMEOUT - */ - String XA_BRANCH_EXECUTION_TIMEOUT = CLIENT_RM_PREFIX + "branchExecutionTimeoutXA"; - /** - * The constant XA_CONNECTION_TWO_PHASE_HOLD_TIMEOUT - */ - String XA_CONNECTION_TWO_PHASE_HOLD_TIMEOUT = CLIENT_RM_PREFIX + "connectionTwoPhaseHoldTimeoutXA"; + /** * The constant CLIENT_TM_PREFIX. */ @@ -248,176 +256,204 @@ public interface ConfigurationKeys { * The constant CLIENT_TM_COMMIT_RETRY_TIMES. */ String CLIENT_TM_COMMIT_RETRY_COUNT = CLIENT_TM_PREFIX + "commitRetryCount"; + /** * The constant CLIENT_TM_ROLLBACK_RETRY_TIMES. */ String CLIENT_TM_ROLLBACK_RETRY_COUNT = CLIENT_TM_PREFIX + "rollbackRetryCount"; + /** * The constant DEFAULT_GLOBAL_TRANSACTION_TIMEOUT. */ String DEFAULT_GLOBAL_TRANSACTION_TIMEOUT = CLIENT_TM_PREFIX + "defaultGlobalTransactionTimeout"; - /** - * The constant CLIENT_DEGRADE_CHECK_PERIOD. - */ - String CLIENT_DEGRADE_CHECK_PERIOD = CLIENT_TM_PREFIX + "degradeCheckPeriod"; - /** - * The constant CLIENT_DEGRADE_CHECK. - */ - String CLIENT_DEGRADE_CHECK = CLIENT_TM_PREFIX + "degradeCheck"; - /** - * The constant CLIENT_DEGRADE_CHECK_ALLOW_TIMES. - */ - String CLIENT_DEGRADE_CHECK_ALLOW_TIMES = CLIENT_TM_PREFIX + "degradeCheckAllowTimes"; - /** - * The constant GLOBAL_TRANSACTION_INTERCEPTOR_ORDER. - */ - String TM_INTERCEPTOR_ORDER = CLIENT_TM_PREFIX + "interceptorOrder"; + /** * The constant SERIALIZE_FOR_RPC. */ String SERIALIZE_FOR_RPC = TRANSPORT_PREFIX + "serialization"; + /** * The constant COMPRESSOR_FOR_RPC. * * @since 0.7.0 */ String COMPRESSOR_FOR_RPC = TRANSPORT_PREFIX + "compressor"; + /** * The constant STORE_DB_PREFIX. */ String STORE_DB_PREFIX = "store.db."; + /** * The constant STORE_REDIS_PREFIX. */ String STORE_REDIS_PREFIX = "store.redis."; + /** * The constant STORE_DB_GLOBAL_TABLE. */ String STORE_DB_GLOBAL_TABLE = STORE_DB_PREFIX + "globalTable"; + /** * The constant STORE_DB_BRANCH_TABLE. */ String STORE_DB_BRANCH_TABLE = STORE_DB_PREFIX + "branchTable"; + /** * The constant DISTRIBUTED_LOCK_DB_TABLE. */ String DISTRIBUTED_LOCK_DB_TABLE = STORE_DB_PREFIX + "distributedLockTable"; + /** * The constant STORE_DB_DATASOURCE_TYPE. */ String STORE_DB_DATASOURCE_TYPE = STORE_DB_PREFIX + "datasource"; + /** * The constant STORE_DB_TYPE. */ String STORE_DB_TYPE = STORE_DB_PREFIX + "dbType"; + /** * The constant STORE_DB_DRIVER_CLASS_NAME. */ String STORE_DB_DRIVER_CLASS_NAME = STORE_DB_PREFIX + "driverClassName"; + /** * The constant STORE_DB_MAX_WAIT. */ String STORE_DB_MAX_WAIT = STORE_DB_PREFIX + "maxWait"; + /** * The constant STORE_DB_URL. */ String STORE_DB_URL = STORE_DB_PREFIX + "url"; + /** * The constant STORE_DB_USER. */ String STORE_DB_USER = STORE_DB_PREFIX + "user"; + /** * The constant STORE_DB_PASSWORD. */ String STORE_DB_PASSWORD = STORE_DB_PREFIX + "password"; + /** * The constant STORE_DB_MIN_CONN. */ String STORE_DB_MIN_CONN = STORE_DB_PREFIX + "minConn"; + /** * The constant STORE_DB_MAX_CONN. */ String STORE_DB_MAX_CONN = STORE_DB_PREFIX + "maxConn"; + /** * The constant STORE_DB_LOG_QUERY_LIMIT. */ String STORE_DB_LOG_QUERY_LIMIT = STORE_DB_PREFIX + "queryLimit"; + /** * The constant LOCK_DB_TABLE. */ String LOCK_DB_TABLE = STORE_DB_PREFIX + "lockTable"; + /** * The constant SERVER_RPC_PORT. */ String SERVER_SERVICE_PORT_CAMEL = SERVER_PREFIX + "servicePort"; + + /** + * The constant SERVER_SERVICE_PORT_CONFIG. + */ + String SERVER_SERVICE_PORT_CONFIG = SEATA_PREFIX + SERVER_PREFIX + "service-port"; + /** * The constant ENV_SEATA_PORT_KEY. */ String ENV_SEATA_PORT_KEY = "SEATA_PORT"; + /** * The constant RECOVERY_PREFIX. */ String RECOVERY_PREFIX = SERVER_PREFIX + "recovery."; + /** * The constant COMMITING_RETRY_PERIOD. */ String COMMITING_RETRY_PERIOD = RECOVERY_PREFIX + "committingRetryPeriod"; + /** * The constant ASYN_COMMITING_RETRY_PERIOD. */ String ASYNC_COMMITING_RETRY_PERIOD = RECOVERY_PREFIX + "asyncCommittingRetryPeriod"; + /** * The constant ROLLBACKING_RETRY_PERIOD. */ String ROLLBACKING_RETRY_PERIOD = RECOVERY_PREFIX + "rollbackingRetryPeriod"; + /** * The constant TIMEOUT_RETRY_PERIOD. */ String TIMEOUT_RETRY_PERIOD = RECOVERY_PREFIX + "timeoutRetryPeriod"; + /** * The constant CLIENT_UNDO_PREFIX. */ String CLIENT_UNDO_PREFIX = "client.undo."; + /** * The constant TRANSACTION_UNDO_DATA_VALIDATION. */ String TRANSACTION_UNDO_DATA_VALIDATION = CLIENT_UNDO_PREFIX + "dataValidation"; + /** * The constant TRANSACTION_UNDO_LOG_SERIALIZATION. */ String TRANSACTION_UNDO_LOG_SERIALIZATION = CLIENT_UNDO_PREFIX + "logSerialization"; + /** * The constant TRANSACTION_UNDO_ONLY_CARE_UPDATE_COLUMNS. */ String TRANSACTION_UNDO_ONLY_CARE_UPDATE_COLUMNS = CLIENT_UNDO_PREFIX + "onlyCareUpdateColumns"; + /** * the constant CLIENT_UNDO_COMPRESS_PREFIX */ String CLIENT_UNDO_COMPRESS_PREFIX = CLIENT_UNDO_PREFIX + "compress."; + /** * the constant CLIENT_UNDO_COMPRESS_TYPE */ String CLIENT_UNDO_COMPRESS_TYPE = CLIENT_UNDO_COMPRESS_PREFIX + "type"; + /** * the constant CLIENT_UNDO_COMPRESS_ENABLE */ String CLIENT_UNDO_COMPRESS_ENABLE = CLIENT_UNDO_COMPRESS_PREFIX + "enable"; + /** * the constant CLIENT_UNDO_COMPRESS_THRESHOLD */ String CLIENT_UNDO_COMPRESS_THRESHOLD = CLIENT_UNDO_COMPRESS_PREFIX + "threshold"; + /** * The constant METRICS_PREFIX. */ String METRICS_PREFIX = "metrics."; + /** * The constant METRICS_ENABLED. */ String METRICS_ENABLED = "enabled"; + /** * The constant METRICS_REGISTRY_TYPE. */ String METRICS_REGISTRY_TYPE = "registryType"; + /** * The constant METRICS_EXPORTER_LIST. */ @@ -426,18 +462,22 @@ public interface ConfigurationKeys { * The constant METRICS_EXPORTER_PROMETHEUS_PORT */ String METRICS_EXPORTER_PROMETHEUS_PORT = "exporterPrometheusPort"; + /** * The constant SERVER_UNDO_PREFIX. */ String SERVER_UNDO_PREFIX = SERVER_PREFIX + "undo."; + /** * The constant TRANSACTION_UNDO_LOG_SAVE_DAYS. */ String TRANSACTION_UNDO_LOG_SAVE_DAYS = SERVER_UNDO_PREFIX + "logSaveDays"; + /** * The constant TRANSACTION_UNDO_LOG_DELETE_PERIOD */ String TRANSACTION_UNDO_LOG_DELETE_PERIOD = SERVER_UNDO_PREFIX + "logDeletePeriod"; + /** * The constant TRANSACTION_UNDO_LOG_TABLE */ @@ -446,211 +486,297 @@ public interface ConfigurationKeys { * The constant LOG_PREFIX */ String LOG_PREFIX = "log."; + /** * The constant TRANSACTION_UNDO_LOG_EXCEPTION_RATE */ String TRANSACTION_LOG_EXCEPTION_RATE = LOG_PREFIX + "exceptionRate"; + /** * The constant MAX_COMMIT_RETRY_TIMEOUT. */ String MAX_COMMIT_RETRY_TIMEOUT = SERVER_PREFIX + "maxCommitRetryTimeout"; + /** * The constant MAX_ROLLBACK_RETRY_TIMEOUT. */ String MAX_ROLLBACK_RETRY_TIMEOUT = SERVER_PREFIX + "maxRollbackRetryTimeout"; + /** * The constant ROLLBACK_RETRY_TIMEOUT_UNLOCK_ENABLE. */ String ROLLBACK_RETRY_TIMEOUT_UNLOCK_ENABLE = SERVER_PREFIX + "rollbackRetryTimeoutUnlockEnable"; + /** * the constant RETRY_DEAD_THRESHOLD */ String RETRY_DEAD_THRESHOLD = SERVER_PREFIX + "retryDeadThreshold"; + /** * the constant DISTRIBUTED_LOCK_EXPIRE_TIME */ String DISTRIBUTED_LOCK_EXPIRE_TIME = SERVER_PREFIX + "distributedLockExpireTime"; + /** * The constant MIN_SERVER_POOL_SIZE. */ String MIN_SERVER_POOL_SIZE = TRANSPORT_PREFIX + "minServerPoolSize"; + /** * The constant MAX_SERVER_POOL_SIZE. */ String MAX_SERVER_POOL_SIZE = TRANSPORT_PREFIX + "maxServerPoolSize"; + /** * The constant MIN_BRANCH_RESULT_POOL_SIZE. */ String MIN_BRANCH_RESULT_POOL_SIZE = TRANSPORT_PREFIX + "minBranchResultPoolSize"; + /** * The constant MAX_BRANCH_RESULT_POOL_SIZE. */ String MAX_BRANCH_RESULT_POOL_SIZE = TRANSPORT_PREFIX + "maxBranchResultPoolSize"; + /** * The constant MAX_TASK_QUEUE_SIZE. */ String MAX_TASK_QUEUE_SIZE = TRANSPORT_PREFIX + "maxTaskQueueSize"; + /** * The constant KEEP_ALIVE_TIME. */ String KEEP_ALIVE_TIME = TRANSPORT_PREFIX + "keepAliveTime"; + /** * The constant TRANSPORT_TYPE */ String TRANSPORT_TYPE = TRANSPORT_PREFIX + "type"; + /** * The constant TRANSPORT_SERVER */ String TRANSPORT_SERVER = TRANSPORT_PREFIX + "server"; + /** * The constant TRANSPORT_HEARTBEAT */ String TRANSPORT_HEARTBEAT = TRANSPORT_PREFIX + "heartbeat"; + /** * The constant THREAD_FACTORY_PREFIX */ String THREAD_FACTORY_PREFIX = TRANSPORT_PREFIX + "threadFactory."; + /** * The constant BOSS_THREAD_PREFIX */ String BOSS_THREAD_PREFIX = THREAD_FACTORY_PREFIX + "bossThreadPrefix"; + /** * The constant WORKER_THREAD_PREFIX */ String WORKER_THREAD_PREFIX = THREAD_FACTORY_PREFIX + "workerThreadPrefix"; + /** * The constant SERVER_EXECUTOR_THREAD_PREFIX */ String SERVER_EXECUTOR_THREAD_PREFIX = THREAD_FACTORY_PREFIX + "serverExecutorThreadPrefix"; + /** * The constant SHARE_BOSS_WORKER */ String SHARE_BOSS_WORKER = THREAD_FACTORY_PREFIX + "shareBossWorker"; + /** * The constant CLIENT_SELECTOR_THREAD_PREFIX */ String CLIENT_SELECTOR_THREAD_PREFIX = THREAD_FACTORY_PREFIX + "clientSelectorThreadPrefix"; + /** * The constant CLIENT_SELECTOR_THREAD_SIZE */ String CLIENT_SELECTOR_THREAD_SIZE = THREAD_FACTORY_PREFIX + "clientSelectorThreadSize"; + /** * The constant CLIENT_WORKER_THREAD_PREFIX */ String CLIENT_WORKER_THREAD_PREFIX = THREAD_FACTORY_PREFIX + "clientWorkerThreadPrefix"; + /** * The constant BOSS_THREAD_SIZE */ String BOSS_THREAD_SIZE = THREAD_FACTORY_PREFIX + "bossThreadSize"; + /** * The constant WORKER_THREAD_SIZE */ String WORKER_THREAD_SIZE = THREAD_FACTORY_PREFIX + "workerThreadSize"; + /** * The constant SHUTDOWN_PREFIX */ String SHUTDOWN_PREFIX = TRANSPORT_PREFIX + "shutdown."; + /** * The constant SHUTDOWN_WAIT */ String SHUTDOWN_WAIT = SHUTDOWN_PREFIX + "wait"; + /** * The constant ENABLE_CLIENT_BATCH_SEND_REQUEST */ @Deprecated String ENABLE_CLIENT_BATCH_SEND_REQUEST = TRANSPORT_PREFIX + "enableClientBatchSendRequest"; + /** * The constant ENABLE_TM_CLIENT_BATCH_SEND_REQUEST */ String ENABLE_TM_CLIENT_BATCH_SEND_REQUEST = TRANSPORT_PREFIX + "enableTmClientBatchSendRequest"; + /** * The constant ENABLE_RM_CLIENT_BATCH_SEND_REQUEST */ String ENABLE_RM_CLIENT_BATCH_SEND_REQUEST = TRANSPORT_PREFIX + "enableRmClientBatchSendRequest"; + /** * The constant ENABLE_TC_SERVER_BATCH_SEND_RESPONSE */ String ENABLE_TC_SERVER_BATCH_SEND_RESPONSE = TRANSPORT_PREFIX + "enableTcServerBatchSendResponse"; + /** * The constant DISABLE_GLOBAL_TRANSACTION. */ String DISABLE_GLOBAL_TRANSACTION = SERVICE_PREFIX + "disableGlobalTransaction"; + + /** + * The constant SQL_PARSER_TYPE. + */ + String SQL_PARSER_TYPE = CLIENT_RM_PREFIX + "sqlParserType"; + /** * The constant STORE_REDIS_MODE. */ String STORE_REDIS_MODE = STORE_REDIS_PREFIX + "mode"; + /** * The constant STORE_REDIS_HOST. */ String STORE_REDIS_HOST = STORE_REDIS_PREFIX + "host"; + /** * The constant STORE_REDIS_PORT. */ String STORE_REDIS_PORT = STORE_REDIS_PREFIX + "port"; + /** * The constant STORE_REDIS_SINGLE_PREFIX. */ String STORE_REDIS_SINGLE_PREFIX = STORE_REDIS_PREFIX + "single."; + /** * The constant STORE_REDIS_SINGLE_HOST. */ String STORE_REDIS_SINGLE_HOST = STORE_REDIS_SINGLE_PREFIX + "host"; - /** - * The constant STORE_REDIS_SINGLE_PORT. - */ - String STORE_REDIS_SINGLE_PORT = STORE_REDIS_SINGLE_PREFIX + "port"; + /** * The constant STORE_MIN_Conn. */ String STORE_REDIS_MIN_CONN = STORE_REDIS_PREFIX + "minConn"; + + /** + * The constant STORE_REDIS_SINGLE_PORT. + */ + String STORE_REDIS_SINGLE_PORT = STORE_REDIS_SINGLE_PREFIX + "port"; + /** * The constant STORE_REDIS_MAX_CONN. */ String STORE_REDIS_MAX_CONN = STORE_REDIS_PREFIX + "maxConn"; + /** * the constant STORE_REDIS_MAX_TOTAL */ String STORE_REDIS_MAX_TOTAL = STORE_REDIS_PREFIX + "maxTotal"; + /** * The constant STORE_REDIS_DATABASE. */ String STORE_REDIS_DATABASE = STORE_REDIS_PREFIX + "database"; + /** * The constant STORE_REDIS_PASSWORD. */ String STORE_REDIS_PASSWORD = STORE_REDIS_PREFIX + "password"; + /** * The constant STORE_REDIS_QUERY_LIMIT. */ String STORE_REDIS_QUERY_LIMIT = STORE_REDIS_PREFIX + "queryLimit"; + /** * The constant REDIS_SENTINEL_MODE. */ String REDIS_SENTINEL_MODE = "sentinel"; + /** * The constant REDIS_SINGLE_MODE. */ String REDIS_SINGLE_MODE = "single"; + /** * The constant STORE_REDIS_SENTINEL_PREFIX. */ String STORE_REDIS_SENTINEL_PREFIX = STORE_REDIS_PREFIX + "sentinel."; + /** * STORE_REDIS_SENTINEL_MASTERNAME. */ String STORE_REDIS_SENTINEL_MASTERNAME = STORE_REDIS_SENTINEL_PREFIX + "masterName"; + /** * STORE_REDIS_SENTINEL_HOST. */ String STORE_REDIS_SENTINEL_HOST = STORE_REDIS_SENTINEL_PREFIX + "sentinelHosts"; + + /** + * The constant CLIENT_DEGRADE_CHECK_PERIOD. + */ + String CLIENT_DEGRADE_CHECK_PERIOD = CLIENT_TM_PREFIX + "degradeCheckPeriod"; + + /** + * The constant CLIENT_DEGRADE_CHECK. + */ + String CLIENT_DEGRADE_CHECK = CLIENT_TM_PREFIX + "degradeCheck"; + /** + * The constant CLIENT_DEGRADE_CHECK_ALLOW_TIMES. + */ + String CLIENT_DEGRADE_CHECK_ALLOW_TIMES = CLIENT_TM_PREFIX + "degradeCheckAllowTimes"; + + /** + * The constant GLOBAL_TRANSACTION_INTERCEPTOR_ORDER. + */ + String TM_INTERCEPTOR_ORDER = CLIENT_TM_PREFIX + "interceptorOrder"; + /** * The constant ACCESS_KEY. */ String ACCESS_KEY = "accesskey"; + /** * The constant SECRET_KEY. */ String SECRET_KEY = "secretkey"; + + /** + * The constant SEATA_ACCESS_KEY. + */ + String SEATA_ACCESS_KEY = SEATA_PREFIX + ACCESS_KEY; + + /** + * The constant SEATA_SECRET_KEY. + */ + String SEATA_SECRET_KEY = SEATA_PREFIX + SECRET_KEY; + /** * The constant EXTRA_DATA_SPLIT_CHAR. */ @@ -659,70 +785,97 @@ public interface ConfigurationKeys { * The constant EXTRA_DATA_KV_CHAR. */ String EXTRA_DATA_KV_CHAR = "="; + /** * The constant SERVER_ENABLE_CHECK_AUTH. */ String SERVER_ENABLE_CHECK_AUTH = SERVER_PREFIX + "enableCheckAuth"; + /** * The constant APPLICATION_ID. */ String APPLICATION_ID = "applicationId"; + /** * The constant TX_SERVICE_GROUP. */ String TX_SERVICE_GROUP = "txServiceGroup"; + /** * The constant DATA_SOURCE_PROXY_MODE. */ String DATA_SOURCE_PROXY_MODE = "dataSourceProxyMode"; + /** * The constant TCC_PREFIX */ String TCC_PREFIX = "tcc."; + /** * The constant TCC_FENCE_PREFIX */ String TCC_FENCE_PREFIX = TCC_PREFIX + "fence."; + /** * The constant TCC_FENCE_CLEAN_PERIOD */ String TCC_FENCE_CLEAN_PERIOD = TCC_FENCE_PREFIX + "cleanPeriod"; + /** * The constant TCC_FENCE_LOG_TABLE_NAME */ String TCC_FENCE_LOG_TABLE_NAME = TCC_FENCE_PREFIX + "logTableName"; + /** * The constant rpcRmRequestTimeout */ String RPC_RM_REQUEST_TIMEOUT = TRANSPORT_PREFIX + "rpcRmRequestTimeout"; + /** * The constant RPC_TM_REQUEST_TIMEOUT */ String RPC_TM_REQUEST_TIMEOUT = TRANSPORT_PREFIX + "rpcTmRequestTimeout"; + /** * The constant RPC_TM_REQUEST_TIMEOUT */ String RPC_TC_REQUEST_TIMEOUT = TRANSPORT_PREFIX + "rpcTcRequestTimeout"; + /** * The constant SESSION_BRANCH_ASYNC_QUEUE_SIZE */ String SESSION_BRANCH_ASYNC_QUEUE_SIZE = SERVER_PREFIX + SESSION_PREFIX + "branchAsyncQueueSize"; + /** * The constant ENABLE_BRANCH_ASYNC_REMOVE */ String ENABLE_BRANCH_ASYNC_REMOVE = SERVER_PREFIX + SESSION_PREFIX + "enableBranchAsyncRemove"; + /** * The constant IS_USE_CLOUD_NAMESPACE_PARSING. */ String IS_USE_CLOUD_NAMESPACE_PARSING = "isUseCloudNamespaceParsing"; + /** * The constant IS_USE_ENDPOINT_PARSING_RULE. */ String IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule"; + /** * The constant XAER_NOTA_RETRY_TIMEOUT */ String XAER_NOTA_RETRY_TIMEOUT = SERVER_PREFIX + "xaerNotaRetryTimeout"; + + /** + * The constant XA_BRANCH_EXECUTION_TIMEOUT + */ + String XA_BRANCH_EXECUTION_TIMEOUT = CLIENT_RM_PREFIX + "branchExecutionTimeoutXA"; + + /** + * The constant XA_CONNECTION_TWO_PHASE_HOLD_TIMEOUT + */ + String XA_CONNECTION_TWO_PHASE_HOLD_TIMEOUT = CLIENT_RM_PREFIX + "connectionTwoPhaseHoldTimeoutXA"; + /** * The constant ENABLE_PARALLEL_REQUEST_HANDLE_KEY */ diff --git a/common/src/main/java/io/seata/common/aot/NativeUtils.java b/common/src/main/java/io/seata/common/aot/NativeUtils.java index 51130150f15..e708d9a78a5 100644 --- a/common/src/main/java/io/seata/common/aot/NativeUtils.java +++ b/common/src/main/java/io/seata/common/aot/NativeUtils.java @@ -22,7 +22,6 @@ */ public class NativeUtils { - public static final String SPRING_AOT_PROCESSING = "spring.aot.processing"; /** * The native-image code * @@ -30,6 +29,10 @@ public class NativeUtils { */ private static final String NATIVE_IMAGE_CODE = System.getProperty("org.graalvm.nativeimage.imagecode"); + + public static final String SPRING_AOT_PROCESSING = "spring.aot.processing"; + + /** * Whether Spring-AOT processing * diff --git a/common/src/main/java/io/seata/common/loader/ExtensionDefinition.java b/common/src/main/java/io/seata/common/loader/ExtensionDefinition.java index b10b865eb40..ea8b4790c1a 100644 --- a/common/src/main/java/io/seata/common/loader/ExtensionDefinition.java +++ b/common/src/main/java/io/seata/common/loader/ExtensionDefinition.java @@ -34,19 +34,19 @@ public Integer getOrder() { return this.order; } - public ExtensionDefinition(String name, Integer order, Scope scope, Class clazz) { - this.name = name; - this.order = order; - this.scope = scope; - this.serviceClass = clazz; + public Class getServiceClass() { + return this.serviceClass; } public Scope getScope() { return this.scope; } - public Class getServiceClass() { - return this.serviceClass; + public ExtensionDefinition(String name, Integer order, Scope scope, Class clazz) { + this.name = name; + this.order = order; + this.scope = scope; + this.serviceClass = clazz; } @Override diff --git a/common/src/main/java/io/seata/common/util/ReflectionUtil.java b/common/src/main/java/io/seata/common/util/ReflectionUtil.java index f86655d18a9..1028e7b0e56 100644 --- a/common/src/main/java/io/seata/common/util/ReflectionUtil.java +++ b/common/src/main/java/io/seata/common/util/ReflectionUtil.java @@ -38,37 +38,42 @@ */ public final class ReflectionUtil { + private ReflectionUtil() { + } + + + //region Constants + /** * The constant EMPTY_FIELD_ARRAY */ public static final Field[] EMPTY_FIELD_ARRAY = new Field[0]; - - //region Constants /** * The constant EMPTY_CLASS_ARRAY */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + /** * The constant EMPTY_ARGS */ public static final Object[] EMPTY_ARGS = new Object[0]; + /** * The cache CLASS_FIELDS_CACHE */ private static final Map, Field[]> CLASS_FIELDS_CACHE = new ConcurrentHashMap<>(); + /** * The cache FIELD_CACHE: Class -> fieldName -> Field */ private static final Map, Map> FIELD_CACHE = new ConcurrentHashMap<>(); + /** * The cache METHOD_CACHE: Class -> methodName|paramClassName1,paramClassName2,...,paramClassNameN -> Method */ private static final Map, Map> METHOD_CACHE = new ConcurrentHashMap<>(); - private ReflectionUtil() { - } - //endregion diff --git a/common/src/main/java/io/seata/common/util/StringUtils.java b/common/src/main/java/io/seata/common/util/StringUtils.java index e6280bde1f5..139541dded1 100644 --- a/common/src/main/java/io/seata/common/util/StringUtils.java +++ b/common/src/main/java/io/seata/common/util/StringUtils.java @@ -38,11 +38,8 @@ */ public class StringUtils { - /** - * Space string - */ - public static final String SPACE = " "; private static final Pattern CAMEL_PATTERN = Pattern.compile("[A-Z]"); + private static final Pattern LINE_PATTERN = Pattern.compile("-(\\w)"); private StringUtils() { } @@ -51,7 +48,11 @@ private StringUtils() { * empty string */ public static final String EMPTY = ""; - private static final Pattern LINE_PATTERN = Pattern.compile("-(\\w)"); + + /** + * Space string + */ + public static final String SPACE = " "; /** * Is empty boolean. diff --git a/common/src/test/java/io/seata/common/util/ReflectionUtilTest.java b/common/src/test/java/io/seata/common/util/ReflectionUtilTest.java index 2cb6b957890..f5c739de894 100644 --- a/common/src/test/java/io/seata/common/util/ReflectionUtilTest.java +++ b/common/src/test/java/io/seata/common/util/ReflectionUtilTest.java @@ -154,9 +154,6 @@ private void testGetAllFieldsInternal(Class clazz, String... fieldNames) { //region the test class and interface - interface TestInterface { - } - class EmptyClass { } @@ -185,6 +182,9 @@ public void setF2(String f2) { } } + interface TestInterface { + } + //endregion //endregion diff --git a/common/src/test/java/io/seata/common/util/StringUtilsTest.java b/common/src/test/java/io/seata/common/util/StringUtilsTest.java index 7d952ce3487..36e31f79eb7 100644 --- a/common/src/test/java/io/seata/common/util/StringUtilsTest.java +++ b/common/src/test/java/io/seata/common/util/StringUtilsTest.java @@ -256,6 +256,10 @@ interface TestInterface { void test(); } + abstract class TestAbstractClass { + abstract void test(); + } + @TestAnnotation(test = true) static class TestClass { public static boolean hashCodeTriggered = false; @@ -322,8 +326,4 @@ public String toString() { ')'; } } - - abstract class TestAbstractClass { - abstract void test(); - } } diff --git a/compressor/seata-compressor-zstd/pom.xml b/compressor/seata-compressor-zstd/pom.xml index 2562299306a..db3753af8c6 100755 --- a/compressor/seata-compressor-zstd/pom.xml +++ b/compressor/seata-compressor-zstd/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/config/seata-config-apollo/src/main/java/io/seata/config/apollo/ApolloConfiguration.java b/config/seata-config-apollo/src/main/java/io/seata/config/apollo/ApolloConfiguration.java index a12299ad351..55c5d4cb3e5 100644 --- a/config/seata-config-apollo/src/main/java/io/seata/config/apollo/ApolloConfiguration.java +++ b/config/seata-config-apollo/src/main/java/io/seata/config/apollo/ApolloConfiguration.java @@ -141,8 +141,13 @@ public boolean removeConfig(String dataId, long timeoutMills) { throw new NotSupportYetException("not support removeConfig"); } - public static String getApolloMetaFileKey() { - return String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_CONFIG, REGISTRY_TYPE, APOLLO_META); + @Override + public void addConfigListener(String dataId, ConfigurationChangeListener listener) { + if (StringUtils.isBlank(dataId) || listener == null) { + return; + } + LISTENER_SERVICE_MAP.computeIfAbsent(dataId, key -> ConcurrentHashMap.newKeySet()) + .add(listener); } @Override @@ -204,6 +209,10 @@ public String getTypeName() { return REGISTRY_TYPE; } + public static String getApolloMetaFileKey() { + return String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_CONFIG, REGISTRY_TYPE, APOLLO_META); + } + public static String getApolloSecretFileKey() { return String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_CONFIG, REGISTRY_TYPE, APOLLO_SECRET); } @@ -224,15 +233,6 @@ public static String getApolloConfigService() { return String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_CONFIG, REGISTRY_TYPE, APOLLO_CONFIG_SERVICE); } - @Override - public void addConfigListener(String dataId, ConfigurationChangeListener listener) { - if (StringUtils.isBlank(dataId) || listener == null) { - return; - } - LISTENER_SERVICE_MAP.computeIfAbsent(dataId, key -> ConcurrentHashMap.newKeySet()) - .add(listener); - } - private ConfigurationChangeType getChangeType(PropertyChangeType changeType) { switch (changeType) { diff --git a/config/seata-config-consul/src/main/java/io/seata/config/consul/ConsulConfiguration.java b/config/seata-config-consul/src/main/java/io/seata/config/consul/ConsulConfiguration.java index a6cb3bd9f85..33092b86f33 100644 --- a/config/seata-config-consul/src/main/java/io/seata/config/consul/ConsulConfiguration.java +++ b/config/seata-config-consul/src/main/java/io/seata/config/consul/ConsulConfiguration.java @@ -105,27 +105,6 @@ public static ConsulConfiguration getInstance() { return instance; } - private static String getConsulDataType() { - return ConfigProcessor.resolverConfigDataType(getConsulConfigKey()); - } - - private static String getConsulConfigKey() { - return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + CONSUL_CONFIG_KEY, DEFAULT_CONSUL_CONFIG_KEY_VALUE); - } - - private static String getSeataConfigStr() { - StringBuilder sb = new StringBuilder(); - - Enumeration enumeration = seataConfig.propertyNames(); - while (enumeration.hasMoreElements()) { - String key = (String) enumeration.nextElement(); - String property = seataConfig.getProperty(key); - sb.append(key).append("=").append(property).append("\n"); - } - - return sb.toString(); - } - @Override public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { String value = seataConfig.getProperty(dataId); @@ -153,25 +132,6 @@ public boolean putConfig(String dataId, String content, long timeoutMills) { return (Boolean) configFuture.get(); } - @Override - public void removeConfigListener(String dataId, ConfigurationChangeListener listener) { - if (StringUtils.isBlank(dataId) || listener == null) { - return; - } - Set configListeners = getConfigListeners(dataId); - if (CollectionUtils.isNotEmpty(configListeners)) { - ConfigurationChangeListener target; - for (ConfigurationChangeListener entry : configListeners) { - target = ((ConsulListener) entry).getTargetListener(); - if (listener.equals(target)) { - entry.onShutDown(); - configListeners.remove(entry); - break; - } - } - } - } - @Override public boolean putConfigIfAbsent(String dataId, String content, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUTIFABSENT, @@ -196,6 +156,55 @@ public boolean putConfigIfAbsent(String dataId, String content, long timeoutMill return (Boolean) configFuture.get(); } + @Override + public boolean removeConfig(String dataId, long timeoutMills) { + ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills); + if (!seataConfig.isEmpty()) { + seataConfig.remove(dataId); + consulNotifierExecutor.execute(() -> complete(getConsulClient().setKVValue(getConsulConfigKey(), getSeataConfigStr(), getAclToken(), null), configFuture)); + } else { + consulNotifierExecutor.execute(() -> complete(getConsulClient().deleteKVValue(dataId, getAclToken()), configFuture)); + } + return (Boolean) configFuture.get(); + } + + @Override + public void addConfigListener(String dataId, ConfigurationChangeListener listener) { + if (StringUtils.isBlank(dataId) || listener == null) { + return; + } + ConsulListener consulListener = new ConsulListener(dataId, listener); + CONFIG_LISTENERS_MAP.computeIfAbsent(dataId, key -> ConcurrentHashMap.newKeySet()) + .add(consulListener); + + // Start config change listener for the dataId. + consulListener.onProcessEvent(new ConfigurationChangeEvent()); + } + + @Override + public void removeConfigListener(String dataId, ConfigurationChangeListener listener) { + if (StringUtils.isBlank(dataId) || listener == null) { + return; + } + Set configListeners = getConfigListeners(dataId); + if (CollectionUtils.isNotEmpty(configListeners)) { + ConfigurationChangeListener target; + for (ConfigurationChangeListener entry : configListeners) { + target = ((ConsulListener) entry).getTargetListener(); + if (listener.equals(target)) { + entry.onShutDown(); + configListeners.remove(entry); + break; + } + } + } + } + + @Override + public Set getConfigListeners(String dataId) { + return CONFIG_LISTENERS_MAP.get(dataId); + } + @Override public String getTypeName() { return CONFIG_TYPE; @@ -247,36 +256,6 @@ private void complete(Response response, ConfigFuture configFuture) { } } - @Override - public boolean removeConfig(String dataId, long timeoutMills) { - ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills); - if (!seataConfig.isEmpty()) { - seataConfig.remove(dataId); - consulNotifierExecutor.execute(() -> complete(getConsulClient().setKVValue(getConsulConfigKey(), getSeataConfigStr(), getAclToken(), null), configFuture)); - } else { - consulNotifierExecutor.execute(() -> complete(getConsulClient().deleteKVValue(dataId, getAclToken()), configFuture)); - } - return (Boolean) configFuture.get(); - } - - @Override - public void addConfigListener(String dataId, ConfigurationChangeListener listener) { - if (StringUtils.isBlank(dataId) || listener == null) { - return; - } - ConsulListener consulListener = new ConsulListener(dataId, listener); - CONFIG_LISTENERS_MAP.computeIfAbsent(dataId, key -> ConcurrentHashMap.newKeySet()) - .add(consulListener); - - // Start config change listener for the dataId. - consulListener.onProcessEvent(new ConfigurationChangeEvent()); - } - - @Override - public Set getConfigListeners(String dataId) { - return CONFIG_LISTENERS_MAP.get(dataId); - } - private void initSeataConfig() { String key = getConsulConfigKey(); @@ -295,6 +274,27 @@ private void initSeataConfig() { consulListener.onProcessEvent(new ConfigurationChangeEvent()); } + private static String getConsulDataType() { + return ConfigProcessor.resolverConfigDataType(getConsulConfigKey()); + } + + private static String getConsulConfigKey() { + return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + CONSUL_CONFIG_KEY, DEFAULT_CONSUL_CONFIG_KEY_VALUE); + } + + private static String getSeataConfigStr() { + StringBuilder sb = new StringBuilder(); + + Enumeration enumeration = seataConfig.propertyNames(); + while (enumeration.hasMoreElements()) { + String key = (String) enumeration.nextElement(); + String property = seataConfig.getProperty(key); + sb.append(key).append("=").append(property).append("\n"); + } + + return sb.toString(); + } + /** * The type Consul listener. */ diff --git a/config/seata-config-core/src/main/java/io/seata/config/ConfigurationCache.java b/config/seata-config-core/src/main/java/io/seata/config/ConfigurationCache.java index 3df60c19206..f3e6bd6c224 100644 --- a/config/seata-config-core/src/main/java/io/seata/config/ConfigurationCache.java +++ b/config/seata-config-core/src/main/java/io/seata/config/ConfigurationCache.java @@ -81,10 +81,6 @@ public static ConfigurationCache getInstance() { return ConfigurationCacheInstance.INSTANCE; } - public static void clear() { - CONFIG_CACHE.clear(); - } - @Override public void onChangeEvent(ConfigurationChangeEvent event) { ObjectWrapper oldWrapper = CONFIG_CACHE.get(event.getDataId()); @@ -103,10 +99,6 @@ public void onChangeEvent(ConfigurationChangeEvent event) { } } - private static class ConfigurationCacheInstance { - private static final ConfigurationCache INSTANCE = new ConfigurationCache(); - } - public Configuration proxy(Configuration originalConfiguration) throws Exception { return (Configuration)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Configuration.class} , (proxy, method, args) -> { @@ -137,6 +129,14 @@ public Configuration proxy(Configuration originalConfiguration) throws Exception ); } + private static class ConfigurationCacheInstance { + private static final ConfigurationCache INSTANCE = new ConfigurationCache(); + } + + public static void clear() { + CONFIG_CACHE.clear(); + } + private static class ObjectWrapper { private final Object data; private final ConfigType type; @@ -156,14 +156,6 @@ public Object getData() { return data; } - public static boolean supportType(String type) { - return getTypeByName(type) != null; - } - - public static ConfigType getTypeByName(String postfix) { - return ConfigType.fromCode(postfix); - } - public ConfigType getType() { return type; } @@ -193,6 +185,14 @@ public Object convertData(ConfigType aType) { return null; } + public static boolean supportType(String type) { + return getTypeByName(type) != null; + } + + public static ConfigType getTypeByName(String postfix) { + return ConfigType.fromCode(postfix); + } + /** * Config Cache Operation type */ @@ -242,6 +242,10 @@ enum ConfigType { this.code = code; } + public String getCode() { + return code; + } + public static ConfigType fromCode(String code) { ConfigType configType = CODE_TO_VALUE.get(code.toUpperCase()); return configType == null ? ConfigType.STRING : configType; @@ -250,10 +254,6 @@ public static ConfigType fromCode(String code) { public static ConfigType fromName(String name) { return ConfigType.valueOf(name); } - - public String getCode() { - return code; - } } } } diff --git a/config/seata-config-etcd3/src/main/java/io/seata/config/etcd3/EtcdConfiguration.java b/config/seata-config-etcd3/src/main/java/io/seata/config/etcd3/EtcdConfiguration.java index c80976c4ffb..02cbd9d6287 100644 --- a/config/seata-config-etcd3/src/main/java/io/seata/config/etcd3/EtcdConfiguration.java +++ b/config/seata-config-etcd3/src/main/java/io/seata/config/etcd3/EtcdConfiguration.java @@ -118,101 +118,6 @@ public String getTypeName() { return CONFIG_TYPE; } - /** - * complete the future - * - * @param completableFuture - * @param configFuture - * @param - */ - private static void complete(CompletableFuture completableFuture, ConfigFuture configFuture) { - try { - T response = completableFuture.get(); - if (response instanceof GetResponse) { - List keyValues = ((GetResponse)response).getKvs(); - if (CollectionUtils.isNotEmpty(keyValues)) { - ByteSequence value = keyValues.get(0).getValue(); - if (value != null) { - configFuture.setResult(value.toString(UTF_8)); - } - } - } else if (response instanceof PutResponse) { - configFuture.setResult(Boolean.TRUE); - } else if (response instanceof TxnResponse) { - boolean result = ((TxnResponse)response).isSucceeded(); - //create key if file does not exist) - if (result) { - configFuture.setResult(Boolean.TRUE); - } - } else if (response instanceof DeleteResponse) { - configFuture.setResult(Boolean.TRUE); - } else { - throw new ShouldNeverHappenException("unsupported response type"); - } - } catch (Exception e) { - LOGGER.error("error occurred while completing the future{}", e.getMessage(),e); - } - } - - private static void initSeataConfig() { - String etcdConfigKey = getEtcdConfigKey(); - CompletableFuture future = getClient().getKVClient().get(ByteSequence.from(etcdConfigKey, UTF_8)); - try { - GetResponse getResponse = future.get(); - List kvs = getResponse.getKvs(); - if (!kvs.isEmpty()) { - seataConfig = ConfigProcessor.processConfig(new String(kvs.get(0).getValue().getBytes(), StandardCharsets.UTF_8), getEtcdDataType()); - - EtcdListener etcdListener = new EtcdListener(etcdConfigKey, null); - CONFIG_LISTENERS_MAP.computeIfAbsent(etcdConfigKey, key -> new ConcurrentSet<>()) - .add(etcdListener); - etcdListener.onProcessEvent(new ConfigurationChangeEvent()); - } - } catch (Exception e) { - LOGGER.error("init config properties error", e); - } - } - - private static String getEtcdConfigKey() { - return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + ETCD_CONFIG_KEY, DEFAULT_ETCD_CONFIG_KEY_VALUE); - } - - private static String getEtcdDataType() { - return ConfigProcessor.resolverConfigDataType(getEtcdConfigKey()); - } - - private static String getSeataConfigStr() { - StringBuilder sb = new StringBuilder(); - - Enumeration enumeration = seataConfig.propertyNames(); - while (enumeration.hasMoreElements()) { - String key = (String) enumeration.nextElement(); - String property = seataConfig.getProperty(key); - sb.append(key).append("=").append(property).append("\n"); - } - - return sb.toString(); - } - - @Override - public void removeConfigListener(String dataId, ConfigurationChangeListener listener) { - if (StringUtils.isBlank(dataId) || listener == null) { - return; - } - Set configListeners = getConfigListeners(dataId); - if (CollectionUtils.isNotEmpty(configListeners)) { - ConfigurationChangeListener target; - for (ConfigurationChangeListener entry : configListeners) { - target = ((EtcdListener)entry).getTargetListener(); - if (listener.equals(target)) { - entry.onShutDown(); - configListeners.remove(entry); - break; - } - } - } - } - @Override public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { String value = seataConfig.getProperty(dataId); @@ -226,23 +131,6 @@ public String getLatestConfig(String dataId, String defaultValue, long timeoutMi return (String)configFuture.get(); } - /** - * get client - * - * @return client - */ - private static Client getClient() { - if (client == null) { - synchronized (EtcdConfiguration.class) { - if (client == null) { - client = Client.builder().endpoints(FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + SERVER_ADDR_KEY)) - .build(); - } - } - } - return client; - } - @Override public boolean putConfig(String dataId, String content, long timeoutMills) { if (!seataConfig.isEmpty()) { @@ -316,11 +204,121 @@ public void addConfigListener(String dataId, ConfigurationChangeListener listene etcdListener.onProcessEvent(new ConfigurationChangeEvent()); } + @Override + public void removeConfigListener(String dataId, ConfigurationChangeListener listener) { + if (StringUtils.isBlank(dataId) || listener == null) { + return; + } + Set configListeners = getConfigListeners(dataId); + if (CollectionUtils.isNotEmpty(configListeners)) { + ConfigurationChangeListener target; + for (ConfigurationChangeListener entry : configListeners) { + target = ((EtcdListener)entry).getTargetListener(); + if (listener.equals(target)) { + entry.onShutDown(); + configListeners.remove(entry); + break; + } + } + } + } + @Override public Set getConfigListeners(String dataId) { return CONFIG_LISTENERS_MAP.get(dataId); } + /** + * get client + * + * @return client + */ + private static Client getClient() { + if (client == null) { + synchronized (EtcdConfiguration.class) { + if (client == null) { + client = Client.builder().endpoints(FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + SERVER_ADDR_KEY)) + .build(); + } + } + } + return client; + } + + /** + * complete the future + * + * @param completableFuture + * @param configFuture + * @param + */ + private static void complete(CompletableFuture completableFuture, ConfigFuture configFuture) { + try { + T response = completableFuture.get(); + if (response instanceof GetResponse) { + List keyValues = ((GetResponse)response).getKvs(); + if (CollectionUtils.isNotEmpty(keyValues)) { + ByteSequence value = keyValues.get(0).getValue(); + if (value != null) { + configFuture.setResult(value.toString(UTF_8)); + } + } + } else if (response instanceof PutResponse) { + configFuture.setResult(Boolean.TRUE); + } else if (response instanceof TxnResponse) { + boolean result = ((TxnResponse)response).isSucceeded(); + //create key if file does not exist) + if (result) { + configFuture.setResult(Boolean.TRUE); + } + } else if (response instanceof DeleteResponse) { + configFuture.setResult(Boolean.TRUE); + } else { + throw new ShouldNeverHappenException("unsupported response type"); + } + } catch (Exception e) { + LOGGER.error("error occurred while completing the future{}", e.getMessage(),e); + } + } + + private static void initSeataConfig() { + String etcdConfigKey = getEtcdConfigKey(); + CompletableFuture future = getClient().getKVClient().get(ByteSequence.from(etcdConfigKey, UTF_8)); + try { + GetResponse getResponse = future.get(); + List kvs = getResponse.getKvs(); + if (!kvs.isEmpty()) { + seataConfig = ConfigProcessor.processConfig(new String(kvs.get(0).getValue().getBytes(), StandardCharsets.UTF_8), getEtcdDataType()); + + EtcdListener etcdListener = new EtcdListener(etcdConfigKey, null); + CONFIG_LISTENERS_MAP.computeIfAbsent(etcdConfigKey, key -> new ConcurrentSet<>()) + .add(etcdListener); + etcdListener.onProcessEvent(new ConfigurationChangeEvent()); + } + } catch (Exception e) { + LOGGER.error("init config properties error", e); + } + } + + private static String getEtcdConfigKey() { + return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + ETCD_CONFIG_KEY, DEFAULT_ETCD_CONFIG_KEY_VALUE); + } + private static String getEtcdDataType() { + return ConfigProcessor.resolverConfigDataType(getEtcdConfigKey()); + } + private static String getSeataConfigStr() { + StringBuilder sb = new StringBuilder(); + + Enumeration enumeration = seataConfig.propertyNames(); + while (enumeration.hasMoreElements()) { + String key = (String) enumeration.nextElement(); + String property = seataConfig.getProperty(key); + sb.append(key).append("=").append(property).append("\n"); + } + + return sb.toString(); + } + /** * the type config change notifier */ diff --git a/config/seata-config-nacos/src/main/java/io/seata/config/nacos/NacosConfiguration.java b/config/seata-config-nacos/src/main/java/io/seata/config/nacos/NacosConfiguration.java index 63a8f1930a6..dde9431941d 100644 --- a/config/seata-config-nacos/src/main/java/io/seata/config/nacos/NacosConfiguration.java +++ b/config/seata-config-nacos/src/main/java/io/seata/config/nacos/NacosConfiguration.java @@ -102,54 +102,18 @@ private NacosConfiguration() { } } - private static Properties getConfigProperties() { - Properties properties = new Properties(); - properties.setProperty(ConfigurationKeys.IS_USE_CLOUD_NAMESPACE_PARSING, USE_PARSE_RULE); - properties.setProperty(ConfigurationKeys.IS_USE_ENDPOINT_PARSING_RULE, USE_PARSE_RULE); - if (System.getProperty(PRO_SERVER_ADDR_KEY) != null) { - properties.setProperty(PRO_SERVER_ADDR_KEY, System.getProperty(PRO_SERVER_ADDR_KEY)); - } else { - String address = FILE_CONFIG.getConfig(getNacosAddrFileKey()); - if (address != null) { - properties.setProperty(PRO_SERVER_ADDR_KEY, address); + @Override + public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { + String value = seataConfig.getProperty(dataId); + if (null == value) { + try { + value = configService.getConfig(dataId, getNacosGroup(), timeoutMills); + } catch (NacosException exx) { + LOGGER.error(exx.getErrMsg()); } } - if (System.getProperty(PRO_NAMESPACE_KEY) != null) { - properties.setProperty(PRO_NAMESPACE_KEY, System.getProperty(PRO_NAMESPACE_KEY)); - } else { - String namespace = FILE_CONFIG.getConfig(getNacosNameSpaceFileKey()); - if (namespace == null) { - namespace = DEFAULT_NAMESPACE; - } - properties.setProperty(PRO_NAMESPACE_KEY, namespace); - } - String userName = StringUtils.isNotBlank(System.getProperty(USER_NAME)) ? System.getProperty(USER_NAME) : FILE_CONFIG.getConfig(getNacosUserName()); - if (StringUtils.isNotBlank(userName)) { - String password = StringUtils.isNotBlank(System.getProperty(PASSWORD)) ? System.getProperty(PASSWORD) : FILE_CONFIG.getConfig(getNacosPassword()); - if (StringUtils.isNotBlank(password)) { - properties.setProperty(USER_NAME, userName); - properties.setProperty(PASSWORD, password); - LOGGER.info("Nacos check auth with userName/password."); - } - } else { - String accessKey = StringUtils.isNotBlank(System.getProperty(ACCESS_KEY)) ? - System.getProperty(ACCESS_KEY) : FILE_CONFIG.getConfig(getNacosAccessKey()); - if (StringUtils.isNotBlank(accessKey)) { - String secretKey = StringUtils.isNotBlank(System.getProperty(SECRET_KEY)) ? - System.getProperty(SECRET_KEY) : FILE_CONFIG.getConfig(getNacosSecretKey()); - if (StringUtils.isNotBlank(secretKey)) { - properties.put(ACCESS_KEY, accessKey); - properties.put(SECRET_KEY, secretKey); - LOGGER.info("Nacos check auth with ak/sk."); - } - } - } - String contextPath = StringUtils.isNotBlank(System.getProperty(CONTEXT_PATH)) ? System.getProperty(CONTEXT_PATH) : FILE_CONFIG.getConfig(getNacosContextPathKey()); - if (StringUtils.isNotBlank(contextPath)) { - properties.setProperty(CONTEXT_PATH, contextPath); - } - return properties; + return value == null ? defaultValue : value; } @Override @@ -238,6 +202,56 @@ public Set getConfigListeners(String dataId) { } } + private static Properties getConfigProperties() { + Properties properties = new Properties(); + properties.setProperty(ConfigurationKeys.IS_USE_CLOUD_NAMESPACE_PARSING, USE_PARSE_RULE); + properties.setProperty(ConfigurationKeys.IS_USE_ENDPOINT_PARSING_RULE, USE_PARSE_RULE); + if (System.getProperty(PRO_SERVER_ADDR_KEY) != null) { + properties.setProperty(PRO_SERVER_ADDR_KEY, System.getProperty(PRO_SERVER_ADDR_KEY)); + } else { + String address = FILE_CONFIG.getConfig(getNacosAddrFileKey()); + if (address != null) { + properties.setProperty(PRO_SERVER_ADDR_KEY, address); + } + } + + if (System.getProperty(PRO_NAMESPACE_KEY) != null) { + properties.setProperty(PRO_NAMESPACE_KEY, System.getProperty(PRO_NAMESPACE_KEY)); + } else { + String namespace = FILE_CONFIG.getConfig(getNacosNameSpaceFileKey()); + if (namespace == null) { + namespace = DEFAULT_NAMESPACE; + } + properties.setProperty(PRO_NAMESPACE_KEY, namespace); + } + String userName = StringUtils.isNotBlank(System.getProperty(USER_NAME)) ? System.getProperty(USER_NAME) : FILE_CONFIG.getConfig(getNacosUserName()); + if (StringUtils.isNotBlank(userName)) { + String password = StringUtils.isNotBlank(System.getProperty(PASSWORD)) ? System.getProperty(PASSWORD) : FILE_CONFIG.getConfig(getNacosPassword()); + if (StringUtils.isNotBlank(password)) { + properties.setProperty(USER_NAME, userName); + properties.setProperty(PASSWORD, password); + LOGGER.info("Nacos check auth with userName/password."); + } + } else { + String accessKey = StringUtils.isNotBlank(System.getProperty(ACCESS_KEY)) ? + System.getProperty(ACCESS_KEY) : FILE_CONFIG.getConfig(getNacosAccessKey()); + if (StringUtils.isNotBlank(accessKey)) { + String secretKey = StringUtils.isNotBlank(System.getProperty(SECRET_KEY)) ? + System.getProperty(SECRET_KEY) : FILE_CONFIG.getConfig(getNacosSecretKey()); + if (StringUtils.isNotBlank(secretKey)) { + properties.put(ACCESS_KEY, accessKey); + properties.put(SECRET_KEY, secretKey); + LOGGER.info("Nacos check auth with ak/sk."); + } + } + } + String contextPath = StringUtils.isNotBlank(System.getProperty(CONTEXT_PATH)) ? System.getProperty(CONTEXT_PATH) : FILE_CONFIG.getConfig(getNacosContextPathKey()); + if (StringUtils.isNotBlank(contextPath)) { + properties.setProperty(CONTEXT_PATH, contextPath); + } + return properties; + } + public static String getNacosNameSpaceFileKey() { return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_CONFIG, CONFIG_TYPE, PRO_NAMESPACE_KEY); } @@ -272,10 +286,6 @@ public static String getNacosSecretKey() { return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_CONFIG, CONFIG_TYPE, SECRET_KEY); } - private static String getNacosDataType() { - return ConfigProcessor.resolverConfigDataType(getNacosDataId()); - } - private static String getNacosGroup() { return FILE_CONFIG.getConfig(getNacosGroupKey(), DEFAULT_GROUP); } @@ -284,8 +294,8 @@ private static String getNacosDataId() { return FILE_CONFIG.getConfig(getNacosDataIdKey(), DEFAULT_DATA_ID); } - private static String getNacosContextPathKey() { - return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_CONFIG, CONFIG_TYPE, CONTEXT_PATH); + private static String getNacosDataType() { + return ConfigProcessor.resolverConfigDataType(getNacosDataId()); } private static String getSeataConfigStr() { @@ -301,6 +311,10 @@ private static String getSeataConfigStr() { return sb.toString(); } + private static String getNacosContextPathKey() { + return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_CONFIG, CONFIG_TYPE, CONTEXT_PATH); + } + private static void initSeataConfig() { try { String nacosDataId = getNacosDataId(); @@ -316,20 +330,6 @@ private static void initSeataConfig() { } } - @Override - public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { - String value = seataConfig.getProperty(dataId); - if (null == value) { - try { - value = configService.getConfig(dataId, getNacosGroup(), timeoutMills); - } catch (NacosException exx) { - LOGGER.error(exx.getErrMsg()); - } - } - - return value == null ? defaultValue : value; - } - @Override public String getTypeName() { diff --git a/config/seata-config-zk/src/main/java/io/seata/config/zk/ZookeeperConfiguration.java b/config/seata-config-zk/src/main/java/io/seata/config/zk/ZookeeperConfiguration.java index c609290ee2b..aad2dc520f8 100644 --- a/config/seata-config-zk/src/main/java/io/seata/config/zk/ZookeeperConfiguration.java +++ b/config/seata-config-zk/src/main/java/io/seata/config/zk/ZookeeperConfiguration.java @@ -118,8 +118,30 @@ public String getTypeName() { return CONFIG_TYPE; } - private static String getZkDataType() { - return ConfigProcessor.resolverConfigDataType(getConfigPath()); + @Override + public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { + String value = seataConfig.getProperty(dataId); + if (value != null) { + return value; + } + FutureTask future = new FutureTask<>(() -> { + String path = ROOT_PATH + ZK_PATH_SPLIT_CHAR + dataId; + if (!zkClient.exists(path)) { + LOGGER.warn("config {} is not existed, return defaultValue {} ", + dataId, defaultValue); + return defaultValue; + } + String value1 = zkClient.readData(path); + return StringUtils.isNullOrEmpty(value1) ? defaultValue : value1; + }); + CONFIG_EXECUTOR.execute(future); + try { + return future.get(timeoutMills, TimeUnit.MILLISECONDS); + } catch (Exception e) { + LOGGER.error("getConfig {} error or timeout, return defaultValue {}, exception:{} ", + dataId, defaultValue, e.getMessage()); + return defaultValue; + } } @Override @@ -235,36 +257,6 @@ public Set getConfigListeners(String dataId) { } } - @Override - public String getLatestConfig(String dataId, String defaultValue, long timeoutMills) { - String value = seataConfig.getProperty(dataId); - if (value != null) { - return value; - } - FutureTask future = new FutureTask<>(() -> { - String path = ROOT_PATH + ZK_PATH_SPLIT_CHAR + dataId; - if (!zkClient.exists(path)) { - LOGGER.warn("config {} is not existed, return defaultValue {} ", - dataId, defaultValue); - return defaultValue; - } - String value1 = zkClient.readData(path); - return StringUtils.isNullOrEmpty(value1) ? defaultValue : value1; - }); - CONFIG_EXECUTOR.execute(future); - try { - return future.get(timeoutMills, TimeUnit.MILLISECONDS); - } catch (Exception e) { - LOGGER.error("getConfig {} error or timeout, return defaultValue {}, exception:{} ", - dataId, defaultValue, e.getMessage()); - return defaultValue; - } - } - - private static String getConfigPath() { - return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + CONFIG_PATH_KEY, DEFAULT_CONFIG_PATH); - } - private void initSeataConfig() { String configPath = getConfigPath(); String config = zkClient.readData(configPath, true); @@ -279,6 +271,14 @@ private void initSeataConfig() { } } + private static String getConfigPath() { + return FILE_CONFIG.getConfig(FILE_CONFIG_KEY_PREFIX + CONFIG_PATH_KEY, DEFAULT_CONFIG_PATH); + } + + private static String getZkDataType() { + return ConfigProcessor.resolverConfigDataType(getConfigPath()); + } + private static String getSeataConfigStr() { StringBuilder sb = new StringBuilder(); diff --git a/console/pom.xml b/console/pom.xml index 6203323411a..62147c66d34 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/console/src/main/java/io/seata/console/constant/Code.java b/console/src/main/java/io/seata/console/constant/Code.java index 2a12f9b7737..aec8f019e18 100644 --- a/console/src/main/java/io/seata/console/constant/Code.java +++ b/console/src/main/java/io/seata/console/constant/Code.java @@ -49,22 +49,6 @@ private Code(String code, String msg) { this.msg = msg; } - /** - * Gets error msg. - * - * @param code the code - * @return the error msg - */ - public static String getErrorMsg(String code) { - Code[] errorCodes = values(); - for (Code errCode : errorCodes) { - if (errCode.getCode().equals(code)) { - return errCode.getMsg(); - } - } - return null; - } - /** * Gets code. * @@ -100,5 +84,21 @@ public String getMsg() { public void setMsg(String msg) { this.msg = msg; } + + /** + * Gets error msg. + * + * @param code the code + * @return the error msg + */ + public static String getErrorMsg(String code) { + Code[] errorCodes = values(); + for (Code errCode : errorCodes) { + if (errCode.getCode().equals(code)) { + return errCode.getMsg(); + } + } + return null; + } } diff --git a/console/src/main/java/io/seata/console/result/PageResult.java b/console/src/main/java/io/seata/console/result/PageResult.java index a8787880add..1acd87a7a99 100644 --- a/console/src/main/java/io/seata/console/result/PageResult.java +++ b/console/src/main/java/io/seata/console/result/PageResult.java @@ -66,20 +66,6 @@ public PageResult(List data, Integer total, Integer pages, Integer pageNum, I this.data = data; } - public PageResult(List data, Integer total, Integer pageNum, Integer pageSize) { - super(SUCCESS_CODE, SUCCESS_MSG); - this.total = total; - this.pageNum = pageNum; - this.pageSize = pageSize; - this.data = data; - - if (total % pageSize == 0) { - this.pages = total / pageSize; - } else { - this.pages = total / pageSize + 1; - } - } - public static PageResult build(List list, Integer pageNum, Integer pageSize) { // calculate pages int pages = list.size() / pageSize; @@ -99,6 +85,20 @@ public static PageResult build(List list, Integer pageNum, Integer pag ); } + public PageResult(List data, Integer total, Integer pageNum, Integer pageSize) { + super(SUCCESS_CODE, SUCCESS_MSG); + this.total = total; + this.pageNum = pageNum; + this.pageSize = pageSize; + this.data = data; + + if (total % pageSize == 0) { + this.pages = total / pageSize; + } else { + this.pages = total / pageSize + 1; + } + } + public static PageResult failure(String code, String msg) { return new PageResult<>(code, msg); } diff --git a/console/src/main/java/io/seata/console/result/Result.java b/console/src/main/java/io/seata/console/result/Result.java index a1615e10bc3..a90ed700dc4 100644 --- a/console/src/main/java/io/seata/console/result/Result.java +++ b/console/src/main/java/io/seata/console/result/Result.java @@ -22,9 +22,11 @@ * @author zhongxiang.wang */ public class Result implements Serializable { + private static final long serialVersionUID = 7761261124298767L; + public static final String SUCCESS_CODE = "200"; public static final String SUCCESS_MSG = "success"; - private static final long serialVersionUID = 7761261124298767L; + private String code = SUCCESS_CODE; private String message = SUCCESS_MSG; diff --git a/console/src/main/resources/static/console-fe/public/index.html b/console/src/main/resources/static/console-fe/public/index.html index c5e67b5b7f6..24df4b8ac43 100644 --- a/console/src/main/resources/static/console-fe/public/index.html +++ b/console/src/main/resources/static/console-fe/public/index.html @@ -19,15 +19,15 @@ - - + + Seata - - - + + + - - + + diff --git a/console/src/main/resources/static/console-fe/src/app.tsx b/console/src/main/resources/static/console-fe/src/app.tsx index 5a62dafb122..08e6c7254a9 100644 --- a/console/src/main/resources/static/console-fe/src/app.tsx +++ b/console/src/main/resources/static/console-fe/src/app.tsx @@ -59,6 +59,12 @@ class App extends React.Component { super(props); } + componentDidMount() { + console.log('this.props: ', this.props, history); + const language: string = getCurrentLanguage(); + this.props.changeLanguage(language); + } + get menu() { const { locale }: AppPropsType = this.props; const { MenuRouter = {} } = locale; @@ -113,12 +119,6 @@ class App extends React.Component { ); } - componentDidMount() { - console.log('this.props: ', this.props, history); - const language: string = getCurrentLanguage(); - this.props.changeLanguage(language); - } - render() { const { locale } = this.props; const { loading } = this.state; diff --git a/console/src/main/resources/static/index.html b/console/src/main/resources/static/index.html index a5be7ba112f..72ffa50518f 100644 --- a/console/src/main/resources/static/index.html +++ b/console/src/main/resources/static/index.html @@ -19,13 +19,13 @@ - - + + Seata - - - + + + @@ -33,6 +33,6 @@
- + diff --git a/console/src/main/resources/static/saga-statemachine-designer/designer.html b/console/src/main/resources/static/saga-statemachine-designer/designer.html index dc1b67632ff..058fc84d0a8 100644 --- a/console/src/main/resources/static/saga-statemachine-designer/designer.html +++ b/console/src/main/resources/static/saga-statemachine-designer/designer.html @@ -3,10 +3,10 @@ - - + + Seata Saga StateMachine Designer - + diff --git a/core/src/main/java/io/seata/core/rpc/netty/NettyServerBootstrap.java b/core/src/main/java/io/seata/core/rpc/netty/NettyServerBootstrap.java index 4770da2e06c..d41e296ee97 100644 --- a/core/src/main/java/io/seata/core/rpc/netty/NettyServerBootstrap.java +++ b/core/src/main/java/io/seata/core/rpc/netty/NettyServerBootstrap.java @@ -102,6 +102,18 @@ private void addChannelPipelineLast(Channel channel, ChannelHandler... handlers) } } + /** + * use for mock + * + * @param listenPort the listen port + */ + public void setListenPort(int listenPort) { + if (listenPort <= 0) { + throw new IllegalArgumentException("listen port: " + listenPort + " is invalid!"); + } + this.listenPort = listenPort; + } + /** * Gets listen port. * @@ -126,18 +138,6 @@ public int getListenPort() { return port; } - /** - * use for mock - * - * @param listenPort the listen port - */ - public void setListenPort(int listenPort) { - if (listenPort <= 0) { - throw new IllegalArgumentException("listen port: " + listenPort + " is invalid!"); - } - this.listenPort = listenPort; - } - @Override public void start() { this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker) diff --git a/core/src/main/java/io/seata/core/rpc/processor/server/ServerOnRequestProcessor.java b/core/src/main/java/io/seata/core/rpc/processor/server/ServerOnRequestProcessor.java index b4fe3b92f4a..5c1ee08d674 100644 --- a/core/src/main/java/io/seata/core/rpc/processor/server/ServerOnRequestProcessor.java +++ b/core/src/main/java/io/seata/core/rpc/processor/server/ServerOnRequestProcessor.java @@ -87,18 +87,21 @@ public class ServerOnRequestProcessor implements RemotingProcessor, Disposable { private static final Logger LOGGER = LoggerFactory.getLogger(ServerOnRequestProcessor.class); + private final RemotingServer remotingServer; + + private final TransactionMessageHandler transactionMessageHandler; + + private ExecutorService batchResponseExecutorService; + + private final ConcurrentMap> basketMap = new ConcurrentHashMap<>(); + protected final Object batchResponseLock = new Object(); + private volatile boolean isResponding = false; private static final int MAX_BATCH_RESPONSE_MILLS = 1; private static final int MAX_BATCH_RESPONSE_THREAD = 1; private static final long KEEP_ALIVE_TIME = Integer.MAX_VALUE; private static final String BATCH_RESPONSE_THREAD_PREFIX = "rpcBatchResponse"; private static final boolean PARALLEL_REQUEST_HANDLE = ConfigurationFactory.getInstance().getBoolean(ConfigurationKeys.ENABLE_PARALLEL_REQUEST_HANDLE_KEY, true); - protected final Object batchResponseLock = new Object(); - private final RemotingServer remotingServer; - private final TransactionMessageHandler transactionMessageHandler; - private final ConcurrentMap> basketMap = new ConcurrentHashMap<>(); - private ExecutorService batchResponseExecutorService; - private volatile boolean isResponding = false; public ServerOnRequestProcessor(RemotingServer remotingServer, TransactionMessageHandler transactionMessageHandler) { this.remotingServer = remotingServer; @@ -230,6 +233,48 @@ private void offerMsg(BlockingQueue msgQueue, RpcMessage rpcMessage, } } + /** + * batch response runnable + * + * @since 1.5.0 + */ + private class BatchResponseRunnable implements Runnable { + @Override + public void run() { + while (true) { + synchronized (batchResponseLock) { + try { + batchResponseLock.wait(MAX_BATCH_RESPONSE_MILLS); + } catch (InterruptedException e) { + LOGGER.error("BatchResponseRunnable Interrupted error", e); + } + } + isResponding = true; + basketMap.forEach((channel, msgQueue) -> { + if (msgQueue.isEmpty()) { + return; + } + // Because the [serialization,compressor,rpcMessageId,headMap] of the response + // needs to be the same as the [serialization,compressor,rpcMessageId,headMap] of the request. + // Assemble by grouping according to the [serialization,compressor,rpcMessageId,headMap] dimensions. + Map batchResultMessageMap = new HashMap<>(); + while (!msgQueue.isEmpty()) { + QueueItem item = msgQueue.poll(); + BatchResultMessage batchResultMessage = CollectionUtils.computeIfAbsent(batchResultMessageMap, + new ClientRequestRpcInfo(item.getRpcMessage()), + key -> new BatchResultMessage()); + batchResultMessage.getResultMessages().add(item.getResultMessage()); + batchResultMessage.getMsgIds().add(item.getMsgId()); + } + batchResultMessageMap.forEach((clientRequestRpcInfo, batchResultMessage) -> + remotingServer.sendAsyncResponse(buildRpcMessage(clientRequestRpcInfo), + channel, batchResultMessage)); + }); + isResponding = false; + } + } + } + /** * handle rpc request message * @param rpcContext rpcContext @@ -430,46 +475,4 @@ public void setRpcMessage(RpcMessage rpcMessage) { } } - /** - * batch response runnable - * - * @since 1.5.0 - */ - private class BatchResponseRunnable implements Runnable { - @Override - public void run() { - while (true) { - synchronized (batchResponseLock) { - try { - batchResponseLock.wait(MAX_BATCH_RESPONSE_MILLS); - } catch (InterruptedException e) { - LOGGER.error("BatchResponseRunnable Interrupted error", e); - } - } - isResponding = true; - basketMap.forEach((channel, msgQueue) -> { - if (msgQueue.isEmpty()) { - return; - } - // Because the [serialization,compressor,rpcMessageId,headMap] of the response - // needs to be the same as the [serialization,compressor,rpcMessageId,headMap] of the request. - // Assemble by grouping according to the [serialization,compressor,rpcMessageId,headMap] dimensions. - Map batchResultMessageMap = new HashMap<>(); - while (!msgQueue.isEmpty()) { - QueueItem item = msgQueue.poll(); - BatchResultMessage batchResultMessage = CollectionUtils.computeIfAbsent(batchResultMessageMap, - new ClientRequestRpcInfo(item.getRpcMessage()), - key -> new BatchResultMessage()); - batchResultMessage.getResultMessages().add(item.getResultMessage()); - batchResultMessage.getMsgIds().add(item.getMsgId()); - } - batchResultMessageMap.forEach((clientRequestRpcInfo, batchResultMessage) -> - remotingServer.sendAsyncResponse(buildRpcMessage(clientRequestRpcInfo), - channel, batchResultMessage)); - }); - isResponding = false; - } - } - } - } diff --git a/core/src/main/java/io/seata/core/serializer/SerializerServiceLoader.java b/core/src/main/java/io/seata/core/serializer/SerializerServiceLoader.java index c3becc8d18f..e602567d444 100644 --- a/core/src/main/java/io/seata/core/serializer/SerializerServiceLoader.java +++ b/core/src/main/java/io/seata/core/serializer/SerializerServiceLoader.java @@ -26,12 +26,12 @@ */ public final class SerializerServiceLoader { - private static final String PROTOBUF_SERIALIZER_CLASS_NAME = "io.seata.serializer.protobuf.ProtobufSerializer"; - - private SerializerServiceLoader() { } + + private static final String PROTOBUF_SERIALIZER_CLASS_NAME = "io.seata.serializer.protobuf.ProtobufSerializer"; + /** * Load the service of {@link Serializer} * diff --git a/core/src/main/java/io/seata/core/store/db/sql/lock/AbstractLockStoreSql.java b/core/src/main/java/io/seata/core/store/db/sql/lock/AbstractLockStoreSql.java index 477ddad015c..0a2b68e1028 100644 --- a/core/src/main/java/io/seata/core/store/db/sql/lock/AbstractLockStoreSql.java +++ b/core/src/main/java/io/seata/core/store/db/sql/lock/AbstractLockStoreSql.java @@ -33,10 +33,7 @@ */ public class AbstractLockStoreSql implements LockStoreSql { - /** - * The constant WHERE_PLACE_HOLD - */ - protected static final String WHERE_PLACE_HOLD = " #where# "; + private static final int MAX_IN_SIZE = 1000; /** * The constant CONFIG. @@ -48,17 +45,25 @@ public class AbstractLockStoreSql implements LockStoreSql { */ protected static final String LOCK_TABLE_PLACE_HOLD = " #lock_table# "; /** - * The constant LOCK_TABLE_PK_WHERE_CONDITION_PLACE_HOLD. + * The constant WHERE_PLACE_HOLD */ - protected static final String LOCK_TABLE_PK_WHERE_CONDITION_PLACE_HOLD = " #lock_table_pk_where_condition# "; + protected static final String WHERE_PLACE_HOLD = " #where# "; /** * The constant IN_PARAMS_PLACE_HOLD. */ protected static final String IN_PARAMS_PLACE_HOLD = " #in_params# "; + + /** + * The constant LOCK_TABLE_PK_WHERE_CONDITION_PLACE_HOLD. + */ + protected static final String LOCK_TABLE_PK_WHERE_CONDITION_PLACE_HOLD = " #lock_table_pk_where_condition# "; + /** * The constant LOCK_TABLE_BRANCH_ID_WHERE_CONDITION_PLACE_HOLD. */ protected static final String LOCK_TABLE_BRANCH_ID_WHERE_CONDITION_PLACE_HOLD = " #lock_table_branch_id_where_condition# "; + + /** * The constant ALL_COLUMNS. * xid, transaction_id, branch_id, resource_id, table_name, pk, row_key, gmt_create, gmt_modified @@ -69,13 +74,13 @@ public class AbstractLockStoreSql implements LockStoreSql { + ServerTableColumnsName.LOCK_TABLE_TABLE_NAME + ", " + ServerTableColumnsName.LOCK_TABLE_PK + ", " + ServerTableColumnsName.LOCK_TABLE_ROW_KEY + ", " + ServerTableColumnsName.LOCK_TABLE_GMT_CREATE + ", " + ServerTableColumnsName.LOCK_TABLE_GMT_MODIFIED + "," + ServerTableColumnsName.LOCK_TABLE_STATUS; - private static final int MAX_IN_SIZE = 1000; /** * The constant DELETE_LOCK_SQL. */ private static final String DELETE_LOCK_SQL = "delete from " + LOCK_TABLE_PLACE_HOLD + " where " + ServerTableColumnsName.LOCK_TABLE_ROW_KEY + " = ? and " + ServerTableColumnsName.LOCK_TABLE_XID + " = ?"; + /** * The constant BATCH_DELETE_LOCK_SQL. */ diff --git a/core/src/main/log4j.properties b/core/src/main/log4j.properties index 5e9e109004a..05ba0e365a1 100644 --- a/core/src/main/log4j.properties +++ b/core/src/main/log4j.properties @@ -16,16 +16,16 @@ log4j.rootCategory=info,R -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=info -log4j.appender.console.layout=org.apache.log4j.PatternLayout -log4j.appender.console.layout.ConversionPattern=- %m%n +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.Threshold=info +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=- %m%n -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.Append=true -log4j.appender.R.Threshold=info -log4j.appender.R.MaxFileSize=102400KB -log4j.appender.R.MaxBackupIndex=10 -log4j.appender.R.File=${WORKDIR}/logs/biz.log -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.Append=true +log4j.appender.R.Threshold=info +log4j.appender.R.MaxFileSize=102400KB +log4j.appender.R.MaxBackupIndex=10 +log4j.appender.R.File=${WORKDIR}/logs/biz.log +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n diff --git a/dependencies/pom.xml b/dependencies/pom.xml index 653b8872f11..1a2c27bc67b 100644 --- a/dependencies/pom.xml +++ b/dependencies/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/discovery/seata-discovery-core/src/test/java/io/seata/discovery/loadbalance/LoadBalanceTest.java b/discovery/seata-discovery-core/src/test/java/io/seata/discovery/loadbalance/LoadBalanceTest.java index 329f2e4fd08..0b113c12b2d 100644 --- a/discovery/seata-discovery-core/src/test/java/io/seata/discovery/loadbalance/LoadBalanceTest.java +++ b/discovery/seata-discovery-core/src/test/java/io/seata/discovery/loadbalance/LoadBalanceTest.java @@ -68,19 +68,23 @@ public void testRoundRobinLoadBalance_select(List addresses) } /** - * Address provider object [ ] [ ]. + * Test xid load load balance select. * - * @return Stream> + * @param addresses the addresses */ - static Stream> addressProvider() { - return Stream.of( - Arrays.asList(new InetSocketAddress("127.0.0.1", 8091), - new InetSocketAddress("127.0.0.1", 8092), - new InetSocketAddress("127.0.0.1", 8093), - new InetSocketAddress("127.0.0.1", 8094), - new InetSocketAddress("127.0.0.1", 8095), - new InetSocketAddress("2000:0000:0000:0000:0001:2345:6789:abcd", 8092)) - ); + @ParameterizedTest + @MethodSource("addressProvider") + public void testXIDLoadBalance_select(List addresses) throws Exception { + XIDLoadBalance loadBalance = new XIDLoadBalance(); + // ipv4 + InetSocketAddress inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8092:123456"); + Assertions.assertNotNull(inetSocketAddress); + // ipv6 + inetSocketAddress = loadBalance.select(addresses, "2000:0000:0000:0000:0001:2345:6789:abcd:8092:123456"); + Assertions.assertNotNull(inetSocketAddress); + // test not found tc channel + inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8199:123456"); + Assertions.assertNotEquals(inetSocketAddress.getPort(),8199); } /** @@ -162,22 +166,18 @@ public Map getSelectedCounter(int runs, List> */ - @ParameterizedTest - @MethodSource("addressProvider") - public void testXIDLoadBalance_select(List addresses) throws Exception { - XIDLoadBalance loadBalance = new XIDLoadBalance(); - // ipv4 - InetSocketAddress inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8092:123456"); - Assertions.assertNotNull(inetSocketAddress); - // ipv6 - inetSocketAddress = loadBalance.select(addresses, "2000:0000:0000:0000:0001:2345:6789:abcd:8092:123456"); - Assertions.assertNotNull(inetSocketAddress); - // test not found tc channel - inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8199:123456"); - Assertions.assertNotEquals(inetSocketAddress.getPort(),8199); + static Stream> addressProvider() { + return Stream.of( + Arrays.asList(new InetSocketAddress("127.0.0.1", 8091), + new InetSocketAddress("127.0.0.1", 8092), + new InetSocketAddress("127.0.0.1", 8093), + new InetSocketAddress("127.0.0.1", 8094), + new InetSocketAddress("127.0.0.1", 8095), + new InetSocketAddress("2000:0000:0000:0000:0001:2345:6789:abcd", 8092)) + ); } } diff --git a/discovery/seata-discovery-etcd3/src/main/java/io/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java b/discovery/seata-discovery-etcd3/src/main/java/io/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java index bb63abedbd4..b2bc4b1858e 100644 --- a/discovery/seata-discovery-etcd3/src/main/java/io/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java +++ b/discovery/seata-discovery-etcd3/src/main/java/io/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java @@ -326,48 +326,6 @@ private ByteSequence buildRegistryValue(InetSocketAddress address) { return ByteSequence.from(NetUtil.toStringAddress(address), UTF_8); } - private static class Pair { - - /** - * Key of this Pair. - */ - private K key; - - /** - * Value of this this Pair. - */ - private V value; - - /** - * Creates a new pair - * - * @param key The key for this pair - * @param value The value to use for this pair - */ - public Pair(K key, V value) { - this.key = key; - this.value = value; - } - - /** - * Gets the key for this pair. - * - * @return key for this pair - */ - public K getKey() { - return key; - } - - /** - * Gets the value for this pair. - * - * @return value for this pair - */ - public V getValue() { - return value; - } - } - /** * the type etcd life keeper */ @@ -455,4 +413,46 @@ public void stop() { this.watcher.close(); } } + + private static class Pair { + + /** + * Key of this Pair. + */ + private K key; + + /** + * Value of this this Pair. + */ + private V value; + + /** + * Creates a new pair + * + * @param key The key for this pair + * @param value The value to use for this pair + */ + public Pair(K key, V value) { + this.key = key; + this.value = value; + } + + /** + * Gets the key for this pair. + * + * @return key for this pair + */ + public K getKey() { + return key; + } + + /** + * Gets the value for this pair. + * + * @return value for this pair + */ + public V getValue() { + return value; + } + } } diff --git a/discovery/seata-discovery-nacos/src/main/java/io/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java b/discovery/seata-discovery-nacos/src/main/java/io/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java index 9f20c43028b..9a62552ea39 100644 --- a/discovery/seata-discovery-nacos/src/main/java/io/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java +++ b/discovery/seata-discovery-nacos/src/main/java/io/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java @@ -78,9 +78,9 @@ public class NacosRegistryServiceImpl implements RegistryService private static final ConcurrentMap> LISTENER_SERVICE_MAP = new ConcurrentHashMap<>(); private static final ConcurrentMap> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>(); private static volatile NacosRegistryServiceImpl instance; - private static final Pattern DEFAULT_SLB_REGISTRY_PATTERN = Pattern.compile("(?!.*internal)(?=.*seata).*mse.aliyuncs.com"); - private static final Object LOCK_OBJ = new Object(); private static volatile NamingMaintainService namingMaintain; + private static final Object LOCK_OBJ = new Object(); + private static final Pattern DEFAULT_SLB_REGISTRY_PATTERN = Pattern.compile("(?!.*internal)(?=.*seata).*mse.aliyuncs.com"); private static volatile Boolean useSLBWay; private NacosRegistryServiceImpl() { @@ -142,15 +142,61 @@ public void unsubscribe(String cluster, EventListener listener) throws Exception getNamingInstance().unsubscribe(getServiceName(), getServiceGroup(), clusters, listener); } - public static NamingMaintainService getNamingMaintainInstance() throws Exception { - if (namingMaintain == null) { - synchronized (NacosRegistryServiceImpl.class) { - if (namingMaintain == null) { - namingMaintain = NacosFactory.createMaintainService(getNamingProperties()); + @Override + public List lookup(String key) throws Exception { + String clusterName = getServiceGroup(key); + if (clusterName == null) { + String missingDataId = PREFIX_SERVICE_ROOT + CONFIG_SPLIT_CHAR + PREFIX_SERVICE_MAPPING + key; + throw new ConfigNotFoundException("%s configuration item is required", missingDataId); + } + if (useSLBWay) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("look up service address of SLB by nacos"); + } + if (!CLUSTER_ADDRESS_MAP.containsKey(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName)) { + Service service = getNamingMaintainInstance().queryService(DEFAULT_APPLICATION, clusterName); + String pubnetIp = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_IP_KEY); + String pubnetPort = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_PORT_KEY); + if (StringUtils.isBlank(pubnetIp) || StringUtils.isBlank(pubnetPort)) { + throw new Exception("cannot find service address from nacos naming mata-data"); } + InetSocketAddress publicAddress = new InetSocketAddress(pubnetIp, + Integer.valueOf(pubnetPort)); + List publicAddressList = Arrays.asList(publicAddress); + CLUSTER_ADDRESS_MAP.put(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName, publicAddressList); + return publicAddressList; } + return CLUSTER_ADDRESS_MAP.get(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName); } - return namingMaintain; + if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) { + synchronized (LOCK_OBJ) { + if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) { + List clusters = new ArrayList<>(); + clusters.add(clusterName); + List firstAllInstances = getNamingInstance().getAllInstances(getServiceName(), getServiceGroup(), clusters); + if (null != firstAllInstances) { + List newAddressList = firstAllInstances.stream() + .filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy()) + .map(eachInstance -> new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort())) + .collect(Collectors.toList()); + CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList); + } + subscribe(clusterName, event -> { + List instances = ((NamingEvent) event).getInstances(); + if (CollectionUtils.isEmpty(instances) && null != CLUSTER_ADDRESS_MAP.get(clusterName)) { + LOGGER.info("receive empty server list,cluster:{}", clusterName); + } else { + List newAddressList = instances.stream() + .filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy()) + .map(eachInstance -> new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort())) + .collect(Collectors.toList()); + CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList); + } + }); + } + } + } + return CLUSTER_ADDRESS_MAP.get(clusterName); } @Override @@ -175,6 +221,17 @@ public static NamingService getNamingInstance() throws Exception { return naming; } + public static NamingMaintainService getNamingMaintainInstance() throws Exception { + if (namingMaintain == null) { + synchronized (NacosRegistryServiceImpl.class) { + if (namingMaintain == null) { + namingMaintain = NacosFactory.createMaintainService(getNamingProperties()); + } + } + } + return namingMaintain; + } + private static Properties getNamingProperties() { Properties properties = new Properties(); properties.setProperty(ConfigurationKeys.IS_USE_CLOUD_NAMESPACE_PARSING, USE_PARSE_RULE); @@ -221,10 +278,6 @@ private static Properties getNamingProperties() { return properties; } - public static String getNacosAccessKey() { - return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_REGISTRY, REGISTRY_TYPE, ACCESS_KEY); - } - private static String getClusterName() { return FILE_CONFIG.getConfig(getNacosClusterFileKey(), DEFAULT_CLUSTER); } @@ -265,6 +318,10 @@ private static String getNacosPassword() { return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_REGISTRY, REGISTRY_TYPE, PASSWORD); } + public static String getNacosAccessKey() { + return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_REGISTRY, REGISTRY_TYPE, ACCESS_KEY); + } + public static String getNacosSecretKey() { return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_REGISTRY, REGISTRY_TYPE, SECRET_KEY); } @@ -277,61 +334,4 @@ private static String getNacosContextPathKey() { return String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR, ConfigurationKeys.FILE_ROOT_REGISTRY, REGISTRY_TYPE, CONTEXT_PATH); } - @Override - public List lookup(String key) throws Exception { - String clusterName = getServiceGroup(key); - if (clusterName == null) { - String missingDataId = PREFIX_SERVICE_ROOT + CONFIG_SPLIT_CHAR + PREFIX_SERVICE_MAPPING + key; - throw new ConfigNotFoundException("%s configuration item is required", missingDataId); - } - if (useSLBWay) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("look up service address of SLB by nacos"); - } - if (!CLUSTER_ADDRESS_MAP.containsKey(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName)) { - Service service = getNamingMaintainInstance().queryService(DEFAULT_APPLICATION, clusterName); - String pubnetIp = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_IP_KEY); - String pubnetPort = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_PORT_KEY); - if (StringUtils.isBlank(pubnetIp) || StringUtils.isBlank(pubnetPort)) { - throw new Exception("cannot find service address from nacos naming mata-data"); - } - InetSocketAddress publicAddress = new InetSocketAddress(pubnetIp, - Integer.valueOf(pubnetPort)); - List publicAddressList = Arrays.asList(publicAddress); - CLUSTER_ADDRESS_MAP.put(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName, publicAddressList); - return publicAddressList; - } - return CLUSTER_ADDRESS_MAP.get(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName); - } - if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) { - synchronized (LOCK_OBJ) { - if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) { - List clusters = new ArrayList<>(); - clusters.add(clusterName); - List firstAllInstances = getNamingInstance().getAllInstances(getServiceName(), getServiceGroup(), clusters); - if (null != firstAllInstances) { - List newAddressList = firstAllInstances.stream() - .filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy()) - .map(eachInstance -> new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort())) - .collect(Collectors.toList()); - CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList); - } - subscribe(clusterName, event -> { - List instances = ((NamingEvent) event).getInstances(); - if (CollectionUtils.isEmpty(instances) && null != CLUSTER_ADDRESS_MAP.get(clusterName)) { - LOGGER.info("receive empty server list,cluster:{}", clusterName); - } else { - List newAddressList = instances.stream() - .filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy()) - .map(eachInstance -> new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort())) - .collect(Collectors.toList()); - CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList); - } - }); - } - } - } - return CLUSTER_ADDRESS_MAP.get(clusterName); - } - } diff --git a/discovery/seata-discovery-redis/src/main/java/io/seata/discovery/registry/redis/RedisRegistryServiceImpl.java b/discovery/seata-discovery-redis/src/main/java/io/seata/discovery/registry/redis/RedisRegistryServiceImpl.java index c84d0fc6beb..77b988a47b0 100644 --- a/discovery/seata-discovery-redis/src/main/java/io/seata/discovery/registry/redis/RedisRegistryServiceImpl.java +++ b/discovery/seata-discovery-redis/src/main/java/io/seata/discovery/registry/redis/RedisRegistryServiceImpl.java @@ -261,6 +261,31 @@ public void close() { jedisPool.destroy(); } + private static class NotifySub extends JedisPubSub { + + private final List redisListeners; + + /** + * Instantiates a new Notify sub. + * + * @param redisListeners the redis listeners + */ + NotifySub(List redisListeners) { + this.redisListeners = redisListeners; + } + + @Override + public void onMessage(String key, String msg) { + for (RedisListener listener : redisListeners) { + try { + listener.onEvent(msg); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + } + } + } + private void updateClusterAddressMap(Jedis jedis, String redisRegistryKey) { ScanParams scanParams = new ScanParams(); scanParams.count(10); @@ -287,31 +312,6 @@ private void updateClusterAddressMap(Jedis jedis, String redisRegistryKey) { } } - private static class NotifySub extends JedisPubSub { - - private final List redisListeners; - - /** - * Instantiates a new Notify sub. - * - * @param redisListeners the redis listeners - */ - NotifySub(List redisListeners) { - this.redisListeners = redisListeners; - } - - @Override - public void onMessage(String key, String msg) { - for (RedisListener listener : redisListeners) { - try { - listener.onEvent(msg); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } - } - } - } - private String getRedisRegistryKey() { return REDIS_FILEKEY_PREFIX + clusterName; } diff --git a/integration/brpc/pom.xml b/integration/brpc/pom.xml index ec1247e4ff6..a40e83d0c68 100644 --- a/integration/brpc/pom.xml +++ b/integration/brpc/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/integration/brpc/src/test/java/io/seata/integration/brpc/TransactionInterceptorTest.java b/integration/brpc/src/test/java/io/seata/integration/brpc/TransactionInterceptorTest.java index 1b8c6c5c155..2d712efa7c6 100644 --- a/integration/brpc/src/test/java/io/seata/integration/brpc/TransactionInterceptorTest.java +++ b/integration/brpc/src/test/java/io/seata/integration/brpc/TransactionInterceptorTest.java @@ -35,24 +35,12 @@ */ public class TransactionInterceptorTest { - private static final String DEFAULT_XID = "XID_FOR_BRPC_TEST"; /** * client and server with TM AND RM role */ private static RpcServer rpcServerB; - @BeforeAll - public static void rpcInit() { - - // ----------------------------- rpc server init ----------------------------- - RpcServerOptions rpcServerBOptions = new RpcServerOptions(); - rpcServerBOptions.setIoThreadNum(1); - rpcServerBOptions.setWorkThreadNum(1); - rpcServerB = new RpcServer(9999, rpcServerBOptions); - rpcServerB.registerService(new EchoServiceImpl()); - rpcServerB.getInterceptors().add(new TransactionPropagationServerInterceptor()); - rpcServerB.start(); - } + private static final String DEFAULT_XID = "XID_FOR_BRPC_TEST"; @Test public void testWithInterceptor() { @@ -85,4 +73,18 @@ private RpcClient initRpcClient() { } + @BeforeAll + public static void rpcInit() { + + // ----------------------------- rpc server init ----------------------------- + RpcServerOptions rpcServerBOptions = new RpcServerOptions(); + rpcServerBOptions.setIoThreadNum(1); + rpcServerBOptions.setWorkThreadNum(1); + rpcServerB = new RpcServer(9999, rpcServerBOptions); + rpcServerB.registerService(new EchoServiceImpl()); + rpcServerB.getInterceptors().add(new TransactionPropagationServerInterceptor()); + rpcServerB.start(); + } + + } diff --git a/integration/brpc/src/test/java/io/seata/integration/brpc/dto/Echo.java b/integration/brpc/src/test/java/io/seata/integration/brpc/dto/Echo.java index b2bc7ef8649..d1668837a6b 100644 --- a/integration/brpc/src/test/java/io/seata/integration/brpc/dto/Echo.java +++ b/integration/brpc/src/test/java/io/seata/integration/brpc/dto/Echo.java @@ -19,53 +19,7 @@ package io.seata.integration.brpc.dto; public final class Echo { - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_io_seata_integration_brpc_dto_EchoRequest_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_io_seata_integration_brpc_dto_EchoResponse_fieldAccessorTable; - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - - static { - java.lang.String[] descriptorData = { - "\n\031src/test/proto/Echo.proto\022\035io.seata.in" + - "tegration.brpc.dto\"\035\n\013EchoRequest\022\016\n\006req" + - "Msg\030\001 \002(\t\"?\n\014EchoResponse\022\013\n\003xid\030\001 \001(\t\022\022" + - "\n\nbranchType\030\002 \001(\t\022\016\n\006reqMsg\030\003 \002(\t" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_io_seata_integration_brpc_dto_EchoRequest_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor, - new java.lang.String[] { "ReqMsg", }); - internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor = - getDescriptor().getMessageTypes().get(1); - internal_static_io_seata_integration_brpc_dto_EchoResponse_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor, - new java.lang.String[] { "Xid", "BranchType", "ReqMsg", }); - } private Echo() {} - public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } @@ -75,11 +29,6 @@ public static void registerAllExtensions( registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } public interface EchoRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:io.seata.integration.brpc.dto.EchoRequest) com.google.protobuf.MessageOrBuilder { @@ -98,54 +47,6 @@ public interface EchoRequestOrBuilder extends com.google.protobuf.ByteString getReqMsgBytes(); } - - public interface EchoResponseOrBuilder extends - // @@protoc_insertion_point(interface_extends:io.seata.integration.brpc.dto.EchoResponse) - com.google.protobuf.MessageOrBuilder { - - /** - * optional string xid = 1; - */ - boolean hasXid(); - /** - * optional string xid = 1; - */ - java.lang.String getXid(); - /** - * optional string xid = 1; - */ - com.google.protobuf.ByteString - getXidBytes(); - - /** - * optional string branchType = 2; - */ - boolean hasBranchType(); - /** - * optional string branchType = 2; - */ - java.lang.String getBranchType(); - /** - * optional string branchType = 2; - */ - com.google.protobuf.ByteString - getBranchTypeBytes(); - - /** - * required string reqMsg = 3; - */ - boolean hasReqMsg(); - /** - * required string reqMsg = 3; - */ - java.lang.String getReqMsg(); - /** - * required string reqMsg = 3; - */ - com.google.protobuf.ByteString - getReqMsgBytes(); - } - /** * Protobuf type {@code io.seata.integration.brpc.dto.EchoRequest} */ @@ -153,27 +54,6 @@ public static final class EchoRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:io.seata.integration.brpc.dto.EchoRequest) EchoRequestOrBuilder { - public static final int REQMSG_FIELD_NUMBER = 1; - @java.lang.Deprecated public static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - public EchoRequest parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new EchoRequest(input, extensionRegistry); - } - }; - private static final long serialVersionUID = 0L; - // @@protoc_insertion_point(class_scope:io.seata.integration.brpc.dto.EchoRequest) - private static final io.seata.integration.brpc.dto.Echo.EchoRequest DEFAULT_INSTANCE; - - static { - DEFAULT_INSTANCE = new io.seata.integration.brpc.dto.Echo.EchoRequest(); - } - - private int bitField0_; - private volatile java.lang.Object reqMsg_; - private byte memoizedIsInitialized = -1; // Use EchoRequest.newBuilder() to construct. private EchoRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); @@ -181,6 +61,12 @@ private EchoRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { private EchoRequest() { reqMsg_ = ""; } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } private EchoRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -222,102 +108,11 @@ private EchoRequest( makeExtensionsImmutable(); } } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor; } - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(io.seata.integration.brpc.dto.Echo.EchoRequest prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - public static io.seata.integration.brpc.dto.Echo.EchoRequest getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoRequest_fieldAccessorTable @@ -325,13 +120,15 @@ public static com.google.protobuf.Parser parser() { io.seata.integration.brpc.dto.Echo.EchoRequest.class, io.seata.integration.brpc.dto.Echo.EchoRequest.Builder.class); } + private int bitField0_; + public static final int REQMSG_FIELD_NUMBER = 1; + private volatile java.lang.Object reqMsg_; /** * required string reqMsg = 1; */ public boolean hasReqMsg() { return ((bitField0_ & 0x00000001) == 0x00000001); } - /** * required string reqMsg = 1; */ @@ -340,7 +137,7 @@ public java.lang.String getReqMsg() { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -349,7 +146,6 @@ public java.lang.String getReqMsg() { return s; } } - /** * required string reqMsg = 1; */ @@ -357,7 +153,7 @@ public java.lang.String getReqMsg() { getReqMsgBytes() { java.lang.Object ref = reqMsg_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reqMsg_ = b; @@ -367,6 +163,7 @@ public java.lang.String getReqMsg() { } } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; @@ -401,6 +198,7 @@ public int getSerializedSize() { return size; } + private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { @@ -437,8 +235,72 @@ public int hashCode() { return hash; } - public Builder newBuilderForType() { return newBuilder(); } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.seata.integration.brpc.dto.Echo.EchoRequest prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); @@ -450,16 +312,6 @@ protected Builder newBuilderForType( Builder builder = new Builder(parent); return builder; } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public io.seata.integration.brpc.dto.Echo.EchoRequest getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - /** * Protobuf type {@code io.seata.integration.brpc.dto.EchoRequest} */ @@ -467,20 +319,6 @@ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:io.seata.integration.brpc.dto.EchoRequest) io.seata.integration.brpc.dto.Echo.EchoRequestOrBuilder { - private int bitField0_; - private java.lang.Object reqMsg_ = ""; - - // Construct using io.seata.integration.brpc.dto.Echo.EchoRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor; @@ -493,12 +331,21 @@ private Builder( io.seata.integration.brpc.dto.Echo.EchoRequest.class, io.seata.integration.brpc.dto.Echo.EchoRequest.Builder.class); } + // Construct using io.seata.integration.brpc.dto.Echo.EchoRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } - public Builder clear() { super.clear(); reqMsg_ = ""; @@ -539,35 +386,29 @@ public io.seata.integration.brpc.dto.Echo.EchoRequest buildPartial() { public Builder clone() { return (Builder) super.clone(); } - public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } - public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } - public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } - public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } - public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } - public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.seata.integration.brpc.dto.Echo.EchoRequest) { return mergeFrom((io.seata.integration.brpc.dto.Echo.EchoRequest)other); @@ -613,7 +454,9 @@ public Builder mergeFrom( } return this; } + private int bitField0_; + private java.lang.Object reqMsg_ = ""; /** * required string reqMsg = 1; */ @@ -637,21 +480,6 @@ public java.lang.String getReqMsg() { return (java.lang.String) ref; } } - - /** - * required string reqMsg = 1; - */ - public Builder setReqMsg( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - reqMsg_ = value; - onChanged(); - return this; - } - /** * required string reqMsg = 1; */ @@ -659,7 +487,7 @@ public Builder setReqMsg( getReqMsgBytes() { java.lang.Object ref = reqMsg_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reqMsg_ = b; @@ -668,12 +496,11 @@ public Builder setReqMsg( return (com.google.protobuf.ByteString) ref; } } - /** * required string reqMsg = 1; */ - public Builder setReqMsgBytes( - com.google.protobuf.ByteString value) { + public Builder setReqMsg( + java.lang.String value) { if (value == null) { throw new NullPointerException(); } @@ -682,7 +509,6 @@ public Builder setReqMsgBytes( onChanged(); return this; } - /** * required string reqMsg = 1; */ @@ -692,7 +518,19 @@ public Builder clearReqMsg() { onChanged(); return this; } - + /** + * required string reqMsg = 1; + */ + public Builder setReqMsgBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + reqMsg_ = value; + onChanged(); + return this; + } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); @@ -707,41 +545,94 @@ public final Builder mergeUnknownFields( // @@protoc_insertion_point(builder_scope:io.seata.integration.brpc.dto.EchoRequest) } - } + // @@protoc_insertion_point(class_scope:io.seata.integration.brpc.dto.EchoRequest) + private static final io.seata.integration.brpc.dto.Echo.EchoRequest DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.seata.integration.brpc.dto.Echo.EchoRequest(); + } - /** - * Protobuf type {@code io.seata.integration.brpc.dto.EchoResponse} - */ - public static final class EchoResponse extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:io.seata.integration.brpc.dto.EchoResponse) - EchoResponseOrBuilder { - public static final int XID_FIELD_NUMBER = 1; - public static final int BRANCHTYPE_FIELD_NUMBER = 2; - public static final int REQMSG_FIELD_NUMBER = 3; - @java.lang.Deprecated public static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - public EchoResponse parsePartialFrom( + public static io.seata.integration.brpc.dto.Echo.EchoRequest getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @java.lang.Deprecated public static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public EchoRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { - return new EchoResponse(input, extensionRegistry); + return new EchoRequest(input, extensionRegistry); } }; - private static final long serialVersionUID = 0L; - // @@protoc_insertion_point(class_scope:io.seata.integration.brpc.dto.EchoResponse) - private static final io.seata.integration.brpc.dto.Echo.EchoResponse DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new io.seata.integration.brpc.dto.Echo.EchoResponse(); + public static com.google.protobuf.Parser parser() { + return PARSER; } - private int bitField0_; - private volatile java.lang.Object xid_; - private volatile java.lang.Object branchType_; - private volatile java.lang.Object reqMsg_; - private byte memoizedIsInitialized = -1; + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.seata.integration.brpc.dto.Echo.EchoRequest getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface EchoResponseOrBuilder extends + // @@protoc_insertion_point(interface_extends:io.seata.integration.brpc.dto.EchoResponse) + com.google.protobuf.MessageOrBuilder { + + /** + * optional string xid = 1; + */ + boolean hasXid(); + /** + * optional string xid = 1; + */ + java.lang.String getXid(); + /** + * optional string xid = 1; + */ + com.google.protobuf.ByteString + getXidBytes(); + + /** + * optional string branchType = 2; + */ + boolean hasBranchType(); + /** + * optional string branchType = 2; + */ + java.lang.String getBranchType(); + /** + * optional string branchType = 2; + */ + com.google.protobuf.ByteString + getBranchTypeBytes(); + /** + * required string reqMsg = 3; + */ + boolean hasReqMsg(); + /** + * required string reqMsg = 3; + */ + java.lang.String getReqMsg(); + /** + * required string reqMsg = 3; + */ + com.google.protobuf.ByteString + getReqMsgBytes(); + } + /** + * Protobuf type {@code io.seata.integration.brpc.dto.EchoResponse} + */ + public static final class EchoResponse extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:io.seata.integration.brpc.dto.EchoResponse) + EchoResponseOrBuilder { // Use EchoResponse.newBuilder() to construct. private EchoResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); @@ -751,6 +642,12 @@ private EchoResponse() { branchType_ = ""; reqMsg_ = ""; } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } private EchoResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -804,102 +701,11 @@ private EchoResponse( makeExtensionsImmutable(); } } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor; } - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(io.seata.integration.brpc.dto.Echo.EchoResponse prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - public static io.seata.integration.brpc.dto.Echo.EchoResponse getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoResponse_fieldAccessorTable @@ -907,13 +713,15 @@ public static com.google.protobuf.Parser parser() { io.seata.integration.brpc.dto.Echo.EchoResponse.class, io.seata.integration.brpc.dto.Echo.EchoResponse.Builder.class); } + private int bitField0_; + public static final int XID_FIELD_NUMBER = 1; + private volatile java.lang.Object xid_; /** * optional string xid = 1; */ public boolean hasXid() { return ((bitField0_ & 0x00000001) == 0x00000001); } - /** * optional string xid = 1; */ @@ -922,7 +730,7 @@ public java.lang.String getXid() { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -931,7 +739,6 @@ public java.lang.String getXid() { return s; } } - /** * optional string xid = 1; */ @@ -939,7 +746,7 @@ public java.lang.String getXid() { getXidBytes() { java.lang.Object ref = xid_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); xid_ = b; @@ -949,13 +756,14 @@ public java.lang.String getXid() { } } + public static final int BRANCHTYPE_FIELD_NUMBER = 2; + private volatile java.lang.Object branchType_; /** * optional string branchType = 2; */ public boolean hasBranchType() { return ((bitField0_ & 0x00000002) == 0x00000002); } - /** * optional string branchType = 2; */ @@ -964,7 +772,7 @@ public java.lang.String getBranchType() { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -973,7 +781,6 @@ public java.lang.String getBranchType() { return s; } } - /** * optional string branchType = 2; */ @@ -981,7 +788,7 @@ public java.lang.String getBranchType() { getBranchTypeBytes() { java.lang.Object ref = branchType_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); branchType_ = b; @@ -991,13 +798,14 @@ public java.lang.String getBranchType() { } } + public static final int REQMSG_FIELD_NUMBER = 3; + private volatile java.lang.Object reqMsg_; /** * required string reqMsg = 3; */ public boolean hasReqMsg() { return ((bitField0_ & 0x00000004) == 0x00000004); } - /** * required string reqMsg = 3; */ @@ -1006,7 +814,7 @@ public java.lang.String getReqMsg() { if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { @@ -1015,7 +823,6 @@ public java.lang.String getReqMsg() { return s; } } - /** * required string reqMsg = 3; */ @@ -1023,7 +830,7 @@ public java.lang.String getReqMsg() { getReqMsgBytes() { java.lang.Object ref = reqMsg_; if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reqMsg_ = b; @@ -1033,6 +840,7 @@ public java.lang.String getReqMsg() { } } + private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; @@ -1079,6 +887,7 @@ public int getSerializedSize() { return size; } + private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { @@ -1133,8 +942,72 @@ public int hashCode() { return hash; } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.seata.integration.brpc.dto.Echo.EchoResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public Builder newBuilderForType() { return newBuilder(); } - + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.seata.integration.brpc.dto.Echo.EchoResponse prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); @@ -1146,16 +1019,6 @@ protected Builder newBuilderForType( Builder builder = new Builder(parent); return builder; } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public io.seata.integration.brpc.dto.Echo.EchoResponse getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - /** * Protobuf type {@code io.seata.integration.brpc.dto.EchoResponse} */ @@ -1163,20 +1026,6 @@ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:io.seata.integration.brpc.dto.EchoResponse) io.seata.integration.brpc.dto.Echo.EchoResponseOrBuilder { - private int bitField0_; - private java.lang.Object xid_ = ""; - private java.lang.Object branchType_ = ""; - private java.lang.Object reqMsg_ = ""; - // Construct using io.seata.integration.brpc.dto.Echo.EchoResponse.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - private Builder( - com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.seata.integration.brpc.dto.Echo.internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor; @@ -1189,12 +1038,21 @@ private Builder( io.seata.integration.brpc.dto.Echo.EchoResponse.class, io.seata.integration.brpc.dto.Echo.EchoResponse.Builder.class); } + // Construct using io.seata.integration.brpc.dto.Echo.EchoResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } - public Builder clear() { super.clear(); xid_ = ""; @@ -1247,35 +1105,29 @@ public io.seata.integration.brpc.dto.Echo.EchoResponse buildPartial() { public Builder clone() { return (Builder) super.clone(); } - public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } - public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } - public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } - public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } - public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } - public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.seata.integration.brpc.dto.Echo.EchoResponse) { return mergeFrom((io.seata.integration.brpc.dto.Echo.EchoResponse)other); @@ -1331,14 +1183,15 @@ public Builder mergeFrom( } return this; } + private int bitField0_; + private java.lang.Object xid_ = ""; /** * optional string xid = 1; */ public boolean hasXid() { return ((bitField0_ & 0x00000001) == 0x00000001); } - /** * optional string xid = 1; */ @@ -1356,21 +1209,6 @@ public java.lang.String getXid() { return (java.lang.String) ref; } } - - /** - * optional string xid = 1; - */ - public Builder setXid( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - xid_ = value; - onChanged(); - return this; - } - /** * optional string xid = 1; */ @@ -1378,7 +1216,7 @@ public Builder setXid( getXidBytes() { java.lang.Object ref = xid_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); xid_ = b; @@ -1387,12 +1225,11 @@ public Builder setXid( return (com.google.protobuf.ByteString) ref; } } - /** * optional string xid = 1; */ - public Builder setXidBytes( - com.google.protobuf.ByteString value) { + public Builder setXid( + java.lang.String value) { if (value == null) { throw new NullPointerException(); } @@ -1401,7 +1238,6 @@ public Builder setXidBytes( onChanged(); return this; } - /** * optional string xid = 1; */ @@ -1411,14 +1247,27 @@ public Builder clearXid() { onChanged(); return this; } + /** + * optional string xid = 1; + */ + public Builder setXidBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + xid_ = value; + onChanged(); + return this; + } + private java.lang.Object branchType_ = ""; /** * optional string branchType = 2; */ public boolean hasBranchType() { return ((bitField0_ & 0x00000002) == 0x00000002); } - /** * optional string branchType = 2; */ @@ -1436,21 +1285,6 @@ public java.lang.String getBranchType() { return (java.lang.String) ref; } } - - /** - * optional string branchType = 2; - */ - public Builder setBranchType( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - branchType_ = value; - onChanged(); - return this; - } - /** * optional string branchType = 2; */ @@ -1458,7 +1292,7 @@ public Builder setBranchType( getBranchTypeBytes() { java.lang.Object ref = branchType_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); branchType_ = b; @@ -1467,12 +1301,11 @@ public Builder setBranchType( return (com.google.protobuf.ByteString) ref; } } - /** * optional string branchType = 2; */ - public Builder setBranchTypeBytes( - com.google.protobuf.ByteString value) { + public Builder setBranchType( + java.lang.String value) { if (value == null) { throw new NullPointerException(); } @@ -1481,7 +1314,6 @@ public Builder setBranchTypeBytes( onChanged(); return this; } - /** * optional string branchType = 2; */ @@ -1491,7 +1323,21 @@ public Builder clearBranchType() { onChanged(); return this; } + /** + * optional string branchType = 2; + */ + public Builder setBranchTypeBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + branchType_ = value; + onChanged(); + return this; + } + private java.lang.Object reqMsg_ = ""; /** * required string reqMsg = 3; */ @@ -1515,21 +1361,6 @@ public java.lang.String getReqMsg() { return (java.lang.String) ref; } } - - /** - * required string reqMsg = 3; - */ - public Builder setReqMsg( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000004; - reqMsg_ = value; - onChanged(); - return this; - } - /** * required string reqMsg = 3; */ @@ -1537,7 +1368,7 @@ public Builder setReqMsg( getReqMsgBytes() { java.lang.Object ref = reqMsg_; if (ref instanceof String) { - com.google.protobuf.ByteString b = + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); reqMsg_ = b; @@ -1546,12 +1377,11 @@ public Builder setReqMsg( return (com.google.protobuf.ByteString) ref; } } - /** * required string reqMsg = 3; */ - public Builder setReqMsgBytes( - com.google.protobuf.ByteString value) { + public Builder setReqMsg( + java.lang.String value) { if (value == null) { throw new NullPointerException(); } @@ -1560,7 +1390,6 @@ public Builder setReqMsgBytes( onChanged(); return this; } - /** * required string reqMsg = 3; */ @@ -1570,7 +1399,19 @@ public Builder clearReqMsg() { onChanged(); return this; } - + /** + * required string reqMsg = 3; + */ + public Builder setReqMsgBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000004; + reqMsg_ = value; + onChanged(); + return this; + } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); @@ -1585,6 +1426,89 @@ public final Builder mergeUnknownFields( // @@protoc_insertion_point(builder_scope:io.seata.integration.brpc.dto.EchoResponse) } + // @@protoc_insertion_point(class_scope:io.seata.integration.brpc.dto.EchoResponse) + private static final io.seata.integration.brpc.dto.Echo.EchoResponse DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.seata.integration.brpc.dto.Echo.EchoResponse(); + } + + public static io.seata.integration.brpc.dto.Echo.EchoResponse getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @java.lang.Deprecated public static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public EchoResponse parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new EchoResponse(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.seata.integration.brpc.dto.Echo.EchoResponse getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_io_seata_integration_brpc_dto_EchoRequest_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_io_seata_integration_brpc_dto_EchoResponse_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\031src/test/proto/Echo.proto\022\035io.seata.in" + + "tegration.brpc.dto\"\035\n\013EchoRequest\022\016\n\006req" + + "Msg\030\001 \002(\t\"?\n\014EchoResponse\022\013\n\003xid\030\001 \001(\t\022\022" + + "\n\nbranchType\030\002 \001(\t\022\016\n\006reqMsg\030\003 \002(\t" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_io_seata_integration_brpc_dto_EchoRequest_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_io_seata_integration_brpc_dto_EchoRequest_descriptor, + new java.lang.String[] { "ReqMsg", }); + internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_io_seata_integration_brpc_dto_EchoResponse_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_io_seata_integration_brpc_dto_EchoResponse_descriptor, + new java.lang.String[] { "Xid", "BranchType", "ReqMsg", }); } // @@protoc_insertion_point(outer_class_scope) diff --git a/integration/hsf/pom.xml b/integration/hsf/pom.xml index 6ab53555694..97f4e89348e 100644 --- a/integration/hsf/pom.xml +++ b/integration/hsf/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/integration/http-jakarta/pom.xml b/integration/http-jakarta/pom.xml index 4cb9ed7dc89..c67ad004208 100644 --- a/integration/http-jakarta/pom.xml +++ b/integration/http-jakarta/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/integration/http/src/main/java/io/seata/integration/http/AbstractHttpExecutor.java b/integration/http/src/main/java/io/seata/integration/http/AbstractHttpExecutor.java index 3b2abcbdea3..2958def37ec 100644 --- a/integration/http/src/main/java/io/seata/integration/http/AbstractHttpExecutor.java +++ b/integration/http/src/main/java/io/seata/integration/http/AbstractHttpExecutor.java @@ -49,11 +49,6 @@ public abstract class AbstractHttpExecutor implements HttpExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHttpExecutor.class); - @SuppressWarnings("lgtm[java/unsafe-deserialization]") - public static Map convertParamOfJsonString(String jsonStr, Class returnType) { - return convertParamOfBean(JSON.parseObject(jsonStr, returnType)); - } - @Override public K executePost(String host, String path, T paramObject, Class returnType) throws IOException { Args.notNull(returnType, "returnType"); @@ -82,30 +77,6 @@ public K executePut(String host, String path, T paramObject, Class ret return wrapHttpExecute(returnType, httpClient, httpPut, headers); } - @Override - public K executeGet(String host, String path, Map paramObject, Class returnType) throws IOException { - - Args.notNull(returnType, "returnType"); - Args.notNull(host, "host"); - Args.notNull(path, "path"); - - CloseableHttpClient httpClient = initHttpClientInstance(paramObject); - - HttpGet httpGet = new HttpGet(initGetUrl(host, path, paramObject)); - Map headers = new HashMap<>(); - - buildGetHeaders(headers, paramObject); - return wrapHttpExecute(returnType, httpClient, httpGet, headers); - } - - private CloseableHttpClient initHttpClientInstance(T paramObject) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - buildClientEntity(httpClient, paramObject); - return httpClient; - } - - protected abstract void buildClientEntity(CloseableHttpClient httpClient, T paramObject); - private StringEntity execute(String host, String path, T paramObject) { Args.notNull(host, "host"); Args.notNull(path, "path"); @@ -135,22 +106,30 @@ private StringEntity execute(String host, String path, T paramObject) { return buildEntity(entity, paramObject); } - protected abstract void buildGetHeaders(Map headers, T paramObject); - - protected abstract String initGetUrl(String host, String path, Map paramObject); - + @Override + public K executeGet(String host, String path, Map paramObject, Class returnType) throws IOException { - protected abstract void buildPostHeaders(Map headers, T t); + Args.notNull(returnType, "returnType"); + Args.notNull(host, "host"); + Args.notNull(path, "path"); - protected abstract StringEntity buildEntity(StringEntity entity, T t); + CloseableHttpClient httpClient = initHttpClientInstance(paramObject); - protected abstract K convertResult(HttpResponse response, Class clazz); + HttpGet httpGet = new HttpGet(initGetUrl(host, path, paramObject)); + Map headers = new HashMap<>(); + buildGetHeaders(headers, paramObject); + return wrapHttpExecute(returnType, httpClient, httpGet, headers); + } - public static Map convertParamOfBean(Object sourceParam) { - return CollectionUtils.toStringMap(JSON.parseObject(JSON.toJSONString(sourceParam, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue), Map.class)); + private CloseableHttpClient initHttpClientInstance(T paramObject) { + CloseableHttpClient httpClient = HttpClients.createDefault(); + buildClientEntity(httpClient, paramObject); + return httpClient; } + protected abstract void buildClientEntity(CloseableHttpClient httpClient, T paramObject); + private K wrapHttpExecute(Class returnType, CloseableHttpClient httpClient, HttpUriRequest httpUriRequest, Map headers) throws IOException { CloseableHttpResponse response; @@ -172,4 +151,25 @@ private K wrapHttpExecute(Class returnType, CloseableHttpClient httpClien return convertResult(response, returnType); } + + protected abstract void buildGetHeaders(Map headers, T paramObject); + + protected abstract String initGetUrl(String host, String path, Map paramObject); + + + protected abstract void buildPostHeaders(Map headers, T t); + + protected abstract StringEntity buildEntity(StringEntity entity, T t); + + protected abstract K convertResult(HttpResponse response, Class clazz); + + + public static Map convertParamOfBean(Object sourceParam) { + return CollectionUtils.toStringMap(JSON.parseObject(JSON.toJSONString(sourceParam, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue), Map.class)); + } + + @SuppressWarnings("lgtm[java/unsafe-deserialization]") + public static Map convertParamOfJsonString(String jsonStr, Class returnType) { + return convertParamOfBean(JSON.parseObject(jsonStr, returnType)); + } } diff --git a/metrics/seata-metrics-exporter-prometheus/src/main/java/io/seata/metrics/exporter/prometheus/PrometheusExporter.java b/metrics/seata-metrics-exporter-prometheus/src/main/java/io/seata/metrics/exporter/prometheus/PrometheusExporter.java index ea6660a1b29..e4c5144d15f 100644 --- a/metrics/seata-metrics-exporter-prometheus/src/main/java/io/seata/metrics/exporter/prometheus/PrometheusExporter.java +++ b/metrics/seata-metrics-exporter-prometheus/src/main/java/io/seata/metrics/exporter/prometheus/PrometheusExporter.java @@ -57,19 +57,20 @@ public void setRegistry(Registry registry) { this.registry = registry; } - /** - * Compatible with high and low versions of 'io.prometheus:simpleclient' - * - * @return the unknown collector type - */ - public static Type getUnknownType() { - Type unknownType; - try { - unknownType = Type.valueOf("UNKNOWN"); - } catch (IllegalArgumentException e) { - unknownType = Type.valueOf("UNTYPED"); + @Override + public List collect() { + List familySamples = new ArrayList<>(); + if (registry != null) { + Iterable measurements = registry.measure(); + List samples = new ArrayList<>(); + measurements.forEach(measurement -> samples.add(convertMeasurementToSample(measurement))); + + if (!samples.isEmpty()) { + Type unknownType = getUnknownType(); + familySamples.add(new MetricFamilySamples("seata", unknownType, "seata", samples)); + } } - return unknownType; + return familySamples; } private Sample convertMeasurementToSample(Measurement measurement) { @@ -84,20 +85,19 @@ private Sample convertMeasurementToSample(Measurement measurement) { (long)measurement.getTimestamp()); } - @Override - public List collect() { - List familySamples = new ArrayList<>(); - if (registry != null) { - Iterable measurements = registry.measure(); - List samples = new ArrayList<>(); - measurements.forEach(measurement -> samples.add(convertMeasurementToSample(measurement))); - - if (!samples.isEmpty()) { - Type unknownType = getUnknownType(); - familySamples.add(new MetricFamilySamples("seata", unknownType, "seata", samples)); - } + /** + * Compatible with high and low versions of 'io.prometheus:simpleclient' + * + * @return the unknown collector type + */ + public static Type getUnknownType() { + Type unknownType; + try { + unknownType = Type.valueOf("UNKNOWN"); + } catch (IllegalArgumentException e) { + unknownType = Type.valueOf("UNTYPED"); } - return familySamples; + return unknownType; } @Override diff --git a/saga/seata-saga-statemachine-designer/index.html b/saga/seata-saga-statemachine-designer/index.html index c502189d393..058fc84d0a8 100644 --- a/saga/seata-saga-statemachine-designer/index.html +++ b/saga/seata-saga-statemachine-designer/index.html @@ -6,7 +6,7 @@ Seata Saga StateMachine Designer - + diff --git a/script/client/spring/application.properties b/script/client/spring/application.properties index acb46ab10e8..662b4de3ced 100755 --- a/script/client/spring/application.properties +++ b/script/client/spring/application.properties @@ -170,4 +170,4 @@ seata.saga.state-machine.service-invoke-timeout=300000 seata.saga.state-machine.auto-register-resources=true seata.saga.state-machine.resources[0]=classpath*:seata/saga/statelang/**/*.json seata.saga.state-machine.default-tenant-id=000001 -seata.saga.state-machine.charset=UTF-8 \ No newline at end of file +seata.saga.state-machine.charset=UTF-8 diff --git a/seata-spring-autoconfigure/seata-spring-autoconfigure-client/src/test/java/io/seata/spring/boot/autoconfigure/properties/client/LoadBalancePropertiesTest.java b/seata-spring-autoconfigure/seata-spring-autoconfigure-client/src/test/java/io/seata/spring/boot/autoconfigure/properties/client/LoadBalancePropertiesTest.java index 735a823fa55..a427af72ae9 100644 --- a/seata-spring-autoconfigure/seata-spring-autoconfigure-client/src/test/java/io/seata/spring/boot/autoconfigure/properties/client/LoadBalancePropertiesTest.java +++ b/seata-spring-autoconfigure/seata-spring-autoconfigure-client/src/test/java/io/seata/spring/boot/autoconfigure/properties/client/LoadBalancePropertiesTest.java @@ -45,11 +45,6 @@ public static void initContext() { applicationContext = new AnnotationConfigApplicationContext(LoadBalancePropertiesTest.class); } - @AfterAll - public static void closeContext() { - applicationContext.close(); - } - @Bean LoadBalanceProperties loadBalanceProperties() { LoadBalanceProperties loadBalanceProperties = new LoadBalanceProperties(); @@ -67,4 +62,9 @@ public void testLoadBalanceProperties() { System.setProperty("seata.client.loadBalance.type", "test"); assertEquals("test", currentConfiguration.getConfig("client.loadBalance.type")); } + + @AfterAll + public static void closeContext() { + applicationContext.close(); + } } diff --git a/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/main/java/io/seata/spring/boot/autoconfigure/SeataCoreEnvironmentPostProcessor.java b/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/main/java/io/seata/spring/boot/autoconfigure/SeataCoreEnvironmentPostProcessor.java index 50e6a9876a0..d81883b89b9 100644 --- a/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/main/java/io/seata/spring/boot/autoconfigure/SeataCoreEnvironmentPostProcessor.java +++ b/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/main/java/io/seata/spring/boot/autoconfigure/SeataCoreEnvironmentPostProcessor.java @@ -74,6 +74,16 @@ public class SeataCoreEnvironmentPostProcessor implements EnvironmentPostProcess private static final AtomicBoolean INIT = new AtomicBoolean(false); + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + init(); + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + public static void init() { if (INIT.compareAndSet(false, true)) { PROPERTY_BEAN_MAP.put(CONFIG_PREFIX, ConfigProperties.class); @@ -103,14 +113,4 @@ public static void init() { } } - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - init(); - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - } diff --git a/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/test/java/io/seata/spring/boot/autoconfigure/BasePropertiesTest.java b/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/test/java/io/seata/spring/boot/autoconfigure/BasePropertiesTest.java index d3a943685e0..e450017a2bb 100644 --- a/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/test/java/io/seata/spring/boot/autoconfigure/BasePropertiesTest.java +++ b/seata-spring-autoconfigure/seata-spring-autoconfigure-core/src/test/java/io/seata/spring/boot/autoconfigure/BasePropertiesTest.java @@ -35,15 +35,16 @@ * @author slievrly */ public class BasePropertiesTest { + protected static AnnotationConfigApplicationContext applicationContex; protected static final String STR_TEST_AAA = "aaa"; protected static final String STR_TEST_BBB = "bbb"; protected static final String STR_TEST_CCC = "ccc"; protected static final String STR_TEST_DDD = "ddd"; protected static final String STR_TEST_EEE = "eee"; protected static final String STR_TEST_FFF = "fff"; + protected static final int LONG_TEST_ONE = 1; protected static final int LONG_TEST_TWO = 2; - protected static AnnotationConfigApplicationContext applicationContex; @BeforeEach public void setUp() throws IOException { diff --git a/seata-spring-autoconfigure/seata-spring-autoconfigure-server/src/main/java/io/seata/spring/boot/autoconfigure/SeataServerEnvironmentPostProcessor.java b/seata-spring-autoconfigure/seata-spring-autoconfigure-server/src/main/java/io/seata/spring/boot/autoconfigure/SeataServerEnvironmentPostProcessor.java index c5b620a798f..57f5d99a36c 100644 --- a/seata-spring-autoconfigure/seata-spring-autoconfigure-server/src/main/java/io/seata/spring/boot/autoconfigure/SeataServerEnvironmentPostProcessor.java +++ b/seata-spring-autoconfigure/seata-spring-autoconfigure-server/src/main/java/io/seata/spring/boot/autoconfigure/SeataServerEnvironmentPostProcessor.java @@ -53,6 +53,16 @@ public class SeataServerEnvironmentPostProcessor implements EnvironmentPostProce private static final AtomicBoolean INIT = new AtomicBoolean(false); + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + init(); + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + public static void init() { if (INIT.compareAndSet(false, true)) { PROPERTY_BEAN_MAP.put(SERVER_PREFIX, ServerProperties.class); @@ -71,14 +81,4 @@ public static void init() { } } - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - init(); - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - } diff --git a/serializer/seata-serializer-protobuf/src/main/java/io/seata/serializer/protobuf/convertor/BatchResultMessageConvertor.java b/serializer/seata-serializer-protobuf/src/main/java/io/seata/serializer/protobuf/convertor/BatchResultMessageConvertor.java index 599a8f22f8b..4cef1145ddd 100644 --- a/serializer/seata-serializer-protobuf/src/main/java/io/seata/serializer/protobuf/convertor/BatchResultMessageConvertor.java +++ b/serializer/seata-serializer-protobuf/src/main/java/io/seata/serializer/protobuf/convertor/BatchResultMessageConvertor.java @@ -37,11 +37,6 @@ */ public class BatchResultMessageConvertor implements PbConvertor { - private static String getTypeNameFromTypeUrl(String typeUrl) { - int pos = typeUrl.lastIndexOf('/'); - return pos == -1 ? "" : typeUrl.substring(pos + 1); - } - @Override public BatchResultMessageProto convert2Proto(BatchResultMessage batchResultMessage) { @@ -87,4 +82,9 @@ public BatchResultMessage convert2Model(BatchResultMessageProto batchResultMessa result.setMsgIds(batchResultMessageProto.getMsgIdsList()); return result; } + + private static String getTypeNameFromTypeUrl(String typeUrl) { + int pos = typeUrl.lastIndexOf('/'); + return pos == -1 ? "" : typeUrl.substring(pos + 1); + } } \ No newline at end of file diff --git a/server/src/main/java/io/seata/server/ServerRunner.java b/server/src/main/java/io/seata/server/ServerRunner.java index e70996aeac1..941d8cee788 100644 --- a/server/src/main/java/io/seata/server/ServerRunner.java +++ b/server/src/main/java/io/seata/server/ServerRunner.java @@ -42,11 +42,13 @@ public class ServerRunner implements CommandLineRunner, DisposableBean, private boolean started = Boolean.FALSE; - private static final List DISPOSABLE_LIST = new CopyOnWriteArrayList<>(); private int port; + @Value("${logging.file.path}") private String logPath; + private static final List DISPOSABLE_LIST = new CopyOnWriteArrayList<>(); + public static void addDisposable(Disposable disposable) { DISPOSABLE_LIST.add(disposable); } diff --git a/server/src/main/java/io/seata/server/console/vo/BranchSessionVO.java b/server/src/main/java/io/seata/server/console/vo/BranchSessionVO.java index b42806b8836..f80f27798de 100644 --- a/server/src/main/java/io/seata/server/console/vo/BranchSessionVO.java +++ b/server/src/main/java/io/seata/server/console/vo/BranchSessionVO.java @@ -75,28 +75,6 @@ public BranchSessionVO(String xid, this.applicationData = applicationData; } - public static BranchSessionVO convert(ResultSet rs) throws SQLException { - BranchSessionVO branchSessionVO = new BranchSessionVO(); - branchSessionVO.setXid(rs.getString(ServerTableColumnsName.BRANCH_TABLE_XID)); - branchSessionVO.setTransactionId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_TRANSACTION_ID)); - branchSessionVO.setBranchId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_BRANCH_ID)); - branchSessionVO.setResourceGroupId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_GROUP_ID)); - branchSessionVO.setResourceId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_ID)); - branchSessionVO.setBranchType(rs.getString(ServerTableColumnsName.BRANCH_TABLE_BRANCH_TYPE)); - branchSessionVO.setStatus(rs.getInt(ServerTableColumnsName.BRANCH_TABLE_STATUS)); - branchSessionVO.setClientId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_CLIENT_ID)); - branchSessionVO.setApplicationData(rs.getString(ServerTableColumnsName.BRANCH_TABLE_APPLICATION_DATA)); - Date gmtCreateTimestamp = rs.getDate(ServerTableColumnsName.BRANCH_TABLE_GMT_CREATE); - if (gmtCreateTimestamp != null) { - branchSessionVO.setGmtCreate(gmtCreateTimestamp.getTime()); - } - Date gmtModifiedTimestamp = rs.getDate(ServerTableColumnsName.BRANCH_TABLE_GMT_MODIFIED); - if (gmtModifiedTimestamp != null) { - branchSessionVO.setGmtModified(gmtModifiedTimestamp.getTime()); - } - return branchSessionVO; - } - public String getXid() { return xid; } @@ -185,6 +163,28 @@ public void setGmtModified(Long gmtModified) { this.gmtModified = gmtModified; } + public static BranchSessionVO convert(ResultSet rs) throws SQLException { + BranchSessionVO branchSessionVO = new BranchSessionVO(); + branchSessionVO.setXid(rs.getString(ServerTableColumnsName.BRANCH_TABLE_XID)); + branchSessionVO.setTransactionId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_TRANSACTION_ID)); + branchSessionVO.setBranchId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_BRANCH_ID)); + branchSessionVO.setResourceGroupId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_GROUP_ID)); + branchSessionVO.setResourceId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_ID)); + branchSessionVO.setBranchType(rs.getString(ServerTableColumnsName.BRANCH_TABLE_BRANCH_TYPE)); + branchSessionVO.setStatus(rs.getInt(ServerTableColumnsName.BRANCH_TABLE_STATUS)); + branchSessionVO.setClientId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_CLIENT_ID)); + branchSessionVO.setApplicationData(rs.getString(ServerTableColumnsName.BRANCH_TABLE_APPLICATION_DATA)); + Date gmtCreateTimestamp = rs.getDate(ServerTableColumnsName.BRANCH_TABLE_GMT_CREATE); + if (gmtCreateTimestamp != null) { + branchSessionVO.setGmtCreate(gmtCreateTimestamp.getTime()); + } + Date gmtModifiedTimestamp = rs.getDate(ServerTableColumnsName.BRANCH_TABLE_GMT_MODIFIED); + if (gmtModifiedTimestamp != null) { + branchSessionVO.setGmtModified(gmtModifiedTimestamp.getTime()); + } + return branchSessionVO; + } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/server/src/main/java/io/seata/server/console/vo/GlobalLockVO.java b/server/src/main/java/io/seata/server/console/vo/GlobalLockVO.java index 477da163742..3a4432d9275 100644 --- a/server/src/main/java/io/seata/server/console/vo/GlobalLockVO.java +++ b/server/src/main/java/io/seata/server/console/vo/GlobalLockVO.java @@ -86,25 +86,6 @@ public static GlobalLockVO convert(RowLock rowLock) { return globalLockVO; } - public static GlobalLockVO convert(ResultSet rs) throws SQLException { - GlobalLockVO globalLockVO = new GlobalLockVO(); - globalLockVO.setRowKey(rs.getString(ServerTableColumnsName.LOCK_TABLE_ROW_KEY)); - globalLockVO.setXid(rs.getString(ServerTableColumnsName.LOCK_TABLE_XID)); - globalLockVO.setTransactionId(rs.getLong(ServerTableColumnsName.LOCK_TABLE_TRANSACTION_ID)); - globalLockVO.setBranchId(rs.getLong(ServerTableColumnsName.LOCK_TABLE_BRANCH_ID)); - globalLockVO.setResourceId(rs.getString(ServerTableColumnsName.LOCK_TABLE_RESOURCE_ID)); - globalLockVO.setTableName(rs.getString(ServerTableColumnsName.LOCK_TABLE_TABLE_NAME)); - globalLockVO.setPk(rs.getString(ServerTableColumnsName.LOCK_TABLE_PK)); - Timestamp gmtCreateTimestamp = rs.getTimestamp(ServerTableColumnsName.LOCK_TABLE_GMT_CREATE); - if (gmtCreateTimestamp != null) { - globalLockVO.setGmtCreate(gmtCreateTimestamp.getTime()); - } - Timestamp gmtModifiedTimestamp = rs.getTimestamp(ServerTableColumnsName.LOCK_TABLE_GMT_MODIFIED); - if (gmtModifiedTimestamp != null) { - globalLockVO.setGmtModified(gmtModifiedTimestamp.getTime()); - } - return globalLockVO; - } public String getXid() { return xid; @@ -178,6 +159,26 @@ public void setGmtModified(Long gmtModified) { this.gmtModified = gmtModified; } + public static GlobalLockVO convert(ResultSet rs) throws SQLException { + GlobalLockVO globalLockVO = new GlobalLockVO(); + globalLockVO.setRowKey(rs.getString(ServerTableColumnsName.LOCK_TABLE_ROW_KEY)); + globalLockVO.setXid(rs.getString(ServerTableColumnsName.LOCK_TABLE_XID)); + globalLockVO.setTransactionId(rs.getLong(ServerTableColumnsName.LOCK_TABLE_TRANSACTION_ID)); + globalLockVO.setBranchId(rs.getLong(ServerTableColumnsName.LOCK_TABLE_BRANCH_ID)); + globalLockVO.setResourceId(rs.getString(ServerTableColumnsName.LOCK_TABLE_RESOURCE_ID)); + globalLockVO.setTableName(rs.getString(ServerTableColumnsName.LOCK_TABLE_TABLE_NAME)); + globalLockVO.setPk(rs.getString(ServerTableColumnsName.LOCK_TABLE_PK)); + Timestamp gmtCreateTimestamp = rs.getTimestamp(ServerTableColumnsName.LOCK_TABLE_GMT_CREATE); + if (gmtCreateTimestamp != null) { + globalLockVO.setGmtCreate(gmtCreateTimestamp.getTime()); + } + Timestamp gmtModifiedTimestamp = rs.getTimestamp(ServerTableColumnsName.LOCK_TABLE_GMT_MODIFIED); + if (gmtModifiedTimestamp != null) { + globalLockVO.setGmtModified(gmtModifiedTimestamp.getTime()); + } + return globalLockVO; + } + @Override public String toString() { return "GlobalLockVO{" + diff --git a/server/src/main/java/io/seata/server/console/vo/GlobalSessionVO.java b/server/src/main/java/io/seata/server/console/vo/GlobalSessionVO.java index 067944485c9..e12b80e0041 100644 --- a/server/src/main/java/io/seata/server/console/vo/GlobalSessionVO.java +++ b/server/src/main/java/io/seata/server/console/vo/GlobalSessionVO.java @@ -79,28 +79,6 @@ public GlobalSessionVO(String xid, this.branchSessionVOs = branchSessionVOs; } - public static GlobalSessionVO convert(ResultSet rs) throws SQLException { - GlobalSessionVO globalSessionVO = new GlobalSessionVO(); - globalSessionVO.setXid(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_XID)); - globalSessionVO.setTransactionId(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_ID)); - globalSessionVO.setStatus(rs.getInt(ServerTableColumnsName.GLOBAL_TABLE_STATUS)); - globalSessionVO.setApplicationId(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_ID)); - globalSessionVO.setTransactionServiceGroup(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_SERVICE_GROUP)); - globalSessionVO.setTransactionName(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_NAME)); - globalSessionVO.setTimeout(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_TIMEOUT)); - globalSessionVO.setBeginTime(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_BEGIN_TIME)); - globalSessionVO.setApplicationData(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_DATA)); - Timestamp gmtCreateTimestamp = rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_CREATE); - if (gmtCreateTimestamp != null) { - globalSessionVO.setGmtCreate(gmtCreateTimestamp.getTime()); - } - Timestamp gmtModifiedTimestamp = rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_MODIFIED); - if (gmtModifiedTimestamp != null) { - globalSessionVO.setGmtModified(gmtModifiedTimestamp.getTime()); - } - return globalSessionVO; - } - public String getXid() { return xid; } @@ -197,6 +175,28 @@ public void setBranchSessionVOs(Set branchSessionVOs) { this.branchSessionVOs = branchSessionVOs; } + public static GlobalSessionVO convert(ResultSet rs) throws SQLException { + GlobalSessionVO globalSessionVO = new GlobalSessionVO(); + globalSessionVO.setXid(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_XID)); + globalSessionVO.setTransactionId(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_ID)); + globalSessionVO.setStatus(rs.getInt(ServerTableColumnsName.GLOBAL_TABLE_STATUS)); + globalSessionVO.setApplicationId(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_ID)); + globalSessionVO.setTransactionServiceGroup(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_SERVICE_GROUP)); + globalSessionVO.setTransactionName(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_NAME)); + globalSessionVO.setTimeout(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_TIMEOUT)); + globalSessionVO.setBeginTime(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_BEGIN_TIME)); + globalSessionVO.setApplicationData(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_DATA)); + Timestamp gmtCreateTimestamp = rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_CREATE); + if (gmtCreateTimestamp != null) { + globalSessionVO.setGmtCreate(gmtCreateTimestamp.getTime()); + } + Timestamp gmtModifiedTimestamp = rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_MODIFIED); + if (gmtModifiedTimestamp != null) { + globalSessionVO.setGmtModified(gmtModifiedTimestamp.getTime()); + } + return globalSessionVO; + } + @Override public String toString() { return "GlobalSessionVO{" + diff --git a/server/src/main/java/io/seata/server/coordinator/DefaultCoordinator.java b/server/src/main/java/io/seata/server/coordinator/DefaultCoordinator.java index 8ff33359c35..5f94bf2a55b 100644 --- a/server/src/main/java/io/seata/server/coordinator/DefaultCoordinator.java +++ b/server/src/main/java/io/seata/server/coordinator/DefaultCoordinator.java @@ -149,25 +149,35 @@ public class DefaultCoordinator extends AbstractTCInboundHandler implements Tran private static final boolean ROLLBACK_RETRY_TIMEOUT_UNLOCK_ENABLE = ConfigurationFactory.getInstance().getBoolean( ConfigurationKeys.ROLLBACK_RETRY_TIMEOUT_UNLOCK_ENABLE, DEFAULT_ROLLBACK_RETRY_TIMEOUT_UNLOCK_ENABLE); - private static volatile DefaultCoordinator instance; + private final ScheduledThreadPoolExecutor retryRollbacking = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(RETRY_ROLLBACKING, 1)); + private final ScheduledThreadPoolExecutor retryCommitting = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(RETRY_COMMITTING, 1)); + private final ScheduledThreadPoolExecutor asyncCommitting = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(ASYNC_COMMITTING, 1)); + private final ScheduledThreadPoolExecutor timeoutCheck = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(TX_TIMEOUT_CHECK, 1)); + private final ScheduledThreadPoolExecutor undoLogDelete = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(UNDOLOG_DELETE, 1)); + private final GlobalStatus[] rollbackingStatuses = new GlobalStatus[] {GlobalStatus.TimeoutRollbacking, GlobalStatus.TimeoutRollbackRetrying, GlobalStatus.RollbackRetrying, GlobalStatus.Rollbacking}; + private final GlobalStatus[] retryCommittingStatuses = new GlobalStatus[] {GlobalStatus.Committing, GlobalStatus.CommitRetrying, GlobalStatus.Committed}; - private RemotingServer remotingServer; private final ThreadPoolExecutor branchRemoveExecutor; + + private RemotingServer remotingServer; + private final DefaultCore core; + private static volatile DefaultCoordinator instance; + /** * Instantiates a new Default coordinator. * diff --git a/server/src/main/java/io/seata/server/session/GlobalSession.java b/server/src/main/java/io/seata/server/session/GlobalSession.java index d9c1da4d832..5ea1a9fa1db 100644 --- a/server/src/main/java/io/seata/server/session/GlobalSession.java +++ b/server/src/main/java/io/seata/server/session/GlobalSession.java @@ -99,10 +99,18 @@ public class GlobalSession implements SessionLifecycle, SessionStorable { /** - * Instantiates a new Global session. + * Add boolean. + * + * @param branchSession the branch session + * @return the boolean */ - public GlobalSession() { - this.lazyLoadBranch = false; + public boolean add(BranchSession branchSession) { + if (null != branchSessions) { + return branchSessions.add(branchSession); + } else { + // db and redis no need to deal with + return true; + } } /** @@ -118,53 +126,48 @@ public boolean remove(BranchSession branchSession) { private Set lifecycleListeners = new HashSet<>(); /** - * Instantiates a new Global session. + * Can be committed async boolean. * - * @param applicationId the application id - * @param transactionServiceGroup the transaction service group - * @param transactionName the transaction name - * @param timeout the timeout - * @param lazyLoadBranch the lazy load branch + * @return the boolean */ - public GlobalSession(String applicationId, String transactionServiceGroup, String transactionName, int timeout, boolean lazyLoadBranch) { - this.transactionId = UUIDGenerator.generateUUID(); - this.status = GlobalStatus.Begin; - this.lazyLoadBranch = lazyLoadBranch; - if (!lazyLoadBranch) { - this.branchSessions = new ArrayList<>(); + public boolean canBeCommittedAsync() { + List branchSessions = getBranchSessions(); + for (BranchSession branchSession : branchSessions) { + if (!branchSession.canBeCommittedAsync()) { + return false; + } } - this.applicationId = applicationId; - this.transactionServiceGroup = transactionServiceGroup; - this.transactionName = transactionName; - this.timeout = timeout; - this.xid = XID.generateXID(transactionId); + return true; } /** - * Instantiates a new Global session. + * Has AT branch * - * @param applicationId the application id - * @param transactionServiceGroup the transaction service group - * @param transactionName the transaction name - * @param timeout the timeout + * @return the boolean */ - public GlobalSession(String applicationId, String transactionServiceGroup, String transactionName, int timeout) { - this(applicationId, transactionServiceGroup, transactionName, timeout, false); + public boolean hasATBranch() { + List branchSessions = getBranchSessions(); + for (BranchSession branchSession : branchSessions) { + if (branchSession.getBranchType() == BranchType.AT) { + return true; + } + } + return false; } /** - * Create global session global session. + * Is saga type transaction * - * @param applicationId the application id - * @param txServiceGroup the tx service group - * @param txName the tx name - * @param timeout the timeout - * @return the global session + * @return is saga */ - public static GlobalSession createGlobalSession(String applicationId, String txServiceGroup, String txName, - int timeout) { - GlobalSession session = new GlobalSession(applicationId, txServiceGroup, txName, timeout, false); - return session; + public boolean isSaga() { + List branchSessions = getBranchSessions(); + if (branchSessions.size() > 0) { + return BranchType.SAGA == branchSessions.get(0).getBranchType(); + } else { + return StringUtils.isNotBlank(transactionName) + && transactionName.startsWith(Constants.SAGA_TRANS_NAME_PREFIX); + } } /** @@ -194,18 +197,14 @@ public void begin() throws TransactionException { } } - /** - * Add boolean. - * - * @param branchSession the branch session - * @return the boolean - */ - public boolean add(BranchSession branchSession) { - if (null != branchSessions) { - return branchSessions.add(branchSession); - } else { - // db and redis no need to deal with - return true; + @Override + public void changeGlobalStatus(GlobalStatus status) throws TransactionException { + if (GlobalStatus.Rollbacking == status) { + LockerManagerFactory.getLockManager().updateLockStatus(xid, LockStatus.Rollbacking); + } + this.status = status; + for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { + lifecycleListener.onStatusChange(this, status); } } @@ -232,48 +231,36 @@ public void close() throws TransactionException { } } - /** - * Can be committed async boolean. - * - * @return the boolean - */ - public boolean canBeCommittedAsync() { - List branchSessions = getBranchSessions(); - for (BranchSession branchSession : branchSessions) { - if (!branchSession.canBeCommittedAsync()) { - return false; + @Override + public void end() throws TransactionException { + if (GlobalStatus.isTwoPhaseSuccess(status)) { + // Clean locks first + clean(); + for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { + lifecycleListener.onSuccessEnd(this); + } + } else { + for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { + lifecycleListener.onFailEnd(this); } } - return true; } - /** - * Has AT branch - * - * @return the boolean - */ - public boolean hasATBranch() { - List branchSessions = getBranchSessions(); - for (BranchSession branchSession : branchSessions) { - if (branchSession.getBranchType() == BranchType.AT) { - return true; - } + public void clean() throws TransactionException { + if (!LockerManagerFactory.getLockManager().releaseGlobalSessionLock(this)) { + throw new TransactionException("UnLock globalSession error, xid = " + this.xid); } - return false; } /** - * Is saga type transaction + * Close and clean. * - * @return is saga + * @throws TransactionException the transaction exception */ - public boolean isSaga() { - List branchSessions = getBranchSessions(); - if (branchSessions.size() > 0) { - return BranchType.SAGA == branchSessions.get(0).getBranchType(); - } else { - return StringUtils.isNotBlank(transactionName) - && transactionName.startsWith(Constants.SAGA_TRANS_NAME_PREFIX); + public void closeAndClean() throws TransactionException { + close(); + if (this.hasATBranch()) { + clean(); } } @@ -304,50 +291,6 @@ public void addBranch(BranchSession branchSession) throws TransactionException { add(branchSession); } - @Override - public void changeGlobalStatus(GlobalStatus status) throws TransactionException { - if (GlobalStatus.Rollbacking == status) { - LockerManagerFactory.getLockManager().updateLockStatus(xid, LockStatus.Rollbacking); - } - this.status = status; - for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { - lifecycleListener.onStatusChange(this, status); - } - } - - @Override - public void end() throws TransactionException { - if (GlobalStatus.isTwoPhaseSuccess(status)) { - // Clean locks first - clean(); - for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { - lifecycleListener.onSuccessEnd(this); - } - } else { - for (SessionLifecycleListener lifecycleListener : lifecycleListeners) { - lifecycleListener.onFailEnd(this); - } - } - } - - public void clean() throws TransactionException { - if (!LockerManagerFactory.getLockManager().releaseGlobalSessionLock(this)) { - throw new TransactionException("UnLock globalSession error, xid = " + this.xid); - } - } - - /** - * Close and clean. - * - * @throws TransactionException the transaction exception - */ - public void closeAndClean() throws TransactionException { - close(); - if (this.hasATBranch()) { - clean(); - } - } - public void loadBranchs() { if (branchSessions == null && isLazyLoadBranch()) { synchronized (this) { @@ -413,6 +356,59 @@ public List getSortedBranches() { return new ArrayList<>(getBranchSessions()); } + /** + * Gets reverse sorted branches. + * + * @return the reverse sorted branches + */ + public List getReverseSortedBranches() { + List reversed = new ArrayList<>(getBranchSessions()); + Collections.reverse(reversed); + return reversed; + } + + /** + * Instantiates a new Global session. + */ + public GlobalSession() { + this.lazyLoadBranch = false; + } + + /** + * Instantiates a new Global session. + * + * @param applicationId the application id + * @param transactionServiceGroup the transaction service group + * @param transactionName the transaction name + * @param timeout the timeout + * @param lazyLoadBranch the lazy load branch + */ + public GlobalSession(String applicationId, String transactionServiceGroup, String transactionName, int timeout, boolean lazyLoadBranch) { + this.transactionId = UUIDGenerator.generateUUID(); + this.status = GlobalStatus.Begin; + this.lazyLoadBranch = lazyLoadBranch; + if (!lazyLoadBranch) { + this.branchSessions = new ArrayList<>(); + } + this.applicationId = applicationId; + this.transactionServiceGroup = transactionServiceGroup; + this.transactionName = transactionName; + this.timeout = timeout; + this.xid = XID.generateXID(transactionId); + } + + /** + * Instantiates a new Global session. + * + * @param applicationId the application id + * @param transactionServiceGroup the transaction service group + * @param transactionName the transaction name + * @param timeout the timeout + */ + public GlobalSession(String applicationId, String transactionServiceGroup, String transactionName, int timeout) { + this(applicationId, transactionServiceGroup, transactionName, timeout, false); + } + /** * Gets transaction id. * @@ -539,19 +535,23 @@ public void setApplicationData(String applicationData) { this.applicationData = applicationData; } + public boolean isLazyLoadBranch() { + return lazyLoadBranch; + } + /** - * Gets reverse sorted branches. + * Create global session global session. * - * @return the reverse sorted branches + * @param applicationId the application id + * @param txServiceGroup the tx service group + * @param txName the tx name + * @param timeout the timeout + * @return the global session */ - public List getReverseSortedBranches() { - List reversed = new ArrayList<>(getBranchSessions()); - Collections.reverse(reversed); - return reversed; - } - - public boolean isLazyLoadBranch() { - return lazyLoadBranch; + public static GlobalSession createGlobalSession(String applicationId, String txServiceGroup, String txName, + int timeout) { + GlobalSession session = new GlobalSession(applicationId, txServiceGroup, txName, timeout, false); + return session; } /** diff --git a/server/src/main/java/io/seata/server/storage/db/lock/DataBaseDistributedLocker.java b/server/src/main/java/io/seata/server/storage/db/lock/DataBaseDistributedLocker.java index 3bfdc5d2d27..70f101edf63 100644 --- a/server/src/main/java/io/seata/server/storage/db/lock/DataBaseDistributedLocker.java +++ b/server/src/main/java/io/seata/server/storage/db/lock/DataBaseDistributedLocker.java @@ -53,9 +53,21 @@ @LoadLevel(name = "db", scope = Scope.SINGLETON) public class DataBaseDistributedLocker implements DistributedLocker { private static final Logger LOGGER = LoggerFactory.getLogger(DataBaseDistributedLocker.class); + + private final String dbType; + + private final String datasourceType; + + private volatile String distributedLockTable; + + private DataSource distributedLockDataSource; + private static final String LOCK_WAIT_TIMEOUT_MYSQL_MESSAGE = "try restarting transaction"; + private static final int LOCK_WAIT_TIMEOUT_MYSQL_CODE = 1205; + private static final Set IGNORE_MYSQL_CODE = new HashSet<>(); + private static final Set IGNORE_MYSQL_MESSAGE = new HashSet<>(); static { @@ -63,10 +75,6 @@ public class DataBaseDistributedLocker implements DistributedLocker { IGNORE_MYSQL_MESSAGE.add(LOCK_WAIT_TIMEOUT_MYSQL_MESSAGE); } - private final String dbType; - private final String datasourceType; - private volatile String distributedLockTable; - private DataSource distributedLockDataSource; /** * whether the distribute lock demotion * using for 1.5.0 only and will remove in 1.6.0 diff --git a/server/src/main/java/io/seata/server/storage/redis/store/RedisTransactionStoreManager.java b/server/src/main/java/io/seata/server/storage/redis/store/RedisTransactionStoreManager.java index 6c57d275432..dd50ca12175 100644 --- a/server/src/main/java/io/seata/server/storage/redis/store/RedisTransactionStoreManager.java +++ b/server/src/main/java/io/seata/server/storage/redis/store/RedisTransactionStoreManager.java @@ -101,10 +101,11 @@ public class RedisTransactionStoreManager extends AbstractTransactionStoreManage * The constant CONFIG. */ private static final Configuration CONFIG = ConfigurationFactory.getInstance(); + /** - * Map for LogOperation Global Operation + * The Log query limit. */ - public static volatile ImmutableMap> globalMap; + private int logQueryLimit; /** * Get the instance. @@ -119,14 +120,6 @@ public static RedisTransactionStoreManager getInstance() { } return instance; } - /** - * Map for LogOperation Branch Operation - */ - public static volatile ImmutableMap> branchMap; - /** - * The Log query limit. - */ - private int logQueryLimit; /** * init map to constructor @@ -138,6 +131,17 @@ public RedisTransactionStoreManager() { logQueryLimit = CONFIG.getInt(STORE_REDIS_QUERY_LIMIT, DEFAULT_QUERY_LIMIT); } + /** + * Map for LogOperation Global Operation + */ + public static volatile ImmutableMap> globalMap; + + /** + * Map for LogOperation Branch Operation + */ + public static volatile ImmutableMap> branchMap; + + /** * init globalMap * diff --git a/server/src/main/java/io/seata/server/store/StoreConfig.java b/server/src/main/java/io/seata/server/store/StoreConfig.java index a0aeafb75af..362c7992e1d 100644 --- a/server/src/main/java/io/seata/server/store/StoreConfig.java +++ b/server/src/main/java/io/seata/server/store/StoreConfig.java @@ -163,6 +163,10 @@ public enum StoreMode { this.name = name; } + public String getName() { + return name; + } + public static StoreMode get(String name) { for (StoreMode mode : StoreMode.values()) { if (mode.getName().equalsIgnoreCase(name)) { @@ -171,10 +175,6 @@ public static StoreMode get(String name) { } throw new IllegalArgumentException("unknown store mode:" + name); } - - public String getName() { - return name; - } } public enum SessionMode { @@ -197,6 +197,10 @@ public enum SessionMode { this.name = name; } + public String getName() { + return name; + } + public static SessionMode get(String name) { for (SessionMode mode : SessionMode.values()) { if (mode.getName().equalsIgnoreCase(name)) { @@ -205,10 +209,6 @@ public static SessionMode get(String name) { } throw new IllegalArgumentException("unknown session mode:" + name); } - - public String getName() { - return name; - } } public enum LockMode { @@ -231,6 +231,10 @@ public enum LockMode { this.name = name; } + public String getName() { + return name; + } + public static LockMode get(String name) { for (LockMode mode : LockMode.values()) { if (mode.getName().equalsIgnoreCase(name)) { @@ -239,10 +243,6 @@ public static LockMode get(String name) { } throw new IllegalArgumentException("unknown lock mode:" + name); } - - public String getName() { - return name; - } } } diff --git a/server/src/test/java/io/seata/server/coordinator/DefaultCoordinatorTest.java b/server/src/test/java/io/seata/server/coordinator/DefaultCoordinatorTest.java index 519a412ef51..594d92c0188 100644 --- a/server/src/test/java/io/seata/server/coordinator/DefaultCoordinatorTest.java +++ b/server/src/test/java/io/seata/server/coordinator/DefaultCoordinatorTest.java @@ -158,11 +158,6 @@ public void test_handleRetryRollbacking() throws TransactionException, Interrupt } - private static void deleteAndCreateDataFile() throws IOException { - StoreUtil.deleteDataFile(); - SessionHolder.init(SessionMode.FILE); - } - @Test @DisabledOnJre(JRE.JAVA_17) // `ReflectionUtil.modifyStaticFinalField` does not supported java17 public void test_handleRetryRollbackingTimeOut() throws TransactionException, InterruptedException, NoSuchFieldException, IllegalAccessException { @@ -189,19 +184,6 @@ public void test_handleRetryRollbackingTimeOut() throws TransactionException, In } } - @AfterAll - public static void afterClass() throws Exception { - - Collection globalSessions = SessionHolder.getRootSessionManager().allSessions(); - Collection asyncGlobalSessions = SessionHolder.getAsyncCommittingSessionManager().allSessions(); - for (GlobalSession asyncGlobalSession : asyncGlobalSessions) { - asyncGlobalSession.closeAndClean(); - } - for (GlobalSession globalSession : globalSessions) { - globalSession.closeAndClean(); - } - } - @Test @DisabledOnJre(JRE.JAVA_17) // `ReflectionUtil.modifyStaticFinalField` does not supported java17 public void test_handleRetryRollbackingTimeOut_unlock() throws TransactionException, InterruptedException, @@ -231,6 +213,24 @@ public void test_handleRetryRollbackingTimeOut_unlock() throws TransactionExcept } } + @AfterAll + public static void afterClass() throws Exception { + + Collection globalSessions = SessionHolder.getRootSessionManager().allSessions(); + Collection asyncGlobalSessions = SessionHolder.getAsyncCommittingSessionManager().allSessions(); + for (GlobalSession asyncGlobalSession : asyncGlobalSessions) { + asyncGlobalSession.closeAndClean(); + } + for (GlobalSession globalSession : globalSessions) { + globalSession.closeAndClean(); + } + } + + private static void deleteAndCreateDataFile() throws IOException { + StoreUtil.deleteDataFile(); + SessionHolder.init(SessionMode.FILE); + } + @AfterEach public void tearDown() throws IOException { MetricsManager.get().getRegistry().clearUp(); diff --git a/server/src/test/java/io/seata/server/event/DefaultCoreForEventBusTest.java b/server/src/test/java/io/seata/server/event/DefaultCoreForEventBusTest.java index f24d511556e..bb9c4a154ad 100644 --- a/server/src/test/java/io/seata/server/event/DefaultCoreForEventBusTest.java +++ b/server/src/test/java/io/seata/server/event/DefaultCoreForEventBusTest.java @@ -61,12 +61,6 @@ public static void setUp(ApplicationContext context) throws InterruptedException Thread.sleep(5000); } - @AfterAll - public static void setDown() throws InterruptedException { - Optional.ofNullable(DefaultCoordinator.getInstance()).ifPresent(DefaultCoordinator::destroy); - Optional.ofNullable(MetricsManager.get().getRegistry()).ifPresent(Registry::clearUp); - } - @Test public void test() throws IOException, TransactionException, InterruptedException { class GlobalTransactionEventSubscriber { @@ -93,14 +87,14 @@ public void processGlobalTransactionEvent(GlobalTransactionEvent event) { } } - public CountDownLatch getDownLatch() { - return downLatch; - } - public void setDownLatch(CountDownLatch countDownLatch) { this.downLatch = countDownLatch; } + public CountDownLatch getDownLatch() { + return downLatch; + } + public void resetDownLatch() { if (null != downLatch) { downLatch = null; @@ -163,4 +157,10 @@ public void resetDownLatch() { } } + @AfterAll + public static void setDown() throws InterruptedException { + Optional.ofNullable(DefaultCoordinator.getInstance()).ifPresent(DefaultCoordinator::destroy); + Optional.ofNullable(MetricsManager.get().getRegistry()).ifPresent(Registry::clearUp); + } + } diff --git a/server/src/test/java/io/seata/server/lock/LockManagerTest.java b/server/src/test/java/io/seata/server/lock/LockManagerTest.java index f99b37f6a46..d661455298f 100644 --- a/server/src/test/java/io/seata/server/lock/LockManagerTest.java +++ b/server/src/test/java/io/seata/server/lock/LockManagerTest.java @@ -199,104 +199,6 @@ public void isLockableTest(BranchSession branchSession) throws Exception { .isLockable(branchSession.getXid(), branchSession.getResourceId(), branchSession.getLockKey())); } - /** - * Branch session provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static Stream branchSessionProvider() { - BranchSession branchSession = new BranchSession(); - branchSession.setTransactionId(UUIDGenerator.generateUUID()); - branchSession.setBranchId(0L); - branchSession.setClientId("c1"); - branchSession.setResourceGroupId(DEFAULT_TX_GROUP); - branchSession.setResourceId("tb_1"); - branchSession.setLockKey("t:0"); - branchSession.setBranchType(BranchType.AT); - branchSession.setApplicationData("{\"data\":\"test\"}"); - branchSession.setBranchType(BranchType.AT); - return Stream.of( - Arguments.of(branchSession)); - } - - /** - * Branch session provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static BranchSession[] baseBranchSession(String resource, String lockKey1, String lockKey2) { - BranchSession branchSession1 = new BranchSession(); - branchSession1.setTransactionId(UUIDGenerator.generateUUID()); - branchSession1.setBranchId(1L); - branchSession1.setClientId("c1"); - branchSession1.setResourceGroupId(DEFAULT_TX_GROUP); - branchSession1.setResourceId(resource); - branchSession1.setLockKey(lockKey1); - branchSession1.setBranchType(BranchType.AT); - branchSession1.setApplicationData("{\"data\":\"test\"}"); - branchSession1.setBranchType(BranchType.AT); - - BranchSession branchSession2 = new BranchSession(); - branchSession2.setTransactionId(UUIDGenerator.generateUUID()); - branchSession2.setBranchId(2L); - branchSession2.setClientId("c1"); - branchSession2.setResourceGroupId(DEFAULT_TX_GROUP); - branchSession2.setResourceId(resource); - branchSession2.setLockKey(lockKey2); - branchSession2.setBranchType(BranchType.AT); - branchSession2.setApplicationData("{\"data\":\"test\"}"); - branchSession2.setBranchType(BranchType.AT); - - return new BranchSession[]{branchSession1, branchSession2}; - } - - /** - * global sessions provider object [ ] [ ]. - * @return the objects [ ] [ ] - */ - static Stream globalSessionForLockTestProvider() throws ParseException { - final BranchSession[] branchSessions1 = baseBranchSession("department", "a:1,2", "e:1,2"); - - final BranchSession branchSession1 = branchSessions1[0]; - branchSession1.setTransactionId(39721L); - final BranchSession branchSession2 = branchSessions1[1]; - branchSession2.setTransactionId(89721L); - - final BranchSession[] branchSessions2 = baseBranchSession("employee", "de:43,99", "df:33,66"); - final BranchSession branchSession3 = branchSessions2[0]; - branchSession3.setTransactionId(924823L); - - final BranchSession branchSession4 = branchSessions2[1]; - branchSession4.setTransactionId(493747292L); - - - final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test1", 6000); - globalSession1.setXid("xid1"); - globalSession1.add(branchSession1); - globalSession1.add(branchSession2); - globalSession1.setBeginTime(dateFormat.parse("2022-1-1 03:00:00").getTime()); - - GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test2", 6000); - globalSession2.setXid("ddd1"); - globalSession2.add(branchSession3); - globalSession2.add(branchSession4); - globalSession2.setBeginTime(dateFormat.parse("2022-1-1 08:00:00").getTime()); - - return Stream.of(Arguments.of(globalSession1, globalSession2)); - } - - /** - * Base branch sessions provider object [ ] [ ]. Could assign resource and lock keys. - * - * @return the object [ ] [ ] - */ - static Stream baseBranchSessionsProvider(String resource, String lockKey1, String lockKey2) { - - return Stream.of(Arguments.of(baseBranchSession(resource, lockKey1, lockKey2))); - } - @ParameterizedTest @MethodSource("duplicatePkBranchSessionsProvider") public void duplicatePkBranchSessionHolderTest(BranchSession branchSession1, BranchSession branchSession2) throws Exception { @@ -446,6 +348,104 @@ public void lockQueryTest(GlobalSession globalSessions1, GlobalSession globalSes } } + /** + * Branch session provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream branchSessionProvider() { + BranchSession branchSession = new BranchSession(); + branchSession.setTransactionId(UUIDGenerator.generateUUID()); + branchSession.setBranchId(0L); + branchSession.setClientId("c1"); + branchSession.setResourceGroupId(DEFAULT_TX_GROUP); + branchSession.setResourceId("tb_1"); + branchSession.setLockKey("t:0"); + branchSession.setBranchType(BranchType.AT); + branchSession.setApplicationData("{\"data\":\"test\"}"); + branchSession.setBranchType(BranchType.AT); + return Stream.of( + Arguments.of(branchSession)); + } + + /** + * Branch session provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static BranchSession[] baseBranchSession(String resource, String lockKey1, String lockKey2) { + BranchSession branchSession1 = new BranchSession(); + branchSession1.setTransactionId(UUIDGenerator.generateUUID()); + branchSession1.setBranchId(1L); + branchSession1.setClientId("c1"); + branchSession1.setResourceGroupId(DEFAULT_TX_GROUP); + branchSession1.setResourceId(resource); + branchSession1.setLockKey(lockKey1); + branchSession1.setBranchType(BranchType.AT); + branchSession1.setApplicationData("{\"data\":\"test\"}"); + branchSession1.setBranchType(BranchType.AT); + + BranchSession branchSession2 = new BranchSession(); + branchSession2.setTransactionId(UUIDGenerator.generateUUID()); + branchSession2.setBranchId(2L); + branchSession2.setClientId("c1"); + branchSession2.setResourceGroupId(DEFAULT_TX_GROUP); + branchSession2.setResourceId(resource); + branchSession2.setLockKey(lockKey2); + branchSession2.setBranchType(BranchType.AT); + branchSession2.setApplicationData("{\"data\":\"test\"}"); + branchSession2.setBranchType(BranchType.AT); + + return new BranchSession[]{branchSession1, branchSession2}; + } + + /** + * global sessions provider object [ ] [ ]. + * @return the objects [ ] [ ] + */ + static Stream globalSessionForLockTestProvider() throws ParseException { + final BranchSession[] branchSessions1 = baseBranchSession("department", "a:1,2", "e:1,2"); + + final BranchSession branchSession1 = branchSessions1[0]; + branchSession1.setTransactionId(39721L); + final BranchSession branchSession2 = branchSessions1[1]; + branchSession2.setTransactionId(89721L); + + final BranchSession[] branchSessions2 = baseBranchSession("employee", "de:43,99", "df:33,66"); + final BranchSession branchSession3 = branchSessions2[0]; + branchSession3.setTransactionId(924823L); + + final BranchSession branchSession4 = branchSessions2[1]; + branchSession4.setTransactionId(493747292L); + + + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test1", 6000); + globalSession1.setXid("xid1"); + globalSession1.add(branchSession1); + globalSession1.add(branchSession2); + globalSession1.setBeginTime(dateFormat.parse("2022-1-1 03:00:00").getTime()); + + GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test2", 6000); + globalSession2.setXid("ddd1"); + globalSession2.add(branchSession3); + globalSession2.add(branchSession4); + globalSession2.setBeginTime(dateFormat.parse("2022-1-1 08:00:00").getTime()); + + return Stream.of(Arguments.of(globalSession1, globalSession2)); + } + + /** + * Base branch sessions provider object [ ] [ ]. Could assign resource and lock keys. + * + * @return the object [ ] [ ] + */ + static Stream baseBranchSessionsProvider(String resource, String lockKey1, String lockKey2) { + + return Stream.of(Arguments.of(baseBranchSession(resource, lockKey1, lockKey2))); + } + /** * Branch sessions provider object [ ] [ ]. * diff --git a/server/src/test/java/io/seata/server/session/FileSessionManagerTest.java b/server/src/test/java/io/seata/server/session/FileSessionManagerTest.java index e206bc4ec7b..9b2b74856c8 100644 --- a/server/src/test/java/io/seata/server/session/FileSessionManagerTest.java +++ b/server/src/test/java/io/seata/server/session/FileSessionManagerTest.java @@ -63,11 +63,13 @@ public class FileSessionManagerTest { private static volatile List sessionManagerList; - private static String sessionStorePath = CONFIG.getConfig(ConfigurationKeys.STORE_FILE_DIR, - DEFAULT_SESSION_STORE_FILE_DIR); + @Resource(type = GlobalSessionService.class) private GlobalSessionService globalSessionService; + private static String sessionStorePath = CONFIG.getConfig(ConfigurationKeys.STORE_FILE_DIR, + DEFAULT_SESSION_STORE_FILE_DIR); + @BeforeAll public static void setUp(ApplicationContext context) { StoreUtil.deleteDataFile(); @@ -233,95 +235,6 @@ public void allSessionsTest(List globalSessions) throws Exception } } - /** - * Global session provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static Stream globalSessionProvider() { - GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - - String xid = XID.generateXID(globalSession.getTransactionId()); - globalSession.setXid(xid); - - return Stream.of( - Arguments.of(globalSession) - ); - } - - /** - * Global sessions provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static Stream globalSessionsProvider() { - GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - return Stream.of( - Arguments.of(Arrays.asList(globalSession1, globalSession2)) - ); - } - - /** - * Global sessions provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static Stream globalSessionsWithPageResultProvider() throws ParseException { - final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test1", 60000); - globalSession1.setBeginTime(dateFormat.parse("2220-1-1 08:02:00").getTime()); - - GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test2", 60000); - globalSession2.setBeginTime(dateFormat.parse("2220-1-1 08:04:00").getTime()); - - GlobalSession globalSession3 = new GlobalSession("with-branchSession-app", DEFAULT_TX_GROUP, "test3", 60000); - globalSession3.setBeginTime(dateFormat.parse("2220-1-1 08:20:00").getTime()); - globalSession3.setStatus(GlobalStatus.CommitFailed); - - - final BranchSession branchSession = new BranchSession(); - branchSession.setApplicationData("applicationData"); - branchSession.setResourceGroupId("applicationData"); - branchSession.setClientId("clientId"); - branchSession.setResourceId("resourceId"); - branchSession.setLockKey("lockKey"); - branchSession.setBranchType(BranchType.AT); - branchSession.setStatus(BranchStatus.Registered); - branchSession.setTransactionId(11L); - branchSession.setBranchId(22L); - branchSession.setXid("xid"); - branchSession.setLockStatus(LockStatus.Locked); - globalSession3.add(branchSession); - - - return Stream.of( - Arguments.of(Arrays.asList(globalSession1, globalSession2, globalSession3)) - ); - } - - /** - * Branch session provider object [ ] [ ]. - * - * @return the object [ ] [ ] - */ - static Stream branchSessionProvider() { - GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - globalSession.setXid(XID.generateXID(globalSession.getTransactionId())); - BranchSession branchSession = new BranchSession(); - branchSession.setTransactionId(globalSession.getTransactionId()); - branchSession.setBranchId(1L); - branchSession.setResourceGroupId(DEFAULT_TX_GROUP); - branchSession.setResourceId("tb_1"); - branchSession.setLockKey("t_1"); - branchSession.setBranchType(BranchType.AT); - branchSession.setApplicationData("{\"data\":\"test\"}"); - return Stream.of( - Arguments.of(globalSession, branchSession) - ); - } - /** * Find global sessions test. * @@ -584,4 +497,93 @@ public void onEndTest(GlobalSession globalSession) throws Exception { } } + /** + * Global session provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream globalSessionProvider() { + GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + + String xid = XID.generateXID(globalSession.getTransactionId()); + globalSession.setXid(xid); + + return Stream.of( + Arguments.of(globalSession) + ); + } + + /** + * Global sessions provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream globalSessionsProvider() { + GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + return Stream.of( + Arguments.of(Arrays.asList(globalSession1, globalSession2)) + ); + } + + /** + * Global sessions provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream globalSessionsWithPageResultProvider() throws ParseException { + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + GlobalSession globalSession1 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test1", 60000); + globalSession1.setBeginTime(dateFormat.parse("2220-1-1 08:02:00").getTime()); + + GlobalSession globalSession2 = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test2", 60000); + globalSession2.setBeginTime(dateFormat.parse("2220-1-1 08:04:00").getTime()); + + GlobalSession globalSession3 = new GlobalSession("with-branchSession-app", DEFAULT_TX_GROUP, "test3", 60000); + globalSession3.setBeginTime(dateFormat.parse("2220-1-1 08:20:00").getTime()); + globalSession3.setStatus(GlobalStatus.CommitFailed); + + + final BranchSession branchSession = new BranchSession(); + branchSession.setApplicationData("applicationData"); + branchSession.setResourceGroupId("applicationData"); + branchSession.setClientId("clientId"); + branchSession.setResourceId("resourceId"); + branchSession.setLockKey("lockKey"); + branchSession.setBranchType(BranchType.AT); + branchSession.setStatus(BranchStatus.Registered); + branchSession.setTransactionId(11L); + branchSession.setBranchId(22L); + branchSession.setXid("xid"); + branchSession.setLockStatus(LockStatus.Locked); + globalSession3.add(branchSession); + + + return Stream.of( + Arguments.of(Arrays.asList(globalSession1, globalSession2, globalSession3)) + ); + } + + /** + * Branch session provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream branchSessionProvider() { + GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + globalSession.setXid(XID.generateXID(globalSession.getTransactionId())); + BranchSession branchSession = new BranchSession(); + branchSession.setTransactionId(globalSession.getTransactionId()); + branchSession.setBranchId(1L); + branchSession.setResourceGroupId(DEFAULT_TX_GROUP); + branchSession.setResourceId("tb_1"); + branchSession.setLockKey("t_1"); + branchSession.setBranchType(BranchType.AT); + branchSession.setApplicationData("{\"data\":\"test\"}"); + return Stream.of( + Arguments.of(globalSession, branchSession) + ); + } + } diff --git a/server/src/test/java/io/seata/server/session/GlobalSessionTest.java b/server/src/test/java/io/seata/server/session/GlobalSessionTest.java index 098b66d5125..c4787ce69e6 100644 --- a/server/src/test/java/io/seata/server/session/GlobalSessionTest.java +++ b/server/src/test/java/io/seata/server/session/GlobalSessionTest.java @@ -72,18 +72,15 @@ public void beginTest(GlobalSession globalSession) throws Exception { } /** - * Global session provider object [ ] [ ]. + * Change status test. * - * @return the object [ ] [ ] + * @param globalSession the global session + * @throws Exception the exception */ - static Stream globalSessionProvider() throws IOException { - GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - globalSession.setActive(true); - globalSession.addSessionLifecycleListener(new FileSessionManager("default", null)); - return Stream.of( - Arguments.of( - globalSession) - ); + @ParameterizedTest + @MethodSource("globalSessionProvider") + public void changeStatusTest(GlobalSession globalSession) throws Exception { + globalSession.changeGlobalStatus(GlobalStatus.Committed); } /** @@ -137,25 +134,17 @@ public void addBranchTest(GlobalSession globalSession, BranchSession branchSessi } /** - * Branch session provider object [ ] [ ]. + * Remove branch test. * - * @return the object [ ] [ ] + * @param globalSession the global session + * @param branchSession the branch session + * @throws Exception the exception */ - static Stream branchSessionProvider() { - GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); - BranchSession branchSession = new BranchSession(); - branchSession.setTransactionId(globalSession.getTransactionId()); - branchSession.setBranchId(1L); - branchSession.setResourceGroupId(DEFAULT_TX_GROUP); - branchSession.setResourceId("tb_1"); - branchSession.setLockKey("t_1"); - branchSession.setBranchType(BranchType.AT); - branchSession.setApplicationData("{\"data\":\"test\"}"); - globalSession.add(branchSession); - return Stream.of( - Arguments.of( - globalSession, branchSession) - ); + @ParameterizedTest + @MethodSource("branchSessionProvider") + public void removeBranchTest(GlobalSession globalSession, BranchSession branchSession) throws Exception { + globalSession.addBranch(branchSession); + globalSession.removeAndUnlockBranch(branchSession); } /** @@ -178,12 +167,26 @@ public void codecTest(GlobalSession globalSession) { } /** - * Branch session mt provider object [ ] [ ]. + * Global session provider object [ ] [ ]. * * @return the object [ ] [ ] */ + static Stream globalSessionProvider() throws IOException { + GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + globalSession.setActive(true); + globalSession.addSessionLifecycleListener(new FileSessionManager("default", null)); + return Stream.of( + Arguments.of( + globalSession) + ); + } - static Stream branchSessionTCCProvider() { + /** + * Branch session provider object [ ] [ ]. + * + * @return the object [ ] [ ] + */ + static Stream branchSessionProvider() { GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); BranchSession branchSession = new BranchSession(); branchSession.setTransactionId(globalSession.getTransactionId()); @@ -191,37 +194,34 @@ static Stream branchSessionTCCProvider() { branchSession.setResourceGroupId(DEFAULT_TX_GROUP); branchSession.setResourceId("tb_1"); branchSession.setLockKey("t_1"); - branchSession.setBranchType(BranchType.TCC); + branchSession.setBranchType(BranchType.AT); branchSession.setApplicationData("{\"data\":\"test\"}"); globalSession.add(branchSession); return Stream.of( - Arguments.of(globalSession) + Arguments.of( + globalSession, branchSession) ); } /** - * Change status test. + * Branch session mt provider object [ ] [ ]. * - * @param globalSession the global session - * @throws Exception the exception + * @return the object [ ] [ ] */ - @ParameterizedTest - @MethodSource("globalSessionProvider") - public void changeStatusTest(GlobalSession globalSession) throws Exception { - globalSession.changeGlobalStatus(GlobalStatus.Committed); - } - /** - * Remove branch test. - * - * @param globalSession the global session - * @param branchSession the branch session - * @throws Exception the exception - */ - @ParameterizedTest - @MethodSource("branchSessionProvider") - public void removeBranchTest(GlobalSession globalSession, BranchSession branchSession) throws Exception { - globalSession.addBranch(branchSession); - globalSession.removeAndUnlockBranch(branchSession); + static Stream branchSessionTCCProvider() { + GlobalSession globalSession = new GlobalSession("demo-app", DEFAULT_TX_GROUP, "test", 6000); + BranchSession branchSession = new BranchSession(); + branchSession.setTransactionId(globalSession.getTransactionId()); + branchSession.setBranchId(1L); + branchSession.setResourceGroupId(DEFAULT_TX_GROUP); + branchSession.setResourceId("tb_1"); + branchSession.setLockKey("t_1"); + branchSession.setBranchType(BranchType.TCC); + branchSession.setApplicationData("{\"data\":\"test\"}"); + globalSession.add(branchSession); + return Stream.of( + Arguments.of(globalSession) + ); } } diff --git a/server/src/test/java/io/seata/server/session/db/DataBaseSessionManagerTest.java b/server/src/test/java/io/seata/server/session/db/DataBaseSessionManagerTest.java index 7b40d373125..8457c7b3c8d 100644 --- a/server/src/test/java/io/seata/server/session/db/DataBaseSessionManagerTest.java +++ b/server/src/test/java/io/seata/server/session/db/DataBaseSessionManagerTest.java @@ -113,10 +113,6 @@ private static void prepareTable(BasicDataSource dataSource) { } } - @AfterAll - public static void setDown() throws SQLException { - dataSource.close(); - } @Test public void test_addGlobalSession() throws TransactionException, SQLException { @@ -151,6 +147,7 @@ public void test_addGlobalSession() throws TransactionException, SQLException { } } + @Test public void test_updateGlobalSessionStatus() throws TransactionException, SQLException { GlobalSession session = GlobalSession.createGlobalSession("test", @@ -271,6 +268,7 @@ public void test_findGlobalSession() throws Exception { } } + @Test public void test_addBranchSession() throws Exception { GlobalSession globalSession = GlobalSession.createGlobalSession("test", @@ -315,6 +313,7 @@ public void test_addBranchSession() throws Exception { } } + @Test public void test_updateBranchSessionStatus() throws Exception { GlobalSession globalSession = GlobalSession.createGlobalSession("test", @@ -411,6 +410,7 @@ public void test_removeBranchSession() throws Exception { } } + @Test public void test_allSessions() throws Exception { GlobalSession globalSession = GlobalSession.createGlobalSession("test", @@ -601,4 +601,9 @@ public void test_transactionNameGreaterDbSize() throws Exception { } } + @AfterAll + public static void setDown() throws SQLException { + dataSource.close(); + } + } diff --git a/server/src/test/java/io/seata/server/session/redis/MockRedisServer.java b/server/src/test/java/io/seata/server/session/redis/MockRedisServer.java index 11642136b88..567b04471de 100644 --- a/server/src/test/java/io/seata/server/session/redis/MockRedisServer.java +++ b/server/src/test/java/io/seata/server/session/redis/MockRedisServer.java @@ -46,12 +46,12 @@ public class MockRedisServer { })); } - public static MockRedisServer getInstance() { - return Instance.mockredis; - } - private static class Instance { private static final MockRedisServer mockredis = new MockRedisServer(); } + public static MockRedisServer getInstance() { + return Instance.mockredis; + } + } diff --git a/server/src/test/java/io/seata/server/session/redis/RedisDistributedLockerTest.java b/server/src/test/java/io/seata/server/session/redis/RedisDistributedLockerTest.java index 9ab646872ff..331c536ed79 100644 --- a/server/src/test/java/io/seata/server/session/redis/RedisDistributedLockerTest.java +++ b/server/src/test/java/io/seata/server/session/redis/RedisDistributedLockerTest.java @@ -44,11 +44,11 @@ @SpringBootTest public class RedisDistributedLockerTest { - private static DistributedLocker distributedLocker; - private static Jedis jedis; private String retryRollbacking = "RetryRollbacking"; private String retryCommiting = "RetryCommiting"; private String lockValue = "127.1.1.1:9081"; + private static DistributedLocker distributedLocker; + private static Jedis jedis; @BeforeAll public static void start(ApplicationContext context) throws IOException { @@ -59,14 +59,6 @@ public static void start(ApplicationContext context) throws IOException { jedis = JedisPooledFactory.getJedisInstance(); } - @AfterAll - public static void after() throws IOException { - EnhancedServiceLoader.unload(DistributedLocker.class); - DistributedLockerFactory.cleanLocker(); - DistributedLockerFactory.getDistributedLocker(StoreMode.FILE.getName()); - jedis.close(); - } - @Test public void test_acquireScheduledLock_success() { boolean acquire = distributedLocker.acquireLock(new DistributedLockDO(retryRollbacking, lockValue, 60000L)); @@ -140,4 +132,12 @@ public void test_acquireLock_false() { Assertions.assertFalse(acquire); } + @AfterAll + public static void after() throws IOException { + EnhancedServiceLoader.unload(DistributedLocker.class); + DistributedLockerFactory.cleanLocker(); + DistributedLockerFactory.getDistributedLocker(StoreMode.FILE.getName()); + jedis.close(); + } + } diff --git a/server/src/test/java/io/seata/server/session/redis/RedisTransactionStoreManagerTest.java b/server/src/test/java/io/seata/server/session/redis/RedisTransactionStoreManagerTest.java index a3de701bde6..a4b8d85abee 100644 --- a/server/src/test/java/io/seata/server/session/redis/RedisTransactionStoreManagerTest.java +++ b/server/src/test/java/io/seata/server/session/redis/RedisTransactionStoreManagerTest.java @@ -73,11 +73,6 @@ public static void start(ApplicationContext context) throws IOException { sessionManager = redisSessionManager; } - @AfterAll - public static void close(){ - redisTransactionStoreManager=null; - } - @Test public synchronized void testBeginSortByTimeoutQuery() throws TransactionException, InterruptedException { GlobalSession session1 = GlobalSession.createGlobalSession("test1", "test2", "test001", 500); @@ -278,4 +273,9 @@ public void testLimitAllSessions() { LOGGER.info("the limit All Sessions result is:[{}]",globalSessions); } + @AfterAll + public static void close(){ + redisTransactionStoreManager=null; + } + } diff --git a/spring-aot/pom.xml b/spring-aot/pom.xml index fb2ccc6728f..b0fb14ed7cf 100644 --- a/spring-aot/pom.xml +++ b/spring-aot/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/spring-aot/seata-spring-aot-client/pom.xml b/spring-aot/seata-spring-aot-client/pom.xml index 708c936f43e..52de9fd9751 100644 --- a/spring-aot/seata-spring-aot-client/pom.xml +++ b/spring-aot/seata-spring-aot-client/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/spring-aot/seata-spring-aot-core/pom.xml b/spring-aot/seata-spring-aot-core/pom.xml index 0e28cae7778..ad270c9d829 100644 --- a/spring-aot/seata-spring-aot-core/pom.xml +++ b/spring-aot/seata-spring-aot-core/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/spring-framework-fake-for-java8/pom.xml b/spring-framework-fake-for-java8/pom.xml index 7635f861353..993c0fd2b25 100644 --- a/spring-framework-fake-for-java8/pom.xml +++ b/spring-framework-fake-for-java8/pom.xml @@ -14,8 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - io.seata diff --git a/spring/src/main/java/io/seata/spring/annotation/AspectTransactional.java b/spring/src/main/java/io/seata/spring/annotation/AspectTransactional.java index b977cf90f30..b603bd8c8e2 100644 --- a/spring/src/main/java/io/seata/spring/annotation/AspectTransactional.java +++ b/spring/src/main/java/io/seata/spring/annotation/AspectTransactional.java @@ -25,51 +25,60 @@ */ public class AspectTransactional { - /** - * customized global lock retry interval(unit: ms) - * you may use this to override global config of "client.rm.lock.retryInterval" - * note: 0 or negative number will take no effect(which mean fall back to global config) - */ - int lockRetryInterval = 0; - /** - * customized global lock retry times - * you may use this to override global config of "client.rm.lock.retryTimes" - * note: negative number will take no effect(which mean fall back to global config) - */ - int lockRetryTimes = -1; - /** - * lock strategy mode - */ - LockStrategyMode lockStrategyMode; /** * Global transaction timeoutMills in MILLISECONDS. */ private int timeoutMills = DefaultValues.DEFAULT_GLOBAL_TRANSACTION_TIMEOUT; + /** * Given name of the global transaction instance. */ private String name = ""; + /** * roll back for the Class */ private Class[] rollbackFor = new Class[] {}; + /** * roll back for the class name */ private String[] rollbackForClassName = {}; + /** * not roll back for the Class */ private Class[] noRollbackFor = new Class[] {}; + /** * not roll back for the class name */ private String[] noRollbackForClassName = {}; + /** * the propagation of the global transaction */ private Propagation propagation = Propagation.REQUIRED; + /** + * customized global lock retry interval(unit: ms) + * you may use this to override global config of "client.rm.lock.retryInterval" + * note: 0 or negative number will take no effect(which mean fall back to global config) + */ + int lockRetryInterval = 0; + + /** + * customized global lock retry times + * you may use this to override global config of "client.rm.lock.retryTimes" + * note: negative number will take no effect(which mean fall back to global config) + */ + int lockRetryTimes = -1; + + /** + * lock strategy mode + */ + LockStrategyMode lockStrategyMode; + public AspectTransactional() {} public AspectTransactional(int timeoutMills, String name, Class[] rollbackFor, diff --git a/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionScanner.java b/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionScanner.java index d01c88ab92a..435b660b267 100644 --- a/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionScanner.java +++ b/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionScanner.java @@ -206,16 +206,6 @@ public void destroy() { ShutdownHook.getInstance().destroyAll(); } - public static boolean isTccAutoProxy(Class beanClass) { - Set> interfaceClasses = ReflectionUtil.getInterfaces(beanClass); - for (Class interClass : interfaceClasses) { - if (interClass.isAnnotationPresent(LocalTCC.class)) { - return true; - } - } - return beanClass.isAnnotationPresent(LocalTCC.class); - } - private void initClient() { if (LOGGER.isInfoEnabled()) { LOGGER.info("Initializing Global Transaction Clients ... "); @@ -256,6 +246,86 @@ private void registerSpringShutdownHook() { ShutdownHook.getInstance().addDisposable(RmNettyRemotingClient.getInstance(applicationId, txServiceGroup)); } + /** + * The following will be scanned, and added corresponding interceptor: + * + * TM: + * @see io.seata.spring.annotation.GlobalTransactional // TM annotation + * Corresponding interceptor: + * @see io.seata.spring.annotation.GlobalTransactionalInterceptor#handleGlobalTransaction(MethodInvocation, AspectTransactional) // TM handler + * + * GlobalLock: + * @see io.seata.spring.annotation.GlobalLock // GlobalLock annotation + * Corresponding interceptor: + * @see io.seata.spring.annotation.GlobalTransactionalInterceptor#handleGlobalLock(MethodInvocation, GlobalLock) // GlobalLock handler + * + * TCC mode: + * @see io.seata.rm.tcc.api.LocalTCC // TCC annotation on interface + * @see io.seata.rm.tcc.api.TwoPhaseBusinessAction // TCC annotation on try method + * @see io.seata.rm.tcc.remoting.RemotingParser // Remote TCC service parser + * Corresponding interceptor: + * @see io.seata.spring.tcc.TccActionInterceptor // the interceptor of TCC mode + */ + @Override + protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { + // do checkers + if (!doCheckers(bean, beanName)) { + return bean; + } + + try { + synchronized (PROXYED_SET) { + if (PROXYED_SET.contains(beanName)) { + return bean; + } + interceptor = null; + //check TCC proxy + if (TCCBeanParserUtils.isTccAutoProxy(bean, beanName, applicationContext)) { + // init tcc fence clean task if enable useTccFence + TCCBeanParserUtils.initTccFenceCleanTask(TCCBeanParserUtils.getRemotingDesc(beanName), applicationContext); + //TCC interceptor, proxy bean of sofa:reference/dubbo:reference, and LocalTCC + interceptor = new TccActionInterceptor(TCCBeanParserUtils.getRemotingDesc(beanName)); + ConfigurationCache.addConfigListener(ConfigurationKeys.DISABLE_GLOBAL_TRANSACTION, + (ConfigurationChangeListener)interceptor); + } else { + Class serviceInterface = SpringProxyUtils.findTargetClass(bean); + Class[] interfacesIfJdk = SpringProxyUtils.findInterfaces(bean); + + if (!existsAnnotation(serviceInterface) + && !existsAnnotation(interfacesIfJdk)) { + return bean; + } + + if (globalTransactionalInterceptor == null) { + globalTransactionalInterceptor = new GlobalTransactionalInterceptor(failureHandlerHook); + ConfigurationCache.addConfigListener( + ConfigurationKeys.DISABLE_GLOBAL_TRANSACTION, + (ConfigurationChangeListener)globalTransactionalInterceptor); + } + interceptor = globalTransactionalInterceptor; + } + + LOGGER.info("Bean [{}] with name [{}] would use interceptor [{}]", bean.getClass().getName(), beanName, interceptor.getClass().getName()); + if (!AopUtils.isAopProxy(bean)) { + bean = super.wrapIfNecessary(bean, beanName, cacheKey); + } else { + AdvisedSupport advised = SpringProxyUtils.getAdvisedSupport(bean); + Advisor[] advisor = buildAdvisors(beanName, getAdvicesAndAdvisorsForBean(null, null, null)); + int pos; + for (Advisor avr : advisor) { + // Find the position based on the advisor's order, and add to advisors by pos + pos = findAddSeataAdvisorPosition(advised, avr); + advised.addAdvisor(pos, avr); + } + } + PROXYED_SET.add(beanName); + return bean; + } + } catch (Exception exx) { + throw new RuntimeException(exx); + } + } + private boolean doCheckers(Object bean, String beanName) { if (PROXYED_SET.contains(beanName) || EXCLUDE_BEAN_NAME_SET.contains(beanName) || FactoryBean.class.isAssignableFrom(bean.getClass())) { @@ -393,89 +463,6 @@ private boolean isTransactionInterceptor(Advisor advisor) { //endregion the methods about findAddSeataAdvisorPosition END - /** - * The following will be scanned, and added corresponding interceptor: - * - * TM: - * @see io.seata.spring.annotation.GlobalTransactional // TM annotation - * Corresponding interceptor: - * @see io.seata.spring.annotation.GlobalTransactionalInterceptor#handleGlobalTransaction(MethodInvocation, AspectTransactional) // TM handler - * - * GlobalLock: - * @see io.seata.spring.annotation.GlobalLock // GlobalLock annotation - * Corresponding interceptor: - * @see io.seata.spring.annotation.GlobalTransactionalInterceptor#handleGlobalLock(MethodInvocation, GlobalLock) // GlobalLock handler - * - * TCC mode: - * @see io.seata.rm.tcc.api.LocalTCC // TCC annotation on interface - * @see io.seata.rm.tcc.api.TwoPhaseBusinessAction // TCC annotation on try method - * @see io.seata.rm.tcc.remoting.RemotingParser // Remote TCC service parser - * Corresponding interceptor: - * @see io.seata.spring.tcc.TccActionInterceptor // the interceptor of TCC mode - */ - @Override - protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { - // do checkers - if (!doCheckers(bean, beanName)) { - return bean; - } - - try { - synchronized (PROXYED_SET) { - if (PROXYED_SET.contains(beanName)) { - return bean; - } - interceptor = null; - //check TCC proxy - if (TCCBeanParserUtils.isTccAutoProxy(bean, beanName, applicationContext)) { - // init tcc fence clean task if enable useTccFence - TCCBeanParserUtils.initTccFenceCleanTask(TCCBeanParserUtils.getRemotingDesc(beanName), applicationContext); - //TCC interceptor, proxy bean of sofa:reference/dubbo:reference, and LocalTCC - interceptor = new TccActionInterceptor(TCCBeanParserUtils.getRemotingDesc(beanName)); - ConfigurationCache.addConfigListener(ConfigurationKeys.DISABLE_GLOBAL_TRANSACTION, - (ConfigurationChangeListener)interceptor); - } else { - Class serviceInterface = SpringProxyUtils.findTargetClass(bean); - Class[] interfacesIfJdk = SpringProxyUtils.findInterfaces(bean); - - if (!existsAnnotation(serviceInterface) - && !existsAnnotation(interfacesIfJdk)) { - return bean; - } - - if (globalTransactionalInterceptor == null) { - globalTransactionalInterceptor = new GlobalTransactionalInterceptor(failureHandlerHook); - ConfigurationCache.addConfigListener( - ConfigurationKeys.DISABLE_GLOBAL_TRANSACTION, - (ConfigurationChangeListener)globalTransactionalInterceptor); - } - interceptor = globalTransactionalInterceptor; - } - - LOGGER.info("Bean [{}] with name [{}] would use interceptor [{}]", bean.getClass().getName(), beanName, interceptor.getClass().getName()); - if (!AopUtils.isAopProxy(bean)) { - bean = super.wrapIfNecessary(bean, beanName, cacheKey); - } else { - AdvisedSupport advised = SpringProxyUtils.getAdvisedSupport(bean); - Advisor[] advisor = buildAdvisors(beanName, getAdvicesAndAdvisorsForBean(null, null, null)); - int pos; - for (Advisor avr : advisor) { - // Find the position based on the advisor's order, and add to advisors by pos - pos = findAddSeataAdvisorPosition(advised, avr); - advised.addAdvisor(pos, avr); - } - } - PROXYED_SET.add(beanName); - return bean; - } - } catch (Exception exx) { - throw new RuntimeException(exx); - } - } - - private MethodDesc makeMethodDesc(GlobalTransactional anno, Method method) { - return new MethodDesc(anno, method); - } private boolean existsAnnotation(Class... classes) { if (CollectionUtils.isNotEmpty(classes)) { @@ -504,6 +491,20 @@ private boolean existsAnnotation(Class... classes) { return false; } + private MethodDesc makeMethodDesc(GlobalTransactional anno, Method method) { + return new MethodDesc(anno, method); + } + + public static boolean isTccAutoProxy(Class beanClass) { + Set> interfaceClasses = ReflectionUtil.getInterfaces(beanClass); + for (Class interClass : interfaceClasses) { + if (interClass.isAnnotationPresent(LocalTCC.class)) { + return true; + } + } + return beanClass.isAnnotationPresent(LocalTCC.class); + } + @Override protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource customTargetSource) throws BeansException { diff --git a/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionalInterceptor.java b/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionalInterceptor.java index 592ed8851a0..088e7462866 100644 --- a/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionalInterceptor.java +++ b/spring/src/main/java/io/seata/spring/annotation/GlobalTransactionalInterceptor.java @@ -82,14 +82,14 @@ public class GlobalTransactionalInterceptor implements ConfigurationChangeListen private final FailureHandler failureHandler; private volatile boolean disable; private int order; - private static final AtomicBoolean ATOMIC_DEGRADE_CHECK = new AtomicBoolean(false); + protected AspectTransactional aspectTransactional; private static int degradeCheckPeriod; - private static volatile ScheduledThreadPoolExecutor executor; + private static final AtomicBoolean ATOMIC_DEGRADE_CHECK = new AtomicBoolean(false); private static int degradeCheckAllowTimes; private static volatile Integer degradeNum = 0; private static volatile Integer reachNum = 0; private static final EventBus EVENT_BUS = new GuavaEventBus("degradeCheckEventBus", true); - protected AspectTransactional aspectTransactional; + private static volatile ScheduledThreadPoolExecutor executor; //region DEFAULT_GLOBAL_TRANSACTION_TIMEOUT private static int defaultGlobalTransactionTimeout = 0; @@ -145,42 +145,6 @@ public GlobalTransactionalInterceptor(FailureHandler failureHandler) { this.initDefaultGlobalTransactionTimeout(); } - /** - * stop auto degrade - */ - private static void stopDegradeCheck() { - if (!ATOMIC_DEGRADE_CHECK.compareAndSet(true, false)) { - return; - } - if (executor != null && !executor.isShutdown()) { - executor.shutdown(); - } - } - - /** - * auto upgrade service detection - */ - private static void startDegradeCheck() { - if (!ATOMIC_DEGRADE_CHECK.compareAndSet(false, true)) { - return; - } - if (executor != null && !executor.isShutdown()) { - return; - } - executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("degradeCheckWorker", 1, true)); - executor.scheduleAtFixedRate(() -> { - if (ATOMIC_DEGRADE_CHECK.get()) { - try { - String xid = TransactionManagerHolder.get().begin(null, null, "degradeCheck", 60000); - TransactionManagerHolder.get().commit(xid); - EVENT_BUS.post(new DegradeCheckEvent(true)); - } catch (Exception e) { - EVENT_BUS.post(new DegradeCheckEvent(false)); - } - } - }, degradeCheckPeriod, degradeCheckPeriod, TimeUnit.MILLISECONDS); - } - @Override public Object invoke(final MethodInvocation methodInvocation) throws Throwable { Class targetClass = @@ -217,25 +181,6 @@ public Object invoke(final MethodInvocation methodInvocation) throws Throwable { return methodInvocation.proceed(); } - public T getAnnotation(Method method, Class targetClass, Class annotationClass) { - return Optional.ofNullable(method).map(m -> m.getAnnotation(annotationClass)) - .orElse(Optional.ofNullable(targetClass).map(t -> t.getAnnotation(annotationClass)).orElse(null)); - } - - private String formatMethod(Method method) { - StringBuilder sb = new StringBuilder(method.getName()).append("("); - - Class[] params = method.getParameterTypes(); - int in = 0; - for (Class clazz : params) { - sb.append(clazz.getName()); - if (++in < params.length) { - sb.append(", "); - } - } - return sb.append(")").toString(); - } - private Object handleGlobalLock(final MethodInvocation methodInvocation, final GlobalLock globalLockAnno) throws Throwable { return globalLockTemplate.execute(new GlobalLockExecutor() { @Override @@ -348,6 +293,25 @@ public TransactionInfo getTransactionInfo() { } } + public T getAnnotation(Method method, Class targetClass, Class annotationClass) { + return Optional.ofNullable(method).map(m -> m.getAnnotation(annotationClass)) + .orElse(Optional.ofNullable(targetClass).map(t -> t.getAnnotation(annotationClass)).orElse(null)); + } + + private String formatMethod(Method method) { + StringBuilder sb = new StringBuilder(method.getName()).append("("); + + Class[] params = method.getParameterTypes(); + int in = 0; + for (Class clazz : params) { + sb.append(clazz.getName()); + if (++in < params.length) { + sb.append(", "); + } + } + return sb.append(")").toString(); + } + @Override public void onChangeEvent(ConfigurationChangeEvent event) { if (ConfigurationKeys.DISABLE_GLOBAL_TRANSACTION.equals(event.getDataId())) { @@ -365,6 +329,42 @@ public void onChangeEvent(ConfigurationChangeEvent event) { } } + /** + * stop auto degrade + */ + private static void stopDegradeCheck() { + if (!ATOMIC_DEGRADE_CHECK.compareAndSet(true, false)) { + return; + } + if (executor != null && !executor.isShutdown()) { + executor.shutdown(); + } + } + + /** + * auto upgrade service detection + */ + private static void startDegradeCheck() { + if (!ATOMIC_DEGRADE_CHECK.compareAndSet(false, true)) { + return; + } + if (executor != null && !executor.isShutdown()) { + return; + } + executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("degradeCheckWorker", 1, true)); + executor.scheduleAtFixedRate(() -> { + if (ATOMIC_DEGRADE_CHECK.get()) { + try { + String xid = TransactionManagerHolder.get().begin(null, null, "degradeCheck", 60000); + TransactionManagerHolder.get().commit(xid); + EVENT_BUS.post(new DegradeCheckEvent(true)); + } catch (Exception e) { + EVENT_BUS.post(new DegradeCheckEvent(false)); + } + } + }, degradeCheckPeriod, degradeCheckPeriod, TimeUnit.MILLISECONDS); + } + private boolean isTimeoutException(Throwable th) { if (null == th) { return false; diff --git a/tcc/src/main/java/io/seata/rm/tcc/TCCFenceHandler.java b/tcc/src/main/java/io/seata/rm/tcc/TCCFenceHandler.java index 74c5e399460..40c3cf44e5d 100644 --- a/tcc/src/main/java/io/seata/rm/tcc/TCCFenceHandler.java +++ b/tcc/src/main/java/io/seata/rm/tcc/TCCFenceHandler.java @@ -49,7 +49,9 @@ */ public class TCCFenceHandler { - private static final int MAX_THREAD_CLEAN = 1; + private TCCFenceHandler() { + throw new IllegalStateException("Utility class"); + } private static final Logger LOGGER = LoggerFactory.getLogger(TCCFenceHandler.class); @@ -58,13 +60,20 @@ public class TCCFenceHandler { private static DataSource dataSource; private static TransactionTemplate transactionTemplate; + + private static final int MAX_THREAD_CLEAN = 1; + private static final int MAX_QUEUE_SIZE = 500; + /** * limit of delete record by date (per sql) */ private static final int LIMIT_DELETE = 1000; + private static final LinkedBlockingQueue LOG_QUEUE = new LinkedBlockingQueue<>(MAX_QUEUE_SIZE); + private static FenceLogCleanRunnable fenceLogCleanRunnable; + private static ExecutorService logCleanExecutor; static { @@ -75,10 +84,6 @@ public class TCCFenceHandler { } } - private TCCFenceHandler() { - throw new IllegalStateException("Utility class"); - } - public static DataSource getDataSource() { return TCCFenceHandler.dataSource; } @@ -384,14 +389,14 @@ public String getXid() { return xid; } - public void setXid(String xid) { - this.xid = xid; - } - public Long getBranchId() { return branchId; } + public void setXid(String xid) { + this.xid = xid; + } + public void setBranchId(Long branchId) { this.branchId = branchId; } diff --git a/tcc/src/main/java/io/seata/rm/tcc/config/TCCFenceConfig.java b/tcc/src/main/java/io/seata/rm/tcc/config/TCCFenceConfig.java index e118740cf30..15e570c039c 100644 --- a/tcc/src/main/java/io/seata/rm/tcc/config/TCCFenceConfig.java +++ b/tcc/src/main/java/io/seata/rm/tcc/config/TCCFenceConfig.java @@ -46,11 +46,13 @@ public class TCCFenceConfig implements InitializingBean, Disposable { private static final Logger LOGGER = LoggerFactory.getLogger(TCCFenceConfig.class); + private final AtomicBoolean initialized = new AtomicBoolean(false); + /** * TCC fence clean period max value. maximum interval is 68 years */ private static final Duration MAX_PERIOD = Duration.ofSeconds(Integer.MAX_VALUE); - private final AtomicBoolean initialized = new AtomicBoolean(false); + /** * TCC fence clean period. only duration type format are supported */ diff --git a/tcc/src/main/java/io/seata/rm/tcc/store/db/sql/TCCFenceStoreSqls.java b/tcc/src/main/java/io/seata/rm/tcc/store/db/sql/TCCFenceStoreSqls.java index e7466dfe34f..9ea6c28c0ca 100644 --- a/tcc/src/main/java/io/seata/rm/tcc/store/db/sql/TCCFenceStoreSqls.java +++ b/tcc/src/main/java/io/seata/rm/tcc/store/db/sql/TCCFenceStoreSqls.java @@ -24,30 +24,27 @@ */ public class TCCFenceStoreSqls { + private TCCFenceStoreSqls() { + throw new IllegalStateException("Utility class"); + } + + /** + * The constant LOCAL_TCC_LOG_PLACEHOLD. + */ + public static final String LOCAL_TCC_LOG_PLACEHOLD = " #local_tcc_log# "; + /** * The constant PRAMETER_PLACEHOLD. * format: ?, ?, ? */ public static final String PRAMETER_PLACEHOLD = " #PRAMETER_PLACEHOLD# "; - /** - * The constant LOCAL_TCC_LOG_PLACEHOLD. - */ - public static final String LOCAL_TCC_LOG_PLACEHOLD = " #local_tcc_log# "; /** * The constant INSERT_LOCAL_TCC_LOG. */ protected static final String INSERT_LOCAL_TCC_LOG = "insert into " + LOCAL_TCC_LOG_PLACEHOLD + " (xid, branch_id, action_name, status, gmt_create, gmt_modified) " + " values (?, ?, ?, ?, ?, ?) "; - /** - * The constant QUERY_END_STATUS_BY_DATE. - */ - protected static final String QUERY_END_STATUS_BY_DATE = "select xid, branch_id, status, gmt_create, gmt_modified " - + "from " + LOCAL_TCC_LOG_PLACEHOLD - + " where gmt_modified < ? " - + " and status in (" + TCCFenceConstant.STATUS_COMMITTED + " , " + TCCFenceConstant.STATUS_ROLLBACKED + " , " + TCCFenceConstant.STATUS_SUSPENDED + ")" - + " limit ?"; /** * The constant QUERY_BY_BRANCH_ID_AND_XID. @@ -55,10 +52,15 @@ public class TCCFenceStoreSqls { protected static final String QUERY_BY_BRANCH_ID_AND_XID = "select xid, branch_id, status, gmt_create, gmt_modified " + "from " + LOCAL_TCC_LOG_PLACEHOLD + " where xid = ? and branch_id = ? for update"; + /** - * The constant DELETE_BY_BRANCH_ID_AND_XID. + * The constant QUERY_END_STATUS_BY_DATE. */ - protected static final String DELETE_BY_BRANCH_XIDS = "delete from " + LOCAL_TCC_LOG_PLACEHOLD + " where xid in (" + PRAMETER_PLACEHOLD + ")"; + protected static final String QUERY_END_STATUS_BY_DATE = "select xid, branch_id, status, gmt_create, gmt_modified " + + "from " + LOCAL_TCC_LOG_PLACEHOLD + + " where gmt_modified < ? " + + " and status in (" + TCCFenceConstant.STATUS_COMMITTED + " , " + TCCFenceConstant.STATUS_ROLLBACKED + " , " + TCCFenceConstant.STATUS_SUSPENDED + ")" + + " limit ?"; /** * The constant UPDATE_STATUS_BY_BRANCH_ID_AND_XID. @@ -70,6 +72,13 @@ public class TCCFenceStoreSqls { * The constant DELETE_BY_BRANCH_ID_AND_XID. */ protected static final String DELETE_BY_BRANCH_ID_AND_XID = "delete from " + LOCAL_TCC_LOG_PLACEHOLD + " where xid = ? and branch_id = ? "; + + /** + * The constant DELETE_BY_BRANCH_ID_AND_XID. + */ + protected static final String DELETE_BY_BRANCH_XIDS = "delete from " + LOCAL_TCC_LOG_PLACEHOLD + " where xid in (" + PRAMETER_PLACEHOLD + ")"; + + /** * The constant DELETE_BY_DATE_AND_STATUS. */ @@ -77,11 +86,6 @@ public class TCCFenceStoreSqls { + " where gmt_modified < ? " + " and status in (" + TCCFenceConstant.STATUS_COMMITTED + " , " + TCCFenceConstant.STATUS_ROLLBACKED + " , " + TCCFenceConstant.STATUS_SUSPENDED + ")"; - - private TCCFenceStoreSqls() { - throw new IllegalStateException("Utility class"); - } - public static String getInsertLocalTCCLogSQL(String localTccTable) { return INSERT_LOCAL_TCC_LOG.replace(LOCAL_TCC_LOG_PLACEHOLD, localTccTable); } diff --git a/test/src/test/java/io/seata/at/ATModeSupportDataBaseDataTypeTest.java b/test/src/test/java/io/seata/at/ATModeSupportDataBaseDataTypeTest.java index 80cd1d5a4de..0effa63c06c 100644 --- a/test/src/test/java/io/seata/at/ATModeSupportDataBaseDataTypeTest.java +++ b/test/src/test/java/io/seata/at/ATModeSupportDataBaseDataTypeTest.java @@ -179,6 +179,39 @@ public void branchReport(BranchType branchType, String xid, long branchId, Branc } + private static class SqlClass { + + private String tableName = ""; + private String updateSql = ""; + private String insertSql = ""; + + public SqlClass() {} + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getUpdateSql() { + return updateSql; + } + + public void setUpdateSql(String updateSql) { + this.updateSql = updateSql; + } + + public String getInsertSql() { + return insertSql; + } + + public void setInsertSql(String insertSql) { + this.insertSql = insertSql; + } + } + private SqlClass dogetType(int sqlType, int type) { SqlClass sqlClass = new SqlClass(); switch (sqlType) { @@ -214,37 +247,4 @@ private SqlClass dogetType(int sqlType, int type) { } return sqlClass; } - - private static class SqlClass { - - private String tableName = ""; - private String updateSql = ""; - private String insertSql = ""; - - public SqlClass() {} - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public String getUpdateSql() { - return updateSql; - } - - public void setUpdateSql(String updateSql) { - this.updateSql = updateSql; - } - - public String getInsertSql() { - return insertSql; - } - - public void setInsertSql(String insertSql) { - this.insertSql = insertSql; - } - } } diff --git a/test/src/test/java/io/seata/at/DruidDataSourceUtils.java b/test/src/test/java/io/seata/at/DruidDataSourceUtils.java index b06801551ee..083b8401e02 100644 --- a/test/src/test/java/io/seata/at/DruidDataSourceUtils.java +++ b/test/src/test/java/io/seata/at/DruidDataSourceUtils.java @@ -28,8 +28,11 @@ */ public class DruidDataSourceUtils { + private static final Logger LOGGER = LoggerFactory.getLogger(DruidDataSourceUtils.class); + public static final int ORACLE = 1; public static final int POSTGRESQL = 2; + /** * oracle: test1: url:jdbc:oracle:thin:@localhost:49161:xe name:system password:oracle * @@ -39,6 +42,7 @@ public class DruidDataSourceUtils { public static final String ORACLE_USERNAME = "system"; public static final String ORACLE_PASSWORD = "oracle"; public static final String ORACLE_DRIVER_CLASSNAME = JdbcUtils.ORACLE_DRIVER; + /** * PostgreSQL: * @@ -47,7 +51,6 @@ public class DruidDataSourceUtils { public static final String POSTGRESQL_USERNAME = ""; public static final String POSTGRESQL_PASSWORD = ""; public static final String POSTGRESQL_DRIVER_CLASSNAME = JdbcUtils.POSTGRESQL_DRIVER; - private static final Logger LOGGER = LoggerFactory.getLogger(DruidDataSourceUtils.class); public static DruidDataSource createNewDruidDataSource(int type) throws Throwable { DruidDataSource druidDataSource = new DruidDataSource(); diff --git a/test/src/test/java/io/seata/at/mysql/MysqlUpdateJoinTest.java b/test/src/test/java/io/seata/at/mysql/MysqlUpdateJoinTest.java index 970d7f36138..20a697b1654 100644 --- a/test/src/test/java/io/seata/at/mysql/MysqlUpdateJoinTest.java +++ b/test/src/test/java/io/seata/at/mysql/MysqlUpdateJoinTest.java @@ -54,6 +54,14 @@ public class MysqlUpdateJoinTest { private static final String mysql_password = "demo"; private static final String mysql_driverClassName = JdbcUtils.MYSQL_DRIVER; + + @Test + @Disabled + public void testUpdateJoin() throws Throwable { + doTestPhase2(false, "update t inner join t1 on t.a = t1.a set b = 3,t.c=3"); + System.out.println("AT MODE Phase2 test for update join looks good!"); + } + private static void doPrepareData(String prepareSql) throws Throwable { // init DataSource: helper DruidDataSource helperDS = createNewDruidDataSource(); @@ -66,27 +74,6 @@ private static void doPrepareData(String prepareSql) throws Throwable { helperConn.close(); } - private static DruidDataSource createNewDruidDataSource() throws Throwable { - DruidDataSource druidDataSource = new DruidDataSource(); - initDruidDataSource(druidDataSource); - return druidDataSource; - } - - private static void initDruidDataSource(DruidDataSource druidDataSource) throws Throwable { - druidDataSource.setDbType(JdbcConstants.MYSQL); - druidDataSource.setUrl(mysql_jdbcUrl); - druidDataSource.setUsername(mysql_username); - druidDataSource.setPassword(mysql_password); - druidDataSource.setDriverClassName(mysql_driverClassName); - druidDataSource.init(); - } - - @Test - @Disabled - public void testUpdateJoin() throws Throwable { - doTestPhase2(false, "update t inner join t1 on t.a = t1.a set b = 3,t.c=3"); - System.out.println("AT MODE Phase2 test for update join looks good!"); - } private void doTestPhase2(boolean globalCommit, String updateSql) throws Throwable { // init DataSource: helper @@ -161,4 +148,19 @@ public void branchReport(BranchType branchType, String xid, long branchId, Branc }); } + + private static DruidDataSource createNewDruidDataSource() throws Throwable { + DruidDataSource druidDataSource = new DruidDataSource(); + initDruidDataSource(druidDataSource); + return druidDataSource; + } + + private static void initDruidDataSource(DruidDataSource druidDataSource) throws Throwable { + druidDataSource.setDbType(JdbcConstants.MYSQL); + druidDataSource.setUrl(mysql_jdbcUrl); + druidDataSource.setUsername(mysql_username); + druidDataSource.setPassword(mysql_password); + druidDataSource.setDriverClassName(mysql_driverClassName); + druidDataSource.init(); + } } \ No newline at end of file From e26f50de2d1c5fd2aa351752a23a537fc7bcb467 Mon Sep 17 00:00:00 2001 From: a364176773 <364176773@qq.com> Date: Tue, 15 Aug 2023 14:55:00 +0800 Subject: [PATCH 08/25] opt --- .../sql/struct/TableMetaCacheFactory.java | 18 ++- .../datasource/sql/struct/TableRecords.java | 142 +++++++++--------- .../undo/parser/KryoSerializerFactory.java | 3 +- .../rm/datasource/util/OffsetTimeUtils.java | 60 ++++---- .../rm/datasource/xa/ConnectionProxyXA.java | 11 +- 5 files changed, 124 insertions(+), 110 deletions(-) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableMetaCacheFactory.java b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableMetaCacheFactory.java index 9db7cd761f0..848ce378084 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableMetaCacheFactory.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableMetaCacheFactory.java @@ -53,17 +53,19 @@ public class TableMetaCacheFactory { private static final long TABLE_META_REFRESH_INTERVAL_TIME = 1000L; private static final int MAX_QUEUE_SIZE = 2000; - /** - * Table meta checker interval - */ - private static final long TABLE_META_CHECKER_INTERVAL = ConfigurationFactory.getInstance() - .getLong(ConfigurationKeys.CLIENT_TABLE_META_CHECKER_INTERVAL, DEFAULT_TABLE_META_CHECKER_INTERVAL); + /** * Enable the table meta checker */ private static boolean ENABLE_TABLE_META_CHECKER_ENABLE = ConfigurationFactory.getInstance() .getBoolean(ConfigurationKeys.CLIENT_TABLE_META_CHECK_ENABLE, DEFAULT_CLIENT_TABLE_META_CHECK_ENABLE); + /** + * Table meta checker interval + */ + private static final long TABLE_META_CHECKER_INTERVAL = ConfigurationFactory.getInstance() + .getLong(ConfigurationKeys.CLIENT_TABLE_META_CHECKER_INTERVAL, DEFAULT_TABLE_META_CHECKER_INTERVAL); + /** * get table meta cache @@ -98,12 +100,14 @@ public static void tableMetaRefreshEvent(String resourceId) { } static class TableMetaRefreshHolder { - private final Executor tableMetaRefreshExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(), new NamedThreadFactory("tableMetaRefresh", 1, true)); private long lastRefreshFinishTime; private DataSourceProxy dataSource; private BlockingQueue tableMetaRefreshQueue; + + private final Executor tableMetaRefreshExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), new NamedThreadFactory("tableMetaRefresh", 1, true)); + TableMetaRefreshHolder(DataSourceProxy dataSource) { this.dataSource = dataSource; this.lastRefreshFinishTime = System.currentTimeMillis() - TABLE_META_REFRESH_INTERVAL_TIME; diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableRecords.java b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableRecords.java index a5a954e029a..6dcada792e7 100755 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableRecords.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/TableRecords.java @@ -112,6 +112,77 @@ public TableRecords(TableMeta tableMeta) { setTableMeta(tableMeta); } + /** + * Sets table meta. + * + * @param tableMeta the table meta + */ + public void setTableMeta(TableMeta tableMeta) { + if (this.tableMeta != null) { + throw new ShouldNeverHappenException("tableMeta has already been set"); + } + this.tableMeta = tableMeta; + this.tableName = tableMeta.getTableName(); + } + + /** + * Size int. + * + * @return the int + */ + public int size() { + return rows.size(); + } + + /** + * Add. + * + * @param row the row + */ + public void add(Row row) { + rows.add(row); + } + + /** + * Pk rows list. + * + * @return return a list. each element of list is a map,the map hold the pk column name as a key and field as the value + */ + public List> pkRows() { + final Map primaryKeyMap = getTableMeta().getPrimaryKeyMap(); + List> pkRows = new ArrayList<>(); + for (Row row : rows) { + List fields = row.getFields(); + Map rowMap = new HashMap<>(3); + for (Field field : fields) { + if (primaryKeyMap.containsKey(field.getName())) { + rowMap.put(field.getName(),field); + } + } + pkRows.add(rowMap); + } + return pkRows; + } + + /** + * Gets table meta. + * + * @return the table meta + */ + public TableMeta getTableMeta() { + return tableMeta; + } + + /** + * Empty table records. + * + * @param tableMeta the table meta + * @return the table records + */ + public static TableRecords empty(TableMeta tableMeta) { + return new EmptyTableRecords(tableMeta); + } + /** * Build records table records. * @@ -193,64 +264,6 @@ public static TableRecords buildRecords(TableMeta tmeta, ResultSet resultSet) th return records; } - /** - * Size int. - * - * @return the int - */ - public int size() { - return rows.size(); - } - - /** - * Add. - * - * @param row the row - */ - public void add(Row row) { - rows.add(row); - } - - /** - * Pk rows list. - * - * @return return a list. each element of list is a map,the map hold the pk column name as a key and field as the value - */ - public List> pkRows() { - final Map primaryKeyMap = getTableMeta().getPrimaryKeyMap(); - List> pkRows = new ArrayList<>(); - for (Row row : rows) { - List fields = row.getFields(); - Map rowMap = new HashMap<>(3); - for (Field field : fields) { - if (primaryKeyMap.containsKey(field.getName())) { - rowMap.put(field.getName(),field); - } - } - pkRows.add(rowMap); - } - return pkRows; - } - - /** - * Gets table meta. - * - * @return the table meta - */ - public TableMeta getTableMeta() { - return tableMeta; - } - - /** - * Empty table records. - * - * @param tableMeta the table meta - * @return the table records - */ - public static TableRecords empty(TableMeta tableMeta) { - return new EmptyTableRecords(tableMeta); - } - /** * check if the column is null and return * @@ -295,19 +308,6 @@ public static Object holdSerialDataType(Object data) throws SQLException { return data; } - /** - * Sets table meta. - * - * @param tableMeta the table meta - */ - public void setTableMeta(TableMeta tableMeta) { - if (this.tableMeta != null) { - throw new ShouldNeverHappenException("tableMeta has already been set"); - } - this.tableMeta = tableMeta; - this.tableName = tableMeta.getTableName(); - } - public static class EmptyTableRecords extends TableRecords { public EmptyTableRecords() {} diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/parser/KryoSerializerFactory.java b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/parser/KryoSerializerFactory.java index 744fa43d81b..7d034fdbed4 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/undo/parser/KryoSerializerFactory.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/undo/parser/KryoSerializerFactory.java @@ -42,7 +42,6 @@ public class KryoSerializerFactory { private static final KryoSerializerFactory FACTORY = new KryoSerializerFactory(); - private static final Map TYPE_MAP = new ConcurrentHashMap<>(); private Pool pool = new Pool(true, true) { @Override @@ -75,6 +74,8 @@ public Kryo create() { }; + private static final Map TYPE_MAP = new ConcurrentHashMap<>(); + private KryoSerializerFactory() {} public static KryoSerializerFactory getInstance() { diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/util/OffsetTimeUtils.java b/rm-datasource/src/main/java/io/seata/rm/datasource/util/OffsetTimeUtils.java index 726760622f6..535d347a0c8 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/util/OffsetTimeUtils.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/util/OffsetTimeUtils.java @@ -42,36 +42,6 @@ public class OffsetTimeUtils { private static final Map ZONE_ID_MAP = new HashMap<>(36); - static { - ZONE_ID_MAP.put(250, "Asia/Shanghai"); - ZONE_ID_MAP.put(345, "Australia/Darwin"); - ZONE_ID_MAP.put(352, "Australia/Sydney"); - ZONE_ID_MAP.put(687, "America/Argentina/Buenos_Aires"); - ZONE_ID_MAP.put(106, "America/Anchorage"); - ZONE_ID_MAP.put(188, "America/Sao_Paulo"); - ZONE_ID_MAP.put(756, "Asia/Dhaka"); - ZONE_ID_MAP.put(80, "Africa/Harare"); - ZONE_ID_MAP.put(118, "America/St_Johns"); - ZONE_ID_MAP.put(101, "America/Chicago"); - ZONE_ID_MAP.put(47, "Africa/Addis_Ababa"); - ZONE_ID_MAP.put(382, "Europe/Paris"); - ZONE_ID_MAP.put(1647, "America/Indiana/Indianapolis"); - ZONE_ID_MAP.put(772, "Asia/Kolkata"); - ZONE_ID_MAP.put(267, "Asia/Tokyo"); - ZONE_ID_MAP.put(479, "Pacific/Apia"); - ZONE_ID_MAP.put(241, "Asia/Yerevan"); - ZONE_ID_MAP.put(471, "Pacific/Auckland"); - ZONE_ID_MAP.put(284, "Asia/Karachi"); - ZONE_ID_MAP.put(109, "America/Phoenix"); - ZONE_ID_MAP.put(167, "America/Puerto_Rico"); - ZONE_ID_MAP.put(103, "America/Los_Angeles"); - ZONE_ID_MAP.put(481, "Pacific/Guadalcanal"); - ZONE_ID_MAP.put(813, "Asia/Ho_Chi_Minh"); - ZONE_ID_MAP.put(1474, "HST"); - ZONE_ID_MAP.put(1636, "EST"); - ZONE_ID_MAP.put(2662, "MST"); - } - public static String getRegion(int code) { return ZONE_ID_MAP.get(code); } @@ -141,4 +111,34 @@ private static LocalDateTime extractLocalDateTime(byte[] bytes) { } return LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond); } + + static { + ZONE_ID_MAP.put(250, "Asia/Shanghai"); + ZONE_ID_MAP.put(345, "Australia/Darwin"); + ZONE_ID_MAP.put(352, "Australia/Sydney"); + ZONE_ID_MAP.put(687, "America/Argentina/Buenos_Aires"); + ZONE_ID_MAP.put(106, "America/Anchorage"); + ZONE_ID_MAP.put(188, "America/Sao_Paulo"); + ZONE_ID_MAP.put(756, "Asia/Dhaka"); + ZONE_ID_MAP.put(80, "Africa/Harare"); + ZONE_ID_MAP.put(118, "America/St_Johns"); + ZONE_ID_MAP.put(101, "America/Chicago"); + ZONE_ID_MAP.put(47, "Africa/Addis_Ababa"); + ZONE_ID_MAP.put(382, "Europe/Paris"); + ZONE_ID_MAP.put(1647, "America/Indiana/Indianapolis"); + ZONE_ID_MAP.put(772, "Asia/Kolkata"); + ZONE_ID_MAP.put(267, "Asia/Tokyo"); + ZONE_ID_MAP.put(479, "Pacific/Apia"); + ZONE_ID_MAP.put(241, "Asia/Yerevan"); + ZONE_ID_MAP.put(471, "Pacific/Auckland"); + ZONE_ID_MAP.put(284, "Asia/Karachi"); + ZONE_ID_MAP.put(109, "America/Phoenix"); + ZONE_ID_MAP.put(167, "America/Puerto_Rico"); + ZONE_ID_MAP.put(103, "America/Los_Angeles"); + ZONE_ID_MAP.put(481, "Pacific/Guadalcanal"); + ZONE_ID_MAP.put(813, "Asia/Ho_Chi_Minh"); + ZONE_ID_MAP.put(1474, "HST"); + ZONE_ID_MAP.put(1636, "EST"); + ZONE_ID_MAP.put(2662, "MST"); + } } diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/xa/ConnectionProxyXA.java b/rm-datasource/src/main/java/io/seata/rm/datasource/xa/ConnectionProxyXA.java index d8da508939b..c229f782a36 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/xa/ConnectionProxyXA.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/xa/ConnectionProxyXA.java @@ -48,14 +48,23 @@ public class ConnectionProxyXA extends AbstractConnectionProxyXA implements Hold private static final int BRANCH_EXECUTION_TIMEOUT = ConfigurationFactory.getInstance().getInt(XA_BRANCH_EXECUTION_TIMEOUT, DefaultValues.DEFAULT_XA_BRANCH_EXECUTION_TIMEOUT); - private static final Integer TIMEOUT = Math.max(BRANCH_EXECUTION_TIMEOUT, DefaultValues.DEFAULT_GLOBAL_TRANSACTION_TIMEOUT); + private volatile boolean currentAutoCommitStatus = true; + private volatile XAXid xaBranchXid; + private volatile boolean xaActive = false; + private volatile boolean kept = false; + private volatile boolean rollBacked = false; + private volatile Long branchRegisterTime = null; + private volatile Long prepareTime = null; + + private static final Integer TIMEOUT = Math.max(BRANCH_EXECUTION_TIMEOUT, DefaultValues.DEFAULT_GLOBAL_TRANSACTION_TIMEOUT); + private boolean shouldBeHeld = false; /** From a610ba19abb7c9deae6a23eb73ea3e4815f45239 Mon Sep 17 00:00:00 2001 From: a364176773 <364176773@qq.com> Date: Tue, 15 Aug 2023 15:00:12 +0800 Subject: [PATCH 09/25] opt --- .../java/io/seata/rm/BaseDataSourceResource.java | 6 ++++-- .../datasource/exec/MySQLInsertExecutorTest.java | 7 ++++++- script/client/at/db/dm.sql | 2 +- .../java/io/seata/sqlparser/struct/TableMeta.java | 4 +++- .../sqlparser/druid/SupportSqlWhereMethod.java | 14 +++++++------- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/rm-datasource/src/main/java/io/seata/rm/BaseDataSourceResource.java b/rm-datasource/src/main/java/io/seata/rm/BaseDataSourceResource.java index 9a1cabb4793..91041c5c90e 100644 --- a/rm-datasource/src/main/java/io/seata/rm/BaseDataSourceResource.java +++ b/rm-datasource/src/main/java/io/seata/rm/BaseDataSourceResource.java @@ -54,11 +54,13 @@ public abstract class BaseDataSourceResource implements Seat protected Driver driver; - private static final Cache BRANCH_STATUS_CACHE = - CacheBuilder.newBuilder().maximumSize(1024).expireAfterAccess(10, TimeUnit.MINUTES).build(); private boolean shouldBeHeld = false; + private Map keeper = new ConcurrentHashMap<>(); + private static final Cache BRANCH_STATUS_CACHE = + CacheBuilder.newBuilder().maximumSize(1024).expireAfterAccess(10, TimeUnit.MINUTES).build(); + /** * Gets target data source. * diff --git a/rm-datasource/src/test/java/io/seata/rm/datasource/exec/MySQLInsertExecutorTest.java b/rm-datasource/src/test/java/io/seata/rm/datasource/exec/MySQLInsertExecutorTest.java index f61f20004cc..b7ba7ccfdb7 100644 --- a/rm-datasource/src/test/java/io/seata/rm/datasource/exec/MySQLInsertExecutorTest.java +++ b/rm-datasource/src/test/java/io/seata/rm/datasource/exec/MySQLInsertExecutorTest.java @@ -66,11 +66,16 @@ public class MySQLInsertExecutorTest { private static final String USER_NAME_COLUMN = "user_name"; private static final String USER_STATUS_COLUMN = "user_status"; private static final Integer PK_VALUE = 100; - protected final int pkIndex = 0; + protected StatementProxy statementProxy; + protected SQLInsertRecognizer sqlInsertRecognizer; + protected TableMeta tableMeta; + protected MySQLInsertExecutor insertExecutor; + + protected final int pkIndex = 0; protected HashMap pkIndexMap; @BeforeEach diff --git a/script/client/at/db/dm.sql b/script/client/at/db/dm.sql index d6f4512705e..4900d39ae4b 100644 --- a/script/client/at/db/dm.sql +++ b/script/client/at/db/dm.sql @@ -2,7 +2,7 @@ CREATE TABLE "UNDO_LOG" ( "ID" BIGINT IDENTITY(1, 1) NOT NULL, "BRANCH_ID" BIGINT NOT NULL, -"XID" VARCHAR(100) NOT NULL, +"XID" VARCHAR(128) NOT NULL, "CONTEXT" VARCHAR(128) NOT NULL, "ROLLBACK_INFO" BLOB NOT NULL, "LOG_STATUS" INT NOT NULL, diff --git a/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/struct/TableMeta.java b/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/struct/TableMeta.java index 128a3738877..67a6b5f04be 100644 --- a/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/struct/TableMeta.java +++ b/sqlparser/seata-sqlparser-core/src/main/java/io/seata/sqlparser/struct/TableMeta.java @@ -39,15 +39,17 @@ public class TableMeta { private String tableName; + private boolean isCaseSensitive; + /** * key: column name */ private final Map allColumns = new LowerCaseLinkHashMap<>(); + /** * key: index name */ private final Map allIndexes = new LowerCaseLinkHashMap<>(); - private boolean isCaseSensitive; /** * Gets table name. diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/SupportSqlWhereMethod.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/SupportSqlWhereMethod.java index 30582bf6ffa..5f6a2d4a262 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/SupportSqlWhereMethod.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/SupportSqlWhereMethod.java @@ -23,12 +23,16 @@ */ public class SupportSqlWhereMethod { - private final Set supportMethodNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); - public SupportSqlWhereMethod() { add("FIND_IN_SET"); } + private final Set supportMethodNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + + private static class SupportSqlWhereMethodHolder { + private static final SupportSqlWhereMethod INSTANCE = new SupportSqlWhereMethod(); + } + public static SupportSqlWhereMethod getInstance() { return SupportSqlWhereMethodHolder.INSTANCE; } @@ -38,15 +42,11 @@ public void add(String methodName) { } /** - * + * * @param methodName * @return boolean */ public boolean checkIsSupport(String methodName) { return supportMethodNames.contains(methodName); } - - private static class SupportSqlWhereMethodHolder { - private static final SupportSqlWhereMethod INSTANCE = new SupportSqlWhereMethod(); - } } From 7551e34216e3a46cbaa7c5160bd34ad84bab9601 Mon Sep 17 00:00:00 2001 From: a364176773 <364176773@qq.com> Date: Tue, 15 Aug 2023 18:02:15 +0800 Subject: [PATCH 10/25] bugfix --- .../seata/sqlparser/druid/dm/DmUpdateRecognizer.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java index 88be7cca0ad..a8a9653ae84 100644 --- a/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java +++ b/sqlparser/seata-sqlparser-druid/src/main/java/io/seata/sqlparser/druid/dm/DmUpdateRecognizer.java @@ -32,6 +32,7 @@ import io.seata.sqlparser.SQLParsingException; import io.seata.sqlparser.SQLType; import io.seata.sqlparser.SQLUpdateRecognizer; +import io.seata.sqlparser.util.ColumnUtils; import java.util.ArrayList; import java.util.List; @@ -102,10 +103,6 @@ public List getUpdateValues() { return list; } - @Override public List getUpdateColumnsUnEscape() { - return null; - } - @Override public String getWhereCondition(final ParametersHolder parametersHolder, final ArrayList> paramAppenderList) { @@ -171,6 +168,12 @@ public String getOrderByCondition(ParametersHolder parametersHolder, ArrayList getUpdateColumnsUnEscape() { + List updateColumns = getUpdateColumns(); + return ColumnUtils.delEscape(updateColumns, getDbType()); + } + @Override protected SQLStatement getAst() { return this.ast; From b1deebe1b74f3b07203e10e86bed75fc98da4882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E8=89=AF?= <841369634@qq.com> Date: Tue, 15 Aug 2023 18:03:00 +0800 Subject: [PATCH 11/25] get metadata by schema, not username. --- .../rm/datasource/sql/struct/cache/DmTableMetaCache.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java index 46e5be21fa8..46701bbe0b6 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/sql/struct/cache/DmTableMetaCache.java @@ -69,7 +69,7 @@ protected TableMeta resultSetMetaToSchema(DatabaseMetaData dbmd, String tableNam TableMeta result = new TableMeta(); result.setTableName(tableName); - TableNameMeta tableNameMeta = toTableNameMeta(tableName, dbmd.getUserName()); + TableNameMeta tableNameMeta = toTableNameMeta(tableName, dbmd.getConnection().getSchema()); try (ResultSet rsColumns = dbmd.getColumns("", tableNameMeta.getSchema(), tableNameMeta.getTableName(), "%"); ResultSet rsIndex = dbmd.getIndexInfo(null, tableNameMeta.getSchema(), tableNameMeta.getTableName(), false, true); ResultSet rsPrimary = dbmd.getPrimaryKeys(null, tableNameMeta.getSchema(), tableNameMeta.getTableName())) { @@ -87,10 +87,10 @@ protected TableMeta resultSetMetaToSchema(DatabaseMetaData dbmd, String tableNam return result; } - protected TableNameMeta toTableNameMeta(String tableName, String username) { + protected TableNameMeta toTableNameMeta(String tableName, String schemaFromConnection) { String[] schemaTable = tableName.split("\\."); - String schema = schemaTable.length > 1 ? schemaTable[0] : username; + String schema = schemaTable.length > 1 ? schemaTable[0] : schemaFromConnection; if (schema != null) { schema = schema.contains("\"") ? schema.replace("\"", "") : schema.toUpperCase(); } From 74e54612ea8e6b0c0e27b4d91cea4f4525963d69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E8=89=AF?= <841369634@qq.com> Date: Tue, 15 Aug 2023 18:03:10 +0800 Subject: [PATCH 12/25] add initDmResourceId() --- .../seata/rm/datasource/DataSourceProxy.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java b/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java index 4e87b9eac0f..63956ea4ae4 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java @@ -161,6 +161,8 @@ private void initResourceId() { initOracleResourceId(); } else if (JdbcConstants.MYSQL.equals(dbType)) { initMysqlResourceId(); + } else if (JdbcConstants.DM.equals(dbType)) { + initDMResourceId(); } else { initDefaultResourceId(); } @@ -246,6 +248,35 @@ private void initPGResourceId() { } } + private void initDMResourceId() { + if (jdbcUrl.contains("?")) { + StringBuilder jdbcUrlBuilder = new StringBuilder(); + jdbcUrlBuilder.append(jdbcUrl, 0, jdbcUrl.indexOf('?')); + + StringBuilder paramsBuilder = new StringBuilder(); + String paramUrl = jdbcUrl.substring(jdbcUrl.indexOf('?') + 1); + String[] urlParams = paramUrl.split("&"); + for (String urlParam : urlParams) { + if (urlParam.contains("schema")) { + // remove the '"' + if (urlParam.contains("\"")) { + urlParam = urlParam.replaceAll("\"", ""); + } + paramsBuilder.append(urlParam); + break; + } + } + + if (paramsBuilder.length() > 0) { + jdbcUrlBuilder.append("?"); + jdbcUrlBuilder.append(paramsBuilder.toString()); + } + resourceId = jdbcUrlBuilder.toString(); + } else { + resourceId = jdbcUrl; + } + } + @Override public BranchType getBranchType() { return BranchType.AT; From 5c8ed36aef494c06759f82ea4fb67912f7bd4057 Mon Sep 17 00:00:00 2001 From: a364176773 <364176773@qq.com> Date: Thu, 17 Aug 2023 16:40:58 +0800 Subject: [PATCH 13/25] bugfix --- .../src/main/java/io/seata/rm/datasource/DataSourceProxy.java | 1 + 1 file changed, 1 insertion(+) diff --git a/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java b/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java index 63956ea4ae4..55e6bd9d7da 100644 --- a/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java +++ b/rm-datasource/src/main/java/io/seata/rm/datasource/DataSourceProxy.java @@ -249,6 +249,7 @@ private void initPGResourceId() { } private void initDMResourceId() { + LOGGER.warn("support for the dameng database is currently an experimental feature "); if (jdbcUrl.contains("?")) { StringBuilder jdbcUrlBuilder = new StringBuilder(); jdbcUrlBuilder.append(jdbcUrl, 0, jdbcUrl.indexOf('?')); From c1ba6c2666f30b582acf58f194e5b1cac8147ae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E8=89=AF?= <841369634@qq.com> Date: Mon, 21 Aug 2023 15:07:34 +0800 Subject: [PATCH 14/25] server support DaMeng database. --- .../java/io/seata/core/constants/DBType.java | 11 ++- .../store/db/sql/lock/DaMengLockStoreSql.java | 28 ++++++++ .../store/db/sql/log/DaMengLogStoreSqls.java | 27 +++++++ ....seata.core.store.db.sql.lock.LockStoreSql | 3 +- ...o.seata.core.store.db.sql.log.LogStoreSqls | 3 +- dependencies/pom.xml | 6 ++ script/server/db/dm.sql | 70 +++++++++++++++++++ server/pom.xml | 4 ++ 8 files changed, 149 insertions(+), 3 deletions(-) create mode 100644 core/src/main/java/io/seata/core/store/db/sql/lock/DaMengLockStoreSql.java create mode 100644 core/src/main/java/io/seata/core/store/db/sql/log/DaMengLogStoreSqls.java create mode 100644 script/server/db/dm.sql diff --git a/core/src/main/java/io/seata/core/constants/DBType.java b/core/src/main/java/io/seata/core/constants/DBType.java index d310cfde909..8774d71123c 100644 --- a/core/src/main/java/io/seata/core/constants/DBType.java +++ b/core/src/main/java/io/seata/core/constants/DBType.java @@ -77,7 +77,16 @@ public enum DBType { /** * Maria db type. */ - MARIADB; + MARIADB, + + /** + * DaMeng db type. + * + * @since 1.7.1 + */ + DM, + + ; /** * Valueof db type. diff --git a/core/src/main/java/io/seata/core/store/db/sql/lock/DaMengLockStoreSql.java b/core/src/main/java/io/seata/core/store/db/sql/lock/DaMengLockStoreSql.java new file mode 100644 index 00000000000..9ce8c66baca --- /dev/null +++ b/core/src/main/java/io/seata/core/store/db/sql/lock/DaMengLockStoreSql.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.core.store.db.sql.lock; + +import io.seata.common.loader.LoadLevel; + +/** + * the database lock store DaMeng sql + * + * @author wang.liang + * @since 1.7.1 + */ +@LoadLevel(name = "dm") +public class DaMengLockStoreSql extends MysqlLockStoreSql { +} diff --git a/core/src/main/java/io/seata/core/store/db/sql/log/DaMengLogStoreSqls.java b/core/src/main/java/io/seata/core/store/db/sql/log/DaMengLogStoreSqls.java new file mode 100644 index 00000000000..bc81cc163cf --- /dev/null +++ b/core/src/main/java/io/seata/core/store/db/sql/log/DaMengLogStoreSqls.java @@ -0,0 +1,27 @@ +/* + * Copyright 1999-2019 Seata.io Group. + * + * Licensed 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 io.seata.core.store.db.sql.log; + +import io.seata.common.loader.LoadLevel; + +/** + * Database log store DaMeng sql + * + * @author 1.7.1 + */ +@LoadLevel(name = "dm") +public class DaMengLogStoreSqls extends MysqlLogStoreSqls { +} diff --git a/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.lock.LockStoreSql b/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.lock.LockStoreSql index a8b5cbcf420..a59a5943a0a 100644 --- a/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.lock.LockStoreSql +++ b/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.lock.LockStoreSql @@ -2,4 +2,5 @@ io.seata.core.store.db.sql.lock.MysqlLockStoreSql io.seata.core.store.db.sql.lock.OracleLockStoreSql io.seata.core.store.db.sql.lock.OceanbaseLockStoreSql io.seata.core.store.db.sql.lock.PostgresqlLockStoreSql -io.seata.core.store.db.sql.lock.H2LockStoreSql \ No newline at end of file +io.seata.core.store.db.sql.lock.H2LockStoreSql +io.seata.core.store.db.sql.lock.DaMengLockStoreSql \ No newline at end of file diff --git a/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.log.LogStoreSqls b/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.log.LogStoreSqls index 42181e109f9..462238e51cc 100644 --- a/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.log.LogStoreSqls +++ b/core/src/main/resources/META-INF/services/io.seata.core.store.db.sql.log.LogStoreSqls @@ -2,4 +2,5 @@ io.seata.core.store.db.sql.log.MysqlLogStoreSqls io.seata.core.store.db.sql.log.OracleLogStoreSqls io.seata.core.store.db.sql.log.PostgresqlLogStoreSqls io.seata.core.store.db.sql.log.OceanbaseLogStoreSqls -io.seata.core.store.db.sql.log.H2LogStoreSqls \ No newline at end of file +io.seata.core.store.db.sql.log.H2LogStoreSqls +io.seata.core.store.db.sql.log.DaMengLogStoreSqls \ No newline at end of file diff --git a/dependencies/pom.xml b/dependencies/pom.xml index 1a2c27bc67b..f42b6b5b519 100644 --- a/dependencies/pom.xml +++ b/dependencies/pom.xml @@ -98,6 +98,7 @@ 42.3.3 1.4.181 2.7.2 + 8.1.2.192 1.2.6 2.9.0 @@ -215,6 +216,11 @@ mariadb-java-client ${mariadb.version} + + com.dameng + DmJdbcDriver18 + ${dm.version} + com.alipay.sofa sofa-rpc-all diff --git a/script/server/db/dm.sql b/script/server/db/dm.sql new file mode 100644 index 00000000000..603dee24a4e --- /dev/null +++ b/script/server/db/dm.sql @@ -0,0 +1,70 @@ +-- -------------------------------- The script used when storeMode is 'db' -------------------------------- +-- the table to store GlobalSession data +CREATE TABLE "SEATA"."GLOBAL_TABLE" +( + "XID" VARCHAR2(128) NOT NULL, + "TRANSACTION_ID" BIGINT, + "STATUS" TINYINT NOT NULL, + "APPLICATION_ID" VARCHAR2(32), + "TRANSACTION_SERVICE_GROUP" VARCHAR2(32), + "TRANSACTION_NAME" VARCHAR2(128), + "TIMEOUT" INT, + "BEGIN_TIME" BIGINT, + "APPLICATION_DATA" VARCHAR2(2000), + "GMT_CREATE" TIMESTAMP(0), + "GMT_MODIFIED" TIMESTAMP(0), + PRIMARY KEY ("XID") +); + +CREATE INDEX "IDX_GMT_MODIFIED_STATUS" ON "SEATA"."GLOBAL_TABLE"("GMT_MODIFIED" ASC,"STATUS" ASC); +CREATE INDEX "IDX_TRANSACTION_ID" ON "SEATA"."GLOBAL_TABLE"("TRANSACTION_ID" ASC); + +-- the table to store BranchSession data +CREATE TABLE "SEATA"."BRANCH_TABLE" +( + "BRANCH_ID" BIGINT NOT NULL, + "XID" VARCHAR2(128) NOT NULL, + "TRANSACTION_ID" BIGINT, + "RESOURCE_GROUP_ID" VARCHAR2(32), + "RESOURCE_ID" VARCHAR2(256), + "BRANCH_TYPE" VARCHAR2(8), + "STATUS" TINYINT, + "CLIENT_ID" VARCHAR2(64), + "APPLICATION_DATA" VARCHAR2(2000), + "GMT_CREATE" TIMESTAMP(0), + "GMT_MODIFIED" TIMESTAMP(0), + PRIMARY KEY ("BRANCH_ID") +); + +CREATE INDEX "IDX_XID" ON "SEATA"."BRANCH_TABLE"("XID" ASC); + +-- the table to store lock data +CREATE TABLE "SEATA"."LOCK_TABLE" +( + "ROW_KEY" VARCHAR2(128) NOT NULL, + "XID" VARCHAR2(128), + "TRANSACTION_ID" BIGINT, + "BRANCH_ID" BIGINT NOT NULL, + "RESOURCE_ID" VARCHAR2(256), + "TABLE_NAME" VARCHAR2(32), + "PK" VARCHAR2(36), + "STATUS" TINYINT NOT NULL DEFAULT 0, + "GMT_CREATE" TIMESTAMP(0), + "GMT_MODIFIED" TIMESTAMP(0), + PRIMARY KEY ("ROW_KEY") +); + +COMMENT ON COLUMN "SEATA"."LOCK_TABLE"."STATUS" IS '0:locked ,1:rollbacking'; + +CREATE INDEX "IDX_BRANCH_ID" ON "SEATA"."LOCK_TABLE" ("BRANCH_ID" ASC); +CREATE INDEX "IDX_STATUS" ON "SEATA"."LOCK_TABLE" ("STATUS" ASC); + +CREATE TABLE "SEATA"."DISTRIBUTED_LOCK" +( + "LOCK_KEY" VARCHAR2(20) NOT NULL, + "LOCK_VALUE" VARCHAR2(20) NOT NULL, + "EXPIRE" BIGINT NOT NULL, + PRIMARY KEY ("LOCK_KEY") +); + +INSERT INTO "SEATA"."DISTRIBUTED_LOCK" ("LOCK_KEY", "LOCK_VALUE", "EXPIRE") VALUES ('HandleAllSession', ' ', 0); diff --git a/server/pom.xml b/server/pom.xml index 1924128aa50..a857645b488 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -170,6 +170,10 @@ org.postgresql postgresql + + com.dameng + DmJdbcDriver18 +