morningman commented on a change in pull request #3191: DeleteV2
URL: https://github.com/apache/incubator-doris/pull/3191#discussion_r408101529
 
 

 ##########
 File path: fe/src/main/java/org/apache/doris/load/DeleteHandler.java
 ##########
 @@ -0,0 +1,627 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.load;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.apache.doris.analysis.BinaryPredicate;
+import org.apache.doris.analysis.DeleteStmt;
+import org.apache.doris.analysis.IsNullPredicate;
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.analysis.Predicate;
+import org.apache.doris.analysis.SlotRef;
+import org.apache.doris.catalog.Catalog;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.KeysType;
+import org.apache.doris.catalog.MaterializedIndex;
+import org.apache.doris.catalog.MaterializedIndex.IndexExtState;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.Partition;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.Replica;
+import org.apache.doris.catalog.Table;
+import org.apache.doris.catalog.Tablet;
+import org.apache.doris.catalog.TabletInvertedIndex;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.ErrorReport;
+import org.apache.doris.common.FeConstants;
+import org.apache.doris.common.MarkedCountDownLatch;
+import org.apache.doris.common.MetaNotFoundException;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.io.Writable;
+import org.apache.doris.common.util.ListComparator;
+import org.apache.doris.common.util.TimeUtils;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.service.FrontendOptions;
+import org.apache.doris.task.AgentBatchTask;
+import org.apache.doris.task.AgentTaskExecutor;
+import org.apache.doris.task.AgentTaskQueue;
+import org.apache.doris.task.DeleteJob;
+import org.apache.doris.task.DeleteJob.DeleteState;
+import org.apache.doris.task.PushTask;
+import org.apache.doris.thrift.TPriority;
+import org.apache.doris.thrift.TPushType;
+import org.apache.doris.thrift.TTaskType;
+import org.apache.doris.transaction.GlobalTransactionMgr;
+import org.apache.doris.transaction.TabletCommitInfo;
+import org.apache.doris.transaction.TransactionState;
+import org.apache.doris.transaction.TransactionStatus;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+public class DeleteHandler implements Writable {
+    private static final Logger LOG = 
LogManager.getLogger(DeleteHandler.class);
+
+    // TransactionId -> DeleteJob
+    private Map<Long, DeleteJob> idToDeleteJob;
+
+    // Db -> DeleteInfo list
+    private Map<Long, List<DeleteInfo>> dbToDeleteInfos;
+
+    public DeleteHandler() {
+        idToDeleteJob = Maps.newConcurrentMap();
+        dbToDeleteInfos = Maps.newConcurrentMap();
+    }
+
+    private enum CancelType {
+        METADATA_MISSING,
+        TIMEOUT,
+        COMMIT_FAIL,
+        UNKNOWN
+    }
+
+    public void process(DeleteStmt stmt) throws DdlException {
+        String dbName = stmt.getDbName();
+        String tableName = stmt.getTableName();
+        String partitionName = stmt.getPartitionName();
+        List<Predicate> conditions = stmt.getDeleteConditions();
+        Database db = Catalog.getInstance().getDb(dbName);
+        if (db == null) {
+            throw new DdlException("Db does not exist. name: " + dbName);
+        }
+
+        DeleteJob deleteJob = null;
+        try {
+            MarkedCountDownLatch<Long, Long> countDownLatch;
+            long transactionId = -1;
+            db.readLock();
+            try {
+                Table table = db.getTable(tableName);
+                if (table == null) {
+                    throw new DdlException("Table does not exist. name: " + 
tableName);
+                }
+
+                if (table.getType() != Table.TableType.OLAP) {
+                    throw new DdlException("Not olap type table. type: " + 
table.getType().name());
+                }
+                OlapTable olapTable = (OlapTable) table;
+
+                if (olapTable.getState() != OlapTable.OlapTableState.NORMAL) {
+                    throw new DdlException("Table's state is not normal: " + 
tableName);
+                }
+
+                if (partitionName == null) {
+                    if (olapTable.getPartitionInfo().getType() == 
PartitionType.RANGE) {
+                        throw new DdlException("This is a range partitioned 
table."
+                                + " You should specify partition in delete 
stmt");
+                    } else {
+                        // this is a unpartitioned table, use table name as 
partition name
+                        partitionName = olapTable.getName();
+                    }
+                }
+
+                Partition partition = olapTable.getPartition(partitionName);
+                if (partition == null) {
+                    throw new DdlException("Partition does not exist. name: " 
+ partitionName);
+                }
+
+                List<String> deleteConditions = Lists.newArrayList();
+
+                // pre check
+                checkDeleteV2(olapTable, partition, conditions, 
deleteConditions, true);
+
+                // generate label
+                String label = "delete_" + UUID.randomUUID();
+                //generate jobId
+                long jobId = Catalog.getCurrentCatalog().getNextId();
+                // begin txn here and generate txn id
+                transactionId = 
Catalog.getCurrentGlobalTransactionMgr().beginTransaction(db.getId(),
+                        Lists.newArrayList(table.getId()), label, null, "FE: " 
+ FrontendOptions.getLocalHostAddress(),
+                        TransactionState.LoadJobSourceType.FRONTEND, jobId, 
Config.stream_load_default_timeout_second);
+
+                DeleteInfo deleteInfo = new DeleteInfo(db.getId(), 
olapTable.getId(), tableName,
+                        partition.getId(), partitionName,
+                        -1, 0, deleteConditions);
+                deleteJob = new DeleteJob(jobId, transactionId, deleteInfo);
+                idToDeleteJob.put(deleteJob.getTransactionId(), deleteJob);
+
+                
Catalog.getCurrentGlobalTransactionMgr().getCallbackFactory().addCallback(deleteJob);
+                // task sent to be
+                AgentBatchTask batchTask = new AgentBatchTask();
+                // count total replica num
+                int totalReplicaNum = 0;
+                for (MaterializedIndex index : 
partition.getMaterializedIndices(IndexExtState.VISIBLE)) {
+                    for (Tablet tablet : index.getTablets()) {
+                        totalReplicaNum += tablet.getReplicas().size();
+                    }
+                }
+                countDownLatch = new MarkedCountDownLatch<Long, 
Long>(totalReplicaNum);
+
+                for (MaterializedIndex index : 
partition.getMaterializedIndices(IndexExtState.VISIBLE)) {
+                    long indexId = index.getId();
+                    int schemaHash = olapTable.getSchemaHashByIndexId(indexId);
+
+                    for (Tablet tablet : index.getTablets()) {
+                        long tabletId = tablet.getId();
+
+                        // set push type
+                        TPushType type = TPushType.DELETE;
+
+                        for (Replica replica : tablet.getReplicas()) {
+                            long replicaId = replica.getId();
+                            long backendId = replica.getBackendId();
+                            countDownLatch.addMark(backendId, tabletId);
+
+                            // create push task for each replica
+                            PushTask pushTask = new PushTask(null,
+                                    replica.getBackendId(), db.getId(), 
olapTable.getId(),
+                                    partition.getId(), indexId,
+                                    tabletId, replicaId, schemaHash,
+                                    -1, 0, "", -1, 0,
+                                    -1, type, conditions,
+                                    true, TPriority.NORMAL,
+                                    TTaskType.REALTIME_PUSH,
+                                    transactionId,
+                                    
Catalog.getCurrentGlobalTransactionMgr().getTransactionIDGenerator().getNextTransactionId());
+                            pushTask.setIsSchemaChanging(false);
+                            pushTask.setCountDownLatch(countDownLatch);
+
+                            if (AgentTaskQueue.addTask(pushTask)) {
+                                batchTask.addTask(pushTask);
+                                deleteJob.addPushTask(pushTask);
+                                deleteJob.addTablet(tabletId);
+                            }
+                        }
+                    }
+                }
+
+                // submit push tasks
+                if (batchTask.getTaskNum() > 0) {
+                    AgentTaskExecutor.submit(batchTask);
+                }
+
+            } catch (Throwable t) {
+                LOG.warn("error occurred during delete process", t);
+                // if transaction has been begun, need to abort it
+                if 
(Catalog.getCurrentGlobalTransactionMgr().getTransactionState(transactionId) != 
null) {
+                    cancelJob(deleteJob, CancelType.UNKNOWN, t.getMessage());
+                }
+                throw new DdlException(t.getMessage(), t);
+            } finally {
+                db.readUnlock();
+            }
+
+            long timeoutMs = deleteJob.getTimeoutMs();
+            LOG.info("waiting delete Job finish, signature: {}, timeout: {}", 
transactionId, timeoutMs);
+            boolean ok = false;
+            try {
+                ok = countDownLatch.await(timeoutMs, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                LOG.warn("InterruptedException: ", e);
+                ok = false;
+            }
+
+            if (!ok) {
+                try {
+                    deleteJob.checkAndUpdateQuorum();
+                } catch (MetaNotFoundException e) {
+                    cancelJob(deleteJob, CancelType.METADATA_MISSING, 
e.getMessage());
+                    throw new DdlException(e.getMessage(), e);
+                }
+                DeleteState state = deleteJob.getState();
+                switch (state) {
+                    case UN_QUORUM:
+                        List<Entry<Long, Long>> unfinishedMarks = 
countDownLatch.getLeftMarks();
+                        // only show at most 5 results
+                        List<Entry<Long, Long>> subList = 
unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5));
+                        String errMsg = "Unfinished replicas:" + Joiner.on(", 
").join(subList);
+                        LOG.warn("delete job timeout: transactionId {}, {}", 
transactionId, errMsg);
+                        cancelJob(deleteJob, CancelType.TIMEOUT, "delete job 
timeout");
+                        throw new DdlException("failed to delete replicas from 
job: " + transactionId + ", " + errMsg);
+                    case QUORUM_FINISHED:
+                    case FINISHED:
+                        try {
+                            long nowQuorumTimeMs = System.currentTimeMillis();
+                            long endQuorumTimeoutMs = nowQuorumTimeMs + 
timeoutMs / 2;
+                            // if job's state is quorum_finished then wait for 
a period of time and commit it.
+                            while (deleteJob.getState() == 
DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs) {
+                                deleteJob.checkAndUpdateQuorum();
+                                Thread.sleep(1000);
+                                nowQuorumTimeMs = System.currentTimeMillis();
+                            }
+                        } catch (MetaNotFoundException e) {
+                            cancelJob(deleteJob, CancelType.METADATA_MISSING, 
e.getMessage());
+                            throw new DdlException(e.getMessage(), e);
+                        } catch (InterruptedException e) {
+                            cancelJob(deleteJob, CancelType.UNKNOWN, 
e.getMessage());
+                            throw new DdlException(e.getMessage(), e);
+                        }
+                        commitJob(deleteJob, db, timeoutMs);
+                        break;
+                    default:
+                        Preconditions.checkState(false, "wrong delete job 
state: " + state.name());
+                        break;
+                }
+            } else {
+                commitJob(deleteJob, db, timeoutMs);
+            }
+        } finally {
+            if (!FeConstants.runningUnitTest) {
+                clearJob(deleteJob);
+            }
+        }
+    }
+
+    private void commitJob(DeleteJob job, Database db, long timeoutMs) throws 
DdlException {
+        TransactionStatus status = null;
+        try {
+            unprotectedCommitJob(job, db, timeoutMs);
+            status = Catalog.getCurrentGlobalTransactionMgr().
+                    
getTransactionState(job.getTransactionId()).getTransactionStatus();
+        } catch (UserException e) {
+            cancelJob(job, CancelType.COMMIT_FAIL, e.getMessage());
+            throw new DdlException(e.getMessage(), e);
+        }
+
+        switch (status) {
+            case COMMITTED:
+                // Although publish is unfinished we should tell user that 
commit already success.
+                throw new DdlException("delete job is committed but may be 
taking effect later, transactionId: " + job.getTransactionId());
+            case VISIBLE:
+                break;
+            default:
+                Preconditions.checkState(false, "wrong transaction status: " + 
status.name());
+                break;
+        }
+    }
+
+    /**
+     * unprotected commit delete job
+     * return true when successfully commit and publish
+     * return false when successfully commit but publish unfinished.
+     * A UserException thrown if both commit and publish failed.
+     * @param job
+     * @param db
+     * @param timeoutMs
+     * @return
+     * @throws UserException
+     */
+    private boolean unprotectedCommitJob(DeleteJob job, Database db, long 
timeoutMs) throws UserException {
+        long transactionId = job.getTransactionId();
+        GlobalTransactionMgr globalTransactionMgr = 
Catalog.getCurrentGlobalTransactionMgr();
+        List<TabletCommitInfo> tabletCommitInfos = new 
ArrayList<TabletCommitInfo>();
+        TabletInvertedIndex invertedIndex = Catalog.getCurrentInvertedIndex();
+        for (TabletDeleteInfo tDeleteInfo : job.getTabletDeleteInfo()) {
+            for (Replica replica : tDeleteInfo.getFinishedReplicas()) {
+                // the inverted index contains rolling up replica
+                Long tabletId = 
invertedIndex.getTabletIdByReplica(replica.getId());
+                if (tabletId == null) {
+                    LOG.warn("could not find tablet id for replica {}, the 
tablet maybe dropped", replica);
+                    continue;
+                }
+                tabletCommitInfos.add(new TabletCommitInfo(tabletId, 
replica.getBackendId()));
+            }
+        }
+        return globalTransactionMgr.commitAndPublishTransaction(db, 
transactionId, tabletCommitInfos, timeoutMs);
+    }
+
+    /**
+     * This method should always be called in the end of the delete process to 
clean the job.
+     * Better put it in finally block.
+     * @param job
+     */
+    private void clearJob(DeleteJob job) {
+        if (job != null) {
+            long signature = job.getTransactionId();
+            if (idToDeleteJob.containsKey(signature)) {
+                idToDeleteJob.remove(signature);
+            }
+            for (PushTask pushTask : job.getPushTasks()) {
+                AgentTaskQueue.removePushTask(pushTask.getBackendId(), 
pushTask.getSignature(),
+                        pushTask.getVersion(), pushTask.getVersionHash(),
+                        pushTask.getPushType(), pushTask.getTaskType());
+            }
+            
Catalog.getCurrentGlobalTransactionMgr().getCallbackFactory().removeCallback(job.getId());
+        }
+    }
+
+    public void recordFinishedJob(DeleteJob job) {
+        if (job != null) {
+            long dbId = job.getDeleteInfo().getDbId();
+            LOG.info("record finished deleteJob, transactionId {}, dbId {}",
+                    job.getTransactionId(), dbId);
+            List<DeleteInfo> deleteInfoList = dbToDeleteInfos.get(dbId);
+            if (deleteInfoList == null) {
+                deleteInfoList = Lists.newArrayList();
+                dbToDeleteInfos.put(dbId, deleteInfoList);
+            }
+            deleteInfoList.add(job.getDeleteInfo());
+        }
+    }
+
+    public boolean cancelJob(DeleteJob job, CancelType cancelType, String 
reason) {
 
 Review comment:
   This method return boolean, but you never use it.
   I think return true means cancel succeed(txn failed), and return false means 
cancel failed(txn succeed).
   And the caller should use this return value to decide whether to return user 
success or failure.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to