ob_trans_service_v4.cpp 112.9 KB
Newer Older
W
wangzelin.wzl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/**
 * Copyright (c) 2021 OceanBase
 * OceanBase CE is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#include "lib/utility/ob_macro_utils.h"
#include "ob_trans_service.h"
#include "ob_trans_define.h"
#include "lib/profile/ob_perf_event.h"
#include "lib/stat/ob_session_stat.h"
#include "lib/ob_name_id_def.h"
#include "lib/ob_running_mode.h"
20
#include "rpc/ob_request.h"
W
wangzelin.wzl 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include "ob_trans_ctx.h"
#include "ob_trans_factory.h"
#include "ob_trans_functor.h"
#include "ob_tx_msg.h"
#include "ob_tx_log_adapter.h"
#include "ob_trans_part_ctx.h"
#include "ob_trans_result.h"
#include "observer/ob_server.h"
#include "observer/ob_server_struct.h"
#include "observer/omt/ob_tenant_config_mgr.h"
#include "storage/ob_i_store.h"
#include "wrs/ob_i_weak_read_service.h"           // ObIWeakReadService
#include "sql/session/ob_basic_session_info.h"
#include "wrs/ob_weak_read_util.h"               // ObWeakReadUtil
#include "storage/memtable/ob_memtable_context.h"
#include "common/storage/ob_sequence.h"
#include "storage/tx_table/ob_tx_table_define.h"
#include "storage/tx_storage/ob_ls_service.h"
#include "storage/tx_storage/ob_ls_handle.h"
#include "storage/ls/ob_ls.h"
#include "ob_xa_service.h"
42
#include "rootserver/ob_tenant_recovery_reportor.h"
W
wangzelin.wzl 已提交
43 44 45 46 47 48

/*  interface(s)  */
namespace oceanbase {
namespace transaction {

using namespace memtable;
49
using namespace share;
W
wangzelin.wzl 已提交
50

O
obdev 已提交
51 52
static const int64_t POST_COMMIT_REQ_RETRY_INTERVAL = 100 * 1000; // 100msg

W
wangzelin.wzl 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
int ObTransService::create_ls(const share::ObLSID &ls_id,
                              ObLS &ls,
                              ObITxLogParam *param,
                              ObITxLogAdapter *log_adapter)
{
  int ret = OB_SUCCESS;
  ObTableHandleV2 lock_memtable;
  ObTxTable *tx_table = nullptr;
  if (IS_NOT_INIT) {
    ret = OB_NOT_INIT;
    TRANS_LOG(WARN, "ObTransService not inited", K(ret), K(*this));
  } else if (OB_UNLIKELY(!is_running_)) {
    ret = OB_NOT_RUNNING;
    TRANS_LOG(WARN, "ObTransService is not running", K(ret), K(*this));
  } else if (!ls_id.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid argument", K(ret), K(ls_id));
  } else if (OB_ISNULL(tx_table = ls.get_tx_table())) {
    TRANS_LOG(WARN, "get tx table fail", K(ret), K(ls_id));
  } else if (OB_FAIL(tx_ctx_mgr_.create_ls(tenant_id_,
                                           ls_id,
                                           tx_table,
                                           ls.get_lock_table(),
                                           *ls.get_tx_svr(),
                                           param,
                                           log_adapter))) {
    TRANS_LOG(WARN, "create ls failed", K(ret), K(*this));
  } else {
    // do nothing
  }
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "create ls failed", K(ret), K(tenant_id_), K(ls_id));
  } else {
    TRANS_LOG(INFO, "create ls success", K(tenant_id_), K(ls_id));
  }

  return ret;
}

int ObTransService::remove_ls(const share::ObLSID &ls_id, const bool graceful)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    ret = OB_NOT_INIT;
    TRANS_LOG(WARN, "ObTransService not inited", K(ret));
  } else if (OB_UNLIKELY(!is_running_)) {
    ret = OB_NOT_RUNNING;
    TRANS_LOG(WARN, "ObTransService is not running", K(ret));
  } else if (!ls_id.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid argument", K(ret), K(ls_id));
  } else if (OB_FAIL(tx_ctx_mgr_.remove_ls(ls_id, graceful))) {
    TRANS_LOG(WARN, "participant remove ls_id error", K(ret), K(ls_id), K(graceful));
  // FIXME. xiaoshi.xjl
  //} else if (OB_FAIL(dup_table_lease_task_map_.del(ls_id))) {
  //  if (OB_ENTRY_NOT_EXIST == ret) {
  //    ret = OB_SUCCESS;
  //    TRANS_LOG(INFO, "remove ls success", K(ls_id), K(graceful));
  //  } else {
  //    TRANS_LOG(WARN, "erase lease task from hashmap error", K(ret), K(ls_id));
  //  }
  } else {
    TRANS_LOG(INFO, "remove ls success", K(ls_id), K(graceful));
  }
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "remove ls failed", K(ret), K(ls_id), K(graceful));
  } else {
    TRANS_LOG(INFO, "remove ls success", K(ls_id), K(graceful));
  }

  return ret;
}

#ifdef TX_PARTS_CONTAIN_
#error "redefine TX_PARTS_CONTAIN_"
#else
#define TX_PARTS_CONTAIN_(parts, id_, ls_id, hit)       \
  do {                                                  \
    hit = false;                                        \
    ARRAY_FOREACH_NORET(parts, idx) {                   \
      if (parts.at(idx).id_ == ls_id) {                 \
        hit = true;                                     \
        break;                                          \
      }                                                 \
    }                                                   \
  } while(0)
#endif

int ObTransService::acquire_tx(const char* buf,
                               const int64_t len,
                               int64_t &pos,
                               ObTxDesc *&tx)
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(tx_desc_mgr_.alloc(tx))) {
    TRANS_LOG(WARN, "alloc tx fail", K(ret), KPC(this));
  } else if (OB_FAIL(tx->deserialize(buf, len, pos))) {
    tx_desc_mgr_.revert(*tx);
    tx = NULL;
    TRANS_LOG(WARN, "desrialize txDesc fail", K(ret),
              K(len),K(pos), K(buf), KPC(this));
  } else {
    tx->flags_.SHADOW_ = true;
  }
  if (tx) {
    REC_TRANS_TRACE_EXT(&tx->get_tlog(), deserialize,
                        OB_ID(addr), (void*)&tx,
                        OB_ID(txid), tx->tx_id_);
  }
  TRANS_LOG(TRACE, "acquire tx by deserialize", K(ret), K(*this), KP(buf), KPC(tx));
  return ret;
}

/*
 * do_commit_tx_ - the real work of commit tx
 *
 * steps:
 * 1. decide coordinator
 * 2. try local call optimization, if fail fallback to step 3
 * 3. post commit message to coordinator
 *
 * If any failures occurred:
 * - if no message has been sent, state can be revert to
 *   ACTIVE, and the caller can retry
 * - if any message has been sent, a prepose timer task will
 *   drive the retry in background, the commit return success
 *
 * Return:
 * OB_SUCCESS - either local commit started or
 *              remote commit retry task has been registred
 * OB_XXX     - try local commit failed and can not been
 *              fallback to remote commit via send message
 */
int ObTransService::do_commit_tx_(ObTxDesc &tx,
                                  const int64_t expire_ts,
                                  ObITxCallback &cb,
190
                                  SCN &commit_version)
W
wangzelin.wzl 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
{
  int ret = OB_SUCCESS;
  ObTxPart *coord = NULL;
  tx.set_commit_cb(&cb);
  tx.commit_expire_ts_ = expire_ts;
  if (OB_FAIL(decide_tx_commit_info_(tx, coord))) {
    TRANS_LOG(WARN, "decide tx coordinator fail, tx will abort", K(ret), K(tx));
  } else if (OB_FAIL(tx.commit_task_.init(&tx, this))) {
    TRANS_LOG(WARN, "init timeout task fail", K(ret), K(tx));
  } else if (coord->addr_ == self_ && (
             OB_SUCC(local_ls_commit_tx_(tx.tx_id_,
                                         tx.coord_id_,
                                         tx.commit_parts_,
                                         expire_ts,
                                         tx.trace_info_.get_app_trace_info(),
                                         tx.op_sn_,
                                         commit_version))
             || !commit_need_retry_(ret))) {
    if (OB_FAIL(ret)) {
      TRANS_LOG(WARN, "local ls commit tx fail", K(ret), K_(tx.coord_id), K(tx));
    } else {
      TRANS_LOG(TRACE, "local ls commit tx started", K(tx));
    }
  } else if (OB_FAIL(do_commit_tx_slowpath_(tx, expire_ts))) {
    TRANS_LOG(WARN, "commit tx slowpath fail", K(ret),
              K_(tx.coord_id), K_(tx.commit_parts), K(tx));
  } else {
    TRANS_LOG(TRACE, "remote commit started", K(tx), K_(self));
  }
  // start commit fail
  if (OB_FAIL(ret)) {
    tx.cancel_commit_cb();
  }
  return ret;
}

/*
 * try send commit msg to coordinator, and register retry task
 * if msg send fail, the retry task will retry later
 * if both register task fail and send are failed, the commit failed
 */
O
obdev 已提交
232 233
int ObTransService::do_commit_tx_slowpath_(ObTxDesc &tx, const int64_t expire_ts)
{
W
wangzelin.wzl 已提交
234 235
  int ret = OB_SUCCESS;
  ObTxCommitMsg commit_msg;
O
obdev 已提交
236 237
  bool post_msg_fail = false;
  if (OB_FAIL(build_tx_commit_msg_(tx, commit_msg))) {
W
wangzelin.wzl 已提交
238 239
    TRANS_LOG(WARN, "build tx commit msg fail", K(ret), K(tx));
    // build msg fail won't cause commit fail, later driven by retry timer
O
obdev 已提交
240
    post_msg_fail = true;
W
wangzelin.wzl 已提交
241 242 243 244
    ret = OB_SUCCESS;
  } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, commit_msg))) {
    TRANS_LOG(WARN, "post tx commit msg fail", K(ret), K(tx), K(commit_msg));
    // send msg fail won't cause commit fail, later driven by retry timer
O
obdev 已提交
245
    post_msg_fail = true;
W
wangzelin.wzl 已提交
246 247
    ret = OB_SUCCESS;
  }
O
obdev 已提交
248 249 250 251 252 253 254 255 256 257 258

  if (post_msg_fail) {
    if (OB_FAIL(register_commit_retry_task_(tx, POST_COMMIT_REQ_RETRY_INTERVAL))) {
      TRANS_LOG(WARN, "register retry commit task fail", K(ret), K(tx));
    }
  } else {
    if (OB_FAIL(register_commit_retry_task_(tx))) {
      TRANS_LOG(WARN, "register retry commit task fail", K(ret), K(tx));
    }
  }
  TRANS_LOG(TRACE, "do commit tx slowpath", K(ret), K(post_msg_fail), K(tx));
W
wangzelin.wzl 已提交
259 260 261
  return ret;
}

C
chinaxing 已提交
262
int ObTransService::register_commit_retry_task_(ObTxDesc &tx, int64_t max_delay)
W
wangzelin.wzl 已提交
263
{
C
chinaxing 已提交
264
  const int64_t MIN_DELAY = 50 * 1000;// 50ms
W
wangzelin.wzl 已提交
265
  int ret = OB_SUCCESS;
O
obdev 已提交
266
  int saved_ret = OB_SUCCESS;
C
chinaxing 已提交
267
  max_delay = max_delay == INT64_MAX ? ObTransCtx::MAX_TRANS_2PC_TIMEOUT_US : max_delay;
W
wangzelin.wzl 已提交
268 269
  int64_t now = ObClockGenerator::getClock();
  int64_t expire_after = std::min(tx.expire_ts_ - now, tx.commit_expire_ts_ - now);
C
chinaxing 已提交
270 271 272 273 274
  int64_t delay = std::min(max_delay, tx.commit_task_.get_delay() * 2);
  if (expire_after > 0) { delay = std::min(delay, expire_after); }
  delay = std::max(delay, MIN_DELAY);
  if (delay != MIN_DELAY) {
    delay = ObRandom::rand(MIN_DELAY, delay);
W
wangzelin.wzl 已提交
275 276 277 278 279 280 281
  }
  if (OB_FAIL(tx_desc_mgr_.acquire_tx_ref(tx.tx_id_))) {
    TRANS_LOG(WARN, "acquire tx ref fail", KR(ret), K(tx));
  } else {
    if (OB_FAIL(timer_.register_timeout_task(tx.commit_task_, delay))) {
      TRANS_LOG(WARN, "register tx retry task fail", KR(ret), K(delay), K(tx));
      tx_desc_mgr_.revert(tx);
O
obdev 已提交
282 283 284 285 286
      if (OB_TIMER_TASK_HAS_SCHEDULED == ret) {
        saved_ret = ret;
        // rewrite ret
        ret = OB_SUCCESS;
      }
W
wangzelin.wzl 已提交
287 288 289 290 291 292 293 294 295
    }
  }
#ifndef NDEBUG
  TRANS_LOG(INFO, "register commit retry task", K(ret), K(delay), K(tx));
#else
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "register commit retry task fail", K(ret), K(delay), K(tx));
  }
#endif
296
  ObTransTraceLog &tlog = tx.get_tlog();
O
obdev 已提交
297 298
  REC_TRANS_TRACE_EXT(&tlog, register_timeout_task,
                      OB_ID(ret), OB_SUCCESS != ret ? ret : saved_ret,
299 300
                      OB_ID(arg), delay,
                      OB_ID(ref), tx.get_ref());
W
wangzelin.wzl 已提交
301 302 303 304 305 306 307
  return ret;
}

// unregister commit retry task, handle its reference to tx correctly
int ObTransService::unregister_commit_retry_task_(ObTxDesc &tx)
{
  int ret = OB_SUCCESS;
308
  const bool is_registered = tx.commit_task_.is_registered();
W
wangzelin.wzl 已提交
309

310
  if (!is_registered) {
W
wangzelin.wzl 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324
    // task has not been scheduled, it has't ref to txDesc
    TRANS_LOG(INFO, "task canceled", K(tx));
  } else if (OB_SUCC(timer_.unregister_timeout_task(tx.commit_task_))) {
    // task has been scheduled but hasn't ran and won't ran in the future
    // release ref of TxDesc hold by task.
    tx_desc_mgr_.revert(tx);
    TRANS_LOG(TRACE, "timeout task deregistered", K(tx));
  } else if(OB_TIMER_TASK_HAS_NOT_SCHEDULED == ret) {
    // task has been scheduled and then was picked up to run
    // it must will run finally, its ref will handle by itself.
    ret = OB_SUCCESS;
    TRANS_LOG(TRACE, "timeout task not scheduled, deregistered", K(tx));
  } else if (FALSE_IT(tx.commit_task_.set_registered(false))) {
  } else {
325
    TRANS_LOG(WARN, "deregister timeout task fail", K(ret), K(tx));
W
wangzelin.wzl 已提交
326
  }
327 328 329 330
  ObTransTraceLog &tlog = tx.get_tlog();
  REC_TRANS_TRACE_EXT(&tlog, unregister_timeout_task, OB_Y(ret),
                      OB_ID(arg), is_registered,
                      OB_ID(ref), tx.get_ref());
W
wangzelin.wzl 已提交
331 332 333 334 335 336 337 338 339 340 341 342

  return ret;
}
/*
 * retry tx commit
 * 1. if tx already terminated, ignore
 * 2. send commit msg to coordinator
 * 3. register retry task again
 */
int ObTransService::handle_tx_commit_timeout(ObTxDesc &tx, const int64_t delay)
{
  int ret = OB_SUCCESS;
343
  int32_t ref_cnt = 0;
W
wangzelin.wzl 已提交
344 345
  // remember tx_id because tx maybe cleanout and reused
  // in this function's following steps.
O
obdev 已提交
346
  tx.lock_.lock();
W
wangzelin.wzl 已提交
347 348
  auto tx_id = tx.tx_id_;
  int64_t now = ObClockGenerator::getClock();
349
  bool cb_executed = false;
O
obdev 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363
  if (!tx.commit_task_.is_registered()){
    TRANS_LOG(INFO, "task canceled", K(tx));
  } else if (FALSE_IT(tx.commit_task_.set_registered(false))) {
  } else if (tx.flags_.RELEASED_) {
    TRANS_LOG(INFO, "tx released, cancel commit retry", K(tx));
  } else if (tx.state_ != ObTxDesc::State::IN_TERMINATE) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpect tx state", K(ret), K_(tx.state), K(tx));
  } else if (tx.expire_ts_ <= now) {
    TRANS_LOG(WARN, "tx has timeout", K_(tx.expire_ts), K(tx));
    handle_tx_commit_result_(tx, OB_TRANS_TIMEOUT);
  } else if (tx.commit_expire_ts_ <= now) {
    TRANS_LOG(WARN, "tx commit timeout", K_(tx.commit_expire_ts), K(tx));
    handle_tx_commit_result_(tx, OB_TRANS_STMT_TIMEOUT);
W
wangzelin.wzl 已提交
364
  } else {
O
obdev 已提交
365 366 367 368 369 370 371 372 373 374
    ObTxCommitMsg commit_msg;
    if (OB_FAIL(build_tx_commit_msg_(tx, commit_msg))) {
      TRANS_LOG(WARN, "build tx commit msg fail", K(ret), K(tx));
    } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, commit_msg))) {
      TRANS_LOG(WARN, "post commit msg fail", K(ret), K(tx));
    }
    // register again
    if (OB_FAIL(ret)) {
      if (OB_FAIL(register_commit_retry_task_(tx, POST_COMMIT_REQ_RETRY_INTERVAL))) {
        TRANS_LOG(WARN, "reregister task fail", K(ret), K(tx));
W
wangzelin.wzl 已提交
375
      }
O
obdev 已提交
376 377 378
    } else {
      if (OB_FAIL(register_commit_retry_task_(tx))) {
        TRANS_LOG(WARN, "reregister task fail", K(ret), K(tx));
W
wangzelin.wzl 已提交
379 380 381
      }
    }
  }
O
obdev 已提交
382 383 384
  ref_cnt = tx.get_ref();
  tx.lock_.unlock();
  cb_executed = tx.execute_commit_cb();
W
wangzelin.wzl 已提交
385 386 387 388
  // NOTE:
  // it not safe and meaningless to access tx after commit_cb
  // has been called, the tx may has been reused or release
  // in the commit_cb
389 390 391 392
  ObTransTraceLog &tlog = tx.get_tlog();
  REC_TRANS_TRACE_EXT(&tlog, handle_timeout, OB_Y(ret),
                      OB_ID(arg), delay,
                      OB_ID(ref), tx.get_ref());
393
  TRANS_LOG(INFO, "handle tx commit timeout", K(ret), K(tx_id), K(ref_cnt), K(cb_executed));
W
wangzelin.wzl 已提交
394 395 396 397 398 399 400 401
  return ret;
}

/*
 * handle_tx_commit_result - callback from coordinator
 */
int ObTransService::handle_tx_commit_result(const ObTransID &tx_id,
                                            const int result,
402
                                            const SCN commit_version)
W
wangzelin.wzl 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
{
  int ret = OB_SUCCESS;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx))) {
    TRANS_LOG(WARN, "cannot found tx by id", K(ret), K(tx_id), K(result));
  } else {
    bool need_cb = false;
    tx->lock_.lock();
    if (tx->state_ < ObTxDesc::State::IN_TERMINATE) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(ERROR, "unexpected tx state", K(ret),
                K_(tx->state), K(tx_id), K(result), KPC(tx));
      tx->print_trace_();
    } else if (tx->state_ > ObTxDesc::State::IN_TERMINATE) {
      TRANS_LOG(WARN, "tx has terminated", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
      tx->print_trace_();
    } else {
      need_cb = true;
      ret = handle_tx_commit_result_(*tx, result, commit_version);
    }
    tx->lock_.unlock();
    if (need_cb) { tx->execute_commit_cb(); }
  }
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  return ret;
}

/* handle_tx_commit_result_ - handle commit's result
 *
 * the result may not be final result
 *
 * result was fall into three categories:
 * 1) finished and finalized:
 *    COMMITTED / ABORTED / NOT_FOUND / TIME_OUT
 * 2) special error hint a retry is expected:
 *    eg. NOT_MASTER | SWITCH_TO_FOLLOWER | FROZEN_BLOKING etc.
 * 3) other errors : should be ignored and retry
 */
int ObTransService::handle_tx_commit_result_(ObTxDesc &tx,
                                             const int result,
446
                                             const SCN commit_version)
W
wangzelin.wzl 已提交
447 448
{
  int ret = OB_SUCCESS;
449
  int32_t ref_cnt_0 = tx.get_ref();
W
wangzelin.wzl 已提交
450
  bool commit_fin = true;
451
  ObTxDesc::State state = ObTxDesc::State::INVL;
W
wangzelin.wzl 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  int commit_out = OB_SUCCESS;
  switch (result) {
  case OB_EAGAIN:
  case OB_BLOCK_FROZEN:
    // for single log stream trans, the leader is freezing
    // and is not able to submit log right now,
    // return this result to drive and try again later.
  case OB_SWITCHING_TO_FOLLOWER_GRACEFULLY:
    // 1. callback from switch_to_follower_gracefully on local
  case OB_NOT_MASTER:
    // 1. callback from switch_to_follower_forcedly on local
    // 2. callback from commit_response (from remote)
    commit_fin = false;
    if (tx.commit_task_.is_registered()) {
      // the task maybe already registred:
      // 1. location cache stale: leader on local actually
      // 2. L--(regier)-->F-->L--(here)-->F
      if (OB_FAIL(unregister_commit_retry_task_(tx))) {
        TRANS_LOG(ERROR, "deregister timeout task fail", K(tx));
      }
    }
    if (OB_SUCC(ret)) {
      int64_t max_delay = INT64_MAX;
      if (OB_SWITCHING_TO_FOLLOWER_GRACEFULLY == result) {
        max_delay = 300 * 1000;
      }

      if (OB_FAIL(register_commit_retry_task_(tx, max_delay))) {
        commit_fin = true;
481
        state = ObTxDesc::State::ROLLED_BACK;
W
wangzelin.wzl 已提交
482 483 484 485 486 487
        commit_out = OB_TRANS_ROLLBACKED;
      }
    }
    break;
  case OB_TRANS_COMMITED:
  case OB_SUCCESS:
488
    state = ObTxDesc::State::COMMITTED;
W
wangzelin.wzl 已提交
489 490 491 492 493
    tx.commit_version_ = commit_version;
    commit_out = OB_SUCCESS;
    break;
  case OB_TRANS_KILLED:
  case OB_TRANS_ROLLBACKED:
494
    state = ObTxDesc::State::ROLLED_BACK;
W
wangzelin.wzl 已提交
495 496 497 498 499
    commit_out = result;
    break;
  case OB_TRANS_TIMEOUT:
    TX_STAT_TIMEOUT_INC
  case OB_TRANS_STMT_TIMEOUT:
500
    state = ObTxDesc::State::COMMIT_TIMEOUT;
W
wangzelin.wzl 已提交
501 502 503
    commit_out = result;
    break;
  case OB_TRANS_UNKNOWN:
504
    state = ObTxDesc::State::COMMIT_UNKNOWN;
W
wangzelin.wzl 已提交
505 506 507 508 509 510 511 512 513 514 515 516
    commit_out = result;
    break;
  default:
    commit_fin = false;
    TRANS_LOG(WARN, "recv unrecongized commit result, just ignore", K(result), K(tx));
    break;
  }
  // commit finished, cleanup
  if (commit_fin) {
    if (tx.finish_ts_ <= 0) { // maybe aborted early
      tx.finish_ts_ = ObClockGenerator::getClock();
    }
517 518 519 520
    /*
     * store_release ObTxDesc::{commit_out_, state_}
     * pair with ObTxDesc::execute_commit_cb
     */
W
wangzelin.wzl 已提交
521
    tx.commit_out_ = commit_out;
522
    ATOMIC_STORE_REL((int*)&tx.state_, (int)state);
W
wangzelin.wzl 已提交
523 524 525 526 527 528 529 530 531 532
    if (tx.commit_task_.is_registered()) {
      if (OB_FAIL(unregister_commit_retry_task_(tx))) {
        TRANS_LOG(ERROR, "deregister timeout task fail", K(tx));
      }
    }
    tx_post_terminate_(tx);
  }
#ifndef NDEBUG
  TRANS_LOG(INFO, "handle tx commit result", K(ret), K(tx), K(commit_fin), K(result));
#else
533 534 535 536
  if (OB_FAIL(ret)
      || (OB_SUCCESS != result && OB_TRANS_COMMITED != result)
      || (ObClockGenerator::getClock() - tx.commit_ts_) > 5 * 1000 * 1000) {
    TRANS_LOG(INFO, "handle tx commit result", K(ret), K(ref_cnt_0), K(tx), K(commit_fin), K(result));
W
wangzelin.wzl 已提交
537 538 539
  }
#endif
  ObTransTraceLog &tlog = tx.get_tlog();
O
obdev 已提交
540
  REC_TRANS_TRACE_EXT(&tlog, handle_tx_commit_result, OB_Y(ret),
W
wangzelin.wzl 已提交
541 542 543
                      OB_ID(arg), result,
                      OB_ID(is_finish), commit_fin,
                      OB_ID(result), commit_out,
544 545 546
                      OB_ID(state), tx.state_,
                      OB_ID(tag1), ref_cnt_0,
                      OB_ID(ref), tx.get_ref(),
W
wangzelin.wzl 已提交
547
                      OB_ID(commit_version), commit_version,
548
                      OB_ID(thread_id), GETTID());
W
wangzelin.wzl 已提交
549 550 551 552 553 554 555 556 557 558 559
  return ret;
}

int ObTransService::abort_tx_(ObTxDesc &tx, const int cause, const bool cleanup)
{
  int ret = OB_SUCCESS;
  if (tx.state_ >= ObTxDesc::State::IN_TERMINATE) {
    ret = OB_TRANS_HAS_DECIDED;
    TRANS_LOG(WARN, "try abort tx which has decided",
              K(ret), K(tx), K(cause));
  } else {
560 561 562 563
    // TODO: refactor state switch and put this to there
    if (ObTxDesc::State::IDLE == tx.state_) {
      tx.state_change_flags_.STATIC_CHANGED_ = 1;
    }
W
wangzelin.wzl 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    tx.state_ = ObTxDesc::State::IN_TERMINATE;
    tx.abort_cause_ = cause;
    abort_participants_(tx);
    tx.state_ = ObTxDesc::State::ABORTED;
    if (!cleanup) {
      invalid_registered_snapshot_(tx);
    } else {
      tx_post_terminate_(tx);
    }
  }
  TRANS_LOG(INFO, "abort tx", K(ret), K(*this), K(tx), K(cause));
  return ret;
}

void ObTransService::invalid_registered_snapshot_(ObTxDesc &tx)
{
  int ret = OB_SUCCESS;
  ARRAY_FOREACH(tx.savepoints_, i) {
    auto &it = tx.savepoints_[i];
    if (it.is_snapshot()) {
      it.rollback();
    }
  }
}

void ObTransService::registered_snapshot_clear_part_(ObTxDesc &tx)
{
  int ret = OB_SUCCESS;
  ARRAY_FOREACH(tx.savepoints_, i) {
    auto &p = tx.savepoints_[i];
    if (p.is_snapshot() && p.snapshot_->valid_) {
      p.snapshot_->parts_.reset();
    }
  }
}

/*
 * decide tx commit coordinator and participants
 *
 * choice local participant as coordinator preferentially
 */
int ObTransService::decide_tx_commit_info_(ObTxDesc &tx, ObTxPart *&coord)
{
  int ret = OB_SUCCESS;
  ObTxPartList &parts = tx.parts_;
  coord = NULL;
  tx.coord_id_.reset();
  tx.commit_parts_.reset();
  ARRAY_FOREACH(parts, i) {
    if (OB_FAIL(tx.commit_parts_.push_back(parts[i].id_))) {
      TRANS_LOG(WARN, "part id push fail", K(ret), K(tx));
    } else if (!tx.coord_id_.is_valid() && parts[i].addr_ == self_) {
      tx.coord_id_ = parts[i].id_;
      coord = &parts[i];
    } else if (OB_ISNULL(coord)) {
      coord = &parts[i];
    }
  }
  if (OB_SUCC(ret) && !tx.coord_id_.is_valid() && OB_NOT_NULL(coord)) {
    tx.coord_id_ = coord->id_;
  }

  TRANS_LOG(TRACE, "decide tx coord", K(ret), K_(tx.coord_id), K(*this), K(tx));
  return ret;
}

/*
 * get coordinator id for 2pc caller
 * it's need to remember coordinaotr in phase 2 of 2PC
 * it's required to remember coordinaotr in phase 2 of 2PC
 * case 1: xa trans gets its coord before xa prepare
 */
int ObTransService::prepare_tx_coord(ObTxDesc &tx, share::ObLSID &coord_id)
{
  // TODO: for xa
  int ret = OB_SUCCESS;
  tx.lock_.lock();
  ObTxPart *coord = NULL;
  if (OB_FAIL(decide_tx_commit_info_(tx, coord))) {
    TRANS_LOG(WARN, "fail to decide tx coordinator, tx will abort", K(ret), K(tx));
  } else if (NULL == coord) {
    // in this case, the trans may be a read-only trans.
    ret = OB_ERR_READ_ONLY_TRANSACTION;
    tx.state_ = ObTxDesc::State::COMMITTED;
    TRANS_LOG(INFO, "coord is null", K(ret), K(tx));
  } else {
    coord_id = coord->id_;
  }
  TRANS_LOG(INFO, "generate tx coord", K(ret), K(tx), K(coord_id));
  tx.lock_.unlock();
  return ret;
}

/*
 * phase one of 2pc, i.e., prepare phase
 * persist log and trans state to ensure recoverablity
 * case 1: xa prepare
 */
#define OB_TRANS_RDONLY 0
int ObTransService::prepare_tx(ObTxDesc &tx,
                               const int64_t timeout_us,
                               ObITxCallback &cb)
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
  tx.lock_.lock();
  tx.set_commit_cb(&cb);
  tx.commit_expire_ts_ = now + timeout_us;
  tx.state_ = ObTxDesc::State::SUB_PREPARING;
  ObTxSubPrepareMsg prepare_msg;
  // TODO, retry mechanism
  if (OB_FAIL(tx.commit_task_.init(&tx, this))) {
    TRANS_LOG(WARN, "fail to init timeout task", K(ret), K(tx));
  } else if (OB_FAIL(register_commit_retry_task_(tx))) {
    TRANS_LOG(WARN, "fail to register retry commit task", K(ret), K(tx));
  } else if (OB_FAIL(build_tx_sub_prepare_msg_(tx, prepare_msg))) {
    TRANS_LOG(WARN, "fail to build tx sub-prepare msg", K(ret), K(tx));
  } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, prepare_msg))) {
    TRANS_LOG(WARN, "fail to post tx sub-prepare msg", K(ret), K(tx), K(prepare_msg));
    // send msg fail won't cause commit fail, later driven by retry timer
    ret = OB_SUCCESS;
  }
  TRANS_LOG(INFO, "prepare tx", K(ret), K(tx), KP(&cb));
  tx.lock_.unlock();
  return ret;
}

int ObTransService::build_tx_sub_prepare_msg_(const ObTxDesc &tx, ObTxSubPrepareMsg &msg)
{
  int ret = OB_SUCCESS;
  msg.cluster_version_ = tx.cluster_version_;
  msg.tenant_id_ = tx.tenant_id_;
  msg.tx_id_ = tx.tx_id_;
  msg.expire_ts_ = tx.commit_expire_ts_;
  msg.receiver_ = tx.coord_id_;
  msg.sender_addr_ = self_;
  msg.sender_ = share::SCHEDULER_LS;
  msg.cluster_id_ = tx.cluster_id_;
  msg.request_id_ = tx.op_sn_;
  msg.xid_ = tx.xid_;
  if (OB_FAIL(msg.parts_.assign(tx.commit_parts_))) {
    TRANS_LOG(WARN, "fail to assign parts", K(ret), K(tx));
  }
  return ret;
}

/*
 * phase two of 2pc
 * alloc trxDesc and register transMgr
 *  if exist ? get and use
 * case 1) coordinator is local, direct function call
 * case 2) send RPC
 * finially, deregister and release trxDesc
 */
int ObTransService::end_two_phase_tx(const ObTransID &tx_id,
                                     const ObXATransID &xid,
                                     const share::ObLSID &coord,
                                     const int64_t timeout_us,
                                     const bool is_rollback,
O
obdev 已提交
723 724
                                     ObITxCallback &cb,
                                     ObTxDesc *&tx_desc)
W
wangzelin.wzl 已提交
725 726 727 728 729 730 731 732 733
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
  // TODO, alloc tx desc from tx mgr
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.alloc(tx))) {
    TRANS_LOG(WARN, "alloc tx fail", K(ret), KPC(this));
  } else if (OB_FAIL(tx_desc_mgr_.add_with_txid(tx_id, *tx))) {
    TRANS_LOG(WARN, "add tx to txMgr fail", K(ret), K(tx));
O
obdev 已提交
734 735
    tx_desc_mgr_.revert(*tx);
    tx = NULL;
W
wangzelin.wzl 已提交
736
  } else {
O
obdev 已提交
737
    tx->tenant_id_ = MTL_ID();
W
wangzelin.wzl 已提交
738 739 740 741 742 743 744 745 746
    tx->commit_expire_ts_ = now + timeout_us;
    tx->coord_id_ = coord;
    tx->xid_ = xid;
    tx->set_commit_cb(&cb);
    if (OB_FAIL(tx->commit_task_.init(tx, this))) {
      TRANS_LOG(WARN, "fail to init timeout task", K(ret), K(*tx));
    } else if (OB_FAIL(register_commit_retry_task_(*tx))) {
      TRANS_LOG(WARN, "fail to register retry commit task", K(ret), K(*tx));
    } else {
O
obdev 已提交
747
      int tmp_ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
748 749 750 751 752 753
      if (is_rollback) {
        // two phase rollback
        ObTxSubRollbackMsg msg;
        tx->state_ = ObTxDesc::State::SUB_ROLLBACKING;
        if (OB_FAIL(build_tx_sub_rollback_msg_(*tx, msg))) {
          TRANS_LOG(WARN, "fail to build tx sub-rollback msg", K(ret), K(*tx));
O
obdev 已提交
754 755
        } else if (OB_SUCCESS != (tmp_ret = rpc_->post_msg(tx->coord_id_, msg))) {
          TRANS_LOG(WARN, "fail to post tx sub-rollback msg", K(tmp_ret), K(*tx), K(msg));
W
wangzelin.wzl 已提交
756 757 758 759 760 761 762
        }
      } else {
        // two phase commit
        ObTxSubCommitMsg msg;
        tx->state_ = ObTxDesc::State::SUB_COMMITTING;
        if (OB_FAIL(build_tx_sub_commit_msg_(*tx, msg))) {
          TRANS_LOG(WARN, "fail to build tx sub-commit msg", K(ret), K(*tx));
O
obdev 已提交
763 764
        } else if (OB_SUCCESS != (tmp_ret = rpc_->post_msg(tx->coord_id_, msg))) {
          TRANS_LOG(WARN, "fail to post tx sub-commit msg", K(tmp_ret), K(*tx), K(msg));
W
wangzelin.wzl 已提交
765 766 767
        }
      }
    }
O
obdev 已提交
768 769 770 771 772 773 774
    if (OB_SUCCESS != ret && OB_NOT_NULL(tx)) {
      tx_desc_mgr_.remove(*tx);
      tx_desc_mgr_.revert(*tx);
      tx = NULL;
    } else {
      tx_desc = tx;
    }
W
wangzelin.wzl 已提交
775
  }
O
obdev 已提交
776
  TRANS_LOG(INFO, "end two phase tx", K(ret), K(tx_id), K(is_rollback), K(xid), KP(&cb));
W
wangzelin.wzl 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  return ret;
}

int ObTransService::build_tx_sub_commit_msg_(const ObTxDesc &tx, ObTxSubCommitMsg &msg)
{
  int ret = OB_SUCCESS;
  msg.tenant_id_ = tenant_id_;
  msg.tx_id_ = tx.tx_id_;
  msg.receiver_ = tx.coord_id_;
  msg.sender_addr_ = self_;
  msg.sender_ = share::SCHEDULER_LS;
  msg.xid_ = tx.xid_;
  msg.cluster_version_ = GET_MIN_CLUSTER_VERSION();
  // invalid
  msg.cluster_id_ = GCONF.cluster_id;
  // TODO, a special request id
  msg.request_id_ = tx.op_sn_;
  return ret;
}

int ObTransService::build_tx_sub_rollback_msg_(const ObTxDesc &tx, ObTxSubRollbackMsg &msg)
{
  int ret = OB_SUCCESS;
  msg.tenant_id_ = tenant_id_;
  msg.tx_id_ = tx.tx_id_;
  msg.receiver_ = tx.coord_id_;
  msg.sender_addr_ = self_;
  msg.sender_ = share::SCHEDULER_LS;
  msg.xid_ = tx.xid_;
  msg.cluster_version_ = GET_MIN_CLUSTER_VERSION();
  // invalid
  msg.cluster_id_ = GCONF.cluster_id;
  // TODO, a special request id
  msg.request_id_ = tx.op_sn_;
  return ret;
}

int ObTransService::interrupt(ObTxDesc &tx, int cause)
{
  int ret = OB_SUCCESS;
  TRANS_LOG(INFO, "start interrupt tx", KPC(this), K(tx.tx_id_), K(cause));
  bool busy_wait = false;
  {
    ObSpinLockGuard guard(tx.lock_);
    if (tx.flags_.BLOCK_) {
      tx.flags_.INTERRUPTED_ = true;
      TRANS_LOG(INFO, "will busy wait tx quit from block state", K(tx));
      busy_wait = true;
    }
  }
  while (busy_wait) {
    if (tx.flags_.BLOCK_) {
      ob_usleep(500);
    } else {
      ObSpinLockGuard guard(tx.lock_);
      tx.flags_.INTERRUPTED_ = false;
      break;
    }
  }
O
obdev 已提交
836
  TRANS_LOG(INFO, "interrupt tx done", KR(ret), KPC(this), K(cause));
W
wangzelin.wzl 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
  return ret;
}

/*
 * participant keepalive
 * this has two effects:
 * 1) GC participant: if tx terminated, participant will abort it self
 * 2) fast abort transaction: if participant report itself failure,
 *    whole transaction will terminated from top to bottom
 */

int ObTransService::handle_trans_keepalive(const ObTxKeepaliveMsg &msg, ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  const ObTransID &tx_id = msg.tx_id_;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx)) &&
      OB_ENTRY_NOT_EXIST != ret) {
    TRANS_LOG(WARN, "get tx fail", K(ret), K(tx_id), K(msg));
  } else if (OB_ISNULL(tx)) {
    ret = OB_TRANS_CTX_NOT_EXIST;
858 859 860 861
  } else if (tx->is_committed() && tx_id == tx->tx_id_) {
    ret = OB_TRANS_COMMITED;
  } else if (tx->is_rollbacked() && tx_id == tx->tx_id_) {
    ret = OB_TRANS_ROLLBACKED;
W
wangzelin.wzl 已提交
862
  } else if (OB_SUCCESS != msg.status_) {
863
    TRANS_LOG(WARN, "tx participant in failed status", K(msg));
W
wangzelin.wzl 已提交
864
  }
O
obdev 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877
  ObTxKeepaliveRespMsg resp;
  resp.cluster_version_ = GET_MIN_CLUSTER_VERSION();
  resp.tenant_id_ = tenant_id_;
  resp.cluster_id_ = GCONF.cluster_id;
  resp.request_id_ = ObClockGenerator::getClock();
  resp.tx_id_ = tx_id;
  resp.sender_addr_ = self_;
  resp.sender_ = share::SCHEDULER_LS;
  resp.receiver_ = msg.sender_;
  resp.status_ = ret;
  if (OB_FAIL(rpc_->post_msg(resp.receiver_, resp))) {
    TRANS_LOG(WARN, "post tx keepalive resp fail", K(ret), K(resp), KPC(this));
  }
W
wangzelin.wzl 已提交
878
  result.reset();
O
obdev 已提交
879
  result.init(ret, resp.get_timestamp());
W
wangzelin.wzl 已提交
880 881 882 883 884 885 886 887 888
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  if (REACH_TIME_INTERVAL(10 * 1000 * 1000)) {
    TRANS_LOG(INFO, "handle trans keepalive", K(ret), K(msg));
  }
  return ret;
}

O
obdev 已提交
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
int ObTransService::handle_trans_keepalive_response(const ObTxKeepaliveRespMsg &msg, obrpc::ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ObPartTransCtx *ctx = NULL;
  const ObTransID &tx_id = msg.tx_id_;
  const share::ObLSID &ls_id = msg.receiver_;
  if (OB_FAIL(get_tx_ctx_(ls_id, tx_id, ctx))) {
    TRANS_LOG(WARN, "get tx ctx fail", K(tx_id), K(ls_id));
  } else {
    (void)ctx->tx_keepalive_response_(msg.status_);
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  return ret;
}

W
wangzelin.wzl 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
int ObTransService::find_parts_after_sp_(ObTxDesc &tx,
                                         ObTxPartRefList &parts,
                                         const int64_t scn)
{
  int ret = OB_SUCCESS;
  ARRAY_FOREACH(tx.parts_, i) {
    if (tx.parts_.at(i).last_scn_ > scn &&
        !tx.parts_.at(i).is_clean()) {
      if (OB_FAIL(parts.push_back(tx.parts_.at(i)))) {
        TRANS_LOG(WARN, "push back participant failed", K(ret));
      }
    }
  }
  return ret;
}

int ObTransService::get_read_store_ctx(const ObTxReadSnapshot &snapshot,
                                       const bool read_latest,
                                       const int64_t lock_timeout,
                                       ObStoreCtx &store_ctx)
{
  int ret = OB_SUCCESS;
  auto ls_id = store_ctx.ls_id_;
  if (!ls_id.is_valid() || !snapshot.valid_) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid ls_id or invalid snapshot store_ctx", K(ret), K(snapshot), K(store_ctx), K(lbt()));
  } else if (snapshot.is_special()) {
    if (OB_FAIL(validate_snapshot_version_(snapshot.core_.version_,
                                           store_ctx.timeout_,
                                           *store_ctx.ls_))) {
      TRANS_LOG(WARN, "invalid speficied snapshot", K(ret), K(snapshot), K(store_ctx));
    }
  } else if (snapshot.is_ls_snapshot() && snapshot.snapshot_lsid_ != ls_id) {
      // try to access differ logstream with snapshot from another logstream
      // FIXME: return code should hint to indicate caller to make sens
      ret = OB_NOT_SUPPORTED;
      TRANS_LOG(WARN, "use a local snapshot to access other logstream",
                K(ret), K(store_ctx), K(snapshot));
  }

  bool check_readable_ok = false;
  auto snap_tx_id = snapshot.core_.tx_id_;
  ObPartTransCtx *tx_ctx = NULL;
  if (OB_SUCC(ret) && snap_tx_id.is_valid()) {
    // inner tx read, we verify txCtx's status
    bool exist = false;
    TX_PARTS_CONTAIN_(snapshot.parts_, left_, ls_id, exist);
    if (exist || read_latest) {
      if (OB_FAIL(get_tx_ctx_(ls_id, store_ctx.ls_, snap_tx_id, tx_ctx))) {
        if (OB_TRANS_CTX_NOT_EXIST == ret && !exist) {
          ret = OB_SUCCESS;
        } else {
O
obdev 已提交
960 961 962
          if (!MTL_IS_PRIMARY_TENANT()) {
            ret = OB_STANDBY_READ_ONLY;
          }
W
wangzelin.wzl 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
          TRANS_LOG(WARN, "get tx ctx fail",
                    K(ret), K(store_ctx), K(snapshot), K(ls_id), K(exist), K(read_latest));
        }
      } else if (OB_FAIL(tx_ctx->check_status())) {
        TRANS_LOG(WARN, "check status fail", K(ret), K(store_ctx), KPC(tx_ctx));
      } else {
        check_readable_ok = true;
      }
      if (OB_FAIL(ret) && OB_NOT_NULL(tx_ctx)) {
        revert_tx_ctx_(store_ctx.ls_, tx_ctx);
        tx_ctx = NULL;
      }
    }
  }

  // need continue to check replica's readability
  if (OB_SUCC(ret) && !check_readable_ok &&
      OB_FAIL(check_replica_readable_(snapshot.core_.version_,
                                      snapshot.core_.elr_,
                                      snapshot.source_,
                                      ls_id,
                                      store_ctx.timeout_,
                                      *store_ctx.ls_))) {
    TRANS_LOG(WARN, "replica not readable", K(ret), K(snapshot), K(ls_id), K(store_ctx));
  }

  // setup tx_table_guard
  ObTxTableGuard tx_table_guard;
  if (OB_SUCC(ret) &&
      OB_FAIL(get_tx_table_guard_(store_ctx.ls_, ls_id, tx_table_guard))) {
    TRANS_LOG(WARN, "get tx_table_guard fail", K(ret), K(ls_id), K(store_ctx));
  }

  // fail, rollback
  if (OB_FAIL(ret)) {
    if (OB_NOT_NULL(tx_ctx)) {
      revert_tx_ctx_(store_ctx.ls_, tx_ctx);
      tx_ctx = NULL;
    }
  }

  // go well, commit
  if (OB_SUCC(ret)) {
    store_ctx.mvcc_acc_ctx_.init_read(
     tx_ctx,
     (tx_ctx ? tx_ctx->get_memtable_ctx() : NULL),
     tx_table_guard,
     snapshot.core_,
     store_ctx.timeout_,
1012 1013
     lock_timeout,
     snapshot.is_weak_read()
W
wangzelin.wzl 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    );
    update_max_read_ts_(tenant_id_, ls_id, snapshot.core_.version_);
  }

  TRANS_LOG(TRACE, "get-read-store-ctx", K(ret), K(store_ctx), K(read_latest), K(snapshot));
  return ret;
}



1024
int ObTransService::get_read_store_ctx(const SCN snapshot_version,
W
wangzelin.wzl 已提交
1025 1026 1027 1028
                                       const int64_t lock_timeout,
                                       ObStoreCtx &store_ctx)
{
  int ret = OB_SUCCESS;
1029
  if (!snapshot_version.is_valid()) {
W
wangzelin.wzl 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid speficied snapshot", K(ret), K(snapshot_version));
  } else {
    ObTxReadSnapshot snapshot;
    snapshot.valid_ = true;
    snapshot.core_.version_ = snapshot_version;
    snapshot.source_ = ObTxReadSnapshot::SRC::SPECIAL;
    ret = get_read_store_ctx(snapshot, false, lock_timeout, store_ctx);
  }
  TRANS_LOG(INFO, "get-read-store-ctx for specified snapshot", K(ret), K(snapshot_version), K(store_ctx));
  return ret;
}

int ObTransService::get_write_store_ctx(ObTxDesc &tx,
                                        const ObTxReadSnapshot &snapshot,
1045
                                        const concurrent_control::ObWriteFlag write_flag,
W
wangzelin.wzl 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                                        storage::ObStoreCtx &store_ctx)
{
  int ret = OB_SUCCESS;
  const share::ObLSID &ls_id = store_ctx.ls_id_;
  ObPartTransCtx *tx_ctx = NULL;
  const int64_t data_scn = ObSequence::inc_and_get_max_seq_no();
  ObTxSnapshot snap = snapshot.core_;
  ObTxTableGuard tx_table_guard;
  bool access_started = false;
  if (tx.access_mode_ == ObTxAccessMode::RD_ONLY) {
    ret = OB_ERR_READ_ONLY_TRANSACTION;
    TRANS_LOG(WARN, "tx is readonly", K(ret), K(ls_id), K(tx), KPC(this));
  } else if (!snapshot.valid_) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "snapshot invalid", K(ret), K(snapshot));
  } else if (snapshot.is_none_read() && OB_FAIL(acquire_local_snapshot_(ls_id, snap.version_))) {
    TRANS_LOG(WARN, "acquire ls snapshot for mvcc write fail", K(ret), K(ls_id));
  } else if (snapshot.is_ls_snapshot() && snapshot.snapshot_lsid_ != ls_id) {
    ret = OB_NOT_SUPPORTED;
    TRANS_LOG(WARN, "use ls snapshot access another ls", K(ret), K(snapshot), K(ls_id));
  } else if (OB_FAIL(acquire_tx_ctx(ls_id, tx, tx_ctx, store_ctx.ls_))) {
    TRANS_LOG(WARN, "acquire tx ctx fail", K(ret), K(tx), K(ls_id), KPC(this));
  } else if (OB_FAIL(tx_ctx->start_access(tx, data_scn))) {
    TRANS_LOG(WARN, "tx ctx start access fail", K(ret), K(tx_ctx), K(ls_id), KPC(this));
  } else if (FALSE_IT(access_started = true)) {
  } else if (OB_FAIL(get_tx_table_guard_(store_ctx.ls_, ls_id, tx_table_guard))) {
    TRANS_LOG(WARN, "acquire tx table guard fail", K(ret), K(tx), K(ls_id), KPC(this));
  }
  // fail, rollback
  if (OB_FAIL(ret)) {
O
obdev 已提交
1076 1077 1078
    if (!MTL_IS_PRIMARY_TENANT()) {
      ret = OB_STANDBY_READ_ONLY;
    }
W
wangzelin.wzl 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    if (OB_NOT_NULL(tx_ctx)) {
      if (access_started) { tx_ctx->end_access(); }
      revert_tx_ctx_(store_ctx.ls_, tx_ctx);
      tx_ctx = NULL;
    }
  }
  // succ, commit
  if (OB_SUCC(ret)) {
    store_ctx.mvcc_acc_ctx_.init_write(
      *tx_ctx,
      *tx_ctx->get_memtable_ctx(),
      tx.tx_id_,
      data_scn,
      tx,
      tx_table_guard,
      snap,
      store_ctx.timeout_,
1096 1097
      tx.lock_timeout_us_,
      write_flag
W
wangzelin.wzl 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    );
    if (tx.get_active_ts() <= 0) {
      tx.active_ts_ = ObClockGenerator::getClock();
    }
    /* NOTE: some write with adjoint reads:
     * eg. insert row to a table with primary key will _check_
     * rowkey-exist before do insert (this check is a read).
     *
     * so it's required to update `max_read_ts` for these write
     */
    update_max_read_ts_(tenant_id_, ls_id, snap.version_);
  }
  TRANS_LOG(TRACE, "get-write-store-ctx", K(ret),
            K(store_ctx), KPC(this), K(tx), K(snapshot), K(lbt()));
  return ret;
}

/*
 * the get here imply `get if exist` or `create if should`
 * create predication:
 *      the create must ensure current replica is leader
 *      at the time of create finish
 */
int ObTransService::acquire_tx_ctx(const share::ObLSID &ls_id, const ObTxDesc &tx, ObPartTransCtx *&ctx, ObLS *ls)
{
  int ret = OB_SUCCESS;
  bool exist = false;
  TX_PARTS_CONTAIN_(tx.parts_, id_, ls_id, exist);
  if (exist) {
    if (OB_FAIL(get_tx_ctx_(ls_id, ls, tx.tx_id_, ctx))) {
O
obdev 已提交
1128
      TRANS_LOG(WARN, "get tx ctx fail", K(ret), K(ls_id), K(tx));
W
wangzelin.wzl 已提交
1129
      if (ret == OB_TRANS_CTX_NOT_EXIST) {
O
obdev 已提交
1130
        TRANS_LOG(WARN, "participant lost update", K(ls_id), K_(tx.tx_id));
W
wangzelin.wzl 已提交
1131 1132 1133
      }
    }
  } else if (OB_FAIL(create_tx_ctx_(ls_id, ls, tx, ctx))) {
O
obdev 已提交
1134
    TRANS_LOG(WARN, "create tx ctx fail", K(ret), K(ls_id), K(tx));
W
wangzelin.wzl 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
  }
  TRANS_LOG(TRACE, "acquire tx ctx", K(ret), K(*this), K(ls_id), K(tx), KP(ctx));
  return ret;
}

// plain create
int ObTransService::get_tx_ctx_(const share::ObLSID &ls_id,
                                ObLS *ls,
                                const ObTransID &tx_id,
                                ObPartTransCtx *&ctx)
{
  int ret = OB_SUCCESS;
  if (OB_NOT_NULL(ls)) {
    ret = ls->get_tx_ctx(tx_id, false, ctx);
  } else {
    ret = tx_ctx_mgr_.get_tx_ctx(ls_id, tx_id, false, ctx);
  }

  TRANS_LOG(TRACE, "get tx ctx", K(ret), K(tx_id), K(ls_id), KP(ctx), KP(ls));
  return ret;
}

int ObTransService::get_tx_ctx_(const share::ObLSID &ls_id,
                                const ObTransID &tx_id,
                                ObPartTransCtx *&ctx)
{ return get_tx_ctx_(ls_id, NULL, tx_id, ctx); }

int ObTransService::revert_tx_ctx_(ObLS* ls, ObPartTransCtx *ctx)
{
  int ret = OB_SUCCESS;
  if (OB_NOT_NULL(ls)) {
    ret = ls->revert_tx_ctx(ctx);
  } else {
    ret = tx_ctx_mgr_.revert_tx_ctx(ctx);
  }

  TRANS_LOG(TRACE, "revert tx ctx", KP(ctx));
  return ret;
}

int ObTransService::revert_tx_ctx_(ObPartTransCtx *ctx)
{ return revert_tx_ctx_(NULL, ctx); }

/*
 * create fresh tranaction ctx
 * 1) allocate
 * 2) initialize
 */
int ObTransService::create_tx_ctx_(const share::ObLSID &ls_id,
                                   ObLS *ls,
                                   const ObTxDesc &tx,
                                   ObPartTransCtx *&ctx)
{
  int ret = OB_SUCCESS;
  bool existed = false;
1190
  int64_t epoch = 0;
1191
  ObTxCreateArg arg(false,  /* for_replay */
W
wangzelin.wzl 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
                    tx.tenant_id_,
                    tx.tx_id_,
                    ls_id,
                    tx.cluster_id_,
                    tx.cluster_version_,
                    tx.sess_id_, /*session_id*/
                    tx.addr_,
                    tx.get_expire_ts(),
                    this);
  ret = OB_NOT_NULL(ls) ?
    ls->create_tx_ctx(arg, existed, ctx) :
    tx_ctx_mgr_.create_tx_ctx(arg, existed, ctx);
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "get tx ctx from mgr fail", K(ret), K(tx.tx_id_), K(ls_id), K(tx), K(arg));
    ctx = NULL;
O
obdev 已提交
1207 1208
  } else if (!tx.xid_.empty()) {
    ctx->exec_info_.xid_ = tx.xid_;
W
wangzelin.wzl 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
  }
  TRANS_LOG(TRACE, "create tx ctx", K(ret), K(ls_id), K(tx));
  return ret;
}

int ObTransService::create_tx_ctx_(const share::ObLSID &ls_id,
                                   const ObTxDesc &tx,
                                   ObPartTransCtx *&ctx)
{ return create_tx_ctx_(ls_id, NULL, tx, ctx); }

void ObTransService::fetch_cflict_tx_ids_from_mem_ctx_to_desc_(ObMvccAccessCtx &acc_ctx)// for deadlock
{
  // merge all ctx(in every logstream)'s conflict trans ids to trans_desc
  int ret = OB_SUCCESS;
  common::ObArray<ObTransIDAndAddr> array;
  if (OB_ISNULL(acc_ctx.mem_ctx_)) {
    ret = OB_BAD_NULL_ERROR;
    DETECT_LOG(ERROR, "mem_ctx_ on acc_ctx is null", KR(ret), K(array));
  } else if (OB_FAIL(acc_ctx.mem_ctx_->get_conflict_trans_ids(array))) {
    DETECT_LOG(WARN, "get conflict ids from mem_ctx failed", KR(ret), K(acc_ctx));
  } else if (FALSE_IT(acc_ctx.mem_ctx_->reset_conflict_trans_ids())) {
  } else if (OB_FAIL(acc_ctx.tx_desc_->merge_conflict_txs(array))) {
    DETECT_LOG(WARN, "fail to merge ctx conflict trans array", KR(ret), K(acc_ctx));
  } else {
    DETECT_LOG(TRACE, "fetch conflict ids from mem_ctx to desc", KR(ret), K(array));
  }
}

int ObTransService::revert_store_ctx(storage::ObStoreCtx &store_ctx)
{
  int ret = OB_SUCCESS;
  auto &acc_ctx = store_ctx.mvcc_acc_ctx_;
  auto *tx_ctx = acc_ctx.tx_ctx_;
  if (acc_ctx.is_read()) {
    if (OB_NOT_NULL(tx_ctx)) {
      acc_ctx.tx_ctx_ = NULL;
      revert_tx_ctx_(store_ctx.ls_, tx_ctx);
    }
  } else if (acc_ctx.is_write()) {
    if (OB_ISNULL(tx_ctx)) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(ERROR, "write access but tx ctx is NULL", K(ret), K(store_ctx));
    } else {
      /*
       * record transaction participant info
       */
      ObTxDesc *tx = acc_ctx.tx_desc_;
      acc_ctx.tx_ctx_ = NULL;
      if (tx->exec_info_reap_ts_ == 0) {
        tx->exec_info_reap_ts_ = ObSequence::get_max_seq_no();
      }
      ObTxPart p;
      p.id_         = tx_ctx->ls_id_;
      p.addr_       = self_;
      p.epoch_      = tx_ctx->epoch_;
      p.first_scn_  = tx_ctx->first_scn_;
      p.last_scn_   = tx_ctx->last_scn_;
      if (OB_FAIL(tx->update_part(p))) {
        TRANS_LOG(WARN, "append part fail", K(ret), K(p), KPC(tx_ctx));
      }
      (void) fetch_cflict_tx_ids_from_mem_ctx_to_desc_(acc_ctx);
      tx_ctx->end_access();
      revert_tx_ctx_(store_ctx.ls_, tx_ctx);
    }
  } else {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(ERROR, "unexpected store ctx type", K(ret), K(store_ctx));
  }
  TRANS_LOG(TRACE, "revert store ctx", K(ret), K(*this), K(lbt()));
  return ret;
}

/*
 * used to validate specified snapshot version
 * precondition: version <= current gts value
 */
1285
int ObTransService::validate_snapshot_version_(const SCN snapshot,
W
wangzelin.wzl 已提交
1286 1287 1288 1289
                                               const int64_t expire_ts,
                                               ObLS &ls)
{
  int ret = OB_SUCCESS;
1290
  const SCN ls_weak_read_ts = ls.get_ls_wrs_handler()->get_ls_weak_read_ts();
W
wangzelin.wzl 已提交
1291 1292 1293 1294
  if (snapshot <= tx_version_mgr_.get_max_commit_ts(false) ||
      snapshot <= tx_version_mgr_.get_max_read_ts() ||
      snapshot <= ls_weak_read_ts) {
  } else {
1295
    SCN gts;
1296
    const MonotonicTs stc_ahead = get_req_receive_mts_() - MonotonicTs(GCONF._ob_get_gts_ahead_interval);
W
wangzelin.wzl 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    MonotonicTs tmp_receive_gts_ts(0);
    do {
      ret = ts_mgr_->get_gts(tenant_id_, stc_ahead, NULL, gts, tmp_receive_gts_ts);
      if (ret == OB_EAGAIN) {
        if (expire_ts <= ObClockGenerator::getClock()) {
          ret = OB_TIMEOUT;
        } else {
          ob_usleep(100);
        }
      } else if (OB_FAIL(ret)) {
        TRANS_LOG(WARN, "get gts fail", KR(ret));
1308
      } else if (!gts.is_valid()) {
W
wangzelin.wzl 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        ret = OB_ERR_UNEXPECTED;
        TRANS_LOG(WARN, "get gts fail", K(gts));
      } else if (snapshot > gts) {
        ret = OB_INVALID_QUERY_TIMESTAMP;
        TRANS_LOG(WARN, "validate snapshot version fail", K(snapshot), K(gts));
      } else {
        TRANS_LOG(DEBUG, "snapshot is valid", K(snapshot), K(gts));
      }
    } while (ret == OB_EAGAIN);
  }
  TRANS_LOG(TRACE, "validate snapshot version",
      K(ret), K(snapshot), K(expire_ts), K(ls_weak_read_ts));
  return ret;
}

/*
 * check ls's readable snapshot
 *
 * here introduce a concept named 'replica_readable_version'
 *
 * it was updated by:
 * 1. tx commit:
 *    on Leader: on pre_commit
 *    on Sync Replica: on pre_commit
 * 2. transaction log replay:
 *    on Follower replica
 * 3. and by read on Leader or Sync Replica
 *
 * with this concept, we can verify replica readable as
 * compare with replica_readable_snapshot:
 * 1. v = my_read_snapshot_version
 * 2. if v <= replica_readble_snapshot return OK, otherwise
 * 3. check is_leader or sync_replica of ls
 *    if so, update replica_readable_snapshot = v and return OK, otherwise
 * 4. return OB_REPLICA_NOT_READABLE
 */
O
obdev 已提交
1345
int ObTransService::check_replica_readable_(const SCN &snapshot,
W
wangzelin.wzl 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354
                                            const bool elr,
                                            const ObTxReadSnapshot::SRC src,
                                            const share::ObLSID &ls_id,
                                            const int64_t expire_ts,
                                            ObLS &ls)
{
  int ret = OB_SUCCESS;
  bool leader = false;
  int64_t epoch = 0;
O
obdev 已提交
1355
  bool readable = check_ls_readable_(ls, snapshot);
W
wangzelin.wzl 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  if (!readable) {
    if (OB_FAIL(ls.get_tx_svr()->get_tx_ls_log_adapter()->get_role(leader, epoch))) {
      TRANS_LOG(WARN, "get replica status fail", K(ls_id));
    } else if (leader || is_sync_replica_(ls_id)) {
      ret = OB_SUCCESS;
    } else if (ObTxReadSnapshot::SRC::SPECIAL == src ||
               ObTxReadSnapshot::SRC::WEAK_READ_SERVICE == src) {
      // to compatible with SQL's retry-logic, trigger re-choose replica
      ret = OB_REPLICA_NOT_READABLE;
    } else {
      if (OB_SUCC(wait_follower_readable_(ls, expire_ts, snapshot))) {
        TRANS_LOG(INFO, "read from follower", K(snapshot),  K(snapshot), K(ls));
      } else {
        ret = OB_NOT_MASTER;
      }
    }
  }
  TRANS_LOG(TRACE, "check replica readable", K(ret), K(snapshot), K(ls_id));
  return ret;
}

O
obdev 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
bool ObTransService::check_ls_readable_(ObLS &ls, const SCN &snapshot)
{
  int ret = OB_SUCCESS;
  bool readable = false;
  SCN scn;
  if (MTL_IS_PRIMARY_TENANT()) {
    readable = snapshot <= ls.get_ls_wrs_handler()->get_ls_weak_read_ts();
  } else if (OB_FAIL(ls.get_ls_replica_readable_scn(scn))) {
    TRANS_LOG(WARN, "get ls replica readable scn fail", K(ret), K(ls.get_ls_id()));
  } else {
    readable = snapshot <= scn;
    if (!readable) {
      TRANS_LOG(INFO, "check replica readable fail", K(ret), K(snapshot), K(scn));
    }
  }
  return readable;
}

W
wangzelin.wzl 已提交
1395 1396
int ObTransService::wait_follower_readable_(ObLS &ls,
                                            const int64_t expire_ts,
O
obdev 已提交
1397
                                            const SCN &snapshot)
W
wangzelin.wzl 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
{
  int ret = OB_REPLICA_NOT_READABLE;
  int64_t compare_timeout = 0;
  const uint64_t tenant_id = MTL_ID();
  omt::ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
  if (tenant_config.is_valid()) {
    compare_timeout = tenant_config->_follower_snapshot_read_retry_duration;
  }
  if (compare_timeout > 0) {
    int64_t compare_expired_time = ObClockGenerator::getClock() + compare_timeout;
    int64_t stmt_timeout = expire_ts - ObClockGenerator::getClock();
    int64_t retry_interval = 0;
    do {
      if (OB_UNLIKELY(ObClockGenerator::getClock() >= expire_ts)) {
        ret = OB_TIMEOUT;
O
obdev 已提交
1413
      } else if (check_ls_readable_(ls, snapshot)) {
W
wangzelin.wzl 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
        TRANS_LOG(WARN, "read from follower", K(snapshot), K(ls.get_ls_id()), K(tenant_id));
        ret = OB_SUCCESS;
      } else if (ObClockGenerator::getClock() >= compare_expired_time) {
        break;
      } else if (OB_REPLICA_NOT_READABLE == ret) {
        stmt_timeout = expire_ts - ObClockGenerator::getClock();
        compare_timeout = compare_expired_time - ObClockGenerator::getClock();
        retry_interval = MIN(MIN3(GCONF.weak_read_version_refresh_interval, compare_timeout, stmt_timeout), 100000);
        ob_usleep(static_cast<int>(retry_interval));
      } else {
        // do nothing
      }
    } while (OB_REPLICA_NOT_READABLE == ret);
  }
  return ret;
}

1431 1432
MonotonicTs ObTransService::get_req_receive_mts_()
{
O
obdev 已提交
1433
  /*
1434 1435 1436 1437 1438 1439 1440 1441
  MonotonicTs mts;
  const rpc::ObRequest *req = THIS_WORKER.get_cur_request();
  if (NULL != req && req->get_receive_mts().is_valid()) {
    mts = req->get_receive_mts();
  } else {
    mts = MonotonicTs::current_time();
  }
  return mts;
O
obdev 已提交
1442 1443
  */
  return MonotonicTs::current_time();
1444 1445
}

W
wangzelin.wzl 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
/*
 * collect trans exec result
 */
int ObTransService::collect_tx_exec_result(ObTxDesc &tx,
                                           ObTxExecResult &result)
{
  int ret = OB_SUCCESS;
  ret = get_tx_exec_result(tx, result);
  TRANS_LOG(TRACE, "collect tx exec result", K(ret), K(tx), K(result), K(lbt()));
  return ret;
}

int ObTransService::build_tx_commit_msg_(const ObTxDesc &tx, ObTxCommitMsg &msg)
{
  int ret = OB_SUCCESS;
  msg.cluster_version_ = tx.cluster_version_;
  msg.tenant_id_ = tx.tenant_id_;
  msg.tx_id_ = tx.tx_id_;
  msg.expire_ts_ = tx.commit_expire_ts_;
  msg.receiver_ = tx.coord_id_;
  msg.sender_addr_ = self_;
  msg.sender_ = share::SCHEDULER_LS;
  msg.cluster_id_ = tx.cluster_id_;
C
chinaxing 已提交
1469
  msg.app_trace_info_ = tx.trace_info_.get_app_trace_info();
W
wangzelin.wzl 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  msg.request_id_ = tx.op_sn_;
  if (OB_FAIL(msg.parts_.assign(tx.commit_parts_))) {
    TRANS_LOG(WARN, "assign parts fail", K(ret), K(tx));
  }
  return ret;
}

int ObTransService::abort_participants_(const ObTxDesc &tx_desc)
{
  int ret = OB_SUCCESS;
  const ObTxPartList &parts = tx_desc.parts_;
  // ignore ret
  ARRAY_FOREACH_NORET(parts, idx) {
    const ObTxPart &p = parts.at(idx);
    if (OB_FAIL(post_tx_abort_part_msg_(tx_desc, p))) {
      TRANS_LOG(WARN, "post tx abort part msg", K(ret), K(tx_desc), K(p));
    }
  }
  return ret;
}

int ObTransService::acquire_local_snapshot_(const share::ObLSID &ls_id,
1492
                                            SCN &snapshot)
W
wangzelin.wzl 已提交
1493 1494
{
  int ret = OB_SUCCESS;
1495
  int64_t epoch = 0;
W
wangzelin.wzl 已提交
1496
  bool leader = false;
1497
  SCN snapshot0;
W
wangzelin.wzl 已提交
1498 1499 1500 1501 1502 1503 1504 1505
  ObLSTxCtxMgr *ls_tx_ctx_mgr = NULL;
  if (OB_FAIL(tx_ctx_mgr_.get_ls_tx_ctx_mgr(ls_id, ls_tx_ctx_mgr))) {
    TRANS_LOG(WARN, "get ls_tx_ctx_mgr fail", K(ret), K(ls_id));
  } else if (!ls_tx_ctx_mgr->in_leader_serving_state()) {
    ret = OB_NOT_MASTER;
    // XXX In standby cluster mode, the failure to call acquire_local_snapshot_ is an
    // normal situation, no error log needs to be printed
    // TRANS_LOG(WARN, "check ls tx service leader serving state fail", K(ret), K(ls_id), K(ret));
O
obdev 已提交
1506 1507 1508 1509
  } else if (OB_FAIL(ls_tx_ctx_mgr->get_ls_log_adapter()->get_role(leader, epoch))) {
    TRANS_LOG(WARN, "get replica role fail", K(ret), K(ls_id));
  } else if (!leader) {
    ret = OB_NOT_MASTER;
1510
  } else if (FALSE_IT(snapshot0 = tx_version_mgr_.get_max_commit_ts(true))) {
O
obdev 已提交
1511 1512
  } else if (!snapshot0.is_valid_and_not_min()) {
    ret = OB_EAGAIN;
W
wangzelin.wzl 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
  } else {
    snapshot = snapshot0;
  }
  if (OB_NOT_NULL(ls_tx_ctx_mgr)) {
    tx_ctx_mgr_.revert_ls_tx_ctx_mgr(ls_tx_ctx_mgr);
  }
  TRANS_LOG(TRACE, "acquire local snapshot", K(ret), K(ls_id), K(snapshot));
  return ret;
}

int ObTransService::sync_acquire_global_snapshot_(ObTxDesc &tx,
                                                  const int64_t expire_ts,
1525
                                                  SCN &snapshot,
W
wangzelin.wzl 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
                                                  int64_t &uncertain_bound)
{
  int ret = OB_SUCCESS;
  auto op_sn = tx.op_sn_;
  tx.flags_.BLOCK_ = true;
  tx.lock_.unlock();
  ret = acquire_global_snapshot__(expire_ts,
                                  GCONF._ob_get_gts_ahead_interval,
                                  snapshot,
                                  uncertain_bound,
                                  [&]() -> bool { return tx.flags_.INTERRUPTED_; });
  tx.lock_.lock();
  bool interrupted = tx.flags_.INTERRUPTED_;
  tx.flags_.BLOCK_ = false;
  if (OB_SUCC(ret)) {
    if (op_sn != tx.op_sn_) {
O
obdev 已提交
1542 1543 1544 1545 1546 1547 1548
      if (interrupted) {
        ret = OB_ERR_INTERRUPTED;
        TRANS_LOG(WARN, "txn has been interrupted", KR(ret), K(tx));
      } else {
        ret = OB_ERR_UNEXPECTED;
        TRANS_LOG(WARN, "txn has been disturbed", KR(ret), K(tx));
      }
W
wangzelin.wzl 已提交
1549 1550 1551 1552 1553 1554 1555
    }
  }
  return ret;
}

int ObTransService::acquire_global_snapshot__(const int64_t expire_ts,
                                              const int64_t gts_ahead,
1556
                                              SCN &snapshot,
W
wangzelin.wzl 已提交
1557 1558 1559 1560
                                              int64_t &uncertain_bound,
                                              ObFunction<bool()> interrupt_checker)
{
  int ret = OB_SUCCESS;
1561
  const MonotonicTs now0 = get_req_receive_mts_();
W
wangzelin.wzl 已提交
1562
  const MonotonicTs now = now0 - MonotonicTs(gts_ahead);
O
obdev 已提交
1563
  int retry_times = 0;
O
obdev 已提交
1564
  const int MAX_RETRY_TIMES = 100;
W
wangzelin.wzl 已提交
1565 1566 1567 1568 1569
  do {
    int64_t n = ObClockGenerator::getClock();
    MonotonicTs rts(0);
    if (n >= expire_ts) {
      ret = OB_TIMEOUT;
O
obdev 已提交
1570 1571 1572
    } else if (retry_times++ > MAX_RETRY_TIMES) {
      ret = OB_GTS_NOT_READY;
      TRANS_LOG(WARN, "gts not ready", K(ret), K(retry_times));
W
wangzelin.wzl 已提交
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    } else if (OB_FAIL(ts_mgr_->get_gts(tenant_id_, now, NULL, snapshot, rts))) {
      if (OB_EAGAIN == ret) {
        if (interrupt_checker()) {
          ret = OB_ERR_INTERRUPTED;
        } else {
          ob_usleep(500);
        }
      } else {
        TRANS_LOG(WARN, "get gts fail", K(now));
      }
1583
    } else if (OB_UNLIKELY(!snapshot.is_valid())) {
W
wangzelin.wzl 已提交
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(WARN, "invalid snapshot from gts", K(snapshot), K(now));
    } else {
      uncertain_bound = rts.mts_ + gts_ahead;
    }
  } while (OB_EAGAIN == ret);

  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "acquire global snapshot fail", K(ret),
              K(gts_ahead), K(expire_ts), K(now), K(now0),
              K(snapshot), K(uncertain_bound));
  }
  return ret;
}


/********************************************************************
 *
 * RPC and Message Handle
 *
 ********************************************************************/

int ObTransService::batch_post_tx_msg_(ObTxRollbackSPMsg &msg,
                                       const ObIArray<ObTxLSEpochPair> &list)
{
  int ret = OB_SUCCESS;
  int last_ret = OB_SUCCESS;
1611
  const ObTxDesc *tx_ptr = msg.tx_ptr_;
W
wangzelin.wzl 已提交
1612 1613 1614 1615
  ARRAY_FOREACH_NORET(list, idx) {
    auto &p = list.at(idx);
    msg.receiver_ = p.left_;
    msg.epoch_ = p.right_;
1616 1617 1618
    if (msg.epoch_ > 0) {
      msg.tx_ptr_ = NULL;
    }
W
wangzelin.wzl 已提交
1619 1620 1621 1622
    if (OB_FAIL(rpc_->post_msg(p.left_, msg))) {
      TRANS_LOG(WARN, "post msg falied", K(ret), K(msg), K(p));
      last_ret = ret;
    }
1623
    msg.tx_ptr_ = tx_ptr;
W
wangzelin.wzl 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
  }
  return last_ret;
}

int ObTransService::post_tx_abort_part_msg_(const ObTxDesc &tx_desc,
                                            const ObTxPart &p)
{
  int ret = OB_SUCCESS;
  ObTxAbortMsg msg;
  msg.cluster_version_ = tx_desc.cluster_version_;
  msg.tenant_id_ = tx_desc.tenant_id_;
  msg.tx_id_ = tx_desc.tx_id_;
  msg.receiver_ = p.id_;
  msg.sender_addr_ = self_;
  msg.sender_ = share::SCHEDULER_LS;
  msg.cluster_id_ = tx_desc.cluster_id_;
  msg.request_id_ = tx_desc.op_sn_;
  msg.reason_ = tx_desc.abort_cause_;
  bool local_opt = false;
  if (p.addr_ == self_) {
    ObTransRpcResult r;
    if (OB_SUCC(handle_trans_abort_request(msg, r))) {
      local_opt = true;
    }
  }
  if (!local_opt) {
    ret = rpc_->post_msg(p.id_, msg);
  }
  return ret;
}



bool ObTransService::is_sync_replica_(const share::ObLSID &ls_id)
{
  UNUSED(ls_id);
  // FIXME:
  /*
   * 1. ls.props.is_for_dup_table = true
   * 2. replica's in lease
   */
  return false;
}

int ObTransService::handle_trans_commit_response(ObTxCommitRespMsg &resp, ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ret = handle_tx_commit_result(resp.tx_id_, resp.ret_, resp.commit_version_);
  result.reset();
  result.init(ret, resp.get_timestamp());
#ifndef NDEBUG
  TRANS_LOG(INFO, "handle trans commit response", K(ret), K(resp));
#else
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "handle trans commit response fail", K(ret), K(resp));
  }
#endif
  return ret;
}

/*
 * handle tx commit request
 * 1. get txCtx and call its commit
 * 2. if txCtx not exist, get txState from txTable
 * 3. if both of txTable and txCtx not exist, replay with TRANS_UNKNOWN
 */
int ObTransService::handle_trans_commit_request(ObTxCommitMsg &msg,
                                                ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
1694
  SCN commit_version;
W
wangzelin.wzl 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
  if (OB_FAIL(local_ls_commit_tx_(msg.tx_id_,
                                  msg.receiver_,
                                  msg.parts_,
                                  msg.expire_ts_,
                                  msg.app_trace_info_,
                                  msg.request_id_,
                                  commit_version))) {
    TRANS_LOG(WARN, "handle tx commit request fail", K(ret), K(msg));
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  result.private_data_ = commit_version;
#ifndef NDEBUG
  TRANS_LOG(INFO, "handle trans commit request", K(ret), K(msg));
#else
  if (OB_FAIL(ret)) {
    TRANS_LOG(WARN, "handle trans commit request failed", K(ret), K(msg));
  }
#endif
  return ret;
}

int ObTransService::local_ls_commit_tx_(const ObTransID &tx_id,
                                        const share::ObLSID &coord,
                                        const share::ObLSArray &parts,
                                        const int64_t &expire_ts,
                                        const common::ObString &app_trace_info,
                                        const int64_t &request_id,
1723
                                        SCN &commit_version)
W
wangzelin.wzl 已提交
1724 1725
{
  int ret = OB_SUCCESS;
1726
  MonotonicTs commit_time = get_req_receive_mts_();
W
wangzelin.wzl 已提交
1727 1728 1729 1730
  ObPartTransCtx *ctx = NULL;
  if (OB_FAIL(get_tx_ctx_(coord, tx_id, ctx))) {
    TRANS_LOG(WARN, "get coordinator tx context fail", K(ret), K(tx_id), K(coord));
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
1731
      int tx_state = ObTxData::RUNNING;
W
wangzelin.wzl 已提交
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
      if (OB_FAIL(get_tx_state_from_tx_table_(coord, tx_id, tx_state, commit_version))) {
        TRANS_LOG(WARN, "get tx state from tx table fail", K(ret), K(coord), K(tx_id));
        if (OB_TRANS_CTX_NOT_EXIST == ret) {
          ret = OB_TRANS_KILLED; // presume abort
        }
      } else {
        switch (tx_state) {
        case ObTxData::COMMIT:
          ret = OB_TRANS_COMMITED;
          break;
        case ObTxData::ABORT:
          ret = OB_TRANS_KILLED;
          break;
        case ObTxData::RUNNING:
        default:
          ret = OB_ERR_UNEXPECTED;
          TRANS_LOG(WARN, "tx in-progress but ctx miss", K(ret), K(tx_state), K(tx_id), K(coord));
        }
      }
    }
  } else {
    if (OB_FAIL(ctx->commit(parts, commit_time, expire_ts, app_trace_info, request_id))) {
      TRANS_LOG(WARN, "commit fail", K(ret), K(coord), K(tx_id));
    }
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  return ret;
}

int ObTransService::get_tx_state_from_tx_table_(const share::ObLSID &lsid,
                                                const ObTransID &tx_id,
                                                int &state,
1766
                                                SCN &commit_version)
W
wangzelin.wzl 已提交
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
{
  int ret = OB_SUCCESS;
  ObTxTableGuard tx_table_guard;
  ObTxTable *tx_table = NULL;
  int64_t _state = 0;
  int64_t read_epoch = ObTxTable::INVALID_READ_EPOCH;
  if (OB_FAIL(get_tx_table_guard_(NULL, lsid, tx_table_guard))) {
    TRANS_LOG(WARN, "get tx table guard failed", KR(ret), K(lsid), KPC(this));
  } else if (!tx_table_guard.is_valid()) {
    TRANS_LOG(WARN, "tx table is null", KR(ret), K(lsid), KPC(this));
  } else if (FALSE_IT(tx_table = tx_table_guard.get_tx_table())) {
  } else if (FALSE_IT(read_epoch = tx_table_guard.epoch())) {
1779
  } else if (OB_FAIL(tx_table->try_get_tx_state(tx_id, read_epoch, _state, commit_version))) {
W
wangzelin.wzl 已提交
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    TRANS_LOG(WARN, "get tx state failed", KR(ret), K(lsid), K(tx_id), KPC(this));
  } else {
    state = (int)_state;
  }
  return ret;
}

int ObTransService::handle_trans_abort_request(ObTxAbortMsg &abort_req, ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  UNUSED(result);
  ObPartTransCtx *ctx = NULL;
  if (OB_FAIL(get_tx_ctx_(abort_req.get_receiver(), abort_req.get_trans_id(), ctx))) {
    // We donot respond with the abort response, because we think the abort is
    // eventually always successful if we have never send the commit request
    TRANS_LOG(WARN, "get transaction context error", KR(ret), K(abort_req.get_trans_id()));
  } else {
    if (OB_FAIL(ctx->abort(abort_req.reason_))) {
      TRANS_LOG(WARN, "trans rollback error", KR(ret), K(abort_req));
    }
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  TRANS_LOG(INFO, "handle trans abort request", K(ret), K(abort_req));
  return ret;
}

int ObTransService::handle_sp_rollback_request(ObTxRollbackSPMsg &msg,
                                               obrpc::ObTxRpcRollbackSPResult &result)
{
  int ret = OB_SUCCESS;
  int64_t ctx_born_epoch = -1;
  ret = ls_rollback_to_savepoint_(msg.tx_id_,
                                  msg.receiver_,
                                  msg.epoch_,
                                  msg.op_sn_,
                                  msg.savepoint_,
                                  ctx_born_epoch,
1819 1820 1821 1822 1823
                                  msg.tx_ptr_);
  if (OB_NOT_NULL(msg.tx_ptr_)) {
    ob_free((void*)msg.tx_ptr_);
    msg.tx_ptr_ = NULL;
  }
W
wangzelin.wzl 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
  result.status_ = ret;
  result.addr_ = self_;
  result.born_epoch_ = ctx_born_epoch;
  result.send_timestamp_ = msg.get_timestamp();
#ifndef NDEBUG
  TRANS_LOG(INFO, "handle savepoint rollback request", K(ret), K(msg), K(result));
#else
  if (OB_FAIL(ret)) {
    TRANS_LOG(INFO, "handle savepoint rollback request fail", K(ret), K(msg), K(result));
  }
#endif
  return ret;
}

int ObTransService::check_ls_status_(const share::ObLSID &ls_id, bool &leader)
{
  int ret = OB_SUCCESS;
  ObLSService *ls_svr =  MTL(ObLSService *);
  common::ObRole role = common::ObRole::INVALID_ROLE;
  storage::ObLSHandle handle;
  ObLS *ls = nullptr;
  int64_t UNUSED = 0;

  if (OB_ISNULL(ls_svr)) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "log stream service is NULL", K(ret));
  } else if (OB_FAIL(ls_svr->get_ls(ls_id, handle, ObLSGetMod::TRANS_MOD))) {
    TRANS_LOG(WARN, "get id service log stream failed");
  } else if (OB_ISNULL(ls = handle.get_ls())) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "id service log stream not exist");
  } else if (OB_FAIL(ls->get_log_handler()->get_role(role, UNUSED))) {
    if (OB_NOT_RUNNING == ret) {
      ret = OB_LS_NOT_EXIST;
    } else {
      TRANS_LOG(WARN, "get ls role fail", K(ret));
    }
  } else if (common::ObRole::LEADER == role) {
    leader = true;
  } else {
    leader = false;
  }

  return ret;
}

// need_check_leader : just for unittest case
int ObTransService::handle_tx_batch_req(int msg_type,
                                        const char *buf,
                                        int32_t size,
                                        const bool need_check_leader)
{
  int ret = OB_SUCCESS;
  bool leader = false;
  int64_t UNUSED = 0;
#define CASE__(msg_type__, msg_class__, msg_handler__)                  \
    case msg_type__:                                                    \
  {                                                                     \
    int64_t pos = 0;                                                    \
    ObPartTransCtx *ctx = NULL;                                         \
    msg_class__ msg;                                                         \
    if (OB_FAIL(msg.deserialize(buf, size, pos))) {                     \
      TRANS_LOG(WARN, "deserialize msg failed", K(ret), K(msg_type), K(size)); \
    } else if (!msg.is_valid()) {                                       \
      ret = OB_INVALID_ARGUMENT;                                        \
      TRANS_LOG(ERROR, "msg is invalid", K(ret), K(msg_type), K(msg));  \
    } else if (OB_FAIL(get_tx_ctx_(msg.get_receiver(), msg.get_trans_id(), ctx))) { \
      TRANS_LOG(WARN, "get tx context fail", K(ret),  K(msg));          \
O
obdev 已提交
1892
      if (OB_TRANS_CTX_NOT_EXIST == ret ||                              \
1893 1894
          OB_PARTITION_NOT_EXIST == ret ||                              \
          OB_LS_NOT_EXIST == ret) {                                     \
W
wangzelin.wzl 已提交
1895 1896 1897 1898 1899 1900 1901 1902 1903
        /* need_check_leader : just for unittest case*/                 \
        handle_orphan_2pc_msg_(msg, need_check_leader);                 \
      }                                                                 \
    } else if (OB_FAIL(ctx->get_ls_tx_ctx_mgr()                         \
                 ->get_ls_log_adapter()->get_role(leader, UNUSED))) {   \
      TRANS_LOG(WARN, "check ls leader status error", K(ret), K(msg));  \
    } else if (!leader) {                                               \
      ret = OB_NOT_MASTER;                                              \
      TRANS_LOG(WARN, "ls not master", K(ret), K(msg));                 \
O
obdev 已提交
1904 1905 1906 1907
    } else if (ctx->is_exiting()) {                                     \
      ret = OB_TRANS_CTX_NOT_EXIST;                                     \
      TRANS_LOG(INFO, "tx context is exiting",K(ret),K(msg));           \
      handle_orphan_2pc_msg_(msg, false);                               \
W
wangzelin.wzl 已提交
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    } else if (OB_FAIL(ctx->msg_handler__(msg))) {                      \
        TRANS_LOG(WARN, "handle 2pc request fail", K(ret), K(msg));     \
    }                                                                   \
    if (OB_NOT_NULL(ctx)) {                                             \
      revert_tx_ctx_(ctx);                                              \
    }                                                                   \
    break;                                                              \
  }

  switch (msg_type) {
    CASE__(TX_2PC_PREPARE_REDO_REQ, Ob2pcPrepareRedoReqMsg, handle_tx_2pc_prepare_redo_req)
    CASE__(TX_2PC_PREPARE_REDO_RESP, Ob2pcPrepareRedoRespMsg, handle_tx_2pc_prepare_redo_resp)
    CASE__(TX_2PC_PREPARE_VERSION_REQ, Ob2pcPrepareVersionReqMsg, handle_tx_2pc_prepare_version_req)
    CASE__(TX_2PC_PREPARE_VERSION_RESP, Ob2pcPrepareVersionRespMsg, handle_tx_2pc_prepare_version_resp)
    CASE__(TX_2PC_PREPARE_REQ, Ob2pcPrepareReqMsg, handle_tx_2pc_prepare_req)
    CASE__(TX_2PC_PREPARE_RESP, Ob2pcPrepareRespMsg, handle_tx_2pc_prepare_resp)
    CASE__(TX_2PC_PRE_COMMIT_REQ, Ob2pcPreCommitReqMsg, handle_tx_2pc_pre_commit_req)
    CASE__(TX_2PC_PRE_COMMIT_RESP, Ob2pcPreCommitRespMsg, handle_tx_2pc_pre_commit_resp)
    CASE__(TX_2PC_COMMIT_REQ, Ob2pcCommitReqMsg, handle_tx_2pc_commit_req)
    CASE__(TX_2PC_COMMIT_RESP, Ob2pcCommitRespMsg, handle_tx_2pc_commit_resp)
    CASE__(TX_2PC_ABORT_REQ, Ob2pcAbortReqMsg, handle_tx_2pc_abort_req)
    CASE__(TX_2PC_ABORT_RESP, Ob2pcAbortRespMsg, handle_tx_2pc_abort_resp)
    CASE__(TX_2PC_CLEAR_REQ, Ob2pcClearReqMsg, handle_tx_2pc_clear_req)
    CASE__(TX_2PC_CLEAR_RESP, Ob2pcClearRespMsg, handle_tx_2pc_clear_resp)
    default: {
      ret = OB_NOT_SUPPORTED;
      TRANS_LOG(WARN, "unsupported msg type", K(ret), K(msg_type));
      break;
    }
  }
#undef CASE__
  return ret;
}
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

#define COMMON_RETRYABLE_ERROR(ret)             \
  (OB_NOT_MASTER == ret                         \
   || OB_EAGAIN == ret                          \
   || OB_NEED_RETRY == ret                      \
   || OB_LS_NOT_EXIST == ret                    \
   || OB_PARTITION_NOT_EXIST == ret             \
   || OB_TENANT_NOT_EXIST == ret                \
   )

W
wangzelin.wzl 已提交
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
int ObTransService::handle_sp_rollback_resp(const share::ObLSID &ls_id,
                                            const int64_t epoch,
                                            const transaction::ObTransID &tx_id,
                                            const int status,
                                            const ObAddr &addr,
                                            const int64_t request_id,
                                            const obrpc::ObTxRpcRollbackSPResult &result)
{
  int ret = OB_SUCCESS;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx))) {
    TRANS_LOG(WARN, "get trans_desc fail", K(ret), K(tx_id));
  } else {
    ObSpinLockGuard guard(tx->lock_);
    if (tx->state_ != ObTxDesc::State::ROLLBACK_SAVEPOINT) {
      TRANS_LOG(WARN, "receive stale rollback response message",
                K(addr), K(status), K(request_id), K(result), KPC(tx));
    } else if (tx->op_sn_ > request_id) {
      TRANS_LOG(WARN, "receive old rpc result msg",
                K(ret), K_(tx->op_sn), K(request_id), K(tx_id));
1971 1972 1973
    } else if (status == OB_TRANS_RPC_TIMEOUT || COMMON_RETRYABLE_ERROR(status)) {
      TRANS_LOG(WARN, "rollback savepoint on ls return an retryable error",
                K(status), K(ls_id), K(tx_id), K(addr));
W
wangzelin.wzl 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
    } else if (status == OB_SUCCESS) {
      ObTxLSEpochPair pair(ls_id, epoch);
      if (tx->brpc_mask_set_.is_mask(pair)) {
        TRANS_LOG(DEBUG, "has marked received", K(pair));
      } else {
        if (epoch <= 0) {
          tx->update_clean_part(ls_id, result.born_epoch_, result.addr_);
        }
        (void)tx->brpc_mask_set_.mask(pair);
        //MEM_BARRIER();
        if (tx->brpc_mask_set_.is_all_mask()) {
          tx->rpc_cond_.notify(OB_SUCCESS);
        }
      }
    } else { // other failure
      // notify waiter, cause the savepoint rollback fail
      TRANS_LOG(WARN, "rollback_sp response an error", K(status),
                K(tx_id), K(tx->tx_id_), K(addr),
                K(request_id), K(ls_id), K(result));
      tx->rpc_cond_.notify(status);
    }
  }
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  return ret;
}

int ObTransService::handle_trans_msg_callback(const share::ObLSID &sender_ls_id,
                                              const share::ObLSID &receiver_ls_id,
                                              const ObTransID &tx_id,
                                              const int16_t msg_type,
                                              const int status,
                                              const ObAddr &receiver_addr,
                                              const int64_t request_id,
2009
                                              const SCN &private_data)
W
wangzelin.wzl 已提交
2010
{
2011
  auto start_ts = ObClockGenerator::getClock();
W
wangzelin.wzl 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!is_running_)) {
    ret = OB_NOT_RUNNING;
    TRANS_LOG(WARN, "ObTransService is not running", K(ret));
  } else if (!tx_id.is_valid()
             || !ObTxMsgTypeChecker::is_valid_msg_type(msg_type)
             || !receiver_addr.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid argument", K(ret), K(tx_id),
              K(msg_type), K(status), K(receiver_addr), K(request_id));
  } else if (common::OB_TENANT_NOT_IN_SERVER == status
             || common::OB_TRANS_RPC_TIMEOUT == status) {
    // upper layer do retry
  } else if (TX_COMMIT == msg_type) {
    switch(status) {
    case OB_NOT_MASTER:
    case OB_SUCCESS: break;
    default:
      auto commit_version = private_data;
      if (OB_FAIL(handle_tx_commit_result(tx_id, status, commit_version))) {
        TRANS_LOG(WARN, "handle tx commit fail", K(ret), K(tx_id));
      }
    }
  } else if (SUBPREPARE == msg_type) {
    switch (status) {
    case OB_NOT_MASTER:
    case OB_SUCCESS: break;
    default:
      if (OB_FAIL(handle_sub_prepare_result(tx_id, status))) {
        TRANS_LOG(WARN, "handle tx commit fail", K(ret), K(tx_id));
      }
    }
  } else if (SUBCOMMIT == msg_type) {
    switch (status) {
    case OB_NOT_MASTER:
    case OB_SUCCESS: break;
    default:
      if (OB_FAIL(handle_sub_commit_result(tx_id, status))) {
        TRANS_LOG(WARN, "handle tx commit fail", K(ret), K(tx_id));
      }
    }
  } else if (SUBROLLBACK == msg_type) {
    switch (status) {
    case OB_NOT_MASTER:
    case OB_SUCCESS: break;
    default:
      if (OB_FAIL(handle_sub_rollback_result(tx_id, status))) {
        TRANS_LOG(WARN, "handle tx commit fail", K(ret), K(tx_id));
      }
    }
  }
2063
  auto elapsed_ts = ObClockGenerator::getClock() - start_ts;
W
wangzelin.wzl 已提交
2064
#ifndef NDEBUG
2065
  TRANS_LOG(INFO, "handle trans msg callback", K(ret), K(elapsed_ts),
W
wangzelin.wzl 已提交
2066 2067 2068 2069
            K(tx_id), K(sender_ls_id), K(receiver_ls_id),
            K(msg_type), K(status), K(receiver_addr), K(request_id));
#else
  if (OB_FAIL(ret) || OB_SUCCESS != status) {
2070
    TRANS_LOG(WARN, "handle trans msg callback", K(ret), K(elapsed_ts),
W
wangzelin.wzl 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079
              K(tx_id), K(sender_ls_id), K(receiver_ls_id),
              K(msg_type), K(status), K(receiver_addr), K(request_id));
  }
#endif
  return ret;
}

int ObTransService::update_max_read_ts_(const uint64_t tenant_id,
                                        const share::ObLSID &lsid,
2080
                                        const SCN ts)
W
wangzelin.wzl 已提交
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
{
  int ret = OB_SUCCESS;
  tx_version_mgr_.update_max_read_ts(ts);
  TRANS_LOG(TRACE, "update max read ts", K(ret), K(tenant_id), K(lsid), K(ts));
  return ret;
}

// need_check_leader : just for unittest case
void ObTransService::handle_orphan_2pc_msg_(const ObTxMsg &msg, const bool need_check_leader)
{
  int ret = OB_SUCCESS;
  bool leader = false;

  if (need_check_leader && OB_FAIL(check_ls_status_(msg.get_receiver(), leader))) {
2095 2096 2097 2098 2099 2100
    if (OB_LS_NOT_EXIST == ret) {
      ret = OB_SUCCESS;
      TRANS_LOG(INFO, "check ls status with ls not exist", K(ret), K(msg), K(need_check_leader));
    } else {
      TRANS_LOG(WARN, "check ls status error", K(ret), K(msg), K(need_check_leader));
    }
W
wangzelin.wzl 已提交
2101 2102 2103
  } else if (need_check_leader && !leader) {
    ret = OB_NOT_MASTER;
    TRANS_LOG(WARN, "receiver not master", K(ret), K(msg));
2104 2105 2106
  }

  if (OB_SUCC(ret) && OB_FAIL(ObPartTransCtx::handle_tx_orphan_2pc_msg(msg, get_server(), get_trans_rpc()))) {
W
wangzelin.wzl 已提交
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
    TRANS_LOG(WARN, "handle tx orphan 2pc msg failed", K(ret), K(msg));
  } else {
    // do nothing
  }
}

int ObTransService::refresh_location_cache(const share::ObLSID ls)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    ret = OB_NOT_INIT;
    TRANS_LOG(WARN, "ObTransService not inited", K(ret));
  } else if (OB_UNLIKELY(!is_running_)) {
    ret = OB_NOT_RUNNING;
    TRANS_LOG(WARN, "ObTransService is not running", K(ret));
  } else if (!ls.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid argument", K(ret), K(ls));
  } else if (OB_FAIL(location_adapter_->nonblock_renew(GCONF.cluster_id, tenant_id_, ls))) {
    TRANS_LOG(WARN, "refresh location cache error", KR(ret), K(ls));
  } else {
    if (EXECUTE_COUNT_PER_SEC(16)) {
      TRANS_LOG(INFO, "refresh location cache success", K(ls), K(lbt()));
    }
  }

  return ret;
}

int ObTransService::gen_trans_id_(ObTransID &trans_id)
{
  int ret = OB_SUCCESS;
O
obdev 已提交
2140

W
wangzelin.wzl 已提交
2141
  int retry_times = 0;
O
obdev 已提交
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
  if (!MTL_IS_PRIMARY_TENANT()) {
    ret = OB_STANDBY_READ_ONLY;
    TRANS_LOG(WARN, "standby tenant support read only", K(ret));
  } else {
    const int MAX_RETRY_TIMES = 50;
    int64_t tx_id = 0;
    do {
      if (OB_SUCC(gti_source_->get_trans_id(tx_id))) {
      } else if (OB_EAGAIN == ret) {
        if (retry_times++ > MAX_RETRY_TIMES) {
          ret = OB_GTI_NOT_READY;
          TRANS_LOG(WARN, "get trans id not ready", K(ret), K(retry_times), KPC(this));
        } else {
          ob_usleep(1000);
        }
W
wangzelin.wzl 已提交
2157
      } else {
O
obdev 已提交
2158
        TRANS_LOG(WARN, "get trans id fail", KR(ret));
W
wangzelin.wzl 已提交
2159
      }
O
obdev 已提交
2160 2161 2162
    } while (OB_EAGAIN == ret);
    if (OB_SUCC(ret)) {
      trans_id = ObTransID(tx_id);
W
wangzelin.wzl 已提交
2163 2164 2165 2166 2167 2168 2169 2170
    }
  }
  TRANS_LOG(TRACE, "gen trans id", K(ret), K(trans_id), K(retry_times));
  return ret;
}

bool ObTransService::commit_need_retry_(const int ret)
{
2171 2172 2173
  return OB_TX_NOLOGCB == ret
    || OB_BLOCK_FROZEN == ret
    || COMMON_RETRYABLE_ERROR(ret);
W
wangzelin.wzl 已提交
2174 2175
}

2176
int ObTransService::get_min_uncommit_tx_prepare_version(const share::ObLSID& ls_id, SCN &min_prepare_version)
W
wangzelin.wzl 已提交
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (!ls_id.is_valid()) {
    TRANS_LOG(WARN, "invalid argument", K(ls_id));
    ret = OB_INVALID_ARGUMENT;
  } else if (OB_FAIL(tx_ctx_mgr_.get_ls_min_uncommit_tx_prepare_version(ls_id, min_prepare_version))) {
    TRANS_LOG(WARN, "ObPartTransCtxMgr set memstore version error", KR(ret), K(ls_id));
2191
  } else if (!min_prepare_version.is_valid()) {
W
wangzelin.wzl 已提交
2192 2193 2194 2195 2196
    TRANS_LOG(ERROR, "invalid min prepare version, unexpected error", K(ls_id), K(min_prepare_version));
    ret = OB_ERR_UNEXPECTED;
  } else {
    TRANS_LOG(DEBUG, "get min uncommit prepare version success", K(ls_id), K(min_prepare_version));
  }
2197
return ret;
W
wangzelin.wzl 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
}

int ObTransService::kill_all_tx(const share::ObLSID &ls_id, const KillTransArg &arg,
    bool &is_all_tx_cleaned_up)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (!ls_id.is_valid()) {
    TRANS_LOG(WARN, "invalid argument", K(ls_id));
    ret = OB_INVALID_ARGUMENT;
  } else if (OB_FAIL(tx_ctx_mgr_.kill_all_tx(ls_id, arg.graceful_, is_all_tx_cleaned_up))) {
    TRANS_LOG(WARN, "kill all tx failed", KR(ret), K(ls_id), K(arg));
  } else {
    TRANS_LOG(INFO, "kill all tx success", K(ls_id), K(arg));
  }

  return ret;
}

int ObTransService::block_ls(const share::ObLSID &ls_id, bool &is_all_tx_cleaned_up)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (!ls_id.is_valid()) {
    TRANS_LOG(WARN, "invalid argument", K(ls_id));
    ret = OB_INVALID_ARGUMENT;
  } else if (OB_FAIL(tx_ctx_mgr_.block_ls(ls_id, is_all_tx_cleaned_up))) {
    TRANS_LOG(WARN, "block ls error", KR(ret), K(ls_id));
  } else {
    TRANS_LOG(INFO, "block ls_id success", K(ls_id), K(is_all_tx_cleaned_up));
  }
  return ret;
}

int ObTransService::iterate_tx_ctx_mgr_stat(ObTxCtxMgrStatIterator &tx_ctx_mgr_stat_iter)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (OB_FAIL(tx_ctx_mgr_.iterate_tx_ctx_mgr_stat(self_, tx_ctx_mgr_stat_iter))) {
    TRANS_LOG(WARN, "iterate_tx_ctx_mgr_stat error", KR(ret), K_(self));
  } else if (OB_FAIL(tx_ctx_mgr_stat_iter.set_ready())) {
    TRANS_LOG(WARN, "tx_ctx_mgr_stat_iter set ready error", KR(ret));
  } else {
    // do nothing
  }
  return ret;
}

int ObTransService::iterate_tx_lock_stat(const share::ObLSID& ls_id,
    ObTxLockStatIterator &tx_lock_stat_iter)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (OB_FAIL(tx_ctx_mgr_.iterate_ls_tx_lock_stat(ls_id, tx_lock_stat_iter))) {
    TRANS_LOG(WARN, "iterate_tx_lock_stat error", KR(ret));
  } else if (OB_FAIL(tx_lock_stat_iter.set_ready())) {
    TRANS_LOG(WARN, "iterate_tx_lock_stat set ready error", KR(ret));
  } else {
    // do nothing
    TRANS_LOG(INFO, "iterate_tx_lock_stat set ready succ", KR(ret));
  }

  return ret;
}

int ObTransService::iterate_ls_id(ObLSIDIterator &ls_id_iter)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (OB_FAIL(tx_ctx_mgr_.iterate_ls_id(ls_id_iter))) {
    TRANS_LOG(WARN, "iterate ls id error", KR(ret));
  } else if (OB_FAIL(ls_id_iter.set_ready())) {
    TRANS_LOG(WARN, "ls_id_iter set ready error", KR(ret));
  } else {
    // do nothing
  }

  return ret;
}

int ObTransService::iterate_all_observer_tx_stat(ObTxStatIterator &tx_stat_iter)
{
  int ret = OB_SUCCESS;
  const int64_t PRINT_SCHE_COUNT = 128;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (OB_FAIL(tx_ctx_mgr_.iterate_all_observer_tx_stat(tx_stat_iter))) {
      TRANS_LOG(WARN, "iterate tx stat error", KR(ret));
  } else {
    // do nothing
  }

  return ret;
}

O
obdev 已提交
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
int ObTransService::iterate_tx_scheduler_stat(ObTxSchedulerStatIterator &tx_scheduler_stat_iter)
{
  int ret = OB_SUCCESS;
  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (OB_FAIL(tx_desc_mgr_.iterate_tx_scheduler_stat(tx_scheduler_stat_iter))) {
    TRANS_LOG(WARN, "iterate tx stat error", KR(ret));
  } else {
    // do nothing
  }
  return ret;
}

W
wangzelin.wzl 已提交
2345 2346 2347 2348 2349 2350 2351 2352
int ObTransService::recover_tx(const ObTxInfo &tx_info, ObTxDesc *&tx)
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(tx_desc_mgr_.alloc(tx))) {
    TRANS_LOG(WARN, "alloc tx desc fail", K(ret));
  } else if (OB_FAIL(tx->parts_.assign(tx_info.parts_))) {
    tx_desc_mgr_.revert(*tx);
    tx = NULL;
O
obdev 已提交
2353
    TRANS_LOG(WARN, "assgin parts fail", K(ret));
W
wangzelin.wzl 已提交
2354
  } else if (OB_FAIL(tx_desc_mgr_.add_with_txid(tx_info.tx_id_, *tx))) {
O
obdev 已提交
2355 2356 2357
    tx_desc_mgr_.revert(*tx);
    tx = NULL;
    TRANS_LOG(WARN, "add tx to txMgr fail", K(ret));
W
wangzelin.wzl 已提交
2358 2359
  } else {
    tx->flags_.REPLICA_ = true;
2360
    tx->flags_.EXPLICIT_ = true;
W
wangzelin.wzl 已提交
2361 2362 2363
    tx->tenant_id_ = tx_info.tenant_id_;
    tx->cluster_id_ = tx_info.cluster_id_;
    tx->cluster_version_ = tx_info.cluster_version_;
O
obdev 已提交
2364
    tx->addr_ = tx_info.addr_; /*origin scheduler addr*/
W
wangzelin.wzl 已提交
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
    tx->tx_id_ = tx_info.tx_id_;
    tx->isolation_ = tx_info.isolation_;
    tx->access_mode_ = tx_info.access_mode_;
    tx->snapshot_version_ = tx_info.snapshot_version_;
    tx->snapshot_uncertain_bound_ = tx_info.snapshot_uncertain_bound_;
    tx->op_sn_ = tx_info.op_sn_;
    tx->alloc_ts_ = tx_info.alloc_ts_;
    tx->active_ts_ = tx_info.active_ts_;
    tx->timeout_us_ = tx_info.timeout_us_;
    tx->expire_ts_ = tx_info.expire_ts_;
    tx->finish_ts_ = tx_info.finish_ts_;
    tx->active_scn_ = tx_info.active_scn_;
    tx->state_ = ObTxDesc::State::ACTIVE;
2378
    tx->sess_id_ = tx_info.session_id_;
W
wangzelin.wzl 已提交
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
  }
  return ret;
}

int ObTransService::get_tx_info(ObTxDesc &tx, ObTxInfo &tx_info)
{
  int ret = OB_SUCCESS;
  tx.lock_.lock();
  if (OB_FAIL(tx_info.parts_.assign(tx.parts_))) {
    TRANS_LOG(WARN, "assgin parts fail", K(ret), K(tx));
  } else {
    tx_info.tenant_id_ = tx.tenant_id_;
    tx_info.cluster_id_ = tx.cluster_id_;
    tx_info.cluster_version_ = tx.cluster_version_;
    tx_info.addr_ = tx.addr_;
    tx_info.tx_id_ = tx.tx_id_;
    tx_info.isolation_ = tx.isolation_;
    tx_info.access_mode_ = tx.access_mode_;
    tx_info.snapshot_version_ = tx.snapshot_version_;
    tx_info.snapshot_uncertain_bound_ = tx.snapshot_uncertain_bound_;
    tx_info.op_sn_ = tx.op_sn_;
    tx_info.alloc_ts_ = tx.alloc_ts_;
    tx_info.active_ts_ = tx.active_ts_;
    tx_info.timeout_us_ = tx.timeout_us_;
    tx_info.expire_ts_ = tx.expire_ts_;
    tx_info.finish_ts_ = tx.finish_ts_;
    tx_info.active_scn_ = tx.active_scn_;
2406
    tx_info.session_id_ = tx.sess_id_;
W
wangzelin.wzl 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
  }
  tx.lock_.unlock();
  return ret;
}

int ObTransService::get_tx_stmt_info(ObTxDesc &tx, ObTxStmtInfo &stmt_info)
{
  int ret = OB_SUCCESS;
  tx.lock_.lock();
  if (OB_FAIL(stmt_info.parts_.assign(tx.parts_))) {
    TRANS_LOG(WARN, "assgin parts fail", K(ret), K(tx));
  } else {
    stmt_info.tx_id_ = tx.tx_id_;
    stmt_info.op_sn_ = tx.op_sn_;
    stmt_info.state_ = tx.state_;
  }
  tx.lock_.unlock();
  return ret;
}

int ObTransService::update_tx_with_stmt_info(const ObTxStmtInfo &tx_info, ObTxDesc *&tx)
{
  int ret = OB_SUCCESS;
  tx->lock_.lock();
  tx->op_sn_ = tx_info.op_sn_;
  tx->state_ = tx_info.state_;
  tx->update_parts_(tx_info.parts_);
  tx->lock_.unlock();
  return ret;
}

int ObTransService::get_tx_table_guard_(ObLS *ls,
                                        const share::ObLSID &ls_id,
                                        ObTxTableGuard &guard)
{
  int ret = OB_SUCCESS;
  if (OB_NOT_NULL(ls)) {
    if (OB_FAIL(ls->get_tx_table_guard(guard))) {
      TRANS_LOG(WARN, "get ls tx_table_guard fail", K(ret), K(ls_id), KPC(ls), KPC(this));
    }
  } else {
    ObLSTxCtxMgr *ls_tx_ctx_mgr = NULL;
    if (OB_FAIL(tx_ctx_mgr_.get_ls_tx_ctx_mgr(ls_id, ls_tx_ctx_mgr))) {
      TRANS_LOG(WARN, "get ls tx_ctx_mgr fail", KR(ret), K(ls_id));
    } else if (OB_FAIL(ls_tx_ctx_mgr->get_tx_table_guard(guard))) {
      TRANS_LOG(WARN, "get ls tx_table_guard fail", KR(ret), K(ls_id), KP(ls_tx_ctx_mgr));
    }
    if (OB_NOT_NULL(ls_tx_ctx_mgr)) {
      tx_ctx_mgr_.revert_ls_tx_ctx_mgr(ls_tx_ctx_mgr);
    }
  }
  return ret;
}

int ObTransService::handle_timeout_for_xa(ObTxDesc &tx, const int64_t delay)
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
2465 2466
  bool cb_executed = false;
  auto tx_id = tx.tx_id_;
W
wangzelin.wzl 已提交
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
  if (OB_FAIL(tx.lock_.lock(5000000))) {
    TRANS_LOG(WARN, "failed to acquire lock in specified time", K(tx));
    // FIXME: how to handle it without lock protection
    // according to handle_tx_commit_timeout
  } else {
    if (!tx.commit_task_.is_registered()){
      TRANS_LOG(INFO, "task canceled", K(tx));
    } else if (tx.flags_.RELEASED_) {
      TRANS_LOG(INFO, "tx released, cancel commit retry", K(tx));
    } else if (FALSE_IT(tx.commit_task_.set_registered(false))) {
    } else {
      if (ObTxDesc::State::SUB_PREPARING == tx.state_) {
        ret = handle_sub_prepare_timeout_(tx, delay);
      } else if (ObTxDesc::State::SUB_COMMITTING == tx.state_) {
        ret = handle_sub_commit_timeout_(tx, delay);
      } else if (ObTxDesc::State::SUB_ROLLBACKING == tx.state_) {
        ret = handle_sub_rollback_timeout_(tx, delay);
      } else {
      }
    }
    tx.lock_.unlock();
2488
    cb_executed = tx.execute_commit_cb();
W
wangzelin.wzl 已提交
2489
  }
2490
  TRANS_LOG(INFO, "handle tx commit timeout", K(ret), K(tx_id), K(cb_executed));
W
wangzelin.wzl 已提交
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
  return ret;
}

int ObTransService::handle_sub_prepare_timeout_(ObTxDesc &tx, const int64_t delay)
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
  if (tx.state_ != ObTxDesc::State::SUB_PREPARING) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpect trans state", K(ret), K_(tx.state), K(tx));
  } else if (tx.commit_expire_ts_ <= now) {
    TRANS_LOG(WARN, "sub prepare timeout", K_(tx.commit_expire_ts), K(tx));
    ret = handle_sub_prepare_result_(tx, OB_TRANS_STMT_TIMEOUT);
  } else {
    ObTxSubPrepareMsg sub_prepare_msg;
    if (OB_FAIL(build_tx_sub_prepare_msg_(tx, sub_prepare_msg))) {
      TRANS_LOG(WARN, "build tx commit msg fail", K(ret), K(tx));
    } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, sub_prepare_msg))) {
      TRANS_LOG(WARN, "post commit msg fail", K(ret), K(tx));
    }
    if (OB_FAIL(register_commit_retry_task_(tx))) {
      TRANS_LOG(WARN, "reregister task fail", K(ret), K(tx));
    }
  }
  TRANS_LOG(INFO, "handle sub prepare timeout", K(ret), K(tx));
  return ret;
}

int ObTransService::handle_sub_rollback_timeout_(ObTxDesc &tx, const int64_t delay)
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
  if (tx.state_ != ObTxDesc::State::SUB_ROLLBACKING) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpect trans state", K(ret), K_(tx.state), K(tx));
  } else if (tx.commit_expire_ts_ <= now) {
O
obdev 已提交
2527
    TRANS_LOG(WARN, "sub rollback timeout", K_(tx.commit_expire_ts), K(tx));
W
wangzelin.wzl 已提交
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
    const bool is_rollback = true;
    ret = handle_sub_end_tx_result_(tx, is_rollback, OB_TRANS_STMT_TIMEOUT);
  } else {
    ObTxSubRollbackMsg sub_rollback_msg;
    if (OB_FAIL(build_tx_sub_rollback_msg_(tx, sub_rollback_msg))) {
      TRANS_LOG(WARN, "build tx commit msg fail", K(ret), K(tx));
    } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, sub_rollback_msg))) {
      TRANS_LOG(WARN, "post commit msg fail", K(ret), K(tx));
    }
    if (OB_FAIL(register_commit_retry_task_(tx))) {
      TRANS_LOG(WARN, "reregister task fail", K(ret), K(tx));
    }
  }
  TRANS_LOG(INFO, "handle sub rollback timeout", K(ret), K(tx));
  return ret;
}

int ObTransService::handle_sub_commit_timeout_(ObTxDesc &tx, const int64_t delay)
{
  int ret = OB_SUCCESS;
  int64_t now = ObClockGenerator::getClock();
  if (tx.state_ != ObTxDesc::State::SUB_COMMITTING) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpect trans state", K(ret), K_(tx.state), K(tx));
  } else if (tx.commit_expire_ts_ <= now) {
O
obdev 已提交
2553
    TRANS_LOG(WARN, "sub commit timeout", K_(tx.commit_expire_ts), K(tx));
W
wangzelin.wzl 已提交
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
    const bool is_rollback = false;
    ret = handle_sub_end_tx_result_(tx, is_rollback, OB_TRANS_STMT_TIMEOUT);
  } else {
    ObTxSubCommitMsg sub_commit_msg;
    if (OB_FAIL(build_tx_sub_commit_msg_(tx, sub_commit_msg))) {
      TRANS_LOG(WARN, "build tx commit msg fail", K(ret), K(tx));
    } else if (OB_FAIL(rpc_->post_msg(tx.coord_id_, sub_commit_msg))) {
      TRANS_LOG(WARN, "post commit msg fail", K(ret), K(tx));
    }
    if (OB_FAIL(register_commit_retry_task_(tx))) {
      TRANS_LOG(WARN, "reregister task fail", K(ret), K(tx));
    }
  }
  TRANS_LOG(INFO, "handle sub commit timeout", K(ret), K(tx));
  return ret;
}

int ObTransService::handle_sub_prepare_request(const ObTxSubPrepareMsg &msg,
                                               ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(sub_prepare_local_ls_(msg.tx_id_,
                                    msg.receiver_,
                                    msg.parts_,
                                    msg.expire_ts_,
                                    msg.app_trace_info_,
                                    msg.request_id_,
                                    msg.xid_))) {
    TRANS_LOG(WARN, "handle tx commit request fail", K(ret), K(msg));
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub prepare request", K(ret), K(msg));
  return ret;
}

int ObTransService::sub_prepare_local_ls_(const ObTransID &tx_id,
                                          const share::ObLSID &coord,
                                          const share::ObLSArray &parts,
                                          const int64_t &expire_ts,
                                          const common::ObString & app_trace_info,
                                          const int64_t &request_id,
                                          const ObXATransID &xid)
{
  int ret = OB_SUCCESS;
2599
  MonotonicTs commit_time = get_req_receive_mts_();
W
wangzelin.wzl 已提交
2600 2601 2602 2603 2604
  ObPartTransCtx *ctx = NULL;
  if (OB_FAIL(get_tx_ctx_(coord, tx_id, ctx))) {
    TRANS_LOG(WARN, "get coordinator context fail", K(ret), K(tx_id), K(coord));
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
      int tx_state;
2605
      SCN commit_version;
W
wangzelin.wzl 已提交
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
      if (OB_FAIL(get_tx_state_from_tx_table_(coord, tx_id, tx_state, commit_version))) {
        TRANS_LOG(WARN, "get tx state from tx table fail", K(ret), K(coord), K(tx_id));
        if (OB_ENTRY_NOT_EXIST == ret) {
          ret = OB_TRANS_KILLED; // presume abort
        }
      } else {
        switch (tx_state) {
        case ObTxData::COMMIT:
          ret = OB_TRANS_COMMITED;
          break;
        case ObTxData::ABORT:
          ret = OB_TRANS_KILLED;
          break;
        case ObTxData::RUNNING:
        default:
          ret = OB_ERR_UNEXPECTED;
          TRANS_LOG(WARN, "unexpected non-existence status of trans ctx", K(ret),
                    K(tx_state), K(tx_id), K(coord));
        }
      }
    }
  } else if (OB_FAIL(ctx->sub_prepare(parts, commit_time, expire_ts, app_trace_info, request_id,
          xid))) {
    TRANS_LOG(WARN, "commit fail", K(ret), K(coord), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  return ret;
}

int ObTransService::handle_sub_prepare_response(const ObTxSubPrepareRespMsg &msg,
                                                ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ret = handle_sub_prepare_result(msg.tx_id_, msg.ret_);
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub prepare response", K(ret), K(msg));
  return ret;
}

int ObTransService::handle_sub_prepare_result(const ObTransID &tx_id,
                                              const int result)
{
  int ret = OB_SUCCESS;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx))) {
    TRANS_LOG(WARN, "cannot found tx by id", K(ret), K(tx_id), K(result));
  } else {
    tx->lock_.lock();
    // TODO, check state
    if (ObTxDesc::State::IN_TERMINATE > tx->state_) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(WARN, "unexpected tx state", K(ret),
                K_(tx->state), K(tx_id), K(result), KPC(tx));
    } else if (ObTxDesc::State::SUB_PREPARED == tx->state_) {
      TRANS_LOG(WARN, "tx has been prepared", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
    } else if (ObTxDesc::State::ROLLED_BACK == tx->state_) {
      TRANS_LOG(WARN, "tx has been rollbacked", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
    } else if (ObTxDesc::State::SUB_PREPARING != tx->state_) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(WARN, "unexpected tx state", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
    } else {
      ret = handle_sub_prepare_result_(*tx, result);
    }
    tx->lock_.unlock();
    tx->execute_commit_cb();
  }
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  return ret;
}

int ObTransService::handle_sub_prepare_result_(ObTxDesc &tx,
                                               const int result)
{
  int ret = OB_SUCCESS;
  bool commit_fin = true;
  int commit_out = OB_SUCCESS;
  switch (result) {
  case OB_BLOCK_FROZEN:
  case OB_NOT_MASTER:
    commit_fin = false;
    if (tx.commit_task_.is_registered()) {
      // the task maybe already registred:
      // 1. location cache stale: leader on local actually
      // 2. L--(regier)-->F-->L--(here)-->F
    } else if (OB_FAIL(register_commit_retry_task_(tx))) {
      commit_fin = true;
      tx.state_ = ObTxDesc::State::ROLLED_BACK;
      commit_out = OB_TRANS_ROLLBACKED;
    }
    break;
  case OB_SUCCESS:
    // success of sub prepare
    tx.state_ = ObTxDesc::State::SUB_PREPARED;
    commit_out = OB_SUCCESS;
    break;
  case OB_TRANS_COMMITED:
    commit_fin = true;
    tx.state_ = ObTxDesc::State::COMMITTED;
    commit_out = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpected tx result", K(tx), K(result));
    break;
  case OB_TRANS_KILLED:
  case OB_TRANS_ROLLBACKED:
  default:
    tx.state_ = ObTxDesc::State::ROLLED_BACK;
    commit_out = result;
    break;
  }
  // commit finished, cleanup
  if (commit_fin) {
    if (tx.finish_ts_ <= 0) { // maybe aborted early
      tx.finish_ts_ = ObClockGenerator::getClock();
    }
    tx.commit_out_ = commit_out;
    if (tx.commit_task_.is_registered()) {
      if (OB_FAIL(unregister_commit_retry_task_(tx))) {
        TRANS_LOG(ERROR, "deregister timeout task fail", K(tx));
      }
    }
    tx_post_terminate_(tx);
  }
  TRANS_LOG(INFO, "handle sub prepare result", K(ret), K(tx), K(commit_fin), K(result));
  return ret;
}

int ObTransService::handle_sub_commit_request(const ObTxSubCommitMsg &msg,
                                              ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  const bool is_rollback = false;
  if (OB_FAIL(sub_end_tx_local_ls_(msg.tx_id_,
                                   msg.receiver_,
                                   msg.request_id_,
                                   msg.xid_,
                                   msg.sender_addr_,
                                   is_rollback))) {
    TRANS_LOG(WARN, "fail to handle tx commit request", K(ret), K(msg));
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub commit request", K(ret), K(msg));
  return ret;
}

int ObTransService::handle_sub_rollback_request(const ObTxSubRollbackMsg &msg,
                                                ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  const bool is_rollback = true;
  if (OB_FAIL(sub_end_tx_local_ls_(msg.tx_id_,
                                   msg.receiver_,
                                   msg.request_id_,
                                   msg.xid_,
                                   msg.sender_addr_,
                                   is_rollback))) {
    TRANS_LOG(WARN, "fail to handle tx rollback request", K(ret), K(msg));
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub rollback request", K(ret), K(msg));
  return ret;
}

int ObTransService::sub_end_tx_local_ls_(const ObTransID &tx_id,
                                         const share::ObLSID &coord,
                                         const int64_t &request_id,
                                         const ObXATransID &xid,
                                         const ObAddr &sender_addr,
                                         const bool is_rollback)
{
  int ret = OB_SUCCESS;
2785
  MonotonicTs commit_time = get_req_receive_mts_();
W
wangzelin.wzl 已提交
2786 2787 2788 2789
  ObPartTransCtx *ctx = NULL;
  if (OB_FAIL(get_tx_ctx_(coord, tx_id, ctx))) {
    TRANS_LOG(WARN, "fail to get coordinator tx context", K(ret), K(tx_id), K(coord));
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
2790
      int tx_state = ObTxData::RUNNING;
2791
      SCN commit_version;
W
wangzelin.wzl 已提交
2792 2793
      if (OB_FAIL(get_tx_state_from_tx_table_(coord, tx_id, tx_state, commit_version))) {
        TRANS_LOG(WARN, "get tx state from tx table fail", K(ret), K(coord), K(tx_id));
2794
        if (OB_TRANS_CTX_NOT_EXIST == ret) {
W
wangzelin.wzl 已提交
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
          ret = OB_TRANS_KILLED; // presume abort
        }
      } else {
        switch (tx_state) {
        case ObTxData::COMMIT:
          ret = OB_TRANS_COMMITED;
          break;
        case ObTxData::ABORT:
          ret = OB_TRANS_KILLED;
          break;
        case ObTxData::RUNNING:
        default:
          ret = OB_ERR_UNEXPECTED;
          TRANS_LOG(WARN, "unexpected non-existence status of trans ctx", K(ret),
                    K(tx_state), K(tx_id), K(coord));
        }
      }
    }
  } else if (OB_FAIL(ctx->sub_end_tx(request_id, xid, sender_addr, is_rollback))) {
    TRANS_LOG(WARN, "fail to end trans", K(ret), K(coord), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  return ret;
}

int ObTransService::handle_sub_commit_response(const ObTxSubCommitRespMsg &msg,
                                               ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ret = handle_sub_commit_result(msg.tx_id_, msg.ret_);
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub commit response", K(ret), K(msg));
  return ret;
}

int ObTransService::handle_sub_commit_result(const ObTransID &tx_id,
                                             const int result)
{
  int ret = OB_SUCCESS;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx))) {
    TRANS_LOG(WARN, "fail to get trans desc by trans id", K(ret), K(tx_id), K(result));
  } else if (NULL == tx) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpected trans desc", K(ret), K(tx_id), K(result));
  } else {
    tx->lock_.lock();
    // TODO, check state
    if (ObTxDesc::State::SUB_COMMITTING != tx->state_) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(WARN, "unexpected trans state", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
    } else {
      int final_result = result;
      const bool is_rollback = false;
      if (OB_TRANS_COMMITED == result) {
        final_result = OB_SUCCESS;
      }
      ret = handle_sub_end_tx_result_(*tx, is_rollback, final_result);
    }
    tx->lock_.unlock();
    tx->execute_commit_cb();
  }
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  return ret;
}

int ObTransService::handle_sub_rollback_response(const ObTxSubRollbackRespMsg &msg,
                                                 ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ret = handle_sub_rollback_result(msg.tx_id_, msg.ret_);
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle sub rollback response", K(ret), K(msg));
  return ret;
}

int ObTransService::handle_sub_rollback_result(const ObTransID &tx_id,
                                               const int result)
{
  int ret = OB_SUCCESS;
  ObTxDesc *tx = NULL;
  if (OB_FAIL(tx_desc_mgr_.get(tx_id, tx))) {
    TRANS_LOG(WARN, "fail to get trans desc by trans id", K(ret), K(tx_id), K(result));
  } else if (NULL == tx) {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "unexpected trans desc", K(ret), K(tx_id), K(result));
  } else {
    tx->lock_.lock();
    // TODO, check state
    if (ObTxDesc::State::SUB_ROLLBACKING != tx->state_) {
      ret = OB_ERR_UNEXPECTED;
      TRANS_LOG(WARN, "unexpected trans state", K_(tx->state),
                K(tx_id), K(result), KPC(tx));
    } else {
      int final_result = result;
      const bool is_rollback = true;
      if (OB_TRANS_KILLED == result) {
        final_result = OB_SUCCESS;
      }
      ret = handle_sub_end_tx_result_(*tx, is_rollback, final_result);
    }
    tx->lock_.unlock();
    tx->execute_commit_cb();
  }
  if (OB_NOT_NULL(tx)) {
    tx_desc_mgr_.revert(*tx);
  }
  return ret;
}

int ObTransService::handle_sub_end_tx_result_(ObTxDesc &tx,
                                              const bool is_rollback,
                                              const int result)
{
  int ret = OB_SUCCESS;
  bool commit_fin = true;
  switch (result) {
    case OB_BLOCK_FROZEN:
    case OB_NOT_MASTER: {
      commit_fin = false;
      if (tx.commit_task_.is_registered()) {
        // the task maybe already registred:
        // 1. location cache stale: leader on local actually
        // 2. L--(regier)-->F-->L--(here)-->F
      } else if (OB_FAIL(register_commit_retry_task_(tx))) {
        commit_fin = true;
        tx.state_ = ObTxDesc::State::ROLLED_BACK;
        tx.commit_out_ = OB_TRANS_ROLLBACKED;
      }
      break;
    }
    case OB_TRANS_STMT_TIMEOUT: {
      commit_fin = true;
      tx.commit_out_ = OB_TRANS_STMT_TIMEOUT;
      // TODO, use other state to denote timeout
      tx.state_ = ObTxDesc::State::ROLLED_BACK;
      TRANS_LOG(WARN, "stmt timeout of sub end trans", K(tx), K(result));
      break;
    }
2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
    case OB_TRANS_COMMITED: {
      commit_fin = true;
      // NOTE that success is returned if xa rollback
      tx.commit_out_ = OB_SUCCESS;
      tx.state_ = ObTxDesc::State::SUB_COMMITTED;
      break;
    }
    case OB_TRANS_ROLLBACKED:
    case OB_TRANS_KILLED: {
      commit_fin = true;
      tx.state_ = ObTxDesc::State::SUB_ROLLBACKED;
      if (is_rollback) {
        tx.commit_out_ = OB_SUCCESS;
      } else {
        tx.commit_out_ = result;
      }
      break;
    }
W
wangzelin.wzl 已提交
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
    case OB_SUCCESS: {
      commit_fin = true;
      tx.commit_out_ = OB_SUCCESS;
      if (is_rollback) {
        tx.state_ = ObTxDesc::State::SUB_ROLLBACKED;
      } else {
        tx.state_ = ObTxDesc::State::SUB_COMMITTED;
      }
      break;
    }
    case OB_TRANS_UNKNOWN: {
      commit_fin = true;
      tx.state_ = ObTxDesc::State::COMMIT_UNKNOWN;
      tx.commit_out_ = result;
      break;
    }
    default: {
      commit_fin = false;
      TRANS_LOG(WARN, "recv unrecongized commit result, just ignore", K(result), K(tx));
      break;
    }
  }
  if (commit_fin) {
    if (tx.commit_task_.is_registered()) {
      if (OB_FAIL(unregister_commit_retry_task_(tx))) {
        TRANS_LOG(ERROR, "deregister timeout task fail", K(tx));
      }
    }
  }
  return ret;
}

int ObTransService::check_scheduler_status(const share::ObLSID &ls_id)
{
  int ret = OB_SUCCESS;

  if (IS_NOT_INIT) {
    TRANS_LOG(WARN, "ObTransService not inited");
    ret = OB_NOT_INIT;
  } else if (OB_UNLIKELY(!is_running_)) {
    TRANS_LOG(WARN, "ObTransService is not running");
    ret = OB_NOT_RUNNING;
  } else if (!ls_id.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    TRANS_LOG(WARN, "invalid argument", KR(ret), K(ls_id));
  } else if (OB_FAIL(tx_ctx_mgr_.check_scheduler_status(ls_id))) {
    TRANS_LOG(WARN, "check_scheduler_status error", KR(ret), K(ls_id));
  } else {
    TRANS_LOG(INFO, "check_scheduler_status success", K(ls_id));
  }

  return ret;
}

/*
 * create_in_txn_implicit_savepoint - create an implicit savepoint when txn is active
 */
int ObTransService::create_in_txn_implicit_savepoint(ObTxDesc &tx, int64_t &savepoint)
{
  int ret = OB_SUCCESS;

  ObTxParam tx_param;
  tx_param.timeout_us_ = tx.timeout_us_;
  tx_param.lock_timeout_us_ = tx.lock_timeout_us_;
  tx_param.access_mode_ = tx.access_mode_;
  tx_param.isolation_ = tx.isolation_;
  tx_param.cluster_id_ = tx.cluster_id_;
  if (tx_param.is_valid()) {
    ret = create_implicit_savepoint(tx, tx_param, savepoint);
  } else {
    ret = OB_ERR_UNEXPECTED;
    TRANS_LOG(WARN, "create in txn implicit savepoint, but txn not in txn", K(ret), K(tx));
  }
  return ret;
}

3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
// for standby
int ObTransService::get_tx_ctx_for_standby_(const share::ObLSID &ls_id,
                                           const ObTransID &tx_id,
                                           ObPartTransCtx *&ctx)
{
  return tx_ctx_mgr_.get_tx_ctx(ls_id, tx_id, true, ctx);
}

int ObTransService::check_for_standby(const share::ObLSID &ls_id,
                                      const ObTransID &tx_id,
                                      const SCN &snapshot,
                                      bool &can_read,
                                      SCN &trans_version,
                                      bool &is_determined_state)
{
  int ret = OB_SUCCESS;
  ObPartTransCtx *ctx = NULL;
  if (OB_SUCC(get_tx_ctx_for_standby_(ls_id, tx_id, ctx))) {
    ret = ctx->check_for_standby(snapshot, can_read, trans_version, is_determined_state);
    revert_tx_ctx_(ctx);
  } else {
    ret = OB_ERR_SHARED_LOCK_CONFLICT;
  }
  return ret;
}

O
obdev 已提交
3061 3062 3063 3064 3065 3066 3067 3068
int ObTransService::handle_trans_ask_state(const ObAskStateMsg &msg,
                                           obrpc::ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ObTransID tx_id = msg.get_trans_id();
  share::ObLSID coord = msg.get_receiver();
  ObPartTransCtx *ctx = NULL;
  ObAskStateRespMsg resp;
3069
  if (OB_FAIL(get_tx_ctx_for_standby_(coord, tx_id, ctx))) {
O
obdev 已提交
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
    TRANS_LOG(INFO, "fail to get coordinator tx context", K(ret), K(tx_id), K(coord));
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
      ObStateInfo state_info;
      state_info.ls_id_ = coord;
      state_info.snapshot_version_ = msg.snapshot_;
      if (OB_FAIL(check_and_fill_state_info(tx_id, state_info))) {
        TRANS_LOG(WARN, "fill state info fail", K(ret), K(coord), K(tx_id), K(state_info));
      } else if (OB_FAIL(resp.state_info_array_.push_back(state_info))) {
        TRANS_LOG(WARN, "state info array push back fail", K(ret), K(coord), K(tx_id), K(state_info));
      }
    }
  } else if (OB_FAIL(ctx->handle_trans_ask_state(msg.snapshot_, resp))) {
    TRANS_LOG(WARN, "fail to handle trans ask state", K(ret), K(coord), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  if (OB_SUCC(ret)) {
    build_tx_ask_state_resp_(resp, msg);
    if (OB_FAIL(rpc_->post_msg(msg.sender_addr_, resp))) {
      TRANS_LOG(WARN, "post ask state msg fail", K(ret), K(resp));
    }
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle trans ask state", K(ret), K(msg), K(resp));
  return ret;
}

int ObTransService::check_and_fill_state_info(const ObTransID &tx_id, ObStateInfo &state_info)
{
  int ret = OB_SUCCESS;
  int tx_state = ObTxData::RUNNING;
  SCN version;
  if (OB_FAIL(get_tx_state_from_tx_table_(state_info.ls_id_, tx_id, tx_state, version))) {
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
      ObLSService *ls_svr =  MTL(ObLSService *);
      ObLSHandle handle;
      ObLS *ls = nullptr;
      if (OB_ISNULL(ls_svr)) {
        ret = OB_ERR_UNEXPECTED;
        TRANS_LOG(WARN, "log stream service is NULL", K(ret));
      } else if (OB_FAIL(ls_svr->get_ls(state_info.ls_id_, handle, ObLSGetMod::TRANS_MOD))) {
        TRANS_LOG(WARN, "get log stream failed", K(ret));
      } else if (OB_ISNULL(ls = handle.get_ls())) {
        ret = OB_TRANS_CTX_NOT_EXIST;
      } else if (OB_FAIL(ls->get_ls_replica_readable_scn(version))) {
        TRANS_LOG(WARN, "get ls replica readable scn fail", K(ret), K(ls_id));
      } else if (version <= state_info.snapshot_version_) {
        state_info.state_ = ObTxState::UNKNOWN;
        state_info.version_ = version;
      } else {
        ret = OB_TRANS_CTX_NOT_EXIST;
      }
3124
      TRANS_LOG(INFO, "get tx state from tx table fail", K(ret), K(state_info), K(tx_id), K(version));
3125
    }
O
obdev 已提交
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
  } else {
    switch (tx_state) {
      case ObTxData::COMMIT:
        state_info.state_ = ObTxState::COMMIT;
        break;
      case ObTxData::ABORT:
        state_info.state_ = ObTxState::ABORT;
        break;
      case ObTxData::RUNNING:
      default:
        ret = OB_ERR_UNEXPECTED;
        TRANS_LOG(WARN, "tx in-progress but ctx miss", K(ret), K(tx_state), K(tx_id), K(state_info));
    }
    state_info.version_ = version;
  }
  return ret;
}

void ObTransService::build_tx_ask_state_resp_(ObAskStateRespMsg &resp, const ObAskStateMsg &msg)
{
  resp.cluster_version_ = msg.cluster_version_;
  resp.tenant_id_ = msg.tenant_id_;
  resp.tx_id_ = msg.tx_id_;
  resp.sender_addr_ = self_;
  resp.sender_ = msg.receiver_;
  resp.request_id_ = ObTimeUtility::current_time();
  resp.cluster_id_ = msg.cluster_id_;
  resp.receiver_ = msg.sender_;
}

int ObTransService::handle_trans_ask_state_response(const ObAskStateRespMsg &msg,
                                                    obrpc::ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ObTransID tx_id = msg.get_trans_id();
  share::ObLSID ls_id = msg.get_receiver();
  ObPartTransCtx *ctx = NULL;
3163
  if (OB_FAIL(get_tx_ctx_for_standby_(ls_id, tx_id, ctx))) {
O
obdev 已提交
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
    TRANS_LOG(INFO, "fail to get tx context", K(ret), K(tx_id), K(ls_id));
  } else if (OB_FAIL(ctx->handle_trans_ask_state_resp(msg))) {
    TRANS_LOG(WARN, "fail to handle trans ask state resp", K(ret), K(ls_id), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle trans ask state resp state", K(ret), K(msg));
  return ret;
}

int ObTransService::handle_trans_collect_state(const ObCollectStateMsg &msg,
                                               obrpc::ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ObTransID tx_id = msg.get_trans_id();
  share::ObLSID ls_id = msg.get_receiver();
  ObPartTransCtx *ctx = NULL;
  ObCollectStateRespMsg resp;
3185
  if (OB_FAIL(get_tx_ctx_for_standby_(ls_id, tx_id, ctx))) {
O
obdev 已提交
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
    TRANS_LOG(INFO, "fail to get tx context", K(ret), K(tx_id), K(ls_id));
    if (OB_TRANS_CTX_NOT_EXIST == ret) {
      ObStateInfo state_info;
      state_info.ls_id_ = ls_id;
      if (OB_FAIL(check_and_fill_state_info(tx_id, state_info))) {
        TRANS_LOG(WARN, "fill state info fail", K(ret), K(ls_id), K(tx_id), K(state_info));
      } else {
        resp.state_info_ = state_info;
      }
    }
  } else if (OB_FAIL(ctx->handle_trans_collect_state(resp.state_info_, msg.snapshot_))) {
    TRANS_LOG(WARN, "fail to handle trans ask state", K(ret), K(ls_id), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  if (OB_SUCC(ret)) {
    build_tx_collect_state_resp_(resp, msg);
    if (OB_FAIL(rpc_->post_msg(msg.sender_addr_, resp))) {
      TRANS_LOG(WARN, "post tx collect state resp fail", K(ret), K(resp));
    }
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  TRANS_LOG(INFO, "handle trans collect state", K(ret), K(msg), K(resp));
  return ret;
}

void ObTransService::build_tx_collect_state_resp_(ObCollectStateRespMsg &resp, const ObCollectStateMsg &msg)
{
  resp.cluster_version_ = msg.cluster_version_;
  resp.tenant_id_ = msg.tenant_id_;
  resp.tx_id_ = msg.tx_id_;
  resp.sender_addr_ = self_;
  resp.sender_ = msg.receiver_;
  resp.request_id_ = ObTimeUtility::current_time();
  resp.cluster_id_ = msg.cluster_id_;
  resp.receiver_ = msg.sender_;
  resp.state_info_.snapshot_version_ = msg.snapshot_;
}

int ObTransService::handle_trans_collect_state_response(const ObCollectStateRespMsg &msg,
                                                        obrpc::ObTransRpcResult &result)
{
  int ret = OB_SUCCESS;
  ObTransID tx_id = msg.get_trans_id();
  share::ObLSID ls_id = msg.get_receiver();
  ObPartTransCtx *ctx = NULL;
3234
  if (OB_FAIL(get_tx_ctx_for_standby_(ls_id, tx_id, ctx))) {
O
obdev 已提交
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
    TRANS_LOG(INFO, "fail to get tx context", K(ret), K(tx_id), K(ls_id));
  } else if (OB_FAIL(ctx->handle_trans_collect_state_resp(msg))) {
    TRANS_LOG(WARN, "fail to handle trans collect state resp", K(ret), K(ls_id), K(tx_id));
  }
  if (OB_NOT_NULL(ctx)) {
    revert_tx_ctx_(ctx);
  }
  result.reset();
  result.init(ret, msg.get_timestamp());
  return ret;
}

W
wangzelin.wzl 已提交
3247 3248
} // transaction
} // ocenabase