Tanya-W commented on code in PR #19063: URL: https://github.com/apache/doris/pull/19063#discussion_r1193447004
########## fe/fe-core/src/main/java/org/apache/doris/alter/InvertedIndexJob.java: ########## @@ -0,0 +1,400 @@ +// 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.alter; + +import org.apache.doris.catalog.Column; +import org.apache.doris.catalog.Database; +import org.apache.doris.catalog.Env; +import org.apache.doris.catalog.Index; +import org.apache.doris.catalog.MaterializedIndex; +import org.apache.doris.catalog.OlapTable; +import org.apache.doris.catalog.Partition; +import org.apache.doris.catalog.Replica; +import org.apache.doris.catalog.TableIf.TableType; +import org.apache.doris.catalog.Tablet; +import org.apache.doris.common.AnalysisException; +import org.apache.doris.common.Config; +import org.apache.doris.common.FeConstants; +import org.apache.doris.common.MetaNotFoundException; +import org.apache.doris.common.io.Text; +import org.apache.doris.common.io.Writable; +import org.apache.doris.common.util.TimeUtils; +import org.apache.doris.persist.gson.GsonUtils; +import org.apache.doris.task.AgentBatchTask; +import org.apache.doris.task.AgentTaskExecutor; +import org.apache.doris.task.AgentTaskQueue; +import org.apache.doris.task.AlterInvertedIndexTask; +import org.apache.doris.thrift.TColumn; + +import com.google.common.base.Joiner; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.gson.annotations.SerializedName; +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.List; + + +public class InvertedIndexJob implements Writable { + private static final Logger LOG = LogManager.getLogger(InvertedIndexJob.class); + + + public enum JobState { + // CHECKSTYLE OFF + WAITING_TXN, // waiting for previous txns to be finished + // CHECKSTYLE ON + RUNNING, // waiting for inverted index tasks finished. + FINISHED, // job is done + CANCELLED; // job is cancelled + + public boolean isFinalState() { + return this == JobState.FINISHED || this == JobState.CANCELLED; + } + } + + @SerializedName(value = "jobId") + private long jobId; + @SerializedName(value = "jobState") + private JobState jobState; + + @SerializedName(value = "dbId") + private long dbId; + @SerializedName(value = "tableId") + private long tableId; + @SerializedName(value = "tableName") + private String tableName; + @SerializedName(value = "partitionId") + private long partitionId; + @SerializedName(value = "partitionName") + private String partitionName; + + @SerializedName(value = "errMsg") + private String errMsg = ""; + @SerializedName(value = "createTimeMs") + private long createTimeMs = -1; + @SerializedName(value = "finishedTimeMs") + private long finishedTimeMs = -1; + @SerializedName(value = "watershedTxnId") + protected long watershedTxnId = -1; + + @SerializedName(value = "isDropOp") + private boolean isDropOp = false; + @SerializedName(value = "alterInvertedIndexes") + private List<Index> alterInvertedIndexes = null; + @SerializedName(value = "originIndexId") + private long originIndexId; + // @SerializedName(value = "partitionInvertedIndexTaskMap") + // private Map<Long, AgentBatchTask> partitionInvertedIndexTaskMap = Maps.newConcurrentMap(); + @SerializedName(value = "invertedIndexBatchTask") + AgentBatchTask invertedIndexBatchTask = new AgentBatchTask(); + + public InvertedIndexJob(long jobId, long dbId, long tableId, String tableName) { + this.jobId = jobId; + this.dbId = dbId; + this.tableId = tableId; + this.tableName = tableName; + + this.createTimeMs = System.currentTimeMillis(); + this.jobState = JobState.WAITING_TXN; + } + + public long getJobId() { + return jobId; + } + + public long getOriginIndexId() { + return originIndexId; + } + + public JobState getJobState() { + return jobState; + } + + public void setJobState(JobState jobState) { + this.jobState = jobState; + } + + public void setPartitionId(long partitionId) { + this.partitionId = partitionId; + } + + public void setPartitionName(String partitionName) { + this.partitionName = partitionName; + } + + public void setOriginIndexId(long originIndexId) { + this.originIndexId = originIndexId; + } + + public void setAlterInvertedIndexInfo(boolean isDropOp, List<Index> alterInvertedIndexes) { + this.isDropOp = isDropOp; + this.alterInvertedIndexes = alterInvertedIndexes; + } + + public boolean hasSameAlterInvertedIndex(boolean isDropOp, List<Index> inputAlterInvertedIndexes) { + if (this.isDropOp == isDropOp) { + for (Index inputIndex : inputAlterInvertedIndexes) { + for (Index existIndex : this.alterInvertedIndexes) { + if (inputIndex.getIndexId() == existIndex.getIndexId()) { + return true; + } + } + } + } + return false; + } + + public long getDbId() { + return dbId; + } + + public long getTableId() { + return tableId; + } + + public String getTableName() { + return tableName; + } + + public String getPartitionName() { + return partitionName; + } + + public boolean isExpire() { + return isDone() && (System.currentTimeMillis() - finishedTimeMs) / 1000 > Config.history_job_keep_max_second; + } + + public boolean isDone() { + return jobState.isFinalState(); + } + + public long getFinishedTimeMs() { + return finishedTimeMs; + } + + public void setFinishedTimeMs(long finishedTimeMs) { + this.finishedTimeMs = finishedTimeMs; + } + + /** + * The keyword 'synchronized' only protects 2 methods: + * run() and cancel() + * Only these 2 methods can be visited by different thread(internal working thread and user connection thread) + * So using 'synchronized' to make sure only one thread can run the job at one time. + * + * lock order: + * synchronized + * db lock + */ + public synchronized void run() { + try { + this.watershedTxnId = Env.getCurrentGlobalTransactionMgr() + .getTransactionIDGenerator().getNextTransactionId(); + switch (jobState) { + case WAITING_TXN: + runWaitingTxnJob(); + break; + case RUNNING: + runRunningJob(); + break; + default: + break; + } + } catch (AlterCancelException e) { + cancelImpl(e.getMessage()); + } + } + + public final synchronized boolean cancel(String errMsg) { + return cancelImpl(errMsg); + } + + // Check whether transactions of the given database which txnId is less than 'watershedTxnId' are finished. + protected boolean isPreviousLoadFinished() throws AnalysisException { + return Env.getCurrentGlobalTransactionMgr().isPreviousTransactionsFinished( + watershedTxnId, dbId, Lists.newArrayList(tableId)); + } + + protected void runWaitingTxnJob() throws AlterCancelException { + Preconditions.checkState(jobState == JobState.WAITING_TXN, jobState); + try { + if (!isPreviousLoadFinished()) { + LOG.info("wait transactions before {} to be finished, inverted index job: {}", watershedTxnId, jobId); + return; + } + } catch (AnalysisException e) { + throw new AlterCancelException(e.getMessage()); + } + + LOG.info("previous transactions are all finished, begin to send build or delete inverted index file tasks." + + "job: {}, is delete: {}", jobId, isDropOp); + Database db = Env.getCurrentInternalCatalog() + .getDbOrException(dbId, s -> new AlterCancelException("Database " + s + " does not exist")); + OlapTable olapTable; + try { + olapTable = (OlapTable) db.getTableOrMetaException(tableId, TableType.OLAP); + } catch (MetaNotFoundException e) { + throw new AlterCancelException(e.getMessage()); + } + + olapTable.readLock(); + try { + List<Column> originSchemaColumns = olapTable.getSchemaByIndexId(originIndexId, true); + for (Column col : originSchemaColumns) { + TColumn tColumn = col.toThrift(); + col.setIndexFlag(tColumn, olapTable); + } + int originSchemaHash = olapTable.getSchemaHashByIndexId(originIndexId); + Partition partition = olapTable.getPartition(partitionId); + MaterializedIndex origIdx = partition.getIndex(originIndexId); + for (Tablet originTablet : origIdx.getTablets()) { + long taskSignature = Env.getCurrentEnv().getNextId(); + long originTabletId = originTablet.getId(); + List<Replica> originReplicas = originTablet.getReplicas(); + for (Replica originReplica : originReplicas) { + if (originReplica.getBackendId() < 0) { + LOG.warn("replica:{}, backendId: {}", originReplica, originReplica.getBackendId()); + throw new AlterCancelException("originReplica:" + originReplica.getId() + + " backendId < 0"); + } + AlterInvertedIndexTask alterInvertedIndexTask = new AlterInvertedIndexTask( + originReplica.getBackendId(), db.getId(), olapTable.getId(), + partitionId, originIndexId, originTabletId, + originSchemaHash, olapTable.getIndexes(), + alterInvertedIndexes, originSchemaColumns, + isDropOp, taskSignature); + invertedIndexBatchTask.addTask(alterInvertedIndexTask); + } + } // end for tablet + + LOG.info("invertedIndexBatchTask:{}", invertedIndexBatchTask); + AgentTaskQueue.addBatchTask(invertedIndexBatchTask); + AgentTaskExecutor.submit(invertedIndexBatchTask); + // partitionInvertedIndexTaskMap.put(partitionId, invertedIndexBatchTask) + } finally { + olapTable.readUnlock(); + } + this.jobState = JobState.RUNNING; + LOG.info("transfer inverted index job {} state to {}", jobId, this.jobState); + } + + protected void runRunningJob() throws AlterCancelException { + Preconditions.checkState(jobState == JobState.RUNNING, jobState); + + if (!invertedIndexBatchTask.isFinished()) { + LOG.info("inverted index tasks not finished. job: {}, partitionId: {}", jobId, partitionId); + // TODO: task failed limit + return; + } + + this.jobState = JobState.FINISHED; + this.finishedTimeMs = System.currentTimeMillis(); + + Env.getCurrentEnv().getEditLog().logInvertedIndexJob(this); + LOG.info("inverted index job finished: {}", jobId); + } + + protected boolean cancelImpl(String errMsg) { + return true; + } + + public void replay(InvertedIndexJob replayedJob) { + try { + InvertedIndexJob replayedInvertedIndexJob = (InvertedIndexJob) replayedJob; + switch (replayedJob.jobState) { + case WAITING_TXN: + replayCreateJob(replayedInvertedIndexJob); + break; + case FINISHED: + replayRunningJob(replayedInvertedIndexJob); + break; + case CANCELLED: + // TODO: + // replayCancelled(replayedInvertedIndexJob); + break; + default: Review Comment: RUNNING state do not write edit log, so no need replay it -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
