ob_partition_migrator.cpp 513.5 KB
Newer Older
O
oceanbase-admin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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 190 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 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 446 447 448 449 450 451 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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 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 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
/**
 * 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.
 */

#define USING_LOG_PREFIX STORAGE
#include "lib/utility/ob_tracepoint.h"
#include "lib/hash/ob_hashset.h"
#include "share/ob_force_print_log.h"
#include "storage/ob_partition_migrator.h"
#include "storage/blocksstable/ob_block_sstable_struct.h"
#include "storage/ob_sstable.h"
#include "storage/ob_partition_service.h"
#include "storage/ob_partition_log.h"
#include "storage/ob_partition_base_data_ob_reader.h"
#include "observer/ob_server_struct.h"
#include "observer/ob_server.h"
#include "clog/ob_clog_history_reporter.h"
#include "share/scheduler/ob_sys_task_stat.h"
#include "share/partition_table/ob_united_pt_operator.h"
#include "storage/ob_partition_base_data_restore_reader.h"
#include "storage/ob_partition_base_data_backup.h"
#include "storage/ob_partition_base_data_validate.h"
#include "share/ob_task_define.h"
#include "share/backup/ob_backup_struct.h"
#include "ob_migrate_logic_row_writer.h"
#include "ob_table_mgr.h"
#include "ob_migrate_macro_block_writer.h"
#include "share/ob_debug_sync_point.h"
#include "ob_storage_struct.h"
#include "observer/omt/ob_tenant_node_balancer.h"
#include "share/ob_force_print_log.h"
#include "storage/ob_partition_migrator_table_key_mgr.h"
#include "storage/ob_partition_migration_status.h"
#include "storage/ob_pg_all_meta_checkpoint_reader.h"
#include "storage/blocksstable/ob_store_file_system.h"
#include "storage/ob_data_macro_id_iterator.h"
#include "share/partition_table/ob_united_pt_operator.h"
#include "share/backup/ob_backup_path.h"
#include "storage/ob_partition_base_data_physical_restore.h"
#include "storage/ob_file_system_util.h"
#include "storage/ob_partition_backup.h"
#include "storage/ob_pg_storage.h"
#include "storage/ob_partition_scheduler.h"

namespace oceanbase {
using namespace common;
using namespace common::hash;
using namespace share;
using namespace obrpc;
using namespace blocksstable;
using namespace oceanbase::share::schema;
using namespace omt;
using namespace transaction;

namespace storage {
#define MIGRATOR (::oceanbase::storage::ObPartitionMigrator::get_instance())
typedef common::hash::ObHashMap<uint64_t, ObSSTable*> SSTableMap;

int ObPartMigrationTask::assign(const ObPartMigrationTask& task)
{
  int ret = common::OB_SUCCESS;

  if (task.ctx_.is_valid()) {
    ret = OB_NOT_SUPPORTED;
    LOG_ERROR("cannot assign valid ctx", K(ret), K(task));
  } else {
    arg_ = task.arg_;
    status_ = task.status_;
    result_ = task.result_;
    need_reset_migrate_status_ = task.need_reset_migrate_status_;
    during_migrating_ = task.during_migrating_;
  }
  return ret;
}

ObMacroBlockReuseMgr::ObMacroBlockReuseMgr() : full_map_(), reuse_map_(), allocator_(ObModIds::OB_PARTITION_MIGRATOR)
{}

ObMacroBlockReuseMgr::~ObMacroBlockReuseMgr()
{
  reset();
}

// TODO(): split reuse macro block not support yet
int ObMacroBlockReuseMgr::build_reuse_macro_map(
    ObMigrateCtx& ctx, const ObITable::TableKey& table_key, const common::ObIArray<ObSSTablePair>& macro_block_list)
{
  int ret = OB_SUCCESS;
  ObTablesHandle tables_handle;
  ObDataMacroIdIterator data_macro_iter;
  ObIPartitionGroup* pg = ctx.get_partition();
  if (OB_ISNULL(pg)) {
    ret = OB_ERR_SYS;
    LOG_WARN("error sys, pg must not be null", K(ret));
  } else if (ObITable::MAJOR_SSTABLE != table_key.table_type_) {
    // only major sstable can reuse macro block
  } else if (OB_FAIL(data_macro_iter.init(ObPartitionService::get_instance(), pg))) {
    LOG_WARN("fail to init pg iterator", K(ret));
  } else if (OB_FAIL(full_map_.init(ObModIds::OB_PARTITION_MIGRATOR, pg->get_partition_key().get_tenant_id()))) {
    LOG_WARN("fail to init hash map", K(ret));
  } else if (!reuse_map_.is_inited() &&
             OB_FAIL(reuse_map_.init(ObModIds::OB_PARTITION_MIGRATOR, pg->get_partition_key().get_tenant_id()))) {
    LOG_WARN("fail to init hash map", K(ret));
  } else {
    ObMacroBlockInfoPair info;
    ObTenantFileKey file_key;
    const ObMacroBlockMetaV2* meta = nullptr;
    while (OB_SUCC(ret)) {
      if (OB_FAIL(data_macro_iter.get_next_macro_info(info, file_key))) {
        if (OB_ITER_END == ret) {
          ret = OB_SUCCESS;
          break;
        }
      } else {
        ObMajorMacroBlockKey key;
        meta = info.meta_.meta_;
        key.table_id_ = meta->table_id_;
        key.partition_id_ = meta->partition_id_;
        key.data_version_ = meta->data_version_;
        key.data_seq_ = meta->data_seq_;
        if (OB_FAIL(full_map_.insert_or_update(key, info))) {
          LOG_WARN("fail to set macro block map", K(ret));
        }
      }
    }

    for (int64_t i = 0; OB_SUCC(ret) && i < macro_block_list.count(); ++i) {
      ObMacroBlockMetaV2* dst_meta = nullptr;
      ObMacroBlockSchemaInfo* dst_schema = nullptr;
      ObMacroBlockInfoPair info;
      ObMajorMacroBlockKey key;
      key.table_id_ = table_key.table_id_;
      key.partition_id_ = table_key.pkey_.get_partition_id();
      key.data_version_ = macro_block_list.at(i).data_version_;
      key.data_seq_ = macro_block_list.at(i).data_seq_;
      if (OB_FAIL(full_map_.get(key, info))) {
        if (OB_ENTRY_NOT_EXIST == ret) {
          ret = OB_SUCCESS;
        } else {
          LOG_WARN("fail to get from hash map", K(ret), K(key));
        }
      } else {
        FLOG_INFO("reuse a macro block", K(key), K(*info.meta_.meta_));
        if (OB_FAIL(ctx.add_major_block_id(info.block_id_))) {
          LOG_WARN("fail to add major block id", K(ret));
        } else if (OB_FAIL(info.meta_.meta_->deep_copy(dst_meta, allocator_))) {
          LOG_WARN("fail to deep copy meta", K(ret));
        } else if (OB_FAIL(info.meta_.schema_->deep_copy(dst_schema, allocator_))) {
          LOG_WARN("fail to deep copy macro schema", K(ret));
        } else {
          ObFullMacroBlockMeta full_meta;
          full_meta.schema_ = dst_schema;
          full_meta.meta_ = dst_meta;
          if (OB_FAIL(reuse_map_.insert_or_update(key, ObMacroBlockInfoPair(info.block_id_, full_meta)))) {
            LOG_WARN("fail to set reuse map", K(ret));
          }
        }
        if (OB_FAIL(ret)) {
          if (nullptr != dst_meta) {
            dst_meta->~ObMacroBlockMetaV2();
            dst_meta = nullptr;
          }
          if (nullptr != dst_schema) {
            dst_schema->~ObMacroBlockSchemaInfo();
            dst_schema = nullptr;
          }
        }
      }
    }
  }
  full_map_.destroy();
  return ret;
}

void ObMacroBlockReuseMgr::reset()
{
  full_map_.destroy();
  RemoveFunctor functor;
  reuse_map_.remove_if(functor);
  reuse_map_.destroy();
  allocator_.reset();
}

bool ObMacroBlockReuseMgr::RemoveFunctor::operator()(
    const blocksstable::ObMajorMacroBlockKey& block_key, blocksstable::ObMacroBlockInfoPair& info)
{
  UNUSED(block_key);
  if (nullptr != info.meta_.meta_) {
    info.meta_.meta_->~ObMacroBlockMetaV2();
  }
  if (nullptr != info.meta_.schema_) {
    info.meta_.schema_->~ObMacroBlockSchemaInfo();
  }
  return true;
}

int ObMacroBlockReuseMgr::get_reuse_macro_meta(
    const blocksstable::ObMajorMacroBlockKey& block_key, blocksstable::ObMacroBlockInfoPair& info)
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(reuse_map_.get(block_key, info))) {
    if (OB_ENTRY_NOT_EXIST != ret) {
      LOG_WARN("fail to get from reuse map", K(ret));
    }
  }
  return ret;
}

ObPartitionGroupInfoResult::ObPartitionGroupInfoResult() : result_(), choose_src_info_()
{}

void ObPartitionGroupInfoResult::reset()
{
  result_.reset();
  choose_src_info_.reset();
}

int ObPartitionGroupInfoResult::assign(const ObPartitionGroupInfoResult& result)
{
  int ret = OB_SUCCESS;
  reset();
  if (OB_FAIL(result_.assign(result.result_))) {
    STORAGE_LOG(WARN, "fail to assign result", K(ret), K(result));
  } else {
    choose_src_info_ = result.choose_src_info_;
  }
  return ret;
}

ObMigrateCtx::ObMigrateCtx()
    : lock_(),
      replica_op_arg_(),
      macro_indexs_(NULL),
      action_(UNKNOWN),
      result_(OB_SUCCESS),
      doing_task_cnt_(0),
      total_task_cnt_(0),
      need_rebuild_(false),
      partition_guard_(),
      replica_state_(OB_UNKNOWN_REPLICA),
      local_publish_version_(0),
      local_last_replay_log_id_(0),
      last_check_replay_ts_(0),
      create_ts_(0),
      task_id_(),
      copy_size_(0),
      continue_fail_count_(0),
      rebuild_count_(-1),
      finish_ts_(0),
      wait_replay_start_ts_(0),
      wait_minor_merge_start_ts_(0),
      last_confirmed_log_id_(OB_INVALID_ID),
      last_confirmed_log_ts_(OB_INVALID_TIMESTAMP),
      group_task_(NULL),
      restore_info_(),
      during_migrating_(false),
      need_online_for_rebuild_(false),
      trace_id_array_(),
      major_block_id_array_ptr_(NULL),
      curr_major_block_array_index_(0),
      can_rebuild_(true),
      pg_meta_(),
      part_ctx_array_(),
      need_offline_(false),
      is_restore_(share::REPLICA_NOT_RESTORE),
      use_slave_safe_read_ts_(false),
      need_report_checksum_(false),
      data_statics_(),
      is_copy_cover_minor_(true),
      mig_src_file_id_(OB_INVALID_DATA_FILE_ID),
      mig_dest_file_id_(OB_INVALID_DATA_FILE_ID),
      src_suspend_ts_(0),
      is_takeover_finished_(false),
      is_member_change_finished_(false),
      local_last_replay_log_ts_(0),
      old_trans_table_seq_(-1),
      create_new_pg_(false),
      restore_meta_reader_(nullptr),
      backup_meta_reader_(nullptr),
      fetch_pg_info_compat_version_(ObFetchPGInfoArg::FETCH_PG_INFO_ARG_COMPAT_VERSION_V2),
      physical_backup_ctx_()
{}

ObMigrateCtx::~ObMigrateCtx()
{
  for (int64_t i = 0; i < 2; ++i) {
    for (int64_t j = 0; j < major_block_id_array_[i].count(); ++j) {
      if (major_block_id_array_[i].at(j).is_valid()) {
        get_partition()->get_storage_file()->dec_ref(major_block_id_array_[i].at(j));
        major_block_id_array_[i].at(j).reset();
      }
    }
  }
  if (NULL != MIGRATOR.get_cp_fty()) {
    if (NULL != restore_meta_reader_) {
      MIGRATOR.get_cp_fty()->free(restore_meta_reader_);
    }
    if (NULL != backup_meta_reader_) {
      MIGRATOR.get_cp_fty()->free(backup_meta_reader_);
    }
    if (NULL != macro_indexs_) {
      MIGRATOR.get_cp_fty()->free(macro_indexs_);
    }
  }
}

bool ObMigrateCtx::is_valid() const
{
  return replica_op_arg_.is_valid() && UNKNOWN != action_ && doing_task_cnt_ >= 0 && total_task_cnt_ >= 0 &&
         NULL != group_task_
      // replica_state_ maybe OB_ERROR_REPLICA in init
      // partition maybe null
      // migrate_src mybe invalid
      ;
}

int ObMigrateCtx::notice_start_part_task()
{
  int ret = OB_SUCCESS;
  if (NULL != group_task_) {
    if (OB_SUCCESS !=
        (ret = group_task_->set_part_task_start(replica_op_arg_.key_, replica_op_arg_.validate_arg_.backup_set_id_))) {
      STORAGE_LOG(ERROR, "set_part_task_start failed", K(ret), K(*this));
    } else {
      STORAGE_LOG(INFO, "set_part_task_start", K(ret), K(*this));
    }
  }

  return ret;
}

int ObMigrateCtx::notice_finish_part_task()
{
  int ret = OB_SUCCESS;
  if (NULL != group_task_) {
    SMART_VAR(ObReplicaOpArg, tmp_replica_op_arg)
    {
      tmp_replica_op_arg = replica_op_arg_;
      if (OB_SUCCESS != (ret = group_task_->set_part_task_finish(replica_op_arg_.key_,
                             result_,
                             task_id_,
                             during_migrating_,
                             replica_op_arg_.validate_arg_.backup_set_id_))) {
        STORAGE_LOG(ERROR, "set_part_task_finish failed", K(ret), K(tmp_replica_op_arg));
      } else {
        STORAGE_LOG(INFO, "set_part_task_finish", K(ret), K(tmp_replica_op_arg));
      }
    }
  }

  return ret;
}

void ObMigrateCtx::set_result_code(const int32_t result)
{
  const bool write_lock = true;
  ObMigrateCtxGuard guard(write_lock, *this);
  if (OB_SUCCESS == result_) {
    result_ = result;
    LOG_WARN("record result code", K(result), K(lbt()));
  }
}

ObMigrateCtxGuard::ObMigrateCtxGuard(const bool is_write_lock, ObMigrateCtx& ctx) : ctx_(ctx)
{
  int tmp_ret = OB_SUCCESS;

  if (is_write_lock) {
    if (OB_SUCCESS != (tmp_ret = ctx_.lock_.wrlock())) {
      STORAGE_LOG(ERROR, "failed to wrlock", K(tmp_ret));
    }
  } else {
    if (OB_SUCCESS != (tmp_ret = ctx_.lock_.rdlock())) {
      STORAGE_LOG(ERROR, "failed to rdlock", K(tmp_ret));
    }
  }
}

ObMigrateCtxGuard::~ObMigrateCtxGuard()
{
  ctx_.lock_.unlock();
}

int ObMigrateCtx::update_partition_migration_status() const
{
  int ret = OB_SUCCESS;
  const ObMigrateCtx& ctx = *this;

  if (!ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(ctx));
  } else {
    ObPartitionMigrationStatusGuard status_guard;
    ObPartitionMigrationStatus* status = NULL;
    if (OB_FAIL(ObPartitionMigrationStatusMgr::get_instance().get_status(ctx.task_id_, status_guard))) {
      STORAGE_LOG(WARN, "failed to get partition status", K(ret), K(ctx));
    } else if (NULL == (status = status_guard.getStatus())) {
      ret = OB_ENTRY_NOT_EXIST;
      STORAGE_LOG(WARN, "status not found", K(ret), K(ctx));
    } else {
      // status->task_id_; should not change
      // status->pkey_; should not change
      status->src_ = ctx.replica_op_arg_.data_src_.get_server();
      // status->dest_; should not change
      status->clog_parent_ = ctx.clog_parent_;
      status->result_ = ctx.result_;
      status->start_time_ = ctx.create_ts_;
      status->action_ = ctx.action_;
      status->replica_state_ = ctx.replica_state_;
      status->doing_task_count_ = ctx.doing_task_cnt_;
      status->total_task_count_ = ctx.total_task_cnt_;
      status->rebuild_count_ = ctx.rebuild_count_;
      status->continue_fail_count_ = ctx.continue_fail_count_;
      status->finish_time_ = ctx.finish_ts_;

      status->data_statics_.total_macro_block_ = ATOMIC_LOAD(&ctx.data_statics_.total_macro_block_);
      status->data_statics_.ready_macro_block_ = ATOMIC_LOAD(&ctx.data_statics_.ready_macro_block_);
      status->data_statics_.major_count_ = ATOMIC_LOAD(&ctx.data_statics_.major_count_);
      status->data_statics_.mini_minor_count_ = ATOMIC_LOAD(&ctx.data_statics_.mini_minor_count_);
      status->data_statics_.normal_minor_count_ = ATOMIC_LOAD(&ctx.data_statics_.normal_minor_count_);
      status->data_statics_.buf_minor_count_ = ATOMIC_LOAD(&ctx.data_statics_.buf_minor_count_);
      // allow comment truncation, no need to set ret
      (void)ctx.fill_comment(status->comment_, sizeof(status->comment_));

      STORAGE_LOG(INFO, "update migration status", K(*status));
    }
  }

  return ret;
}

bool ObMigrateCtx::is_only_copy_sstable() const
{
  return COPY_GLOBAL_INDEX_OP == replica_op_arg_.type_ || COPY_LOCAL_INDEX_OP == replica_op_arg_.type_ ||
         RESTORE_REPLICA_OP == replica_op_arg_.type_ || RESTORE_FOLLOWER_REPLICA_OP == replica_op_arg_.type_ ||
         BACKUP_REPLICA_OP == replica_op_arg_.type_ || RESTORE_STANDBY_OP == replica_op_arg_.type_ ||
         VALIDATE_BACKUP_OP == replica_op_arg_.type_ || LINK_SHARE_MAJOR_OP == replica_op_arg_.type_;
}

bool ObMigrateCtx::is_copy_index() const
{
  return COPY_GLOBAL_INDEX_OP == replica_op_arg_.type_ || COPY_LOCAL_INDEX_OP == replica_op_arg_.type_;
}

int ObMigrateCtx::add_major_block_id(const MacroBlockId& macro_block_id)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(major_block_id_array_ptr_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "major block id array ptr should not be NULL", K(ret));
  } else {
    common::SpinWLockGuard guard(lock_);
    if (OB_FAIL(major_block_id_array_ptr_->push_back(macro_block_id))) {
      STORAGE_LOG(WARN, "fail to add major block key into array", K(ret));
    } else if (OB_FAIL(get_partition()->get_storage_file()->inc_ref(macro_block_id))) {
      major_block_id_array_ptr_->pop_back();
      STORAGE_LOG(WARN, "fail to inc ref, ", K(ret), K(macro_block_id));
    }
  }
  return ret;
}

void ObMigrateCtx::free_old_macro_block()
{
  int ret = OB_SUCCESS;
  common::SpinWLockGuard guard(lock_);
  int64_t index = (curr_major_block_array_index_ + 1) % 2;
  for (int64_t i = 0; i < major_block_id_array_[index].count(); ++i) {
    if (OB_FAIL(get_partition()->get_storage_file()->dec_ref(major_block_id_array_[index].at(i)))) {
      STORAGE_LOG(WARN, "fail to dec ref, ", K(ret), K(major_block_id_array_[index].at(i)));
    }
  }
  major_block_id_array_[index].reuse();
}

void ObMigrateCtx::calc_need_retry()
{
  common::SpinWLockGuard guard(lock_);
  if (!need_rebuild_) {
    LOG_INFO("ObParGroupMigrationTask do not need rebuild", K(*this));
  } else if (rebuild_count_ < GCONF.sys_bkgd_migration_retry_num) {
    rebuild_count_++;
  } else {
    need_rebuild_ = false;
  }
}

void ObMigrateCtx::rebuild_migrate_ctx()
{
  common::SpinWLockGuard guard(lock_);
  action_ = ObMigrateCtx::INIT;
  result_ = OB_SUCCESS;
  doing_task_cnt_ = 1;
  total_task_cnt_++;
  need_rebuild_ = false;
  need_online_for_rebuild_ = false;
  part_ctx_array_.reset();
  need_report_checksum_ = false;
  data_statics_.reset();
  trans_table_handle_.reset();
  old_trans_table_seq_ = -1;
  create_new_pg_ = false;
  if (BACKUP_REPLICA_OP != replica_op_arg_.type_) {
    pg_meta_.reset();
  }
  local_publish_version_ = 0;
  local_last_replay_log_ts_ = 0;
  fetch_pg_info_compat_version_ = ObFetchPGInfoArg::FETCH_PG_INFO_ARG_COMPAT_VERSION_V2;
  local_last_replay_log_id_ = 0;
  physical_backup_ctx_.reset();
}

int ObMigrateCtx::generate_and_schedule_migrate_dag()
{
  int ret = OB_SUCCESS;
  ObBaseMigrateDag* dag = NULL;
  ObMigratePrepareTask* prepare_task = NULL;
  if (BACKUP_REPLICA_OP == replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("generate and schedule migrate dag get unexpected replica op", K(ret), K(*this));
  } else {
    {
      common::SpinWLockGuard guard(lock_);
      if (OB_FAIL(alloc_migrate_dag(dag))) {
        LOG_WARN("failed to alloc migrate dag", K(ret));
      } else if (OB_FAIL(dag->alloc_task(prepare_task))) {
        STORAGE_LOG(WARN, "Fail to alloc task, ", K(ret));
      } else if (OB_FAIL(prepare_task->init())) {
        STORAGE_LOG(WARN, "failed to init prepare_task", K(ret));
      } else if (OB_FAIL(dag->add_task(*prepare_task))) {
        STORAGE_LOG(WARN, "Fail to add task", K(ret), K(replica_op_arg_));
      } else if (OB_FAIL(ObDagScheduler::get_instance().add_dag(dag))) {
        STORAGE_LOG(WARN, "failed to add dag", K(ret), K(*dag));
        if (OB_SIZE_OVERFLOW != ret && OB_EAGAIN != ret) {
          LOG_WARN("Fail to add task", K(ret));
          ret = OB_EAGAIN;
        }
      } else {
        LOG_INFO("succeed to schedule migrate dag", K(*dag));
      }
    }
  }

  if (OB_FAIL(ret)) {
    result_ = ret;
    if (NULL != dag) {
      dag->clear();  // release dag ctx_
      ObDagScheduler::get_instance().free_dag(*dag);
    }
  }
  return ret;
}

int ObMigrateCtx::generate_and_schedule_backup_dag(const ObBackupDataType& backup_data_type)
{
  int ret = OB_SUCCESS;
  ObBackupDag* backup_dag = NULL;
  ObBackupPrepareTask* prepare_task = NULL;

  if (!backup_data_type.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate and schedule backup dag get invalid argument", K(ret), K(backup_data_type));
  } else if (BACKUP_REPLICA_OP != replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("generate and schedule backup dag get unexpected replica op", K(ret), K(*this));
  } else {
    {
      common::SpinWLockGuard guard(lock_);
      if (OB_FAIL(ObDagScheduler::get_instance().alloc_dag(backup_dag))) {
        LOG_WARN("failed to alloc backup dag", K(ret));
      } else if (OB_FAIL(backup_dag->init(backup_data_type, *this))) {
        LOG_WARN("failed to init migrate dag", K(ret));
      } else if (OB_FAIL(backup_dag->alloc_task(prepare_task))) {
        STORAGE_LOG(WARN, "Fail to alloc task, ", K(ret));
      } else if (OB_FAIL(prepare_task->init(
                     *MIGRATOR.get_cp_fty(), *MIGRATOR.get_bandwidth_throttle(), *MIGRATOR.get_partition_service()))) {
        STORAGE_LOG(WARN, "failed to init prepare_task", K(ret));
      } else if (OB_FAIL(backup_dag->add_task(*prepare_task))) {
        STORAGE_LOG(WARN, "Fail to add task", K(ret), K(replica_op_arg_));
      } else if (OB_FAIL(ObDagScheduler::get_instance().add_dag(backup_dag))) {
        STORAGE_LOG(WARN, "failed to add dag", K(ret), K(*backup_dag));
        if (OB_SIZE_OVERFLOW != ret && OB_EAGAIN != ret) {
          LOG_WARN("Fail to add task", K(ret));
          ret = OB_EAGAIN;
        }
      } else {
        LOG_INFO("succeed to schedule backup dag", K(*backup_dag));
      }
    }
  }

  if (OB_FAIL(ret)) {
    result_ = ret;
    if (NULL != backup_dag) {
      backup_dag->clear();  // release dag ctx_
      ObDagScheduler::get_instance().free_dag(*backup_dag);
    }
  }
  return ret;
}

bool ObMigrateCtx::is_need_retry(const int result) const
{
  bool ret = false;
  if (OB_NOT_INIT != result && OB_INVALID_ARGUMENT != result && OB_ERR_SYS != result && OB_INIT_TWICE != result &&
      OB_ERR_UNEXPECTED != result && OB_LOG_NOT_SYNC != result && OB_NO_NEED_REBUILD != result &&
      OB_SRC_DO_NOT_ALLOWED_MIGRATE != result && OB_NOT_SUPPORTED != result && OB_PG_IS_REMOVED != result &&
      can_rebuild_) {
    ret = true;
  }
  return ret;
}

// if local has partition full data, no need copy, return true
int ObMigrateCtx::change_replica_with_data(bool& is_replica_with_data)
{
  int ret = OB_SUCCESS;
  is_replica_with_data = false;

  if (CHANGE_REPLICA_OP != replica_op_arg_.type_) {
    is_replica_with_data = false;
    LOG_INFO("not change replica op");
  } else if (OB_ISNULL(partition_guard_.get_partition_group())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("partition should not be NULL", K(ret));
  } else {
    const ObReplicaType& replica_type = partition_guard_.get_partition_group()->get_replica_type();
    is_replica_with_data = ObReplicaTypeCheck::is_replica_with_ssstore(replica_type);
    LOG_INFO("get local replica type", K(is_replica_with_data), K(replica_type));
  }
  return ret;
}

int ObMigrateCtx::get_restore_clog_info(uint64_t& log_id, int64_t& acc_checksum) const
{
  int ret = OB_SUCCESS;

  if (OB_UNLIKELY(!replica_op_arg_.is_physical_restore_leader())) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid argument", K(ret), K(replica_op_arg_));
  } else if (OB_UNLIKELY(pg_meta_.is_valid())) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "restore pg meta is invalid", K(ret), K(pg_meta_));
  } else {
    log_id = pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();
    acc_checksum = pg_meta_.storage_info_.get_clog_info().get_accumulate_checksum();
  }
  return ret;
}

bool ObMigrateCtx::is_leader_restore_archive_data() const
{
  return replica_op_arg_.is_physical_restore_leader() && REPLICA_RESTORE_ARCHIVE_DATA == is_restore_;
}

// reset is_restore in add_replica when src is in restore process
int ObMigrateCtx::set_is_restore_for_add_replica(const int16_t src_is_restore)
{
  int ret = OB_SUCCESS;
  if (ADD_REPLICA_OP != replica_op_arg_.type_) {
    // do nothing
  } else {
    switch (src_is_restore) {
      case REPLICA_NOT_RESTORE:
      case REPLICA_LOGICAL_RESTORE_DATA:
      case REPLICA_RESTORE_DATA:
      case REPLICA_RESTORE_STANDBY:
      case REPLICA_RESTORE_CUT_DATA:
        is_restore_ = src_is_restore;
        break;
      case REPLICA_RESTORE_ARCHIVE_DATA:
      case REPLICA_RESTORE_LOG:
      case REPLICA_RESTORE_DUMP_MEMTABLE:
        is_restore_ = REPLICA_RESTORE_ARCHIVE_DATA;
        break;
      case REPLICA_RESTORE_WAIT_ALL_DUMPED:
        is_restore_ = REPLICA_RESTORE_WAIT_ALL_DUMPED;
        break;
      case REPLICA_RESTORE_MEMBER_LIST: {
        ret = OB_CANNOT_ADD_REPLICA_DURING_SET_MEMBER_LIST;
        STORAGE_LOG(WARN, "cannot add replica during set member list", K(ret), K(src_is_restore));
        break;
      }
      default: {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN, "unknown restore type", K(ret), K(src_is_restore));
        break;
      }
    }
  }
  return ret;
}

int ObMigrateCtx::alloc_migrate_dag(ObBaseMigrateDag*& base_migrate_dag)
{
  int ret = OB_SUCCESS;
  base_migrate_dag = NULL;
  if (!replica_op_arg_.is_valid()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "replica op arg is invlaid", K(ret), K(*this));
  } else if (VALIDATE_BACKUP_OP == replica_op_arg_.type_) {
    ObValidateDag* dag = NULL;
    if (OB_FAIL(ObDagScheduler::get_instance().alloc_dag(dag))) {
      LOG_WARN("failed to alloc validate dag", K(ret));
    } else if (FALSE_IT(base_migrate_dag = dag)) {
    } else if (OB_FAIL(dag->init(*this))) {
      LOG_WARN("failed to init validate dag", K(ret));
    }
  } else {
    ObMigrateDag* dag = NULL;
    if (OB_FAIL(ObDagScheduler::get_instance().alloc_dag(dag))) {
      LOG_WARN("failed to alloc migrate dag", K(ret));
    } else if (FALSE_IT(base_migrate_dag = dag)) {
    } else if (OB_FAIL(dag->init(*this))) {
      LOG_WARN("failed to init migrate dag", K(ret));
    }
  }

  if (OB_FAIL(ret)) {
    if (NULL != base_migrate_dag) {
      base_migrate_dag->clear();  // release dag ctx_
      ObDagScheduler::get_instance().free_dag(*base_migrate_dag);
      base_migrate_dag = nullptr;
    }
  }
  return ret;
}

ObPartitionMigrateCtx::ObPartitionMigrateCtx()
    : ctx_(NULL), copy_info_(), handle_(), is_partition_exist_(true), lock_(), need_reuse_local_minor_(true)
{}

bool ObPartitionMigrateCtx::is_valid() const
{
  bool bret = NULL != ctx_ && ctx_->is_valid() && copy_info_.is_valid();
  if (bret) {
    if (ctx_->is_copy_index() && !handle_.empty()) {
      bret = false;
    }
  }
  return bret;
}

void ObPartitionMigrateCtx::reset()
{
  ctx_ = NULL;
  copy_info_.reset();
  handle_.reset();
  is_partition_exist_ = true;
  need_reuse_local_minor_ = true;
}

int ObPartitionMigrateCtx::assign(const ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;
  if (!part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("assign partition migrate ctx get invalid argument", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(copy_info_.assign(part_migrate_ctx.copy_info_))) {
    LOG_WARN("failed to assign copy info", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(handle_.assign(part_migrate_ctx.handle_))) {
    LOG_WARN("failed to assign handle", K(ret));
  } else {
    ctx_ = part_migrate_ctx.ctx_;
    is_partition_exist_ = part_migrate_ctx.is_partition_exist_;
    need_reuse_local_minor_ = part_migrate_ctx.need_reuse_local_minor_;
  }
  return ret;
}

int ObPartitionMigrateCtx::add_sstable(ObSSTable& sstable)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* pg = NULL;
  const int64_t max_kept_major_version_number = 0;
  const bool in_slog_trans = false;

  if (OB_ISNULL(ctx_)) {
    ret = OB_ERR_SYS;
    LOG_WARN("ctx must not null", K(ret), K(*this));
O
obdev 已提交
789
  } else if (!ctx_->is_copy_index()) {
O
oceanbase-admin 已提交
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 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    common::SpinWLockGuard guard(lock_);
    if (OB_FAIL(handle_.add_table(&sstable))) {
      LOG_WARN("failed to add table", K(ret));
    } else {
      FLOG_INFO("hold sstable in ctx", "pkey", copy_info_.meta_.pkey_, "table_key", sstable.get_key());
    }
  } else {
    if (OB_ISNULL(pg = ctx_->partition_guard_.get_partition_group())) {
      ret = OB_ERR_SYS;
      LOG_ERROR("partition must not null", K(ret));
    } else if (OB_FAIL(pg->get_pg_storage().add_sstable(
                   copy_info_.meta_.pkey_, &sstable, max_kept_major_version_number, in_slog_trans))) {
      LOG_WARN("failed to add sstable", K(ret));
    } else {
      FLOG_INFO("add sstable to pg", "pkey", copy_info_.meta_.pkey_, "table_key", sstable.get_key());
    }
  }
  return ret;
}

int ObMigrateFinishPhysicalTask::check_sstable_meta(
    const blocksstable::ObSSTableBaseMeta& src_meta, const blocksstable::ObSSTableBaseMeta& write_meta)
{
  int ret = OB_SUCCESS;
  if (src_meta.index_id_ != write_meta.index_id_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "index_id_ not match", K(ret));
  } else if (src_meta.row_count_ != write_meta.row_count_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "row_count_ not match", K(ret));
  } else if (src_meta.occupy_size_ != write_meta.occupy_size_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "occupy_size_ not match", K(ret));
  } else if (src_meta.data_checksum_ != write_meta.data_checksum_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "data checksum not match", K(ret));
  } else if (src_meta.row_checksum_ != write_meta.row_checksum_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "row_checksum_ not match", K(ret));
  } else if (src_meta.data_version_ != write_meta.data_version_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "data_version_ not match", K(ret));
  } else if (src_meta.rowkey_column_count_ != write_meta.rowkey_column_count_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "rowkey_column_count_ not match", K(ret));
  } else if (src_meta.table_type_ != write_meta.table_type_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "table_type_ not match", K(ret));
  } else if (src_meta.index_type_ != write_meta.index_type_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "index_type_ not match", K(ret));
  } else if (src_meta.macro_block_count_ != write_meta.macro_block_count_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "macro_block_count_ not match", K(ret));
  } else if (src_meta.lob_macro_block_count_ != write_meta.lob_macro_block_count_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "lob_macro_block_count_ not match", K(ret));
  } else if (src_meta.column_cnt_ != write_meta.column_cnt_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "column_cnt_ not match", K(ret));
  } else if (src_meta.total_sstable_count_ != write_meta.total_sstable_count_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "total_sstable_count_ not match", K(ret));
  } else if (src_meta.max_logic_block_index_ != write_meta.max_logic_block_index_) {
    ret = OB_INVALID_DATA;
    STORAGE_LOG(WARN, "max_logic_block_index_ not match", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < src_meta.column_cnt_; ++i) {
      const ObSSTableColumnMeta& src_col = src_meta.column_metas_.at(i);
      const ObSSTableColumnMeta& write_col = write_meta.column_metas_.at(i);
      if (src_col.column_id_ != write_col.column_id_ ||
          src_col.column_default_checksum_ != write_col.column_default_checksum_ ||
          src_col.column_checksum_ != write_col.column_checksum_) {
        ret = OB_INVALID_DATA;
        STORAGE_LOG(WARN, "column_metas_ not match", K(ret), K(i), K(src_meta), K(write_meta));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::create_new_partition(const ObAddr& src_server, ObReplicaOpArg& replica_op_arg,
    ObIPartitionGroupGuard& partition_guard, ObStorageFileHandle& file_handle)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  clog::ObIPartitionLogService* pls = NULL;
  const int64_t is_restore = ctx_->is_restore_;
  ObTablesHandle sstables_handle;                                        // empty
  ctx_->pg_meta_.storage_info_.set_pg_file_id(OB_INVALID_DATA_FILE_ID);  // for create a new pg_file in ofs mode
  const ObSavedStorageInfoV2& saved_storage_info = ctx_->pg_meta_.storage_info_;
  const ObPartitionSplitInfo& split_info = ctx_->pg_meta_.split_info_;
  int64_t split_state = ctx_->pg_meta_.saved_split_state_;
  // 221 and 222 observer may set split_state = -1, upgrade to 224 may has problem, now set split_state = 1 directly
  if (-1 == split_state) {
    split_state = 1;
    LOG_WARN("split state was -1, should be rewritten to 1", "pkey", ctx_->pg_meta_.pg_key_);
  }
  const ObBaseStorageInfo& clog_info = saved_storage_info.get_clog_info();
  common::ObReplicaType replica_type = replica_op_arg.dst_.get_replica_type();
  const int64_t memstore_percent = replica_op_arg.dst_.get_memstore_percent();
  ObCreatePGParam param;
  common::ObReplicaProperty replica_property;  // TODO: need using RS appoint replica property
  ObMigrateStatus migrate_status;
O
obdev 已提交
894
  bool need_create_memtable = false;
O
oceanbase-admin 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907 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 960 961 962 963 964 965

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "task has not initialized.", K(ret));
  } else if (OB_FAIL(partition_service_->create_new_partition(replica_op_arg.key_, partition))) {
    STORAGE_LOG(WARN, "Fail to create new partition, ", K(replica_op_arg.key_), K(ret));
  } else if (NULL == partition) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "The partition is NULL, ", K(ret), K(replica_op_arg.key_));
  } else if (OB_FAIL(ObMigrateStatusHelper::trans_replica_op(replica_op_arg.type_, migrate_status))) {
    LOG_WARN("failed to trans migrate status", K(ret), K(replica_op_arg));
  } else {
    partition_guard.set_partition_group(partition_service_->get_pg_mgr(), *partition);
    ObChangePartitionLogEntry entry;
    const int64_t subcmd = ObIRedoModule::gen_subcmd(OB_REDO_LOG_PARTITION, REDO_LOG_ADD_PARTITION_GROUP);
    const bool write_slog = true;
    const int64_t data_version = 0;
    const bool in_slog_trans = true;

    entry.partition_key_ = ctx_->replica_op_arg_.key_;
    entry.replica_type_ = replica_type;
    // pg and partition witch contains pg_key and partition_key are same
    entry.pg_key_ = ctx_->replica_op_arg_.key_;

    ObStorageLogAttribute log_attr;

    param.create_frozen_version_ = ctx_->pg_meta_.create_frozen_version_;
    param.last_restore_log_id_ = ctx_->pg_meta_.last_restore_log_id_;
    param.restore_snapshot_version_ = ctx_->pg_meta_.restore_snapshot_version_;
    if (NULL == (pls = partition->get_log_service())) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "Unexpected error, pls is NULL, ", K(ret));
    } else if (OB_FAIL(replica_property.set_memstore_percent(memstore_percent))) {
      STORAGE_LOG(WARN, "failed to set memstore percent", K(ret), K(replica_op_arg), K(memstore_percent));
    } else if (FALSE_IT(param.create_timestamp_ = ctx_->pg_meta_.create_timestamp_)) {
    } else if (FALSE_IT(param.replica_property_ = replica_property)) {
    } else if (FALSE_IT(param.replica_type_ = replica_type)) {
    } else if (FALSE_IT(param.is_restore_ = is_restore)) {
    } else if (FALSE_IT(param.write_slog_ = write_slog)) {
    } else if (FALSE_IT(param.data_version_ = data_version)) {
    } else if (FALSE_IT(param.split_state_ = split_state)) {
    } else if (FALSE_IT(param.file_handle_ = &file_handle)) {
    } else if (FALSE_IT(param.file_mgr_ = &OB_SERVER_FILE_MGR)) {
    } else if (FALSE_IT(param.migrate_status_ = migrate_status)) {
    } else if (OB_FAIL(param.set_storage_info(saved_storage_info))) {
      LOG_WARN("failed to set storage info", K(ret), K(saved_storage_info));
    } else if (OB_FAIL(param.set_split_info(split_info))) {
      LOG_WARN("failed to set split info", K(ret), K(split_info));
    } else if (OB_FAIL(partition_service_->get_clog_mgr()->add_partition(replica_op_arg.key_,
                   replica_type,
                   replica_property,
                   clog_info,
                   ObVersion(0, 0) /*freeze version*/,
                   src_server,
                   is_restore,
                   pls))) {
      STORAGE_LOG(WARN, "fail to initiate partition log service", K(ret), K(replica_op_arg));
      // migrate partition will not refresh schema, need set region
    } else if (OB_FAIL(partition_service_->set_region(replica_op_arg.key_, pls))) {
      STORAGE_LOG(WARN, "fail to set region", K(ret), K(replica_op_arg));
    } else {
      log_attr.tenant_id_ = entry.pg_key_.get_tenant_id();
      log_attr.data_file_id_ = file_handle.get_storage_file()->get_file_id();
      param.migrate_status_ = migrate_status;
    }

    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(SLOGGER.write_log(subcmd, log_attr, entry))) {
      STORAGE_LOG(WARN, "fail to write add partition (group) log.", K(ret), K(subcmd), K(log_attr));
    } else if (OB_FAIL(partition->create_partition_group(param))) {
      STORAGE_LOG(WARN, "fail to create partition group", K(ret));
O
obdev 已提交
966 967 968
    } else if (FALSE_IT(need_create_memtable = !(partition->get_pg_storage().is_restoring_base_data() ||
                                                 partition->get_pg_storage().is_restoring_standby()))) {
    } else if (need_create_memtable && OB_FAIL(partition->create_memtable(in_slog_trans))) {
O
oceanbase-admin 已提交
969
      STORAGE_LOG(WARN, "fail to create memtable", K(ret));
970 971
    // pause it to make sure the sstable upper trans version is update after migration finished.
    } else if (need_create_memtable && OB_FALSE_IT(partition->get_pg_storage().pause())) {
O
oceanbase-admin 已提交
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 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 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 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 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 1128 1129 1130 1131 1132 1133 1134 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 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 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 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 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 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 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 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 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 1694 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 1723 1724 1725 1726 1727 1728 1729 1730 1731 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 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 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 1819 1820 1821 1822 1823 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 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 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 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 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 2009 2010 2011 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 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 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 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 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 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 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 2406 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 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 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 2527 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 2553 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 2599 2600 2601 2602 2603 2604 2605 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
    } else {
      file_handle.reset();
      // create new partition need set schema_version in pg meta in order to prevent gc
      for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
        const ObMigratePartitionInfo& copy_info = ctx_->part_ctx_array_.at(i).copy_info_;
        const ObPGPartitionStoreMeta& meta = copy_info.meta_;
        if (!meta.pkey_.is_trans_table() && OB_FAIL(create_pg_partition(meta, partition, in_slog_trans))) {
          LOG_WARN("failed to create pg partition", K(ret), K(meta));
        }
      }
    }
  }

  return ret;
}

////////////////////////////////////////////////////////////////////
// ObPartitionMigrator
//
ObPartitionMigrator::ObPartitionMigrator()
    : is_inited_(false),
      is_stop_(false),
      bandwidth_throttle_(NULL),
      partition_service_(NULL),
      svr_rpc_proxy_(NULL),
      pts_rpc_(NULL),
      cp_fty_(NULL),
      location_cache_(NULL),
      lock_(ObLatchIds::MIGRATE_LOCK),
      schema_service_(NULL)
{}

ObPartitionMigrator::~ObPartitionMigrator()
{
  if (is_inited_) {
    destroy();
  }
}

void ObPartitionMigrator::destroy()
{
  stop();
  wait();
}

void ObPartitionMigrator::stop()
{
  common::SpinWLockGuard guard(lock_);
  is_stop_ = true;
}

void ObPartitionMigrator::wait()
{
  STORAGE_LOG(INFO, "wait restore_macro_block_task_pool_ stop");
  restore_macro_block_task_pool_.destroy();

  STORAGE_LOG(INFO, "wait migrate task stop");
  if (is_inited_) {
    bool has_running_task = true;
    while (has_running_task) {
      int64_t migrate_dag_count = ObDagScheduler::get_instance().get_dag_count(ObIDag::DAG_TYPE_MIGRATE) +
                                  ObDagScheduler::get_instance().get_dag_count(ObIDag::DAG_TYPE_BACKUP) +
                                  ObDagScheduler::get_instance().get_dag_count(ObIDag::DAG_TYPE_VALIDATE);
      has_running_task = migrate_dag_count > 0;

      if (has_running_task) {
        usleep(OB_MIGRATE_SCHEDULE_SLEEP_INTERVAL_S);
      }
    }
  }
  is_inited_ = false;

  STORAGE_LOG(INFO, "ObPartitionMigrator stopped");
}

int ObMigratePrepareTask::add_migrate_status(ObMigrateCtx* ctx)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (NULL == ctx) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arg", K(ret));
  } else if (!ctx->is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(*ctx));
  } else if (OB_FAIL(add_partition_migration_status(*ctx))) {
    STORAGE_LOG(WARN, "failed to add partition_migration_status", K(ret), K(*ctx));
  } else {
    STORAGE_LOG(INFO, "succeed to add migrate ctx", KP(ctx), K(*ctx));
  }
  return ret;
}

int ObMigratePrepareTask::add_partition_migration_status(const ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(ctx));
  } else {
    ObPartitionMigrationStatus task;
    task.task_id_ = ctx.task_id_;
    task.migrate_type_ = ctx.replica_op_arg_.get_replica_op_type_str();
    task.pkey_ = ctx.replica_op_arg_.key_;
    task.clog_parent_.reset();  // we don't know it now
    task.src_.reset();          // we don't know it now
    task.dest_ = OBSERVER.get_self();
    task.result_ = ctx.result_;
    task.start_time_ = ctx.create_ts_;
    task.action_ = ctx.action_;
    task.replica_state_ = OB_UNKNOWN_REPLICA;  // we don't know it now
    task.doing_task_count_ = 0;
    task.total_task_count_ = 0;
    task.rebuild_count_ = 0;
    task.continue_fail_count_ = 0;
    task.data_statics_ = ctx.data_statics_;

    // allow comment truncation, no need to set ret
    (void)ctx.fill_comment(task.comment_, sizeof(task.comment_));

    if (OB_SUCCESS != (tmp_ret = ObPartitionMigrationStatusMgr::get_instance().add_status(task))) {
      STORAGE_LOG(WARN, "failed to add partition migration status", K(tmp_ret), K(task));
    }
  }

  return ret;
}

int ObMigrateCtx::fill_comment(char* buf, const int64_t buf_len) const
{
  // static function, no need check is_inited_
  int ret = OB_SUCCESS;

  if (NULL == buf || NULL == group_task_) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), KP(group_task_), K(buf));
  } else {
    int n = snprintf(buf,
        buf_len,
        "single partition migration: group_task_id=%s key=%s, op_type=%s, src=%s, dest=%s,"
        "dest_memstore_percent=%s",
        to_cstring(group_task_->get_task_id()),
        to_cstring(replica_op_arg_.key_),
        replica_op_arg_.get_replica_op_type_str(),
        to_cstring(replica_op_arg_.data_src_.get_server()),
        to_cstring(replica_op_arg_.dst_.get_server()),
        to_cstring(replica_op_arg_.dst_.get_memstore_percent()));
    if (n < 0 || n >= buf_len) {
      ret = OB_BUF_NOT_ENOUGH;
      if (REACH_TIME_INTERVAL(10 * 1000 * 1000)) {  // 10s
        STORAGE_LOG(WARN, "buf not enough, comment is truncated", K(ret), K(n), K(buf));
      }
    }
  }
  return ret;
}

ObPartitionMigrator& ObPartitionMigrator::get_instance()
{
  static ObPartitionMigrator migrator_instance_;
  return migrator_instance_;
}

int ObPartitionMigrator::init(obrpc::ObPartitionServiceRpcProxy& srv_rpc_proxy, ObPartitionServiceRpc& pts_rpc,
    ObIPartitionComponentFactory* cp_fty, ObPartitionService* partition_service,
    common::ObInOutBandwidthThrottle& bandwidth_throttle, share::ObIPartitionLocationCache* location_cache,
    share::schema::ObMultiVersionSchemaService* schema_service)
{
  int ret = OB_SUCCESS;
  common::SpinWLockGuard guard(lock_);
  if (is_inited_) {
    ret = OB_INIT_TWICE;
    STORAGE_LOG(WARN, "The ObPartitionMigrator has inited.", K(ret));
  } else if (!srv_rpc_proxy.is_inited() || NULL == cp_fty || NULL == partition_service || NULL == location_cache ||
             NULL == schema_service) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN,
        "invalid arguments.",
        "proxy valid",
        srv_rpc_proxy.is_inited(),
        KP(cp_fty),
        KP(partition_service),
        KP(location_cache),
        KP(schema_service),
        K(ret));
  } else if (OB_FAIL(restore_macro_block_task_pool_.init("RstMacroTask"))) {
    STORAGE_LOG(WARN, "failed to init restore_macro_block_task_pool_", K(ret));
  } else {
    bandwidth_throttle_ = &bandwidth_throttle;
    partition_service_ = partition_service;
    svr_rpc_proxy_ = &srv_rpc_proxy;
    pts_rpc_ = &pts_rpc;
    cp_fty_ = cp_fty;
    location_cache_ = location_cache;
    schema_service_ = schema_service;
    is_inited_ = true;
  }

  return ret;
}

const char* ObMigrateCtx::trans_action_to_str(const MigrateAction& action)
{
  const char* str = "UNKNOWN";

  switch (action) {
    case INIT:
      str = "INIT";
      break;
    case PREPARE:
      str = "PREPARE";
      break;
    case COPY_MINOR:
      str = "COPY_MINOR";
      break;
    case COPY_MAJOR:
      str = "COPY_MAJOR";
      break;
    case END:
      str = "END";
      break;
    default:
      str = "UNKOWN";
      STORAGE_LOG(WARN, "unknown action", K(action));
  }

  return str;
}

ObPartGroupMigrator::ObPartGroupMigrator()
    : is_inited_(false),
      update_task_list_lock_(ObLatchIds::GROUP_MIGRATE_LOCK),
      task_list_(),
      partition_service_(NULL),
      cp_fty_(NULL),
      is_stop_(false)
{}

ObPartGroupMigrator::~ObPartGroupMigrator()
{
  if (is_inited_) {
    destroy();
  }
}

void ObPartGroupMigrator::destroy()
{
  stop();
  wait();
}

void ObPartGroupMigrator::stop()
{
  common::SpinWLockGuard guard(update_task_list_lock_);
  is_stop_ = true;
}

void ObPartGroupMigrator::wait()
{
  bool need_wait = true;
  while (need_wait) {
    common::SpinRLockGuard guard(update_task_list_lock_);
    if (task_list_.count() > 0) {
      STORAGE_LOG(INFO, "not finish part group task, waiting", "total_count", task_list_.count());
      usleep(1000 * 1000);  // sleep 1s
    } else {
      need_wait = false;
    }
  }
  is_inited_ = false;
}

bool ObPartGroupMigrator::is_stop() const
{
  return is_stop_;
}

ObPartGroupMigrator& ObPartGroupMigrator::get_instance()
{
  static ObPartGroupMigrator group_migrator;
  return group_migrator;
}

int ObPartGroupMigrator::init(storage::ObPartitionService* partition_service, ObIPartitionComponentFactory* cp_fty)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    STORAGE_LOG(ERROR, "cannot init twice", K(ret));
  } else if (NULL == partition_service || NULL == cp_fty) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), KP(partition_service), KP(cp_fty));
  } else {
    is_inited_ = true;
    partition_service_ = partition_service;
    cp_fty_ = cp_fty;
  }
  return ret;
}

int ObPartGroupMigrator::schedule(const ObReplicaOpArg& arg, const share::ObTaskId& task_id)
{
  int ret = OB_SUCCESS;
  // task will be executed directly when it is scheduled and will be release when it execute over,
  // so this task point address will not keep effective
  ObPartGroupTask* group_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!arg.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(task_id), K(arg));
  } else {
    ObSEArray<ObReplicaOpArg, 1> task_list;
    const bool is_batch_mode = false;
    const bool is_normal_migrate = true;

    if (OB_FAIL(task_list.push_back(arg))) {
      STORAGE_LOG(WARN, "failed to add task list", K(ret), K(arg));
    } else if (OB_FAIL(inner_schedule(task_list, is_batch_mode, task_id, is_normal_migrate, group_task))) {
      STORAGE_LOG(WARN, "failed to inner schedule task", K(ret), K(arg), K(task_id));
    }
  }
  return ret;
}

int ObPartGroupMigrator::schedule(const ObIArray<ObReplicaOpArg>& arg_list, const share::ObTaskId& task_id)
{
  int ret = OB_SUCCESS;
  const bool is_batch_mode = true;
  // task will be executed directly when it is scheduled and will be release when it execute over,
  // so this task point address will not keep effective
  ObPartGroupTask* group_task = NULL;
  bool is_normal_migrate = true;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (arg_list.count() <= 0) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(task_id), K(arg_list));
  } else if (OB_FAIL(inner_schedule(arg_list, is_batch_mode, task_id, is_normal_migrate, group_task))) {
    STORAGE_LOG(WARN, "failed to inner schedule task", K(ret), K(arg_list), K(task_id));
  }
  return ret;
}

int ObPartGroupMigrator::mark(const ObReplicaOpArg& arg, const share::ObTaskId& task_id, ObPartGroupTask*& group_task)
{
  // only remove replica task finsih is control outside, so allo outside call group_task to finish
  int ret = OB_SUCCESS;
  group_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!arg.is_valid() || task_id.is_invalid() || REMOVE_REPLICA_OP != arg.type_) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(task_id), K(arg));
  } else {
    SMART_VAR(ObArray<ObReplicaOpArg>, task_list)
    {
      const bool is_batch_mode = false;
      const bool is_normal_migrate = false;

      if (OB_FAIL(task_list.push_back(arg))) {
        STORAGE_LOG(WARN, "failed to add task list", K(ret), K(arg));
      } else if (OB_FAIL(inner_schedule(task_list, is_batch_mode, task_id, is_normal_migrate, group_task))) {
        STORAGE_LOG(WARN, "failed to inner schedule task", K(ret), K(arg), K(task_id));
      }

      DEBUG_SYNC(AFTER_MIGRATION_MARK);
    }
  }
  return ret;
}

int ObPartGroupMigrator::get_not_finish_task_count(
    int64_t& rebuild_count, int64_t& backup_count, int64_t& validate_count, int64_t& is_normal_migrate)
{  // caller must hold lock
  int ret = OB_SUCCESS;
  rebuild_count = 0;
  backup_count = 0;
  validate_count = 0;
  is_normal_migrate = 0;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      if (!task_list_[i]->is_finish() && REMOVE_REPLICA_OP != task_list_[i]->get_type()) {
        if (REBUILD_REPLICA_OP == task_list_[i]->get_type()) {
          ++rebuild_count;
        } else if (BACKUP_REPLICA_OP == task_list_[i]->get_type()) {
          ++backup_count;
        } else if (VALIDATE_BACKUP_OP == task_list_[i]->get_type()) {
          ++validate_count;
        } else {
          ++is_normal_migrate;
        }
        STORAGE_LOG(DEBUG, "dump task list", K(i), K(*task_list_[i]));
      }
    }
  }

  return ret;
}

static inline bool task_need_data_copy(const ObIArray<ObReplicaOpArg>& task_list)
{
  bool bool_ret = false;
  for (int64_t i = 0; i < task_list.count() && !bool_ret; ++i) {
    const ObReplicaOpArg& task = task_list.at(i);
    if (REMOVE_REPLICA_OP != task.type_) {
      bool_ret = true;
    }
  }
  return bool_ret;
}

int ObPartGroupMigrator::has_task(const ObPartitionKey& pkey, bool& has_task)
{
  int ret = OB_SUCCESS;
  ObArray<ObPartitionKey> pkey_list;
  common::SpinRLockGuard guard(update_task_list_lock_);

  has_task = false;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(pkey_list.push_back(pkey))) {
    LOG_WARN("failed to add pkey", K(ret), K(pkey));
  } else if (OB_FAIL(check_dup_task(pkey_list))) {
    if (OB_TASK_EXIST != ret) {
      LOG_WARN("failed to check dup task", K(ret), K(pkey));
    } else {
      ret = OB_SUCCESS;
      has_task = true;
    }
  }
  return ret;
}

int ObPartGroupMigrator::task_exist(const share::ObTaskId& task_id, bool& exist)
{
  int ret = OB_SUCCESS;
  exist = false;

  common::SpinRLockGuard guard(update_task_list_lock_);
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count() && !exist; ++i) {
    if (NULL != task_list_[i] && task_id.equals(task_list_[i]->get_task_id())) {
      exist = true;
    }
  }
  return ret;
}

int ObPartGroupMigrator::check_copy_limit_(const ObIArray<ObReplicaOpArg>& arg_list)
{
  int ret = OB_SUCCESS;
  int64_t data_copy_in_limit = GCONF.server_data_copy_in_concurrency;
  int64_t rebuild_count = 0;
  int64_t backup_count = 0;
  int64_t validate_count = 0;
  int64_t is_normal_migrate = 0;
  ObReplicaOpType type = UNKNOWN_REPLICA_OP;

  if (GCONF.migrate_concurrency == 0) {
    data_copy_in_limit = 0;
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (arg_list.count() <= 0) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(arg_list));
  } else if (FALSE_IT(type = arg_list.at(0).type_)) {
  } else if (OB_FAIL(get_not_finish_task_count(rebuild_count, backup_count, validate_count, is_normal_migrate))) {
    STORAGE_LOG(WARN, "failed to get_not_finish_task_count", K(ret));
  } else if (!task_need_data_copy(arg_list)) {
    // pass
  } else if (REBUILD_REPLICA_OP == type) {
    if (rebuild_count >= data_copy_in_limit) {
      ret = OB_REACH_SERVER_DATA_COPY_IN_CONCURRENCY_LIMIT;
      LOG_WARN("rebuild count exceed the limit", K(ret), K(rebuild_count), K(data_copy_in_limit));
    }
  } else if (BACKUP_REPLICA_OP == type) {
    data_copy_in_limit = OB_GROUP_BACKUP_CONCURRENCY;
    if (backup_count >= data_copy_in_limit) {
      ret = OB_REACH_SERVER_DATA_COPY_IN_CONCURRENCY_LIMIT;
      LOG_WARN("backup count exceed the limit", K(ret), K(backup_count), K(data_copy_in_limit));
    }
  } else if (VALIDATE_BACKUP_OP == type) {
    data_copy_in_limit = OB_GROUP_VALIDATE_CONCURRENCY;
    if (validate_count >= data_copy_in_limit) {
      ret = OB_REACH_SERVER_DATA_COPY_IN_CONCURRENCY_LIMIT;
      LOG_WARN("validate count exceed the limit", K(ret), K(validate_count), K(data_copy_in_limit));
    }
  } else {
    if (is_normal_migrate >= data_copy_in_limit) {
      ret = OB_REACH_SERVER_DATA_COPY_IN_CONCURRENCY_LIMIT;
      LOG_WARN("migrator count exceed the limit", K(ret), K(is_normal_migrate), K(data_copy_in_limit));
    }
  }
  return ret;
}

int ObPartGroupMigrator::inner_schedule(const ObIArray<ObReplicaOpArg>& arg_list, const bool is_batch_mode,
    const share::ObTaskId& in_task_id, const bool is_normal_migrate, ObPartGroupTask*& out_group_task)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObPartGroupTask* group_task = NULL;
  share::ObTaskId task_id = in_task_id;  // copy it
  DEBUG_SYNC(BEFORE_OBSERVER_SCHEDULE_MIGRATE);

  common::SpinWLockGuard guard(update_task_list_lock_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(check_arg_list(arg_list))) {
    STORAGE_LOG(WARN, "arg_list is empty", K(ret), K(arg_list));
  } else if (OB_FAIL(check_copy_limit_(arg_list))) {
    LOG_WARN("failed to check_copy_limit", K(ret));
  } else if (OB_FAIL(get_group_task(arg_list, is_batch_mode, task_id, group_task))) {
    STORAGE_LOG(WARN, "failed to get group task", K(ret), K(arg_list));
  } else if (OB_FAIL(check_dup_task(*group_task))) {
    STORAGE_LOG(WARN, "failed to check new task", K(ret), K(group_task));
  } else if (OB_FAIL(task_list_.push_back(group_task))) {
    STORAGE_LOG(WARN, "failed to add task", K(ret), K(group_task));
  } else if (is_normal_migrate && OB_FAIL(schedule_group_migrate_dag(group_task))) {
    LOG_WARN("failed to schedule_group_migrate_dag", K(ret));
    if (OB_SUCCESS != (tmp_ret = task_list_.remove(task_list_.count() - 1))) {
      LOG_ERROR("failed to rollback failed group task, fatal error", K(ret));
      ob_abort();
    }
  } else {
    STORAGE_LOG(INFO,
        "succeed to schedule partition group migration task",
        "task_count",
        task_list_.count(),
        KP(group_task),
        K(*group_task));
    out_group_task = group_task;
    group_task = NULL;
  }

  if (NULL != group_task && NULL != cp_fty_) {
    cp_fty_->free(group_task);
  }
  return ret;
}

// static func
int ObPartGroupMigrator::check_arg_list(const ObIArray<ObReplicaOpArg>& arg_list)
{
  int ret = OB_SUCCESS;
  ObReplicaOpType type = UNKNOWN_REPLICA_OP;
  const int64_t restore_concurrency = GCONF.restore_concurrency;

  if (arg_list.count() <= 0) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "arg list must not empty", K(ret), K(arg_list));
  } else {
    type = arg_list.at(0).type_;
    if (!is_replica_op_valid(type)) {
      ret = OB_INVALID_ARGUMENT;
      STORAGE_LOG(WARN, "invalid type", K(ret), K(type), K(arg_list));
    } else if (RESTORE_REPLICA_OP == type && restore_concurrency <= 0) {
      ret = OB_OP_NOT_ALLOW;
      STORAGE_LOG(WARN, "restore is disabled, cannot restore tenant", K(ret), K(restore_concurrency));
    }
    for (int64_t i = 1; OB_SUCC(ret) && i < arg_list.count(); ++i) {
      if (type != arg_list.at(i).type_) {
        ret = OB_INVALID_ARGUMENT;
        STORAGE_LOG(ERROR, "op type must be same", K(ret), K(type), K(i), K(arg_list));
      }
    }
  }
  return ret;
}

int ObPartGroupMigrator::check_dup_task(const ObPartGroupTask& task)
{
  // caller must hold update_task_list_lock_
  int ret = OB_SUCCESS;
  ObArray<ObPartitionKey> pkey_list;
  ObReplicaOpType type = task.get_type();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(task.check_self_dup_task())) {
    STORAGE_LOG(WARN, "failed to check_self_dup_task", K(ret));
  } else if (VALIDATE_BACKUP_OP == type) {
    // skip
  } else if (OB_FAIL(task.get_pkey_list(pkey_list))) {
    STORAGE_LOG(WARN, "failed to get pkey list", K(ret));
  } else if (OB_FAIL(check_dup_task(pkey_list))) {
    LOG_WARN("failed to check dup task", K(ret));
  }
  return ret;
}

int ObPartGroupMigrator::check_dup_task(const ObIArray<ObPartitionKey>& pkey_list)
{
  // caller must hold update_task_list_lock_
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
    if (OB_FAIL(task_list_[i]->check_dup_task(pkey_list))) {
      STORAGE_LOG(WARN, "failed to check_dup_task in task_list", K(ret), K(i));
    }
  }

  return ret;
}

int ObPartGroupMigrator::schedule_group_migrate_dag(ObPartGroupTask*& group_task)
{
  int ret = OB_SUCCESS;
  ObGroupMigrateDag* dag = NULL;
  ObGroupMigrateExecuteTask* task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(group_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_ERROR("group_task must not null", K(ret), KP(group_task));
  } else if (OB_FAIL(ObDagScheduler::get_instance().alloc_dag(dag))) {
    LOG_WARN("failed to alloc group migrate dag", K(ret));
  } else if (OB_FAIL(dag->init(group_task, partition_service_))) {
    LOG_WARN("failed to init dag", K(ret));
  } else if (OB_FAIL(dag->alloc_task(task))) {
    LOG_WARN("failed to alloc task, ", K(ret));
  } else if (OB_FAIL(task->init(group_task))) {
    LOG_WARN("failed to init task", K(ret));
  } else if (OB_FAIL(dag->add_task(*task))) {
    LOG_WARN("Failed to add task", K(ret));
  } else if (OB_FAIL(ObDagScheduler::get_instance().add_dag(dag))) {
    if (OB_SIZE_OVERFLOW != ret && OB_EAGAIN != ret) {
      LOG_WARN("Fail to add group migrate dag", K(ret));
    }
  }

  if (OB_FAIL(ret)) {
    if (NULL != dag) {
      dag->clear();
      ObDagScheduler::get_instance().free_dag(*dag);
    }
  }

  return ret;
}

int ObPartGroupMigrator::remove_finish_task(ObPartGroupTask* group_task)
{
  int ret = OB_SUCCESS;
  bool found = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(group_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_ERROR("group_task must not null", K(ret), KP(group_task));
  } else {
    {
      common::SpinWLockGuard guard(update_task_list_lock_);
      for (int64_t i = task_list_.count() - 1; OB_SUCC(ret) && !found && i >= 0; --i) {
        ObPartGroupTask* task = task_list_[i];
        ;
        if (task == group_task) {
          found = true;
          if (OB_FAIL(task_list_.remove(i))) {
            STORAGE_LOG(ERROR, "failed to remove finished part group migration task", K(ret), K(i), K(task_list_));
          }
        }
      }
    }

    if (OB_FAIL(ret)) {
      // do nothing
    } else if (!found) {
      ret = OB_ERR_SYS;
      LOG_ERROR("cannot find need remove finish task", K(ret), KP(group_task), K(*group_task));
    } else {
      STORAGE_LOG(
          INFO, "remove finished part group migration task", K(task_list_.count()), KP(group_task), K(*group_task));
      cp_fty_->free(group_task);
    }
  }
  return ret;
}

void ObPartGroupMigrator::wakeup()
{
  common::SpinRLockGuard guard(update_task_list_lock_);
  for (int64_t i = 0; i < task_list_.count(); ++i) {
    ObPartGroupTask* task = task_list_[i];
    if (NULL != task) {
      task->wakeup();
    }
  }
}

int ObPartGroupMigrator::get_group_task(const ObIArray<ObReplicaOpArg>& arg_list, const bool is_batch_mode,
    const share::ObTaskId& in_task_id, ObPartGroupTask*& group_task)
{
  int ret = OB_SUCCESS;
  group_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (arg_list.empty()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "replica op arg list should not be empty", K(ret), K(in_task_id), K(arg_list));
  } else {
    const ObReplicaOpType type = arg_list.at(0).type_;
    if (BACKUP_REPLICA_OP == type) {
      ObPartGroupBackupTask* backup_group_task = NULL;
      if (NULL == (backup_group_task = cp_fty_->get_part_group_backup_task())) {
        ret = OB_ALLOCATE_MEMORY_FAILED;
        STORAGE_LOG(WARN, "failed to alloc group task", K(ret));
      } else if (FALSE_IT(group_task = backup_group_task)) {
      } else if (OB_FAIL(backup_group_task->init(arg_list, is_batch_mode, partition_service_, in_task_id))) {
        STORAGE_LOG(WARN, "failed to init group task", K(ret));
      }
    } else {
      ObPartGroupMigrationTask* migration_group_task = NULL;
      if (NULL == (migration_group_task = cp_fty_->get_part_group_migration_task())) {
        ret = OB_ALLOCATE_MEMORY_FAILED;
        STORAGE_LOG(WARN, "failed to alloc group task", K(ret));
      } else if (FALSE_IT(group_task = migration_group_task)) {
      } else if (OB_FAIL(migration_group_task->init(arg_list, is_batch_mode, partition_service_, in_task_id))) {
        STORAGE_LOG(WARN, "failed to init group task", K(ret));
      }
    }
  }
  return ret;
}

ObPartGroupTask::ObPartGroupTask()
    : is_inited_(false),
      is_batch_mode_(true),
      lock_(ObLatchIds::GROUP_MIGRATE_TASK_LOCK),
      task_list_(),
      partition_service_(NULL),
      first_error_code_(OB_SUCCESS),
      type_(UNKNOWN_REPLICA_OP),
      task_id_(),
      is_finished_(false),
      retry_job_start_ts_(0),
      tenant_id_(0),
      cond_(),
      need_idle_(true),
      report_list_(),
      change_member_option_(NORMAL_CHANGE_MEMBER_LIST)
{}

ObPartGroupTask::~ObPartGroupTask()
{}

bool ObPartGroupTask::is_finish() const
{
  common::SpinRLockGuard guard(lock_);
  return is_finished_;
}

int ObPartGroupTask::get_pkey_list(ObIArray<ObPartitionKey>& pkey_list) const
{
  int ret = OB_SUCCESS;

  common::SpinRLockGuard guard(lock_);
  pkey_list.reset();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      if (OB_FAIL(pkey_list.push_back(task_list_.at(i).arg_.key_))) {
        STORAGE_LOG(WARN, "failed to add pkey", K(ret));
      }
    }
  }
  return ret;
}

int ObPartGroupTask::check_dup_task(const ObIArray<ObPartitionKey>& pkey_list) const
{
  // Check duplicate task just use pkey, so it do not has concurrency. No need lock
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (ObReplicaOpType::VALIDATE_BACKUP_OP == get_type()) {
    // skip
  } else {
    for (int64_t task_idx = 0; OB_SUCC(ret) && task_idx < task_list_.count(); ++task_idx) {
      for (int64_t pkey_idx = 0; OB_SUCC(ret) && pkey_idx < pkey_list.count(); ++pkey_idx) {
        if (task_list_[task_idx].arg_.key_ == pkey_list.at(pkey_idx)) {
          ret = OB_TASK_EXIST;
          ObTaskController::get().allow_next_syslog();
          STORAGE_LOG(WARN,
              "migration task is dup",
              K(ret),
              K_(task_id),
              K_(type),
              "pkey",
              pkey_list.at(pkey_idx),
              K(task_list_[task_idx]));
        }
      }
    }
  }

  return ret;
}

int ObPartGroupTask::check_self_dup_task() const
{
  int ret = OB_SUCCESS;
  // Check duplicate task just use pkey, so it do not has concurrency. No need lock

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      for (int64_t j = i + 1; OB_SUCC(ret) && j < task_list_.count(); ++j) {
        if (task_list_[i].arg_.type_ == VALIDATE_BACKUP_OP && task_list_[j].arg_.type_ == VALIDATE_BACKUP_OP) {
          if (task_list_[i].arg_.validate_arg_.pg_key_ == task_list_[j].arg_.validate_arg_.pg_key_ &&
              task_list_[i].arg_.validate_arg_.backup_set_id_ == task_list_[j].arg_.validate_arg_.backup_set_id_) {
            ret = OB_INVALID_ARGUMENT;
            STORAGE_LOG(WARN, "task is dup", K(ret), K(i), K(j), K(task_list_[i]), K(task_list_[j]));
          }
        } else if (task_list_[i].arg_.key_ == task_list_[j].arg_.key_) {
          ret = OB_INVALID_ARGUMENT;
          STORAGE_LOG(WARN, "task is dup", K(ret), K(i), K(j), K(task_list_[i]), K(task_list_[j]));
        }
      }
    }
  }

  return ret;
}

int ObPartGroupTask::set_part_task_start(const ObPartitionKey& pkey, const int64_t backup_set_id)
{
  int ret = OB_SUCCESS;
  ObPartMigrationTask* task = NULL;

  {
    common::SpinWLockGuard guard(lock_);

    if (!is_inited_) {
      ret = OB_NOT_INIT;
      STORAGE_LOG(WARN, "not inited", K(ret));
    } else {
      for (int64_t i = 0; NULL == task && i < task_list_.count(); ++i) {
        if (VALIDATE_BACKUP_OP == get_type()) {
          if (task_list_[i].arg_.validate_arg_.pg_key_ == pkey &&
              task_list_[i].arg_.validate_arg_.backup_set_id_ == backup_set_id) {
            task = &task_list_[i];
          }
        } else {
          if (task_list_[i].arg_.key_ == pkey) {
            task = &task_list_[i];
          }
        }
      }
      if (NULL == task) {
        ret = OB_ENTRY_NOT_EXIST;
        STORAGE_LOG(ERROR, "cannot found pkey in task", K(ret), K(pkey), KP(this), K(*this));
      } else if (ObPartMigrationTask::INIT == task->status_) {
        task->status_ = ObPartMigrationTask::DOING;
        STORAGE_LOG(INFO, "set_part_task_start", K(pkey), K(ret), K(*this));
        dump_task_status();
      }
    }
  }
  return ret;
}

int ObPartGroupTask::set_part_task_finish(const ObPartitionKey& pkey, const int32_t result,
    const share::ObTaskId& part_task_id, const bool during_migrating, const int64_t backup_set_id)
{
  int ret = OB_SUCCESS;
  ObPartMigrationTask* task = NULL;

  {
    common::SpinWLockGuard guard(lock_);

    if (!is_inited_) {
      ret = OB_NOT_INIT;
      STORAGE_LOG(WARN, "not inited", K(ret));
    } else {
      for (int64_t i = 0; NULL == task && i < task_list_.count(); ++i) {
        if (VALIDATE_BACKUP_OP == get_type()) {
          if (task_list_[i].arg_.validate_arg_.pg_key_ == pkey &&
              task_list_[i].arg_.validate_arg_.backup_set_id_ == backup_set_id) {
            task = &task_list_[i];
          }
        } else {
          if (task_list_[i].arg_.key_ == pkey) {
            task = &task_list_[i];
          }
        }
      }
      if (NULL == task) {
        ret = OB_ENTRY_NOT_EXIST;
        STORAGE_LOG(ERROR, "cannot found pkey in task", K(ret), K(pkey), K(result), KP(this), K(*this));
      } else {
        task->status_ = ObPartMigrationTask::FINISH;
        task->result_ = result;
        task->during_migrating_ = during_migrating;
      }
    }

    if (OB_SUCCESS == first_error_code_) {
      if (OB_SUCCESS != result) {
        if (BACKUP_REPLICA_OP == get_type() && OB_PG_IS_REMOVED == result) {
          // backup while partition may migrate out, skip set first error code
          // do nothing
        } else {
          first_error_code_ = result;
        }
        STORAGE_LOG(WARN, "record first_error_code_ with partition task", K(result), K(pkey), K(ret));
      } else if (OB_SUCCESS != ret) {
        first_error_code_ = ret;
        STORAGE_LOG(WARN, "record first_error_code_", K(result), K(pkey), K(ret));
      }
    }
    STORAGE_LOG(INFO,
        "set_part_task_finish",
        K(pkey),
        K(result),
        K(during_migrating),
        K(ret),
        K(part_task_id),
        K(*this),
        K(backup_set_id));
    dump_task_status();
  }
  ObPartGroupMigrator::get_instance().wakeup();

  return ret;
}

int ObPartGroupTask::build_migrate_ctx(const ObReplicaOpArg& arg, ObMigrateCtx& migrate_ctx)
{
  int ret = OB_SUCCESS;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else {
    migrate_ctx.replica_op_arg_ = arg;
    migrate_ctx.action_ = ObMigrateCtx::INIT;
    migrate_ctx.result_ = OB_SUCCESS;
    migrate_ctx.doing_task_cnt_ = 1;
    migrate_ctx.total_task_cnt_ = 1;
    migrate_ctx.need_rebuild_ = false;
    if (0 == migrate_ctx.create_ts_) {
      migrate_ctx.create_ts_ = ObTimeUtility::current_time();
    }
    migrate_ctx.task_id_.reset();  // filled in add_migrate_ctx_without_lock
    migrate_ctx.continue_fail_count_ = 0;
    migrate_ctx.rebuild_count_ = migrate_ctx.rebuild_count_ < 0 ? 0 : migrate_ctx.rebuild_count_;
    migrate_ctx.group_task_ = this;
    migrate_ctx.group_task_id_ = get_task_id();
    migrate_ctx.part_ctx_array_.reset();
    migrate_ctx.curr_major_block_array_index_ = (migrate_ctx.curr_major_block_array_index_ + 1) % 2;
    migrate_ctx.major_block_id_array_ptr_ =
        &migrate_ctx.major_block_id_array_[migrate_ctx.curr_major_block_array_index_];
    migrate_ctx.is_copy_cover_minor_ = false;
  }
  return ret;
}

void ObPartGroupTask::dump_task_status()
{
  // caller must hold lock
  int tmp_ret = OB_SUCCESS;
  int64_t count[ObPartMigrationTask::MAX];
  memset(count, 0, sizeof(count));

  if (!is_inited_) {
    tmp_ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(tmp_ret));
  } else {
    for (int64_t i = 0; OB_SUCCESS == tmp_ret && i < task_list_.count(); ++i) {
      ObPartMigrationTask& task = task_list_[i];
      if (task.status_ < 0 || task.status_ >= ObPartMigrationTask::MAX) {
        tmp_ret = OB_ERR_SYS;
        STORAGE_LOG(ERROR, "invalid task stauts", K(tmp_ret), K(i), K(task));
      } else {
        count[task.status_]++;
      }
    }

    STORAGE_LOG(INFO,
        "dump group migration task status",
        "total_count",
        task_list_.count(),
        "INIT",
        count[ObPartMigrationTask::INIT],
        "DOING",
        count[ObPartMigrationTask::DOING],
        "FINISH",
        count[ObPartMigrationTask::FINISH]);
  }
}

int ObPartGroupTask::check_is_task_cancel()
{
  int ret = OB_SUCCESS;
  bool is_cancel = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (OB_SUCCESS == first_error_code_) {
    common::SpinWLockGuard guard(lock_);
    if (OB_FAIL(SYS_TASK_STATUS_MGR.is_task_cancel(task_id_, is_cancel))) {
      STORAGE_LOG(ERROR, "failed to check is group task cancel", K(ret), K(*this));
    } else if (is_cancel) {
      first_error_code_ = OB_CANCELED;
      STORAGE_LOG(WARN, "group part migration is cancelled", K(ret), K(*this));
    } else if (ObPartitionMigrator::get_instance().is_stop()) {
      first_error_code_ = OB_CANCELED;
      STORAGE_LOG(WARN, "mirgator is stop, set group task is cancelled", K(ret), K(*this));
    } else if (ObReplicaOpType::VALIDATE_BACKUP_OP == get_type()) {
      // do nothing
    } else if (!GCTX.omt_->has_tenant(tenant_id_)) {
      first_error_code_ = OB_TENANT_NOT_EXIST;
      STORAGE_LOG(WARN, "tenant not exists, set migration failed", K(ret), K(*this));
    }
  }

  if (OB_SUCC(ret) && OB_SUCCESS == first_error_code_) {
    // TODO(jiage): remove it after fix GCTX.omt_->has_tenant
    bool is_tenant_exist = false;
    if (ObReplicaOpType::VALIDATE_BACKUP_OP == get_type()) {
      // do nothing
    } else if (OB_FAIL(check_is_tenant_exist(is_tenant_exist))) {
      LOG_WARN("failed to check is tenant exist", K(ret));
    } else if (!is_tenant_exist) {
      common::SpinWLockGuard guard(lock_);
      first_error_code_ = OB_TENANT_NOT_EXIST;
      STORAGE_LOG(WARN, "tenant schema not exists, set migration failed", K(ret), K(*this));
    }
  }
  return ret;
}

int ObPartGroupTask::check_partition_checksum(const common::ObPartitionKey& pkey)
{
  int ret = OB_SUCCESS;
  ModulePageAllocator allocator(ObNewModIds::OB_PARTITION_MIGRATE);
  share::ObPartitionInfo partition_info;
  partition_info.set_allocator(&allocator);
  share::ObUnitedPtOperator united_operator;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "The migrator has not inited or stopped.", K(ret));
  } else if (OB_ISNULL(GCTX.pt_operator_) || OB_ISNULL(GCTX.remote_pt_operator_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "pt_operator must not NULL.", K(ret));
  } else if (OB_FAIL(united_operator.init(GCTX.pt_operator_, GCTX.remote_pt_operator_))) {
    LOG_WARN("fail to init united_operator", KR(ret));
  } else if (OB_SUCCESS !=
             (ret = united_operator.united_get(pkey.get_table_id(), pkey.get_partition_id(), partition_info))) {
    STORAGE_LOG(WARN, "fail to get partition info.", K(ret), K(pkey));
  } else if (partition_info.replica_count() > 1) {
    const common::ObIArray<share::ObPartitionReplica>& replicas = partition_info.get_replicas_v2();
    int64_t lastIdx = -1;
    for (int64_t i = 0; OB_SUCC(ret) && i < replicas.count(); ++i) {
      if (replicas.at(i).replica_type_ == REPLICA_TYPE_LOGONLY || replicas.at(i).is_restore_ != 0 ||
          (lastIdx >= 0 && replicas.at(lastIdx).is_restore_ != 0)) {
        continue;
      } else if (lastIdx == -1) {
        lastIdx = i;
      } else if (replicas.at(i).data_version_ > replicas.at(lastIdx).data_version_) {
        lastIdx = i;
      } else if (replicas.at(i).data_version_ == replicas.at(lastIdx).data_version_) {
        if (replicas.at(i).data_checksum_ != replicas.at(lastIdx).data_checksum_) {
          ret = OB_CHECKSUM_ERROR;
          STORAGE_LOG(ERROR,
              "replicas check sum is not match",
              K(pkey),
              "replica1",
              replicas.at(i),
              "replica2",
              replicas.at(lastIdx));
        }
      }
    }
  }

  if (OB_SUCCESS != ret && OB_CHECKSUM_ERROR != ret) {
    STORAGE_LOG(WARN, "failed to check checksum for partition, overwrite ret", K(pkey), K(ret));
    ret = OB_SUCCESS;
  }
  return ret;
}

int ObPartGroupTask::check_is_tenant_exist(bool& is_exist)
{
  int ret = OB_SUCCESS;
  share::schema::ObSchemaGetterGuard schema_guard;
  share::schema::ObMultiVersionSchemaService& schema_service =
      share::schema::ObMultiVersionSchemaService::get_instance();

  is_exist = true;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (OB_FAIL(schema_service.get_tenant_full_schema_guard(OB_SYS_TENANT_ID, schema_guard))) {
    LOG_WARN("failed to get schema guard", K(ret));
  } else if (OB_FAIL(schema_guard.check_tenant_exist(tenant_id_, is_exist))) {
    LOG_WARN("failed to check tenant exist", K(ret), K_(tenant_id));
  }
  return ret;
}

int ObPartGroupTask::check_is_partition_exist(const common::ObPartitionKey& pkey, bool& is_exist)
{
  int ret = OB_SUCCESS;
  share::schema::ObSchemaGetterGuard schema_guard;
  share::schema::ObMultiVersionSchemaService& schema_service =
      share::schema::ObMultiVersionSchemaService::get_instance();
  const uint64_t fetch_tenant_id = is_inner_table(pkey.get_table_id()) ? OB_SYS_TENANT_ID : pkey.get_tenant_id();
  bool check_dropped_partition = true;
  is_exist = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (OB_FAIL(schema_service.get_tenant_full_schema_guard(fetch_tenant_id, schema_guard))) {
    LOG_WARN("failed to get schema guard", K(ret));
  } else if (OB_FAIL(schema_guard.check_partition_exist(
                 pkey.get_table_id(), pkey.get_partition_id(), check_dropped_partition, is_exist))) {
    LOG_WARN("failed to check partition exist", K(ret), K(pkey));
  }

  return ret;
}

int ObPartGroupTask::check_can_as_data_source(
    const ObReplicaOpType& op, const ObReplicaType& src_type, const ObReplicaType& dst_type, bool& as_data_source)
{
  int ret = OB_SUCCESS;
  as_data_source = false;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else {
    if (COPY_GLOBAL_INDEX_OP == op || COPY_LOCAL_INDEX_OP == op) {
      as_data_source = ObReplicaTypeCheck::is_replica_with_ssstore(src_type) &&
                       ObReplicaTypeCheck::is_replica_with_ssstore(dst_type);
    } else {
      as_data_source = ObReplicaTypeCheck::can_as_data_source(dst_type, src_type);
    }
  }
  return ret;
}

int ObPartGroupTask::build_failed_report_list(
    const int32_t first_fail_code, ObIArray<ObReportPartMigrationTask>& report_list)
{
  // static func
  int ret = OB_SUCCESS;

  if (OB_SUCCESS == first_fail_code) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(first_fail_code));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      report_list.at(i).result_ = first_fail_code;
    }
  }
  return ret;
}

int ObPartGroupTask::set_report_list_result(
    ObIArray<ObReportPartMigrationTask>& report_list, const ObPartitionKey& pkey, const int32_t result)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_SUCCESS == result) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "only failed result need set", K(ret), K(pkey), K(result));
  } else {
    ret = OB_ENTRY_NOT_EXIST;
    for (int64_t i = 0; OB_ENTRY_NOT_EXIST == ret && i < report_list.count(); ++i) {
      if (report_list.at(i).arg_.key_ == pkey) {
        report_list.at(i).result_ = result;
        STORAGE_LOG(INFO, "set report list result", K(i), K(pkey), K(result));
        ret = OB_SUCCESS;
      }
    }
  }

  return ret;
}

int ObPartGroupTask::fill_report_list(bool& is_batch_mode, ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  common::SpinRLockGuard guard(lock_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!is_finished_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("part group migration task not finished, cannot fill report list", K(ret), K(*this));
  } else if (OB_FAIL(report_list.assign(report_list_))) {
    LOG_WARN("failed to assign report list", K(ret));
  } else {
    is_batch_mode = is_batch_mode_;
  }
  return ret;
}

bool ObPartGroupTask::has_error() const
{
  return OB_SUCCESS != first_error_code_;
}

void ObPartGroupTask::wakeup()
{
  ObThreadCondGuard guard(cond_);
  need_idle_ = false;
  cond_.broadcast();
}

ObPartGroupMigrationTask::ObPartGroupMigrationTask()
    : ObPartGroupTask(),
      schedule_ts_(0),
      start_change_member_ts_(0),
      meta_indexs_(),
      meta_index_store_(),
      restore_version_(INT64_MAX)
{}

ObPartGroupMigrationTask::~ObPartGroupMigrationTask()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  if (is_inited_) {
    int64_t timestamp = ObTimeUtility::current_time();
    common::SpinWLockGuard guard(lock_);

    bool is_all_finish = false;
    while (!is_all_finish) {
      if (ObPartGroupMigrator::get_instance().is_stop()) {
        STORAGE_LOG(WARN, "mirgator is stop, set group task is cancelled", K(ret), K(*this));
        break;
      } else {
        // After the dfault loop is over, it should all be over
        is_all_finish = true;
        for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
          if (task_list_[i].need_reset_migrate_status_) {
            DEBUG_SYNC(BEFORE_CLEAR_MIGRATE_STATUS);
            bool need_retry = false;
            ObIPartitionGroup* partition = NULL;
            ObPGStorage* pg_storage = NULL;
            ObMigrateStatus cur_migrate_status = OB_MIGRATE_STATUS_NONE;
            ObMigrateStatus new_migrate_status = OB_MIGRATE_STATUS_NONE;

            if (OB_ISNULL(partition = task_list_[i].ctx_.get_partition())) {
              tmp_ret = OB_ERR_SYS;
              LOG_ERROR("partition/partition storage must not null", K(tmp_ret));
            } else if (OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
              tmp_ret = OB_ERR_SYS;
              LOG_ERROR("pg_storage must not null", K(tmp_ret), KP(pg_storage));
            } else if (OB_SUCCESS != (tmp_ret = pg_storage->get_pg_migrate_status(cur_migrate_status))) {
              LOG_WARN("failed to get migrate status", K(tmp_ret), "pkey", task_list_[i].arg_.key_);
            } else if (OB_SUCCESS == task_list_[i].result_) {
              new_migrate_status = OB_MIGRATE_STATUS_NONE;
              LOG_INFO(
                  "migrate success, set migrate status none", "pkey", task_list_[i].arg_.key_, K(cur_migrate_status));
            } else if (!task_list_[i].during_migrating_) {
              new_migrate_status = OB_MIGRATE_STATUS_NONE;
              LOG_INFO("migrate fail not during migrting, set migrate status none",
                  "pkey",
                  task_list_[i].arg_.key_,
                  K(cur_migrate_status));
            } else if (FAST_MIGRATE_REPLICA_OP == task_list_[i].arg_.type_ &&
                       task_list_[i].ctx_.is_takeover_finished_) {
              new_migrate_status = OB_MIGRATE_STATUS_NONE;
              LOG_INFO("fast migrate: set status normal when takeover finished",
                  K(ret),
                  K(cur_migrate_status),
                  K(task_list_[i].arg_.key_));
            } else {
              if (OB_SUCCESS !=
                  (tmp_ret = ObMigrateStatusHelper::trans_fail_status(cur_migrate_status, new_migrate_status))) {
                LOG_WARN("failed to trans_migrate_fail_status",
                    K(tmp_ret),
                    "pkey",
                    task_list_[i].arg_.key_,
                    K(cur_migrate_status));
              }
            }

            if (OB_SUCCESS == tmp_ret) {
              if (OB_SUCCESS != (tmp_ret = pg_storage->set_pg_migrate_status(new_migrate_status, timestamp))) {
                if (OB_PARTITION_IS_REMOVED == tmp_ret) {
                  LOG_WARN("partition is removed, no need to set migrate status",
                      "pkey",
                      task_list_[i].arg_.key_,
                      K(tmp_ret));
                } else {
                  LOG_ERROR("failed to set migrate status, will retry next loop",
                      "pkey",
                      task_list_[i].arg_.key_,
                      K(tmp_ret));
                  need_retry = true;
                }
              } else {
                LOG_INFO(
                    "succ to reset migrate status", "pkey", task_list_[i].arg_.key_, K(new_migrate_status), K(tmp_ret));
              }
            }

            if (!need_retry) {
              task_list_[i].need_reset_migrate_status_ = false;
            } else {
              // If there are tasks that need to be retried, not all tasks are considered to has been completed
              is_all_finish = false;
            }
          }  // end of if (task_list_[i].need_reset_migrate_status_)
        }    // end of for loop
      }
    }  // end of while loop
    is_inited_ = false;
  }
}

int ObPartGroupMigrationTask::init(const ObIArray<ObReplicaOpArg>& task_list, const bool is_batch_mode,
    storage::ObPartitionService* partition_service, const share::ObTaskId& task_id)
{
  int ret = OB_SUCCESS;
  SMART_VAR(ObPartMigrationTask, tmp_task)
  {
    ObChangeMemberOption change_member_option = NORMAL_CHANGE_MEMBER_LIST;
    common::SpinWLockGuard guard(lock_);

    if (is_inited_) {
      ret = OB_INIT_TWICE;
      STORAGE_LOG(WARN, "cannot init twice", K(ret));
    } else if (NULL == partition_service || task_list.empty() || task_id.is_invalid()) {
      ret = OB_INVALID_ARGUMENT;
      STORAGE_LOG(WARN, "invalid args", K(ret), K(is_batch_mode), KP(partition_service), K(task_id), K(task_list));
    } else if (OB_FAIL(cond_.init(ObWaitEventIds::GROUP_MIGRATE_TASK_IDLE_WAIT))) {
      STORAGE_LOG(WARN, "failed to init cond", K(ret));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < task_list.count(); ++i) {
        tmp_task.arg_ = task_list.at(i);
        tmp_task.arg_.cluster_id_ =
            (tmp_task.arg_.cluster_id_ == OB_INVALID_CLUSTER_ID) ? GCONF.cluster_id : tmp_task.arg_.cluster_id_;
        tmp_task.status_ = ObPartMigrationTask::INIT;
        tmp_task.result_ = OB_SUCCESS;

        if (OB_FAIL(task_list_.push_back(tmp_task))) {
          STORAGE_LOG(WARN, "failed to add task list", K(ret));
        }

        if (OB_SUCC(ret)) {
          if (0 == i) {
            type_ = task_list.at(i).type_;
            tenant_id_ = task_list.at(i).key_.get_tenant_id();
            change_member_option = task_list.at(i).change_member_option_;
            restore_version_ = task_list.at(i).restore_version_;
            if (!is_replica_op_valid(type_)) {
              ret = OB_ERR_SYS;
              STORAGE_LOG(ERROR, "invalid type", K(ret), K(i), K(type_), K(task_list));
            } else if (SKIP_CHANGE_MEMBER_LIST == change_member_option && ADD_REPLICA_OP != type_ &&
                       REBUILD_REPLICA_OP != type_ && MIGRATE_REPLICA_OP != type_ && FAST_MIGRATE_REPLICA_OP != type_ &&
                       CHANGE_REPLICA_OP != type_ && LINK_SHARE_MAJOR_OP != type_ && RESTORE_STANDBY_OP != type_) {
              ret = OB_ERR_SYS;
              STORAGE_LOG(ERROR,
                  "only add or migrate or change replica can skip change member list",
                  K(ret),
                  K(type_),
                  K(task_list));
            }
          } else if (type_ != task_list.at(i).type_ || tenant_id_ != task_list.at(i).key_.get_tenant_id() ||
                     change_member_option != task_list.at(i).change_member_option_) {
            ret = OB_ERR_SYS;
            STORAGE_LOG(ERROR,
                "migration type or tenant_id or skip_change_member_list not same in task list",
                K(ret),
                K(i),
                K(task_list));
          }
        }
      }

      if (OB_SUCC(ret)) {
        is_inited_ = true;
        is_batch_mode_ = is_batch_mode;
        schedule_ts_ = ObTimeUtility::current_time();
        start_change_member_ts_ = 0;
        partition_service_ = partition_service;
        first_error_code_ = OB_SUCCESS;
        task_id_ = task_id;
        is_finished_ = false;
        need_idle_ = true;
        change_member_option_ = change_member_option;
        STORAGE_LOG(INFO, "succeed to init group migration task", K(*this));
      }
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::do_task()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  const int64_t start_ts = ObTimeUtility::current_time();
  ObTaskController::get().switch_task(share::ObTaskType::DATA_MAINTAIN);
  ObCurTraceId::set(task_id_);

  ObTaskController::get().allow_next_syslog();
  LOG_INFO("start group migration task", K(*this));
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    if (OB_FAIL(check_before_do_task())) {
      LOG_WARN("Failed to check_before_do_task", K(ret));
    } else if (OB_FAIL(remove_member_list_if_need())) {
      LOG_WARN("failed to remove_member_list_if_need", K(ret));
    } else if (RESTORE_REPLICA_OP == type_) {
      const bool need_check_compeleted = true;
      if (OB_UNLIKELY(0 == task_list_.count())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("restore task_list_ is empty", K(ret), K(type_), K(task_list_.count()));
      } else if (task_list_[0].arg_.is_physical_restore_leader()) {
        const share::ObPhysicalRestoreArg& restore_arg = task_list_[0].arg_.phy_restore_arg_;
        ObBackupBaseDataPathInfo path_info;
        bool need_check_compeleted = true;
        if (!restore_arg.is_valid()) {
          ret = OB_INVALID_ARGUMENT;
          LOG_WARN("restore arg is invlaid, pelase check", K(ret), K(restore_arg));
        } else if (OB_FAIL(restore_arg.get_backup_base_data_info(path_info))) {
          LOG_WARN("failed to get backup base data info", K(ret), K(restore_arg));
        } else if (FALSE_IT(
                       need_check_compeleted = (restore_arg.restore_info_.cluster_version_ > CLUSTER_VERSION_2271))) {
        } else if (OB_FAIL(
                       meta_indexs_.init(path_info, restore_arg.restore_info_.compatible_, need_check_compeleted))) {
          LOG_WARN("init restore meta index map fail", K(ret), K(restore_arg));
        }
      }
    } else if (VALIDATE_BACKUP_OP == type_) {
      const share::ObPhysicalValidateArg& validate_arg = task_list_[0].arg_.validate_arg_;
      ObBackupBaseDataPathInfo path_info;
      if (!validate_arg.is_valid()) {
        ret = OB_INVALID_ARGUMENT;
        LOG_WARN("validate arg is invalid, please check", K(ret), K(validate_arg));
      } else if (OB_FAIL(validate_arg.get_backup_base_data_info(path_info))) {
        LOG_WARN("failed to get backup base data info", K(ret), K(validate_arg));
      } else if (OB_FAIL(meta_index_store_.init(path_info))) {
        LOG_WARN("init validate meta_index_store failed", K(ret), K(path_info));
      }
    } else {
      // do nothing
    }

    if (OB_FAIL(ret)) {
      common::SpinWLockGuard guard(lock_);
      if (OB_SUCCESS == first_error_code_) {
        first_error_code_ = ret;
        STORAGE_LOG(WARN, "set first_error_code_", K(ret));
      }
    }

    while (!is_finished_) {
      if (OB_SUCCESS != (tmp_ret = check_is_task_cancel())) {
        STORAGE_LOG(WARN, "failed to check is task cancel", K(tmp_ret));
      }

      if (OB_SUCCESS != (tmp_ret = try_schedule_new_partition_migration())) {
        STORAGE_LOG(WARN, "failed to try_schedule_new_partition_migration", K(tmp_ret));
      }

      if (OB_SUCCESS != (tmp_ret = try_finish_group_migration())) {
        STORAGE_LOG(WARN, "failed to try_finish_group_migration", K(tmp_ret));
      }

      if (!is_finished_) {
        share::dag_yield();
        ObThreadCondGuard guard(cond_);
        if (need_idle_) {
          if (OB_SUCCESS != (tmp_ret = cond_.wait(PART_GROUP_TASK_IDLE_TIME_MS))) {
            if (OB_TIMEOUT != tmp_ret) {
              STORAGE_LOG(WARN, "failed to idle", K(tmp_ret));
            }
          }
        }
        need_idle_ = true;
      }
    }
  }

  ObTaskController::get().allow_next_syslog();
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  LOG_INFO("group migrate task finish", K(cost_ts), K(*this));

  return ret;
}

int ObPartGroupMigrationTask::remove_member_list_if_need()
{
  int ret = OB_SUCCESS;
  ObAddr leader_addr;
  bool need_remove = false;
  bool need_batch = true;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (CHANGE_REPLICA_OP != type_) {
    LOG_INFO("no need remove member list");
  } else if (OB_FAIL(check_need_batch_remove_member(leader_addr, need_remove, need_batch))) {
    LOG_WARN("failed to check need batch remove member", K(ret));
  } else if (!need_remove) {
    LOG_INFO("no need remove member");
  } else if (need_batch) {
    hash::ObHashSet<ObPartitionKey> removed_pkeys;
    ObArray<ObReportPartMigrationTask> report_list;
    SMART_VAR(ObReportPartMigrationTask, tmp_task)
    {
      for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
        ObPartMigrationTask& sub_task = task_list_[i];
        tmp_task.arg_ = sub_task.arg_;
        tmp_task.status_ = sub_task.status_;
        tmp_task.result_ = sub_task.result_;
        tmp_task.need_report_checksum_ = sub_task.ctx_.need_report_checksum_;
        tmp_task.ctx_ = &sub_task.ctx_;
        if (OB_FAIL(report_list.push_back(tmp_task))) {
          // report_list is reserved before, should not fail here
          STORAGE_LOG(ERROR, "failed to add report list", K(ret));
        }
      }

      if (OB_FAIL(try_batch_remove_member(report_list, leader_addr, removed_pkeys))) {
        LOG_WARN("failed to batch remove member list", K(ret));
      } else if ((removed_pkeys.size() != report_list.count()) || (report_list.count() != task_list_.count())) {
        ret = OB_PARTIAL_FAILED;
        LOG_WARN("failed to remove member list",
            K(ret),
            K(leader_addr),
            "removed_pkeys",
            removed_pkeys.size(),
            "task_count",
            report_list.count(),
            K(task_list_.count()));
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
          ObPartMigrationTask& sub_task = task_list_[i];
          sub_task.result_ = report_list.at(i).result_;
        }
      }
    }
  } else {
    if (OB_FAIL(try_single_remove_member())) {
      LOG_WARN("failed to single remove member list", K(ret));
    }
  }

  if (OB_FAIL(ret)) {
    first_error_code_ = ret;
  }
  return ret;
}

int ObPartGroupMigrationTask::check_need_batch_remove_member(ObAddr& leader_addr, bool& need_remove, bool& need_batch)
{
  int ret = OB_SUCCESS;
  ObMigrateSrcInfo tmp_src_info;
  const int64_t start_ts = ObTimeUtility::current_time();
  leader_addr.reset();
  need_remove = false;
  need_batch = true;
  const bool is_primary_cluster = GCTX.is_primary_cluster();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (task_list_.count() <= 0) {
    ret = OB_ERR_SYS;
    LOG_ERROR("no task need migrate", K(ret), K(task_list_));
  } else if (NORMAL_CHANGE_MEMBER_LIST != task_list_.at(0).arg_.change_member_option_) {
    LOG_INFO("task skip change member list, skip it", K(task_list_.at(0)));
  } else {
    ObReplicaType src_type = task_list_.at(0).arg_.src_.get_replica_type();
    ObReplicaType dest_type = task_list_.at(0).arg_.dst_.get_replica_type();
    const ObAddr& self_addr = partition_service_->get_self_addr();

    // For batch operations of this type, rs guarantees src_type and dest_type must be consistent with the local,
    // or an error will be report directly
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      ObIPartitionGroupGuard guard;
      ObPartMigrationTask& task = task_list_.at(i);
      if (OB_FAIL(ObPartitionService::get_instance().get_partition(task.arg_.key_, guard))) {
        LOG_WARN("failed to get partition guard", K(ret), "arg", task.arg_);
      } else if (OB_ISNULL(guard.get_partition_group())) {
        ret = OB_ERR_SYS;
        LOG_ERROR("partition must not null", K(ret), "arg", task.arg_);
      } else if (guard.get_partition_group()->get_replica_type() != src_type ||
                 src_type != task.arg_.src_.get_replica_type() || dest_type != task.arg_.dst_.get_replica_type() ||
                 self_addr != task.arg_.src_.get_server() || self_addr != task.arg_.dst_.get_server()) {
        ret = OB_INVALID_ARGUMENT;
        LOG_WARN("replica type not match",
            K(ret),
            K(self_addr),
            K(src_type),
            K(dest_type),
            "local_replica_type",
            guard.get_partition_group()->get_replica_type(),
            "arg",
            task.arg_);
      }
    }

    if (OB_SUCC(ret)) {
      if (src_type == dest_type) {
        ret = OB_ALREADY_DONE;
        STORAGE_LOG(WARN, "no change of replica type", K(ret), K(src_type), K(dest_type));
      } else if (!ObReplicaTypeCheck::change_replica_op_allow(src_type, dest_type)) {
        ret = OB_OP_NOT_ALLOW;
        STORAGE_LOG(WARN, "change replica op not allow", K(src_type), K(dest_type), K(ret));
      } else if (ObReplicaTypeCheck::is_paxos_replica(src_type) && !ObReplicaTypeCheck::is_paxos_replica(dest_type)) {
        LOG_INFO("need remove member list first");
        need_remove = true;
        for (int64_t i = 0; OB_SUCC(ret) && need_batch && i < task_list_.count(); ++i) {
          const ObReplicaOpArg& arg = task_list_.at(i).arg_;
          if (OB_FAIL(ObMigrateGetLeaderUtil::get_leader(arg.key_, tmp_src_info, true /*force_update*/))) {
            STORAGE_LOG(WARN, "failed to get leader address", K(ret), K(arg.key_));
          } else if (!tmp_src_info.is_valid()) {
            need_batch = false;
            STORAGE_LOG(WARN, "some partition has no leader, cannot batch change member", K(arg), K(tmp_src_info));
          } else if (0 == i) {
            leader_addr = tmp_src_info.src_addr_;
          } else if (leader_addr != tmp_src_info.src_addr_) {
            need_batch = false;
            STORAGE_LOG(WARN,
                "partitions have diff leader, cannot batch change member",
                K(tmp_src_info),
                K(leader_addr),
                K(arg));
          }
        }
      }
    }
  }

#ifdef ERRSIM
  if (OB_SUCC(ret) && need_batch) {
    need_batch = GCONF.allow_batch_remove_member_during_change_replica;
    if (!need_batch) {
      LOG_ERROR("fake not need batch remove member list");
    }
  }
#endif

  ObTaskController::get().allow_next_syslog();
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  STORAGE_LOG(INFO,
      "check_need_batch_remove_member",
      K(ret),
      "count",
      task_list_.count(),
      K(need_remove),
      K(need_batch),
      K(cost_ts));
  return ret;
}

int ObPartGroupMigrationTask::try_single_remove_member()
{
  int ret = OB_SUCCESS;
  share::ObTaskId dummy_id;
  const int64_t start_ts = ObTimeUtility::current_time();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    dummy_id.init(partition_service_->get_self_addr());
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      const ObReplicaOpArg& arg = task_list_.at(i).arg_;
      int64_t dummy_orig_quorum = OB_INVALID_COUNT;  // only used in ObPartitionService::batch_remove_replica_mc
      obrpc::ObMemberChangeArg remove_arg = {
          arg.key_, arg.src_, false, arg.quorum_, dummy_orig_quorum, WITHOUT_MODIFY_QUORUM, dummy_id};  // mock task id
      if (OB_FAIL(partition_service_->try_remove_from_member_list(remove_arg))) {
        STORAGE_LOG(WARN, "remove replica from member list failed", K(remove_arg), K(ret));
      } else {
        STORAGE_LOG(INFO, "remove replica from member list successfully", K(i), K(arg));
      }
    }
  }

  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  ObTaskController::get().allow_next_syslog();
  LOG_INFO("finish try_single_remove_member", K(ret), "count", task_list_.count(), K(cost_ts));
  return ret;
}

int ObPartGroupMigrationTask::set_create_new_pg(const ObPartitionKey& pg_key)
{
  int ret = OB_SUCCESS;
  ObPartMigrationTask* task = NULL;
  common::SpinWLockGuard guard(lock_);
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    for (int64_t i = 0; NULL == task && i < task_list_.count(); ++i) {
      if (task_list_[i].arg_.key_ == pg_key) {
        task = &task_list_[i];
      }
    }
    if (OB_ISNULL(task)) {
      ret = OB_ENTRY_NOT_EXIST;
      STORAGE_LOG(ERROR, "cannot found pg in task", K(ret), K(pg_key), KP(this), K(*this));
    } else {
      task->need_reset_migrate_status_ = true;
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::set_migrate_in(ObPGStorage& pg_storage)
{
  int ret = OB_SUCCESS;
  ObPartMigrationTask* task = NULL;
  const ObPartitionKey& pkey = pg_storage.get_partition_key();  // TODO () change it to pg key
  int64_t current_ts = ObTimeUtility::current_time();
  ObMigrateStatus old_status = OB_MIGRATE_STATUS_MAX;
  ObMigrateStatus new_status = OB_MIGRATE_STATUS_MAX;
  common::SpinWLockGuard guard(lock_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    for (int64_t i = 0; NULL == task && i < task_list_.count(); ++i) {
      if (task_list_[i].arg_.key_ == pkey) {
        task = &task_list_[i];
      }
    }
    if (NULL == task) {
      ret = OB_ENTRY_NOT_EXIST;
      STORAGE_LOG(ERROR, "cannot found pkey in task", K(ret), K(pkey), KP(this), K(*this));
    } else if (OB_FAIL(pg_storage.get_pg_migrate_status(old_status))) {
      LOG_WARN("failed to get old status", K(ret), K(pkey));
    } else if (BACKUP_REPLICA_OP == task->arg_.type_ || VALIDATE_BACKUP_OP == task->arg_.type_) {
      LOG_INFO("no need set migrate_status", K(task->arg_.type_), K(pkey));
    } else if (OB_FAIL(ObMigrateStatusHelper::trans_replica_op(task->arg_.type_, new_status))) {
      LOG_WARN("failed to trans_replica_op_to_migrate_status", K(ret), "arg", task->arg_);
O
obdev 已提交
2771
    } else if (OB_MIGRATE_STATUS_NONE != old_status) {
O
oceanbase-admin 已提交
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 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 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 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 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 3061 3062 3063 3064 3065 3066 3067 3068 3069 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 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 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 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 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 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916
      ret = OB_STATE_NOT_MATCH;
      LOG_WARN("old migrate is not finish, cannot set new migrate status",
          K(ret),
          K(pkey),
          K(old_status),
          "arg",
          task->arg_);
    } else {
      if (OB_FAIL(pg_storage.set_pg_migrate_status(new_status, current_ts))) {
        STORAGE_LOG(WARN, "failed to set migrate status", K(ret), K(pkey), K(new_status));
      } else {
        task->need_reset_migrate_status_ = true;
        if (old_status == OB_MIGRATE_STATUS_ADD_FAIL || old_status == OB_MIGRATE_STATUS_MIGRATE_FAIL) {
          task->during_migrating_ = true;
        }
        if (ADD_REPLICA_OP == task->arg_.type_ && pg_storage.is_restore()) {
          change_member_option_ = SKIP_CHANGE_MEMBER_LIST;
          STORAGE_LOG(INFO, "add replica op when restore skip set member list", K(pkey));
        }
      }
      STORAGE_LOG(INFO,
          "finish set migrate status",
          K(ret),
          K(pkey),
          K(old_status),
          K(new_status),
          "during_migrating_flag",
          task->during_migrating_);
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::check_before_do_task()
{
  // Scheduling is only necessary before starting execution, without concurrent consideration
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (REMOVE_REPLICA_OP == type_) {
    STORAGE_LOG(INFO, "no need to check remove replica task", K(*this));
  } else if (BACKUP_REPLICA_OP == type_) {
    if (OB_FAIL(check_before_backup())) {
      STORAGE_LOG(WARN, "failed to check before backup", K(ret), K(*this));
    }
  }

  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(check_partition_validation())) {
    STORAGE_LOG(WARN, "failed to check_partition_validation", K(ret));
  } else if (OB_FAIL(check_disk_space())) {
    STORAGE_LOG(WARN, "failed to check_disk_space", K(ret));
  }

  if (OB_FAIL(ret)) {
    ObTaskController::get().allow_next_syslog();
    first_error_code_ = ret;
    STORAGE_LOG(WARN, "failed to check task, mark fail", K(ret), K(*this));
  }
  return ret;
}

int ObPartGroupMigrationTask::check_partition_validation()
{
  // Scheduling is only necessary before starting execution, without concurrent consideration
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      ObPartMigrationTask& sub_task = task_list_[i];
      ObPartitionKey& pkey = sub_task.arg_.key_;
      bool in_member_list = false;
      bool is_working_partition = partition_service_->is_working_partition(pkey);

      if (ObPartGroupMigrator::get_instance().is_stop()) {
        ret = OB_SERVER_IS_STOPPING;
        STORAGE_LOG(WARN, "server is stopping", K(ret));
      } else if (REMOVE_REPLICA_OP == sub_task.arg_.type_) {
        ret = OB_ERR_SYS;
        LOG_ERROR("remove replica cannot schedule migrate", K(ret), "arg", sub_task.arg_);
      } else if (ADD_REPLICA_OP == type_ || MIGRATE_REPLICA_OP == type_ || FAST_MIGRATE_REPLICA_OP == type_) {
        if (partition_service_->is_partition_exist(pkey)) {
          ret = OB_ENTRY_EXIST;
          ObTaskController::get().allow_next_syslog();
          STORAGE_LOG(WARN, "can not add replica which is already exsit", K(ret), K(pkey), K(sub_task));
        }
      } else if (REBUILD_REPLICA_OP == type_) {
        if (!is_working_partition) {
          if (OB_FAIL(partition_service_->check_self_in_member_list(pkey, in_member_list))) {
            STORAGE_LOG(WARN, "failed to check_self_in_member_list", K(ret), K(pkey));
          } else if (!in_member_list) {
            ret = OB_WORKING_PARTITION_NOT_EXIST;
            ObTaskController::get().allow_next_syslog();
            STORAGE_LOG(WARN, "can not rebuild, it is not normal replica", K(ret), K(pkey), K(sub_task));
          } else {
            // Allow partition reconstruction in the member list except for non normal partition
            ObTaskController::get().allow_next_syslog();
            STORAGE_LOG(WARN, "it is not normal partition", K(ret), K(pkey), K(sub_task));
          }
        }
      } else if (COPY_GLOBAL_INDEX_OP == type_ || COPY_LOCAL_INDEX_OP == type_ || LINK_SHARE_MAJOR_OP == type_) {
        if (!is_working_partition) {
          ret = OB_STATE_NOT_MATCH;
          ObTaskController::get().allow_next_syslog();
          LOG_WARN("cannot copy index to not working partition", K(ret));
        }
      } else {
        // do nothing
      }
    }
#ifdef ERRSIM
    if (OB_SUCC(ret)) {
      ret = E(EventTable::EN_CHECK_SUB_MIGRATION_TASK) OB_SUCCESS;
      if (OB_FAIL(ret)) {
        STORAGE_LOG(ERROR, "fake EN_CHECK_SUB_MIGRATION_TASK", K(ret));
      }
    }
#endif
  }

  return ret;
}

int ObPartGroupMigrationTask::check_disk_space()
{  // Scheduling is only necessary before starting execution, without concurrent consideration
  int ret = OB_SUCCESS;
  int64_t required_size = 0;
  int64_t partition_required_size = 0;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (MIGRATE_REPLICA_OP != type_ && ADD_REPLICA_OP != type_) {
    STORAGE_LOG(INFO, "only migrate or add replica task need check disk space, others skip it", K(type_));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      ObPartitionKey& pkey = task_list_[i].arg_.key_;
      if (ObPartGroupMigrator::get_instance().is_stop()) {
        ret = OB_SERVER_IS_STOPPING;
        STORAGE_LOG(WARN, "server is stopping", K(ret));
      } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(task_list_[i].arg_.dst_.get_replica_type())) {
        STORAGE_LOG(INFO, "dst has no ssstore, no need check disk space", "arg", task_list_[i].arg_);
      } else if (OB_FAIL(get_partition_required_size(pkey, partition_required_size))) {
        STORAGE_LOG(WARN, "failed to partition_required_size", K(ret), K(pkey));
      } else {
        required_size += partition_required_size;
      }
    }

    if (OB_SUCC(ret) && required_size > 0) {
      if (OB_FAIL(OB_STORE_FILE.check_disk_full(required_size))) {
        if (OB_CS_OUTOF_DISK_SPACE == ret) {
          ret = OB_SERVER_MIGRATE_IN_DENIED;
        }
        ObTaskController::get().allow_next_syslog();
        STORAGE_LOG(WARN, "failed to check_is_disk_full, cannot migrate in", K(ret), K(required_size));
      }
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::check_before_backup()
{
  int ret = OB_SUCCESS;
  ObExternBackupInfoMgr extern_backup_info_mgr;
  ObClusterBackupDest cluster_backup_dest;
  ObBackupDest backup_dest;
  ObFakeBackupLeaseService fake_backup_lease_service;
  ObExternBackupInfo last_backup_info;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (BACKUP_REPLICA_OP != type_) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "replica op is not backup, no need check", K(ret));
  } else {
    const ObPhysicalBackupArg& backup_arg = task_list_[0].arg_.backup_arg_;
    const uint64_t tenant_id = task_list_[0].arg_.key_.get_tenant_id();
    if (OB_FAIL(backup_dest.set(backup_arg.uri_header_, backup_arg.storage_info_))) {
      STORAGE_LOG(WARN, "failed to set backup dest", K(ret), K(backup_arg));
    } else if (OB_FAIL(cluster_backup_dest.set(backup_dest, backup_arg.incarnation_))) {
      STORAGE_LOG(WARN, "failed to set cluster backup dest", K(ret), K(backup_dest));
    } else if (OB_FAIL(extern_backup_info_mgr.init(tenant_id, cluster_backup_dest, fake_backup_lease_service))) {
      STORAGE_LOG(WARN, "failed to init extern backup info", K(ret), K(cluster_backup_dest));
    } else if (OB_FAIL(extern_backup_info_mgr.get_last_info(last_backup_info))) {
      STORAGE_LOG(WARN, "failed to get last info", K(ret), K(cluster_backup_dest));
    } else if (!last_backup_info.is_valid() || ObExternBackupInfo::DOING != last_backup_info.status_ ||
               last_backup_info.backup_data_version_ != backup_arg.backup_data_version_ ||
               last_backup_info.backup_schema_version_ != backup_arg.backup_schema_version_ ||
               last_backup_info.backup_type_ != backup_arg.backup_type_ ||
               last_backup_info.inc_backup_set_id_ != backup_arg.backup_set_id_) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("last backup info is unexpected", K(ret), K(last_backup_info), K(backup_arg));
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::get_partition_required_size(const common::ObPartitionKey& pkey, int64_t& required_size)
{
  // statuc func
  int ret = OB_SUCCESS;
  share::ObPartitionTableOperator* pt_operator = NULL;
  ModulePageAllocator allocator(ObNewModIds::OB_PARTITION_MIGRATE);
  share::ObPartitionInfo partition_info;
  partition_info.set_allocator(&allocator);
  required_size = 0;

  if (NULL == (pt_operator = GCTX.pt_operator_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "pt_operator must not NULL.", K(ret));
  } else if (OB_SUCCESS != (ret = pt_operator->get(pkey.get_table_id(), pkey.get_partition_id(), partition_info))) {
    STORAGE_LOG(WARN, "fail to get partition info.", K(ret), K(pkey));
  } else {
    const common::ObIArray<share::ObPartitionReplica>& replicas = partition_info.get_replicas_v2();
    for (int64_t i = 0; OB_SUCC(ret) && i < replicas.count(); ++i) {
      if (replicas.at(i).required_size_ > required_size) {
        required_size = replicas.at(i).required_size_;
      }
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::try_schedule_new_partition_migration()
{
  int ret = OB_SUCCESS;

  {
    common::SpinRLockGuard guard(lock_);
    if (!is_inited_) {
      ret = OB_NOT_INIT;
      STORAGE_LOG(ERROR, "not inited", K(ret));
    } else if (OB_SUCCESS != first_error_code_) {
      ret = first_error_code_;
      STORAGE_LOG(WARN, "first_error_code_ is set, skip schedule new partition migration", K(ret));
    }
  }

  if (OB_SUCC(ret)) {
    if (VALIDATE_BACKUP_OP == type_) {
      if (OB_FAIL(try_schedule_partition_validate())) {
        STORAGE_LOG(WARN, "failed to try schedule partition validate", K(ret));
      }
    } else {
      if (OB_FAIL(try_schedule_partition_migration())) {
        STORAGE_LOG(WARN, "failed to try scheudule partition migration", K(ret));
      }
    }
  }
  return ret;
}

// caller must not hold wlock
int ObPartGroupMigrationTask::schedule_migrate_dag(ObMigrateCtx& migrate_ctx)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(check_partition_checksum(migrate_ctx.replica_op_arg_.key_))) {
    STORAGE_LOG(WARN,
        "failed to check partition checksum, cannot schedule migration",
        K(ret),
        K(migrate_ctx.replica_op_arg_.key_));
  } else if (OB_FAIL(migrate_ctx.generate_and_schedule_migrate_dag())) {
    STORAGE_LOG(WARN, "failed to generate migrate dag", K(ret));
  }

  if (OB_FAIL(ret)) {
    share::ObTaskId fake_task_id;
    const bool during_migrating = false;
    const int64_t backup_set_id = migrate_ctx.replica_op_arg_.validate_arg_.backup_set_id_;
    if (OB_SUCCESS != (tmp_ret = set_part_task_finish(
                           migrate_ctx.replica_op_arg_.key_, ret, fake_task_id, during_migrating, backup_set_id))) {
      LOG_WARN("failed to finish part task", K(ret));
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::try_finish_group_migration()
{
  int ret = OB_SUCCESS;
  bool is_sub_task_finish = true;
  report_list_.reset();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else {
    common::SpinWLockGuard guard(lock_);

    for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
      ObPartMigrationTask& task = task_list_[i];
      if (ObPartMigrationTask::FINISH != task.status_) {
        if (OB_SUCCESS != first_error_code_ && ObPartMigrationTask::INIT == task.status_) {
          task.status_ = ObPartMigrationTask::FINISH;
          task.result_ = first_error_code_;
        } else {
          is_sub_task_finish = false;
        }
      } else if (OB_SUCCESS != task.result_) {
        if (BACKUP_REPLICA_OP == get_type() && OB_PG_IS_REMOVED == task.result_) {
          // do nothing
        } else if (OB_SUCCESS == first_error_code_) {
          first_error_code_ = OB_ERR_SYS;
          STORAGE_LOG(ERROR, "sub task has error , but first_error_code_ is succ, use OB_ERR_SYS", K(*this));
        }
      }
    }

    if (OB_SUCC(ret) && is_sub_task_finish) {
      SMART_VAR(ObReportPartMigrationTask, tmp_task)
      {

        if (OB_FAIL(report_list_.reserve(task_list_.count()))) {
          STORAGE_LOG(WARN, "failed to reserve report list", K(ret));
        }
        for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
          ObPartMigrationTask& sub_task = task_list_[i];
          tmp_task.arg_ = sub_task.arg_;
          tmp_task.status_ = ObIPartMigrationTask::FINISH;
          tmp_task.result_ = sub_task.result_;
          tmp_task.need_report_checksum_ = sub_task.ctx_.need_report_checksum_;
          tmp_task.ctx_ = &sub_task.ctx_;
          tmp_task.data_statics_ = sub_task.ctx_.data_statics_;
          if (OB_FAIL(tmp_task.partitions_.assign(sub_task.ctx_.pg_meta_.partitions_))) {
            STORAGE_LOG(WARN, "failed to assign partitions", K(ret), K(sub_task.ctx_));
          } else if (OB_FAIL(report_list_.push_back(tmp_task))) {
            // report_list is reserved before, should not fail here
            STORAGE_LOG(ERROR, "failed to add report list", K(ret));
          }
        }
      }
    }
  }

  if (OB_SUCC(ret) && is_sub_task_finish) {
    if (OB_FAIL(finish_group_migration(report_list_))) {
      STORAGE_LOG(WARN, "failed to do finish_group_migration", K(ret));
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::finish_group_migration(ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (REMOVE_REPLICA_OP == type_) {
    // The deleting op of the replica does not change the operation of the member list and reporting operation
    common::SpinWLockGuard guard(lock_);
    is_finished_ = true;
    ObTaskController::get().allow_next_syslog();
    STORAGE_LOG(INFO, "group migration all finish", K(ret), K(first_error_code_), K(report_list), K(*this));
  } else if (BACKUP_REPLICA_OP == type_ || VALIDATE_BACKUP_OP == type_) {
    // backup base sstable only need change task status
    common::SpinWLockGuard guard(lock_);
    is_finished_ = true;
    ObTaskController::get().allow_next_syslog();
    STORAGE_LOG(INFO, "group migration-backup all finish", K(ret), K(first_error_code_), K(report_list), K(*this));
  } else if (OB_UNLIKELY(report_list.count() <= 0)) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arguments", K(ret), K(report_list.count()));
  } else {
    bool is_all_finish = false;
    bool is_report_succ = false;
    hash::ObHashSet<ObPartitionKey> removed_pkeys;

    if (0 == retry_job_start_ts_) {
      retry_job_start_ts_ = ObTimeUtility::current_time();
    }
    if (OB_SUCCESS != (tmp_ret = report_meta_table(report_list, removed_pkeys))) {
      STORAGE_LOG(WARN, "fail to report meta table", K(ret));
    } else {
      is_report_succ = true;
    }
    if (has_error()) {
      is_all_finish = true;
      if (OB_FAIL(build_failed_report_list(first_error_code_, report_list))) {
        STORAGE_LOG(WARN, "failed to build_failed_report_list", K(ret));
      }
    } else if (is_report_succ) {
      // TODO () consider more detail about it
      if (RESTORE_REPLICA_OP == type_ || COPY_LOCAL_INDEX_OP == type_ || RESTORE_FOLLOWER_REPLICA_OP == type_ ||
          RESTORE_STANDBY_OP == type_ || LINK_SHARE_MAJOR_OP == type_) {
        is_all_finish = true;
        STORAGE_LOG(INFO, "no need change member list", K(type_));
      } else {
        if (OB_SUCCESS != (tmp_ret = try_change_member_list(report_list, is_all_finish))) {
          STORAGE_LOG(WARN, "failed to try_change_member_list", K(tmp_ret), K(first_error_code_));
        } else {
          is_all_finish = true;
        }
      }

      if (first_error_code_ != OB_SUCCESS) {
        is_all_finish = true;
        if (OB_FAIL(build_failed_report_list(first_error_code_, report_list))) {
          STORAGE_LOG(WARN, "failed to build_failed_report_list", K(ret));
        }
      }
    }

    if (is_all_finish) {
      {
        common::SpinWLockGuard guard(lock_);
        is_finished_ = true;
        ObTaskController::get().allow_next_syslog();
        STORAGE_LOG(INFO, "group migration all finish", K(ret), K(first_error_code_), K(report_list), K(*this));
      }
      if (OB_SUCC(ret)) {
        for (int64_t i = 0; i < report_list.count(); ++i) {
          for (int64_t j = 0; j < report_list.at(i).partitions_.count(); ++j) {
            const ObPartitionKey& pkey = report_list.at(i).partitions_.at(j);
            if (OB_SUCCESS != (tmp_ret = partition_service_->report_migrate_in_indexes(pkey))) {
              STORAGE_LOG(WARN, "failed to handle_report_meta_table_callback", K(tmp_ret), K(i), K(report_list.at(i)));
            }
          }
        }
      }

      if (RESTORE_REPLICA_OP == type_ && OB_SUCCESS != first_error_code_) {
        if (OB_SUCCESS != (tmp_ret = report_restore_fatal_error_())) {
          LOG_WARN("failed to report restore failed", K(tmp_ret));
        }
      }

      ObRebuildReplicaTaskScheduler& rebuild_scheduler =
          partition_service_->get_rebuild_replica_service().get_scheduler();
      if (OB_SUCC(ret) && REBUILD_REPLICA_OP == type_) {
        ObRebuildReplicaResult results;
        for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
          if (OB_FAIL(results.set_result(report_list.at(i).arg_.key_, report_list.at(i).result_))) {
            STORAGE_LOG(WARN, "failed to set rebuild result", K(ret), K(report_list.at(i)));
          }
        }
      }
      rebuild_scheduler.notify();
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::report_restore_fatal_error_()
{
  int ret = OB_SUCCESS;
  int64_t job_id = 0;

  if (OB_FAIL(ObBackupInfoMgr::get_instance().get_restore_job_id(tenant_id_, job_id))) {
    if (OB_ENTRY_NOT_EXIST != ret) {
      LOG_WARN("failed to get restore info", K(ret), K(tenant_id_));
    } else {
      ret = OB_SUCCESS;
      LOG_INFO("physical restore info not exist", K(tenant_id_), K(first_error_code_));
    }
  } else if (OB_INVALID_ARGUMENT == first_error_code_ || OB_ERR_SYS == first_error_code_ ||
             OB_INIT_TWICE == first_error_code_ || OB_ERR_UNEXPECTED == first_error_code_ ||
             OB_INVALID_BACKUP_DEST == first_error_code_ || OB_INVALID_DATA == first_error_code_ ||
             OB_CHECKSUM_ERROR == first_error_code_) {
    if (OB_FAIL(ObRestoreFatalErrorReporter::get_instance().add_restore_error_task(
            tenant_id_, PHYSICAL_RESTORE_MOD_STORAGE, first_error_code_, job_id, MYADDR))) {
      LOG_WARN("failed to report restore error", K(ret), K(tenant_id_), K(first_error_code_));
    }
  } else {
    LOG_INFO("skip not fatal report restore error", K(tenant_id_), K(first_error_code_));
  }

  return ret;
}

int ObPartGroupMigrationTask::try_change_member_list(
    ObIArray<ObReportPartMigrationTask>& report_list, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  const int64_t change_member_list_timeout = GCONF.sys_bkgd_migration_change_member_list_timeout;
  const int64_t start_ts = ObTimeUtility::current_time();
  ObMigrateSrcInfo leader_info;
  bool need_batch = false;

  DEBUG_SYNC(BEFORE_CHANGE_MEMBER_LIST);

  if (0 == start_change_member_ts_) {
    start_change_member_ts_ = ObTimeUtility::current_time();
    STORAGE_LOG(INFO, "start change member list", K(report_list));
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() <= 0) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "task list is empty", K(ret));
  } else if (NORMAL_CHANGE_MEMBER_LIST != change_member_option_) {
    if (MIGRATE_REPLICA_OP == type_) {
      if (OB_SUCCESS != (tmp_ret = batch_remove_src_replica(report_list))) {
        STORAGE_LOG(WARN, "failed to batch remove src replica", K(ret));
      }
    }
    STORAGE_LOG(INFO, "skip change member list is set, no need try_change_memer_list", K(ret), K(*this));
  } else if (start_ts - start_change_member_ts_ > change_member_list_timeout) {
    is_all_finish = true;
    ret = OB_TIMEOUT;
    first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
    STORAGE_LOG(WARN,
        "max retry change member time exceeds",
        K(ret),
        K(start_change_member_ts_),
        K(change_member_list_timeout));
  } else if (OB_FAIL(
                 ObMigrateGetLeaderUtil::get_leader(report_list.at(0).arg_.key_, leader_info, true /*force_update*/))) {
    bool is_partition_exist = true;
    if (OB_SUCCESS != (tmp_ret = check_is_partition_exist(report_list.at(0).arg_.key_, is_partition_exist))) {
      LOG_WARN("failed to check is partition exist", K(tmp_ret));
    } else if (!is_partition_exist) {
      first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
      LOG_WARN("partition not exist, set migration failed", K(ret), "pkey", report_list.at(0).arg_.key_);
    } else {
      STORAGE_LOG(WARN, "fail to get leader", K(ret));
    }
  } else if (OB_FAIL(check_need_batch_change_member_list(leader_info.src_addr_, report_list, need_batch))) {
    STORAGE_LOG(WARN, "failed to check_need_batch_change_member_list", K(ret));
  } else if (need_batch) {
    if (MIGRATE_REPLICA_OP == type_ || FAST_MIGRATE_REPLICA_OP == type_) {
      if (OB_FAIL(try_batch_change_member_list(report_list, leader_info.src_addr_, is_all_finish))) {
        STORAGE_LOG(WARN, "failed to try_batch_change_member_list", K(ret), K(leader_info), K(report_list));
      }
    } else if (CHANGE_REPLICA_OP == type_) {
      if (OB_FAIL(try_batch_add_member(report_list, leader_info.src_addr_, is_all_finish))) {
        LOG_WARN("failed to try_batch_add_member", K(ret), K(leader_info), K(report_list));
      }
    } else {
      ret = OB_ERR_SYS;
      LOG_ERROR("not support batch type", K(ret), K_(type));
    }
  } else {
    if (OB_FAIL(try_not_batch_change_member_list(report_list, is_all_finish))) {
      STORAGE_LOG(WARN, "failed to try_not_batch_change_member_list", K(ret));
    }
  }
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  STORAGE_LOG(INFO, "try_change_member_list", K(cost_ts), K(ret), K(is_all_finish), "count", report_list.count());

  return ret;
}

int ObPartGroupMigrationTask::check_need_batch_change_member_list(
    const ObAddr& leader_addr, ObIArray<ObReportPartMigrationTask>& report_list, bool& need_batch)
{
  int ret = OB_SUCCESS;
  ObMigrateSrcInfo tmp_leader_info;
  need_batch = false;
  const int64_t start_ts = ObTimeUtility::current_time();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() <= 0 || !leader_addr.is_valid()) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "task list is empty", K(ret), K(leader_addr));
  } else {
    need_batch = true;
    for (int64_t i = 0; OB_SUCC(ret) && need_batch && i < report_list.count(); ++i) {
      const ObReplicaOpArg& arg = report_list.at(i).arg_;
      if (MIGRATE_REPLICA_OP == arg.type_ || FAST_MIGRATE_REPLICA_OP == arg.type_) {
        if (!ObReplicaTypeCheck::is_paxos_replica(arg.dst_.get_replica_type())) {
          need_batch = false;
        }
      } else if (CHANGE_REPLICA_OP == arg.type_) {
        if (ObReplicaTypeCheck::is_paxos_replica(arg.src_.get_replica_type()) ||
            !ObReplicaTypeCheck::is_paxos_replica(arg.dst_.get_replica_type())) {
          need_batch = false;
        }
      } else {
        need_batch = false;
      }

      if (OB_SUCC(ret) && need_batch) {
        if (OB_FAIL(ObMigrateGetLeaderUtil::get_leader(arg.key_, tmp_leader_info, true /*force_update*/))) {
          STORAGE_LOG(WARN, "failed to get leader address", K(ret), K(arg.key_));
          int tmp_ret = OB_SUCCESS;
          bool is_schema_exist = true;
          if (OB_SUCCESS != (tmp_ret = check_is_partition_exist(arg.key_, is_schema_exist))) {
            LOG_WARN("check is partition exist failed", K(tmp_ret), K(arg.key_));
          } else if (!is_schema_exist) {
            first_error_code_ = ret;
            LOG_WARN("partition schema not exist, set first_error_code_", K(first_error_code_));
          }
        } else if (!tmp_leader_info.is_valid()) {
          need_batch = false;
          STORAGE_LOG(WARN, "some partition has no leader, cannot batch change member", K(arg), K(tmp_leader_info));
        } else if (leader_addr != tmp_leader_info.src_addr_) {
          need_batch = false;
          STORAGE_LOG(WARN,
              "partitions have diff leader, cannot batch change member",
              K(tmp_leader_info),
              K(leader_addr),
              K(arg));
        }
      }
    }
  }

#ifdef ERRSIM
  if (OB_SUCC(ret) && need_batch) {
    need_batch = GCONF.allow_batch_change_member;
    if (!need_batch) {
      LOG_ERROR("fake not need batch change member list");
    }
  }
#endif

  ObTaskController::get().allow_next_syslog();
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  STORAGE_LOG(
      INFO, "check_need_batch_change_member_list", K(cost_ts), K(ret), K(need_batch), "count", report_list.count());
  return ret;
}

int ObPartGroupMigrationTask::fast_migrate_add_member_list_one_by_one(
    common::ObIArray<ObReportPartMigrationTask>& report_list, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
  int64_t start_ts = ObTimeUtility::current_time();
  int64_t succ_count = 0;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (report_list.count() <= 0) {
    ret = OB_ERR_SYS;
    LOG_WARN("task list is empty", K(ret));
  } else if (FAST_MIGRATE_REPLICA_OP != type_) {
    ret = OB_ERR_SYS;
    LOG_WARN("wrong task type", K(ret), K(type_));
  }
  int64_t switch_epoch = GCTX.get_switch_epoch2();
  for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
    ObReportPartMigrationTask& cur_task = report_list.at(i);
    const ObPGKey& pg_key = cur_task.arg_.key_;
    ObMigrateCtx* cur_ctx = cur_task.ctx_;
    ObIPartitionGroup* pg = nullptr;
    int64_t quorum = 0;
    ObMigrateSrcInfo leader_info;
    ObMember new_member(GCTX.self_addr_, ObTimeUtility::current_time());
    int tmp_ret = OB_SUCCESS;
    if (OB_ISNULL(cur_ctx) || OB_ISNULL(pg = cur_ctx->partition_guard_.get_partition_group())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("migrate ctx is null", K(ret), K(pg_key), KP(cur_ctx), KP(pg));
    } else if (OB_SUCCESS != cur_task.result_) {
      LOG_INFO("fast migrate: skip add self to member list", K(cur_task.result_), K(pg_key));
    } else if (OB_SUCCESS != (tmp_ret = pg->get_log_service()->get_replica_num(quorum))) {
      LOG_WARN("fail to get quorum", K(tmp_ret), K(pg_key));
    } else if (OB_SUCCESS !=
               (tmp_ret = ObMigrateGetLeaderUtil::get_leader(pg_key, leader_info, true /*force_update*/))) {
      LOG_WARN("fail to get pg leader", K(tmp_ret), K(pg_key));
    } else if (OB_SUCCESS != (tmp_ret = partition_service_->fast_migrate_try_add_member(
                                  leader_info.src_addr_, pg_key, new_member, quorum, switch_epoch))) {
      LOG_WARN("fail to add self to member list", K(tmp_ret), K(pg_key));
    } else {
      cur_ctx->is_member_change_finished_ = true;
      LOG_INFO("fast_migrate: succ to change member list", K(pg_key));
      ++succ_count;
    }
  }
  if (OB_FAIL(ret)) {
    first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
    STORAGE_LOG(WARN, "set first_error_code_", K(ret), K(first_error_code_));
  }
  int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  is_all_finish = true;
  LOG_INFO("fast migrate: finish change member list in turn",
      K(ret),
      K(cost_ts),
      "task_count",
      report_list.count(),
      K(succ_count));
  return ret;
}

int ObPartGroupMigrationTask::try_batch_change_member_list(
    ObIArray<ObReportPartMigrationTask>& report_list, const ObAddr& leader_addr, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  hash::ObHashSet<ObPartitionKey> removed_pkeys;
  hash::ObHashSet<ObPartitionKey> added_pkeys;
  const int64_t start_ts = ObTimeUtility::current_time();
  is_all_finish = false;

  STORAGE_LOG(INFO, "start try_batch_change_member_list");

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() <= 0) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "task list is empty", K(ret));
  } else {
    if (MIGRATE_REPLICA_OP == type_) {
      if (OB_FAIL(try_batch_remove_member(report_list, leader_addr, removed_pkeys))) {
        STORAGE_LOG(WARN, "failed to try_batch_remove_member", K(ret), K(leader_addr), K(report_list));
      }
    } else {
      ret = OB_ERR_SYS;
      LOG_WARN("only migrate or fast migrate allow batch change member list", K(ret), K(type_));
    }
  }
  if (OB_SUCC(ret)) {
    // For migartion, if no need to retry, then add the deleted partition, otherwise no need to care
    is_all_finish = true;
    if (removed_pkeys.size() > 0) {
      if (OB_SUCCESS !=
          (tmp_ret = try_batch_add_member(report_list, removed_pkeys, leader_addr, added_pkeys, is_all_finish))) {
        STORAGE_LOG(WARN,
            "failed to try batch add member",
            K(ret),
            K(tmp_ret),
            K(leader_addr),
            K(removed_pkeys),
            K(report_list));
      } else if (FAST_MIGRATE_REPLICA_OP == type_) {
        for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
          ObReportPartMigrationTask& report_task = report_list.at(i);
          if (OB_NOT_NULL(report_task.ctx_) && OB_HASH_EXIST == added_pkeys.exist_refactored(report_task.arg_.key_)) {
            report_task.ctx_->is_member_change_finished_ = true;
            LOG_INFO("fast_migrate: succ to change member list", K(report_task.arg_.key_));
          }
        }
      }
    }

    // only migrate need remove src
    if (added_pkeys.size() > 0 && FAST_MIGRATE_REPLICA_OP != type_) {
      if (OB_SUCCESS != (tmp_ret = batch_remove_src_replica(report_list))) {
        STORAGE_LOG(WARN, "failed to batch remove src replica", K(ret), K(added_pkeys));
      }
    }
  }
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  STORAGE_LOG(INFO,
      "finish try_batch_change_member_list",
      K(cost_ts),
      K(ret),
      K(is_all_finish),
      "count",
      report_list.count(),
      "removed_count",
      removed_pkeys.size(),
      "added_count",
      added_pkeys.size());

  return ret;
}

int ObPartGroupMigrationTask::try_batch_remove_member(ObIArray<ObReportPartMigrationTask>& report_list,
    const ObAddr& leader_addr, hash::ObHashSet<ObPartitionKey>& removed_pkeys)
{
  int ret = OB_SUCCESS;
  ObChangeMemberArgs args;
  ObChangeMemberArg single_arg;
  ObChangeMemberCtxs change_member_info;
  const int64_t start_ts = ObTimeUtility::current_time();

  STORAGE_LOG(INFO, "start try_batch_remove_member");
  DEBUG_SYNC(BEFORE_BATCH_REMOVE_MEMBER);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(removed_pkeys.create(report_list.count()))) {
    STORAGE_LOG(WARN, "failed to create removed_pkeys", K(ret));
  } else if (OB_FAIL(args.reserve(report_list.count()))) {
    STORAGE_LOG(WARN, "failed to reserve change member ctx", K(ret), K(report_list.count()));
  } else {
    ObIPartitionServiceRpc& rpc = partition_service_->get_pts_rpc();
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      single_arg.partition_key_ = report_list.at(i).arg_.key_;
      single_arg.member_ = report_list.at(i).arg_.src_;
      single_arg.quorum_ = report_list.at(i).arg_.quorum_;
      single_arg.switch_epoch_ = report_list.at(0).arg_.switch_epoch_;
      if (OB_FAIL(args.push_back(single_arg))) {
        STORAGE_LOG(WARN, "failed to add single ctx", K(ret), K(single_arg));
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(rpc.batch_post_remove_replica_mc_msg(leader_addr, args, change_member_info))) {
        STORAGE_LOG(
            WARN, "failed to batch_post_remove_replica_mc_msg", K(ret), K(leader_addr), K(args), K(change_member_info));
      }
    }

    if (OB_SUCC(ret) || OB_PARTIAL_FAILED == ret) {
      ret = OB_SUCCESS;  // ovewrwrite retry
      if (OB_FAIL(wait_batch_member_change_done(leader_addr, change_member_info))) {
        STORAGE_LOG(
            WARN, "failed to wait_change_member_done for remove", K(ret), K(leader_addr), K(change_member_info));
      }

      if (OB_SUCC(ret) || OB_PARTIAL_FAILED == ret) {
        ret = OB_SUCCESS;  // overwrite ret
        if (change_member_info.count() != report_list.count()) {
          ret = OB_ERR_SYS;
          STORAGE_LOG(ERROR,
              "change_member_info count not match report_list count",
              K(ret),
              K(change_member_info.count()),
              K(report_list.count()),
              K(change_member_info),
              K(report_list));
        } else {
          for (int64_t i = 0; OB_SUCC(ret) && i < change_member_info.count(); ++i) {
            const ObChangeMemberCtx& ret_ctx = change_member_info.at(i);
            if (OB_SUCCESS != ret_ctx.ret_value_) {
              STORAGE_LOG(WARN, "skip add removed pkey", K(ret_ctx));
              if (OB_FAIL(set_report_list_result(report_list, ret_ctx.partition_key_, ret_ctx.ret_value_))) {
                STORAGE_LOG(WARN, "failed to set report list result", K(ret));
              }
            } else {
              if (OB_FAIL(removed_pkeys.set_refactored(ret_ctx.partition_key_))) {
                removed_pkeys.reuse();
                STORAGE_LOG(WARN, "failed to set removed_pkeys", K(ret));
              }
            }
          }
        }
      }

      if (OB_FAIL(ret)) {
        first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
        STORAGE_LOG(WARN, "set first_error_code_", K(ret), K(first_error_code_));
        ret = OB_SUCCESS;  // overwrite ret
      }
    }
  }
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  ObTaskController::get().allow_next_syslog();
  STORAGE_LOG(
      INFO, "finish try_batch_remove_member", K(cost_ts), K(ret), K(first_error_code_), "count", report_list.count());
  return ret;
}

int ObPartGroupMigrationTask::try_batch_add_member(ObIArray<ObReportPartMigrationTask>& report_list,
    const hash::ObHashSet<ObPartitionKey>& removed_pkeys, const ObAddr& leader_addr,
    hash::ObHashSet<ObPartitionKey>& added_keys, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
#ifdef ERRSIM
  UNUSEDx(report_list, removed_pkeys, leader_addr, added_keys, is_all_finish);
  ret = E(EventTable::EN_FAST_MIGRATE_ADD_MEMBER_FAIL) OB_SUCCESS;
  if (OB_FAIL(ret)) {
    LOG_INFO("errsim add member failure", K(ret));
    return ret;
  }
#endif
  ObChangeMemberArgs args;
  ObChangeMemberCtxs add_member_info;
  const int64_t start_ts = ObTimeUtility::current_time();
  STORAGE_LOG(INFO, "start try_batch_add_member");
  DEBUG_SYNC(BEFORE_BATCH_ADD_MEMBER);
  // is_all_finish is not initialized here. It may have been assigned true outside

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(added_keys.create(removed_pkeys.size()))) {
    STORAGE_LOG(WARN, "failed to create added_keys", K(ret));
  } else if (OB_FAIL(build_add_member_ctx(report_list, removed_pkeys, args))) {
    STORAGE_LOG(WARN, "failed to build_add_member_ctx", K(ret), K(removed_pkeys), K(report_list));
  } else {
    ObIPartitionServiceRpc& rpc = partition_service_->get_pts_rpc();

    if (OB_SUCC(ret)) {
      if (OB_FAIL(rpc.batch_post_add_replica_mc_msg(leader_addr, args, add_member_info))) {
        STORAGE_LOG(
            WARN, "failed to batch_post_add_replica_mc_msg", K(ret), K(leader_addr), K(args), K(add_member_info));
      }
    }

    if (OB_SUCC(ret) || OB_PARTIAL_FAILED == ret) {
      is_all_finish = true;
      ret = OB_SUCCESS;  // overwrite ret
      if (OB_FAIL(wait_batch_member_change_done(leader_addr, add_member_info))) {
        STORAGE_LOG(WARN, "failed to wait_change_member_done for add", K(ret), K(leader_addr), K(add_member_info));
      }

      if (OB_SUCC(ret) || OB_PARTIAL_FAILED == ret) {
        ret = OB_SUCCESS;  // overwrite ret
        if (add_member_info.count() != removed_pkeys.size()) {
          ret = OB_ERR_SYS;
          STORAGE_LOG(ERROR,
              "removed_pkeys count not match add_member_info count",
              K(ret),
              K(removed_pkeys.size()),
              K(add_member_info.count()),
              K(removed_pkeys),
              K(add_member_info));
        } else {
          for (int64_t i = 0; OB_SUCC(ret) && i < add_member_info.count(); ++i) {
            const ObChangeMemberCtx& ret_ctx = add_member_info.at(i);
            if (OB_SUCCESS != ret_ctx.ret_value_) {
              STORAGE_LOG(WARN, "skip add added pkey", K(ret_ctx));
              if (OB_FAIL(set_report_list_result(report_list, ret_ctx.partition_key_, ret_ctx.ret_value_))) {
                STORAGE_LOG(WARN, "failed to set report list result", K(ret));
              }
            } else if (OB_FAIL(added_keys.set_refactored(add_member_info.at(i).partition_key_))) {
              STORAGE_LOG(WARN, "failed to set added keys", K(ret));
              added_keys.reuse();
            }
          }
        }
      }
    }
  }
  if (OB_FAIL(ret) && is_all_finish) {
    first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
    STORAGE_LOG(WARN, "set first_error_code_", K(ret), K(first_error_code_));
  }
  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  ObTaskController::get().allow_next_syslog();
  STORAGE_LOG(INFO,
      "finish try_batch_add_member",
      K(cost_ts),
      K(ret),
      K(first_error_code_),
      K(is_all_finish),
      "count",
      removed_pkeys.size());
  return ret;
}

int ObPartGroupMigrationTask::try_batch_add_member(
    ObIArray<ObReportPartMigrationTask>& report_list, const ObAddr& leader_addr, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
  hash::ObHashSet<ObPartitionKey> removed_pkeys;
  hash::ObHashSet<ObPartitionKey> added_keys;
  const int64_t start_ts = ObTimeUtility::current_time();

  is_all_finish = false;
  STORAGE_LOG(INFO, "start try_batch_add_member");
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() <= 0) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "task list is empty", K(ret));
  } else if (CHANGE_REPLICA_OP != type_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("only migrate or change replica allow batch change member list", K(ret), K(type_));
  } else if (OB_FAIL(removed_pkeys.create(report_list.count()))) {
    STORAGE_LOG(WARN, "failed to create removed_pkeys", K(ret));
  } else {
    // chang replica also needs to set removed_pkeys. The logic behind it is than only pkeys than have been successfully
    // removed will be added
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      if (OB_FAIL(removed_pkeys.set_refactored(report_list.at(i).arg_.key_))) {
        LOG_WARN("failed to add change replica pkey", K(ret));
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_FAIL(try_batch_add_member(report_list, removed_pkeys, leader_addr, added_keys, is_all_finish))) {
      LOG_WARN("failed to try_batch_add_member", K(ret));
    } else if (CHANGE_REPLICA_OP == type_) {
      for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
        ObReportPartMigrationTask& report_task = report_list.at(i);
        if (OB_NOT_NULL(report_task.ctx_) && OB_HASH_EXIST == added_keys.exist_refactored(report_task.arg_.key_)) {
          report_task.ctx_->is_member_change_finished_ = true;
          LOG_INFO("change replica: succ to add member list", K(report_task.arg_.key_));
        }
      }
    }
  }

  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  STORAGE_LOG(INFO,
      "finish try_batch_add_member",
      K(cost_ts),
      K(ret),
      K(is_all_finish),
      "count",
      report_list.count(),
      "added_count",
      added_keys.size());
  return ret;
}

int ObPartGroupMigrationTask::build_add_member_ctx(const ObIArray<ObReportPartMigrationTask>& report_list,
    const hash::ObHashSet<ObPartitionKey>& removed_pkeys, ObChangeMemberArgs& ctx)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObChangeMemberArg single_ctx;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(ctx.reserve(removed_pkeys.size()))) {
    STORAGE_LOG(WARN, "failed to reserve change member ctx", K(ret), K(removed_pkeys.size()));
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
    const ObReplicaOpArg& arg = report_list.at(i).arg_;
    if (OB_HASH_EXIST == (tmp_ret = removed_pkeys.exist_refactored(arg.key_))) {
      single_ctx.partition_key_ = arg.key_;
      single_ctx.member_ = arg.dst_;
      single_ctx.quorum_ = arg.quorum_;
      single_ctx.switch_epoch_ = report_list.at(0).arg_.switch_epoch_;
      if (OB_FAIL(ctx.push_back(single_ctx))) {
        STORAGE_LOG(WARN, "failed to add single ctx", K(ret), K(single_ctx));
      }
    } else if (OB_HASH_NOT_EXIST != tmp_ret) {
      ret = tmp_ret;
      STORAGE_LOG(WARN, "failed to check removed pkey exist", K(ret));
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::remove_src_replica(const ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  share::ObTaskId dummy_id;
  dummy_id.init(OBSERVER.get_self());

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
    const ObReplicaOpArg& arg = report_list.at(i).arg_;
    if (OB_SUCCESS != report_list.at(i).result_) {
      STORAGE_LOG(INFO, "skip remove failed partition", K(report_list.at(i)));
    } else {
      obrpc::ObRemoveReplicaArg remove_replica_arg = {arg.key_, arg.src_};
      if (OB_SUCCESS != (tmp_ret = partition_service_->get_pts_rpc().post_remove_replica(
                             arg.src_.get_server(), remove_replica_arg))) {
        STORAGE_LOG(WARN, "remove replica from source observer failed", K(tmp_ret), K(remove_replica_arg));
      } else {
        STORAGE_LOG(INFO, "remove source replica successfully", K(arg.src_), K(remove_replica_arg));
      }
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::batch_remove_src_replica(const ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  share::ObTaskId dummy_id;
  dummy_id.init(OBSERVER.get_self());
  ObArenaAllocator allocator;
  typedef hash::ObHashMap<ObAddr, obrpc::ObRemoveReplicaArgs*, common::hash::NoPthreadDefendMode> JoinMap;
  JoinMap join_map;  // Map aggregated by serve
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(join_map.create(report_list.count(), ObModIds::OB_PARTITION_MIGRATOR))) {
    STORAGE_LOG(WARN, "failed to create hash table for join", K(ret));
  } else {
    obrpc::ObRemoveReplicaArgs* remove_replica_args = NULL;
    void* buf = NULL;
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      const ObReplicaOpArg& arg = report_list.at(i).arg_;
      buf = NULL;
      remove_replica_args = NULL;
      if (OB_SUCCESS != report_list.at(i).result_) {
        STORAGE_LOG(INFO, "skip remove failed partition", "pkey", arg.key_);
      } else {
        if (OB_FAIL(join_map.get_refactored(arg.src_.get_server(), remove_replica_args))) {
          if (OB_HASH_NOT_EXIST != ret) {
            STORAGE_LOG(WARN, "failed to get remove replica args from map", K(ret));
          } else if (NULL == (buf = allocator.alloc(sizeof(obrpc::ObRemoveReplicaArgs)))) {
            ret = OB_ALLOCATE_MEMORY_FAILED;
            STORAGE_LOG(WARN, "failed to alloc buf", K(ret));
          } else if (NULL == (remove_replica_args = new (buf) obrpc::ObRemoveReplicaArgs())) {
            ret = OB_ALLOCATE_MEMORY_FAILED;
            STORAGE_LOG(WARN, "failed to new remove replica args");
          } else if (OB_FAIL(join_map.set_refactored(arg.src_.get_server(), remove_replica_args))) {
            STORAGE_LOG(WARN, "failed to set join map", K(ret));
          }
        }

        if (OB_SUCC(ret)) {
          obrpc::ObRemoveReplicaArg remove_replica_arg = {arg.key_, arg.src_};
          if (OB_FAIL(remove_replica_args->arg_array_.push_back(remove_replica_arg))) {
            STORAGE_LOG(WARN, "failed to push remove replica arg into array", K(ret));
          }
        }
      }
    }

    if (OB_SUCC(ret)) {
      for (JoinMap::iterator iter = join_map.begin(); iter != join_map.end(); ++iter) {
        const ObAddr server = iter->first;
        remove_replica_args = iter->second;
        if (OB_SUCCESS !=
            (tmp_ret = partition_service_->get_pts_rpc().batch_post_remove_replica(server, *remove_replica_args))) {
          STORAGE_LOG(WARN, "remove replica from source observer failed", K(tmp_ret), K(*remove_replica_args));
        } else {
          STORAGE_LOG(INFO, "remove source replica successfully", K(*remove_replica_args));
        }
      }
    }
    // demonstrate destruct remove_replica_args
    for (JoinMap::iterator iter = join_map.begin(); iter != join_map.end(); ++iter) {
      remove_replica_args = iter->second;
      if (NULL != remove_replica_args) {
        remove_replica_args->~ObRemoveReplicaArgs();
      }
    }
    join_map.clear();
  }
  return ret;
}

int ObPartGroupMigrationTask::check_member_major_sstable_enough(ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else if (OB_UNLIKELY(report_list.count() <= 0)) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arguments", K(ret), K(report_list.count()));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      if (ObReplicaTypeCheck::is_replica_with_ssstore(report_list.at(i).arg_.dst_.get_replica_type()) &&
          (ADD_REPLICA_OP == report_list.at(i).arg_.type_ ||
              MIGRATE_REPLICA_OP == report_list.at(i).arg_.type_
              //          || CHANGE_REPLICA_OP == report_list.at(i).arg_.type_ // TODO(): open it after add batch check
              || REBUILD_REPLICA_OP == report_list.at(i).arg_.type_)) {

        if (OB_FAIL(check_member_pg_major_sstable_enough(report_list.at(i)))) {
          STORAGE_LOG(WARN, "fail to check member pg major sstable enough", K(ret));
        }
      }
    }
  }
  if (OB_FAIL(ret)) {
    if (OB_MAJOR_SSTABLE_NOT_EXIST == ret || OB_NOT_SUPPORTED == ret) {
      first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
      STORAGE_LOG(WARN, "set first_error_code_", K(ret), K(first_error_code_), K(report_list));
    } else {
      const int64_t now = ObTimeUtility::current_time();
      if (now > retry_job_start_ts_ + RETRY_JOB_MAX_WAIT_TIMEOUT) {
        ret = OB_TIMEOUT;
        first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
        STORAGE_LOG(WARN, "set first_error_code_", K(ret), K(first_error_code_), K(report_list));
      } else {
        STORAGE_LOG(WARN, "fail to check member major sstable enough, retry it", K(ret));
      }
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::check_member_pg_major_sstable_enough(ObReportPartMigrationTask& task)
{
  int ret = OB_SUCCESS;
  ObMigrateSrcInfo leader_info;
  ObIPartitionGroupGuard guard;
  ObIPartitionGroup* partition = NULL;
  ObPGStorage* pg_storage = NULL;
  ObTablesHandle tables_handle;
  ObArray<uint64_t> table_ids;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else if (ObReplicaTypeCheck::is_replica_with_ssstore(task.arg_.dst_.get_replica_type()) &&
             (ADD_REPLICA_OP != task.arg_.type_ &&
                 MIGRATE_REPLICA_OP != task.arg_.type_
                 //          || CHANGE_REPLICA_OP != task.arg_.arg_.type_ // TODO(): open it after add batch check
                 && REBUILD_REPLICA_OP != task.arg_.type_)) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "failed to check member pg major sstable enough", K(ret), K(task));
  } else if (OB_FAIL(ObMigrateGetLeaderUtil::get_leader(task.arg_.key_, leader_info, true /*force_update*/))) {
    STORAGE_LOG(WARN, "failed to get leader address", K(ret), K(task.arg_.key_));
  } else if (OB_FAIL(partition_service_->get_partition(task.arg_.key_, guard))) {
    STORAGE_LOG(WARN, "failed to get partition group", K(ret), K(task.arg_));
  } else if (OB_ISNULL(partition = guard.get_partition_group())) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "partition group should not be NULL", K(ret), KP(partition));
  } else if (OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "pg_storage should not be NULL", K(ret), KP(pg_storage));
  } else if (OB_FAIL(pg_storage->get_last_all_major_sstable(tables_handle))) {
    STORAGE_LOG(WARN, "failed to get last all major sstable", K(ret), K(task));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < tables_handle.get_count(); ++i) {
      ObITable* table = tables_handle.get_tables().at(i);
      if (OB_ISNULL(table)) {
        ret = OB_ERR_SYS;
        STORAGE_LOG(WARN, "error sys, table must not be NULL", K(ret));
      } else if (OB_FAIL(table_ids.push_back(table->get_key().table_id_))) {
        STORAGE_LOG(WARN, "failed to push table id into array", K(ret));
      }
    }

    if (OB_SUCC(ret)) {
      obrpc::ObMemberMajorSSTableCheckArg arg;
      arg.pkey_ = task.arg_.key_;
      if (OB_FAIL(arg.table_ids_.assign(table_ids))) {
        STORAGE_LOG(WARN, "fail to assign table ids", K(ret));
      } else if (OB_FAIL(partition_service_->get_pts_rpc().check_member_pg_major_sstable_enough(
                     leader_info.src_addr_, arg))) {
        STORAGE_LOG(WARN, "fail to check member pg major sstable enough", K(ret), K(arg));
        if (OB_NOT_SUPPORTED == ret) {
          if (REBUILD_REPLICA_OP == task.arg_.type_) {

            // not supported may rpc send to old server, for compat
            STORAGE_LOG(WARN, "result is not supported, may src server not support the rpc", K(ret));
            ret = OB_SUCCESS;
          } else if (OB_FAIL(partition_service_->get_pts_rpc().check_member_major_sstable_enough(
                         leader_info.src_addr_, arg))) {
            STORAGE_LOG(WARN, "fail to check member major sstable enough", K(ret), K(leader_info));
          }
        }
      }
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::report_meta_table(
    const ObIArray<ObReportPartMigrationTask>& report_list, const hash::ObHashSet<ObPartitionKey>& member_removed_pkeys)
{
  int ret = OB_SUCCESS;
  const int64_t ONE_ROUND_WAIT_TIMEOUT = 60 * 1000 * 1000;  // 1m
  const int64_t RETRY_INTERVAL = 100 * 1000;                // 100ms
  const int64_t start_ts = ObTimeUtility::current_time();
  ObArray<bool> check_result;
  FLOG_INFO("start report meta table", K(report_list));

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else if (OB_UNLIKELY(report_list.count() <= 0)) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arguments", K(ret), K(report_list.count()));
  } else if (OB_FAIL(check_result.reserve(report_list.count()))) {
    STORAGE_LOG(WARN, "fail to reserve check result", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      const ObReportPartMigrationTask& report_task = report_list.at(i);
      if (OB_FAIL(partition_service_->handle_report_meta_table_callback(
              report_task.arg_.key_, report_task.result_, report_task.need_report_checksum_))) {
        STORAGE_LOG(WARN, "fail to report meta table", K(ret));
      }
    }
    if (OB_SUCC(ret) && !has_error()) {
      for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
        const ObReportPartMigrationTask& report_task = report_list.at(i);
        bool need_check = ObReplicaTypeCheck::is_replica_with_ssstore(report_task.arg_.dst_.get_replica_type());
        if (FAST_MIGRATE_REPLICA_OP == type_) {
          int exist_ret = member_removed_pkeys.exist_refactored(report_list.at(i).arg_.key_);
          if (OB_HASH_EXIST != exist_ret && OB_HASH_NOT_EXIST != exist_ret) {
            ret = exist_ret;
            LOG_WARN("check is partition member list removed fail", K(ret), K(i), "report_task", report_list.at(i));
          } else if (OB_HASH_NOT_EXIST == exist_ret) {
            need_check = false;
          }
        }
        if (OB_FAIL(ret)) {
        } else if (OB_FAIL(check_result.push_back(!need_check))) {
          STORAGE_LOG(WARN, "fail to push back check result", K(ret));
        }
      }
    }
    // If the previous migration fails, there is no need to wait
    while (OB_SUCC(ret) && !has_error()) {
      if (OB_FAIL(check_report_done(report_list, check_result))) {
        STORAGE_LOG(WARN, "fail to check report done", K(ret));
      } else {
        bool is_all_done = true;
        for (int64_t i = 0; OB_SUCC(ret) && i < check_result.count() && is_all_done; ++i) {
          is_all_done = check_result.at(i);
        }
        if (is_all_done) {
          break;
        } else {
          const int64_t now = ObTimeUtility::current_time();
          if (now > retry_job_start_ts_ + RETRY_JOB_MAX_WAIT_TIMEOUT) {
            ret = OB_TIMEOUT;
            first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
            STORAGE_LOG(WARN, "wait report meta table done timeout, migration failed", K(ret));
          } else if (now > start_ts + ONE_ROUND_WAIT_TIMEOUT) {
            ret = OB_TIMEOUT;
            STORAGE_LOG(WARN, "wait report meta table done timeout, retry later", K(ret));
          } else {
            usleep(RETRY_INTERVAL);
          }
        }
      }
    }
  }
  const int64_t end_ts = ObTimeUtility::current_time();
  FLOG_INFO("wait report meta table done", "cost_ts", end_ts - start_ts, K(ret));
  return ret;
}

int ObPartGroupMigrationTask::check_report_done(
    const ObIArray<ObReportPartMigrationTask>& report_list, ObIArray<bool>& result)
{
  int ret = OB_SUCCESS;
  share::ObPartitionTableOperator* pt_operator = NULL;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else if (report_list.count() <= 0 || (report_list.count() != result.count())) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arguments", K(ret), K(report_list.count()), K(result.count()));
  } else if (OB_ISNULL(pt_operator = GCTX.pt_operator_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "error unexpected, pt operator must not be NULL", K(ret));
  } else {
    share::ObPartitionInfo partition_info;
    share::ObReplicaStatus replica_status;
    ObArenaAllocator allocator(ObModIds::OB_PARTITION_MIGRATOR);
    partition_info.set_allocator(&allocator);
    for (int64_t i = 0; OB_SUCC(ret) && i < result.count(); ++i) {
      const ObPartitionReplica* replica = NULL;
      partition_info.reuse();
      if (OB_FAIL(partition_service_->get_replica_status(report_list.at(i).arg_.key_, replica_status))) {
        STORAGE_LOG(WARN, "fail to get replica status", K(ret));
      } else if (REPLICA_STATUS_NORMAL != replica_status) {
        ret = OB_STATE_NOT_MATCH;
        first_error_code_ = OB_SUCCESS == first_error_code_ ? ret : first_error_code_;
        STORAGE_LOG(
            WARN, "partition status not match, migration failed", K(report_list.at(i).arg_.key_), K(replica_status));
      } else if (!result.at(i)) {
        if (OB_FAIL(pt_operator->get(report_list.at(i).arg_.key_.get_table_id(),
                report_list.at(i).arg_.key_.get_partition_id(),
                partition_info))) {
          STORAGE_LOG(WARN, "fail to get partition info.", K(ret), "pkey", report_list.at(i).arg_.key_);
        } else if (OB_FAIL(partition_info.find(GCTX.self_addr_, replica))) {
          if (OB_ENTRY_NOT_EXIST != ret) {
            STORAGE_LOG(WARN, "fail to find replica", K(ret), K(GCTX.self_addr_));
          } else {
            ret = OB_SUCCESS;
          }
        } else if (OB_ISNULL(replica)) {
          ret = OB_ERR_UNEXPECTED;
          STORAGE_LOG(WARN, "replica must not be NULL", K(ret));
        } else {
          result.at(i) = REPLICA_STATUS_NORMAL == replica->status_;
        }
      }
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::wait_batch_member_change_done(
    const ObAddr& leader_addr, ObChangeMemberCtxs& change_member_info)
{
  int ret = OB_SUCCESS;
  int64_t max_wait_batch_member_change_done_us = 300 * 1000 * 1000;  // 5m
  const int64_t start_ts = ObTimeUtility::current_time();

#ifdef ERRSIM
  int64_t tmp = GCONF.max_wait_batch_member_change_done_us;
  if (tmp != max_wait_batch_member_change_done_us) {
    max_wait_batch_member_change_done_us = tmp;
    STORAGE_LOG(INFO, "fake max_wait_batch_member_change_done_us", K(max_wait_batch_member_change_done_us));
  }
#endif
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    while (OB_SUCC(ret)) {
      const int64_t now = ObTimeUtility::current_time();
      if (now > start_ts + max_wait_batch_member_change_done_us) {
        ret = OB_TIMEOUT;
        STORAGE_LOG(WARN, "wait batch member change done retry timeout", K(ret));
        break;
      } else if (OB_FAIL(
                     partition_service_->get_pts_rpc().is_batch_member_change_done(leader_addr, change_member_info))) {
        if (OB_PARTIAL_FAILED != ret) {
          STORAGE_LOG(WARN, "failed to is_batch_member_change_done", K(ret), K(leader_addr), K(change_member_info));
        } else {
          STORAGE_LOG(INFO, "failed to is_batch_member_change_done", K(ret), K(leader_addr), K(change_member_info));
        }
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < change_member_info.count(); ++i) {
          if (OB_SUCCESS != change_member_info.at(i).ret_value_) {
            ret = OB_ERR_SYS;
            STORAGE_LOG(ERROR,
                "is_batch_member_change_done return OB_SUCCESS, butn has failed sub part",
                K(ret),
                K(i),
                K(change_member_info.at(i)));
          }
        }
        break;
      }

      if (OB_PARTIAL_FAILED == ret) {
        for (int64_t i = 0; i < change_member_info.count(); ++i) {
          if (OB_EAGAIN == change_member_info.at(i).ret_value_) {
            STORAGE_LOG(
                INFO, "some partition change member is not finish, need retry", K(i), K(change_member_info.at(i)));
            ret = OB_SUCCESS;
            break;
          }
        }
      } else if (OB_TIMEOUT == ret) {
        STORAGE_LOG(INFO, "send is_batch_member_change_done fail, need retry", K(ret));
        ret = OB_SUCCESS;
      }

      if (OB_SUCC(ret)) {
        usleep(100 * 1000);  // 100ms
      }
    }
  }

  const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
  LOG_INFO("finish wait_batch_member_change_done", K(ret), K(cost_ts));
  return ret;
}

int ObPartGroupMigrationTask::try_not_batch_change_member_list(
    ObIArray<ObReportPartMigrationTask>& report_list, bool& is_all_finish)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  bool could_retry = false;
  SMART_VAR(ObPartMigrationTask, tmp_task)
  {
    const int64_t start_ts = ObTimeUtility::current_time();
    is_all_finish = false;

    if (!is_inited_) {
      ret = OB_NOT_INIT;
      STORAGE_LOG(WARN, "not inited", K(ret));
    } else if (report_list.count() <= 0) {
      ret = OB_ERR_SYS;
      STORAGE_LOG(ERROR, "task list is empty", K(ret));
    } else {
      ObReportPartMigrationTask& first_task = report_list.at(0);

      if (OB_SUCCESS != (tmp_ret = partition_service_->handle_member_change_callback(
                             first_task.arg_, first_task.result_, could_retry))) {
        if (MIGRATE_REPLICA_OP == type_ && could_retry && need_retry_change_member_list(tmp_ret)) {
          STORAGE_LOG(WARN, "failed to handle_replica_callback, retry later", K(tmp_ret), K(first_task));
        } else {
          is_all_finish = true;
          STORAGE_LOG(WARN,
              "failed to handle_replica_callback, failed all sub tasks",
              K(tmp_ret),
              K(could_retry),
              K(first_task));
          if (OB_FAIL(build_failed_report_list(tmp_ret, report_list))) {
            STORAGE_LOG(WARN, "failed to build failed report list", K(ret));
          }
        }
      } else {
        first_task.ctx_->is_member_change_finished_ = true;
        is_all_finish = true;

        for (int64_t i = 1; OB_SUCC(ret) && i < report_list.count(); ++i) {
          ObReportPartMigrationTask& sub_task = report_list.at(i);
          if (OB_SUCCESS != (tmp_ret = partition_service_->handle_member_change_callback(
                                 sub_task.arg_, sub_task.result_, could_retry))) {
            sub_task.result_ = tmp_ret;
            STORAGE_LOG(WARN, "failed to handle_replica_callback,", K(tmp_ret), K(sub_task));
          } else {
            sub_task.ctx_->is_member_change_finished_ = true;
          }
        }
      }

      const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
      STORAGE_LOG(INFO,
          "finish try_not_batch_change_member_list",
          "count",
          report_list.count(),
          K(start_ts),
          K(cost_ts),
          "avg_cost",
          cost_ts / report_list.count());
    }
  }
  return ret;
}

bool ObPartGroupMigrationTask::need_retry_change_member_list(const int32_t result_code)
{
  bool need_retry = false;
  const int64_t change_member_list_timeout = GCONF.sys_bkgd_migration_change_member_list_timeout;
  const int64_t now = ObTimeUtility::current_time();
  int64_t large_migration_need_retry_cost_time = LARGE_MIGRATION_NEED_RETRY_COST_TIME;

#ifdef ERRSIM
  large_migration_need_retry_cost_time = GCONF.sys_bkgd_migration_large_task_threshold;
  STORAGE_LOG(INFO, "use GCONF.sys_bkgd_migration_large_task_threshold", K(large_migration_need_retry_cost_time));
#endif

  if (!is_inited_) {
    STORAGE_LOG(ERROR, "not inited");
  } else {
    // Retrial condition
    // 1. It tasks more than 2 hours to copy data
    // 2. The default retry times has not been exceeded
    // 3. Match specific error code
    need_retry = true;
    if (change_member_list_timeout <= 0) {
      need_retry = false;
      STORAGE_LOG(INFO, "change member list time out is 0, no need retry", K(change_member_list_timeout));
    } else if (start_change_member_ts_ - schedule_ts_ < large_migration_need_retry_cost_time) {
      need_retry = false;
      STORAGE_LOG(INFO,
          "no large migration, no need retry",
          K(schedule_ts_),
          K(start_change_member_ts_),
          K(large_migration_need_retry_cost_time));
    } else if (now > start_change_member_ts_ + change_member_list_timeout) {
      need_retry = false;
      STORAGE_LOG(INFO,
          "retry timeout expired, no need retry",
          K(now),
          K(start_change_member_ts_),
          K(change_member_list_timeout));
    } else if (result_code != OB_STATE_NOT_MATCH && result_code != OB_LOG_NOT_SYNC) {
      need_retry = false;
      STORAGE_LOG(INFO, "no need retry for these error", K(result_code));
    }
  }
  return need_retry;
}

int ObPartGroupMigrationTask::inner_schedule_partition(ObPartMigrationTask*& task, bool& need_schedule)
{
  int ret = OB_SUCCESS;
  need_schedule = false;
  task = NULL;
  common::SpinRLockGuard guard(lock_);
  for (int64_t i = 0; OB_SUCC(ret) && i < task_list_.count(); ++i) {
    task = &task_list_[i];
    bool as_data_source = false;
    if (type_ != task->arg_.type_ || !is_replica_op_valid(task->arg_.type_)) {
      ret = OB_ERR_SYS;
      STORAGE_LOG(ERROR, "invalid type, cannot handle this task", K(ret), K(i), K(*task));
    } else if (REMOVE_REPLICA_OP == type_) {
      // do nothing
    } else if (OB_FAIL(check_can_as_data_source(type_,
                   task->arg_.data_src_.get_replica_type(),
                   task->arg_.dst_.get_replica_type(),
                   as_data_source))) {
      STORAGE_LOG(WARN, "fail to check can as data source", K(ret), K(task->arg_));
    } else if (!as_data_source) {
      ret = OB_NOT_SUPPORTED;
      first_error_code_ = ret;
      LOG_ERROR("invalid data src", K(ret), K(task->arg_));
    } else if (ObPartMigrationTask::INIT == task->status_) {
      if (OB_FAIL(build_migrate_ctx(task->arg_, task->ctx_))) {
        STORAGE_LOG(WARN, "fail to build migrate ctx", K(ret));
      } else {
        need_schedule = true;
        break;
      }
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::try_schedule_partition_migration()
{
  int ret = OB_SUCCESS;
  bool need_schedule = true;
  ObPartMigrationTask* task = NULL;
  const int64_t data_copy_in_concurrency = GCONF.server_data_copy_in_concurrency;

  while (OB_SUCC(ret) && need_schedule &&
         ObDagScheduler::get_instance().get_dag_count(ObIDag::DAG_TYPE_MIGRATE) < data_copy_in_concurrency) {
    if (OB_FAIL(inner_schedule_partition(task, need_schedule))) {
      STORAGE_LOG(WARN, "failed to inner schedule partition", K(ret));
    } else if (!need_schedule) {
      // do nothing
    } else if (OB_ISNULL(task)) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "task need schedule but is NULL", K(ret), KP(task));
    } else if (OB_FAIL(schedule_migrate_dag(task->ctx_))) {
      STORAGE_LOG(WARN, "failed to schedule migrate dag", K(ret), K(task->arg_));
    }
  }
  return ret;
}

int ObPartGroupMigrationTask::try_schedule_partition_validate()
{
  int ret = OB_SUCCESS;
  bool need_schedule = true;
  ObPartMigrationTask* task = NULL;
  int64_t data_validate_concurrency = GCONF.backup_concurrency;
  int32_t up_limit = 0;
  if (OB_FAIL(ObDagScheduler::get_instance().get_up_limit(ObIDag::DAG_ULT_BACKUP, up_limit))) {
    STORAGE_LOG(WARN, "failed to get up limit", K(ret));
  } else {
    data_validate_concurrency = data_validate_concurrency == 0 ? up_limit : data_validate_concurrency;
    FLOG_INFO("validate concurrency", K(data_validate_concurrency), K(up_limit));
  }

  while (OB_SUCC(ret) && need_schedule &&
         ObDagScheduler::get_instance().get_dag_count(ObIDag::DAG_TYPE_VALIDATE) < data_validate_concurrency) {
    if (OB_FAIL(inner_schedule_partition(task, need_schedule))) {
      STORAGE_LOG(WARN, "failed to inner schedule partiion", K(ret));
    } else if (!need_schedule) {
      // do nothing
    } else if (OB_ISNULL(task)) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "task need schedule but is NULL", K(ret), KP(task));
    } else if (OB_FAIL(schedule_migrate_dag(task->ctx_))) {
      STORAGE_LOG(WARN, "failed to schedule migrate dag", K(ret), K(task->arg_));
    }
  }
  return ret;
}

int ObGroupMigrateDag::report_result(const bool is_batch_mode, const ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!is_batch_mode) {
    if (OB_FAIL(single_report_result(report_list))) {
      STORAGE_LOG(WARN, "failed to single_report_result", K(ret));
    }
  } else {
    if (OB_FAIL(batch_report_result(report_list))) {
      STORAGE_LOG(WARN, "failed to batch_report_result", K(ret));
    }
  }
  return ret;
}

int ObGroupMigrateDag::single_report_result(const ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() != 1) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "cannot single report result more than 1", K(ret), K(report_list));
  } else {
    const ObReportPartMigrationTask& task = report_list.at(0);
    if (OB_FAIL(partition_service_->retry_post_operate_replica_res(task.arg_, task.result_))) {
      STORAGE_LOG(WARN, "failed to retry_post_operate_replica_res", K(ret), K(task));
    }
  }
  return ret;
}

int ObGroupMigrateDag::batch_report_result(const ObIArray<ObReportPartMigrationTask>& report_list)
{
  int ret = OB_SUCCESS;
  ObArray<ObPartMigrationRes> report_res_list;
  ObPartMigrationRes tmp_res;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (report_list.count() <= 0) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "report list must not empty", K(ret));
  } else if (OB_FAIL(report_res_list.reserve(report_list.count()))) {
    STORAGE_LOG(WARN, "failed to reserve report_res_list", K(ret), K(report_list));
  } else {
    ObReplicaOpType type = report_list.at(0).arg_.type_;
    for (int64_t i = 0; OB_SUCC(ret) && i < report_list.count(); ++i) {
      const ObReplicaOpArg& arg = report_list.at(i).arg_;
      if (type != arg.type_) {
        ret = OB_INVALID_ARGUMENT;
        STORAGE_LOG(ERROR, "op type not same", K(ret), K(type), K(i), K(arg), K(report_list));
      } else {
        tmp_res.key_ = arg.key_;
        tmp_res.src_ = arg.src_;
        tmp_res.dst_ = arg.dst_;
        tmp_res.data_src_ = arg.data_src_;
        tmp_res.quorum_ = arg.quorum_;
        tmp_res.backup_arg_ = arg.backup_arg_;
        tmp_res.validate_arg_ = arg.validate_arg_;
        tmp_res.data_statics_ = report_list.at(i).data_statics_;
        tmp_res.result_ = report_list.at(i).result_;
        if (OB_FAIL(report_res_list.push_back(tmp_res))) {
          STORAGE_LOG(WARN, "failed to add report res list", K(ret));
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(partition_service_->retry_post_batch_migrate_replica_res(type, report_res_list))) {
        STORAGE_LOG(WARN, "failed to retry_post_operate_replica_res", K(ret), K(type), K(report_res_list));
      }
    }
  }

  return ret;
}

int ObPartGroupMigrationTask::get_tables_with_major_sstable(const ObPartitionKey& pkey, ObIArray<uint64_t>& table_ids)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroupGuard part_guard;
  ObIPartitionGroup* partition = NULL;
  ObPartitionStorage* storage = NULL;
  ObPGPartitionGuard pg_partition_guard;
  ObTablesHandle tables_handle;
  table_ids.reset();
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "ObPartGroupMigrationTask has not been inited", K(ret));
  } else if (!pkey.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid arguments", K(ret), K(pkey));
  } else if (OB_FAIL(ObPartitionService::get_instance().get_partition(pkey, part_guard))) {
    STORAGE_LOG(WARN, "fail to get partition", K(ret), K(pkey));
  } else if (OB_ISNULL(partition = part_guard.get_partition_group())) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "partition must not be NULL", K(ret), K(pkey));
  } else if (OB_FAIL(partition->get_pg_partition(pkey, pg_partition_guard))) {
    STORAGE_LOG(WARN, "get pg partition error", K(ret), K(pkey));
  } else if (OB_ISNULL(pg_partition_guard.get_pg_partition())) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "get pg partition error", K(ret), KP(pg_partition_guard.get_pg_partition()));
  } else if (OB_ISNULL(
                 storage = static_cast<ObPartitionStorage*>(pg_partition_guard.get_pg_partition()->get_storage()))) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "partition storage must not be NULL", K(ret));
  } else if (OB_FAIL(storage->get_partition_store().get_last_all_major_sstable(tables_handle))) {
    STORAGE_LOG(WARN, "fail to get last all major sstables", K(ret), K(pkey));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < tables_handle.get_count(); ++i) {
      ObITable* table = tables_handle.get_tables().at(i);
      if (OB_ISNULL(table)) {
        ret = OB_ERR_SYS;
        STORAGE_LOG(WARN, "error sys, table must not be NULL", K(ret));
      } else if (OB_FAIL(table_ids.push_back(table->get_key().table_id_))) {
        STORAGE_LOG(WARN, "fail to push back table id", K(ret));
      }
    }
  }
  return ret;
}

ObFastMigrateDag::ObFastMigrateDag()
    : ObIDag(ObIDagType::DAG_TYPE_MIGRATE, ObIDagPriority::DAG_PRIO_MIGRATE_MID),
      group_task_(nullptr),
      sub_type_(TaskType::INVALID)
{}

ObFastMigrateDag::~ObFastMigrateDag()
{
  group_task_ = nullptr;
}

bool ObFastMigrateDag::operator==(const ObIDag& other) const
{
  bool is_same = true;
  if (this == &other) {
    // same
  } else if (get_type() != other.get_type()) {
    is_same = false;
  } else {
    const ObFastMigrateDag& other_dag = static_cast<const ObFastMigrateDag&>(other);
    is_same = (group_task_ == other_dag.group_task_ && sub_type_ == other_dag.sub_type_);
  }
  return is_same;
}

int64_t ObFastMigrateDag::hash() const
{
  int64_t hash_value = 0;
  if (nullptr != group_task_) {
    hash_value = common::murmurhash(&group_task_, sizeof(group_task_), hash_value);
  }
  if (is_valid_task_type(sub_type_)) {
    hash_value = common::murmurhash(&sub_type_, sizeof(sub_type_), hash_value);
  }
  return hash_value;
}

int64_t ObFastMigrateDag::get_tenant_id() const
{
  int64_t tenant_id = OB_INVALID_TENANT_ID;
  if (nullptr != group_task_) {
    tenant_id = group_task_->get_tenant_id();
  }
  return tenant_id;
}

int ObFastMigrateDag::fill_comment(char* buf, const int64_t buf_len) const
{
  int ret = OB_SUCCESS;
  if (NULL == buf || buf_len <= 0) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(buf), K(buf_len));
  } else {
    const char* type_str = "UNKOWN";
    static const char* TYPE_STRING[] = {
        "INVALID",
        "SUSPEND_SRC",
        "HANDOVER_PG",
        "CLEAN_UP",
        "REPORT_META_TABLE",
    };
    STATIC_ASSERT(ARRAYSIZEOF(TYPE_STRING) == TaskType::MAX_TYPE, "TYPE_STRING count mismatch with task type count");
    if (is_valid_task_type(sub_type_)) {
      type_str = TYPE_STRING[sub_type_];
    }
    int64_t pos = 0;
    if (OB_FAIL(databuff_printf(buf, buf_len, pos, "%s", "fast migrate batch exec: "))) {
      LOG_WARN("generate comment failed", K(ret));
    } else if (OB_FAIL(databuff_print_json_kv(buf, buf_len, pos, "type", type_str))) {
      LOG_WARN("generate sub_type failed", K(ret));
    } else if (OB_FAIL(databuff_print_json_kv_comma(buf, buf_len, pos, K(group_task_)))) {
      LOG_WARN("generate group task addr failed", K(ret));
    } else if (nullptr != group_task_ &&
               OB_FAIL(databuff_print_json_kv_comma(buf, buf_len, pos, "trace_id", group_task_->get_task_id()))) {
      LOG_WARN("generate trace id failed", K(ret));
    } else if (OB_FAIL(
                   databuff_print_json_kv_comma(buf, buf_len, pos, "running_task_count", get_running_task_count()))) {
      LOG_WARN("generate group task addr failed", K(ret));
    }
  }
  return ret;
}

int64_t ObFastMigrateDag::get_compat_mode() const
{
  return static_cast<int64_t>(share::ObWorker::CompatMode::MYSQL);
}

bool ObFastMigrateDag::is_valid_task_type(TaskType type)
{
  return type > TaskType::INVALID && type < TaskType::MAX_TYPE;
}

int ObFastMigrateDag::init(ObPartGroupMigrationTask* group_task, TaskType sub_type)
{
  int ret = OB_SUCCESS;
  if (OB_NOT_NULL(group_task_)) {
    ret = OB_INIT_TWICE;
    LOG_WARN("init twice", K(ret), K(group_task_));
  } else if (OB_ISNULL(group_task) || !is_valid_task_type(sub_type)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret), KP(group_task), K(sub_type));
  } else {
    group_task_ = group_task;
    sub_type_ = sub_type;
  }
  return ret;
}

ObBaseMigrateDag::ObBaseMigrateDag(const ObIDagType type, const ObIDagPriority priority)
    : ObIDag(type, priority), is_inited_(false), ctx_(NULL), tenant_id_(0), compat_mode_()
{}

ObBaseMigrateDag::~ObBaseMigrateDag()
{}

bool ObBaseMigrateDag::operator==(const ObIDag& other) const
{
  bool is_same = true;
  if (this == &other) {
    // same
  } else if (get_type() != other.get_type()) {
    is_same = false;
  } else {
    const ObMigrateDag& other_dag = static_cast<const ObMigrateDag&>(other);
    if (NULL != ctx_ && NULL != other_dag.ctx_) {
      if (ctx_->replica_op_arg_.key_ != other_dag.ctx_->replica_op_arg_.key_) {
        is_same = false;
      }
    }
  }
  return is_same;
}

int64_t ObBaseMigrateDag::hash() const
{
  int64_t hash_value = 0;

  if (NULL != ctx_) {
    hash_value = common::murmurhash(&ctx_->replica_op_arg_.key_, sizeof(ctx_->replica_op_arg_.key_), hash_value);
  }
  return hash_value;
}

void ObBaseMigrateDag::clear()
{
  ctx_ = NULL;
  is_inited_ = false;
  tenant_id_ = 0;
}

int ObBaseMigrateDag::fill_comment(char* buf, const int64_t buf_len) const
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(ctx_->fill_comment(buf, buf_len))) {
    LOG_WARN("failed to fill comment", K(ret), K(*ctx_));
  }
  return ret;
}

ObMigrateDag::ObMigrateDag() : ObBaseMigrateDag(ObIDag::DAG_TYPE_MIGRATE, ObIDag::DAG_PRIO_MIGRATE_HIGH)
{}

ObMigrateDag::~ObMigrateDag()
{
  int tmp_ret = OB_SUCCESS;
  ObPartitionService* partition_service = MIGRATOR.get_partition_service();
  ObMigrateStatus migrate_status = OB_MIGRATE_STATUS_NONE;
  bool need_offline_partition = false;

  if (NULL != ctx_) {
    ctx_->calc_need_retry();
    ObReplicaOpArg tmp_relica_op_arg = ctx_->replica_op_arg_;
    ObIPartitionGroup* partition = ctx_->get_partition();
    if (OB_SUCCESS == ctx_->result_ && OB_SUCCESS != this->get_dag_ret()) {
      ctx_->result_ = this->get_dag_ret();
      LOG_WARN("migrate dag is failed", "result", this->get_dag_ret(), K(*ctx_));
    }

    if (OB_SUCCESS == ctx_->result_ && ctx_->need_rebuild_) {  // A state that should not exist
      tmp_ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("result success no need rebuild", K(tmp_ret), K(*ctx_));
      ctx_->result_ = tmp_ret;
      ctx_->need_rebuild_ = false;
    }

    if (OB_SUCCESS != ctx_->result_ && NULL != partition_service && NULL != partition) {
      if (OB_SUCCESS != (tmp_ret = ctx_->get_partition()->get_pg_storage().get_pg_migrate_status(migrate_status))) {
        LOG_WARN("failed to get_migrate_status", K(tmp_ret), K(*ctx_));
      } else if (OB_MIGRATE_STATUS_ADD == migrate_status || OB_MIGRATE_STATUS_MIGRATE == migrate_status) {
        if (OB_NOT_EXIST_REPLICA == ctx_->replica_state_ &&
            !partition_service->is_partition_exist(ctx_->replica_op_arg_.key_)) {
          if (OB_SUCCESS !=
              (tmp_ret = partition_service->get_election_mgr()->stop_partition(ctx_->replica_op_arg_.key_))) {
            STORAGE_LOG(WARN, "failed to stop partition in election mgr", K(tmp_ret), K(*ctx_));
          }
        } else if (OB_NORMAL_REPLICA != ctx_->replica_state_) {
          need_offline_partition = true;
          if (ctx_->need_rebuild_) {
            STORAGE_LOG(INFO, "rebuild offline partition without state switch", K(*ctx_));
            if (OB_SUCCESS != (tmp_ret = partition->pause())) {
              STORAGE_LOG(WARN, "fail to pause partition", K(tmp_ret), K(*ctx_));
            }
          } else if (FAST_MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_ && ctx_->is_takeover_finished_) {
            // do nothing, fast_migrate_mgr will retry
            LOG_INFO("fast migrate: keep pg when takeover finished", K(ctx_->replica_op_arg_.key_));
          } else {
            // If the migration and replication of partition fail,
            // offline opertion is performed on the partition and the status is rolled backup to offline
            STORAGE_LOG(INFO, "rollback partition when migrate fail", K(*ctx_));
            ObPartitionState pstate = partition->get_partition_state();
            if (ObPartitionState::INIT == pstate) {
              if (OB_SUCCESS != (tmp_ret = partition->set_valid())) {
                STORAGE_LOG(WARN, "failed to set partition to valid", K(tmp_ret), KPC(ctx_));
              }
            } else if (OB_SUCCESS != (tmp_ret = partition->offline())) {
              STORAGE_LOG(WARN, "fail to offline partition", K(tmp_ret), K(*ctx_));
            }
          }
        } else {
          // For the rebuild replica opertion, if it fails, it will not be handled temporarily.
          // The reasion is that there may be trasactions in the rebuild replica state that have partitipated in the
          // voting. If it is handled, the majority will not be established.
        }
      } else if (OB_MIGRATE_STATUS_REBUILD == migrate_status) {
        if (OB_SUCCESS != (tmp_ret = online_for_rebuild())) {
          LOG_WARN("failed to online_for_rebuild", K(tmp_ret), K(*ctx_));
        }
      } else if (OB_MIGRATE_STATUS_RESTORE == migrate_status) {
        if (OB_RESTORE_PARTITION_IS_COMPELETE == ctx_->result_) {
          LOG_INFO("restore partition compelete", K(*ctx_));
          ctx_->need_rebuild_ = false;
          ctx_->result_ = OB_SUCCESS;
        }
      }
    }

    ctx_->finish_ts_ = ObTimeUtility::current_time();

    if (!ctx_->need_rebuild_) {
      ctx_->action_ = ObMigrateCtx::END;
      if (OB_SUCCESS == ctx_->result_ && VALIDATE_BACKUP_OP != ctx_->replica_op_arg_.type_) {
        ctx_->result_ = update_partition_meta_for_restore();
      } else if (RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
        // this is for restore standby, cause standby need receive log to retry
        if (OB_SUCCESS != (tmp_ret = online_for_restore())) {
          STORAGE_LOG(WARN, "failed to online for restore", K(tmp_ret), K(ctx_->replica_op_arg_));
        }
      }

      if (OB_SUCCESS == ctx_->result_) {
        ctx_->during_migrating_ = false;
      }

      if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
        STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
      }

      if (OB_SUCCESS != (tmp_ret = ctx_->notice_finish_part_task())) {
        STORAGE_LOG(WARN, "failed to notice_finish_part_task", K(tmp_ret), K(tmp_relica_op_arg));
      }
    } else {
      if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
        STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
      }

      LOG_INFO("migrate retry", "replica_op_arg", ctx_->replica_op_arg_, "rebuild_count", ctx_->rebuild_count_);

      int tmp_result = ctx_->result_;
      ctx_->rebuild_migrate_ctx();
      // gereate_and_schedule_migrate_dag is successful, you should not access ctx content,
      // and there will be concurrency problems

      if (OB_SUCCESS != (tmp_ret = ctx_->generate_and_schedule_migrate_dag())) {
        LOG_WARN("failed to schedule migrate dag", K(tmp_ret), K(*ctx_));
        ctx_->result_ = tmp_result;  // set error state before rebuild
        ctx_->need_rebuild_ = false;
        ctx_->action_ = ObMigrateCtx::END;

        if (need_offline_partition) {
          STORAGE_LOG(INFO, "rollback partition when migrate fail", K(*ctx_));
          if (OB_SUCCESS != (tmp_ret = partition->offline())) {
            STORAGE_LOG(WARN, "fail to offline partition", K(tmp_ret), K(*ctx_));
          }
        }

        if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
          STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
        }

        if (OB_SUCCESS != (tmp_ret = ctx_->notice_finish_part_task())) {
          STORAGE_LOG(WARN, "failed to notice_finish_part_task", K(tmp_ret), K(tmp_relica_op_arg));
        }
      }
    }  // need rebuild

  }  // ctx != NULL
}

int ObMigrateDag::init(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (!ctx.replica_op_arg_.is_valid() || OB_ISNULL(ctx.group_task_)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(ctx.group_task_), K(ctx.replica_op_arg_));
  } else {
    tenant_id_ = ctx.replica_op_arg_.key_.get_tenant_id();
    if (ctx.replica_op_arg_.is_physical_restore_leader()) {
      if (OB_FAIL(init_for_restore_(ctx))) {
        LOG_WARN("failed to init for restore", K(ret));
      }
    } else if (RESTORE_REPLICA_OP == ctx.replica_op_arg_.type_) {
      if (OB_FAIL(ctx.restore_info_.init(ctx.replica_op_arg_.restore_arg_))) {
        STORAGE_LOG(WARN, "failed to init restore info", K(ret));
      }
    } else if (VALIDATE_BACKUP_OP == ctx.replica_op_arg_.type_) {
      ObBackupBaseDataPathInfo path_info;
      if (OB_FAIL(ctx.replica_op_arg_.validate_arg_.get_backup_base_data_info(path_info))) {
        STORAGE_LOG(WARN, "failed to get backup base data info", K(ret));
      } else if (!ctx.macro_index_store_.is_inited() && OB_FAIL(ctx.macro_index_store_.init(path_info))) {
        STORAGE_LOG(WARN, "failed to init macro index store", K(ret), K(path_info));
      }
    }

    if (OB_SUCC(ret)) {
      if (ObReplicaOpPriority::PRIO_LOW == ctx.replica_op_arg_.priority_) {
        set_priority(ObIDag::DAG_PRIO_MIGRATE_LOW);
      } else if (ObReplicaOpPriority::PRIO_MID == ctx.replica_op_arg_.priority_) {
        set_priority(ObIDag::DAG_PRIO_MIGRATE_MID);
      } else {
        set_priority(ObIDag::DAG_PRIO_MIGRATE_HIGH);
      }

      if (OB_FAIL(ctx.notice_start_part_task())) {
        LOG_WARN("failed to notice_start_part_task", K(ret));
        ctx.result_ = ret;
      } else if (OB_FAIL(get_compat_mode_with_table_id(ctx.replica_op_arg_.key_.table_id_, compat_mode_))) {
        LOG_WARN("failed to get table compat mode", K(ret), K(ctx));
      } else {
        ctx_ = &ctx;
        is_inited_ = true;
        STORAGE_LOG(INFO, "succeed init migrate dag");
      }
    }
  }
  return ret;
}

int ObMigrateDag::init_for_restore_(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  ObReplicaRestoreStatus restore_status = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
  ObIPartitionGroupGuard guard;
  ObIPartitionGroup* partition = NULL;
  ObPartGroupMigrationTask* group_task = NULL;
  ObPGKey backup_pg_key;
  ObBackupMetaIndex meta_index;
  const int64_t compatible = ctx.replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;

  if (OB_FAIL(ObPartitionService::get_instance().get_partition(ctx.replica_op_arg_.key_, guard))) {
    LOG_WARN("failed to get physical restore partition", K(ret), "pkey", ctx.replica_op_arg_.key_);
  } else if (OB_ISNULL(partition = guard.get_partition_group())) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "partition must not null", K(ret), K(ctx.replica_op_arg_));
  } else if (FALSE_IT(restore_status =
                          static_cast<ObReplicaRestoreStatus>(partition->get_pg_storage().get_restore_state()))) {
  } else if (ObReplicaRestoreStatus::REPLICA_RESTORE_ARCHIVE_DATA == restore_status) {
    STORAGE_LOG(INFO,
        "restore status is replica restore archive data, no need init for restore",
        "pkey",
        ctx.replica_op_arg_.key_);
  } else if (OB_FAIL(ctx.replica_op_arg_.phy_restore_arg_.get_backup_pgkey(backup_pg_key))) {
    STORAGE_LOG(WARN, "failed to get backup pgkey", K(ret), K(ctx.replica_op_arg_.phy_restore_arg_));
  } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx.group_task_))) {
  } else if (OB_ISNULL(ctx.macro_indexs_)) {
    if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
      const ObBackupMetaType meta_type = ObBackupMetaType::PARTITION_GROUP_META_INFO;
      ObPhyRestoreMacroIndexStoreV2* phy_restore_macro_index_v2 = NULL;
      if (OB_ISNULL(phy_restore_macro_index_v2 = MIGRATOR.get_cp_fty()->get_phy_restore_macro_index_v2())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("phy restore macro index should not be NULL", K(ret), KP(phy_restore_macro_index_v2));
      } else if (OB_FAIL(group_task->get_meta_indexs().get_meta_index(backup_pg_key, meta_type, meta_index))) {
        STORAGE_LOG(WARN, "failed to get meta index", K(ret), K(backup_pg_key), K(meta_index));
      } else if (OB_FAIL(phy_restore_macro_index_v2->init(
                     meta_index.task_id_, ctx.replica_op_arg_.phy_restore_arg_, restore_status))) {
        LOG_WARN("failed to int physcial restore macro index", K(ret));
      } else {
        ctx.macro_indexs_ = phy_restore_macro_index_v2;
        phy_restore_macro_index_v2 = NULL;
      }
      if (OB_NOT_NULL(phy_restore_macro_index_v2)) {
        MIGRATOR.get_cp_fty()->free(phy_restore_macro_index_v2);
        ctx.macro_indexs_ = NULL;
      }
    } else if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
      ObPhyRestoreMacroIndexStore* phy_restore_macro_index = NULL;
      if (OB_ISNULL(phy_restore_macro_index = MIGRATOR.get_cp_fty()->get_phy_restore_macro_index())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("phy restore macro index should not be NULL", K(ret), KP(phy_restore_macro_index));
      } else if (OB_FAIL(phy_restore_macro_index->init(ctx.replica_op_arg_.phy_restore_arg_, restore_status))) {
        LOG_WARN("failed to int physcial restore macro index", K(ret));
      } else {
        ctx.macro_indexs_ = phy_restore_macro_index;
        phy_restore_macro_index = NULL;
      }
      if (OB_NOT_NULL(phy_restore_macro_index)) {
        MIGRATOR.get_cp_fty()->free(phy_restore_macro_index);
        ctx.macro_indexs_ = NULL;
      }
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("restore get invalid compatible version", K(ret), K(compatible));
    }
  } else if (!ctx.macro_indexs_->is_inited()) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("macro index is not NULL but not init", K(ret), KP(ctx.macro_indexs_));
  }

  return ret;
}

int ObMigrateDag::update_partition_meta_for_restore()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  bool need_set_restore = true;
  // If it is a phsical restore, is_restore will set REPLICA_RESTORE_LOG, if not, directly chagne to
  // REPLICA_NOT_RESTORE.
  int16_t is_restore = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
  int16_t restore_state = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "migrate dag do not init", K(ret));
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "partition must not null", K(ret), K(*ctx_));
  } else if ((RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 RESTORE_FOLLOWER_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) &&
             OB_SUCC(ctx_->result_)) {
    const ObPartitionKey& pgkey = ctx_->replica_op_arg_.key_;
    if (ctx_->replica_op_arg_.is_physical_restore() || ctx_->replica_op_arg_.is_standby_restore()) {
      is_restore = ctx_->replica_op_arg_.is_physical_restore() ? ObReplicaRestoreStatus::REPLICA_RESTORE_LOG
                                                               : ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
      ObSavedStorageInfoV2 info;
      ObBaseStorageInfo clog_info;
      bool has_memtable = partition->get_pg_storage().has_memstore();
      bool is_offline = true;
      restore_state = partition->get_pg_storage().get_restore_state();

      if (REPLICA_RESTORE_DATA != restore_state && REPLICA_RESTORE_ARCHIVE_DATA != restore_state &&
          REPLICA_RESTORE_STANDBY != restore_state && REPLICA_RESTORE_CUT_DATA != restore_state) {
        need_set_restore = false;
        STORAGE_LOG(ERROR, "physical restore state is unexpected", K(pgkey), K(restore_state));
      }

      if (OB_SUCC(ret) && OB_FAIL(partition->get_log_service()->is_offline(is_offline))) {
        STORAGE_LOG(WARN, "get log service offline stat fail", K(pgkey));
      }
      // check status, restore finish, no memtable or offline
      if (OB_SUCC(ret) && !need_set_restore && (!has_memtable || is_offline)) {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN,
            "pg has restore finish, but memtable or log service is not ready",
            K(ret),
            K(need_set_restore),
            K(restore_state),
            K(has_memtable),
            K(is_offline));
      }

#ifdef ERRSIM
      if (OB_SUCC(ret)) {
        ret = E(EventTable::EN_RESTORE_UPDATE_PARTITION_META_FAILED) OB_SUCCESS;
        if (-9001 == ret) {
          STORAGE_LOG(INFO, "inject restore fail before create_memtable", K(ret), K(pgkey));
        } else {
          ret = OB_SUCCESS;
        }
      }
#endif
      if (OB_SUCC(ret) && ctx_->pg_meta_.storage_info_.get_data_info().get_schema_version() == 0) {
        ObDataStorageInfo cur_data_info;
        if (OB_FAIL(partition->get_saved_data_info(cur_data_info))) {
          LOG_WARN("failed to get saved data info", K(ret));
        } else {
          ctx_->pg_meta_.storage_info_.get_data_info().set_schema_version(cur_data_info.get_schema_version());
        }
      }

      if (OB_SUCC(ret) && !has_memtable) {
        if (REPLICA_RESTORE_CUT_DATA == restore_state) {
          // do nothing
        } else if (OB_FAIL(partition->set_storage_info(ctx_->pg_meta_.storage_info_))) {
          STORAGE_LOG(WARN, "failed to set storage info", K(ret), K(pgkey));
        }

        if (OB_FAIL(ret)) {
        } else if (OB_FAIL(partition->create_memtable())) {
          STORAGE_LOG(WARN, "failed to create memtable", K(ret), K(pgkey));
        }
      }

#ifdef ERRSIM
      if (OB_SUCC(ret)) {
        ret = E(EventTable::EN_RESTORE_UPDATE_PARTITION_META_FAILED) OB_SUCCESS;
        if (-9002 == ret) {
          STORAGE_LOG(INFO, "inject restore fail before log online", K(ret), K(pgkey));
        } else {
          ret = OB_SUCCESS;
        }
      }
#endif

      if (OB_SUCC(ret) && is_offline) {
        if (OB_FAIL(online_for_restore())) {
          LOG_WARN("failed to online for restore", K(ret));
        }
      }
      STORAGE_LOG(INFO,
          "physical restore update partition meta finish",
          K(pgkey),
          K(restore_state),
          K(has_memtable),
          K(is_offline),
          K(info));
    }

#ifdef ERRSIM
    if (OB_SUCC(ret)) {
      ret = E(EventTable::EN_RESTORE_UPDATE_PARTITION_META_FAILED) OB_SUCCESS;
      if (-9003 == ret) {
        STORAGE_LOG(INFO, "inject restore fail before set_restore_flag", K(ret), K(pgkey));
      } else {
        ret = OB_SUCCESS;
      }
    }
#endif

    if (OB_FAIL(ret) || !need_set_restore) {
    } else if (!partition->get_pg_storage().is_restore()) {
      ret = OB_RESTORE_PARTITION_TWICE;
      STORAGE_LOG(WARN, "partition restore twice", K(ret), K(pgkey));
    } else if (REPLICA_RESTORE_CUT_DATA == restore_state && RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
      const int16_t new_restore_state = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
      if (OB_FAIL(partition->get_pg_storage().set_restore_flag(new_restore_state, OB_INVALID_ID))) {
        LOG_WARN("failed to set restore flag", K(ret), K(*ctx_));
      }
    } else if (OB_FAIL(ObPartitionService::get_instance().set_restore_flag(pgkey, is_restore))) {
      STORAGE_LOG(WARN, "fail to set partition store meta", K(ret));
    }
    // If it is physical restore, set_archive_restoring will be setted in set_restore_flag function
    if (OB_FAIL(ret)) {
      int tmp_ret = OB_SUCCESS;
      if (OB_SUCCESS != (tmp_ret = partition->get_pg_storage().clear_all_memtables())) {
        LOG_WARN("failed to clear all memtables", K(tmp_ret));
      }
    }

#ifdef ERRSIM
    if (OB_SUCC(ret)) {
      ret = E(EventTable::EN_RESTORE_UPDATE_PARTITION_META_FAILED) OB_SUCCESS;
      if (-9004 == ret) {
        STORAGE_LOG(INFO, "inject restore fail before report to rs", K(ret), K(pgkey));
      } else {
        ret = OB_SUCCESS;
      }
    }
#endif
  }
  return ret;
}

int ObMigrateDag::online_for_rebuild()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObSavedStorageInfoV2 info;
  ObBaseStorageInfo& clog_info = info.get_clog_info();
  ObDataStorageInfo& data_info = info.get_data_info();
  if (NULL != ctx_ && ctx_->need_online_for_rebuild_) {
    ObIPartitionGroup* partition = ctx_->get_partition();
    int64_t restore_snapshot_version = OB_INVALID_TIMESTAMP;
    uint64_t last_restore_log_id = OB_INVALID_ID;
    if (NULL == partition) {
      ret = OB_ERR_SYS;
      LOG_ERROR("partition must not null", K(ret), K(*ctx_));
    } else if (partition->is_replica_using_remote_memstore()) {
      // do nothing, cause data replica no need offline
    } else if (OB_FAIL(partition->get_all_saved_info(info))) {
      STORAGE_LOG(WARN, "failed to get saved info", K(ret));
    } else if (OB_FAIL(partition->create_memtable())) {
      LOG_WARN("failed to create memtable", K(ret), "pkey", partition->get_partition_key());
    } else if (OB_FAIL(partition->get_log_service()->migrate_set_base_storage_info(clog_info))) {
      STORAGE_LOG(WARN, "reset clog start point fail", K(ret), K(info));
    } else if (OB_FAIL(partition->get_pg_storage().get_restore_replay_info(
                   last_restore_log_id, restore_snapshot_version))) {
      LOG_WARN("failed to get_restore_replay_info", KR(ret), "pkey", partition->get_partition_key());
    } else if (OB_FAIL(MIGRATOR.get_partition_service()->online_partition(ctx_->replica_op_arg_.key_,
                   data_info.get_publish_version(),
                   restore_snapshot_version,
                   last_restore_log_id))) {
      STORAGE_LOG(WARN,
          "online partition failed",
          K(ret),
          K(info),
          K(restore_snapshot_version),
          K(last_restore_log_id),
          K(*ctx_));
    } else if (OB_FAIL(ctx_->get_partition()->get_log_service()->restore_replayed_log(clog_info))) {
      STORAGE_LOG(WARN, "restore and replay log failed.", K(ret), K_(ctx_->replica_op_arg_.key), K(info));
    } else if (OB_FAIL(ctx_->get_partition()->get_log_service()->set_online(
                   clog_info, ObVersion(0, 0) /*freeze version*/))) {
      STORAGE_LOG(WARN, "reset log temporary status failed.", K(ret), K_(ctx_->replica_op_arg_.key), K(info));
    } else if (OB_FAIL(ctx_->get_partition()->report_clog_history_online())) {
      LOG_WARN("failed to report clog history online", K(ret));
    } else {
      STORAGE_LOG(INFO, "succeed online_for_rebuild", K(ret), "pkey", ctx_->replica_op_arg_.key_, K(info));
      if (OB_SUCCESS != (tmp_ret = MIGRATOR.get_partition_service()->turn_off_rebuild_flag(ctx_->replica_op_arg_))) {
        LOG_WARN("Failed to report_rebuild_replica off", K(tmp_ret), "arg", ctx_->replica_op_arg_);
      }
    }
  }
  return ret;
}

int ObMigrateDag::online_for_restore()
{
  int ret = OB_SUCCESS;
  bool is_offline = true;
  ObSavedStorageInfoV2 info;
  ObBaseStorageInfo clog_info;
  ObIPartitionGroup* partition = NULL;
  if (OB_ISNULL(ctx_)) {
    // do nothing
  } else if (RESTORE_STANDBY_OP != ctx_->replica_op_arg_.type_ && RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ &&
             RESTORE_FOLLOWER_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "online for restore replica op type is unexpected", K(ret), K(ctx_->replica_op_arg_));
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    // do nothing
  } else if (OB_FAIL(partition->get_log_service()->is_offline(is_offline))) {
    STORAGE_LOG(WARN, "get log service offline stat fail");
  } else if (!is_offline) {
    STORAGE_LOG(INFO, "partition standby restore is online", K(partition->get_partition_key()));
  } else if (OB_FAIL(partition->reset_for_replay())) {
    LOG_WARN("failed to reset partition for replay", K(ret), K(partition->get_partition_key()));
  } else if (OB_FAIL(partition->get_all_saved_info(info))) {
    STORAGE_LOG(WARN, "failed to get saved info", K(ret));
  } else if (OB_FAIL(partition->get_saved_clog_info(clog_info))) {
    LOG_WARN("failed to get saved clog info", K(ret));
  } else if (OB_FAIL(partition->get_log_service()->migrate_set_base_storage_info(clog_info))) {
    STORAGE_LOG(WARN, "migrate_set_base_storage_info fail", K(ret), K(clog_info));
  } else if (OB_FAIL(partition->get_log_service()->set_online(clog_info, ObVersion(0, 0) /*freeze version*/))) {
    STORAGE_LOG(WARN, "set_online fail", K(ret), K(clog_info));
  } else if (OB_FAIL(partition->report_clog_history_online())) {
    STORAGE_LOG(WARN, "failed to report clog history online", K(ret), K(partition->get_partition_key()));
  } else {
    STORAGE_LOG(
        INFO, "partition restore online succ", K(partition->get_partition_key()), K(ctx_->replica_op_arg_.type_));
  }
  return ret;
}

ObBackupDag::ObBackupDag() : ObBaseMigrateDag(ObIDag::DAG_TYPE_BACKUP, ObIDag::DAG_PRIO_BACKUP), backup_data_type_()
{}

ObBackupDag::~ObBackupDag()
{
  int tmp_ret = OB_SUCCESS;

  if (NULL != ctx_) {
    ctx_->calc_need_retry();
    ObReplicaOpArg tmp_relica_op_arg = ctx_->replica_op_arg_;
    ObIPartitionGroup* partition = ctx_->get_partition();
    if (OB_SUCCESS == ctx_->result_ && OB_SUCCESS != this->get_dag_ret()) {
      ctx_->result_ = this->get_dag_ret();
      LOG_WARN("migrate dag is failed", "result", this->get_dag_ret(), K(*ctx_));
    }

    if (OB_SUCCESS == ctx_->result_ && ctx_->need_rebuild_) {  // Status should not exist status
      tmp_ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("result success no need rebuild", K(tmp_ret), K(*ctx_));
      ctx_->result_ = tmp_ret;
      ctx_->need_rebuild_ = false;
    }

    ctx_->finish_ts_ = ObTimeUtility::current_time();

    if (!ctx_->need_rebuild_) {
      ctx_->action_ = ObMigrateCtx::END;

      if (OB_SUCCESS == ctx_->result_) {
        ctx_->during_migrating_ = false;
      }

      if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
        STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
      }

      if (OB_SUCCESS != (tmp_ret = ctx_->notice_finish_part_task())) {
        STORAGE_LOG(WARN, "failed to notice_finish_part_task", K(tmp_ret), K(tmp_relica_op_arg));
      }
    } else {
      if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
        STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
      }
      LOG_INFO("backup retry", "replica_op_arg", ctx_->replica_op_arg_, "rebuild_count", ctx_->rebuild_count_);
      int tmp_result = ctx_->result_;
      ctx_->rebuild_migrate_ctx();
      // It has concurrency problems when you use ctx after generate_and_scheduler_migrate_dag successful
      if (OB_SUCCESS != (tmp_ret = ctx_->generate_and_schedule_backup_dag(backup_data_type_))) {
        LOG_WARN("failed to schedule migrate dag", K(tmp_ret), K(*ctx_));
        ctx_->result_ = tmp_result;  // set error code before rebuild
        ctx_->need_rebuild_ = false;
        ctx_->action_ = ObMigrateCtx::END;
        if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
          STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
        }

        if (OB_SUCCESS != (tmp_ret = ctx_->notice_finish_part_task())) {
          STORAGE_LOG(WARN, "failed to notice_finish_part_task", K(tmp_ret), K(tmp_relica_op_arg));
        }
      }
    }  // need rebuild
  }    // ctx != NULL
}

int ObBackupDag::init(const ObBackupDataType& backup_data_type, ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (!ctx.replica_op_arg_.is_valid() || OB_ISNULL(ctx.group_task_) || !backup_data_type.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(ctx.group_task_), K(ctx.replica_op_arg_), K(backup_data_type));
  } else if (BACKUP_REPLICA_OP != ctx.replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "replica op type is not backup", K(ret), K(ctx.replica_op_arg_));
  } else {
    tenant_id_ = ctx.replica_op_arg_.key_.get_tenant_id();
    if (OB_FAIL(ctx.physical_backup_ctx_.init(*ObPartitionMigrator::get_instance().get_bandwidth_throttle(),
            ctx.replica_op_arg_.backup_arg_,
            ctx.replica_op_arg_.key_))) {
      LOG_WARN("failed to init physical backup ctx", K(ret), K(ctx.replica_op_arg_.backup_arg_));
    } else if (ctx.replica_op_arg_.backup_arg_.is_incremental_backup() && OB_ISNULL(ctx.macro_indexs_)) {
      ObPhyRestoreMacroIndexStoreV2* phy_restore_macro_index_v2 = NULL;
      if (OB_ISNULL(phy_restore_macro_index_v2 = MIGRATOR.get_cp_fty()->get_phy_restore_macro_index_v2())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("phy restore macro index should not be NULL", K(ret), KP(phy_restore_macro_index_v2));
      } else if (OB_FAIL(phy_restore_macro_index_v2->init(ctx.replica_op_arg_.backup_arg_.task_id_,
                     ctx.replica_op_arg_.key_,
                     ctx.replica_op_arg_.backup_arg_,
                     backup_data_type))) {
        LOG_WARN("failed to int physcial restore macro index", K(ret));
      } else {
        ctx.macro_indexs_ = phy_restore_macro_index_v2;
        phy_restore_macro_index_v2 = NULL;
      }
      if (OB_NOT_NULL(phy_restore_macro_index_v2)) {
        MIGRATOR.get_cp_fty()->free(phy_restore_macro_index_v2);
        ctx.macro_indexs_ = NULL;
      }
    }

    if (OB_SUCC(ret)) {
      set_priority(ObIDag::DAG_PRIO_BACKUP);
      if (OB_FAIL(ctx.notice_start_part_task())) {
        LOG_WARN("failed to notice_start_part_task", K(ret));
        ctx.result_ = ret;
      } else if (OB_FAIL(get_compat_mode_with_table_id(ctx.replica_op_arg_.key_.table_id_, compat_mode_))) {
        LOG_WARN("failed to get table compat mode", K(ret), K(ctx));
      } else {
        ctx_ = &ctx;
        backup_data_type_ = backup_data_type;
        is_inited_ = true;
        STORAGE_LOG(INFO, "succeed init backup dag");
      }
    }
  }
  return ret;
}

ObValidateDag::ObValidateDag() : ObBaseMigrateDag(ObIDag::DAG_TYPE_VALIDATE, ObIDag::DAG_PRIO_VALIDATE)
{}

ObValidateDag::~ObValidateDag()
{
  int tmp_ret = OB_SUCCESS;
  int ret = OB_SUCCESS;
  if (NULL != ctx_) {
    ctx_->calc_need_retry();
    SMART_VAR(ObReplicaOpArg, tmp_relica_op_arg)
    {
      tmp_relica_op_arg = ctx_->replica_op_arg_;
      if (OB_SUCCESS == ctx_->result_ && OB_SUCCESS != this->get_dag_ret()) {
        ctx_->result_ = this->get_dag_ret();
        LOG_WARN("migrate dag is failed", "result", this->get_dag_ret(), K(*ctx_));
      }

      ctx_->action_ = ObMigrateCtx::END;
      ctx_->during_migrating_ = false;
      if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
        STORAGE_LOG(WARN, "failed to update_partition_migration_status", K(tmp_ret));
      }

      ctx_->finish_ts_ = ObTimeUtility::current_time();
      if (OB_SUCCESS != (tmp_ret = ctx_->notice_finish_part_task())) {
        STORAGE_LOG(WARN, "failed to notice_finish_part_task", K(tmp_ret), K(tmp_relica_op_arg));
      }
    }
  }  // ctx != NULL
}

bool ObValidateDag::operator==(const ObIDag& other) const
{
  bool is_same = true;
  if (this == &other) {
    // same
  } else if (get_type() != other.get_type()) {
    is_same = false;
  } else {
    const ObValidateDag& other_dag = static_cast<const ObValidateDag&>(other);
    if (NULL != ctx_ && NULL != other_dag.ctx_) {
      const ObPhysicalValidateArg& other_arg = other_dag.ctx_->replica_op_arg_.validate_arg_;
      const ObPhysicalValidateArg& arg = ctx_->replica_op_arg_.validate_arg_;
      is_same = arg.backup_set_id_ == other_arg.backup_set_id_ && arg.pg_key_ == other_arg.pg_key_;
    } else {
      is_same = false;
    }
  }
  return is_same;
}

int64_t ObValidateDag::hash() const
{
  int64_t hash_value = 0;
  if (NULL != ctx_) {
    const ObPhysicalValidateArg& arg = ctx_->replica_op_arg_.validate_arg_;
    hash_value = common::murmurhash(&(arg.backup_set_id_), sizeof(arg.backup_set_id_), hash_value);
    hash_value = common::murmurhash(&(arg.pg_key_), sizeof(arg.pg_key_), hash_value);
  }
  return hash_value;
}

int ObValidateDag::init(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (!ctx.replica_op_arg_.is_valid() || OB_ISNULL(ctx.group_task_)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(ctx.group_task_), K(ctx.replica_op_arg_));
  } else if (VALIDATE_BACKUP_OP != ctx.replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "replica op type is not validate", K(ret), K(ctx.replica_op_arg_));
  } else {
    const ObPartitionKey& pkey = ctx.replica_op_arg_.key_;
    tenant_id_ = pkey.get_tenant_id();
    set_priority(ObIDag::DAG_PRIO_VALIDATE);
    if (OB_FAIL(ctx.notice_start_part_task())) {
      LOG_WARN("failed to notice_start_part_task", K(ret));
      ctx.result_ = ret;
    } else {
      ctx_ = &ctx;
      is_inited_ = true;
      STORAGE_LOG(INFO, "succeed init validate dag", K(pkey));
    }
  }
  return ret;
}

ObMigratePrepareTask::ObMigratePrepareTask()
    : ObITask(TASK_TYPE_MIGRATE_PREPARE),
      is_inited_(false),
      ctx_(NULL),
      cp_fty_(NULL),
      rpc_(NULL),
      srv_rpc_proxy_(NULL),
      bandwidth_throttle_(NULL),
      partition_service_(NULL),
      validate_meta_reader_(NULL),
      restore_meta_reader_(NULL),
      backup_meta_reader_(NULL)
{}

ObMigratePrepareTask::~ObMigratePrepareTask()
{
  if (NULL != cp_fty_) {
    if (NULL != validate_meta_reader_) {
      cp_fty_->free(validate_meta_reader_);
    }
    if (NULL != restore_meta_reader_) {
      cp_fty_->free(restore_meta_reader_);
    }
    if (NULL != backup_meta_reader_) {
      cp_fty_->free(backup_meta_reader_);
    }
  }
}

int ObMigratePrepareTask::init()
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (ObIDag::DAG_TYPE_MIGRATE != dag_->get_type() && ObIDag::DAG_TYPE_BACKUP != dag_->get_type() &&
             ObIDag::DAG_TYPE_VALIDATE != dag_->get_type()) {
    ret = OB_ERR_SYS;
    LOG_ERROR("dag type not match", K(ret), K(*dag_));
  } else {
    ctx_ = static_cast<ObMigrateDag*>(dag_)->get_ctx();
    is_inited_ = true;
    bandwidth_throttle_ = MIGRATOR.get_bandwidth_throttle();
    partition_service_ = MIGRATOR.get_partition_service();
    srv_rpc_proxy_ = MIGRATOR.get_svr_rpc_proxy();
    rpc_ = MIGRATOR.get_pts_rpc();
    cp_fty_ = MIGRATOR.get_cp_fty();
  }
  return ret;
}

int ObMigratePrepareTask::prepare_restore_reader_if_needed()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPartGroupMigrationTask* group_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
             RESTORE_FOLLOWER_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_ISNULL(partition = ctx_->get_partition())) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "Unexpected error, the partition is NULL ", K(ret));
    } else if (!partition->get_pg_storage().is_restore()) {
      ret = OB_RESTORE_PARTITION_TWICE;
      STORAGE_LOG(WARN, "partition restore twice", K(ret), K(ctx_->replica_op_arg_.key_));
    } else if (ctx_->replica_op_arg_.is_physical_restore_leader()) {
      if (OB_FAIL(prepare_restore_reader())) {
        LOG_WARN("failed to prepare restore reader", K(ret), "op_arg", ctx_->replica_op_arg_);
      }
    } else if (ctx_->replica_op_arg_.is_physical_restore_follower()) {
      ctx_->use_slave_safe_read_ts_ = false;
    } else {
      ret = OB_NOT_SUPPORTED;
      LOG_WARN("only support physical restore", K(ret), "op", ctx_->replica_op_arg_);
    }
  }
  return ret;
}

int ObMigratePrepareTask::prepare_restore_reader()
{
  int ret = OB_SUCCESS;
  ObPartGroupMigrationTask* group_task = NULL;
  const int64_t compatible = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
    ObPartitionGroupMetaRestoreReaderV2* restore_meta_reader_v2 = NULL;
    ObPhyRestoreMacroIndexStoreV2* macro_index = NULL;

    if (OB_ISNULL(ctx_->macro_indexs_)) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "macro indexs should not be NULL", K(ret), KP(ctx_->macro_indexs_));
    } else if (ObIPhyRestoreMacroIndexStore::PHY_RESTORE_MACRO_INDEX_STORE_V2 != ctx_->macro_indexs_->get_type()) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "macro indexs type is unexpected", K(ret), K(ctx_->macro_indexs_->get_type()));
    } else if (FALSE_IT(macro_index = reinterpret_cast<ObPhyRestoreMacroIndexStoreV2*>(ctx_->macro_indexs_))) {
    } else if (OB_ISNULL(restore_meta_reader_v2 = cp_fty_->get_partition_group_meta_restore_reader_v2())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("meta reader should not be NULL", K(ret), KP(restore_meta_reader_v2));
    } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx_->group_task_))) {
    } else if (OB_FAIL(restore_meta_reader_v2->init(*bandwidth_throttle_,
                   ctx_->replica_op_arg_.phy_restore_arg_,
                   group_task->get_meta_indexs(),
                   *macro_index))) {
      LOG_WARN("fail to init meta reader", K(ret), KP(restore_meta_reader_v2));
    } else {
      ctx_->restore_meta_reader_ = restore_meta_reader_v2;
      restore_meta_reader_v2 = NULL;
    }
    if (NULL != cp_fty_) {
      if (NULL != restore_meta_reader_v2) {
        cp_fty_->free(restore_meta_reader_v2);
      }
    }
  } else if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
    ObPartitionGroupMetaRestoreReaderV1* restore_meta_reader_v1 = NULL;
    ObPhyRestoreMacroIndexStore* macro_index = NULL;
    if (OB_ISNULL(ctx_->macro_indexs_)) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "macro indexs should not be NULL", K(ret), KP(ctx_->macro_indexs_));
    } else if (ObIPhyRestoreMacroIndexStore::PHY_RESTORE_MACRO_INDEX_STORE_V1 != ctx_->macro_indexs_->get_type()) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "macro indexs type is unexpected", K(ret), K(ctx_->macro_indexs_->get_type()));
    } else if (FALSE_IT(macro_index = reinterpret_cast<ObPhyRestoreMacroIndexStore*>(ctx_->macro_indexs_))) {
    } else if (OB_ISNULL(restore_meta_reader_v1 = cp_fty_->get_partition_group_meta_restore_reader_v1())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("meta reader should not be NULL", K(ret), KP(restore_meta_reader_v1));
    } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx_->group_task_))) {
    } else if (OB_FAIL(restore_meta_reader_v1->init(*bandwidth_throttle_,
                   ctx_->replica_op_arg_.phy_restore_arg_,
                   group_task->get_meta_indexs(),
                   *macro_index))) {
      LOG_WARN("fail to init meta reader", K(ret), KP(restore_meta_reader_v1));
    } else {
      ctx_->restore_meta_reader_ = restore_meta_reader_v1;
      restore_meta_reader_v1 = NULL;
    }
    if (NULL != cp_fty_) {
      if (NULL != restore_meta_reader_v1) {
        cp_fty_->free(restore_meta_reader_v1);
      }
    }
  } else {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("compatible version is unexpected", K(ret), K(compatible));
  }
  return ret;
}

int ObMigratePrepareTask::prepare_backup_reader_if_needed()
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_ISNULL(ctx_->backup_meta_reader_ = cp_fty_->get_partition_group_meta_backup_reader())) {
      ret = OB_ERR_UNEXPECTED;
      STORAGE_LOG(WARN, "pg meta reader should not be NULL", K(ret));
    } else if (OB_FAIL(ctx_->backup_meta_reader_->init(ctx_->pg_meta_, ctx_->replica_op_arg_.backup_arg_))) {
      STORAGE_LOG(WARN, "fail to init backup meta reader", K(ret));
    }
  }
  return ret;
}

// TODO() interface optimization for restore and rebuild
int ObMigratePrepareTask::create_partition_if_needed(
    ObIPartitionGroupGuard& pg_guard, const ObPGPartitionStoreMeta& partition_meta)
{
  int ret = OB_SUCCESS;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(ERROR, "not inited", K(ret));
  } else if (OB_UNLIKELY(!partition_meta.is_valid())) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "partition_meta is not valid", K(ret), K(partition_meta));
  } else {
    const ObPartitionKey& pg_key = ctx_->replica_op_arg_.key_;
    const ObPartitionKey& pkey = partition_meta.pkey_;
    ObIPartitionGroupGuard guard;
    ObIPartitionGroup* pg = NULL;
    int tmp_ret = OB_SUCCESS;
    if (OB_SUCCESS == (tmp_ret = ObPartitionService::get_instance().get_partition(pkey, guard))) {
      STORAGE_LOG(INFO, "partition exist, not need to create", K(ret), K(pkey));
    } else if (OB_PARTITION_NOT_EXIST != tmp_ret) {
      ret = tmp_ret;
      STORAGE_LOG(WARN, "restore get partition fail", K(ret), K(pkey));
    } else {
      obrpc::ObCreatePartitionArg arg;
      arg.schema_version_ = partition_meta.create_schema_version_;
      arg.lease_start_ = partition_meta.create_timestamp_;
      arg.restore_ = REPLICA_RESTORE_DATA;
      const bool is_replay = false;
      const uint64_t unused = 0;
      const bool in_slog_trans = false;
      ObTablesHandle sstables_handle;

      if (OB_ISNULL(pg = pg_guard.get_partition_group())) {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN, "partition group should not be null", K(ret), K(pg_key));
      } else if (OB_FAIL(pg->create_pg_partition(pkey,
                     partition_meta.multi_version_start_,
                     partition_meta.data_table_id_,
                     arg,
                     in_slog_trans,
                     is_replay,
                     unused,
                     sstables_handle))) {
        STORAGE_LOG(WARN, "fail to create pg partition", K(ret), K(partition_meta));
      } else {
        sstables_handle.reset();
        STORAGE_LOG(
            INFO, "succeed to create follower pg partition during physical restore", K(pkey), K(partition_meta));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::process()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  if (NULL != ctx_) {
    ctx_->action_ = ObMigrateCtx::PREPARE;
    if (NULL != dag_) {
      ctx_->task_id_ = dag_->get_dag_id();
    }

    if (OB_SUCCESS != (tmp_ret = (ctx_->trace_id_array_.push_back(*ObCurTraceId::get_trace_id())))) {
      STORAGE_LOG(WARN, "failed to push back trace id to array", K(tmp_ret));
    }
    LOG_INFO("start ObMigratePrepareTask process", "arg", ctx_->replica_op_arg_);
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(add_migrate_status(ctx_))) {
    LOG_WARN("failed to add migrate status", K(ret));
  } else {
    {
      const bool is_write_lock = true;
      ObMigrateCtxGuard guard(is_write_lock, *ctx_);
      if (!ctx_->is_valid()) {
        ret = OB_ERR_SYS;
        STORAGE_LOG(ERROR, "invalid migrate ctx", K(ret), K(*this), K(*ctx_));
      } else if (1 != ctx_->doing_task_cnt_) {
        ret = OB_ERR_SYS;
        STORAGE_LOG(ERROR, "doing task must be 1 during prepare action", K(ret), K(*this), K(*ctx_));
      } else if (REMOVE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
        ret = OB_ERR_SYS;
        STORAGE_LOG(ERROR, "should not prepare migrate for remove replica", K(ret), K(ctx_->replica_op_arg_));
      } else if (OB_FAIL(try_hold_local_partition())) {
        LOG_WARN("failed to hold local partition", K(ret));
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(generate_tasks_by_type())) {
        LOG_WARN("failed to generate tasks by type", K(ret));
      }
    }
  }

  if (OB_SUCC(ret)) {
    ObTaskController::get().allow_next_syslog();
    LOG_INFO("finish prepare task", K(*ctx_));
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    if (ctx_->is_need_retry(ret)) {
      ctx_->need_rebuild_ = true;
      LOG_INFO("migrate prepare task need retry", K(ret), K(*ctx_));
    }
    ctx_->set_result_code(ret);
  }

  LOG_INFO("end ObMigratePrepareTask process", K(ret));
  return ret;
}

int ObMigratePrepareTask::need_generate_sstable_migrate_tasks(bool& need_schedule)
{
  int ret = OB_SUCCESS;
  need_schedule = true;
  bool is_replica_with_data = true;

  if (NULL != ctx_) {
    if (OB_FAIL(ctx_->change_replica_with_data(is_replica_with_data))) {
      LOG_WARN("failed to check replica", K(ret), K(*ctx_));
    } else if (is_replica_with_data) {
      need_schedule = false;
      LOG_INFO("change replica op with data, no need migrate task", K(*ctx_));
    } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
      need_schedule = false;
      LOG_INFO("dst replica has no ssstore, no need migrate task", K(*ctx_));
    } else if (ctx_->is_leader_restore_archive_data()) {
      need_schedule = false;
      LOG_INFO("no need restore archive data", "arg", ctx_->replica_op_arg_);
    } else if (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_ &&
               (REPLICA_LOGICAL_RESTORE_DATA == ctx_->is_restore_ || REPLICA_RESTORE_DATA == ctx_->is_restore_ ||
                   REPLICA_RESTORE_STANDBY == ctx_->is_restore_)) {
      need_schedule = false;
      LOG_INFO("no need migrate task for add replica when restoring", "arg", ctx_->replica_op_arg_);
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_trans_table_migrate_task(ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  bool need_schedule = false;
  last_task = nullptr;
  if (ObFetchPGInfoResult::FETCH_PG_INFO_RES_COMPAT_VERSION_V2 <= ctx_->fetch_pg_info_compat_version_) {
    if (OB_FAIL(need_generate_sstable_migrate_tasks(need_schedule))) {
      LOG_WARN("failed to check need generate migrate task", K(ret));
    } else if (!need_schedule) {
    } else if (!need_migrate_trans_table(ctx_->replica_op_arg_.type_)) {
      LOG_INFO("no need to migrate trans table", K(ctx_->replica_op_arg_.type_));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
        ObPartitionMigrateCtx& part_migrate_ctx = ctx_->part_ctx_array_.at(i);
        if (part_migrate_ctx.copy_info_.meta_.pkey_.is_trans_table()) {
          if (OB_FAIL(generate_migrate_tasks(part_migrate_ctx, last_task))) {
            LOG_WARN("fail to generate migrate tasks", K(ret), K(part_migrate_ctx));
          }
          break;
        }
      }
    }
  }
  if (OB_SUCC(ret) && OB_ISNULL(last_task)) {
    last_task = this;
  }
  return ret;
}

int ObMigratePrepareTask::generate_post_prepare_task(ObITask& parent_task)
{
  int ret = OB_SUCCESS;
  ObMigratePostPrepareTask* post_prepare_task = nullptr;
  if (OB_ISNULL(dag_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("dag can not be null", K(ret));
  } else if (OB_FAIL(dag_->alloc_task(post_prepare_task))) {
    LOG_WARN("failed to alloc post prepare task", K(ret));
  } else if (OB_ISNULL(post_prepare_task)) {
    ret = OB_ERR_SYS;
    LOG_WARN("post prepare task can not be null", K(ret));
  } else if (OB_FAIL(post_prepare_task->init())) {
    LOG_WARN("failed to init post prepare task", K(ret));
  } else if (OB_FAIL(parent_task.add_child(*post_prepare_task))) {
    LOG_WARN("failed to add post_prepare_task to parent task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*post_prepare_task))) {
    LOG_WARN("failed to add post_prepare_task to dag", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::prepare_migrate()
{
  int ret = OB_SUCCESS;
  const bool is_write_lock = true;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else {
    ObMigrateCtxGuard guard(is_write_lock, *ctx_);

    if (ctx_->is_leader_restore_archive_data()) {
      LOG_INFO("no need restore archive data", "arg", ctx_->replica_op_arg_);
    } else if (OB_FAIL(prepare_restore_reader_if_needed())) {
      LOG_WARN("failed to prepare restore reader", K(ret));
    } else if (OB_FAIL(prepare_backup_reader_if_needed())) {
      LOG_WARN("failed to prepare backup reader", K(ret));
    } else if (OB_FAIL(choose_migrate_src())) {
      LOG_WARN("fail to choose migrate src", K(ret));
    } else if (OB_FAIL(check_backup_data_continues())) {
      LOG_WARN("failed to check backup data continues", K(ret));
    } else if (OB_FAIL(build_migrate_pg_partition_info())) {
      LOG_WARN("failed to build migrate pg partition info", K(ret), K(*ctx_));
    } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      LOG_INFO("no need replay for BACKUP_REPLICA_OP", "arg", ctx_->replica_op_arg_);
    } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
      LOG_INFO("no need replay for VALIDATE_BACKUP_OP", "arg", ctx_->replica_op_arg_);
    } else if (OB_ISNULL(ctx_->get_partition())) {
      if (OB_FAIL(prepare_new_partition())) {
        LOG_WARN("failed to prepare new partition", K(ret), "arg", ctx_->replica_op_arg_);
      } else {
        ctx_->create_new_pg_ = true;
      }
    }

    if (OB_SUCC(ret)) {
      ATOMIC_AAF(&ctx_->data_statics_.partition_count_, ctx_->pg_meta_.partitions_.count());
      ctx_->need_rebuild_ = false;
      ObTaskController::get().allow_next_syslog();
      STORAGE_LOG(INFO, "finish prepare migrate", "pkey", ctx_->replica_op_arg_.key_, K(*ctx_));
    } else if (NULL != ctx_) {
      ctx_->result_ = ret;
    }
  }
  return ret;
}

int ObMigratePrepareTask::try_hold_local_partition()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGStorage* pg_storage = NULL;
  common::ObAddr leader;
  ObReplicaProperty replica_property;
  int16_t restore_state = 0;
  int64_t trans_table_end_log_ts = 0;
  int64_t trans_table_timestamp = 0;
  ObRole role;
  ObPartitionGroupMeta local_pg_meta;
  ObPartGroupMigrationTask* group_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
    // do nothing
    LOG_INFO("no need to hold local partition if validate backup");
  } else if (OB_NOT_NULL(partition = ctx_->get_partition())) {
    // do nothing
    pg_storage = &(partition->get_pg_storage());
    LOG_INFO("partition already hold, do not hold again");
  } else if (OB_FAIL(ObPartitionService::get_instance().get_partition(
                 ctx_->replica_op_arg_.key_, ctx_->partition_guard_))) {
    if (OB_PARTITION_NOT_EXIST != ret) {
      STORAGE_LOG(WARN, "get partition failed.", K(ret), K(*ctx_));
    } else if (ctx_->is_only_copy_sstable()) {
      LOG_WARN("failed to get partition for copy index", K(ret), K(*ctx_));
    } else if (CHANGE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      LOG_WARN("partition not exist, cannot change replica", K(ret), K(*ctx_));
    } else if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      LOG_WARN("partition not exist, cannot rebuild replica", K(ret), K(*ctx_));
    } else if (LINK_SHARE_MAJOR_OP == ctx_->replica_op_arg_.type_) {
      LOG_WARN("partition not exist, cannot link share major", K(ret), K(*ctx_));
    } else {
      ret = OB_SUCCESS;
      ctx_->replica_state_ = OB_NOT_EXIST_REPLICA;
    }
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group()) ||
             OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "partition must not null", K(ret));
  } else if (FALSE_IT(ctx_->is_restore_ = partition->get_pg_storage().get_restore_state())) {
  } else if (ctx_->replica_op_arg_.is_physical_restore() && REPLICA_RESTORE_DATA != ctx_->is_restore_ &&
             REPLICA_RESTORE_ARCHIVE_DATA != ctx_->is_restore_) {
    ObMigrateStatus migrate_status;
    if (OB_FAIL(partition->get_pg_storage().get_pg_migrate_status(migrate_status))) {
      STORAGE_LOG(WARN, "get pg migrate status fail", K(ret), K(ctx_->replica_op_arg_));
    } else if (OB_MIGRATE_STATUS_NONE != migrate_status) {
      ret = OB_STATE_NOT_MATCH;
      STORAGE_LOG(
          WARN, "physical restore failed", K(ret), K(ctx_->is_restore_), K(migrate_status), K(ctx_->replica_op_arg_));
    } else {
      // restore = 0,1,3,4,5 skip physical restore and ret will be set succ before dag finish
      ret = OB_RESTORE_PARTITION_IS_COMPELETE;
      STORAGE_LOG(INFO,
          "physical restore base data is already finished",
          K(ret),
          K(ctx_->is_restore_),
          K(ctx_->replica_op_arg_));
    }
  } else if (ctx_->replica_op_arg_.is_standby_restore() && REPLICA_RESTORE_STANDBY != ctx_->is_restore_ &&
             REPLICA_RESTORE_CUT_DATA != ctx_->is_restore_) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("standby replica restore but restore status is wrong", K(*ctx_));
  } else if (OB_FAIL(partition->get_leader(leader))) {
    LOG_WARN("failed to get leader", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_FAIL(partition->get_role(role))) {
    LOG_WARN("failed to get partition role", K(ret), "arg", ctx_->replica_op_arg_);
R
rl0 已提交
5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928
  } else if (leader.is_valid()
      && leader == MYADDR
      // support rebuild in leader reconfirm
      && is_strong_leader(role)
      //TODO(wait yanmu)
      //&& is_strong_leader(role)
      && (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_
          || MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_
          || FAST_MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_
          || REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_
          || CHANGE_REPLICA_OP == ctx_->replica_op_arg_.type_
          || LINK_SHARE_MAJOR_OP == ctx_->replica_op_arg_.type_)) {
O
oceanbase-admin 已提交
5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715
    if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      if (OB_FAIL(MIGRATOR.get_partition_service()->turn_off_rebuild_flag(ctx_->replica_op_arg_))) {
        LOG_WARN("Failed to report_rebuild_replica off", K(ret), "arg", ctx_->replica_op_arg_);
      } else {
        ret = OB_NO_NEED_REBUILD;
        LOG_WARN("leader can not as rebuild dst", K(ret), K(leader), "myaddr", MYADDR, "arg", ctx_->replica_op_arg_);
      }
    } else {
      ret = OB_ERR_SYS;
      LOG_WARN("leader cannot as add_replica,migrate,change_replica,share_major dst",
          K(ret),
          K(leader),
          "myaddr",
          MYADDR,
          "arg",
          ctx_->replica_op_arg_);
    }
  } else if (OB_ISNULL(ctx_->group_task_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("group task should not be null here", K(ret));
  } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx_->group_task_))) {
  } else if (OB_FAIL(group_task->set_migrate_in(partition->get_pg_storage()))) {
    LOG_WARN("failed to set migrate int", "pkey", ctx_->replica_op_arg_.key_, K(ret));
  }

  if (OB_FAIL(ret) || OB_ISNULL(partition) || OB_ISNULL(pg_storage)) {
    // do nothing
  } else if (OB_FAIL(partition->get_replica_state(ctx_->replica_state_))) {
    LOG_WARN("failed to get replica state", K(ret), K(*ctx_));
  } else if (OB_FAIL(pg_storage->get_replica_property(replica_property))) {
    LOG_WARN("failed to get replica property", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_FAIL(pg_storage->get_pg_meta(local_pg_meta))) {
    LOG_WARN("failed to get pg meta", K(ret));
  } else {
    if (OB_FAIL(pg_storage->get_trans_table_end_log_ts_and_timestamp(trans_table_end_log_ts, trans_table_timestamp))) {
      if (OB_ENTRY_NOT_EXIST != ret && OB_PARTITION_NOT_EXIST != ret) {
        LOG_WARN("failed to get trans table end_log_ts and timestamp", K(ret), K(ctx_->replica_op_arg_.key_));
      } else if (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_ || MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 FAST_MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 RESTORE_FOLLOWER_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
                 RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
        ret = OB_SUCCESS;
      } else {
        LOG_WARN("failed to get trans table end_log_ts and timestamp", K(ret), K(ctx_->replica_op_arg_));
      }
    }

    if (OB_FAIL(ret)) {
    } else {
      ctx_->local_publish_version_ = local_pg_meta.storage_info_.get_data_info().get_publish_version();
      ctx_->local_last_replay_log_id_ = local_pg_meta.storage_info_.get_clog_info().get_last_replay_log_id();
      ctx_->local_last_replay_log_ts_ =
          std::max(trans_table_end_log_ts, local_pg_meta.storage_info_.get_data_info().get_last_replay_log_ts());
      common::ObReplicaType replica_type = ctx_->replica_op_arg_.dst_.get_replica_type();
      common::ObReplicaType local_replica_type = partition->get_replica_type();
      if (local_replica_type != replica_type &&
          !ObReplicaTypeCheck::change_replica_op_allow(local_replica_type, replica_type)) {
        ret = OB_OP_NOT_ALLOW;
        STORAGE_LOG(WARN, "change replica op not allow", K(ret), K(local_replica_type), K(replica_type), K(*ctx_));
      }
    }

    if (OB_SUCC(ret)) {
      if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
        if (pg_storage->is_replica_with_remote_memstore()) {
          ctx_->use_slave_safe_read_ts_ = false;
          LOG_INFO("rebuild replica op which memstore percent is 0 do not use slave safe read ts", K(replica_property));
        }
      } else if (ctx_->is_leader_restore_archive_data()) {
        if (OB_FAIL(partition->get_pg_storage().get_pg_meta(ctx_->pg_meta_))) {
          ctx_->result_ = ret;
          STORAGE_LOG(WARN, "get local pg meta fail", K(ret), K(ctx_->replica_op_arg_.key_));
        }
      }
    }
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    ctx_->can_rebuild_ = false;
    LOG_WARN("failed during try_hold_local_partition, set cannot rebuild", K(ret), K(*ctx_));
  }
  return ret;
}

int ObMigratePrepareTask::choose_migrate_src()
{
  int ret = OB_SUCCESS;
  const int64_t local_cluster_id = GCONF.cluster_id;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else {
    const ObReplicaOpType op_type = ctx_->replica_op_arg_.type_;
    switch (op_type) {
      case VALIDATE_BACKUP_OP: {
        LOG_INFO("no need to choose migrate src for validate backup", K(ret));
        break;
      }
      case RESTORE_REPLICA_OP: {
        if (OB_FAIL(choose_restore_migrate_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("failed to choose restore migrate src", K(ret));
        }
        break;
      }
      case BACKUP_REPLICA_OP: {
        if (OB_FAIL(choose_backup_migrate_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("failed to choose restore migrate src", K(ret));
        }
        break;
      }
      case REBUILD_REPLICA_OP: {
        if (OB_FAIL(choose_ob_rebuild_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("failed to choose rebuild src", K(ret));
        }
        break;
      }
      case CHANGE_REPLICA_OP:
      case ADD_REPLICA_OP:
      case MIGRATE_REPLICA_OP: {
        if (ctx_->replica_op_arg_.cluster_id_ != local_cluster_id) {
          ret = OB_ERR_SYS;
          LOG_WARN("can not migrate from diff cluster", K(*ctx_), K(local_cluster_id));
        } else if (OB_FAIL(choose_ob_migrate_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("fail to choose ob master migrate src", K(ret));
        }
        LOG_INFO("migrate choose src", K(*ctx_));
        break;
      }
      case RESTORE_STANDBY_OP: {
        if (OB_FAIL(choose_standby_restore_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("failed to choose standby restore src", K(ret));
        }
        break;
      }
      case COPY_LOCAL_INDEX_OP:
      case COPY_GLOBAL_INDEX_OP:
      case RESTORE_FOLLOWER_REPLICA_OP:
      case FAST_MIGRATE_REPLICA_OP: {
        // these operation type no need choose src, use rs provided
        if (OB_FAIL(choose_recommendable_src(ctx_->replica_op_arg_, ctx_->pg_meta_, ctx_->migrate_src_info_))) {
          LOG_WARN("failed to choose recommendable src", K(ret));
        }
        break;
      }
      default: {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected replica op type", K(ret), K(*ctx_));
        break;
      }
    }  // end-switch
  }
  return ret;
}

int ObMigratePrepareTask::choose_ob_migrate_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  const int64_t local_cluster_id = GCONF.cluster_id;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (ctx_->replica_op_arg_.cluster_id_ != local_cluster_id &&
             MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_WARN("can not migrate from diff cluster", K(*ctx_), K(local_cluster_id));
  } else if (OB_FAIL(choose_ob_src(is_valid_migrate_src, arg, pg_meta, src_info))) {
    LOG_WARN("failed to choose ob src", K(ret), K(arg));
  }
  return ret;
}

int ObMigratePrepareTask::choose_ob_rebuild_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(choose_rebuild_src(arg, meta, src_info))) {
    LOG_WARN("failed to choose local cluster rebuild src, try choose remote cluster rebuild src", K(ret), K(arg));
  }
  return ret;
}

int ObMigratePrepareTask::choose_rebuild_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  ObArray<ObMigrateSrcInfo> src_info_array;
  meta.reset();
  src_info_array.reset();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(partition_service_->get_migrate_leader_and_parent(arg.key_, src_info_array))) {
    LOG_WARN("failed to get migrat src", K(ret), K(arg));
  } else if (OB_FAIL(choose_rebuild_candidate(arg, src_info_array, meta, src_info))) {
    LOG_WARN("fail to choose rebuild candidate", K(ret), K(arg));
  }

  if (OB_FAIL(ret)) {
    // overwrite ret
    src_info_array.reset();
    if (OB_FAIL(partition_service_->get_rebuild_src(arg.key_, arg.dst_.get_replica_type(), src_info_array))) {
      LOG_WARN("failed to get migrat src", K(ret), K(arg));
    } else if (OB_FAIL(choose_rebuild_candidate(arg, src_info_array, meta, src_info))) {
      LOG_WARN("fail to choose rebuild candidate", K(ret), K(arg));
    }
  }
  return ret;
}

int ObMigratePrepareTask::copy_needed_table_info(const ObReplicaOpArg& arg,
    const obrpc::ObPGPartitionMetaInfo& data_src_result, ObIArray<obrpc::ObFetchTableInfoResult>& table_info_res,
    ObIArray<uint64_t>& table_id_list, bool& found)
{
  int ret = OB_SUCCESS;
  found = false;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else {
    if (COPY_LOCAL_INDEX_OP != arg.type_) {
      if (OB_FAIL(table_id_list.assign(data_src_result.table_id_list_))) {
        LOG_WARN("failed to assign table id list", K(ret));
      } else if (OB_FAIL(table_info_res.assign(data_src_result.table_info_))) {
        LOG_WARN("failed to copy needed table info", K(ret), K(data_src_result));
      } else {
        found = true;
      }
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < data_src_result.table_id_list_.count() && !found; ++i) {
        found = arg.index_id_ == data_src_result.table_id_list_.at(i);
        if (found) {
          if (OB_FAIL(table_id_list.push_back(data_src_result.table_id_list_.at(i)))) {
            LOG_WARN("failed to push table id into array", K(ret), K(arg));
          } else if (OB_FAIL(table_info_res.push_back(data_src_result.table_info_.at(i)))) {
            LOG_WARN("failed to push table info into array", K(ret), K(data_src_result), K(i));
          }
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (found) {
        if (table_id_list.count() != table_info_res.count()) {
          ret = OB_ERR_SYS;
          LOG_WARN("table id list count not equal to table info count",
              K(ret),
              "table_id_list count",
              table_id_list.count(),
              "table_info count",
              table_info_res.count());
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::fetch_partition_group_info(
    const ObReplicaOpArg& arg, const ObMigrateSrcInfo& src_info, ObPartitionGroupInfoResult& result)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (!src_info.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("fetch rebuild partition info get invalid argument", K(ret), K(src_info));
  } else if (OB_FAIL(rpc_->post_fetch_partition_group_info_request(src_info.src_addr_,
                 arg.key_,
                 arg.dst_.get_replica_type(),
                 src_info.cluster_id_,
                 ctx_->use_slave_safe_read_ts_,
                 result.result_))) {
    LOG_WARN("fail to post fetch partition info request", K(ret), K(src_info), K(arg));
  } else {
    result.choose_src_info_ = src_info;
  }

  return ret;
}

int ObMigratePrepareTask::choose_rebuild_candidate(const ObReplicaOpArg& arg,
    const common::ObIArray<ObMigrateSrcInfo>& src_info_array, ObPartitionGroupMeta& meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObArray<ObMigrateSrcInfo> same_region_array;
  ObArray<ObMigrateSrcInfo> diff_region_array;
  bool find_src = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (src_info_array.empty() || !arg.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("choose fetch candidate get invalid argument", K(ret), K(src_info_array.count()), K(arg));
  } else if (OB_FAIL(split_candidate_with_region(src_info_array, same_region_array, diff_region_array))) {
    LOG_WARN("fail to split candidate with region", K(ret));
  } else if (src_info_array.count() != (same_region_array.count() + diff_region_array.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("split candidate error ",
        K(ret),
        K(src_info_array.count()),
        K(same_region_array.count()),
        K(diff_region_array.count()));
  } else {
    // first choose same region
    ObPartitionGroupInfoResult result;
    ObPartitionGroupInfoResult tmp_result;
    if (OB_SUCCESS != (tmp_ret = fetch_suitable_rebuild_src(arg, same_region_array, result))) {
      LOG_WARN("fail to fetch same region suitable src and result", K(tmp_ret), K(arg));
    } else {
      find_src = result.is_valid() && result.result_.is_log_sync_;
    }
    // if not find same region src, then try choose from all region
    if (OB_SUCC(ret) && !find_src) {
      if (OB_FAIL(fetch_suitable_rebuild_src(arg, diff_region_array, tmp_result))) {
        LOG_WARN("fail to fetch diff region suitable src and result", K(ret), K(arg));
      } else if (OB_FAIL(copy_rebuild_partition_info_result(tmp_result, result, find_src))) {
        LOG_WARN("fail to copy rebuild partition info", K(ret), K(tmp_result), K(result));
      }
    }

    if (OB_SUCC(ret) && !result.is_valid()) {
      ret = OB_DATA_SOURCE_NOT_EXIST;
      LOG_WARN("cannot choose_ob_rebuild_src", K(ret), K(arg), K(src_info_array), K(result), K(find_src));
    } else {
      LOG_INFO("choose_ob_rebuild_src", "src", result.choose_src_info_);
      if (OB_FAIL(meta.deep_copy(result.result_.pg_meta_))) {
        LOG_WARN("failed to deep copy meta", K(ret));
      } else {
        ctx_->mig_src_file_id_ = result.result_.pg_file_id_;
        ctx_->fetch_pg_info_compat_version_ = result.result_.compat_version_;
        src_info = result.choose_src_info_;
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::copy_rebuild_partition_info_result(
    ObPartitionGroupInfoResult& tmp_result, ObPartitionGroupInfoResult& target_result, bool& find_src)
{
  int ret = OB_SUCCESS;
  find_src = false;
  if (tmp_result.is_valid()) {
    bool need_assign = false;
    if (target_result.is_valid()) {
      if (tmp_result.result_.pg_meta_.storage_info_.get_data_info().get_publish_version() >
          target_result.result_.pg_meta_.storage_info_.get_data_info().get_publish_version()) {
        need_assign = true;
      }
    } else {
      need_assign = true;
    }

    if (need_assign) {
      target_result.reset();
      if (OB_FAIL(target_result.assign(tmp_result))) {
        LOG_WARN("fail to assign out result", K(ret), K(tmp_result));
      } else {
        find_src = target_result.is_valid() && target_result.result_.is_log_sync_;
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::split_candidate_with_region(const ObIArray<ObMigrateSrcInfo>& src_info_array,
    ObIArray<ObMigrateSrcInfo>& same_region_array, ObIArray<ObMigrateSrcInfo>& diff_region_array)
{
  int ret = OB_SUCCESS;
  ObRegion local_addr_region;
  const ObAddr& self_addr = OBSERVER.get_self();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (src_info_array.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("split candidate with region get invaid argument", K(ret), K(src_info_array.count()));
  } else if (OB_FAIL(partition_service_->get_server_region(self_addr, local_addr_region))) {
    LOG_WARN("fail to get local src region", K(ret), K(self_addr));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < src_info_array.count(); ++i) {
      ObRegion tmp_region;
      const ObMigrateSrcInfo& src = src_info_array.at(i);
      if (OB_FAIL(partition_service_->get_server_region_across_cluster(src.src_addr_, tmp_region))) {
        LOG_WARN("fail to get server region", K(ret), K(src));
      } else if (local_addr_region == tmp_region) {
        if (OB_FAIL(same_region_array.push_back(src))) {
          LOG_WARN("fail to push src into same region array", K(ret), K(src));
        }
      } else {
        if (OB_FAIL(diff_region_array.push_back(src))) {
          LOG_WARN("fail to push src into diff region array", K(ret), K(src));
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::fetch_suitable_rebuild_src(const ObReplicaOpArg& arg,
    const common::ObIArray<ObMigrateSrcInfo>& src_array, ObPartitionGroupInfoResult& out_result)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGStorage* pg_storage = NULL;
  ObPartitionGroupMeta local_pg_meta;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not init", K(ret));
  } else if (!arg.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("fetch suitable src get invalid argument", K(ret), K(arg));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group()) ||
             OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "partition must not null", K(ret));
  } else if (OB_FAIL(pg_storage->get_pg_meta(local_pg_meta))) {
    LOG_WARN("failed to get pg meta", K(ret));
  } else {
    ObPartitionGroupInfoResult tmp_result;
    int64_t max_major_snapshot_version = local_pg_meta.report_status_.snapshot_version_;
    int64_t max_minor_snapshot_version = ctx_->local_publish_version_;
    // TODO() handle 22x compatible
    uint64_t max_migrate_replay_log_ts =
        std::max(local_pg_meta.get_migrate_replay_log_ts(), ctx_->local_last_replay_log_ts_);
    int64_t max_last_replay_log_id = ctx_->local_last_replay_log_id_;
    for (int64_t i = 0; OB_SUCC(ret) && i < src_array.count(); ++i) {
      tmp_result.reset();
      const ObMigrateSrcInfo& src_info = src_array.at(i);
      bool is_valid_src = false;
      bool is_suitable = false;
      if (!src_info.is_valid()) {
        ret = OB_ERR_SYS;
        LOG_ERROR("invalid src addr", K(src_info));
      } else if (OB_SUCCESS != (tmp_ret = fetch_partition_group_info(arg, src_info, tmp_result))) {
        LOG_WARN("fail to fetch rebuild partition info", K(tmp_ret), K(src_info));
      } else if (OB_FAIL(is_valid_rebuild_src(tmp_result.result_, *ctx_, is_valid_src))) {
        LOG_WARN("failed to check rebuild src valid", K(ret), K(tmp_result));
      } else if (!is_valid_src) {
        // do nothing
      } else {
        const ObDataStorageInfo& data_info = tmp_result.result_.pg_meta_.storage_info_.get_data_info();
        const int64_t remote_minor_snapshot_version = data_info.get_publish_version();
        const int64_t remote_major_snapshot_version = tmp_result.result_.pg_meta_.report_status_.snapshot_version_;
        const uint64_t remote_last_replay_log_id =
            tmp_result.result_.pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();
        const uint64_t remote_migrate_replay_log_ts = tmp_result.result_.pg_meta_.get_migrate_replay_log_ts();
        bool is_suitable = false;
        const bool is_empty_pg = tmp_result.result_.pg_meta_.partitions_.empty();
        // new freeze might generate empty log_ts_range, still need use version compare
        // pg upgrade from 22x will always has replay_log_ts with 4096
        if (remote_migrate_replay_log_ts > max_migrate_replay_log_ts) {
          is_suitable = true;
        } else if (!ctx_->is_migrate_compat_version() && remote_migrate_replay_log_ts < max_migrate_replay_log_ts) {
          // from 3.1, replay_log_ts is an accurate metric
          is_suitable = false;
        } else if (is_empty_pg) {
          if (remote_last_replay_log_id > max_last_replay_log_id) {
            is_suitable = true;
          }
        } else if (remote_minor_snapshot_version > max_minor_snapshot_version) {
          is_suitable = true;
        } else if (remote_minor_snapshot_version < max_minor_snapshot_version) {
          is_suitable = false;
        } else if (remote_major_snapshot_version > max_major_snapshot_version) {
          is_suitable = true;
        } else if (remote_major_snapshot_version < max_major_snapshot_version) {
          is_suitable = false;
        } else if (remote_last_replay_log_id > max_last_replay_log_id) {
          is_suitable = true;
        } else {  // remote_last_replay_log_id <= max_last_replay_log_id
          is_suitable = false;
        }

#ifdef ERRSIM
        if (OB_SUCC(ret) && !is_suitable) {
          is_suitable = ObServerConfig::get_instance()._ob_enable_rebuild_on_purpose;
        }
#endif
        if (is_suitable) {
          out_result.reset();
          if (OB_FAIL(out_result.assign(tmp_result))) {
            LOG_WARN("fail to assign out result", K(ret), K(tmp_result));
          } else {
            max_minor_snapshot_version = std::max(remote_minor_snapshot_version, max_minor_snapshot_version);
            max_major_snapshot_version = remote_major_snapshot_version;
            max_last_replay_log_id = remote_last_replay_log_id;
            max_migrate_replay_log_ts = remote_migrate_replay_log_ts;
            LOG_INFO("find one candidate src",
                K(src_info),
                K(remote_minor_snapshot_version),
                K(max_minor_snapshot_version),
                K(remote_major_snapshot_version),
                K(remote_last_replay_log_id),
                K(remote_migrate_replay_log_ts));
          }
        } else {
          LOG_INFO("src snapshot version cannot use as src",
              K(src_info),
              K(remote_minor_snapshot_version),
              K(max_minor_snapshot_version),
              K(remote_major_snapshot_version),
              K(max_major_snapshot_version),
              K(remote_last_replay_log_id),
              K(max_last_replay_log_id),
              K(remote_migrate_replay_log_ts),
              K(max_migrate_replay_log_ts),
              K_(ctx_->fetch_pg_info_compat_version));
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::choose_restore_migrate_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  const int64_t compatible = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("restore meta read is NULL", K(ret), KP(ctx_->restore_meta_reader_));
  } else {
    src_info.src_addr_ = arg.data_src_.get_server();
    src_info.cluster_id_ = arg.cluster_id_;
    if (OB_FAIL(ctx_->restore_meta_reader_->fetch_partition_group_meta(pg_meta))) {
      LOG_WARN("fail to fetch partition store meta", K(ret), K(arg));
    } else {
      // TODO() consider compat
      if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
        ctx_->fetch_pg_info_compat_version_ = ObFetchPGInfoArg::FETCH_PG_INFO_ARG_COMPAT_VERSION_V1;
      } else if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
        ctx_->fetch_pg_info_compat_version_ = ObFetchPGInfoArg::FETCH_PG_INFO_ARG_COMPAT_VERSION_V2;
      } else {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("restore compatible version is unexpected", K(ret), K(compatible), "arg", arg);
      }
    }
  }
  if (OB_SUCC(ret)) {
    LOG_INFO("succeed to choose_restore_migrate_src", K(ret), K(arg), K(pg_meta));
  }
  return ret;
}

int ObMigratePrepareTask::choose_phy_restore_follower_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  ObPartitionGroupInfoResult src_result;
  ObMigrateSrcInfo tmp_src_info;
  tmp_src_info.src_addr_ = arg.data_src_.get_server();
  tmp_src_info.cluster_id_ = arg.cluster_id_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(fetch_partition_group_info(arg, tmp_src_info, src_result))) {
    LOG_WARN("failed to fetch partition info", K(ret), K(arg));
  } else if (OB_FAIL(pg_meta.deep_copy(src_result.result_.pg_meta_))) {
    LOG_WARN("Failed to copy pg meta", K(ret));
  } else {
    src_info = tmp_src_info;
    LOG_INFO("succeed to choose_phy_restore_follower src", K(ret), K(arg), K(pg_meta));
  }
  return ret;
}

int ObMigratePrepareTask::choose_backup_migrate_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(ctx_->backup_meta_reader_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "backup meta read is NULL", K(ret), KP(ctx_->backup_meta_reader_));
  } else if (!pg_meta.is_valid()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "backup pg meta is invalid", K(ret), K(pg_meta));
  } else {
    src_info.src_addr_ = arg.data_src_.get_server();
    src_info.cluster_id_ = arg.cluster_id_;
  }
  DEBUG_SYNC(BACKUP_BEFROE_CHOOSE_SRC);
  if (OB_SUCC(ret)) {
    STORAGE_LOG(INFO, "succeed to choose_backup_migrate_src", K(ret), K(arg), K(pg_meta));
  }
  return ret;
}

int ObMigratePrepareTask::choose_standby_restore_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  const int64_t local_cluster_id = GCONF.cluster_id;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (ctx_->replica_op_arg_.cluster_id_ != local_cluster_id &&
             RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_WARN("can not migrate from diff cluster", K(*ctx_), K(local_cluster_id));
  } else if (OB_FAIL(choose_ob_src(is_valid_standby_restore_src, arg, pg_meta, src_info))) {
    LOG_WARN("failed to choose ob src", K(ret), K(arg));
  }
  return ret;
}

int ObMigratePrepareTask::choose_ob_src(
    IsValidSrcFunc is_valid_src, const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  ObPartitionGroupInfoResult data_src_result;
  ObArray<ObMigrateSrcInfo> src_info_array;
  bool find_suitable_src = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(get_minor_src_candidate_with_region(arg, src_info_array))) {
    LOG_WARN("failed to get minor src candidate with region", K(ret), K(arg));
  } else if (!src_info_array.empty()) {
    if (OB_FAIL(get_migrate_suitable_src(src_info_array, arg, is_valid_src, find_suitable_src, pg_meta, src_info))) {
      LOG_WARN("failed to get migrate suitable src", K(ret));
    }
  }

  // rewrite ret
  if (!find_suitable_src) {
    src_info_array.reset();
    if (OB_FAIL(get_minor_src_candidate_without_region(arg, src_info_array))) {
      LOG_WARN("failed to get minor src candidate without region", K(ret), K(arg));
    } else if (src_info_array.empty()) {
      ret = OB_DATA_SOURCE_NOT_EXIST;
      STORAGE_LOG(WARN, "no available src, migrate failed", K(ret), K(arg), K(src_info_array));
    } else if (OB_FAIL(
                   get_migrate_suitable_src(src_info_array, arg, is_valid_src, find_suitable_src, pg_meta, src_info))) {
      LOG_WARN("failed to get migrate suitable src", K(ret));
    }
  }

  if (OB_SUCC(ret) && !find_suitable_src) {
    ret = OB_DATA_SOURCE_NOT_EXIST;
    STORAGE_LOG(WARN, "no available src, migrate failed", K(ret), K(arg), K(src_info_array));
  }
  return ret;
}

int ObMigratePrepareTask::is_valid_migrate_src(
    const obrpc::ObFetchPGInfoResult& result, ObMigrateCtx& ctx, bool& is_valid)
{
  int ret = OB_SUCCESS;
  is_valid = false;
  const ObDataStorageInfo& data_info = result.pg_meta_.storage_info_.get_data_info();
  const ObBaseStorageInfo& clog_info = result.pg_meta_.storage_info_.get_clog_info();
  const ObReplicaType replica_type = ctx.replica_op_arg_.dst_.get_replica_type();
  const int64_t remote_last_replay_log_id = result.pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();
  const int64_t remote_publish_version = data_info.get_publish_version();
  const bool is_empty_pg = result.pg_meta_.partitions_.empty();

  if (!ObReplicaTypeCheck::is_replica_with_memstore(replica_type) &&
      !ObReplicaTypeCheck::is_replica_with_ssstore(replica_type)) {
    is_valid = true;
    LOG_INFO("data is not needed, skip check src valid");
  } else if (data_info.is_created_by_new_minor_freeze() &&
             data_info.get_last_replay_log_ts() < ctx.local_last_replay_log_ts_ &&
             CHANGE_REPLICA_OP != ctx.replica_op_arg_.type_) {
    LOG_INFO("replica with smaller last_replay_log_id is not a valid migrate src",
        "remote last_replay_log_ts",
        data_info.get_last_replay_log_ts(),
        "local last_replay_log_ts",
        ctx.local_last_replay_log_ts_);
  } else if (!can_migrate_src_skip_log_sync(result, ctx) && !result.is_log_sync_) {
    LOG_INFO("src log not sync", K(result));
  } else if (CHANGE_REPLICA_OP == ctx.replica_op_arg_.type_) {
    // no need check last replay log id
    is_valid = true;
  } else if (remote_last_replay_log_id < ctx.local_last_replay_log_id_) {
    LOG_INFO("src last replay log id  must not less than local",
        "remote_last_replay_log_id",
        remote_last_replay_log_id,
        "local_last_replay_log_id",
        ctx.local_last_replay_log_id_);
  } else {
    is_valid = true;
  }

#ifdef ERRSIM
  if (OB_SUCC(ret)) {
    ret = E(EventTable::EN_VALID_MIGRATE_SRC) OB_SUCCESS;
  }
#endif
  return ret;
}

int ObMigratePrepareTask::is_valid_standby_restore_src(
    const obrpc::ObFetchPGInfoResult& result, ObMigrateCtx& ctx, bool& is_valid)
{
  int ret = OB_SUCCESS;
  is_valid = false;
  const ObDataStorageInfo& data_info = result.pg_meta_.storage_info_.get_data_info();
  const ObBaseStorageInfo& clog_info = result.pg_meta_.storage_info_.get_clog_info();
  const ObReplicaType replica_type = ctx.replica_op_arg_.dst_.get_replica_type();
  const int64_t remote_last_replay_log_id = result.pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();

  // TODO() standby cluster need choose data version >= self data version as src
  if (!ObReplicaTypeCheck::is_replica_with_ssstore(result.pg_meta_.replica_type_)) {
    LOG_WARN("src not has ssstore, cannot copy sstable", K(result));
  } else if (REPLICA_NOT_RESTORE != result.pg_meta_.is_restore_) {
    LOG_INFO("data src is doing restore, cannot copy sstable");
  } else if (!ObReplicaTypeCheck::is_replica_with_memstore(replica_type) &&
             !ObReplicaTypeCheck::is_replica_with_ssstore(replica_type)) {
    is_valid = true;
    LOG_INFO("data is not needed, skip check src valid");
  } else if (remote_last_replay_log_id < ctx.local_last_replay_log_id_) {
    LOG_INFO("src last replay log id  must not less than local",
        "remote_last_replay_log_id",
        remote_last_replay_log_id,
        "local_last_replay_log_id",
        ctx.local_last_replay_log_id_);
  } else {
    is_valid = true;
  }

  return ret;
}

int ObMigratePrepareTask::is_valid_rebuild_src(
    const obrpc::ObFetchPGInfoResult& result, ObMigrateCtx& ctx, bool& is_valid)
{
  int ret = OB_SUCCESS;
  is_valid = false;
  const ObReplicaType replica_type = ctx.replica_op_arg_.dst_.get_replica_type();
  const int64_t remote_last_replay_log_id = result.pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();

  if (REBUILD_REPLICA_OP != ctx.replica_op_arg_.type_) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("is valid rebuild src get invalid argument", K(ret), K(ctx));
  } else if (ObReplicaTypeCheck::is_replica_with_ssstore(replica_type) &&
             !ObReplicaTypeCheck::is_replica_with_ssstore(result.pg_meta_.replica_type_)) {
    LOG_WARN("src not has ssstore, cannot copy sstable", K(result));
  } else if (remote_last_replay_log_id <= ctx.local_last_replay_log_id_) {
    LOG_INFO("src last replay log id  must not less than local",
        "remote_last_replay_log_id",
        remote_last_replay_log_id,
        "local_last_replay_log_id",
        ctx.local_last_replay_log_id_);
#ifdef ERRSIM
    is_valid = ObServerConfig::get_instance()._ob_enable_rebuild_on_purpose;
#endif
  } else {
    is_valid = true;
  }
  return ret;
}

bool ObMigratePrepareTask::can_migrate_src_skip_log_sync(const obrpc::ObFetchPGInfoResult& result, ObMigrateCtx& ctx)
{
  bool b_ret = false;

  if (REPLICA_NOT_RESTORE == result.pg_meta_.is_restore_) {
    b_ret = false;
  } else if (ADD_REPLICA_OP == ctx.replica_op_arg_.type_ || MIGRATE_REPLICA_OP == ctx.replica_op_arg_.type_) {
    if (result.pg_meta_.is_restore_ > REPLICA_NOT_RESTORE &&
O
obdev 已提交
6716
        result.pg_meta_.is_restore_ <= REPLICA_RESTORE_MEMBER_LIST) {
O
oceanbase-admin 已提交
6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911
      b_ret = true;
    }
  }
  return b_ret;
}

int ObMigratePrepareTask::build_migrate_pg_partition_info()
{
  int ret = OB_SUCCESS;
  ObIPGPartitionBaseDataMetaObReader* reader = NULL;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
    // do nothing
  } else if (OB_FAIL(get_partition_table_info_reader(ctx_->migrate_src_info_, reader))) {
    LOG_WARN("failed to get partition info reader", K(ret), K(ctx_));
  } else {
    if (COPY_LOCAL_INDEX_OP == ctx_->replica_op_arg_.type_) {
      if (OB_FAIL(build_index_partition_info(ctx_->replica_op_arg_, reader))) {
        LOG_WARN("failed to build index partition info", K(ret), K(ctx_->replica_op_arg_));
      }
    } else {
      if (OB_FAIL(build_table_partition_info(ctx_->replica_op_arg_, reader))) {
        LOG_WARN("failed to build table partition info", K(ret), K(ctx_->replica_op_arg_));
      }
    }
  }

  if (NULL != reader) {
    cp_fty_->free(reader);
  }
  return ret;
}

int ObMigratePrepareTask::build_migrate_partition_info(const ObPGPartitionMetaInfo& partition_meta_info,
    const common::ObIArray<obrpc::ObFetchTableInfoResult>& table_info_res,
    const common::ObIArray<uint64_t>& table_id_list, ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;
  ObArray<ObITable::TableKey> local_tables_info;
  ObMigrateTableInfo table_info;
  int64_t cost_ts = ObTimeUtility::current_time();
  const ObPartitionKey& pkey = partition_meta_info.meta_.pkey_;
  ObMigratePartitionInfo& info = part_migrate_ctx.copy_info_;
  part_migrate_ctx.ctx_ = ctx_;
  DEBUG_SYNC(BEFORE_BUILD_MIGRATE_PARTITION_INFO);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (!partition_meta_info.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("build migrate partition info get invalid argument", K(ret), K(partition_meta_info));
  } else if (OB_FAIL(info.meta_.deep_copy(partition_meta_info.meta_))) {
    LOG_WARN("fail to deep copy partition store meta", K(ret), K(partition_meta_info.meta_));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < table_info_res.count(); ++i) {
      table_info.reuse();
      local_tables_info.reuse();
      const obrpc::ObFetchTableInfoResult& table_res = table_info_res.at(i);
      const uint64_t table_id = table_id_list.at(i);
      LOG_INFO("build_migrate_partition_info for table", "table_id", table_id);

      if (OB_SUCC(ret)) {
        if (OB_FAIL(remove_uncontinue_local_tables(pkey, table_id))) {
          LOG_WARN("failed to remove uncontinue local tables", K(ret), K(pkey), K(table_id));
        } else if (OB_FAIL(get_local_table_info(table_id, pkey, local_tables_info))) {
          LOG_WARN("failed to get local table info", K(ret));
        } else if (OB_FAIL(build_migrate_table_info(
                       table_id, pkey, local_tables_info, table_res, table_info, part_migrate_ctx))) {
          LOG_WARN("failed to build migrate table info", K(ret));
        } else if (OB_FAIL(info.table_id_list_.push_back(table_id))) {
          LOG_WARN("failed to push table id into array", K(ret));
        } else if (OB_FAIL(info.table_infos_.push_back(table_info))) {
          LOG_WARN("failed to add migrate table info", K(ret));
        } else {
          LOG_INFO("add table info", K(table_info));
          if (table_res.multi_version_start_ > info.meta_.multi_version_start_) {
            info.meta_.multi_version_start_ = table_res.multi_version_start_;
            LOG_INFO("update migrate multi version start", K(table_res.multi_version_start_));
          }
        }
      }
    }
  }

  cost_ts = ObTimeUtility::current_time() - cost_ts;
  LOG_INFO("build_migrate_partition_info",
      K(cost_ts),
      "pkey",
      info.meta_.pkey_,
      "src",
      info.src_,
      "table_count",
      info.table_id_list_.count());
  return ret;
}

int ObMigratePrepareTask::get_local_table_info(
    const uint64_t table_id, const ObPartitionKey& pkey, ObIArray<ObITable::TableKey>& local_tables_info)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGPartitionGuard guard;
  ObPGPartition* pg_partition = NULL;
  ObIPartitionStorage* storage = NULL;
  ObTablesHandle handle;
  local_tables_info.reuse();
  bool is_ready_for_read = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (NULL == (partition = ctx_->partition_guard_.get_partition_group())) {
    LOG_INFO("local partition not exist, no thing reuse", K(table_id));
  } else if (OB_FAIL(partition->get_pg_partition(pkey, guard))) {
    if (OB_ENTRY_NOT_EXIST != ret) {
      LOG_WARN("failed to get pg partition", K(ret), K(pkey));
    } else {
      ret = OB_SUCCESS;
    }
  } else if (OB_ISNULL(pg_partition = guard.get_pg_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("pg partition should not be NULL", K(ret), KP(pg_partition), K(pkey));
  } else if (OB_ISNULL(storage = pg_partition->get_storage())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("storage must not null", K(ret), KP(storage));
  } else if (OB_FAIL(static_cast<ObPartitionStorage*>(storage)->get_partition_store().get_migrate_tables(
                 table_id, handle, is_ready_for_read))) {
    LOG_WARN("failed to get effective tables", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < handle.get_count(); ++i) {
      const ObITable* table = handle.get_table(i);
      if (OB_ISNULL(table)) {
        ret = OB_ERR_SYS;
        LOG_ERROR("table must not null", K(ret));
      } else if (table->is_memtable()) {
        ret = OB_ERR_SYS;
        LOG_ERROR("Unexpected local memtable", K(ret), K(i), KPC(table), K(handle));
      } else if (OB_FAIL(local_tables_info.push_back(table->get_key()))) {
        LOG_WARN("failed to add local table info into array", K(ret), K(table->get_key()));
      }
    }
  }

  return ret;
}

int ObMigratePrepareTask::build_migrate_table_info(const uint64_t table_id, const ObPartitionKey& pkey,
    ObIArray<ObITable::TableKey>& local_tables_info, const obrpc::ObFetchTableInfoResult& result,
    ObMigrateTableInfo& info, ObPartitionMigrateCtx& part_ctx)
{
  int ret = OB_SUCCESS;
  ObArray<ObITable::TableKey> remote_major_sstables;
  ObArray<ObITable::TableKey> remote_inc_sstables;
  ObArray<ObITable::TableKey> remote_gc_major_sstables;
  ObArray<ObITable::TableKey> remote_gc_inc_sstables;
  ObArray<ObITable::TableKey> local_major_sstables;
  ObArray<ObITable::TableKey> local_inc_sstables;
  bool& need_reuse_local_minor = part_ctx.need_reuse_local_minor_;
  info.reuse();
  info.table_id_ = table_id;
  // TODO  only use source minor sstable now, consider performance later
  need_reuse_local_minor = false;

  FLOG_INFO("start to build_migrate_table_info",
      K(result),
      K(info),
      K(local_major_sstables),
      K(local_inc_sstables),
      K(remote_gc_major_sstables),
      K(pkey),
      K(table_id),
      K(need_reuse_local_minor));
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(ObTableKeyMgrUtil::classify_mgirate_tables(
                 table_id, local_tables_info, local_major_sstables, local_inc_sstables))) {
    LOG_WARN("failed to classify local migrate tables", K(ret));
  } else if (OB_FAIL(ObTableKeyMgrUtil::classify_mgirate_tables(
                 table_id, result.table_keys_, remote_major_sstables, remote_inc_sstables))) {
    LOG_WARN("failed to classify remote migrate tables", K(ret));
  } else if (OB_FAIL(ObTableKeyMgrUtil::classify_mgirate_tables(
                 table_id, result.gc_table_keys_, remote_gc_major_sstables, remote_gc_inc_sstables))) {
    LOG_WARN("failed to classify remote gc sstables", K(ret));
  } else if (OB_FAIL(check_remote_sstables(table_id, remote_major_sstables, remote_inc_sstables))) {
    LOG_WARN("failed to check remote sstables", K(ret), K(table_id));
  } else if (OB_FAIL(build_migrate_major_sstable(need_reuse_local_minor,
                 local_major_sstables,
                 local_inc_sstables,
                 remote_major_sstables,
                 remote_inc_sstables,
O
obdev 已提交
6912 6913
                 info.major_sstables_,
                 part_ctx))) {
O
oceanbase-admin 已提交
6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105
    LOG_WARN("failed to build migrate major sstable", K(ret));
  } else if (OB_FAIL(build_migrate_minor_sstable(need_reuse_local_minor,
                 local_inc_sstables,
                 remote_inc_sstables,
                 remote_gc_inc_sstables,
                 info.minor_sstables_))) {
    LOG_WARN("failed to build migrate minor sstable", K(ret));
  } else if (OB_FAIL(fill_log_ts_for_compat(info))) {
    LOG_WARN("Failed to fill new log ts fro compat", K(info));
  } else if (OB_FAIL(check_can_reuse_sstable(pkey, info, part_ctx))) {
    LOG_WARN("failed to check can reuse sstable", K(ret));
  }

  if (OB_SUCC(ret)) {
    info.multi_version_start_ = result.multi_version_start_;
    info.ready_for_read_ = result.is_ready_for_read_;
    FLOG_INFO("succeed build_migrate_table_info",
        K(result),
        K(info),
        K(local_major_sstables),
        K(local_inc_sstables),
        K(remote_gc_major_sstables),
        K(pkey),
        K(table_id),
        K(need_reuse_local_minor));
  }
  return ret;
}

int ObMigratePrepareTask::fill_log_ts_for_compat(ObMigrateTableInfo& info)
{
  int ret = OB_SUCCESS;

  if (!ctx_->is_migrate_compat_version()) {
  } else {
    ObTableCompater table_compater;
    if (OB_FAIL(table_compater.add_tables(info.major_sstables_))) {
      STORAGE_LOG(WARN, "Failed to add major sstables for compat", K(ret), K(info.major_sstables_));
    } else if (OB_FAIL(table_compater.add_tables(info.minor_sstables_))) {
      STORAGE_LOG(WARN, "Failed to add minor sstables for compat", K(ret), K(info.minor_sstables_));
    } else if (OB_FAIL(table_compater.fill_log_ts())) {
      STORAGE_LOG(WARN, "Failed to set new log ts for compat", K(ret), K(table_compater));
    } else {
      ctx_->pg_meta_.storage_info_.get_data_info().set_last_replay_log_ts(ObTableCompater::OB_MAX_COMPAT_LOG_TS);
    }
  }

  return ret;
}

int ObMigratePrepareTask::check_remote_sstables(const uint64_t table_id,
    common::ObIArray<ObITable::TableKey>& remote_major_sstables,
    common::ObIArray<ObITable::TableKey>& remote_inc_tables)
{
  int ret = OB_SUCCESS;
  bool need_check_major_sstable = true;
  const share::schema::ObTableSchema* table_schema = NULL;
  share::schema::ObSchemaGetterGuard schema_guard;
  share::schema::ObMultiVersionSchemaService& schema_service =
      share::schema::ObMultiVersionSchemaService::get_instance();
  const uint64_t fetch_tenant_id = is_inner_table(table_id) ? OB_SYS_TENANT_ID : extract_tenant_id(table_id);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (is_trans_table_id(table_id)) {
    need_check_major_sstable = false;
  } else if (OB_FAIL(schema_service.get_tenant_full_schema_guard(fetch_tenant_id, schema_guard))) {
    LOG_WARN("failed to get schema guard", K(ret));
  } else if (OB_FAIL(schema_guard.get_table_schema(table_id, table_schema))) {
    LOG_WARN("Failed to get table schema", K(ret), K(table_id));
  } else if (OB_ISNULL(table_schema)) {
    need_check_major_sstable = false;
    LOG_INFO("table schema is null, skip check major", K(table_id));
  } else if (table_schema->is_index_table() && INDEX_STATUS_AVAILABLE != table_schema->get_index_status()) {
    need_check_major_sstable = false;
    LOG_INFO("index table schema is not available, skip check major", K(table_id));
  } else if (REPLICA_NOT_RESTORE != ctx_->pg_meta_.is_restore_) {
    need_check_major_sstable = false;
    LOG_INFO("table is in restore status, skip check major", K(table_id));
  }

  if (OB_SUCC(ret)) {
    if (remote_major_sstables.empty()) {
      if (need_check_major_sstable) {
        ret = OB_DATA_SOURCE_NOT_VALID;
        LOG_WARN("major remote table not found", K(ret), K(table_id));
      } else if (remote_inc_tables.count() > 0) {
      } else {
        // no logic migrate, allow inc table be empty
      }
    }
  }

  if (OB_SUCC(ret) && remote_inc_tables.count() > 0) {
    if (OB_FAIL(check_remote_inc_sstables_continuity(remote_inc_tables))) {
      LOG_WARN(
          "failed to check remote inc sstables continuity", K(ret), K(remote_major_sstables), K(remote_inc_tables));
    }
  }

  return ret;
}

int ObMigratePrepareTask::check_remote_inc_sstables_continuity(common::ObIArray<ObITable::TableKey>& remote_inc_tables)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_UNLIKELY(remote_inc_tables.empty())) {
    // skip empty inc tables
  } else {
    int64_t last_end_log_ts = remote_inc_tables.at(0).get_start_log_ts();
    for (int64_t i = 0; OB_SUCC(ret) && i < remote_inc_tables.count(); ++i) {
      const ObITable::TableKey& remote_inc_table = remote_inc_tables.at(i);
      if (remote_inc_table.is_complement_minor_sstable()) {
        // skip complement sstable
      } else if (remote_inc_table.get_start_log_ts() != last_end_log_ts) {
        ret = OB_DATA_SOURCE_NOT_VALID;
        LOG_WARN(
            "minor sstables not continue", K(ret), K(i), K(remote_inc_table), K(last_end_log_ts), K(remote_inc_tables));
      } else {
        last_end_log_ts = remote_inc_table.get_end_log_ts();
      }
    }
  }
  return ret;
}

// TODO  only use source minor sstable now, consider performance later
int ObMigratePrepareTask::build_remote_minor_sstables(const common::ObIArray<ObITable::TableKey>& local_minor_sstables,
    const common::ObIArray<ObITable::TableKey>& tmp_remote_minor_sstables,
    const common::ObIArray<ObITable::TableKey>& tmp_remote_gc_minor_sstables,
    common::ObIArray<ObITable::TableKey>& remote_minor_sstables,
    common::ObIArray<ObITable::TableKey>& remote_gc_minor_sstables, bool& need_reuse_local_minor)
{
  return OB_NOT_SUPPORTED;
  int ret = OB_SUCCESS;
  remote_minor_sstables.reuse();
  remote_gc_minor_sstables.reuse();
  need_reuse_local_minor = !ctx_->is_migrate_compat_version();
  if (local_minor_sstables.empty()) {
    if (OB_FAIL(remote_minor_sstables.assign(tmp_remote_minor_sstables))) {
      LOG_WARN("failed to assign tables", K(ret));
    } else if (OB_FAIL(remote_gc_minor_sstables.assign(tmp_remote_gc_minor_sstables))) {
      LOG_WARN("failed to assign tables", K(ret));
    }
  } else if (need_reuse_local_minor) {
    const ObLogTsRange local_last_log_ts_range =
        local_minor_sstables.at(local_minor_sstables.count() - 1).log_ts_range_;
    for (int64_t i = 0; OB_SUCC(ret) && i < tmp_remote_minor_sstables.count(); ++i) {
      const ObITable::TableKey& remote_sstable = tmp_remote_minor_sstables.at(i);
      if (remote_minor_sstables.empty() &&
          remote_sstable.log_ts_range_.start_log_ts_ > local_last_log_ts_range.end_log_ts_) {
        need_reuse_local_minor = false;
        break;
      } else if (remote_sstable.log_ts_range_.end_log_ts_ > local_last_log_ts_range.end_log_ts_) {
        if (OB_FAIL(remote_minor_sstables.push_back(remote_sstable))) {
          LOG_WARN("failed to push back remote sstable", K(ret), K(remote_sstable));
        }
      }
    }
    if (OB_SUCC(ret)) {
      if (!need_reuse_local_minor) {
        if (OB_FAIL(remote_minor_sstables.assign(tmp_remote_minor_sstables))) {
          LOG_WARN("failed to assign remote minor sstable", K(ret), K(tmp_remote_minor_sstables));
        }
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < tmp_remote_gc_minor_sstables.count(); ++i) {
          const ObITable::TableKey& remote_sstable = tmp_remote_gc_minor_sstables.at(i);
          if (remote_sstable.log_ts_range_.end_log_ts_ > local_last_log_ts_range.end_log_ts_) {
            if (OB_FAIL(remote_gc_minor_sstables.push_back(remote_sstable))) {
              LOG_WARN("failed to push back remote sstable", K(ret), K(remote_sstable));
            }
          }
        }
      }
    }
  } else {
    // migrate from compat version, only use remote sstable
    if (OB_FAIL(remote_minor_sstables.assign(tmp_remote_minor_sstables))) {
      LOG_WARN("failed to assign remote minor sstable", K(ret), K(tmp_remote_minor_sstables));
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_migrate_major_sstable(const bool need_reuse_local_minor,
    ObIArray<ObITable::TableKey>& local_major_tables, ObIArray<ObITable::TableKey>& local_inc_tables,
    ObIArray<ObITable::TableKey>& remote_major_tables, ObIArray<ObITable::TableKey>& remote_inc_tables,
O
obdev 已提交
7106
    ObIArray<ObMigrateTableInfo::SSTableInfo>& copy_sstables, ObPartitionMigrateCtx& part_ctx)
O
oceanbase-admin 已提交
7107 7108 7109 7110 7111 7112 7113 7114
{
  int ret = OB_SUCCESS;

  if (OB_FAIL(build_migrate_major_sstable_v2_(need_reuse_local_minor,
          local_major_tables,
          local_inc_tables,
          remote_major_tables,
          remote_inc_tables,
O
obdev 已提交
7115 7116
          copy_sstables,
          part_ctx))) {
O
oceanbase-admin 已提交
7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213
    LOG_WARN("failed to build_migrate_major_sstable", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::build_migrate_major_sstable_(ObIArray<ObITable::TableKey>& local_major_tables,
    ObIArray<ObITable::TableKey>& local_inc_tables, ObIArray<ObITable::TableKey>& remote_major_tables,
    ObIArray<ObITable::TableKey>& remote_inc_tables, ObIArray<ObMigrateTableInfo::SSTableInfo>& copy_sstables)
{
  int ret = OB_SUCCESS;
  // static func, skip check is_inited_
  int64_t local_major_max_snapshot_version = 0;
  int64_t local_inc_max_snapshot_version = 0;
  int64_t local_max_snapshot_version = 0;
  int64_t max_snapshot_version = 0;
  int64_t remote_min_base_version = 0;
  int64_t remote_max_snapshot_version = 0;
  bool local_has_major = false;
  // D type replica major need to consider compaction_interval. Do local compaction when greater than 0, and meanwhile
  // need local major
  const int64_t follower_replica_merge_level = GCONF._follower_replica_merge_level;

  for (int64_t i = 0; i < local_major_tables.count(); ++i) {
    const ObITable::TableKey& local_major_table = local_major_tables.at(i);
    if (ObITable::is_major_sstable(local_major_table.table_type_)) {
      local_has_major = true;
      local_major_max_snapshot_version = local_major_table.trans_version_range_.snapshot_version_;
    }
  }
  if (local_inc_tables.count() > 0) {
    local_inc_max_snapshot_version =
        local_inc_tables.at(local_inc_tables.count() - 1).trans_version_range_.snapshot_version_;
  }
  local_max_snapshot_version = std::max(local_inc_max_snapshot_version, local_major_max_snapshot_version);

  if (remote_inc_tables.count() > 0) {
    remote_min_base_version = remote_inc_tables.at(0).trans_version_range_.base_version_;
    remote_max_snapshot_version =
        remote_inc_tables.at(remote_inc_tables.count() - 1).trans_version_range_.snapshot_version_;
  }

  if (local_max_snapshot_version >= remote_min_base_version) {
    max_snapshot_version = std::max(local_max_snapshot_version, remote_max_snapshot_version);
  } else {
    max_snapshot_version = local_max_snapshot_version;
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < remote_major_tables.count(); ++i) {
    bool use_local = false;
    const ObITable::TableKey& remote_major_table = remote_major_tables.at(i);
    for (int64_t j = 0; OB_SUCC(ret) && j < local_major_tables.count() && !use_local; ++j) {
      if (local_major_tables.at(j) == remote_major_table) {
        use_local = true;
        LOG_INFO("use local major sstable", "table_key", remote_major_table);
      }
    }

    if (OB_SUCC(ret) && !use_local) {
      // check major tables can use minor sstable to merge
      if (local_has_major && max_snapshot_version >= remote_major_table.trans_version_range_.snapshot_version_ &&
          is_follower_d_major_merge(follower_replica_merge_level)) {
        use_local = true;
        LOG_INFO("local table can merge become need major table, no need copy",
            K(local_inc_tables),
            K(remote_inc_tables),
            K(local_major_tables),
            "need table_key",
            remote_major_table);
      }
    }

    if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      use_local = false;
    }
    if (OB_SUCC(ret) && !use_local) {
      ObMigrateTableInfo::SSTableInfo info;
      info.src_table_key_ = remote_major_table;
      info.dest_base_version_ = remote_major_table.trans_version_range_.base_version_;
      info.dest_log_ts_range_ = remote_major_table.log_ts_range_;
      if (OB_FAIL(copy_sstables.push_back(info))) {
        LOG_WARN("failed to add major sstables", K(ret));
      } else {
        ctx_->need_report_checksum_ = true;
        LOG_INFO("use remote major sstable", "table_key", remote_major_table);
      }
    }
  }

  if (OB_SUCC(ret)) {
    FLOG_INFO("build_migrate_major_sstable", K(local_major_tables), K(remote_major_tables), K(copy_sstables));
  }
  return ret;
}

int ObMigratePrepareTask::build_migrate_major_sstable_v2_(const bool need_reuse_local_minor,
    ObIArray<ObITable::TableKey>& local_major_tables, ObIArray<ObITable::TableKey>& local_inc_tables,
    ObIArray<ObITable::TableKey>& remote_major_tables, ObIArray<ObITable::TableKey>& remote_inc_tables,
O
obdev 已提交
7214
    ObIArray<ObMigrateTableInfo::SSTableInfo>& copy_sstables, ObPartitionMigrateCtx& part_ctx)
O
oceanbase-admin 已提交
7215 7216 7217 7218 7219 7220
{
  int ret = OB_SUCCESS;
  int64_t max_snapshot_version = 0;
  UNUSED(local_inc_tables);
  UNUSED(remote_inc_tables);
  UNUSED(need_reuse_local_minor);
O
obdev 已提交
7221
  bool need_add_local_major = false;
O
oceanbase-admin 已提交
7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235

  // D type replica major need to consider compaction_interval. Do local compaction when greater than 0, and meanwhile
  // need local major const int64_t follower_replica_merge_level = GCONF._follower_replica_merge_level;

  for (int64_t i = 0; i < local_major_tables.count(); ++i) {
    const ObITable::TableKey& local_major_table = local_major_tables.at(i);
    if (ObITable::is_major_sstable(local_major_table.table_type_)) {
      max_snapshot_version = local_major_table.get_snapshot_version();
    }
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < remote_major_tables.count(); ++i) {
    const ObITable::TableKey& remote_major_table = remote_major_tables.at(i);
    if (remote_major_table.get_snapshot_version() <= max_snapshot_version && !remote_major_table.is_trans_sstable()) {
O
obdev 已提交
7236
      need_add_local_major = true;
O
oceanbase-admin 已提交
7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250
      continue;
    } else {
      ObMigrateTableInfo::SSTableInfo info;
      info.src_table_key_ = remote_major_table;
      info.dest_base_version_ = remote_major_table.get_base_version();
      info.dest_log_ts_range_ = remote_major_table.log_ts_range_;
      if (OB_FAIL(copy_sstables.push_back(info))) {
        LOG_WARN("failed to push back sstable info", K(ret), K(info));
      } else {
        ctx_->need_report_checksum_ = true;
        LOG_INFO("use remote major sstable", "table_key", remote_major_table);
      }
    }
  }
O
obdev 已提交
7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268

  if (OB_SUCC(ret) && need_add_local_major) {
    ObTableHandle table_handle;
    for (int64_t i = 0; OB_SUCC(ret) && i < local_major_tables.count(); ++i) {
      const ObITable::TableKey& local_major_table = local_major_tables.at(i);
      ObITable* table = NULL;
      table_handle.reset();
      if (OB_FAIL(ObPartitionService::get_instance().acquire_sstable(local_major_table, table_handle))) {
        LOG_WARN("failed to get complete sstable by key", K(ret), K(local_major_table));
      } else if (NULL == (table = table_handle.get_table())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table should not be NULL", K(ret), KP(table));
      } else if (OB_FAIL(part_ctx.add_sstable(*reinterpret_cast<ObSSTable*>(table)))) {
        LOG_WARN("failed to add sstable", K(ret));
      }
    }
  }

O
oceanbase-admin 已提交
7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973
  if (OB_SUCC(ret)) {
    FLOG_INFO("build_migrate_major_sstable",
        K(local_major_tables),
        K(remote_major_tables),
        K(copy_sstables),
        K(need_reuse_local_minor));
  }

  return ret;
}

int ObMigratePrepareTask::get_migrate_suitable_src(const common::ObIArray<ObMigrateSrcInfo>& src_info_array,
    const ObReplicaOpArg& arg, IsValidSrcFunc is_valid_src, bool& find_suitable_src, ObPartitionGroupMeta& pg_meta,
    ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  find_suitable_src = false;
  pg_meta.reset();
  src_info.reset();
  ObPartitionGroupInfoResult data_src_result;
  ObPartitionGroupInfoResult tmp_data_src_result;
  int64_t max_last_replay_log_id = 0;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (src_info_array.empty() || !arg.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("get migrate suitable src get invalid argument", K(ret), K(src_info_array), K(arg));
  } else {
    // skip ret, try all servers
    for (int64_t i = 0; i < src_info_array.count(); ++i) {
      const ObMigrateSrcInfo& tmp_src_info = src_info_array.at(i);
      bool is_src_valid = true;
      int64_t remote_last_replay_log_id = 0;
      tmp_data_src_result.reset();
      if (MYADDR == tmp_src_info.src_addr_) {
        // do nothing
      } else if (OB_FAIL(fetch_partition_group_info(arg, tmp_src_info, tmp_data_src_result))) {
        LOG_WARN("failed to fetch data src result", K(ret), K(arg), K(tmp_src_info));
        ret = OB_SUCCESS;
      } else if (OB_FAIL(is_valid_src(tmp_data_src_result.result_, *ctx_, is_src_valid))) {
        LOG_WARN("Failed to check is valid migrate src", K(ret), K(arg.data_src_), K(tmp_data_src_result));
      } else if (!is_src_valid) {
        STORAGE_LOG(INFO, "migrate src is not suitable, skip it", K(arg), K(tmp_src_info));
      } else if (FALSE_IT(
                     remote_last_replay_log_id =
                         tmp_data_src_result.result_.pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id())) {
      } else if (max_last_replay_log_id <= remote_last_replay_log_id) {
        data_src_result.reset();
        if (OB_FAIL(data_src_result.assign(tmp_data_src_result))) {
          LOG_WARN("failed to assign partition info result", K(ret), K(tmp_data_src_result));
        } else {
          max_last_replay_log_id = remote_last_replay_log_id;
          find_suitable_src = true;
        }
      }
    }

    if (OB_SUCC(ret) && find_suitable_src) {
      if (OB_FAIL(pg_meta.deep_copy(data_src_result.result_.pg_meta_))) {
        LOG_WARN("Failed to copy pg meta", K(ret));
      } else if (OB_FAIL(ctx_->set_is_restore_for_add_replica(pg_meta.is_restore_))) {
        LOG_WARN("Failed to set is restore", K(ret), K(pg_meta));
      } else {
        ctx_->mig_src_file_id_ = data_src_result.result_.pg_file_id_;
        ctx_->fetch_pg_info_compat_version_ = data_src_result.result_.compat_version_;
        src_info = data_src_result.choose_src_info_;
        LOG_INFO("succeed to choose_ob_migrate_src", K(ret), K(arg), K(pg_meta));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_minor_src_candidate_with_region(
    const ObReplicaOpArg& arg, ObIArray<ObMigrateSrcInfo>& src_info_array)
{
  int ret = OB_SUCCESS;
  ObArray<ObMigrateSrcInfo> tmp_info_array;
  ObArray<ObMigrateSrcInfo> same_region_array;
  ObArray<ObMigrateSrcInfo> diff_region_array;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_FAIL(partition_service_->get_migrate_member_list_src(arg.key_, tmp_info_array))) {
    LOG_WARN("failed to get migrate src", K(ret), "pkey", arg.key_);
  } else if (tmp_info_array.empty()) {
    LOG_INFO("migrate meta table src is empty");
  } else if (OB_FAIL(split_candidate_with_region(tmp_info_array, same_region_array, diff_region_array))) {
    LOG_WARN("failed to split candidate with region", K(ret), K(arg));
  } else if (OB_FAIL(src_info_array.assign(same_region_array))) {
    LOG_WARN("failed to assign src info array", K(ret));
  } else {
    LOG_INFO("get minor src with region", K(tmp_info_array), K(same_region_array));
  }
  return ret;
}

int ObMigratePrepareTask::get_minor_src_candidate_without_region(
    const ObReplicaOpArg& arg, common::ObIArray<ObMigrateSrcInfo>& src_info_array)
{
  int ret = OB_SUCCESS;

  src_info_array.reset();
  bool found_recommendable_src = false;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_FAIL(partition_service_->get_migrate_leader_and_parent(arg.key_, src_info_array))) {
    LOG_WARN("failed to get migrate src", K(ret), "pkey", arg.key_);
  }

  // skip get migrate leader and parent ret, overwrite it
  {
    ret = OB_SUCCESS;
    for (int64_t i = 0; i < src_info_array.count() && !found_recommendable_src; ++i) {
      const ObMigrateSrcInfo& src_info = src_info_array.at(i);
      if (arg.data_src_.get_server() == src_info.src_addr_) {
        found_recommendable_src = true;
      }
    }

    if (!found_recommendable_src) {
      ObMigrateSrcInfo recommendable_src_info;
      recommendable_src_info.src_addr_ = arg.data_src_.get_server();
      recommendable_src_info.cluster_id_ = arg.cluster_id_;
      if (OB_FAIL(src_info_array.push_back(recommendable_src_info))) {
        LOG_WARN("failed to push migrate src into array", K(ret), K(recommendable_src_info));
      }
    }
  }

  LOG_INFO("get minor src candidate without region", K(ret), K(src_info_array));
  return ret;
}

int ObMigratePrepareTask::choose_recommendable_src(
    const ObReplicaOpArg& arg, ObPartitionGroupMeta& pg_meta, ObMigrateSrcInfo& src_info)
{
  int ret = OB_SUCCESS;
  ObPartitionGroupInfoResult src_result;
  ObMigrateSrcInfo tmp_src_info;
  tmp_src_info.src_addr_ = arg.data_src_.get_server();
  tmp_src_info.cluster_id_ = arg.cluster_id_;
  bool need_recovery_point = true;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(fetch_partition_group_info(arg, tmp_src_info, src_result))) {
    LOG_WARN("failed to fetch partition info", K(ret), K(arg));
  } else if (ctx_->is_only_copy_sstable()) {
    if (!ObReplicaTypeCheck::is_replica_with_ssstore(src_result.result_.pg_meta_.replica_type_)) {
      ret = OB_DATA_SOURCE_NOT_EXIST;
      LOG_WARN("src not has ssstore, cannot copy sstable", K(src_result));
    } else {
      need_recovery_point = false;
    }
  }

  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(pg_meta.deep_copy(src_result.result_.pg_meta_))) {
    LOG_WARN("Failed to copy pg meta", K(ret));
  } else {
    ctx_->mig_src_file_id_ = src_result.result_.pg_file_id_;
    ctx_->fetch_pg_info_compat_version_ = src_result.result_.compat_version_;
    src_info = tmp_src_info;
    LOG_INFO("succeed to choose_recommendable src", K(ret), K(arg), K(pg_meta));
  }
  return ret;
}

int ObMigratePrepareTask::build_migrate_minor_sstable(const bool need_reuse_local_minor,
    ObIArray<ObITable::TableKey>& local_inc_tables, ObIArray<ObITable::TableKey>& remote_inc_tables,
    ObIArray<ObITable::TableKey>& remote_gc_inc_sstables, ObIArray<ObMigrateTableInfo::SSTableInfo>& copy_sstables)
{
  int ret = OB_SUCCESS;
  // ObITable::Tablekey's table_key.version is mark major version flag which is smaller than copy sstables need to
  // remove remote'version is monotonically increasing continuously, and there is only one minor sstable for each
  // version there are some minor sstables for on version in local
  // TODO() errsim case may not pass
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (ctx_->is_copy_index() || LINK_SHARE_MAJOR_OP == ctx_->replica_op_arg_.type_) {
    // copy index only need major sstable
  } else if (remote_inc_tables.empty()) {
    LOG_INFO("remote inc table is empty, skip it",
        K(copy_sstables),
        K(local_inc_tables),
        K(remote_inc_tables),
        K(remote_gc_inc_sstables));
  } else if (!need_reuse_local_minor) {
    ObMigrateTableInfo::SSTableInfo info;
    for (int64_t i = 0; OB_SUCC(ret) && i < remote_inc_tables.count(); ++i) {
      info.reset();
      const ObITable::TableKey& remote_table = remote_inc_tables.at(i);
      info.src_table_key_ = remote_table;
      info.dest_base_version_ = remote_table.trans_version_range_.base_version_;
      info.dest_log_ts_range_ = remote_table.log_ts_range_;
      if (OB_FAIL(copy_sstables.push_back(info))) {
        LOG_WARN("failed to push back sstable info", K(ret), K(info));
      }
    }
  } else {
    // TODO  reuse local minor with continuous log ts range
    ret = OB_NOT_SUPPORTED;
    LOG_WARN("Reusing local minor sstable within migration is not supported", K(ret));
  }
  if (OB_SUCC(ret)) {
    LOG_INFO("build_migrate_minor_sstable",
        K(copy_sstables),
        K(local_inc_tables),
        K(remote_inc_tables),
        K(remote_gc_inc_sstables));
  }
  return ret;
}

int ObMigratePrepareTask::check_can_reuse_sstable(
    const ObPartitionKey& pkey, ObMigrateTableInfo& table_info, ObPartitionMigrateCtx& part_ctx)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
  } else if (NULL == (ctx_->partition_guard_.get_partition_group())) {
    LOG_INFO("local partition not exist, no thing reuse", K(table_info));
    // skip backup
  } else {
    // check major sstable
    bool is_reuse = false;
    for (int64_t i = table_info.major_sstables_.count() - 1; OB_SUCC(ret) && i >= 0; --i) {
      is_reuse = false;
      if (OB_FAIL(check_and_reuse_sstable(pkey, table_info.major_sstables_.at(i).src_table_key_, is_reuse, part_ctx))) {
        LOG_WARN("failed to check can reuse sstable", K(ret), "table_key", table_info.major_sstables_.at(i));
      } else if (!is_reuse) {
        // do nothing
      } else if (OB_FAIL(table_info.major_sstables_.remove(i))) {
        LOG_WARN("failed to remove reused table", K(ret), "table_key", table_info.major_sstables_.at(i));
      }
    }

    if (OB_SUCC(ret)) {
      // check minor sstable
      for (int64_t i = table_info.minor_sstables_.count() - 1; OB_SUCC(ret) && i >= 0; --i) {
        is_reuse = false;
        ObITable::TableKey table_key;
        if (OB_FAIL(ObDestTableKeyManager::convert_sstable_info_to_table_key(
                table_info.minor_sstables_.at(i), table_key))) {
          LOG_WARN("failed to convert sstable info to table key", K(ret), K(table_info));
        } else if (OB_FAIL(check_and_reuse_sstable(pkey, table_key, is_reuse, part_ctx))) {
          LOG_WARN("failed to check can reuse sstable", K(ret), "table_key", table_key);
        } else if (!is_reuse) {
          // do nothing
        } else if (OB_FAIL(table_info.minor_sstables_.remove(i))) {
          LOG_WARN("failed to remove reused table", K(ret), "table_key", table_key);
        }
      }
    }
  }
  return ret;
}

// for split reuse, because dest pkey may not eqaul to table key's pkey
int ObMigratePrepareTask::check_and_reuse_sstable(
    const ObPartitionKey& pkey, const ObITable::TableKey& table_key, bool& is_reuse, ObPartitionMigrateCtx& part_ctx)
{
  int ret = OB_SUCCESS;
  ObTableHandle table_handle;
  const bool in_slog_trans = false;
  ObITable* table = NULL;
  is_reuse = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (!pkey.is_valid() || !table_key.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("table key is invalid", K(ret), K(pkey), K(table_key));
  } else if (table_key.is_memtable()) {
    LOG_INFO("memtable no need check and reuse, skip it", K(table_key));
  } else if (table_key.is_trans_sstable()) {
    LOG_INFO("trans sstable can not reuse, skip it", K(table_key));
  } else if (!table_key.is_table_log_ts_comparable()) {
    // old minor sstable always need to migrate to fill log ts
    LOG_INFO("old minor sstable can not reuse, skip it", K(table_key));
  } else {
    if (OB_FAIL(ObPartitionService::get_instance().acquire_sstable(table_key, table_handle))) {
      if (OB_ENTRY_NOT_EXIST != ret && OB_PARTITION_NOT_EXIST != ret) {
        LOG_WARN("failed to get complete sstable by key", K(ret), K(table_key));
      } else {
        is_reuse = false;
        ret = OB_SUCCESS;
      }
    } else if (NULL == (table = table_handle.get_table())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("table should not be NULL", K(ret), KP(table));
    } else if (OB_FAIL(part_ctx.add_sstable(*reinterpret_cast<ObSSTable*>(table)))) {
      LOG_WARN("failed to add sstable", K(ret));
    } else {
      is_reuse = true;
      LOG_INFO("table has already been in table mgr", K(table_key));
    }
  }
  return ret;
}

int ObMigratePrepareTask::prepare_new_partition()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObStorageFileHandle file_handle;
  ObPartGroupMigrationTask* group_task = NULL;
  bool has_mark_creating = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (NULL != ctx_->get_partition()) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot prepare new partition for exist partition", K(ret), K(*ctx_), K(ctx_->get_partition()));
  } else if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_PARTITION_NOT_EXIST;
    LOG_ERROR("cannot create new partition for rebuild", K(ret), K(*ctx_));
  } else if (ctx_->is_only_copy_sstable()) {
    ret = OB_PARTITION_NOT_EXIST;
    LOG_WARN("partition not exist, cannot copy only sstable", K(ret));
  } else if (OB_FAIL(OB_SERVER_FILE_MGR.alloc_file(ctx_->replica_op_arg_.key_.get_tenant_id(),
                 common::is_sys_table(ctx_->replica_op_arg_.key_.get_table_id()),
                 file_handle))) {
    STORAGE_LOG(WARN, "fail to alloc file", K(ret));
  } else if (OB_ISNULL(file_handle.get_storage_file())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("storage file is null", K(ret), K(file_handle));
  } else if (OB_UNLIKELY(0 >= (ctx_->mig_dest_file_id_ = file_handle.get_storage_file()->get_file_id()))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid file id", K(ret), K(ctx_->mig_dest_file_id_));
  } else if (OB_FAIL(SLOGGER.begin(OB_LOG_CS_MIGRATE_PARTITION))) {
    STORAGE_LOG(WARN, "fail to begin commit log.", K(ret));
  } else if (OB_FAIL(partition_service_->mark_pg_creating(ctx_->replica_op_arg_.key_))) {
    STORAGE_LOG(WARN, "fail to mark pg creating.", K(ret));
  } else if (FALSE_IT(has_mark_creating = true)) {
  } else if (OB_FAIL(create_new_partition(
                 ctx_->migrate_src_info_.src_addr_, ctx_->replica_op_arg_, ctx_->partition_guard_, file_handle))) {
    STORAGE_LOG(WARN, "failed to create new partition", K(ret));
  } else if (OB_ISNULL(ctx_->get_partition()) || OB_ISNULL(&(ctx_->get_partition()->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition or storage must not null", K(ctx_->get_partition()), K(ret));
  } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx_->group_task_))) {
  } else if (OB_FAIL(group_task->set_create_new_pg(ctx_->get_partition()->get_partition_key()))) {
    LOG_WARN("failed to set create new pg", K(ret));
  } else {
    ctx_->need_offline_ = true;
    ctx_->during_migrating_ = true;
    LOG_INFO("create new partition for migrate, record migrate start", K(ctx_->replica_op_arg_));
  }

  if (OB_FAIL(ret)) {
    // partition_service_->add_new_parititoon must have commit log or abort log
    if (OB_SUCCESS != (tmp_ret = SLOGGER.abort())) {
      STORAGE_LOG(WARN, "fail to abort log.", K(tmp_ret));
    }
  } else if (OB_FAIL(partition_service_->add_new_partition(ctx_->partition_guard_))) {
    STORAGE_LOG(WARN, "add partition to manager failed", K(ctx_->replica_op_arg_), K(ret));
  }
  if (has_mark_creating) {
    partition_service_->mark_pg_created(ctx_->replica_op_arg_.key_);
  }
  if (OB_FAIL(ret) && NULL != ctx_) {
    ctx_->can_rebuild_ = false;
    LOG_WARN("failed during prepare_new_partition, set cannot rebuild", K(ret), K(*ctx_));
  }
  return ret;
}

int ObMigratePrepareTask::generate_tasks_by_type()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition_group = NULL;
  int16_t restore_flag = REPLICA_NOT_RESTORE;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (FALSE_IT(partition_group = ctx_->partition_guard_.get_partition_group())) {
  } else if (OB_NOT_NULL(partition_group) &&
             FALSE_IT(restore_flag = partition_group->get_pg_storage().get_restore_state())) {
  } else if (REPLICA_RESTORE_CUT_DATA == restore_flag &&
             (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ || RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_)) {
    if (OB_FAIL(generate_restore_cut_prepare_task())) {
      LOG_WARN("failed to generate restore cut prepare task", K(ret), K(*ctx_));
    }
  } else {
    if (OB_FAIL(generate_migrate_prepare_task())) {
      LOG_WARN("failed to generate migrate prepare task", K(ret), K(*ctx_));
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_migrate_prepare_task()
{
  int ret = OB_SUCCESS;
  ObITask* last_task = nullptr;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(prepare_migrate())) {
    LOG_WARN("failed to prepare migrate", K(ret));
  } else if (OB_FAIL(generate_trans_table_migrate_task(last_task))) {
    LOG_WARN("failed to generate trans table migrate task", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_ISNULL(last_task)) {
    ret = OB_ERR_SYS;
    LOG_WARN("last task can not be null", K(ret));
  } else if (OB_FAIL(generate_post_prepare_task(*last_task))) {
    LOG_WARN("failed to generate_post_prepare_task", K(ret), "arg", ctx_->replica_op_arg_);
  }
  return ret;
}

int ObMigratePrepareTask::generate_restore_cut_prepare_task()
{
  int ret = OB_SUCCESS;
  ObRestoreTailoredPrepareTask* task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(dag_->alloc_task(task))) {
    LOG_WARN("failed to alloc dag task", K(ret), K(*ctx_));
  } else if (OB_FAIL(task->init())) {
    LOG_WARN("failed to init restore tailored pepare task", K(ret), K(*ctx_));
  } else if (OB_FAIL(this->add_child(*task))) {
    LOG_WARN("failed to add child task", K(ret), K(*ctx_));
  } else if (OB_FAIL(dag_->add_task(*task))) {
    LOG_WARN("failed to add task to dag", K(ret), K(*ctx_));
  }
  return ret;
}

int ObMigrateUtil::enable_replay_with_new_partition(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;

  LOG_INFO("enable_replay_with_new_partition");
  if (OB_ISNULL(partition = ctx.get_partition())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition should not be null", K(ret));
  } else if (OB_FAIL(partition->create_memtable())) {
    LOG_WARN("failed to create memtable", K(ret), "pkey", partition->get_partition_key());
  } else if (OB_FAIL(ObPartitionService::get_instance().log_new_partition(
                 partition, ctx.pg_meta_.storage_info_.get_data_info().get_publish_version()))) {
    STORAGE_LOG(WARN, "add partition to manager failed", K(ctx.replica_op_arg_), K(ret));
  }

  if (OB_SUCC(ret)) {
    if (ADD_REPLICA_OP == ctx.replica_op_arg_.type_ &&
        (REPLICA_RESTORE_DATA == ctx.is_restore_ || REPLICA_RESTORE_ARCHIVE_DATA == ctx.is_restore_ ||
            REPLICA_RESTORE_STANDBY == ctx.is_restore_)) {
      ctx.need_offline_ = false;
      LOG_INFO("no need set clog online for add replica during restore",
          "pkey",
          ctx.replica_op_arg_.key_,
          "restore_state",
          ctx.is_restore_);
    } else if (OB_FAIL(partition->get_log_service()->set_online(
                   ctx.pg_meta_.storage_info_.get_clog_info(), ObVersion(0, 0) /*freeze version*/))) {
      STORAGE_LOG(WARN, "failed to set clog online", K(ret), K(ctx));
    } else if (OB_FAIL(partition->report_clog_history_online())) {
      LOG_WARN("failed to report clog history", K(ret));
    } else {
      STORAGE_LOG(INFO, "succeed to enable replay for new partition", K(ctx.pg_meta_.storage_info_));
    }
  }

  if (OB_FAIL(ret)) {
    ctx.can_rebuild_ = false;
    LOG_WARN("failed during enable_replay_with_new_partition, set cannot rebuild", K(ret), K(ctx));
  }
  return ret;
}

int ObMigratePostPrepareTask::deal_with_old_partition()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  clog::ObIPartitionLogService* pls = NULL;
  const bool write_slog = true;
  bool is_log_sync = false;

  LOG_INFO("start enable replay");
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else if (NULL == (pls = partition->get_log_service())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Unexpected error, pls is NULL, ", K(ret), KP(pls));
  } else if (OB_FAIL(pls->is_log_sync_with_leader(is_log_sync))) {
    LOG_WARN("failed to get log is in sync", K(ret));
  } else if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot enable_replay_with_old_partition for rebuild", K(ret), K(*ctx_));
  } else {
    bool is_replica_with_data = true;
    common::ObReplicaType replica_type = ctx_->replica_op_arg_.dst_.get_replica_type();
    common::ObReplicaType local_replica_type = partition->get_replica_type();
    const ObReplicaProperty& local_replica_property = partition->get_replica_property();
    ctx_->need_offline_ = true;
    const ObPartitionSplitInfo& split_info = ctx_->pg_meta_.split_info_;
    if (split_info.is_valid() && OB_FAIL(partition->save_split_info(split_info))) {
      LOG_WARN("failed to save split info", K(ret), K(split_info), K(*ctx_));
    } else if (OB_FAIL(update_multi_version_start())) {
      LOG_WARN("failed to update multi version start", K(ret), K(*ctx_));
    } else if (local_replica_type != replica_type &&
               !ObReplicaTypeCheck::change_replica_op_allow(local_replica_type, replica_type)) {
      ret = OB_OP_NOT_ALLOW;
      STORAGE_LOG(WARN, "change replica op not allow", K(ret), K(local_replica_type), K(replica_type), K(*ctx_));
    } else if (ctx_->replica_op_arg_.is_physical_restore()) {
      if (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ &&
          RESTORE_FOLLOWER_REPLICA_OP != ctx_->replica_op_arg_.type_) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN(
            "replica op type is not restore or follower restore or standby restore", K(ret), K(ctx_->replica_op_arg_));
      } else {
        ctx_->need_offline_ = false;
        if (OB_FAIL(partition->set_replica_type(replica_type, write_slog))) {
          LOG_WARN("Failed to set replica type", K(ret), K(ctx_->replica_op_arg_));
        } else {
          ctx_->during_migrating_ = true;
          LOG_INFO("record migrate start", K(ctx_->replica_op_arg_));
        }
      }
    } else if (is_log_sync &&
               (0 != local_replica_property.get_memstore_percent() ||
                   (0 == local_replica_property.get_memstore_percent() &&
                       ObReplicaTypeCheck::is_replica_with_memstore(local_replica_type))) &&
               (OB_NORMAL_REPLICA == ctx_->replica_state_ || OB_RESTORE_REPLICA == ctx_->replica_state_) &&
               ADD_REPLICA_OP != ctx_->replica_op_arg_.type_ && MIGRATE_REPLICA_OP != ctx_->replica_op_arg_.type_ &&
               FAST_MIGRATE_REPLICA_OP != ctx_->replica_op_arg_.type_) {
      ctx_->need_offline_ = false;
      LOG_INFO("reuse memtable", K(ctx_->replica_op_arg_), K(is_log_sync));
      if (OB_FAIL(partition->set_replica_type(replica_type, write_slog))) {
        LOG_WARN("Failed to set replica type", K(ret), K(ctx_->replica_op_arg_));
      } else {
        ctx_->during_migrating_ = true;
        LOG_INFO("record migrate start", K(ctx_->replica_op_arg_));
      }
    } else if (ctx_->is_only_copy_sstable()) {
      ret = OB_LOG_NOT_SYNC;
      LOG_WARN("log is not sync, cannot copy only sstable now", K(ret), K(is_log_sync), K(*ctx_));
    } else if (OB_FAIL(ctx_->change_replica_with_data(is_replica_with_data))) {
      LOG_WARN("failed to check replica", K(ret), K(*ctx_));
    } else if (is_replica_with_data) {
      ret = OB_LOG_NOT_SYNC;
      LOG_WARN("log is not sync, cannot change replica now", K(is_log_sync), K(*ctx_));
    } else if (OB_FAIL(partition->set_replica_type(replica_type, write_slog))) {
      LOG_WARN("Failed to set replica type", K(ret), K(ctx_->replica_op_arg_));
    } else {
      ctx_->during_migrating_ = true;
      LOG_INFO("record migrate start", K(ctx_->replica_op_arg_));

      if (OB_FAIL(partition->pause())) {
        LOG_WARN("failed to pause partition", K(ret));
      }
    }
  }
  return ret;
}

int ObMigrateUtil::enable_replay_with_old_partition(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;

  LOG_INFO("start enable replay");
  if (!ctx.is_valid()) {
    ret = OB_NOT_INIT;
    LOG_ERROR("ctx not valid", K(ret), K(ctx));
  } else if (OB_ISNULL(partition = ctx.get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else {
    int64_t retry_times = 0;
    ObPartitionGroupMeta& meta = ctx.pg_meta_;
    ObBaseStorageInfo& clog_info = meta.storage_info_.get_clog_info();
    ObDataStorageInfo& data_info = meta.storage_info_.get_data_info();
    int64_t restore_snapshot_version = meta.restore_snapshot_version_;
    uint64_t last_restore_log_id = meta.last_restore_log_id_;

    const int64_t local_last_replay_log_id = partition->get_log_service()->get_next_index_log_id() - 1;
    const int64_t src_last_replay_log_id =
        std::max(clog_info.get_last_replay_log_id(), data_info.get_last_replay_log_id());
    if (src_last_replay_log_id <= local_last_replay_log_id && REBUILD_REPLICA_OP == ctx.replica_op_arg_.type_ &&
        partition->get_pg_storage().is_replica_with_remote_memstore()) {
      if (OB_FAIL(partition->set_storage_info(meta.storage_info_))) {
        LOG_WARN("failed to set storage info for migration", K(ret), "pkey", partition->get_partition_key());
      }
      LOG_INFO("local last replay log id is new enough, no need offline and online pg",
          K(local_last_replay_log_id),
          K(src_last_replay_log_id));
    } else {
      while (OB_SUCC(ret) && retry_times < OB_MIGRATE_ONLINE_RETRY_COUNT) {
        if (OB_FAIL(partition->pause())) {
          LOG_WARN("failed to pause partition", K(ret), "pkey", partition->get_partition_key());
        } else if (OB_FAIL(partition->set_storage_info(meta.storage_info_))) {
          LOG_WARN("failed to set storage info", K(ret), "pkey", partition->get_partition_key());
        } else if (OB_FAIL(partition->create_memtable())) {
          LOG_WARN("failed to create memtable", K(ret), "pkey", partition->get_partition_key());
        } else if (OB_FAIL(ctx.get_partition()->get_log_service()->migrate_set_base_storage_info(clog_info))) {
          STORAGE_LOG(WARN, "reset clog start point fail", K(ret), K(meta.storage_info_));
        } else if (OB_FAIL(MIGRATOR.get_partition_service()->online_partition(ctx.replica_op_arg_.key_,
                       data_info.get_publish_version(),
                       restore_snapshot_version,
                       last_restore_log_id))) {
          STORAGE_LOG(WARN, "online partition failed", K(ctx.replica_op_arg_), K(meta), K(ret));
        } else if (OB_PERMANENT_OFFLINE_REPLICA == ctx.replica_state_ &&
                   F_WORKING != ctx.get_partition()->get_partition_state() &&
                   OB_FAIL(ctx.get_partition()->switch_partition_state(F_WORKING))) {
          STORAGE_LOG(WARN, "partition set partition state F_WORKING failed", K(ctx.replica_op_arg_.key_), K(ret));
        }
        ++retry_times;
        if (OB_FAIL(ret) && retry_times < OB_MIGRATE_ONLINE_RETRY_COUNT) {
          ret = OB_SUCCESS;
          usleep(RETRY_TASK_SLEEP_INTERVAL_S);
        } else {
          STORAGE_LOG(INFO, "online partition finish", K(ret), K(ctx.replica_op_arg_.key_), K(meta.storage_info_));
          break;
        }
      }

      if (OB_SUCC(ret)) {
        if (OB_FAIL(ctx.get_partition()->get_log_service()->restore_replayed_log(clog_info))) {
          STORAGE_LOG(WARN, "restore and replay log failed.", K(ret), K_(ctx.replica_op_arg_.key), K(meta));
        } else if (OB_FAIL(ctx.get_partition()->get_log_service()->set_online(
                       clog_info, ObVersion(0, 0) /*freeze version*/))) {
          STORAGE_LOG(WARN, "reset log temporary status failed.", K(ret), K_(ctx.replica_op_arg_.key), K(meta));
        } else if (OB_FAIL(ctx.get_partition()->report_clog_history_online())) {
          LOG_WARN("failed to report clog history online", K(ret));
        } else {
          STORAGE_LOG(INFO, "succeed to enable replay for exist partition");
        }
      }
    }
  }

  return ret;
}

int ObMigrateUtil::push_reference_tables_if_need(
    ObMigrateCtx& ctx, const ObPartitionSplitInfo& split_info, const int64_t last_replay_log_id)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  if (!ctx.is_valid()) {
    ret = OB_NOT_INIT;
    LOG_ERROR("ctx not valid", K(ret), K(ctx));
  } else if (OB_ISNULL(partition = ctx.get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else {
    ObPartitionGroupMeta& meta = ctx.pg_meta_;
    if (split_info.get_src_partition() == meta.pg_key_) {
      const int64_t source_log_id = split_info.get_source_log_id();
      if (last_replay_log_id >= source_log_id && OB_INVALID_ID != source_log_id) {
        if (OB_FAIL(
                partition->push_reference_tables(split_info.get_dest_partitions(), split_info.get_split_version()))) {
          LOG_WARN("failed to push reference tables", K(split_info));
        }
      }
    }
  }

  return ret;
}

int ObMigrateUtil::merge_trans_table(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* pg = nullptr;
  ObSSTable* trans_sstable = nullptr;
  ObPartitionKey pg_key;
  bool is_replica_with_data = false;

  if (OB_ISNULL(trans_sstable = static_cast<ObSSTable*>(ctx.trans_table_handle_.get_table()))) {
    FLOG_INFO("trans sstable is empty", K(ret), K(ctx));
    if (need_migrate_trans_table(ctx.replica_op_arg_.type_) && ctx.is_migrate_compat_version()) {
      if (OB_FAIL(ObMigrateUtil::create_empty_trans_sstable_for_compat(ctx))) {
        LOG_WARN("failed to create empty trans sstable for compat", K(ret), K(ctx));
      }
    } else if (LINK_SHARE_MAJOR_OP == ctx.replica_op_arg_.type_) {
      ctx.old_trans_table_seq_ = ctx.get_partition()->get_pg_storage().get_trans_table_seq();
    }
  } else if (OB_FAIL(wait_trans_table_merge_finish(ctx))) {
    LOG_WARN("failed to wait trans table merge finish", K(ret), K(ctx));
  } else if (OB_ISNULL(pg = ctx.get_partition())) {
    ret = OB_ERR_SYS;
    LOG_WARN("partition group must not null", K(ret));
  } else if (FALSE_IT(pg_key = pg->get_partition_key())) {
O
obdev 已提交
7974 7975 7976 7977 7978 7979 7980 7981
  } else if (FALSE_IT(ctx.old_trans_table_seq_ = pg->get_pg_storage().get_trans_table_seq())) {
  } else if (OB_FAIL(
                 ObMigrateUtil::add_trans_sstable_to_part_ctx(trans_sstable->get_key().pkey_, *trans_sstable, ctx))) {
    LOG_WARN("failed to add trans sstable to part migrate ctx", K(ret), KPC(trans_sstable));
  }
  // TODO() need reconsider sstable reuse, now skip trans sstable reuse
  /*
  else {
O
oceanbase-admin 已提交
7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000
    ObTransTableMergeTask merge_task;
    ObMacroBlockWriter writer;
    ObTableHandle new_trans_sstable;
    ObSSTable* new_sstable = nullptr;
    ctx.old_trans_table_seq_ = pg->get_pg_storage().get_trans_table_seq();
    if (OB_FAIL(merge_task.init(pg_key, trans_sstable))) {
      LOG_WARN("failed to init merge task", K(ret), K(pg_key));
    } else if (OB_FAIL(merge_task.init_schema_and_writer(writer))) {
      LOG_WARN("failed to init schema and writer", K(ret), K(pg_key));
    } else if (OB_FAIL(merge_task.merge_trans_table(writer))) {
      LOG_WARN("failed to merge trans table", K(ret), K(pg_key));
    } else if (OB_FAIL(merge_task.get_merged_trans_sstable(new_trans_sstable, writer))) {
      LOG_WARN("failed to get merged trans sstable", K(ret), K(pg_key));
    } else if (OB_FAIL(new_trans_sstable.get_sstable(new_sstable))) {
      LOG_WARN("failed to get new trans sstable", K(ret), K(pg_key));
    } else if (OB_FAIL(ObMigrateUtil::add_trans_sstable_to_part_ctx(new_sstable->get_key().pkey_, *new_sstable, ctx))) {
      LOG_WARN("failed to add trans sstable to part migrate ctx", K(ret), KPC(new_sstable));
    }
  }
O
obdev 已提交
8001
  */
O
oceanbase-admin 已提交
8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114
  return ret;
}

int ObMigrateUtil::create_empty_trans_sstable_for_compat(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  ObTableSchema table_schema;
  ObPartitionKey trans_table_pkey;
  const int64_t SCHEMA_VERSION = 1;
  if (OB_FAIL(trans_table_pkey.generate_trans_table_pkey(ctx.pg_meta_.pg_key_))) {
    LOG_WARN("failed to generate trans table pkey", K(ret), K(ctx));
  } else if (OB_FAIL(
                 table_schema.generate_kv_schema(trans_table_pkey.get_tenant_id(), trans_table_pkey.get_table_id()))) {
    LOG_WARN("failed to generate trans table schema", K(ret), K(trans_table_pkey));
  } else {
    ObCreateSSTableParamWithTable param;
    ObITable::TableKey table_key;
    ObSSTable* sstable = nullptr;
    ObTableHandle table_handle;

    table_key.table_type_ = ObITable::TableType::TRANS_SSTABLE;
    table_key.table_id_ = trans_table_pkey.get_table_id();
    table_key.trans_version_range_.multi_version_start_ = 0;
    table_key.trans_version_range_.base_version_ = 0;
    table_key.trans_version_range_.snapshot_version_ = ObTimeUtility::current_time();
    table_key.log_ts_range_.start_log_ts_ = 0;
    table_key.log_ts_range_.end_log_ts_ = ctx.pg_meta_.storage_info_.get_data_info().get_last_replay_log_ts();
    table_key.log_ts_range_.max_log_ts_ = table_key.log_ts_range_.end_log_ts_;
    table_key.pkey_ = trans_table_pkey;

    param.table_key_ = table_key;
    param.schema_ = &table_schema;
    param.schema_version_ = SCHEMA_VERSION;
    param.logical_data_version_ = table_key.version_ + 1;
    ObPGCreateSSTableParam pg_create_sstable_param;
    pg_create_sstable_param.with_table_param_ = &param;
    if (OB_FAIL(ctx.get_partition()->create_sstable(pg_create_sstable_param, table_handle))) {
      LOG_WARN("fail to create sstable", K(ret));
    } else if (OB_FAIL(table_handle.get_sstable(sstable))) {
      LOG_WARN("failed to get sstable", K(ret), K(table_handle));
    } else if (OB_ISNULL(sstable)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("sstable should not be null", K(ret));
    } else if (OB_FAIL(ObMigrateUtil::add_trans_sstable_to_part_ctx(trans_table_pkey, *sstable, ctx))) {
      LOG_WARN("failed to add trans sstable to part ctx", K(ret), K(trans_table_pkey));
    } else {
      ctx.old_trans_table_seq_ = ctx.get_partition()->get_pg_storage().get_trans_table_seq();
    }
  }
  return ret;
}

int ObMigrateUtil::add_trans_sstable_to_part_ctx(
    const ObPartitionKey& trans_table_pkey, ObSSTable& sstable, ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  bool found = false;
  for (int64_t i = 0; OB_SUCC(ret) && i < ctx.part_ctx_array_.count(); ++i) {
    ObPartitionMigrateCtx& part_ctx = ctx.part_ctx_array_.at(i);
    if (part_ctx.copy_info_.meta_.pkey_.is_trans_table()) {
      if (OB_FAIL(part_ctx.add_sstable(sstable))) {
        LOG_WARN("failed to add new trans sstable to partition migrate ctx", K(ret), K(trans_table_pkey));
      } else {
        FLOG_INFO("succeed to add trans sstable to partition migrate ctx", K(ret), K(sstable));
      }
      found = true;
      break;
    }
  }
  if (OB_SUCC(ret) && !found) {
    ObPartitionMigrateCtx part_ctx;
    part_ctx.copy_info_.meta_.pkey_ = trans_table_pkey;
    part_ctx.copy_info_.meta_.multi_version_start_ = 1;
    part_ctx.copy_info_.meta_.create_timestamp_ = ObTimeUtility::current_time();
    part_ctx.is_partition_exist_ = false;
    part_ctx.need_reuse_local_minor_ = false;
    part_ctx.ctx_ = &ctx;
    if (OB_FAIL(part_ctx.add_sstable(sstable))) {
      LOG_WARN("failed to add sstable to partition ctx", K(ret), K(sstable));
    } else if (OB_FAIL(ctx.part_ctx_array_.push_back(part_ctx))) {
      LOG_WARN("failed to push back migrate partition ctx", K(ret), K(trans_table_pkey));
    }
  }
  return ret;
}

int ObMigratePostPrepareTask::deal_with_rebuild_partition()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  common::ObAddr leader;
  ctx_->need_offline_ = true;
  ObRole role;
  LOG_INFO("start deal_with_rebuild_partition");

  if (NULL != ctx_) {
    FLOG_INFO("rebuild is start", "pkey", ctx_->replica_op_arg_.key_);
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (REBUILD_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("replica op is  not rebuild op", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else if (OB_FAIL(partition->get_leader(leader))) {
    LOG_WARN("failed to get leader", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_FAIL(partition->get_role(role))) {
    LOG_WARN("failed to get real role", K(ret), "arg", ctx_->replica_op_arg_);
R
rl0 已提交
8115 8116 8117
  } else if (leader.is_valid() && leader == MYADDR
      // support rebuild in leader reconfirm
      && is_strong_leader(role)) {
O
oceanbase-admin 已提交
8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440
    if (OB_FAIL(MIGRATOR.get_partition_service()->turn_off_rebuild_flag(ctx_->replica_op_arg_))) {
      LOG_WARN("Failed to report_rebuild_replica off", K(ret), "arg", ctx_->replica_op_arg_);
    } else {
      ret = OB_NO_NEED_REBUILD;
      LOG_WARN("leader can not as rebuild dst", K(ret), K(leader), "myaddr", MYADDR, "arg", ctx_->replica_op_arg_);
    }
  } else {
    ObBaseStorageInfo& remote_clog_info = ctx_->pg_meta_.storage_info_.get_clog_info();
    const ObPartitionSplitInfo& split_info = ctx_->pg_meta_.split_info_;
    const int64_t local_max_confirm_log_id = partition->get_log_service()->get_next_index_log_id() - 1;
    const int64_t src_last_replay_log_id = remote_clog_info.get_last_replay_log_id();
    const bool is_replica_with_remote_memstore = partition->get_pg_storage().is_replica_with_remote_memstore();
    bool skip_log_id_check = false;

#ifdef ERRSIM
    skip_log_id_check = ObServerConfig::get_instance()._ob_enable_rebuild_on_purpose;
#endif

    if (OB_FAIL(ret)) {
    } else if (src_last_replay_log_id <= local_max_confirm_log_id && !is_replica_with_remote_memstore &&
               !skip_log_id_check) {
      ret = OB_NO_NEED_REBUILD;
      LOG_WARN("local log id is new enough , no need to rebuild, will turn off rebuild flag",
          K(ret),
          K(src_last_replay_log_id),
          K(local_max_confirm_log_id),
          K(remote_clog_info));
      if (OB_SUCCESS != (tmp_ret = partition_service_->turn_off_rebuild_flag(ctx_->replica_op_arg_))) {
        LOG_WARN("Failed to report_rebuild_replica off", K(tmp_ret), "arg", ctx_->replica_op_arg_);
      }
    } else if (OB_FAIL(update_multi_version_start())) {
      LOG_WARN("failed to update multi version start", K(ret), K(*ctx_));
    } else if (split_info.is_valid() && OB_FAIL(partition->save_split_info(split_info))) {
      LOG_WARN("failed to save split info", K(ret), K(split_info), K(*ctx_));
    } else {
      ctx_->during_migrating_ = true;
      if (!is_replica_with_remote_memstore) {
        ctx_->need_online_for_rebuild_ = true;
        if (OB_FAIL(partition->pause())) {
          LOG_WARN("failed to pause partition", K(ret), "pkey", partition->get_partition_key());
        } else if (is_standby_leader(role)) {
          uint64_t unused_log_id = OB_INVALID_ID;
          ObBaseStorageInfo clog_info;
          if (OB_FAIL(partition->get_log_service()->get_base_storage_info(clog_info, unused_log_id))) {
            LOG_WARN("failed to get base storage info", K(ret));
          } else if (OB_FAIL(remote_clog_info.standby_force_update_member_list(clog_info.get_membership_log_id(),
                         clog_info.get_membership_timestamp(),
                         clog_info.get_replica_num(),
                         clog_info.get_curr_member_list(),
                         clog_info.get_ms_proposal_id()))) {
            LOG_WARN("failed to update restore standby member list", K(ret), K(clog_info), K(remote_clog_info));
          }
        }

        if (OB_SUCC(ret)) {
          LOG_INFO("succeed to offline_rebuild_partition",
              K(leader),
              "arg",
              ctx_->replica_op_arg_,
              K(src_last_replay_log_id),
              K(local_max_confirm_log_id));
        }
      } else {
        LOG_INFO("succeed to deal_with_replica using remote memestore replica",
            K(leader),
            "arg",
            ctx_->replica_op_arg_,
            K(src_last_replay_log_id),
            K(local_max_confirm_log_id));
      }
    }
  }
  return ret;
}

int ObMigratePostPrepareTask::deal_with_standby_restore_partition()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;

  LOG_INFO("start deal_with_standby restore_partition");

  if (NULL != ctx_) {
    FLOG_INFO("standby restore is start", "pkey", ctx_->replica_op_arg_.key_);
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (RESTORE_STANDBY_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("replica op is  not standby restore op", K(ret), "arg", ctx_->replica_op_arg_);
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else {
    ObBaseStorageInfo& remote_clog_info = ctx_->pg_meta_.storage_info_.get_clog_info();
    uint64_t unused_log_id = OB_INVALID_ID;
    ObBaseStorageInfo clog_info;
    if (OB_FAIL(partition->get_log_service()->get_base_storage_info(clog_info, unused_log_id))) {
      LOG_WARN("failed to get base storage info", K(ret));
    } else if (OB_FAIL(update_multi_version_start())) {
      LOG_WARN("failed to update multi version start", K(ret), K(*ctx_));
    } else if (OB_FAIL(partition->get_log_service()->set_offline())) {
      LOG_WARN("failed to offline log service", K(ret));
    } else if (OB_FAIL(remote_clog_info.standby_force_update_member_list(clog_info.get_membership_log_id(),
                   clog_info.get_membership_timestamp(),
                   clog_info.get_replica_num(),
                   clog_info.get_curr_member_list(),
                   clog_info.get_ms_proposal_id()))) {
      LOG_WARN("failed to update restore standby member list", K(ret), K(clog_info), K(remote_clog_info));
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_pg_validate_tasks(ObIArray<ObITask*>& last_task_array)
{
  int ret = OB_SUCCESS;
  ObITask* last_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (VALIDATE_BACKUP_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("unexpected op type, ", K(ret), K(ctx_->replica_op_arg_.type_));
  } else if (OB_FAIL(generate_validate_tasks(last_task))) {
    LOG_WARN("failed to generate validate tasks", K(ret));
  } else if (OB_FAIL(last_task_array.push_back(last_task))) {
    LOG_WARN("failed to push last task into last task array", K(ret));
    ;
  }
  return ret;
}

int ObMigratePrepareTask::generate_validate_tasks(ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_validate_finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(generate_wait_migrate_finish_task(wait_validate_finish_task))) {
    LOG_WARN("failed to generate_wait_migrate_finish_task", K(ret));
  } else if (OB_ISNULL(wait_validate_finish_task)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("wait_validate_finsh_task must not be NULL", K(ret));
  } else if (OB_FAIL(generate_validate_tasks(*wait_validate_finish_task))) {
    LOG_WARN("failed to generate_validate_tasks", K(ret));
  }

  if (OB_SUCC(ret)) {
    last_task = wait_validate_finish_task;
  }
  return ret;
}

int ObMigratePrepareTask::generate_validate_tasks(ObFakeTask& wait_validate_finish_task)
{
  int ret = OB_SUCCESS;
  ObITask* parent_task = this;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(generate_validate_backup_tasks(parent_task))) {
    LOG_WARN("failed to generate validate backup tasks", K(ret));
  } else if (OB_FAIL(parent_task->add_child(wait_validate_finish_task))) {
    LOG_WARN("failed to add wait_validate_finish_task", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_validate_backup_tasks(share::ObITask*& parent_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_finish_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_ISNULL(parent_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret), KP(parent_task));
  } else if (OB_FAIL(dag_->alloc_task(wait_finish_task))) {
    LOG_WARN("failed to alloc wait finish task", K(ret));
  } else if (OB_FAIL(generate_validate_backup_task(parent_task, wait_finish_task))) {
    LOG_WARN("failed to generate validate backup task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*wait_finish_task))) {
    LOG_WARN("failed to add wait finish task", K(ret));
  } else {
    parent_task = wait_finish_task;
    LOG_DEBUG("succeed to generate_validate_backup_tasks");
  }
  return ret;
}

int ObMigratePrepareTask::generate_validate_backup_task(share::ObITask* parent_task, share::ObITask* child_task)
{
  int ret = OB_SUCCESS;
  const int64_t task_idx = 0;
  const int64_t clog_file_id = 1;
  ObValidatePrepareTask* prepare_task = NULL;
  ObValidateClogDataTask* clog_task = NULL;
  ObValidateBaseDataTask* base_task = NULL;
  ObValidateFinishTask* finish_task = NULL;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(parent_task), KP(child_task));
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc finish task", K(ret));
  } else if (OB_FAIL(build_validate_backup_ctx(finish_task->get_validate_ctx()))) {
    LOG_WARN("failed to build validate backup ctx", K(ret));
  } else if (OB_FAIL(finish_task->init(*ctx_))) {
    LOG_WARN("failed to init finish task", K(ret));
  } else if (OB_FAIL(finish_task->add_child(*child_task))) {
    LOG_WARN("failed to add child", K(ret));
  }

  if (OB_SUCC(ret)) {
    if (finish_task->get_validate_ctx().get_sub_task_count() > 0) {
      if (OB_FAIL(dag_->alloc_task(prepare_task))) {
        LOG_WARN("failed to alloc prepare task", K(ret));
      } else if (OB_FAIL(dag_->alloc_task(clog_task))) {
        LOG_WARN("failed to alloc clog task", K(ret));
      } else if (OB_FAIL(dag_->alloc_task(base_task))) {
        LOG_WARN("failed to alloc base task", K(ret));
      } else if (OB_FAIL(prepare_task->init(*ctx_, finish_task->get_validate_ctx()))) {
        LOG_WARN("failed to init prepare task", K(ret));
      } else if (OB_FAIL(clog_task->init(clog_file_id, *ctx_, finish_task->get_validate_ctx()))) {
        LOG_WARN("failed to init clog task", K(ret));
      } else if (OB_FAIL(base_task->init(task_idx, *ctx_, finish_task->get_validate_ctx()))) {
        LOG_WARN("failed to init base task", K(ret));
      } else if (OB_FAIL(parent_task->add_child(*prepare_task))) {
        LOG_WARN("failed to add child prepare task", K(ret));
      } else if (OB_FAIL(prepare_task->add_child(*clog_task))) {
        LOG_WARN("failed to add child clog task", K(ret));
      } else if (OB_FAIL(clog_task->add_child(*base_task))) {
        LOG_WARN("failed to add child base task", K(ret));
      } else if (OB_FAIL(base_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish task", K(ret));
      } else if (OB_FAIL(dag_->add_task(*prepare_task))) {
        LOG_WARN("failed to add prepare task to dag", K(ret));
      } else if (OB_FAIL(dag_->add_task(*clog_task))) {
        LOG_WARN("failed to add clog task to dag", K(ret));
      } else if (OB_FAIL(dag_->add_task(*base_task))) {
        LOG_WARN("failed to add base task to dag", K(ret));
      }
    } else {
      if (OB_FAIL(parent_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish_task for parent");
      }
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(dag_->add_task(*finish_task))) {
      LOG_WARN("failed tp add finish task to dag", K(ret));
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_validate_backup_ctx(ObValidateBackupPGCtx& pg_ctx)
{
  int ret = OB_SUCCESS;
  pg_ctx.reset();
  ObBackupBaseDataPathInfo path_info;
  ObArray<ObBackupMacroIndex> macro_index_list;
  const ObPartitionKey& pg_key = ctx_->replica_op_arg_.validate_arg_.pg_key_;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(ctx_->replica_op_arg_.validate_arg_.get_backup_base_data_info(path_info))) {
    STORAGE_LOG(WARN, "failed to get backup base data info", K(ret));
  } else if (!ctx_->macro_index_store_.is_inited() && OB_FAIL(ctx_->macro_index_store_.init(path_info))) {
    STORAGE_LOG(WARN, "failed to init macro index store", K(ret), K(path_info));
  } else if (OB_FAIL(pg_ctx.init(*ctx_, *bandwidth_throttle_))) {
    LOG_WARN("ctx init failed", K(ret));
  } else if (OB_FAIL(fetch_pg_macro_index_list(pg_key, pg_ctx, macro_index_list))) {
    LOG_WARN("failed to fetch pg macro block list", K(ret));
  } else if (OB_FAIL(build_validate_sub_task(macro_index_list, pg_ctx))) {
    LOG_WARN("failed to build validate sub task", K(ret));
  } else {
    LOG_INFO("succeed to build validate backup pg ctx", K(pg_ctx));
  }
  return ret;
}

int ObMigratePrepareTask::fetch_pg_macro_index_list(
    const ObPartitionKey& pg_key, ObValidateBackupPGCtx& pg_ctx, ObIArray<ObBackupMacroIndex>& macro_index_list)
{
  int ret = OB_SUCCESS;
  share::ObBackupMetaIndex meta_index;
  ObArray<ObBackupMacroIndex>* index_list = NULL;
  ObBackupMetaIndexStore* meta_index_store = NULL;
  ObBackupMacroIndexStore& macro_index_store = ctx_->macro_index_store_;
  ObPartGroupMigrationTask* group_task = NULL;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (FALSE_IT(group_task = reinterpret_cast<ObPartGroupMigrationTask*>(ctx_->group_task_))) {
  } else if (FALSE_IT(meta_index_store = &group_task->get_meta_index_store())) {
  } else if (OB_ISNULL(meta_index_store)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("meta index store should not be NULL", K(ret), KP(meta_index_store));
  } else if (OB_FAIL(meta_index_store->get_meta_index(pg_key, ObBackupMetaType::PARTITION_GROUP_META, meta_index))) {
    if (OB_HASH_NOT_EXIST == ret) {
      pg_ctx.only_in_clog_ = true;
      ret = OB_SUCCESS;
      LOG_INFO("pkey only exists in clog", K(ret), K(pg_key));
    }
  } else if (OB_UNLIKELY(!macro_index_store.is_inited())) {
    ret = OB_NOT_INIT;
    LOG_WARN("macro index store do not init", K(ret));
  } else if (OB_FAIL(macro_index_store.get_macro_block_index(pg_key, index_list))) {
    LOG_WARN("failed to get macro block index", K(ret), K(pg_key));
  } else if (OB_ISNULL(index_list)) {
    LOG_INFO("the pg is empty, skip", K(ret), K(pg_key));
  } else if (OB_FAIL(macro_index_list.assign(*index_list))) {
    LOG_WARN("failed to assign to macro_index_list", K(ret));
  } else if (FALSE_IT(pg_ctx.total_macro_block_count_ = macro_index_list.count())) {
    // do nothing
  }
  return ret;
}

int ObMigratePrepareTask::build_validate_sub_task(
    const ObIArray<ObBackupMacroIndex>& macro_index_list, ObValidateBackupPGCtx& ctx)
{
  int ret = OB_SUCCESS;
  void* buf = NULL;
  int64_t max_macro_block_count_per_task = 1024 /*MAX_MACRO_BLOCK_COUNT_PER_TASK*/;
  LOG_INFO("start to build validate sub task");
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (macro_index_list.empty()) {
    ctx.sub_task_cnt_ = 0;
    LOG_INFO("macro index list is empty, skip validating", K(ret));
  } else {
    ctx.sub_task_cnt_ = macro_index_list.count() / max_macro_block_count_per_task;
    if (macro_index_list.count() % max_macro_block_count_per_task > 0) {
      ++ctx.sub_task_cnt_;
    }
    if (OB_ISNULL(buf = ctx.allocator_.alloc(sizeof(ObValidateBackupPGCtx::SubTask) * ctx.sub_task_cnt_))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_ERROR("failed to allocate memory", K(ret));
    } else {
      ctx.sub_tasks_ = new (buf) ObValidateBackupPGCtx::SubTask[ctx.sub_task_cnt_];
      buf = NULL;
    }

    for (int64_t i = 0; OB_SUCC(ret) && i < ctx.sub_task_cnt_; ++i) {
      ObValidateBackupPGCtx::SubTask& sub_task = ctx.sub_tasks_[i];
      sub_task.macro_block_count_ =
          std::min(max_macro_block_count_per_task, macro_index_list.count() - i * max_macro_block_count_per_task);
      sub_task.pkey_ = ctx.pg_key_;
      if (OB_ISNULL(buf = ctx.allocator_.alloc(sizeof(ObBackupMacroIndex) * sub_task.macro_block_count_))) {
        ret = OB_ALLOCATE_MEMORY_FAILED;
        LOG_WARN("failed to alloc memory", K(ret));
      } else {
        sub_task.macro_block_infos_ = new (buf) ObBackupMacroIndex[sub_task.macro_block_count_];
        buf = NULL;
      }
      for (int64_t j = 0; OB_SUCC(ret) && j < sub_task.macro_block_count_; ++j) {
        const int64_t macro_idx = i * max_macro_block_count_per_task + j;
        if (macro_idx >= macro_index_list.count()) {
          break;
        }
        const ObBackupMacroIndex& macro_index = macro_index_list.at(macro_idx);
        ObBackupMacroIndex& index = ctx.sub_tasks_[i].macro_block_infos_[j];
        index = macro_index;
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_pg_backup_tasks(ObIArray<ObITask*>& last_task_array)
{
  int ret = OB_SUCCESS;
  ObITask* last_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (BACKUP_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("unexcepted op type, ", K(ret), K(ctx_->replica_op_arg_));
  } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.src_.get_replica_type())) {
    ret = OB_REPLICA_CANNOT_BACKUP;
    LOG_WARN("replica has no sstore.", K(ret), K(ctx_->replica_op_arg_));
  } else if (ctx_->partition_guard_.get_partition_group()->is_removed()) {
    ret = OB_PG_IS_REMOVED;
    LOG_WARN("partition is already removed, can not backup", K(ret), K(ctx_->replica_op_arg_.key_));
  } else if (OB_FAIL(generate_backup_tasks(last_task))) {
    LOG_WARN("fail to generate backup tasks", K(ret));
  } else if (OB_FAIL(last_task_array.push_back(last_task))) {
    LOG_WARN("fail to push last task into last task array", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_backup_tasks(ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_migrate_finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(generate_wait_migrate_finish_task(wait_migrate_finish_task))) {
    LOG_WARN("failed to generate_wait_migrate_finish_task", K(ret));
  } else if (OB_ISNULL(wait_migrate_finish_task)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("wait_rebuild_finish_task must not null", K(ret));
  } else if (OB_FAIL(generate_backup_tasks(*wait_migrate_finish_task))) {
    LOG_WARN("failed to generate_backup_tasks", K(ret));
  }

  if (OB_SUCC(ret)) {
    last_task = wait_migrate_finish_task;
  }
  return ret;
}

int ObMigratePrepareTask::generate_backup_tasks(ObFakeTask& wait_migrate_finish_task)
{
  int ret = OB_SUCCESS;
  ObITask* parent_task = this;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(generate_backup_major_tasks(parent_task))) {
    LOG_WARN("failed to generate backup major tasks", K(ret));
  } else if (OB_FAIL(parent_task->add_child(wait_migrate_finish_task))) {
    LOG_WARN("failed to add wait_migrate_finish_task", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_backup_major_tasks(share::ObITask*& parent_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_finish_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_ISNULL(parent_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret), KP(parent_task));
  } else if (OB_FAIL(dag_->alloc_task(wait_finish_task))) {
    LOG_WARN("failed to alloc wait finish task", K(ret));
  } else if (OB_FAIL(generate_backup_major_copy_task(parent_task, wait_finish_task))) {
    LOG_WARN("failed to generate major sstable copy task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*wait_finish_task))) {
    LOG_WARN("failed to add wait finish task", K(ret));
  } else {
    parent_task = wait_finish_task;
    LOG_DEBUG("succeed to generate_major_sstable_copy_task");
  }
  return ret;
}

int ObMigratePrepareTask::generate_backup_major_copy_task(ObITask* parent_task, ObITask* child_task)
{
  int ret = OB_SUCCESS;
  ObBackupCopyPhysicalTask* copy_task = NULL;
  ObBackupFinishTask* finish_task = NULL;
  const int64_t task_idx = 0;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(parent_task), KP(child_task));
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc finish task", K(ret));
  } else if (OB_FAIL(build_backup_physical_ctx(ctx_->physical_backup_ctx_))) {
    LOG_WARN("failed to build physical sstable ctx", K(ret));
  } else if (OB_FAIL(finish_task->init(*ctx_))) {
    LOG_WARN("failed to init finish task", K(ret));
  } else if (OB_FAIL(finish_task->add_child(*child_task))) {
    LOG_WARN("failed to add child", K(ret));
  }

  if (OB_SUCC(ret)) {
    if (ctx_->physical_backup_ctx_.get_task_count() > 0) {
      // parent->copy->finish->child
      if (OB_FAIL(dag_->alloc_task(copy_task))) {
        LOG_WARN("failed to alloc copy task", K(ret));
      } else if (OB_FAIL(copy_task->init(task_idx, *ctx_))) {
        LOG_WARN("failed to init copy task", K(ret));
      } else if (OB_FAIL(parent_task->add_child(*copy_task))) {
        LOG_WARN("failed to add child copy task", K(ret));
      } else if (OB_FAIL(copy_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish task", K(ret));
      } else if (OB_FAIL(dag_->add_task(*copy_task))) {
        LOG_WARN("failed to add copy task to dag", K(ret));
      }
    } else {
      // parent->finish->child
      if (OB_FAIL(parent_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish_task for parent", K(ret));
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_FAIL(dag_->add_task(*finish_task))) {
      LOG_WARN("failed to add finish task to dag", K(ret));
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_backup_physical_ctx(ObBackupPhysicalPGCtx& physical_backup_ctx)
{
  int ret = OB_SUCCESS;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(physical_backup_ctx.open())) {
    LOG_WARN("failed to open physical backup ctx", K(ret), K(ctx_->pg_meta_));
  } else if (OB_FAIL(fetch_backup_sstables(physical_backup_ctx.table_keys_))) {
    LOG_WARN("failed to build sub task", K(ret));
  } else if (0 == physical_backup_ctx.table_keys_.count()) {
    LOG_INFO("pg don't have major sstable, ", K(ret), K(ctx_->pg_meta_));
  } else if (OB_FAIL(build_backup_sub_task(physical_backup_ctx))) {
    LOG_WARN("failed to build sub task", K(ret));
  } else {
    ATOMIC_AAF(&ctx_->data_statics_.total_macro_block_, physical_backup_ctx.macro_block_count_);
    LOG_INFO("succeed to build physical sstable ctx", K(physical_backup_ctx));
  }

  return ret;
}

int ObMigratePrepareTask::fetch_backup_sstables(ObIArray<ObITable::TableKey>& table_keys)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else {
    // partition
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      ObPartitionMigrateCtx& part_migrate_ctx = ctx_->part_ctx_array_.at(i);
      if (OB_LIKELY(!part_migrate_ctx.is_valid())) {
        ret = OB_INVALID_ARGUMENT;
        LOG_WARN("part_migrate_ctx is invalid", K(ret), K(part_migrate_ctx));
      } else {
        // tables
        const ObArray<ObMigrateTableInfo>& table_infos = part_migrate_ctx.copy_info_.table_infos_;
        for (int64_t i = 0; OB_SUCC(ret) && i < table_infos.count(); ++i) {
          const ObMigrateTableInfo& table_info = table_infos.at(i);
          // major sstables
          for (int64_t sstable_idx = 0; OB_SUCC(ret) && sstable_idx < table_info.major_sstables_.count();
               ++sstable_idx) {
            const ObITable::TableKey& major_table_key = table_info.major_sstables_.at(sstable_idx).src_table_key_;
            if (OB_UNLIKELY(!major_table_key.is_valid())) {
              ret = OB_INVALID_ARGUMENT;
              LOG_WARN("invalid major table key", K(ret), K(major_table_key));
            } else if (OB_UNLIKELY(!ObITable::is_major_sstable(major_table_key.table_type_))) {
              ret = OB_ERR_SYS;
              LOG_ERROR("table type is not major sstable", K(ret), K(major_table_key), K(table_info));
            } else {
              table_keys.push_back(major_table_key);
            }
          }
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_backup_sub_task(ObBackupPhysicalPGCtx& ctx)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else {
    for (int i = 0; OB_SUCC(ret) && i < ctx.table_keys_.count(); ++i) {
      ObTableHandle tmp_handle;
      ObSSTable* sstable = NULL;
      int64_t sstable_macro_count = 0;
      ObITable::TableKey& major_table_key = ctx.table_keys_.at(i);
      if (OB_FAIL(ObPartitionService::get_instance().acquire_sstable(major_table_key, tmp_handle))) {
        STORAGE_LOG(WARN, "failed to get table", K(major_table_key), K(ret));
      } else if (OB_FAIL(tmp_handle.get_sstable(sstable))) {
        STORAGE_LOG(WARN, "failed to get table", K(major_table_key), K(ret));
      } else if (OB_ISNULL(sstable)) {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN, "sstable should not be null", K(ret));
      } else if (0 == (sstable_macro_count = sstable->get_meta().get_total_macro_block_count())) {
        // empty sstable
      } else {
        ObBackupMacroBlockInfo block_info;
        block_info.table_key_ = major_table_key;
        block_info.start_index_ = 0;
        block_info.cur_block_count_ = sstable_macro_count;
        block_info.total_block_count_ = sstable_macro_count;
        if (OB_FAIL(ctx.add_backup_macro_block_info(block_info))) {
          STORAGE_LOG(WARN, "add backup block info failed", K(ret), K(block_info));
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_pg_migrate_tasks(ObIArray<ObITask*>& last_task_array)
{
  int ret = OB_SUCCESS;
  ObITask* last_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
    ret = OB_ERR_SYS;
    LOG_WARN("no need to generate migrate tasks", K(ret), K(ctx_->replica_op_arg_));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      ObPartitionMigrateCtx& part_migrate_ctx = ctx_->part_ctx_array_.at(i);
      if (part_migrate_ctx.copy_info_.meta_.pkey_.is_trans_table()) {
        continue;
      } else if (OB_FAIL(generate_migrate_tasks(part_migrate_ctx, last_task))) {
        LOG_WARN("fail to generate migrate tasks", K(ret), K(part_migrate_ctx));
      } else if (OB_FAIL(last_task_array.push_back(last_task))) {
        LOG_WARN("fail to push last task into last task array", K(ret));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_pg_rebuild_tasks(ObIArray<ObITask*>& last_task_array)
{
  int ret = OB_SUCCESS;
  ObITask* last_task = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
    ret = OB_ERR_SYS;
    LOG_WARN("no need to generate rebuild tasks", K(ret), K(ctx_->replica_op_arg_));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      ObPartitionMigrateCtx& part_migrate_ctx = ctx_->part_ctx_array_.at(i);
      if (part_migrate_ctx.copy_info_.meta_.pkey_.is_trans_table()) {
        continue;
      } else if (OB_FAIL(generate_rebuild_tasks(part_migrate_ctx, last_task))) {
        LOG_WARN("fail to generate rebuild tasks", K(ret), K(part_migrate_ctx));
      } else if (OB_FAIL(last_task_array.push_back(last_task))) {
        LOG_WARN("fail to push last task into last task array", K(ret));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_migrate_tasks(ObPartitionMigrateCtx& part_migrate_ctx, ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_migrate_finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (!part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("copy info is invalid", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(generate_wait_migrate_finish_task(wait_migrate_finish_task))) {
    LOG_WARN("failed to generate_wait_migrate_finish_task", K(ret));
  } else if (OB_ISNULL(wait_migrate_finish_task)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("wait_rebuild_finish_task must not null", K(ret));
  } else {
    const ObMigratePartitionInfo& copy_info = part_migrate_ctx.copy_info_;
    const ObArray<ObMigrateTableInfo>& table_infos = copy_info.table_infos_;
    for (int64_t i = 0; OB_SUCC(ret) && i < table_infos.count(); ++i) {
      const ObMigrateTableInfo& table_info = table_infos.at(i);
      if (OB_FAIL(generate_migrate_tasks(
              ctx_->migrate_src_info_, part_migrate_ctx, table_info, *wait_migrate_finish_task))) {
        LOG_WARN("failed to generate_migrate_tasks", K(ret), K(i), K(table_info), K(part_migrate_ctx));
      }
    }
  }

  if (OB_SUCC(ret)) {
    last_task = wait_migrate_finish_task;
  }
#ifdef ERRSIM
  if (OB_SUCC(ret)) {
    ret = E(EventTable::EN_GEN_REBUILD_TASK) OB_SUCCESS;
    if (OB_FAIL(ret)) {
      STORAGE_LOG(ERROR, "fake EN_GEN_REBUILD_TASK", K(ret));
    }
  }
#endif
  return ret;
}

int ObMigratePrepareTask::generate_rebuild_tasks(ObPartitionMigrateCtx& part_migrate_ctx, ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  ObFakeTask* wait_rebuild_finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (!part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("copy info is invalid", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(generate_wait_migrate_finish_task(wait_rebuild_finish_task))) {
    LOG_WARN("failed to generate_wait_rebuild_finish_task", K(ret));
  } else if (OB_ISNULL(wait_rebuild_finish_task)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("wait_rebuild_finish_task must not null", K(ret));
  } else {
    const ObMigratePartitionInfo& copy_info = part_migrate_ctx.copy_info_;
    const ObArray<ObMigrateTableInfo>& table_infos = copy_info.table_infos_;
    for (int64_t i = 0; OB_SUCC(ret) && i < table_infos.count(); ++i) {
      const ObMigrateTableInfo& table_info = table_infos.at(i);
      if (OB_FAIL(generate_rebuild_tasks(
              ctx_->migrate_src_info_, part_migrate_ctx, table_info, *wait_rebuild_finish_task))) {
        LOG_WARN("failed to generate_rebuild_tasks", K(ret), K(i), K(table_info), K(part_migrate_ctx));
      }
    }
  }

  if (OB_SUCC(ret)) {
    last_task = wait_rebuild_finish_task;
  }
#ifdef ERRSIM
  if (OB_SUCC(ret)) {
    ret = E(EventTable::EN_GEN_REBUILD_TASK) OB_SUCCESS;
    if (OB_FAIL(ret)) {
      STORAGE_LOG(ERROR, "fake EN_GEN_REBUILD_TASK", K(ret));
    }
  }
#endif
  return ret;
}

int ObMigratePrepareTask::generate_wait_migrate_finish_task(ObFakeTask*& wait_migrate_finish_task)
{
  int ret = OB_SUCCESS;
  wait_migrate_finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(dag_->alloc_task(wait_migrate_finish_task))) {
    LOG_WARN("failed to alloc wait_rebuild_finish_task", K(ret));
  } else if (OB_FAIL(add_child(*wait_migrate_finish_task))) {
    LOG_WARN("failed to add child wait_rebuild_finish_task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*wait_migrate_finish_task))) {
    LOG_WARN("failed to add wait_rebuild_finish_task", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_rebuild_tasks(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo& table_info, ObFakeTask& wait_rebuild_finish_task)
{
  int ret = OB_SUCCESS;
  ObITask* parent_task = this;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if ((!src_info.is_valid() && RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_) ||
             !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate migrate tasks get invalid argument", K(ret), K(src_info), K(part_migrate_ctx));
  } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
    ret = OB_ERR_SYS;
    LOG_WARN("no need to generate minor task", K(ret), K(ctx_->replica_op_arg_));
  } else if (OB_FAIL(generate_major_tasks(src_info, part_migrate_ctx, table_info, parent_task))) {
    LOG_WARN("failed to generate rebuild major tasks", K(ret), K(table_info), K(part_migrate_ctx));
  } else if (OB_FAIL(generate_minor_tasks(src_info, part_migrate_ctx, table_info, parent_task))) {
    LOG_WARN("failed to generate rebuild minor tasks", K(ret), K(table_info), K(part_migrate_ctx));
  } else if (OB_FAIL(parent_task->add_child(wait_rebuild_finish_task))) {
    LOG_WARN("failed to add wait_rebuild_finish_task", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_migrate_tasks(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo& table_info, ObFakeTask& wait_migrate_finish_task)
{
  int ret = OB_SUCCESS;
  ObITask* parent_task = this;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if ((RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && !src_info.is_valid()) ||
             !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate tasks get invalid argument", K(ret), K(src_info), K(part_migrate_ctx));
  } else if (!ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
    ret = OB_ERR_SYS;
    LOG_WARN("no need to generate minor task", K(ret), K(ctx_->replica_op_arg_));
  } else if (OB_FAIL(generate_minor_tasks(src_info, part_migrate_ctx, table_info, parent_task))) {
    LOG_WARN("failed to generate migrate minor tasks", K(ret), K(table_info), K(part_migrate_ctx));
  } else if (OB_FAIL(generate_major_tasks(src_info, part_migrate_ctx, table_info, parent_task))) {
    LOG_WARN("failed to generate migrate major tasks", K(ret), K(table_info), K(part_migrate_ctx));
  } else if (OB_FAIL(parent_task->add_child(wait_migrate_finish_task))) {
    LOG_WARN("failed to add wait_migrate_finish_task", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_major_tasks(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo& table_info, share::ObITask*& parent_task)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if ((!src_info.is_valid() && RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_) || OB_ISNULL(parent_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate migrate major task get invalid argument", K(ret), K(src_info), KP(parent_task));
  } else {
    // add major sstables
    for (int64_t sstable_idx = 0; OB_SUCC(ret) && sstable_idx < table_info.major_sstables_.count(); ++sstable_idx) {
      const ObMigrateTableInfo::SSTableInfo& major_table_info = table_info.major_sstables_.at(sstable_idx);
      ObFakeTask* wait_finish_task = NULL;
      if (!ObITable::is_major_sstable(major_table_info.src_table_key_.table_type_)) {
        ret = OB_ERR_SYS;
        LOG_ERROR("table type not match major sstable", K(ret), K(major_table_info), K(table_info));
      } else {
        if (OB_FAIL(dag_->alloc_task(wait_finish_task))) {
          LOG_WARN("failed to alloc wait finish task", K(ret));
        } else if (OB_FAIL(generate_major_sstable_copy_task(
                       src_info, part_migrate_ctx, major_table_info, parent_task, wait_finish_task))) {
          LOG_WARN("failed to generate major sstable copy task", K(ret), K(major_table_info));
        } else if (OB_FAIL(dag_->add_task(*wait_finish_task))) {
          LOG_WARN("failed to add wait finish task", K(ret));
        } else {
          parent_task = wait_finish_task;
          LOG_INFO("succeed to generate_major_sstable_copy_task", K(src_info), K(major_table_info));
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_minor_tasks(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo& table_info, share::ObITask*& parent_task)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if ((!src_info.is_valid() && RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_) || OB_ISNULL(parent_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate migrate minor task get invalid argument", K(ret), K(src_info), KP(parent_task));
  } else {
    for (int64_t sstable_idx = 0; OB_SUCC(ret) && sstable_idx < table_info.minor_sstables_.count(); ++sstable_idx) {
      const ObMigrateTableInfo::SSTableInfo& minor_sstable_info = table_info.minor_sstables_.at(sstable_idx);
      ObFakeTask* wait_finish_task = NULL;
      if (!ObITable::is_minor_sstable(minor_sstable_info.src_table_key_.table_type_) &&
          !ObITable::is_memtable(minor_sstable_info.src_table_key_.table_type_)) {
        ret = OB_ERR_SYS;
        LOG_ERROR("table type not match minor sstable", K(ret), K(minor_sstable_info), K(table_info));
      } else {
        if (OB_FAIL(dag_->alloc_task(wait_finish_task))) {
          LOG_WARN("failed to alloc wait finish task", K(ret));
        } else if (OB_FAIL(generate_minor_sstable_copy_task(
                       parent_task, wait_finish_task, src_info, minor_sstable_info, part_migrate_ctx))) {
          LOG_WARN("failed to generate minor sstable copy task", K(ret), K(minor_sstable_info));
        }

        if (OB_SUCC(ret)) {
          if (OB_FAIL(dag_->add_task(*wait_finish_task))) {
            LOG_WARN("failed to add wait finish task", K(ret));
          } else {
            parent_task = wait_finish_task;
            LOG_INFO("succeed to generate_minor_sstable_copy_task", K(src_info), K(minor_sstable_info));
          }
        }
      }
    }
  }
  return ret;
}

// now only support rebuild from old server,
// if want support more condition, modified it
int ObMigratePrepareTask::generate_physic_minor_sstable_copy_task(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo::SSTableInfo& minor_sstable_info,
    ObITask* parent_task, ObITask* child_task)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task) ||
             (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && !src_info.is_valid()) ||
             !minor_sstable_info.is_valid() || !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args",
        K(ret),
        KP(parent_task),
        KP(child_task),
        K(src_info),
        K(minor_sstable_info),
        K(ctx_->replica_op_arg_),
        K(part_migrate_ctx));
  } else if (OB_FAIL(generate_physic_sstable_copy_task(
                 src_info, part_migrate_ctx, minor_sstable_info, parent_task, child_task))) {
    LOG_WARN("fail to generate physic sstable copy task", K(ret), K(src_info), K(minor_sstable_info));
  }
  return ret;
}

int ObMigratePrepareTask::generate_logic_minor_sstable_copy_task(ObITask* parent_task, ObITask* child_task,
    const ObMigrateSrcInfo& src_info, const ObMigrateTableInfo::SSTableInfo& minor_sstable_info,
    ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;
  ObMigrateCopyLogicTask* copy_task = NULL;
  ObMigrateFinishLogicTask* finish_task = NULL;
  const int64_t task_idx = 0;
  const ObITable::TableKey& table_key = minor_sstable_info.src_table_key_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task) || !src_info.is_valid() ||
             !minor_sstable_info.is_valid() || !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args",
        K(ret),
        KP(parent_task),
        KP(child_task),
        K(src_info),
        K(minor_sstable_info),
        K(part_migrate_ctx));
  } else if (table_key.pkey_.get_partition_id() != part_migrate_ctx.copy_info_.meta_.pkey_.get_partition_id()) {
    ret = OB_NOT_SUPPORTED;
    LOG_ERROR("cannot migrate partition with different partition id minor sstable",
        K(ret),
        K(table_key),
        "pkey",
        part_migrate_ctx.copy_info_.meta_.pkey_,
        "pg_key",
        ctx_->replica_op_arg_.key_);
  } else if (OB_FAIL(dag_->alloc_task(copy_task))) {
    LOG_WARN("failed to alloc copy task", K(ret));
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc finish task", K(ret));
  } else if (OB_FAIL(build_logic_sstable_ctx(src_info, minor_sstable_info, finish_task->get_sstable_ctx()))) {
    LOG_WARN("failed to build logic sstable ctx", K(ret), K(minor_sstable_info));
  } else if (OB_FAIL(copy_task->init(task_idx, finish_task->get_sstable_ctx(), *ctx_))) {
    LOG_WARN("failed to init copy task", K(ret));
  } else if (OB_FAIL(finish_task->init(part_migrate_ctx))) {
    LOG_WARN("failed to init finish task", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(parent_task->add_child(*copy_task))) {
    LOG_WARN("failed to add child copy task", K(ret));
  } else if (OB_FAIL(copy_task->add_child(*finish_task))) {
    LOG_WARN("failed to add child finish task", K(ret));
  } else if (OB_FAIL(finish_task->add_child(*child_task))) {
    LOG_WARN("failed to add child", K(ret));
  } else if (OB_FAIL(dag_->add_task(*copy_task))) {
    LOG_WARN("failed to add copy task to dag", K(ret));
  } else if (OB_FAIL(dag_->add_task(*finish_task))) {
    LOG_WARN("failed to add finish task to dag", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::generate_minor_sstable_copy_task(share::ObITask* parent_task, share::ObITask* child_task,
    const ObMigrateSrcInfo& src_info, const ObMigrateTableInfo::SSTableInfo& minor_sstable_info,
    ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task) ||
             (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && !src_info.is_valid()) ||
             !minor_sstable_info.is_valid() || !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args",
        K(ret),
        KP(parent_task),
        KP(child_task),
        K(src_info),
        K(minor_sstable_info),
        K(part_migrate_ctx));
  } else {
    if (ObITable::is_minor_sstable(minor_sstable_info.src_table_key_.table_type_)) {
      if (OB_FAIL(generate_physic_minor_sstable_copy_task(
              src_info, part_migrate_ctx, minor_sstable_info, parent_task, child_task))) {
        LOG_WARN("failed to generate physic minor sstable copy task", K(ret), K(src_info), K(minor_sstable_info));
      }
    } else {
      if (OB_FAIL(generate_logic_minor_sstable_copy_task(
              parent_task, child_task, src_info, minor_sstable_info, part_migrate_ctx))) {
        LOG_WARN("fail to generate logic minor sstable copy task", K(ret), K(src_info), K(minor_sstable_info));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_logic_sstable_ctx(const ObMigrateSrcInfo& src_info,
    const ObMigrateTableInfo::SSTableInfo& minor_sstable_info, ObMigrateLogicSSTableCtx& ctx)
{
  int ret = OB_SUCCESS;
  obrpc::ObFetchLogicBaseMetaArg arg;
  ObLogicBaseMetaReader reader;
  obrpc::ObFetchLogicRowArg logic_row_arg;
  ObLogicDataChecksumReader logic_data_checksum_reader;
  ObSchemaGetterGuard schema_guard;

  common::ObArray<common::ObStoreRowkey> end_key_list;
  ctx.reset();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else {
    arg.table_key_ = minor_sstable_info.src_table_key_;
    arg.task_count_ = MAX_LOGIC_TASK_COUNT_PER_SSTABLE;
  }

  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(
                 reader.init(*srv_rpc_proxy_, *bandwidth_throttle_, src_info.src_addr_, arg, src_info.cluster_id_))) {
    LOG_WARN("failed to init logic meta reader", K(ret), K(src_info), K(arg));
  } else if (OB_FAIL(reader.fetch_end_key_list(end_key_list))) {
    LOG_WARN("failed to fetch_end_key_list", K(ret), K(src_info), K(arg));
  } else if (OB_FAIL(ctx.build_sub_task(end_key_list))) {
    LOG_WARN("failed to build sub task", K(ret));
  } else if (FALSE_IT(ctx.meta_.schema_version_ = ctx_->pg_meta_.storage_info_.get_data_info().get_schema_version())) {
    // get remote memtable's max table_schema_version
  } else if (OB_FAIL(MIGRATOR.get_schema_service()->retry_get_schema_guard(ctx.meta_.schema_version_,
                 minor_sstable_info.src_table_key_.table_id_,
                 schema_guard,
                 ctx.meta_.schema_version_))) {
    LOG_WARN("failed to get schema guard", K(minor_sstable_info), K(ret), K(ctx));
  } else {
    ctx.src_info_ = src_info;
    ctx.table_key_ = minor_sstable_info.src_table_key_;
    ctx.dest_base_version_ = minor_sstable_info.dest_base_version_;
    LOG_INFO("succ to get logic migrate context", K(ctx));
  }

  // fetch logic data checksum
  if (OB_FAIL(ret)) {
  } else {
    logic_row_arg.table_key_ = minor_sstable_info.src_table_key_;
    logic_row_arg.key_range_.set_whole_range();
    logic_row_arg.schema_version_ = ctx.meta_.schema_version_;
    if (OB_FAIL(logic_data_checksum_reader.init(
            *srv_rpc_proxy_, *bandwidth_throttle_, src_info.src_addr_, src_info.cluster_id_, logic_row_arg))) {
      LOG_WARN("failed to init logic data checksum reader", K(ret));
    } else if (OB_FAIL(logic_data_checksum_reader.get_data_checksum(ctx.data_checksum_))) {
      LOG_WARN("fail to get logic data checksum", K(ret));
    } else {
      LOG_INFO("succ to get logic data checksum", K(ctx.data_checksum_));
    }
  }

  return ret;
}

int ObMigratePrepareTask::generate_physic_sstable_copy_task(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo::SSTableInfo& sstable_info, ObITask* parent_task,
    ObITask* child_task)
{
  int ret = OB_SUCCESS;
  ObMigrateCopyPhysicalTask* copy_task = NULL;
  ObMigrateFinishPhysicalTask* finish_task = NULL;
  const int64_t task_idx = 0;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task) ||
             (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && !src_info.is_valid()) || !sstable_info.is_valid() ||
             !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN(
        "invalid args", K(ret), KP(parent_task), KP(child_task), K(src_info), K(sstable_info), K(part_migrate_ctx));
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc finish task", K(ret));
  } else if (OB_FAIL(build_physical_sstable_ctx(src_info, sstable_info, finish_task->get_sstable_ctx()))) {
    LOG_WARN("failed to build physical sstable ctx", K(ret), K(src_info), K(sstable_info));
  } else if (OB_FAIL(finish_task->init(part_migrate_ctx))) {
    LOG_WARN("failed to init finish task", K(ret), K(part_migrate_ctx));
  } else if (OB_FAIL(finish_task->add_child(*child_task))) {
    LOG_WARN("failed to add child", K(ret));
  }

  if (OB_SUCC(ret)) {
    if (finish_task->get_sstable_ctx().task_count_ > 0) {
      // parent->copy->finish->child
      if (OB_FAIL(dag_->alloc_task(copy_task))) {
        LOG_WARN("failed to alloc copy task", K(ret));
      } else if (OB_FAIL(copy_task->init(task_idx, finish_task->get_sstable_ctx(), *ctx_))) {
        LOG_WARN("failed to init copy task", K(ret));
      } else if (OB_FAIL(parent_task->add_child(*copy_task))) {
        LOG_WARN("failed to add child copy task", K(ret));
      } else if (OB_FAIL(copy_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish task", K(ret));
      } else if (OB_FAIL(dag_->add_task(*copy_task))) {
        LOG_WARN("failed to add copy task to dag", K(ret));
      }
    } else {
      // parent->finish->child
      if (OB_FAIL(parent_task->add_child(*finish_task))) {
        LOG_WARN("failed to add child finish_task for parent", K(ret));
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_FAIL(dag_->add_task(*finish_task))) {
      LOG_WARN("failed to add finish task to dag", K(ret));
    }
  }
  return ret;
}

int ObMigratePrepareTask::generate_major_sstable_copy_task(const ObMigrateSrcInfo& src_info,
    ObPartitionMigrateCtx& part_migrate_ctx, const ObMigrateTableInfo::SSTableInfo& major_sstable_info,
    ObITask* parent_task, ObITask* child_task)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(parent_task) || OB_ISNULL(child_task) ||
             (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && !src_info.is_valid()) ||
             !major_sstable_info.is_valid() || !part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args",
        K(ret),
        KP(parent_task),
        KP(child_task),
        K(src_info),
        K(major_sstable_info),
        K(part_migrate_ctx));
  } else if (OB_FAIL(generate_physic_sstable_copy_task(
                 src_info, part_migrate_ctx, major_sstable_info, parent_task, child_task))) {
    LOG_WARN("fail to generate physic sstable copy task", K(ret), K(major_sstable_info), K(src_info));
  }

  return ret;
}

int ObMigratePrepareTask::generate_finish_migrate_task(
    const ObIArray<ObITask*>& last_task_array, share::ObITask*& last_task)
{
  int ret = OB_SUCCESS;
  ObMigrateFinishTask* finish_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc task", K(ret));
  } else if (OB_FAIL(finish_task->init(*ctx_))) {
    LOG_WARN("failed to init finish task", K(ret));
  }

  if (OB_SUCC(ret)) {
    for (int64_t i = 0; OB_SUCC(ret) && i < last_task_array.count(); ++i) {
      ObITask* last_task = last_task_array.at(i);
      if (NULL != last_task) {
        if (OB_FAIL(last_task->add_child(*finish_task))) {
          LOG_WARN("failed to add child of last task", K(ret));
        }
      } else {
        if (OB_FAIL(add_child(*finish_task))) {
          LOG_WARN("failed to add child of prepare task", K(ret));
        }
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_FAIL(dag_->add_task(*finish_task))) {
      LOG_WARN("failed to add finish task", K(ret));
    } else {
      last_task = finish_task;
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_reader(
    const ObMigrateSrcInfo& src_info, const obrpc::ObFetchPhysicalBaseMetaArg& arg, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;
  const int64_t compatible = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (ctx_->replica_op_arg_.is_physical_restore_leader()) {
    if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
      if (OB_FAIL(get_base_meta_restore_reader_v1(arg.table_key_, reader))) {
        STORAGE_LOG(WARN, "fail to get_base_meta_restore_reader_v1", K(ret));
      }
    } else if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
      if (OB_FAIL(get_base_meta_restore_reader_v2(arg.table_key_, reader))) {
        STORAGE_LOG(WARN, "fail to get_base_meta_restore_reader_v1", K(ret));
      }
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("restore compatible version is expected", K(ret), K(compatible), K(arg));
    }
  } else if (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_NOT_SUPPORTED;
    LOG_ERROR("not support logical restore", K(ret), "replica_op_arg", ctx_->replica_op_arg_);
  } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(get_base_meta_backup_reader(arg.table_key_, reader))) {
      STORAGE_LOG(WARN, "fail to get_base_meta_restore_reader", K(ret));
    }
  } else {
    if (OB_FAIL(get_base_meta_ob_reader(src_info, arg, reader))) {
      STORAGE_LOG(WARN, "failed to get_macro_block_ob_reader", K(ret));
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_restore_reader_v1(
    const ObITable::TableKey& table_key, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPhysicalBaseMetaRestoreReaderV1* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("restore meta reader must not null", K(ret));
  } else if (NULL == (tmp_reader = cp_fty_->get_base_data_meta_restore_reader_v1())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(*bandwidth_throttle_,
                 ctx_->replica_op_arg_.phy_restore_arg_,
                 table_key,
                 *ctx_->restore_meta_reader_))) {
    STORAGE_LOG(WARN, "failed to init ob reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_restore_reader_v2(
    const ObITable::TableKey& table_key, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPhysicalBaseMetaRestoreReaderV2* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("restore meta reader must not null", K(ret));
  } else if (NULL == (tmp_reader = cp_fty_->get_base_data_meta_restore_reader_v2())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(*bandwidth_throttle_,
                 ctx_->replica_op_arg_.phy_restore_arg_,
                 table_key,
                 *ctx_->restore_meta_reader_))) {
    STORAGE_LOG(WARN, "failed to init ob reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_backup_reader(
    const ObITable::TableKey& table_key, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPhysicalBaseMetaBackupReader* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_base_data_meta_backup_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_ISNULL(ctx_->backup_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("ctx_->backup_meta_reader_ must not null", K(ret));
  } else if (OB_FAIL(tmp_reader->init(
                 ctx_->restore_info_, table_key.pkey_, table_key.table_id_, *ctx_->backup_meta_reader_))) {
    STORAGE_LOG(WARN, "failed to init ob reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_ob_reader(
    const ObMigrateSrcInfo& src_info, const obrpc::ObFetchPhysicalBaseMetaArg& arg, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_FAIL(get_base_meta_rpc_reader(src_info, arg, reader))) {
    STORAGE_LOG(WARN, "fail to get base meta rpc reader", K(ret), K(src_info), K(arg));
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_base_meta_rpc_reader(
    const ObMigrateSrcInfo& src_info, const obrpc::ObFetchPhysicalBaseMetaArg& arg, ObIPhysicalBaseMetaReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPhysicalBaseMetaReader* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (NULL == (tmp_reader = cp_fty_->get_base_data_meta_ob_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(
                 *srv_rpc_proxy_, *bandwidth_throttle_, src_info.src_addr_, arg, src_info.cluster_id_))) {
    STORAGE_LOG(WARN, "failed to init ob reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != tmp_reader) {
        cp_fty_->free(tmp_reader);
        tmp_reader = NULL;
      }
    }
  }

  return ret;
}

int ObMigratePrepareTask::build_physical_sstable_ctx(const ObMigrateSrcInfo& src_info,
    const ObMigrateTableInfo::SSTableInfo& sstable_info, ObMigratePhysicalSSTableCtx& ctx)
{
  int ret = OB_SUCCESS;
  obrpc::ObFetchPhysicalBaseMetaArg arg;
  common::ObArray<blocksstable::ObSSTablePair> macro_block_list;
  ObTablesHandle handle;
  ctx.reset();
  ObIPhysicalBaseMetaReader* reader = NULL;
  arg.table_key_ = sstable_info.src_table_key_;
  ctx.sstable_info_ = sstable_info;
  ctx.src_info_ = src_info;
  ctx.is_leader_restore_ = ctx_->replica_op_arg_.is_physical_restore_leader();
  ctx.restore_version_ = ctx_->replica_op_arg_.phy_restore_arg_.restore_data_version_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(get_base_meta_reader(src_info, arg, reader))) {
    LOG_WARN("fail to get base meta reader", K(ret));
  } else if (OB_ISNULL(reader)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("reader should not be NULL", K(ret), KP(reader));
  }

  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(reader->fetch_sstable_meta(ctx.meta_))) {
    LOG_WARN("failed to fetch physic table meta", K(ret), K(src_info), K(arg));
  } else if (OB_FAIL(reader->fetch_macro_block_list(macro_block_list))) {
    LOG_WARN("failed to fetch_macro_block_list", K(ret), K(src_info), K(arg));
  } else if (OB_FAIL(calc_macro_block_reuse(sstable_info.src_table_key_, macro_block_list))) {
    LOG_WARN("fail to calc macro block reuse", K(ret));
  } else if (OB_FAIL(build_sub_physical_task(ctx, macro_block_list))) {
    LOG_WARN("failed to build sub task", K(ret));
  } else {
    ATOMIC_AAF(&ctx_->data_statics_.total_macro_block_, macro_block_list.count());
    LOG_INFO("succeed to build physical sstable ctx", K(ctx));
  }
  if (NULL != reader) {
    cp_fty_->free(reader);
  }

  return ret;
}

int ObMigratePrepareTask::build_sub_physical_task(
    ObMigratePhysicalSSTableCtx& ctx, common::ObIArray<blocksstable::ObSSTablePair>& macro_block_list)
{
  int ret = OB_SUCCESS;
  void* buf = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (0 == macro_block_list.count()) {
    ctx.task_count_ = 0;
    LOG_INFO("no macro block need copy", K(ret));
  } else {
    const int64_t max_macro_block_count_per_task = MAX_MACRO_BLOCK_COUNT_PER_TASK;
    ctx.task_count_ = macro_block_list.count() / max_macro_block_count_per_task;
    if (macro_block_list.count() % max_macro_block_count_per_task > 0) {
      ++ctx.task_count_;
    }

    if (OB_ISNULL(buf = ctx.allocator_.alloc(sizeof(ObMigratePhysicalSSTableCtx::SubTask) * ctx.task_count_))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("failed to alloc buf", K(ret));
    } else {
      ctx.tasks_ = new (buf) ObMigratePhysicalSSTableCtx::SubTask[ctx.task_count_];
      buf = NULL;
    }
    for (int64_t task_idx = 0; OB_SUCC(ret) && task_idx < ctx.task_count_; ++task_idx) {
      ObMigratePhysicalSSTableCtx::SubTask& sub_task = ctx.tasks_[task_idx];
      sub_task.pkey_ = ctx.sstable_info_.src_table_key_.pkey_;
      sub_task.block_count_ = std::min(
          max_macro_block_count_per_task, macro_block_list.count() - task_idx * max_macro_block_count_per_task);
      if (OB_ISNULL(buf = ctx.allocator_.alloc(sizeof(ObMigrateMacroBlockInfo) * sub_task.block_count_))) {
        ret = OB_ALLOCATE_MEMORY_FAILED;
        LOG_WARN("failed to alloc buf", K(ret));
      } else {
        sub_task.block_info_ = new (buf) ObMigrateMacroBlockInfo[sub_task.block_count_];
        buf = NULL;
      }

      for (int64_t i = 0; OB_SUCC(ret) && i < sub_task.block_count_; ++i) {
        const int64_t macro_idx = task_idx * max_macro_block_count_per_task + i;

        if (macro_idx >= macro_block_list.count()) {
          break;
        }

        const blocksstable::ObSSTablePair& pair = macro_block_list.at(macro_idx);
        ObMigrateMacroBlockInfo& info = ctx.tasks_[task_idx].block_info_[i];
        info.pair_ = pair;
        info.need_copy_ = true;
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::calc_macro_block_reuse(
    const ObITable::TableKey& table_key, ObIArray<ObSSTablePair>& macro_block_list)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (0 == macro_block_list.count()) {
    // do nothing
  } else if (OB_FAIL(ctx_->reuse_block_mgr_.build_reuse_macro_map(*ctx_, table_key, macro_block_list))) {
    LOG_WARN("fail to build reuse macro map", K(ret));
  }

  return ret;
}

int ObMigratePrepareTask::build_index_partition_info(
    const ObReplicaOpArg& arg, ObIPGPartitionBaseDataMetaObReader* reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMigrateCtx part_migrate_ctx;
  ObArray<obrpc::ObFetchTableInfoResult> table_info_res;
  ObArray<uint64_t> table_id_list;
  bool found = false;
  ObPGPartitionMetaInfo partition_meta_info;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate preprae task do not init", K(ret));
  } else if (!arg.is_valid() || OB_ISNULL(reader)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("build index partition info get invalid argument", K(ret), K(arg), KP(reader));
  } else if (COPY_LOCAL_INDEX_OP != arg.type_) {
    ret = OB_ERR_SYS;
    LOG_WARN("replica op type do not match", K(ret), K(arg));
  } else {
    while (OB_SUCC(ret)) {
      partition_meta_info.reset();
      table_info_res.reuse();
      table_id_list.reuse();
      part_migrate_ctx.reset();
      found = false;
      if (OB_FAIL(reader->fetch_pg_partition_meta_info(partition_meta_info))) {
        if (OB_ITER_END != ret) {
          LOG_WARN("fail to fetch pg partition meta info", K(ret), K(ctx_->replica_op_arg_));
        } else {
          ret = OB_SUCCESS;
          break;
        }
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < partition_meta_info.table_id_list_.count() && !found; ++i) {
          found = arg.index_id_ == partition_meta_info.table_id_list_.at(i);
          if (found) {
            if (OB_FAIL(table_id_list.push_back(partition_meta_info.table_id_list_.at(i)))) {
              LOG_WARN("failed to push table id into array", K(ret), K(arg));
            } else if (OB_FAIL(table_info_res.push_back(partition_meta_info.table_info_.at(i)))) {
              LOG_WARN("failed to push table info into array", K(ret), K(partition_meta_info), K(i));
            }
          }
        }
      }
      if (OB_SUCC(ret)) {
        if (found) {
          if (OB_FAIL(
                  build_migrate_partition_info(partition_meta_info, table_info_res, table_id_list, part_migrate_ctx))) {
            LOG_WARN("fail to build migrate partition info", K(ret), K(partition_meta_info));
          } else if (OB_FAIL(ctx_->part_ctx_array_.push_back(part_migrate_ctx))) {
            LOG_WARN("fail to push part migrate ctx into array", K(ret), K(part_migrate_ctx));
          } else {
            break;
          }
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (0 == ctx_->part_ctx_array_.count()) {
        ret = OB_ERR_SYS;
        FLOG_WARN("local index can not find part ctx", K(ret), K(*ctx_));
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::build_table_partition_info(
    const ObReplicaOpArg& arg, ObIPGPartitionBaseDataMetaObReader* reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMigrateCtx part_migrate_ctx;
  ObArray<obrpc::ObFetchTableInfoResult> table_info_res;
  ObArray<uint64_t> table_id_list;
  ObPGPartitionMetaInfo partition_meta_info;

  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (!arg.is_valid() || OB_ISNULL(reader)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("build table partition info get invalid argument", K(ret), K(arg), KP(reader));
  } else if (OB_UNLIKELY(COPY_LOCAL_INDEX_OP == arg.type_)) {
    ret = OB_ERR_SYS;
    LOG_WARN("replica op type do not match", K(ret), K(arg));
  } else {
    while (OB_SUCC(ret)) {
      partition_meta_info.reset();
      table_info_res.reuse();
      table_id_list.reuse();
      part_migrate_ctx.reset();
      if (OB_FAIL(reader->fetch_pg_partition_meta_info(partition_meta_info))) {
        if (OB_ITER_END != ret) {
          LOG_WARN("fail to fetch pg partition meta info", K(ret), K(ctx_->replica_op_arg_));
        } else {
          ret = OB_SUCCESS;
          break;
        }
      } else if (OB_FAIL(table_id_list.assign(partition_meta_info.table_id_list_))) {
        LOG_WARN("failed to assign table id list", K(ret));
      } else if (OB_FAIL(table_info_res.assign(partition_meta_info.table_info_))) {
        LOG_WARN("failed to copy needed table info", K(ret), K(partition_meta_info));
      } else if (OB_FAIL(build_migrate_partition_info(
                     partition_meta_info, table_info_res, table_id_list, part_migrate_ctx))) {
        LOG_WARN("fail to build migrate partition info", K(ret), K(partition_meta_info));
      } else if (OB_FAIL(ctx_->part_ctx_array_.push_back(part_migrate_ctx))) {
        LOG_WARN("fail to push part migrate ctx into array", K(ret), K(part_migrate_ctx));
      }

      if (OB_SUCC(ret) && ctx_->replica_op_arg_.is_physical_restore_follower()) {
        if (OB_FAIL(create_partition_if_needed(ctx_->partition_guard_, partition_meta_info.meta_))) {
          LOG_WARN("fail to create partition for follower restore", K(ret), K(arg), K(partition_meta_info.meta_));
        }
      }
    }
  }
  return ret;
}

int ObMigratePrepareTask::remove_uncontinue_local_tables(const ObPartitionKey& pkey, const uint64_t table_id)
{
  int ret = OB_SUCCESS;
  ObPGPartitionGuard guard;
  ObIPartitionGroup* partition = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (!pkey.is_valid() || 0 == table_id || OB_INVALID_ID == table_id) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("remove uncontinue local tables get invalid argument", K(ret), K(pkey), K(table_id));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    // do nothing
    LOG_DEBUG("partition not exist, skip remove uncontinue local tables", K(pkey), K(table_id));
  } else if (OB_FAIL(partition->get_pg_storage().remove_uncontinues_inc_tables(pkey, table_id))) {
    LOG_WARN("failed to remove uncontinue local tables", K(ret));
  }
  return ret;
}

int ObMigratePrepareTask::check_partition_integrity()
{
  int ret = OB_SUCCESS;
  ObPGPartitionGuard guard;
  ObIPartitionGroup* partition = NULL;
  ObPartitionArray local_pkeys;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (COPY_LOCAL_INDEX_OP == ctx_->replica_op_arg_.type_ || BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
             VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
    LOG_INFO("no need check partition integrity", "arg", ctx_->replica_op_arg_);
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_WARN("partition should not be NULL", K(ret), KP(partition));
  } else if (OB_FAIL(partition->get_all_pg_partition_keys(local_pkeys, true /*include_trans_table*/))) {
    LOG_WARN("failed to get pg partition keys", K(ret), K(*ctx_));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      ObPartitionMigrateCtx& pctx = ctx_->part_ctx_array_.at(i);
      const ObPartitionKey& remote_pkey = pctx.copy_info_.meta_.pkey_;
      pctx.is_partition_exist_ = false;
      for (int64_t j = 0; OB_SUCC(ret) && j < local_pkeys.count() && !pctx.is_partition_exist_; ++j) {
        const ObPartitionKey& local_pkey = local_pkeys.at(j);
        if (local_pkey == remote_pkey) {
          pctx.is_partition_exist_ = true;
        }
      }

      LOG_INFO("check partition exist", K(remote_pkey), "is_exist", pctx.is_partition_exist_);
    }
  }
  return ret;
}

int ObMigratePrepareTask::create_pg_partition(
    const ObPGPartitionStoreMeta& meta, ObIPartitionGroup* partition, const bool in_slog_trans)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (!meta.is_valid() || OB_ISNULL(partition)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("create pg partition get invalid argument", K(ret), K(meta), KP(partition));
  } else {
    ObTablesHandle sstables_handle;  // empty
    obrpc::ObCreatePartitionArg arg;
    const ObSavedStorageInfoV2& saved_storage_info = ctx_->pg_meta_.storage_info_;
    arg.schema_version_ = saved_storage_info.get_data_info().get_schema_version();
    arg.lease_start_ = meta.create_timestamp_;
    arg.restore_ = ctx_->is_restore_;
    const int64_t multi_version_start = meta.multi_version_start_;
    const int64_t data_table_id = meta.data_table_id_;
    const uint64_t unused = 0;
    const bool is_replay = false;

    if (OB_FAIL(partition->create_pg_partition(
            meta.pkey_, multi_version_start, data_table_id, arg, in_slog_trans, is_replay, unused, sstables_handle))) {
      LOG_WARN("fail to create pg partition", K(ret), K(meta));
    }
  }
  return ret;
}

int ObMigratePrepareTask::inner_get_partition_table_info_reader(
    const ObMigrateSrcInfo& src_info, ObIPGPartitionBaseDataMetaObReader*& reader)
{
  int ret = OB_SUCCESS;
  UNUSED(src_info);
  const bool is_copy_index = COPY_LOCAL_INDEX_OP == ctx_->replica_op_arg_.type_ ||
                             COPY_GLOBAL_INDEX_OP == ctx_->replica_op_arg_.type_ ||
                             LINK_SHARE_MAJOR_OP == ctx_->replica_op_arg_.type_;

  ObPGPartitionBaseDataMetaObReader* tmp_reader = NULL;
  obrpc::ObFetchPGPartitionInfoArg rpc_arg;
  rpc_arg.pg_key_ = ctx_->replica_op_arg_.key_;
  rpc_arg.snapshot_version_ = ctx_->pg_meta_.storage_info_.get_data_info().get_publish_version();
  rpc_arg.log_ts_ = ctx_->pg_meta_.storage_info_.get_data_info().get_last_replay_log_ts();
  rpc_arg.is_only_major_sstable_ = is_copy_index;

  if (OB_ISNULL(cp_fty_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cp fty should not be NULL", K(ret), KP(cp_fty_));
  } else if (NULL == (tmp_reader = cp_fty_->get_pg_info_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(
                 *srv_rpc_proxy_, *bandwidth_throttle_, src_info.src_addr_, rpc_arg, src_info.cluster_id_))) {
    LOG_WARN("fail to init partition meta info reader", K(ret), K(src_info));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::inner_get_partition_table_info_restore_reader_v1(
    const ObMigrateSrcInfo& src_info, ObIPGPartitionBaseDataMetaObReader*& reader)
{
  int ret = OB_SUCCESS;
  UNUSED(src_info);
  ObPGPartitionBaseDataMetaRestoreReaderV1* tmp_reader = NULL;
  ObPartitionGroupMetaRestoreReaderV1* restore_meta_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("restore_meta_reader_ must not null", K(ret));
  } else if (OB_ISNULL(cp_fty_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cp fty should not be NULL", K(ret), KP(cp_fty_));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_pg_info_restore_reader_v1())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "phaysical restore macro index should not be NULL", K(ret), KP(ctx_->restore_meta_reader_));
  } else if (ObIPartitionGroupMetaRestoreReader::PG_META_RESTORE_READER_V1 != ctx_->restore_meta_reader_->get_type()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "restore meta reader type is unexpected", K(ret), K(ctx_->restore_meta_reader_->get_type()));
  } else if (FALSE_IT(restore_meta_reader =
                          reinterpret_cast<ObPartitionGroupMetaRestoreReaderV1*>(ctx_->restore_meta_reader_))) {
  } else if (OB_FAIL(tmp_reader->init(ctx_->pg_meta_.partitions_, restore_meta_reader))) {
    LOG_WARN("fail to init partition table info restore reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::inner_get_partition_table_info_restore_reader_v2(
    const ObMigrateSrcInfo& src_info, ObIPGPartitionBaseDataMetaObReader*& reader)
{
  int ret = OB_SUCCESS;
  UNUSED(src_info);
  ObPGPartitionBaseDataMetaRestoreReaderV2* tmp_reader = NULL;
  ObPartitionGroupMetaRestoreReaderV2* restore_meta_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("restore_meta_reader_ must not null", K(ret));
  } else if (OB_ISNULL(cp_fty_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cp fty should not be NULL", K(ret), KP(cp_fty_));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_pg_info_restore_reader_v2())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_ISNULL(ctx_->restore_meta_reader_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "phaysical restore macro index should not be NULL", K(ret), KP(restore_meta_reader));
  } else if (ObIPartitionGroupMetaRestoreReader::PG_META_RESTORE_READER_V2 != ctx_->restore_meta_reader_->get_type()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "restore meta reader type is unexpected", K(ret), K(ctx_->restore_meta_reader_->get_type()));
  } else if (FALSE_IT(restore_meta_reader =
                          reinterpret_cast<ObPartitionGroupMetaRestoreReaderV2*>(ctx_->restore_meta_reader_))) {
  } else if (OB_FAIL(tmp_reader->init(ctx_->pg_meta_.partitions_, restore_meta_reader))) {
    LOG_WARN("fail to init partition table info restore reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::inner_get_partition_table_info_backup_reader(
    const ObMigrateSrcInfo& src_info, ObIPGPartitionBaseDataMetaObReader*& reader)
{
  int ret = OB_SUCCESS;
  UNUSED(src_info);
  ObPGPartitionBaseDataMetaBackupReader* tmp_reader = NULL;

  if (OB_ISNULL(cp_fty_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cp fty should not be NULL", K(ret), KP(cp_fty_));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_pg_info_backup_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_ISNULL(ctx_->backup_meta_reader_)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("ctx_->backup_meta_reader_ must not null", K(ret));
  } else if (OB_FAIL(tmp_reader->init(ctx_->pg_meta_.partitions_, ctx_->backup_meta_reader_))) {
    LOG_WARN("fail to init partition table info restore reader", K(ret));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigratePrepareTask::get_partition_table_info_reader(
    const ObMigrateSrcInfo& src_info, ObIPGPartitionBaseDataMetaObReader*& reader)
{
  int ret = OB_SUCCESS;
  reader = NULL;
  const int64_t compatible = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (!src_info.is_valid() && RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN(
        "get partition table info reader get invalid argument", K(ret), K(src_info), K(ctx_->replica_op_arg_.type_));
  } else if (ctx_->replica_op_arg_.is_physical_restore_leader() && share::REPLICA_RESTORE_DATA == ctx_->is_restore_) {
    if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
      if (OB_FAIL(inner_get_partition_table_info_restore_reader_v1(src_info, reader))) {
        LOG_WARN("failed to get partition table info restore reader", K(ret));
      }
    } else if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
      if (OB_FAIL(inner_get_partition_table_info_restore_reader_v2(src_info, reader))) {
        LOG_WARN("failed to get partition table info restore reader", K(ret));
      }
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("restore compatible version is expected", K(ret), K(compatible));
    }
  } else if (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ &&
             share::REPLICA_LOGICAL_RESTORE_DATA == ctx_->is_restore_) {
    ret = OB_NOT_SUPPORTED;
    LOG_ERROR("not support logical restore", K(ret));
  } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(inner_get_partition_table_info_backup_reader(src_info, reader))) {
      LOG_WARN("failed to get partition table info backup reader", K(ret));
    }
  } else {
    if (OB_FAIL(inner_get_partition_table_info_reader(src_info, reader))) {
      LOG_WARN("failed to get partition table info reader", K(ret));
    }
  }
  return ret;
}

int ObMigratePrepareTask::check_backup_data_continues()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition_group = NULL;
  clog::ObPGLogArchiveStatus pg_log_archive_status;
  ObLogArchiveBackupInfo archive_backup_info;
  const int64_t start_ts = ObTimeUtility::current_time();
  static const int64_t OB_MAX_RETRY_TIME = 60 * 1000 * 1000;  // 60s
  static const int64_t OB_SINGLE_SLEEP_US = 1 * 1000 * 1000;  // 1s
  const int64_t last_replay_log_id = ctx_->pg_meta_.storage_info_.get_clog_info().get_last_replay_log_id();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (BACKUP_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    // do nothing
  } else if (OB_ISNULL(partition_group = ctx_->get_partition())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("backup local partition should not be NULL", K(ret), KP(partition_group), K(*ctx_));
  } else {
    while (OB_SUCC(ret)) {
      if (OB_FAIL(partition_group->get_log_archive_status(pg_log_archive_status))) {
        LOG_WARN("failed to get log archive status", K(ret), K(*ctx_));
      } else if (OB_FAIL(ObBackupInfoMgr::get_instance().get_log_archive_backup_info(archive_backup_info))) {
        LOG_WARN("failed to get log archive backup info", K(ret));
      } else if (ObLogArchiveStatus::INVALID == pg_log_archive_status.status_) {
        if (ObLogArchiveStatus::DOING == archive_backup_info.status_.status_) {
          LOG_WARN("partition group log archive status is invalid, need retry",
              K(pg_log_archive_status),
              K(archive_backup_info));
          ret = OB_EAGAIN;
        } else {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN(
              "server do not archive log, can not backup", K(ret), K(pg_log_archive_status), K(archive_backup_info));
        }
      } else if (ObLogArchiveStatus::DOING == pg_log_archive_status.status_) {
        if (pg_log_archive_status.archive_incarnation_ != archive_backup_info.status_.incarnation_ ||
            pg_log_archive_status.log_archive_round_ != archive_backup_info.status_.round_) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("pg archive round or incarnation not equal to server archive info",
              K(ret),
              K(pg_log_archive_status),
              K(archive_backup_info));
        } else if (pg_log_archive_status.round_start_log_id_ < 1) {
          ret = OB_LOG_ARCHIVE_STAT_NOT_MATCH;
          LOG_WARN("log archive status is not match", K(ret), K(pg_log_archive_status));
        } else if (last_replay_log_id + 1 < pg_log_archive_status.round_start_log_id_) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("base data and log archive data do not continues",
              K(ret),
              K(pg_log_archive_status),
              K(ctx_->pg_meta_),
              K(last_replay_log_id));
        } else {
          break;
        }
      } else {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("log archive status is unexpected", K(ret), K(pg_log_archive_status));
      }

      if (OB_EAGAIN == ret) {
        const int64_t cost_ts = ObTimeUtility::current_time() - start_ts;
        if (cost_ts < OB_MAX_RETRY_TIME) {
          usleep(OB_SINGLE_SLEEP_US);
          ret = OB_SUCCESS;
        } else {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("server start do archive log, but partition retry many times status still wrong",
              K(ret),
              K(pg_log_archive_status),
              K(archive_backup_info),
              K(*ctx_));
        }
      }
    }
  }
  return ret;
}

ObMigrateLogicSSTableCtx::SubLogicTask::SubLogicTask() : end_key_(), block_write_ctx_(), lob_block_write_ctx_()
{}

ObMigrateLogicSSTableCtx::SubLogicTask::~SubLogicTask()
{}

ObMigrateLogicSSTableCtx::ObMigrateLogicSSTableCtx()
    : tasks_(NULL),
      task_count_(0),
      meta_(),
      allocator_(ObModIds::OB_PARTITION_MIGRATOR),
      src_info_(),
      table_key_(),
      dest_base_version_(-1),
      data_checksum_(0)
{}

ObMigrateLogicSSTableCtx::~ObMigrateLogicSSTableCtx()
{
  reset();
}

void ObMigrateLogicSSTableCtx::reset()
{
  for (int64_t i = 0; i < task_count_; ++i) {
    tasks_[i].~SubLogicTask();
  }
  tasks_ = NULL;
  task_count_ = 0;
  meta_.reset();
  allocator_.reset();
  src_info_.reset();
  table_key_.reset();
  dest_base_version_ = -1;
  data_checksum_ = 0;
}

bool ObMigrateLogicSSTableCtx::is_valid()
{
  bool valid = true;

  if (NULL == tasks_ || task_count_ <= 0 || !meta_.is_valid() || !src_info_.is_valid() || !table_key_.is_valid() ||
      dest_base_version_ < table_key_.trans_version_range_.base_version_ ||
      dest_base_version_ >= table_key_.trans_version_range_.snapshot_version_) {
    valid = false;
  } else {
    for (int64_t i = 0; valid && i < task_count_; ++i) {
      if (!tasks_[i].end_key_.is_valid()) {
        valid = false;
      }
    }
  }
  return valid;
}

int ObMigrateLogicSSTableCtx::build_sub_task(const common::ObIArray<common::ObStoreRowkey>& end_key_list)
{
  int ret = OB_SUCCESS;
  void* buf = NULL;

  if (NULL != tasks_) {
    ret = OB_INIT_TWICE;
    LOG_WARN("cannot init twice", K(ret));
  } else if (end_key_list.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(end_key_list));
  } else if (OB_ISNULL(buf = allocator_.alloc(sizeof(SubLogicTask) * end_key_list.count()))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to alloc sub logic task buf", K(ret));
  } else {
    task_count_ = end_key_list.count();
    tasks_ = new (buf) SubLogicTask[task_count_];
    for (int64_t i = 0; OB_SUCC(ret) && i < task_count_; ++i) {
      if (OB_FAIL(end_key_list.at(i).deep_copy(tasks_[i].end_key_, allocator_))) {
        LOG_WARN("failed to deep copy end key", K(ret));
      }

      if (OB_SUCC(ret) && i == task_count_ - 1) {
        if (!tasks_[i].end_key_.is_max()) {
          ret = OB_ERR_SYS;
          LOG_ERROR("the last end key must be max row", K(ret), K(tasks_[i].end_key_), K(end_key_list));
        }
      }
    }
  }
  return ret;
}

int ObMigrateLogicSSTableCtx::get_sub_task(const int64_t idx, SubLogicTask*& sub_task)
{
  int ret = OB_SUCCESS;
  sub_task = NULL;

  if (OB_ISNULL(tasks_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not init", K(ret), K(*this));
  } else if (idx < 0 || idx >= task_count_) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(idx), K(*this));
  } else {
    sub_task = tasks_ + idx;
  }
  return ret;
}

int ObMigrateLogicSSTableCtx::get_dest_table_key(ObITable::TableKey& dest_table_key)
{
  int ret = OB_SUCCESS;

  if (!is_valid()) {
    ret = OB_NOT_INIT;
    LOG_WARN("invalid ctx", K(ret), K(*this));
  } else if (table_key_.trans_version_range_.base_version_ == dest_base_version_) {
    dest_table_key = table_key_;
    dest_table_key.table_type_ = ObITable::MINI_MINOR_SSTABLE;
  } else {
    dest_table_key = table_key_;
    dest_table_key.table_type_ = ObITable::MINI_MINOR_SSTABLE;
    dest_table_key.trans_version_range_.base_version_ = dest_base_version_;
    dest_table_key.version_ = 0;
    if (dest_base_version_ > dest_table_key.trans_version_range_.multi_version_start_) {
      dest_table_key.trans_version_range_.multi_version_start_ = dest_base_version_;
    }
    LOG_INFO(
        "base version not match, rewrite trans version range", K(dest_base_version_), K_(table_key), K(dest_table_key));
  }
  return ret;
}

ObMigrateCopyLogicTask::ObMigrateCopyLogicTask()
    : ObITask(TASK_TYPE_MIGRATE_COPY_LOGIC),
      is_inited_(false),
      ctx_(NULL),
      task_idx_(-1),
      sstable_ctx_(NULL),
      sub_task_(NULL)
{}

ObMigrateCopyLogicTask::~ObMigrateCopyLogicTask()
{}

int ObMigrateCopyLogicTask::init(const int64_t task_idx, ObMigrateLogicSSTableCtx& sstable_ctx, ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (task_idx < 0 || task_idx >= sstable_ctx.task_count_ || !sstable_ctx.is_valid() || !ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(task_idx), K(sstable_ctx), K(ctx));
  } else {
    ctx_ = &ctx;
    task_idx_ = task_idx;
    sstable_ctx_ = &sstable_ctx;
    sub_task_ = sstable_ctx.tasks_ + task_idx_;
    is_inited_ = true;
  }
  return ret;
}

int ObMigrateCopyLogicTask::generate_next_task(ObITask*& next_task)
{
  int ret = OB_SUCCESS;
  const int64_t next_task_idx = task_idx_ + 1;
  ObMigrateCopyLogicTask* tmp_next_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not init", K(ret));
  } else if (task_idx_ + 1 == sstable_ctx_->task_count_) {
    ret = OB_ITER_END;
  } else if (OB_FAIL(dag_->alloc_task(tmp_next_task))) {
    LOG_WARN("failed to alloc task", K(ret));
  } else if (OB_FAIL(tmp_next_task->init(next_task_idx, *sstable_ctx_, *ctx_))) {
    LOG_WARN("failed o init next task", K(ret));
  } else {
    next_task = tmp_next_task;
  }
  return ret;
}

int ObMigrateCopyLogicTask::process()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObLogicRowFetcher fetcher;
  obrpc::ObFetchLogicRowArg reader_arg;
  ObMigrateLogicRowWriter writer;
  obrpc::ObPartitionServiceRpcProxy* srv_rpc_proxy = MIGRATOR.get_svr_rpc_proxy();
  common::ObInOutBandwidthThrottle* bandwidth_throttle = MIGRATOR.get_bandwidth_throttle();
  DEBUG_SYNC(BEFORE_MIGRATE_COPY_LOGIC_DATA);

  if (NULL != sstable_ctx_) {
    LOG_INFO("start ObMigrateCopyLogicTask process",
        "table_key",
        sstable_ctx_->table_key_,
        "dest_base_version",
        sstable_ctx_->dest_base_version_);
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_ISNULL(srv_rpc_proxy) || OB_ISNULL(bandwidth_throttle)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("srv_rpc_proxy or bandwidth_throttle must not null", K(ret), KP(srv_rpc_proxy), KP(bandwidth_throttle));
  } else {
    ctx_->action_ = ObMigrateCtx::COPY_MINOR;
    if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
      LOG_WARN("failed to update_partition_migration_status", K(tmp_ret));
    }

    reader_arg.table_key_ = sstable_ctx_->table_key_;
    reader_arg.key_range_.set_left_open();
    reader_arg.schema_version_ = sstable_ctx_->meta_.schema_version_;
    if (task_idx_ == 0) {
      reader_arg.key_range_.set_start_key(ObStoreRowkey::MIN_STORE_ROWKEY);
    } else {
      reader_arg.key_range_.set_start_key(sstable_ctx_->tasks_[task_idx_ - 1].end_key_);
    }

    if (task_idx_ == sstable_ctx_->task_count_ - 1) {
      reader_arg.key_range_.set_end_key(ObStoreRowkey::MAX_STORE_ROWKEY);
      reader_arg.key_range_.set_right_open();
    } else {
      reader_arg.key_range_.set_end_key(sub_task_->end_key_);
      reader_arg.key_range_.set_right_closed();
    }
    reader_arg.data_checksum_ = sstable_ctx_->data_checksum_;
    if (OB_FAIL(fetcher.init(*srv_rpc_proxy,
            *bandwidth_throttle,
            sstable_ctx_->src_info_.src_addr_,
            reader_arg,
            ctx_->replica_op_arg_.cluster_id_))) {
      LOG_WARN("failed to init reader", K(ret));
    } else if (OB_FAIL(writer.init(
                   &fetcher, ctx_->replica_op_arg_.key_, ctx_->get_partition()->get_storage_file_handle()))) {
      LOG_WARN("failed to init writer", K(ret));
    } else if (OB_FAIL(writer.process(sub_task_->block_write_ctx_, sub_task_->lob_block_write_ctx_))) {
      LOG_WARN("failed to process writer", K(ret));
    } else {
      const int64_t data_checksum = writer.get_data_checksum();
      if (data_checksum != sstable_ctx_->data_checksum_) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("logic migrate data checksum is not equal",
            K(ret),
            "dst data_checksum",
            data_checksum,
            "src data_checksum",
            sstable_ctx_->data_checksum_);
      }
    }
  }

#ifdef ERRSIM
  if (OB_SUCC(ret)) {
    ret = E(EventTable::EN_MIGRATE_LOGIC_TASK) OB_SUCCESS;
    if (OB_FAIL(ret)) {
      LOG_ERROR("fake logic migrate fail", K(ret));
    }
  }
#endif

  if (OB_FAIL(ret) && NULL != ctx_) {
    if (ctx_->is_need_retry(ret)) {
      ctx_->need_rebuild_ = true;
      LOG_INFO("migreate copy logic task need retry", K(ret), K(*ctx_));
    }
    ctx_->set_result_code(ret);
  }

  if (NULL != sstable_ctx_) {
    LOG_INFO("end ObMigrateCopyLogicTask process",
        "table_key",
        sstable_ctx_->table_key_,
        "dest_base_version",
        sstable_ctx_->dest_base_version_);
  }
  return ret;
}

ObMigrateFinishLogicTask::ObMigrateFinishLogicTask()
    : ObITask(TASK_TYPE_MIGRATE_FINISH_LOGIC), is_inited_(false), part_migrate_ctx_(NULL), sstable_ctx_()
{}

ObMigrateFinishLogicTask::~ObMigrateFinishLogicTask()
{}

int ObMigrateFinishLogicTask::init(ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (!part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(part_migrate_ctx));
  } else {
    is_inited_ = true;
    part_migrate_ctx_ = &part_migrate_ctx;
  }
  return ret;
}

int ObMigrateFinishLogicTask::process()
{
  int ret = OB_SUCCESS;
  storage::ObCreateSSTableParamWithTable create_sstable_param;
  ObSSTable* sstable = NULL;
  ObSchemaGetterGuard schema_guard;
  ObTableHandle handle;
  ObMigrateCtx* ctx = part_migrate_ctx_->ctx_;

  bool has_lob_column = false;
  const uint64_t table_id = sstable_ctx_.table_key_.table_id_;
  const uint64_t tenant_id = is_inner_table(table_id) ? OB_SYS_TENANT_ID : extract_tenant_id(table_id);
  const bool check_formal =
      extract_pure_id(table_id) > OB_MAX_CORE_TABLE_ID;  // Avoid the problem of circular dependency
  LOG_INFO("start ObMigrateFinishLogicTask process",
      "table_key",
      sstable_ctx_.table_key_,
      "dest_base_version",
      sstable_ctx_.dest_base_version_);
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(sstable_ctx_.get_dest_table_key(create_sstable_param.table_key_))) {
    LOG_WARN("failed to get dest table key", K(ret), K(sstable_ctx_));
  } else {
    create_sstable_param.schema_version_ = sstable_ctx_.meta_.schema_version_;
    create_sstable_param.logical_data_version_ = create_sstable_param.table_key_.trans_version_range_.snapshot_version_;

    if (OB_FAIL(MIGRATOR.get_schema_service()->get_tenant_schema_guard(
            tenant_id, schema_guard, sstable_ctx_.meta_.schema_version_, OB_INVALID_VERSION))) {
      LOG_WARN("failed to get schema guard", K(ret), K(sstable_ctx_.meta_));
    } else if (check_formal && OB_FAIL(schema_guard.check_formal_guard())) {
      LOG_WARN("schema_guard is not formal", K(ret), K(tenant_id));
    } else if (OB_FAIL(
                   schema_guard.get_table_schema(sstable_ctx_.table_key_.table_id_, create_sstable_param.schema_))) {
      LOG_WARN("Fail to get table schema, ", K(ret), K(sstable_ctx_.table_key_));
    } else if (OB_ISNULL(create_sstable_param.schema_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("Unexpected null table schema", K(ret), K(sstable_ctx_.table_key_));
    } else if (OB_FAIL(create_sstable_param.schema_->has_lob_column(has_lob_column, true))) {
      LOG_WARN("Failed to check lob column in table schema", K(ret));
    } else {
      ObPGCreateSSTableParam param;
      param.with_table_param_ = &create_sstable_param;
      for (int64_t task_idx = 0; OB_SUCC(ret) && task_idx < sstable_ctx_.task_count_; ++task_idx) {
        ObMigrateLogicSSTableCtx::SubLogicTask& sub_task = sstable_ctx_.tasks_[task_idx];
        if (!sub_task.block_write_ctx_.file_handle_.is_valid() &&
            OB_FAIL(sub_task.block_write_ctx_.file_handle_.assign(
                part_migrate_ctx_->ctx_->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
          LOG_WARN("fail to assign file handle", K(ret));
        } else if (!sub_task.lob_block_write_ctx_.file_handle_.is_valid() &&
                   OB_FAIL(sub_task.lob_block_write_ctx_.file_handle_.assign(
                       part_migrate_ctx_->ctx_->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
          LOG_WARN("fail to assign file handle", K(ret));
        } else if (OB_FAIL(param.data_blocks_.push_back(&sub_task.block_write_ctx_))) {
          LOG_WARN("fail to push back data block write ctx", K(ret));
        } else if (has_lob_column && sub_task.lob_block_write_ctx_.is_valid() &&
                   !sub_task.lob_block_write_ctx_.is_empty()) {
          if (OB_FAIL(param.lob_blocks_.push_back(&sub_task.lob_block_write_ctx_))) {
            LOG_WARN("fail to push back lob block write ctx", K(ret));
          }
        }
      }

      if (OB_SUCC(ret)) {
        ObIPartitionGroup* pg = nullptr;
        if (OB_ISNULL(pg = part_migrate_ctx_->ctx_->partition_guard_.get_partition_group())) {
          ret = OB_ERR_SYS;
          LOG_WARN("partition must not null", K(ret));
        } else if (OB_FAIL(pg->create_sstable(param, handle))) {
          LOG_WARN("fail to create sstable", K(ret));
        } else if (OB_FAIL(handle.get_sstable(sstable))) {
          LOG_WARN("fail to get sstable", K(ret));
        } else if (OB_FAIL(part_migrate_ctx_->add_sstable(*sstable))) {
          LOG_WARN("failed to add sstable", K(ret));
        }
      }
    }
  }

  if (OB_FAIL(ret) && NULL != ctx) {
    ctx->set_result_code(ret);
  }

  LOG_INFO("end ObMigrateFinishLogicTask process",
      "table_key",
      sstable_ctx_.table_key_,
      "dest_base_version",
      sstable_ctx_.dest_base_version_);
  return ret;
}

ObMigratePhysicalSSTableCtx::SubTask::SubTask()
    : block_info_(NULL), block_count_(0), pkey_(), allocator_(ObModIds::OB_PARTITION_MIGRATOR)
{}

ObMigratePhysicalSSTableCtx::SubTask::~SubTask()
{
  int ret = OB_SUCCESS;
  storage::ObIPartitionGroupGuard pg_guard;
  blocksstable::ObStorageFile* pg_file = NULL;
  if (OB_FAIL(ObFileSystemUtil::get_pg_file_with_guard(pkey_, pg_guard, pg_file))) {
    LOG_ERROR("meta must not null", K(ret), K_(pkey));
  } else {
    if (NULL != block_info_ && block_count_ > 0) {
      for (int64_t i = 0; i < block_count_; ++i) {
        if (nullptr != block_info_[i].full_meta_.meta_) {
          block_info_[i].full_meta_.meta_->~ObMacroBlockMetaV2();
          block_info_[i].full_meta_.meta_ = nullptr;
        }
        if (nullptr != block_info_[i].full_meta_.schema_) {
          block_info_[i].full_meta_.schema_->~ObMacroBlockSchemaInfo();
          block_info_[i].full_meta_.schema_ = nullptr;
        }
        if (block_info_[i].macro_block_id_.is_valid()) {
          if (OB_FAIL(pg_file->dec_ref(block_info_[i].macro_block_id_))) {
            LOG_WARN("fail to dec ref, ", K(ret));
          }
          block_info_[i].need_copy_ = false;
          block_info_[i].macro_block_id_.reset();
        }
      }
    }
  }
  allocator_.clear();
}

ObMigratePhysicalSSTableCtx::ObMigratePhysicalSSTableCtx()
    : tasks_(NULL),
      task_count_(0),
      allocator_(ObModIds::OB_PARTITION_MIGRATOR),
      meta_(allocator_),
      src_info_(),
      sstable_info_(),
      is_leader_restore_(false),
      restore_version_(0)
{}

ObMigratePhysicalSSTableCtx::~ObMigratePhysicalSSTableCtx()
{
  reset();
}

bool ObMigratePhysicalSSTableCtx::is_valid()
{
  bool valid = true;
  if (NULL == tasks_ || task_count_ <= 0 || !meta_.is_valid() || (!is_leader_restore_ && !src_info_.is_valid()) ||
      !sstable_info_.is_valid()) {
    valid = false;
    LOG_WARN("ctx not valid",
        K(task_count_),
        KP(tasks_),
        K(meta_.is_valid()),
        K(src_info_.is_valid()),
        K(sstable_info_.is_valid()));
  } else {
    for (int64_t i = 0; valid && i < task_count_; ++i) {
      if (tasks_[i].block_count_ <= 0 || NULL == tasks_[i].block_info_) {
        valid = false;
        LOG_WARN("sub task not valid", K(i), K(task_count_), K(tasks_[i]));
      }
    }
  }
  return valid;
}

void ObMigratePhysicalSSTableCtx::reset()
{
  if (NULL != tasks_ && task_count_ > 0) {
    for (int64_t task_idx = 0; task_idx < task_count_; ++task_idx) {
      ObMigratePhysicalSSTableCtx::SubTask& task = tasks_[task_idx];
      task.~SubTask();
    }
  }
  tasks_ = NULL;
  task_count_ = 0;
  meta_.reset();
  allocator_.reset();
  src_info_.reset();
  sstable_info_.reset();
  is_leader_restore_ = false;
  restore_version_ = 0;
}

int ObMigratePhysicalSSTableCtx::get_dest_table_key(ObITable::TableKey& dest_table_key)
{
  int ret = OB_SUCCESS;

  if (OB_FAIL(ObDestTableKeyManager::convert_sstable_info_to_table_key(sstable_info_, dest_table_key))) {
    LOG_WARN("failed to conver sstable info to table key", K(ret), K(sstable_info_));
  } else if (ObITable::is_major_sstable(sstable_info_.src_table_key_.table_type_)) {
    dest_table_key = sstable_info_.src_table_key_;
    if (is_leader_restore_) {
      dest_table_key.version_ = restore_version_;
    }
  }

  return ret;
}

ObMigrateCopyPhysicalTask::ObMigrateCopyPhysicalTask()
    : ObITask(TASK_TYPE_MIGRATE_COPY_PHYSICAL),
      is_inited_(false),
      ctx_(NULL),
      task_idx_(-1),
      sstable_ctx_(NULL),
      sub_task_(NULL),
      cp_fty_(NULL)
{}

ObMigrateCopyPhysicalTask::~ObMigrateCopyPhysicalTask()
{}

int ObMigrateCopyPhysicalTask::init(const int64_t task_idx, ObMigratePhysicalSSTableCtx& sstable_ctx, ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret), K(is_inited_));
  } else if (task_idx < 0 || task_idx >= sstable_ctx.task_count_ || !sstable_ctx.is_valid() || !ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(task_idx), K(sstable_ctx.is_valid()), K(ctx.is_valid()), K(sstable_ctx), K(ctx));
  } else {
    is_inited_ = true;
    ctx_ = &ctx;
    task_idx_ = task_idx;
    sstable_ctx_ = &sstable_ctx;
    sub_task_ = sstable_ctx.tasks_ + task_idx_;
    cp_fty_ = MIGRATOR.get_cp_fty();
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::get_macro_block_reader(obrpc::ObPartitionServiceRpcProxy* srv_rpc_proxy,
    common::ObInOutBandwidthThrottle* bandwidth_throttle, const ObMigrateSrcInfo& src_info,
    common::ObIArray<ObMigrateArgMacroBlockInfo>& list, ObITable::TableKey& table_key,
    const ObRestoreInfo* restore_info, ObIPartitionMacroBlockReader*& reader)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (ctx_->replica_op_arg_.is_physical_restore_leader() && share::REPLICA_RESTORE_DATA == ctx_->is_restore_) {
    const int64_t compatible = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.compatible_;
    if (OB_BACKUP_COMPATIBLE_VERSION_V1 == compatible) {
      if (OB_FAIL(get_macro_block_restore_reader_v1(
              *bandwidth_throttle, list, ctx_->replica_op_arg_.phy_restore_arg_, table_key, reader))) {
        STORAGE_LOG(WARN, "get_macro_block_restore_reader_v1 fail", K(ret), K(table_key));
      }
    } else if (OB_BACKUP_COMPATIBLE_VERSION_V2 == compatible) {
      if (OB_FAIL(get_macro_block_restore_reader_v2(
              *bandwidth_throttle, list, ctx_->replica_op_arg_.phy_restore_arg_, table_key, reader))) {
        STORAGE_LOG(WARN, "get_macro_block_restore_reader_v2 fail", K(ret), K(table_key));
      }
    } else {
      ret = OB_NOT_SUPPORTED;
      LOG_ERROR("not supported compatible", K(ret), K(compatible));
    }
  } else if (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(get_macro_block_restore_reader(*bandwidth_throttle, list, *restore_info, table_key, reader))) {
      STORAGE_LOG(WARN, "get_macro_block_restore_reader", K(ret), K(table_key));
    }
  } else {
    if (OB_FAIL(get_macro_block_ob_reader(*srv_rpc_proxy, *bandwidth_throttle, src_info, table_key, list, reader))) {
      STORAGE_LOG(WARN, "failed to get_macro_block_ob_reader", K(ret));
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::get_macro_block_restore_reader(common::ObInOutBandwidthThrottle& bandwidth_throttle,
    common::ObIArray<ObMigrateArgMacroBlockInfo>& list, const ObRestoreInfo& restore_info,
    const ObITable::TableKey& table_key, ObIPartitionMacroBlockReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMacroBlockRestoreReader* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_macro_block_restore_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(bandwidth_throttle, list, restore_info, table_key.pkey_, table_key.table_id_))) {
    STORAGE_LOG(WARN, "failed to init restore reader", K(ret), K(table_key));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::get_macro_block_restore_reader_v1(common::ObInOutBandwidthThrottle& bandwidth_throttle,
    common::ObIArray<ObMigrateArgMacroBlockInfo>& list, const share::ObPhysicalRestoreArg& restore_info,
    const ObITable::TableKey& table_key, ObIPartitionMacroBlockReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMacroBlockRestoreReaderV1* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (ctx_->macro_indexs_->get_type() != ObIPhyRestoreMacroIndexStore::PHY_RESTORE_MACRO_INDEX_STORE_V1) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("invlaid macro index type", K(ret), "type", ctx_->macro_indexs_->get_type());
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_macro_block_restore_reader_v1())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(bandwidth_throttle,
                 list,
                 restore_info,
                 *static_cast<const ObPhyRestoreMacroIndexStore*>(ctx_->macro_indexs_),
                 table_key))) {
    STORAGE_LOG(WARN, "failed to init restore reader", K(ret), K(table_key));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::get_macro_block_restore_reader_v2(common::ObInOutBandwidthThrottle& bandwidth_throttle,
    common::ObIArray<ObMigrateArgMacroBlockInfo>& list, const share::ObPhysicalRestoreArg& restore_info,
    const ObITable::TableKey& table_key, ObIPartitionMacroBlockReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMacroBlockRestoreReaderV2* tmp_reader = NULL;
  ObPhyRestoreMacroIndexStoreV2* macro_index = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (OB_ISNULL(tmp_reader = cp_fty_->get_macro_block_restore_reader_v2())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_ISNULL(ctx_->macro_indexs_)) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "macro index should not be NULL", K(ret), KP(ctx_->macro_indexs_));
  } else if (ObIPhyRestoreMacroIndexStore::PHY_RESTORE_MACRO_INDEX_STORE_V2 != ctx_->macro_indexs_->get_type()) {
    ret = OB_ERR_UNEXPECTED;
    STORAGE_LOG(WARN, "macro index type is unexpected", K(ret), "type", ctx_->macro_indexs_->get_type());
  } else if (FALSE_IT(macro_index = reinterpret_cast<ObPhyRestoreMacroIndexStoreV2*>(ctx_->macro_indexs_))) {
  } else if (OB_FAIL(tmp_reader->init(bandwidth_throttle, list, restore_info, *macro_index, table_key))) {
    STORAGE_LOG(WARN, "failed to init restore reader", K(ret), K(table_key));
  } else {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::get_macro_block_ob_reader(obrpc::ObPartitionServiceRpcProxy& srv_rpc_proxy,
    common::ObInOutBandwidthThrottle& bandwidth_throttle, const ObMigrateSrcInfo& src_info,
    ObITable::TableKey& table_key, common::ObIArray<ObMigrateArgMacroBlockInfo>& list,
    ObIPartitionMacroBlockReader*& reader)
{
  int ret = OB_SUCCESS;
  ObPartitionMacroBlockObReader* tmp_reader = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    STORAGE_LOG(WARN, "not inited", K(ret));
  } else if (!is_replica_op_valid(ctx_->replica_op_arg_.type_) || RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    STORAGE_LOG(ERROR, "unexpected type", K(ret), K(*this), K(*ctx_));
  } else if (NULL == (tmp_reader = cp_fty_->get_macro_block_ob_reader())) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    STORAGE_LOG(WARN, "failed to get macro block ob reader", K(ret));
  } else if (OB_FAIL(tmp_reader->init(
                 srv_rpc_proxy, bandwidth_throttle, src_info.src_addr_, table_key, list, src_info.cluster_id_))) {
    STORAGE_LOG(WARN, "failed to init ob reader", K(ret));
  }

  if (OB_SUCC(ret)) {
    reader = tmp_reader;
    tmp_reader = NULL;
  }

  if (NULL != cp_fty_) {
    if (OB_FAIL(ret)) {
      if (NULL != reader) {
        cp_fty_->free(reader);
        reader = NULL;
      }
    }
    if (NULL != tmp_reader) {
      cp_fty_->free(tmp_reader);
      tmp_reader = NULL;
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::generate_next_task(ObITask*& next_task)
{
  int ret = OB_SUCCESS;
  const int64_t next_task_idx = task_idx_ + 1;
  ObMigrateCopyPhysicalTask* tmp_next_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (task_idx_ + 1 == sstable_ctx_->task_count_) {
    ret = OB_ITER_END;
  } else if (OB_FAIL(dag_->alloc_task(tmp_next_task))) {
    LOG_WARN("failed to alloc task", K(ret));
  } else if (OB_FAIL(tmp_next_task->init(next_task_idx, *sstable_ctx_, *ctx_))) {
    LOG_WARN("failed o init next task", K(ret));
  } else {
    next_task = tmp_next_task;
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::process()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  common::ObArray<ObMigrateArgMacroBlockInfo> list;
  ObMigrateArgMacroBlockInfo arg_info;
  ObMacroBlockInfoPair info;
  ObMacroBlocksWriteCtx copied_ctx;
  ObMajorMacroBlockKey key;
  int64_t copy_count = 0;
  int64_t reuse_count = 0;
  storage::ObIPartitionGroupGuard pg_guard;
  blocksstable::ObStorageFile* pg_file = NULL;
  DEBUG_SYNC(BEFORE_MIGRATE_COPY_BASE_DATA);

  if (NULL != sstable_ctx_) {
    LOG_INFO("start ObMigrateCopyPhysicalTask process", "table_key", sstable_ctx_->sstable_info_.src_table_key_);
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(ObFileSystemUtil::get_pg_file_with_guard(
                 sstable_ctx_->sstable_info_.src_table_key_.pkey_, pg_guard, pg_file))) {
    LOG_ERROR("fail to get pg file", K(ret), K(sstable_ctx_->sstable_info_.src_table_key_.pkey_));
  } else if (!copied_ctx.file_handle_.is_valid() &&
             OB_FAIL(copied_ctx.file_handle_.assign(pg_guard.get_partition_group()->get_storage_file_handle()))) {
    LOG_WARN("fail to assign file handle", K(ret));
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < sub_task_->block_count_; ++i) {
    arg_info.reset();
    info.reset();
    key.reset();

    if (!sub_task_->block_info_[i].need_copy_) {
      ++reuse_count;
    } else {
      key.table_id_ = sstable_ctx_->sstable_info_.src_table_key_.table_id_;
      key.partition_id_ = sstable_ctx_->sstable_info_.src_table_key_.pkey_.get_partition_id();
      key.data_version_ = sub_task_->block_info_[i].pair_.data_version_;
      key.data_seq_ = sub_task_->block_info_[i].pair_.data_seq_;
      if (sub_task_->block_info_[i].macro_block_id_.is_valid()) {
        ret = OB_ERR_SYS;
        LOG_ERROR(
            "need copy block info's macro block id must be 0", K(ret), K(i), "block_info", sub_task_->block_info_[i]);
      } else if (key.is_valid() && BACKUP_REPLICA_OP != ctx_->replica_op_arg_.type_ &&
                 OB_SUCCESS == ctx_->reuse_block_mgr_.get_reuse_macro_meta(key, info)) {
        sub_task_->block_info_[i].need_copy_ = false;
        sub_task_->block_info_[i].macro_block_id_ = info.block_id_;
        sub_task_->block_info_[i].full_meta_ = info.meta_;
        if (OB_FAIL(pg_file->inc_ref(info.block_id_))) {
          LOG_ERROR("fail to inc ref, ", K(ret), K(info.block_id_));
        } else {
          ObTaskController::get().allow_next_syslog();
          LOG_INFO("reuse local macro id", K(info.block_id_), K(key), "meta", info.meta_);
          ++reuse_count;
        }
        if (OB_FAIL(ret)) {
          sub_task_->block_info_[i].macro_block_id_.reset();
        }
        // todo ():backup macro reuse
      } else {
        const int64_t max_block_count_per_task = ObMigratePrepareTask::MAX_MACRO_BLOCK_COUNT_PER_TASK;
        arg_info.fetch_arg_.macro_block_index_ = max_block_count_per_task * task_idx_ + i;
        arg_info.fetch_arg_.data_version_ = sub_task_->block_info_[i].pair_.data_version_;
        arg_info.fetch_arg_.data_seq_ = sub_task_->block_info_[i].pair_.data_seq_;
        if (OB_FAIL(list.push_back(arg_info))) {
          LOG_WARN("failed to add list", K(ret));
        }
      }
    }
  }

  if (OB_SUCC(ret) && list.count() > 0) {
    if (OB_FAIL(fetch_major_block_with_retry(list, copied_ctx))) {
      LOG_WARN("failed to fetch major block", K(ret), K(list));
    } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      copy_count += list.count();
    } else if (list.count() != copied_ctx.get_macro_block_count()) {
      ret = OB_ERR_SYS;
      LOG_ERROR("list count not match",
          K(ret),
          K(list.count()),
          K(copied_ctx.get_macro_block_count()),
          K(list),
          K(copied_ctx));
    } else if (copied_ctx.macro_block_list_.count() != copied_ctx.macro_block_meta_list_.count()) {
      ret = OB_ERR_SYS;
      LOG_WARN("error sys, macro block count do not match", K(ret), K(copied_ctx));
    } else {
      int64_t sub_task_idx = 0;
      bool found = false;
      for (int64_t i = 0; OB_SUCC(ret) && i < copied_ctx.macro_block_list_.count(); ++i) {
        blocksstable::ObSSTablePair pair;
        pair.data_version_ = list.at(i).fetch_arg_.data_version_;
        pair.data_seq_ = list.at(i).fetch_arg_.data_seq_;
        found = false;

        while (OB_SUCC(ret) && !found && sub_task_idx < sub_task_->block_count_) {
          if (sub_task_->block_info_[sub_task_idx].pair_ == pair) {
            found = true;
            sub_task_->block_info_[sub_task_idx].macro_block_id_ = copied_ctx.macro_block_list_.at(i);
            if (OB_FAIL(copied_ctx.macro_block_meta_list_.at(i).deep_copy(
                    sub_task_->block_info_[sub_task_idx].full_meta_, sub_task_->allocator_))) {
              LOG_WARN("fail to deep copy macro block meta, ", K(ret));
            } else if (OB_FAIL(pg_file->inc_ref(copied_ctx.macro_block_list_.at(i)))) {
              sub_task_->block_info_[sub_task_idx].macro_block_id_.reset();
              LOG_WARN("fail to inc ref", K(ret));
            } else if (OB_FAIL(ctx_->add_major_block_id(copied_ctx.macro_block_list_.at(i)))) {
              LOG_WARN("fail to add major block info", K(ret));
            }
          }
          ++sub_task_idx;
          ++copy_count;
        }

        if (!found && OB_SUCC(ret)) {
          ret = OB_ERR_SYS;
          LOG_ERROR("no macro block task found", K(ret), K(i), K(pair), K(*sub_task_), K(copied_ctx));
        }
      }
    }
  }

  if (OB_SUCCESS != (tmp_ret = calc_migrate_data_statics(copy_count, reuse_count))) {
    LOG_WARN("failed to calc migrate data statics", K(ret));
  }
  if (OB_FAIL(ret) && NULL != ctx_) {
    if (ctx_->is_need_retry(ret)) {
      ctx_->need_rebuild_ = true;
      LOG_INFO("migreate copy physical task need retry", K(ret), K(*ctx_));
    }
    ctx_->set_result_code(ret);
  }

  if (NULL != sstable_ctx_) {
    LOG_INFO("end ObMigrateCopyPhysicalTask process", "table_key", sstable_ctx_->sstable_info_.src_table_key_);
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::fetch_major_block_with_retry(
    ObIArray<ObMigrateArgMacroBlockInfo>& list, ObMacroBlocksWriteCtx& copied_ctx)
{
  int ret = OB_SUCCESS;
  int64_t retry_times = 0;
  obrpc::ObPartitionServiceRpcProxy* srv_rpc_proxy = MIGRATOR.get_svr_rpc_proxy();
  common::ObInOutBandwidthThrottle* bandwidth_throttle = MIGRATOR.get_bandwidth_throttle();
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate copy physical task do not init", K(ret));
  } else if (OB_ISNULL(srv_rpc_proxy) || OB_ISNULL(bandwidth_throttle)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("srv_rpc_proxy or bandwidth_throttle must not null", K(ret), KP(srv_rpc_proxy), KP(bandwidth_throttle));
  } else if (0 == list.count()) {
    LOG_INFO("no macro block need fetch", K(list.count()));
  } else {
    while (retry_times < MAX_RETRY_TIMES) {
      if (retry_times > 0) {
        LOG_INFO("retry get major block", K(retry_times));
      }

      if (OB_FAIL(fetch_major_block(list, copied_ctx))) {
        STORAGE_LOG(WARN, "failed to fetch major block", K(ret), K(retry_times));
      }

      if (OB_SUCC(ret)) {
        break;
      }

      if (OB_FAIL(ret)) {
        copied_ctx.clear();
        retry_times++;
        usleep(OB_FETCH_MAJOR_BLOCK_RETRY_INTERVAL);
      }
    }
  }

  return ret;
}

int ObMigrateCopyPhysicalTask::alloc_migrate_writer(
    ObIPartitionMacroBlockReader* reader, ObIMigrateMacroBlockWriter*& writer)
{
  int ret = OB_SUCCESS;
  writer = nullptr;
  if (OB_UNLIKELY(!is_inited_)) {
    ret = OB_NOT_INIT;
    LOG_WARN("not init", K(ret));
  } else if (OB_ISNULL(reader)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret), KP(reader));
  } else if (OB_ISNULL(sstable_ctx_) || OB_ISNULL(ctx_)) {
    ret = OB_ERR_SYS;
    LOG_WARN("invalid inner state", K(ret), KP(sstable_ctx_), KP(ctx_));
  } else {
    void* buf = nullptr;
    const uint64_t tenant_id = sstable_ctx_->sstable_info_.src_table_key_.get_tenant_id();
    ObStorageFile* dest_pg_file = ctx_->get_partition()->get_pg_storage().get_storage_file();
    if (OB_ISNULL(buf = ob_malloc(sizeof(ObMigrateMacroBlockWriter), ObModIds::OB_PARTITION_MIGRATE))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("fail to alloc migrate macro block writer", K(ret));
    } else {
      ObMigrateMacroBlockWriter* tmp_writer = new (buf) ObMigrateMacroBlockWriter;
      if (OB_FAIL(tmp_writer->init(reader, tenant_id, dest_pg_file))) {
        LOG_WARN("failed to init writer", K(ret), KP(reader), K(tenant_id), KP(dest_pg_file));
        tmp_writer->~ObMigrateMacroBlockWriter();
      } else {
        writer = tmp_writer;
      }
    }
    if (OB_FAIL(ret) && NULL != buf) {
      ob_free(buf);
    }
  }
  return ret;
}

void ObMigrateCopyPhysicalTask::free_migrate_writer(ObIMigrateMacroBlockWriter*& writer)
{
  if (NULL != writer) {
    writer->~ObIMigrateMacroBlockWriter();
    ob_free(writer);
    writer = nullptr;
  }
}

int ObMigrateCopyPhysicalTask::fetch_major_block(
    ObIArray<ObMigrateArgMacroBlockInfo>& list, ObMacroBlocksWriteCtx& copied_ctx)
{
  int ret = OB_SUCCESS;
  obrpc::ObPartitionServiceRpcProxy* srv_rpc_proxy = MIGRATOR.get_svr_rpc_proxy();
  common::ObInOutBandwidthThrottle* bandwidth_throttle = MIGRATOR.get_bandwidth_throttle();
  ObIMigrateMacroBlockWriter* writer = NULL;
  ObIPartitionMacroBlockReader* reader = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate copy physical task do not init", K(ret));
  } else if (OB_ISNULL(srv_rpc_proxy) || OB_ISNULL(bandwidth_throttle)) {
    ret = OB_ERR_SYS;
    LOG_ERROR("srv_rpc_proxy or bandwidth_throttle must not null", K(ret), KP(srv_rpc_proxy), KP(bandwidth_throttle));
  } else if (0 == list.count()) {
    LOG_INFO("no macro block need fetch", K(list.count()));
  } else {
    LOG_INFO("init reader", K(list));
    if (OB_FAIL(get_macro_block_reader(srv_rpc_proxy,
            bandwidth_throttle,
            sstable_ctx_->src_info_,
            list,
            sstable_ctx_->sstable_info_.src_table_key_,
            &ctx_->restore_info_,
            reader))) {
      LOG_WARN("fail to get macro block reader", K(ret));
    } else if (OB_FAIL(alloc_migrate_writer(reader, writer))) {
      LOG_WARN("fail to alloc migrate macro block writer", K(ret), KP(reader));
    } else if (OB_FAIL(writer->process(copied_ctx))) {
      LOG_WARN("failed to process writer", K(ret));
    } else if (list.count() != copied_ctx.get_macro_block_count()) {
      ret = OB_ERR_SYS;
      LOG_ERROR("list count not match",
          K(ret),
          K(list.count()),
          K(copied_ctx.get_macro_block_count()),
          K(list),
          K(copied_ctx));
    }

    if (NULL != reader) {
      cp_fty_->free(reader);
    }
    if (NULL != writer) {
      free_migrate_writer(writer);
    }
  }
  return ret;
}

int ObMigrateCopyPhysicalTask::calc_migrate_data_statics(const int64_t copy_count, const int64_t reuse_count)
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate copy physic task do not init", K(ret));
  } else {
    const ObITable::TableKey& src_table_key = sstable_ctx_->sstable_info_.src_table_key_;
    ctx_->action_ = src_table_key.is_major_sstable() ? ObMigrateCtx::COPY_MAJOR : ObMigrateCtx::COPY_MINOR;
    ATOMIC_AAF(&ctx_->data_statics_.ready_macro_block_, sub_task_->block_count_);
    if (src_table_key.is_major_sstable()) {
      ATOMIC_AAF(&ctx_->data_statics_.major_count_, copy_count);
    } else if (src_table_key.is_mini_minor_sstable()) {
      ATOMIC_AAF(&ctx_->data_statics_.mini_minor_count_, copy_count);
    } else if (src_table_key.is_normal_minor_sstable()) {
      ATOMIC_AAF(&ctx_->data_statics_.normal_minor_count_, copy_count);
    }

    ATOMIC_AAF(&ctx_->data_statics_.reuse_count_, reuse_count);
    if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
      LOG_WARN("failed to update_partition_migration_status", K(tmp_ret));
    }
  }
  return ret;
}

ObMigrateFinishPhysicalTask::ObMigrateFinishPhysicalTask()
    : ObITask(TASK_TYPE_MIGRATE_FINISH_PHYSICAL), is_inited_(false), part_migrate_ctx_(NULL), sstable_ctx_()
{}

ObMigrateFinishPhysicalTask::~ObMigrateFinishPhysicalTask()
{}

int ObMigrateFinishPhysicalTask::init(ObPartitionMigrateCtx& part_migrate_ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (!part_migrate_ctx.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), K(part_migrate_ctx));
  } else {
    is_inited_ = true;
    part_migrate_ctx_ = &part_migrate_ctx;
  }
  return ret;
}

int ObMigrateFinishPhysicalTask::process()
{
  int ret = OB_SUCCESS;
  ObSSTable* sstable = NULL;
  ObTableHandle handle;
  ObIPartitionGroup* partition = NULL;
  ObMigrateCtx* ctx = part_migrate_ctx_->ctx_;
  ObITable::TableKey dest_table_key;
  blocksstable::ObMacroBlocksWriteCtx write_ctx, lob_write_ctx;  // TODO(): fix it for ofs
  ObPGCreateSSTableParam param;
  ObTimeGuard tg("ObMigrateFinishPhysicalTask", 1000L * 1000L);

  LOG_INFO("start ObMigrateFinishPhysicalTask process", "table_key", sstable_ctx_.sstable_info_.src_table_key_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(sstable_ctx_.get_dest_table_key(dest_table_key))) {
    LOG_WARN("failed to get dest table key", K(ret), K(dest_table_key));
  } else if (!dest_table_key.is_valid()) {
    ret = OB_ERR_SYS;
    LOG_WARN("table key is invalid", K(ret), K(dest_table_key));
  } else if (OB_FAIL(OB_FILE_SYSTEM.init_file_ctx(STORE_FILE_MACRO_BLOCK, write_ctx.file_ctx_))) {
    LOG_WARN("Failed to init file ctx", K(ret));
  } else if (sstable_ctx_.meta_.lob_macro_block_count_ > 0) {
    if (OB_FAIL(OB_FILE_SYSTEM.init_file_ctx(STORE_FILE_MACRO_BLOCK, lob_write_ctx.file_ctx_))) {
      LOG_WARN("Failed to init lob file ctx", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    if (!write_ctx.file_handle_.is_valid() &&
        OB_FAIL(
            write_ctx.file_handle_.assign(ctx->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
      LOG_WARN("fail to assign file handle", K(ret));
    } else if (!lob_write_ctx.file_handle_.is_valid() &&
               OB_FAIL(lob_write_ctx.file_handle_.assign(
                   ctx->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
      LOG_WARN("fail to assign file handle", K(ret));
    }
    tg.click("init");
    for (int64_t task_idx = 0; OB_SUCC(ret) && task_idx < sstable_ctx_.task_count_; ++task_idx) {
      ObMigratePhysicalSSTableCtx::SubTask& sub_task = sstable_ctx_.tasks_[task_idx];
      for (int64_t i = 0; OB_SUCC(ret) && i < sub_task.block_count_; ++i) {
        const MacroBlockId macro_block_id = sub_task.block_info_[i].macro_block_id_;
        const ObFullMacroBlockMeta& macro_meta = sub_task.block_info_[i].full_meta_;
        if (sstable_ctx_.meta_.lob_macro_block_count_ > 0) {
          if (OB_UNLIKELY(!macro_meta.is_valid())) {
            ret = OB_ERR_SYS;
            LOG_WARN("Invalid macro meta", "macro_block_id", macro_block_id, K(macro_meta), K(ret));
          } else if (macro_meta.meta_->is_lob_data_block()) {
            if (OB_FAIL(lob_write_ctx.add_macro_block(macro_block_id, macro_meta))) {
              LOG_WARN("Failed to add lob macro block to write ctx", K(ret));
            }
          } else if (OB_FAIL(write_ctx.add_macro_block(macro_block_id, macro_meta))) {
            LOG_WARN("Failed to add macro block to write ctx", K(ret));
          }
        } else if (OB_FAIL(write_ctx.add_macro_block(macro_block_id, macro_meta))) {
          LOG_WARN("Failed to add macro block to write ctx", K(ret));
        }
      }
    }
    tg.click("for_loop");
    if (OB_SUCC(ret)) {
      if (OB_FAIL(param.data_blocks_.push_back(&write_ctx))) {
        LOG_WARN("fail to push back data block", K(ret));
      } else if (sstable_ctx_.meta_.lob_macro_block_count_ > 0) {
        if (OB_FAIL(param.lob_blocks_.push_back(&lob_write_ctx))) {
          LOG_WARN("fail to push back lob macro block", K(ret));
        }
      }
    }
  }

  if (OB_SUCC(ret)) {
    param.table_key_ = &dest_table_key;
    param.meta_ = &sstable_ctx_.meta_;
    if (OB_ISNULL(partition = ctx->partition_guard_.get_partition_group())) {
      ret = OB_ERR_SYS;
      LOG_ERROR("partition must not null", K(ret));
    } else if (OB_FAIL(partition->create_sstable(param, handle))) {
      LOG_WARN("fail to create sstable", K(ret));
      if (OB_ENTRY_EXIST == ret) {
        // cover ret
        if (!dest_table_key.is_trans_sstable() && OB_FAIL(acquire_sstable(dest_table_key, handle))) {
          LOG_WARN("failed to acquire sstables", K(ret), K(dest_table_key));
        }
      }
    }
    tg.click("create_sstable");

    if (OB_SUCC(ret)) {
      if (OB_FAIL(handle.get_sstable(sstable))) {
        LOG_WARN("fail to get sstable", K(ret));
      } else if (OB_ISNULL(sstable)) {
        ret = OB_ERR_SYS;
        LOG_WARN("sstable should not be null", K(ret));
      } else if (dest_table_key.is_trans_sstable()) {
        if (OB_FAIL(ctx->trans_table_handle_.set_table(sstable))) {
          LOG_WARN("failed to set trans table", K(ret));
        }
      } else if (OB_FAIL(part_migrate_ctx_->add_sstable(*sstable))) {
        LOG_WARN("failed to add sstable", K(ret));
      }
      tg.click("add_sstable");
    }
  }

  if (OB_FAIL(ret) && NULL != ctx) {
    ctx->set_result_code(ret);
  }
  tg.click("set_result_code");
  LOG_INFO("end ObMigrateFinishPhysicalTask process",
      "table_key",
      dest_table_key,
      "sub_task_cnt",
      sstable_ctx_.task_count_,
      K(tg));
  return ret;
}

int ObMigrateFinishPhysicalTask::acquire_sstable(const ObITable::TableKey& dest_table_key, ObTableHandle& handle)
{
  int ret = OB_SUCCESS;
  handle.reset();
  ObSSTable* sstable = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("finish physical task do not init", K(ret));
  } else if (!dest_table_key.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("acquire sstable get invalid argument", K(ret), K(dest_table_key));
  } else if (OB_FAIL(ObPartitionService::get_instance().acquire_sstable(dest_table_key, handle))) {
    LOG_WARN("failed to acquire sstable", K(ret), K(dest_table_key));
  } else if (OB_FAIL(handle.get_sstable(sstable))) {
    LOG_WARN("failed to get sstable", K(ret), K(handle));
  } else if (OB_FAIL(check_sstable_meta(sstable_ctx_.meta_, sstable->get_meta()))) {
    LOG_WARN("failed to check sstable meta", K(ret), K(sstable_ctx_.meta_), "new_meta", sstable->get_meta());
  }
  return ret;
}

ObMigrateFinishTask::ObMigrateFinishTask() : ObITask(TASK_TYPE_MIGRATE_FINISH), is_inited_(false), ctx_(NULL)
{}

ObMigrateFinishTask::~ObMigrateFinishTask()
{}

int ObMigrateFinishTask::init(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else {
    is_inited_ = true;
    ctx_ = &ctx;
  }
  return ret;
}

int ObMigrateFinishTask::process()
{
  int ret = OB_SUCCESS;
  bool is_change_replica_with_data = true;
  bool is_add_replica_during_restore = false;
  ObIPartitionGroup* partition = NULL;
  ObPGStorage* pg_storage = NULL;
  DEBUG_SYNC(BEFORE_FINISH_MIGRATE_TASK);

  if (NULL != ctx_) {
    LOG_INFO("start ObMigrateFinishTask process", "pkey", ctx_->replica_op_arg_.key_, K(ctx_->replica_op_arg_.type_));
  }

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_UNLIKELY(BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("migrate op type is unexpected", K(ctx_->replica_op_arg_));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition must not null", K(ret));
  } else if (OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    LOG_ERROR("storage must not null", K(ret), KP(pg_storage));
  } else if (ctx_->is_leader_restore_archive_data()) {
    LOG_INFO("no need check read for leader_restore_archive_data",
        "pkey",
        ctx_->replica_op_arg_.key_,
        "type",
        ctx_->replica_op_arg_.type_);
  } else if (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_ &&
             ((ctx_->is_restore_ > REPLICA_NOT_RESTORE && ctx_->is_restore_ < REPLICA_RESTORE_MAX) ||
                 REPLICA_RESTORE_STANDBY == ctx_->is_restore_)) {
    is_add_replica_during_restore = true;
    LOG_INFO("no need check read add replica during restore", K(ctx_->is_restore_), "pkey", ctx_->replica_op_arg_.key_);
  } else if (OB_FAIL(ctx_->change_replica_with_data(is_change_replica_with_data))) {
    LOG_WARN("failed to check replica", K(ret), K(*ctx_));
  } else if (is_change_replica_with_data) {
    LOG_INFO("no need check read for change replica", K(*ctx_));
  } else if (OB_FAIL(ObMigrateUtil::merge_trans_table(*ctx_))) {
    LOG_WARN("failed to merge trans table", K(ret));
  } else if (OB_FAIL(create_pg_partition_if_need())) {
    LOG_WARN("Failed to create pg partition if need", K(ret));
O
obdev 已提交
11441 11442 11443 11444 11445
  } else if (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_ &&
             ((ctx_->is_restore_ > REPLICA_NOT_RESTORE && ctx_->is_restore_ < REPLICA_RESTORE_MAX) ||
                 REPLICA_RESTORE_STANDBY == ctx_->is_restore_)) {
    is_add_replica_during_restore = true;
    LOG_INFO("no need check read add replica during restore", K(ctx_->is_restore_), "pkey", ctx_->replica_op_arg_.key_);
O
oceanbase-admin 已提交
11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457
  } else {
    if (ObReplicaTypeCheck::is_replica_with_ssstore(ctx_->replica_op_arg_.dst_.get_replica_type())) {
      if (OB_FAIL(check_pg_partition_ready_for_read())) {
        LOG_WARN("Failed to check partition ready for read", K(ret));
      } else if (OB_FAIL(check_pg_available_index_all_exist())) {
        if (ctx_->replica_op_arg_.is_physical_restore()) {
          ret = OB_SUCCESS;
          // TODO: fix restore schema, some index status should be set unavailable
        }
        LOG_WARN("failed to check_available_index_all_exist", K(ret));
      }
    }
O
obdev 已提交
11458
  }
O
oceanbase-admin 已提交
11459

O
obdev 已提交
11460 11461
  if (OB_SUCC(ret)) {
    if (OB_FAIL(enable_replay())) {
O
oceanbase-admin 已提交
11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632
      LOG_WARN("failed to enable replay", K(ret), K(ctx_->replica_op_arg_));
    }
  }

  if (OB_SUCC(ret)) {
    int64_t retry_times = 0;
    while (OB_SUCC(ret) && retry_times < ObMigrateUtil::OB_MIGRATE_ONLINE_RETRY_COUNT) {
      if (OB_FAIL(update_split_state())) {
        LOG_WARN("failed to update split state", K(ret));
      }
      retry_times++;
      if (OB_FAIL(ret) && retry_times < ObMigrateUtil::OB_MIGRATE_ONLINE_RETRY_COUNT) {
        ret = OB_SUCCESS;
        usleep(ObMigrateUtil::RETRY_TASK_SLEEP_INTERVAL_S);
      } else {
        break;
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (is_change_replica_with_data || is_add_replica_during_restore ||
        REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_ || ctx_->is_only_copy_sstable()) {
      LOG_INFO("no need to wait log sync", K(is_change_replica_with_data), "arg", ctx_->replica_op_arg_);
    } else if (OB_FAIL(wait_log_sync())) {
      LOG_WARN("failed to check is log sync", K(ret));
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_FAIL(update_pg_partition_report_status())) {
      LOG_WARN("fail to update pg partition report status", K(ret));
    }
  }

  if (OB_SUCC(ret)) {
    const int64_t cur_ts = ObTimeUtility::current_time();
    if (OB_FAIL(pg_storage->set_pg_migrate_status(OB_MIGRATE_STATUS_HOLD, cur_ts))) {
      LOG_WARN("failed to set migrate status to OB_MIGRATE_STATUS_HOLD", K(ret), K(*ctx_));
    } else {
      LOG_INFO("succeed to set migrate status to OB_MIGRATE_STATUS_HOLD", K(*ctx_));
    }
  }

  if (OB_SUCC(ret) && RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ && REPLICA_RESTORE_DATA == ctx_->is_restore_) {
    if (OB_FAIL(partition->set_storage_info(ctx_->pg_meta_.storage_info_))) {
      STORAGE_LOG(WARN,
          "failed to set storage info",
          K(ret),
          "pg_key",
          ctx_->replica_op_arg_.key_,
          "storage_info",
          ctx_->pg_meta_.storage_info_);
    }
  }

  if (OB_SUCC(ret) &&
      ((RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_ &&
           (REPLICA_RESTORE_DATA == ctx_->is_restore_ || REPLICA_RESTORE_CUT_DATA == ctx_->is_restore_)) ||
          (RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_ && REPLICA_RESTORE_STANDBY == ctx_->is_restore_) ||
          RESTORE_FOLLOWER_REPLICA_OP == ctx_->replica_op_arg_.type_)) {
    if (ObReplicaTypeCheck::is_replica_with_memstore(partition->get_replica_type()) &&
        OB_FAIL(partition->get_pg_storage().restore_mem_trans_table())) {
      STORAGE_LOG(WARN, "failed to restore mem trans table", K(ret));
    }
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    if (OB_LOG_NOT_SYNC == ret) {
      if (ADD_REPLICA_OP == ctx_->replica_op_arg_.type_ || MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_ ||
          FAST_MIGRATE_REPLICA_OP == ctx_->replica_op_arg_.type_ || REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
        ctx_->need_rebuild_ = true;
      }
    }
    ctx_->set_result_code(ret);
  }

  if (NULL != ctx_) {
    LOG_INFO("end ObMigrateFinishTask process", "pkey", ctx_->replica_op_arg_.key_, K(ctx_->replica_op_arg_.type_));
  }

#ifdef ERRSIM
  if (OB_SUCC(ret)) {
    ret = E(EventTable::AFTER_MIGRATE_FINISH_TASK) OB_SUCCESS;
    if (OB_FAIL(ret)) {
      STORAGE_LOG(ERROR, "fake AFTER_MIGRATE_FINISH_TASK", K(ret));
    }
  }
#endif
  return ret;
}

int ObMigrateFinishTask::lock_pg_owner(common::ObMySQLTransaction& trans, ObIPartitionGroup& pg,
    const common::ObAddr& data_src_addr, const int64_t epoch_number)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!pg.is_valid() || !data_src_addr.is_valid() || OB_INVALID_VERSION == epoch_number)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret), K(pg), K(data_src_addr), K(epoch_number));
  } else {
    const ObPGKey& pg_key = pg.get_partition_key();
    ObSqlString sql;
    SMART_VAR(ObISQLClient::ReadResult, result)
    {
      sqlclient::ObMySQLResult* mysql_result = nullptr;
      char ip_str[32] = {0};
      const char* sql_template = " SELECT is_owner, epoch_num "
                                 " FROM __all_tenant_meta_table "
                                 " WHERE tenant_id=%lu AND table_id=%lu AND partition_id=%ld "
                                 " AND svr_ip='%s' AND svr_port=%d AND epoch_num=%ld and is_owner=%d"
                                 " FOR UPDATE; ";
      if (OB_UNLIKELY(!data_src_addr.ip_to_string(ip_str, sizeof(ip_str)))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("fail to get ip string", K(ret), K(data_src_addr));
      } else if (OB_FAIL(sql.append_fmt(sql_template,
                     pg_key.get_tenant_id(),
                     pg_key.get_table_id(),
                     pg_key.get_partition_id(),
                     ip_str,
                     data_src_addr.get_port(),
                     epoch_number,
                     true /*is_owner*/))) {
        LOG_WARN("fail to generate sql string", K(ret), K(pg_key));
      } else if (OB_FAIL(trans.read(result, pg_key.get_tenant_id(), sql.ptr()))) {
        LOG_WARN("fail to execute read sql", K(ret), K(sql), K(pg_key));
      } else if (OB_ISNULL(mysql_result = result.get_result())) {
        // empty result, owner maybe changed or src server reboot
        ret = OB_EMPTY_RESULT;
        LOG_WARN("query get empty result", K(ret), K(data_src_addr), K(pg_key), K(epoch_number));
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::enable_replay()
{
  int ret = OB_SUCCESS;
  if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(enable_replay_for_rebuild())) {
      LOG_WARN("failed to enable_replay_for_rebuild", K(ret), "arg", ctx_->replica_op_arg_);
    }
  } else {
    if (ctx_->create_new_pg_) {
      if (OB_FAIL(ObMigrateUtil::enable_replay_with_new_partition(*ctx_))) {
        LOG_WARN("failed to enable replay with new partition", K(ret), KPC(ctx_));
      }
    } else if (ctx_->get_partition()->get_pg_storage().is_paused()) {
      if (OB_FAIL(ObMigrateUtil::enable_replay_with_old_partition(*ctx_))) {
        LOG_WARN("failed to enable replay with old partition", K(ret), KPC(ctx_));
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::create_pg_partition_if_need()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* pg = NULL;
  const bool in_slog_trans = false;
  const int64_t max_kept_major_version_number = 0;

  LOG_INFO("start create_pg_partition_if_need");

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(pg = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_WARN("pg should not be NULL", K(ret), KP(pg));
O
obdev 已提交
11633 11634 11635
  } else if (ctx_->is_copy_index()) {
    // no need to replace store map, just skip it.
    LOG_INFO("replica op tyoe is no need batch replace sstable, skip it");
O
obdev 已提交
11636 11637 11638 11639 11640 11641
  } else if (!ctx_->is_copy_index()) {
    const ObSavedStorageInfoV2 &saved_storage_info = ctx_->pg_meta_.storage_info_;
    if (ctx_->replica_op_arg_.is_FtoL()) {
      // no need to replace store map, just skip.
    } else if (OB_FAIL(pg->get_pg_storage().batch_replace_store_map(
            ctx_->part_ctx_array_,
O
oceanbase-admin 已提交
11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518
            saved_storage_info.get_data_info().get_schema_version(),
            ctx_->is_restore_,
            ctx_->old_trans_table_seq_))) {
      LOG_WARN("failed to batch replace store map", K(ret));
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_pg_partition_ready_for_read()
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not init", K(ret));
  } else if (OB_FAIL(check_partition_ready_for_read_in_remote())) {
    LOG_WARN("failed to check partition ready for read in remote", K(ret));
  } else if (OB_FAIL(check_partition_ready_for_read_out_remote())) {
    LOG_WARN("failed to check partition ready for read out remote", K(ret));
  }
  return ret;
}

int ObMigrateFinishTask::check_partition_ready_for_read_in_remote()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGPartition* pg_partition = NULL;
  ObIPartitionStorage* storage = NULL;
  ObPartitionArray pkeys;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition must not null", K(ret));
  } else if (OB_FAIL(partition->get_all_pg_partition_keys(pkeys, true /*include_trans_table*/))) {
    LOG_WARN("fail to get all pg partition keys", K(ret));
  } else if (pkeys.count() < ctx_->part_ctx_array_.count()) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("can not remove partition during migration", K(ret), K(pkeys.count()), K(ctx_->part_ctx_array_.count()));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      ObPGPartitionGuard guard;
      storage = NULL;
      const ObMigratePartitionInfo& copy_info = ctx_->part_ctx_array_.at(i).copy_info_;
      const ObPartitionKey& pkey = copy_info.meta_.pkey_;
      if (pkey.is_trans_table()) {
        continue;
      } else if (OB_FAIL(partition->get_pg_partition(pkey, guard))) {
        LOG_ERROR("failed to get pg partition", K(ret), K(pkey));
      } else if (OB_ISNULL(pg_partition = guard.get_pg_partition())) {
        ret = OB_ERR_SYS;
        LOG_ERROR("pg partition should not be NULL", K(ret), KP(pg_partition));
      } else if (OB_ISNULL(storage = pg_partition->get_storage())) {
        ret = OB_ERR_SYS;
        LOG_ERROR("storage must not null", K(ret));
      } else if (OB_FAIL(check_partition_ready_for_read(copy_info, storage))) {
        LOG_WARN("failed to check partition ready for read", K(ret), K(copy_info));
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_partition_ready_for_read(
    const ObMigratePartitionInfo& copy_info, ObIPartitionStorage* storage)
{
  int ret = OB_SUCCESS;
  ObTablesHandle handle;
  bool is_ready_for_read = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (!copy_info.is_valid() || OB_ISNULL(storage)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("check partition ready for read get invalid argument", K(ret), K(copy_info), KP(storage));
  } else {
    ObPartitionStore& store = static_cast<ObPartitionStorage*>(storage)->get_partition_store();
    for (int64_t i = 0; OB_SUCC(ret) && i < copy_info.table_infos_.count(); ++i) {
      const ObMigrateTableInfo& info = copy_info.table_infos_[i];
      handle.reset();
      if (OB_FAIL(store.get_effective_tables(info.table_id_, handle, is_ready_for_read))) {
        LOG_WARN("failed to check ready for read", K(ret), K(info.table_id_));
      } else if (info.ready_for_read_ && !is_ready_for_read) {
        const uint64_t tenant_id = extract_tenant_id(info.table_id_);
        share::schema::ObSchemaGetterGuard schema_guard;
        share::schema::ObMultiVersionSchemaService& schema_service =
            share::schema::ObMultiVersionSchemaService::get_instance();
        bool is_exist = true;
        if (OB_FAIL(schema_service.get_tenant_schema_guard(tenant_id, schema_guard))) {
          LOG_WARN("failed to get schema guard", K(ret), K(tenant_id));
        } else if (OB_FAIL(schema_guard.check_table_exist(info.table_id_, is_exist))) {
          LOG_WARN("failed to check table exist", K(ret));
        } else if (!is_exist) {
          ret = OB_TABLE_IS_DELETED;
          LOG_WARN("table is not exist, can not check is ready for read", K(ret), K(info));
        } else {
          ret = OB_ERR_SYS;
          LOG_ERROR("src is ready for read, but dest is not, migrate failed", K(ret), K(info), K(handle));
        }
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_partition_ready_for_read_out_remote()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGPartition* pg_partition = NULL;
  ObIPartitionStorage* storage = NULL;
  ObTablesHandle handle;
  ObPartitionArray pkeys;
  ObHashSet<ObPartitionKey> remote_pkeys;
  int hash_ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition must not null", K(ret));
  } else if (OB_FAIL(partition->get_pg_storage().get_all_pg_partition_keys_with_lock(
                 pkeys, true /*include_trans_table*/))) {
    LOG_WARN("fail to get all pg partition keys", K(ret));
  } else {
    const int64_t OB_MAX_BUCKET = std::max(pkeys.count(), ctx_->part_ctx_array_.count());
    if (0 == OB_MAX_BUCKET) {
      // do nothing
    } else if (pkeys.count() < ctx_->part_ctx_array_.count()) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("can not remove partition during migration", K(ret), K(pkeys.count()), K(ctx_->part_ctx_array_.count()));
    } else if (OB_FAIL(remote_pkeys.create(OB_MAX_BUCKET))) {
      LOG_WARN("failed to create remote pkeys set", K(ret), K(ctx_->part_ctx_array_.count()));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
        const ObMigratePartitionInfo& copy_info = ctx_->part_ctx_array_.at(i).copy_info_;
        const ObPartitionKey& pkey = copy_info.meta_.pkey_;
        if (OB_FAIL(remote_pkeys.set_refactored(pkey))) {
          LOG_WARN("failed to set pkey into remote pkey set", K(ret), K(pkey));
        }
      }

      for (int64_t i = 0; OB_SUCC(ret) && i < pkeys.count(); ++i) {
        const ObPartitionKey& pkey = pkeys.at(i);
        hash_ret = remote_pkeys.exist_refactored(pkey);
        if (OB_HASH_EXIST == hash_ret) {
          // do nothing
        } else if (OB_HASH_NOT_EXIST == hash_ret) {
          ObPGPartitionGuard guard;
          storage = NULL;
          if (pkey.is_trans_table()) {
            continue;
          } else if (OB_FAIL(partition->get_pg_partition(pkey, guard))) {
            LOG_ERROR("failed to get pg partition", K(ret), K(pkey));
          } else if (OB_ISNULL(pg_partition = guard.get_pg_partition())) {
            ret = OB_ERR_SYS;
            LOG_ERROR("pg partition should not be NULL", K(ret), KP(pg_partition));
          } else if (OB_ISNULL(storage = pg_partition->get_storage())) {
            ret = OB_ERR_SYS;
            LOG_ERROR("storage must not null", K(ret));
          } else if (OB_FAIL(check_partition_ready_for_read(storage))) {
            LOG_WARN("failed to check partition out remote ready for read", K(ret), K(pkey));
          }
        } else {
          ret = hash_ret;
          LOG_WARN("failed to check pkey into set", K(ret), K(pkey));
        }
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_partition_ready_for_read(ObIPartitionStorage* storage)
{
  int ret = OB_SUCCESS;
  ObTablesHandle handle;
  bool is_ready_for_read = false;
  ObArray<uint64_t> table_ids;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(storage)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("check partition ready for read get invalid argument", K(ret), KP(storage));
  } else {
    ObPartitionStore& store = static_cast<ObPartitionStorage*>(storage)->get_partition_store();
    if (OB_FAIL(store.get_all_table_ids(table_ids))) {
      LOG_WARN("failed to get all table ids", K(ret), K(storage->get_partition_key()));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < table_ids.count(); ++i) {
        const uint64_t table_id = table_ids.at(i);
        handle.reset();
        if (OB_FAIL(store.get_effective_tables(table_id, handle, is_ready_for_read))) {
          LOG_WARN("failed to check ready for read", K(ret), K(table_id));
        } else if (!is_ready_for_read) {
          ret = OB_VERSION_RANGE_NOT_CONTINUES;
          LOG_WARN("partition which not in remote has uncontinues tables",
              K(ret),
              K(table_id),
              K(handle),
              K(storage->get_partition_key()));
        }
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_pg_available_index_all_exist()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGPartition* pg_partition = NULL;
  ObPartitionStorage* storage = NULL;
  ObPartitionArray pkeys;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition must not null", K(ret));
  } else if (OB_FAIL(partition->get_all_pg_partition_keys(pkeys))) {
    LOG_WARN("failed to get all pg partition keys", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < pkeys.count(); ++i) {
      ObPGPartitionGuard guard;
      storage = NULL;
      const ObPartitionKey& pkey = pkeys.at(i);
      if (OB_FAIL(partition->get_pg_partition(pkey, guard))) {
        LOG_ERROR("failed to get pg partition", K(ret), K(pkey));
      } else if (OB_ISNULL(pg_partition = guard.get_pg_partition())) {
        ret = OB_ERR_SYS;
        LOG_WARN("pg partition should not be NULL", K(ret), KP(pg_partition));
      } else if (OB_ISNULL(storage = static_cast<ObPartitionStorage*>(pg_partition->get_storage()))) {
        ret = OB_ERR_SYS;
        LOG_WARN("fail to get partition storage", K(ret), KP(storage));
      } else if (OB_FAIL(check_available_index_all_exist(pkey, storage))) {
        LOG_WARN("fail to check available index all exist", K(ret));
      }
    }
  }
  return ret;
}

int ObMigrateFinishTask::check_available_index_all_exist(const ObPartitionKey& pkey, ObPartitionStorage* storage)
{
  int ret = OB_SUCCESS;
  ObSchemaGetterGuard schema_guard;
  ObArray<ObIndexTableStat> index_stats;
  ObTableHandle handle;
  const uint64_t tenant_id = is_inner_table(pkey.get_table_id()) ? OB_SYS_TENANT_ID : pkey.get_tenant_id();

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(storage)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("check available index get invalid argument", K(ret), KP(storage));
  } else if (OB_FAIL(MIGRATOR.get_schema_service()->get_tenant_full_schema_guard(tenant_id, schema_guard))) {
    LOG_WARN("fail to get schema schema guard", K(ret));
  } else if (OB_FAIL(schema_guard.get_index_status(pkey.get_table_id(), false /*with global index*/, index_stats))) {
    LOG_WARN("fail to get index status", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < index_stats.count(); ++i) {
      if (is_available_index_status(index_stats.at(i).index_status_)) {
        if (OB_FAIL(storage->get_partition_store().get_last_major_sstable(index_stats.at(i).index_id_, handle))) {
          LOG_WARN("failed to get last major sstable for index", K(ret), "index_id", index_stats.at(i).index_id_);
        } else if (NULL == handle.get_table()) {
          ret = OB_ENTRY_NOT_EXIST;
          LOG_WARN("has no major sstable for index", K(ret), "index_id", index_stats.at(i).index_id_);
        }
      }
    }
    // TODO(): should rebuild migrate
  }
  return ret;
}

int ObMigrateFinishTask::update_pg_partition_report_status()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  const int64_t version = ctx_->pg_meta_.report_status_.data_version_ > 0
                              ? ctx_->pg_meta_.report_status_.data_version_
                              : ObPartitionScheduler::get_instance().get_frozen_version();
  const common::ObVersion report_version(version);
  bool need_report = false;
  bool check_finished = false;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_ISNULL(partition = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("partition must not null", K(ret));
  } else if (OB_ISNULL(GCTX.ob_service_)) {
    // skip it
  } else if (OB_SUCCESS != (tmp_ret = partition->get_pg_storage().try_update_report_status(
                                *GCTX.ob_service_, report_version, check_finished, need_report))) {
    LOG_WARN("failed to try_update_report_status", K(ret), K(partition->get_partition_key()));
  }
  return ret;
}

int64_t ObMigratePhysicalSSTableCtx::SubTask::to_string(char* buf, const int64_t buf_len) const
{
  int64_t pos = 0;
  if (OB_ISNULL(buf) || buf_len <= 0) {
    // do nothing
  } else {
    J_OBJ_START();
    J_KV(KP(this), K_(block_count));
    J_COMMA();
    J_ARRAY_START();
    for (int64_t i = 0; i < block_count_; ++i) {
      ObMigrateMacroBlockInfo& info = block_info_[i];
      J_OBJ_START();
      J_KV(K(i), K(info));
      J_OBJ_END();
      J_COMMA();
    }
    J_ARRAY_END();
    J_OBJ_END();
  }
  return pos;
}

int64_t ObMigratePhysicalSSTableCtx::to_string(char* buf, const int64_t buf_len) const
{
  int64_t pos = 0;
  if (OB_ISNULL(buf) || buf_len <= 0) {
    // do nothing
  } else {
    J_OBJ_START();
    J_KV(KP(this), K_(src_info), K_(sstable_info), K_(task_count), KP(tasks_), K_(meta));
    J_COMMA();
    J_ARRAY_START();
    for (int64_t i = 0; i < task_count_; ++i) {
      SubTask& task = tasks_[i];
      J_OBJ_START();
      J_KV(K(i), K(task));
      J_OBJ_END();
      J_COMMA();
    }
    J_ARRAY_END();
    J_OBJ_END();
  }
  return pos;
}

int ObMigrateFinishTask::wait_log_sync(uint64_t max_clog_id /* = OB_INVALID_TIMESTAMP*/)
{
  int ret = OB_SUCCESS;
  bool is_log_sync = false;
  uint64_t last_confirmed_log_id = 0;
  bool is_cancel = false;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret), "pkey", ctx_->replica_op_arg_.key_);
  } else if (0 == ctx_->wait_replay_start_ts_) {
    ctx_->wait_replay_start_ts_ = ObTimeUtility::current_time();
    LOG_INFO("start wait_log_sync", "pkey", ctx_->replica_op_arg_.key_);
  }

  while (OB_SUCC(ret) && !is_log_sync) {
    if (ctx_->group_task_->has_error()) {
      ret = OB_CANCELED;
      STORAGE_LOG(WARN, "group task has error, cancel subtask", K(ret));
    } else if (OB_FAIL(SYS_TASK_STATUS_MGR.is_task_cancel(get_dag()->get_dag_id(), is_cancel))) {
      STORAGE_LOG(ERROR, "failed to check is task canceled", K(ret), K(*this));
    } else if (is_cancel) {
      ret = OB_CANCELED;
      STORAGE_LOG(WARN, "task is cancelled", K(ret), K(*this));
    } else if (OB_FAIL(MIGRATOR.get_partition_service()->is_log_sync(
                   ctx_->replica_op_arg_.key_, is_log_sync, last_confirmed_log_id))) {
      LOG_WARN("failed to check is log sync", K(ret));
    } else if (OB_INVALID_TIMESTAMP != max_clog_id) {
      is_log_sync = last_confirmed_log_id >= max_clog_id;
    }
    if (OB_FAIL(ret)) {
    } else if (is_log_sync) {
      const int64_t cost_ts = ObTimeUtility::current_time() - ctx_->wait_replay_start_ts_;
      LOG_INFO(
          "log is sync, stop wait_log_sync", "pkey", ctx_->replica_op_arg_.key_, K(cost_ts), K(last_confirmed_log_id));
    } else {
      if (REACH_TIME_INTERVAL(60 * 1000 * 1000)) {
        LOG_INFO("log is not sync, retry next loop", "pkey", ctx_->replica_op_arg_.key_, K(last_confirmed_log_id));
      }
      usleep(OB_CHECK_LOG_SYNC_INTERVAL);
      // If a log is not played backup for more than 30 minutes, it will be timeout during in sync
      const int64_t CLOG_IN_SYNC_DELAY_TIMEOUT = 30 * 60 * 1000 * 1000;
      if ((ctx_->last_confirmed_log_id_ == last_confirmed_log_id) &&
          (OB_INVALID_TIMESTAMP != ctx_->last_confirmed_log_ts_)) {
        if (ObTimeUtility::current_time() - ctx_->last_confirmed_log_ts_ >= CLOG_IN_SYNC_DELAY_TIMEOUT) {
          ctx_->result_ = OB_TIMEOUT;
          ret = OB_TIMEOUT;
          STORAGE_LOG(
              WARN, "failed to check is partition log replay sync. timeout, stop migrate task", K(ret), K(*ctx_));
        }
      } else {
        ctx_->last_confirmed_log_id_ = last_confirmed_log_id;
        ctx_->last_confirmed_log_ts_ = ObTimeUtility::current_time();
      }
    }
  }

  if (OB_SUCC(ret) && !is_log_sync) {
    const int64_t cost_ts = ObTimeUtility::current_time() - ctx_->wait_replay_start_ts_;
    ret = OB_LOG_NOT_SYNC;
    LOG_WARN(
        "log is not sync", "pkey", ctx_->replica_op_arg_.key_, "pkey", ctx_->replica_op_arg_.key_, K(cost_ts), K(ret));
  }
  return ret;
}

int ObMigrateFinishTask::enable_replay_for_rebuild()
{
  int ret = OB_SUCCESS;

  LOG_INFO("start enable_replay_for_rebuild");

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret), "pkey", ctx_->replica_op_arg_.key_);
  } else if (REBUILD_REPLICA_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot enable_replay_for_rebuild for other type", K(ret), K(*ctx_));
  } else {
    ctx_->need_online_for_rebuild_ = false;
    if (OB_FAIL(ObMigrateUtil::enable_replay_with_old_partition(*ctx_))) {
      LOG_WARN("failed to enable_replay_with_old_partition", K(ret), K(*ctx_));
    }
  }

  return ret;
}

int ObMigrateFinishTask::update_split_state()
{
  int ret = OB_SUCCESS;
  ObPartitionGroupMeta& meta = ctx_->pg_meta_;
  ObBaseStorageInfo& clog_info = meta.storage_info_.get_clog_info();
  ObDataStorageInfo& data_info = meta.storage_info_.get_data_info();
  const ObPartitionSplitInfo& split_info = meta.split_info_;
  int64_t split_state = meta.saved_split_state_;
  // 221,222 may set spit_status = -1, and it has bug during upgrade to 224. Now set split_status = 1.
  if (-1 == split_state) {
    split_state = 1;
    LOG_WARN("split state was -1, should be rewritten to 1", K(meta.pg_key_));
  }
  ObIPartitionGroup* partition = NULL;

  if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_SYS;
    LOG_ERROR("cannot use old partition", K(ret));
  } else if (need_copy_split_state(ctx_->replica_op_arg_.type_)) {
    if (split_info.get_src_partition() == meta.pg_key_) {
      const int64_t source_log_id = split_info.get_source_log_id();
      const int64_t last_replay_log_id =
          std::min(clog_info.get_last_replay_log_id(), data_info.get_last_replay_log_id());

      if (last_replay_log_id >= source_log_id && OB_INVALID_ID != source_log_id) {
        if (OB_FAIL(
                partition->shutdown(split_info.get_split_version(), source_log_id, split_info.get_schema_version()))) {
          LOG_WARN("failed to shutdown", K(ret), K(split_info));
        } else if (OB_FAIL(partition->push_reference_tables(
                       split_info.get_dest_partitions(), split_info.get_split_version()))) {
          LOG_WARN("failed to push reference tables", K(split_info));
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(partition->save_split_state(split_state))) {
        LOG_WARN("failed to save split info and state", K(ret), K(split_state));
      }
    }
  }

  return ret;
}

ObGroupMigrateDag::ObGroupMigrateDag()
    : ObIDag(ObIDag::DAG_TYPE_GROUP_MIGRATE, ObIDag::DAG_PRIO_GROUP_MIGRATE),
      is_inited_(false),
      group_task_(NULL),
      tenant_id_(0),
      partition_service_(NULL)
{}

ObGroupMigrateDag::~ObGroupMigrateDag()
{
  int tmp_ret = OB_SUCCESS;

  if (NULL != group_task_) {
    ObArray<ObReportPartMigrationTask> report_list;
    bool is_batch_mode = false;
    bool could_report = false;
    if (OB_SUCCESS != (tmp_ret = group_task_->fill_report_list(is_batch_mode, report_list))) {
      LOG_WARN("failed to fill report list", K(tmp_ret), K_(tenant_id));
    } else {
      could_report = true;
    }

    if (OB_SUCCESS != (tmp_ret = ObPartGroupMigrator::get_instance().remove_finish_task(group_task_))) {
      LOG_WARN("failed to remove finish task", K(tmp_ret), K_(tenant_id));
    }
    group_task_ = NULL;

    if (could_report) {
      if (OB_SUCCESS != (tmp_ret = report_result(is_batch_mode, report_list))) {
        STORAGE_LOG(WARN, "failed to report result", K(tmp_ret), K_(tenant_id), K(is_batch_mode));
      }
    }
  }
}

bool ObGroupMigrateDag::operator==(const ObIDag& other) const
{
  bool is_same = true;
  if (this == &other) {
    // same
  } else if (get_type() != other.get_type()) {
    is_same = false;
  } else {
    const ObGroupMigrateDag& other_dag = static_cast<const ObGroupMigrateDag&>(other);
    is_same = group_task_ == other_dag.group_task_;
  }
  return is_same;
}

int64_t ObGroupMigrateDag::hash() const
{
  int64_t ptr = reinterpret_cast<int64_t>(group_task_);
  return common::murmurhash(&ptr, sizeof(ptr), 0);
}

int ObGroupMigrateDag::init(ObPartGroupTask* group_task, storage::ObPartitionService* partition_service)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (OB_ISNULL(group_task) || OB_ISNULL(partition_service)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(group_task), KP(partition_service));
  } else if (OB_FAIL(set_dag_id(group_task->get_task_id()))) {
    LOG_WARN("failed to set dag id", K(ret));
  } else {
    tenant_id_ = group_task->get_tenant_id();
    group_task_ = group_task;
    partition_service_ = partition_service;
    is_inited_ = true;
  }
  return ret;
}

void ObGroupMigrateDag::clear()
{
  is_inited_ = false;
  group_task_ = NULL;
  tenant_id_ = 0;
}

int ObGroupMigrateDag::fill_comment(char* buf, const int64_t buf_len) const
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;

  if (NULL == buf || NULL == group_task_) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), KP(group_task_), K(buf));
  } else if (group_task_->get_task_list().count() <= 0) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "invalid args", K(ret), K(*group_task_));
  } else {
    const ObReplicaOpArg& arg = group_task_->get_task_list().at(0).arg_;
    int n = snprintf(buf,
        buf_len,
        "group partition migration executor: group_task_id=%s partition_count=%ld partition_id=%ld "
        "key=%s, op_type=%s, src=%s, dest=%s,",
        to_cstring(group_task_->get_task_id()),
        group_task_->get_task_list().count(),
        arg.key_.get_partition_id(),
        to_cstring(arg.key_),
        arg.get_replica_op_type_str(),
        to_cstring(arg.data_src_.get_server()),
        to_cstring(arg.dst_.get_server()));
    if (n < 0 || n >= buf_len) {
      tmp_ret = OB_BUF_NOT_ENOUGH;
      STORAGE_LOG(WARN, "buf not enough, comment is truncated", K(tmp_ret), K(n));
    }
  }
  return ret;
}

ObGroupMigrateExecuteTask::ObGroupMigrateExecuteTask()
    : ObITask(TASK_TYPE_GROUP_MIGRATE), is_inited_(false), group_task_(NULL)
{}

ObGroupMigrateExecuteTask::~ObGroupMigrateExecuteTask()
{}

int ObGroupMigrateExecuteTask::init(ObPartGroupTask* group_task)
{
  int ret = OB_SUCCESS;

  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_ERROR("cannot init twice", K(ret));
  } else if (OB_ISNULL(group_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid args", K(ret), KP(group_task));
  } else {
    is_inited_ = true;
    group_task_ = group_task;
  }
  return ret;
}

int ObGroupMigrateExecuteTask::process()
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("not inited", K(ret));
  } else if (OB_FAIL(group_task_->do_task())) {
    LOG_WARN("failed to do task", K(ret));
  }
  return ret;
}

int ObMigrateGetLeaderUtil::get_leader(
    const common::ObPartitionKey& pkey, ObMigrateSrcInfo& leader_info, const bool force_renew)
{
  int ret = OB_SUCCESS;
  const int64_t cluster_id = GCONF.cluster_id;
  leader_info.reset();
  if (!pkey.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    STORAGE_LOG(WARN, "pkey is invalid", K(ret), K(pkey));
  } else {
    share::ObIPartitionLocationCache* location_cache = NULL;
    if (NULL == (location_cache = ObPartitionService::get_instance().get_location_cache())) {
      ret = OB_ERR_SYS;
      STORAGE_LOG(ERROR, "location cache must not null", K(ret));
    } else if (OB_FAIL(location_cache->get_leader_by_election(pkey, leader_info.src_addr_, force_renew))) {
      STORAGE_LOG(WARN, "get leader address failed", K(ret), K(pkey));
    } else {
      leader_info.cluster_id_ = cluster_id;
    }
  }
  return ret;
}

int ObMigrateGetLeaderUtil::get_clog_parent(clog::ObIPartitionLogService& log_service, ObMigrateSrcInfo& parent_info)
{
  int ret = OB_SUCCESS;
  parent_info.reset();
  ObAddr parent_src;
  int64_t cluster_id = -1;

  if (OB_FAIL(log_service.get_clog_parent(parent_src, cluster_id))) {
    STORAGE_LOG(WARN, "get parent addr failed", K(ret));
  } else {
    parent_info.src_addr_ = parent_src;
    parent_info.cluster_id_ = cluster_id;
  }
  return ret;
}

ObMigratePostPrepareTask::ObMigratePostPrepareTask()
{}

ObMigratePostPrepareTask::~ObMigratePostPrepareTask()
{}

int ObMigratePostPrepareTask::process()
{
  int ret = OB_SUCCESS;
  if (IS_NOT_INIT) {
    ret = OB_NOT_INIT;
    LOG_WARN("task is not inited", K(ret));
  } else {
    if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      LOG_INFO("no need replay for BACKUP_REPLICA_OP", "arg", ctx_->replica_op_arg_);
    } else if (ctx_->create_new_pg_) {
      if (OB_FAIL(deal_with_new_partition())) {
        LOG_WARN("failed to enable_replay_with_new_partition", K(ret), "arg", ctx_->replica_op_arg_);
      }
    } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
      // do nothing
    } else {
      if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
        if (OB_FAIL(deal_with_rebuild_partition())) {
          LOG_WARN("failed to offline_rebuild_partition", K(ret), "arg", ctx_->replica_op_arg_);
        }
      } else if (RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
        if (OB_FAIL(deal_with_standby_restore_partition())) {
          LOG_WARN("failed to deal with standby restore partition", K(ret), "arg", ctx_->replica_op_arg_);
        }
      } else {
        if (OB_FAIL(deal_with_old_partition())) {
          LOG_WARN("failed to deal_with_old_partition", K(ret), "arg", ctx_->replica_op_arg_);
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(check_partition_integrity())) {
        LOG_WARN("failed to check partition intergrity", K(ret), "arg", ctx_->replica_op_arg_);
      } else if (OB_FAIL(schedule_migrate_tasks())) {
        LOG_WARN("failed to schedule migrate tasks", K(ret), KPC(ctx_));
      }
    }

    if (OB_FAIL(ret) && NULL != ctx_) {
      if (ctx_->is_need_retry(ret)) {
        ctx_->need_rebuild_ = true;
        LOG_INFO("migrate post prepare task need retry", K(ret), K(*ctx_));
      }
      ctx_->set_result_code(ret);
    }
    LOG_INFO("migrate post prepare task finish", K(ret));
  }
  return ret;
}

int ObMigratePostPrepareTask::schedule_migrate_tasks()
{
  int ret = OB_SUCCESS;
  int tmp_ret = OB_SUCCESS;
  bool need_schedule = false;
  ObArray<ObITask*> last_task_array;
  ObITask* last_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_ERROR("not inited", K(ret));
  } else if (OB_FAIL(need_generate_sstable_migrate_tasks(need_schedule))) {
    LOG_WARN("failed to check generate sstable migrate task", K(ret));
  } else if (!need_schedule) {
    LOG_INFO("no need_generate_sstable_migrate_tasks");
  } else if (REBUILD_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(generate_pg_rebuild_tasks(last_task_array))) {
      LOG_WARN("failed to generate rebuild task", K(ret));
    }
  } else if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(generate_pg_backup_tasks(last_task_array))) {
      LOG_WARN("failed to generate backup task", K(ret));
    }
  } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
    if (OB_FAIL(generate_pg_validate_tasks(last_task_array))) {
      LOG_WARN("failed to generate validate task", K(ret));
    }
  } else if (OB_FAIL(generate_pg_migrate_tasks(last_task_array))) {
    LOG_WARN("failed to generate_pg_migrate_tasks", K(ret));
  }

  if (OB_SUCC(ret)) {
    if (BACKUP_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      LOG_INFO("no need finish task for backup");
    } else if (VALIDATE_BACKUP_OP == ctx_->replica_op_arg_.type_) {
      LOG_INFO("no need finish task for validate");
    } else if (OB_FAIL(generate_finish_migrate_task(last_task_array, last_task))) {
      LOG_WARN("failed to generate prepare migrate task", K(ret));
    } else if (RESTORE_REPLICA_OP == ctx_->replica_op_arg_.type_) {
      if (OB_FAIL(generate_restore_tailored_task(last_task))) {
        LOG_WARN("failed to generate restore tailored task", K(ret));
      }
    }
  }

  if (OB_SUCC(ret)) {
    if (OB_SUCCESS != (tmp_ret = ctx_->update_partition_migration_status())) {
      LOG_WARN("failed to update partition migration status", K(tmp_ret));
    }
  }

  // Whether success or failure, we need to clean up the reference count of macro block to prevent leakage
  if (NULL != ctx_) {
    ctx_->free_old_macro_block();
  }
  return ret;
}

int ObMigratePostPrepareTask::update_multi_version_start()
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition = NULL;
  ObPGStorage* pg_storage = NULL;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate prepare task do not init", K(ret));
  } else if (OB_ISNULL(partition = ctx_->get_partition())) {
    ret = OB_ERR_SYS;
    LOG_WARN("can not update multi version when pg is null", K(ret), KP(partition));
  } else if (OB_ISNULL(pg_storage = &(partition->get_pg_storage()))) {
    ret = OB_ERR_SYS;
    LOG_WARN("pg storage should not be NULL", K(ret), KP(pg_storage));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < ctx_->part_ctx_array_.count(); ++i) {
      const ObPartitionMigrateCtx& pctx = ctx_->part_ctx_array_.at(i);
      const ObMigratePartitionInfo& copy_info = ctx_->part_ctx_array_.at(i).copy_info_;
      const ObPartitionKey& pkey = copy_info.meta_.pkey_;
      if (pctx.is_partition_exist_) {
        if (OB_FAIL(pg_storage->update_multi_version_start(pkey, copy_info.meta_.multi_version_start_))) {
          LOG_WARN("fail to update multi version start", K(ret), K(pkey), K(copy_info));
        }
      }
    }
  }
  return ret;
}

int ObMigratePostPrepareTask::deal_with_new_partition()
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(ctx_->group_task_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("group task should not be null here", K(ret));
  }
  return ret;
}

int ObMigratePostPrepareTask::generate_restore_tailored_task(share::ObITask* last_task)
{
  int ret = OB_SUCCESS;
  ObRestoreTailoredPrepareTask* prepare_task = NULL;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("migrate post prepare task do not init", K(ret));
  } else if (OB_ISNULL(last_task)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate restore tailored task get invalid argument", K(ret), KP(last_task));
  } else if (RESTORE_REPLICA_OP != ctx_->replica_op_arg_.type_ && RESTORE_STANDBY_OP != ctx_->replica_op_arg_.type_) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("failed to generate restore tailored task", K(ret), K(*ctx_));
  } else if (OB_FAIL(dag_->alloc_task(prepare_task))) {
    LOG_WARN("failed to allock prepare task", K(ret));
  } else if (OB_FAIL(prepare_task->init())) {
    LOG_WARN("failed to init prepare task", K(ret));
  } else if (OB_FAIL(last_task->add_child(*prepare_task))) {
    LOG_WARN("failed to add prepare task to child task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*prepare_task))) {
    LOG_WARN("failed to add prepare task to dag", K(ret));
  }
  return ret;
}

int ObMigrateUtil::wait_trans_table_merge_finish(ObMigrateCtx& ctx)
{
  int ret = OB_SUCCESS;
  const int64_t WAIT_TIMEOUT = 300L * 1000L * 1000L;  // 5min
  const int64_t SLEEP_INTERVAL = 100L * 1000L;        // 100ms
  ObTransTableMergeDag fake_dag;
  if (OB_FAIL(fake_dag.init(ctx.pg_meta_.pg_key_))) {
    LOG_WARN("failed to init dag", K(ret), K(ctx.pg_meta_.pg_key_));
  } else if (OB_FAIL(ObDagScheduler::get_instance().cancel_dag(&fake_dag))) {
    LOG_WARN("failed to cancel dag", K(ret), K(fake_dag));
  } else {
    bool exist = true;
    const int64_t start_ts = ObTimeUtility::current_time();
    do {
      if (OB_FAIL(ObDagScheduler::get_instance().check_dag_exist(&fake_dag, exist))) {
        LOG_WARN("failed to check dag exist", K(ret), K(fake_dag));
12519
      } else if (exist) {
O
oceanbase-admin 已提交
12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616
        if (ObTimeUtility::current_time() - start_ts > WAIT_TIMEOUT) {
          ret = OB_WAIT_TRANS_TABLE_MERGE_TIMEOUT;
          LOG_WARN("wait trans table merge finish timeout", K(ret), K(fake_dag));
        } else {
          usleep(SLEEP_INTERVAL);
        }
      }
    } while (OB_SUCC(ret) && exist);
  }
  return ret;
}

ObRestoreTailoredPrepareTask::ObRestoreTailoredPrepareTask()
    : ObITask(TASK_TYPE_RESTORE_TAILORED_PREPARE), is_inited_(false), ctx_(NULL)
{}

ObRestoreTailoredPrepareTask::~ObRestoreTailoredPrepareTask()
{}

int ObRestoreTailoredPrepareTask::init()
{
  int ret = OB_SUCCESS;
  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_WARN("restore tailored prepare task init twice", K(ret));
  } else if (ObIDag::DAG_TYPE_MIGRATE != dag_->get_type()) {
    ret = OB_ERR_SYS;
    LOG_ERROR("dag type not match", K(ret), K(*dag_));
  } else {
    ctx_ = static_cast<ObMigrateDag*>(dag_)->get_ctx();
    is_inited_ = true;
  }
  return ret;
}

int ObRestoreTailoredPrepareTask::process()
{
  int ret = OB_SUCCESS;
  ObRestoreTailoredFinishTask* finish_task = NULL;
  ObIPartitionGroup* partition_group = NULL;
  bool need_generate = false;
  bool cleared_memstore = false;
  bool has_memstore = false;
  int16_t restore_state = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;

  LOG_INFO("start ObRestoreTailoredPrepareTask process", "pg_key", ctx_->replica_op_arg_.key_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored prepare task do not init", K(ret));
  } else if (OB_ISNULL(partition_group = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition should not be NULL", K(ret), KP(partition_group));
  } else if (FALSE_IT(restore_state = partition_group->get_pg_storage().get_restore_state())) {
  } else if (REPLICA_RESTORE_DATA != restore_state && REPLICA_RESTORE_CUT_DATA != restore_state &&
             REPLICA_RESTORE_ARCHIVE_DATA != restore_state) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected restore state during tailored task", K(ret), K(restore_state));
  } else if (REPLICA_RESTORE_ARCHIVE_DATA == restore_state) {
    LOG_INFO("replica archive data not need cut data, skip", K(restore_state));
  } else if (FALSE_IT(has_memstore = partition_group->get_pg_storage().has_memstore())) {
  } else if (has_memstore && OB_FAIL(partition_group->get_pg_storage().clear_non_reused_stores(
                                 ctx_->replica_op_arg_.key_, cleared_memstore))) {
    LOG_WARN("failed to clean non reuse stores", K(ret), K(*ctx_));
  } else if (has_memstore && !cleared_memstore) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("has memstore but do do cleared memstore", K(ret), K(has_memstore), K(cleared_memstore));
  } else if (OB_FAIL(check_need_generate_task(need_generate))) {
    LOG_WARN("failed to check need generate task", K(ret));
  } else if (!need_generate) {
    // do nothing
  } else if (OB_FAIL(dag_->alloc_task(finish_task))) {
    LOG_WARN("failed to alloc finish task", K(ret));
  } else if (OB_FAIL(finish_task->init())) {
    LOG_WARN("failed to init finish task", K(ret));
  } else if (OB_FAIL(update_restore_flag_cut_data())) {
    LOG_WARN("failed to update restore flag cut data", K(ret));
  } else if (OB_FAIL(schedule_restore_tailored_task(*finish_task))) {
    LOG_WARN("failed to schedule restore tailored task", K(ret));
  } else if (OB_FAIL(dag_->add_task(*finish_task))) {
    LOG_WARN("failed to add finish task", K(ret));
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    ctx_->set_result_code(ret);
  }

  LOG_INFO("end ObRestoreTailoredPrepareTask process", "pg_key", ctx_->replica_op_arg_.key_);
  return ret;
}

int ObRestoreTailoredPrepareTask::schedule_restore_tailored_task(ObRestoreTailoredFinishTask& finish_task)
{
  int ret = OB_SUCCESS;
  ObIPartitionGroup* partition_group = NULL;
  ObPartitionArray pkeys;
  const bool include_trans_table = false;
12617
  const bool is_restore_point = false;
O
oceanbase-admin 已提交
12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631
  const int64_t restore_schema_version = OB_INVALID_VERSION;
  const int64_t current_schema_version = OB_INVALID_VERSION;
  ObRecoveryPointSchemaFilter schema_filter;
  uint64_t tenant_id = OB_INVALID_ID;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored prepare task do not init", K(ret));
  } else if (FALSE_IT(tenant_id = ctx_->replica_op_arg_.key_.get_tenant_id())) {
  } else if (OB_ISNULL(partition_group = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition group should not be NULL", K(ret), KP(partition_group));
  } else if (OB_FAIL(partition_group->get_all_pg_partition_keys(pkeys, include_trans_table))) {
    LOG_WARN("failed to get all pg partition keys", K(ret), "pg key", ctx_->replica_op_arg_.key_);
12632
  } else if (OB_FAIL(schema_filter.init(tenant_id, is_restore_point, restore_schema_version, current_schema_version))) {
O
oceanbase-admin 已提交
12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731
    LOG_WARN("failed to init schema filter", K(ret), K(tenant_id), K(restore_schema_version));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < pkeys.count(); ++i) {
      const ObPartitionKey& pkey = pkeys.at(i);
      ObPGPartitionGuard pg_partition_guard;
      ObTablesHandle tables_handle;
      ObPartitionStorage* storage = NULL;
      ObArray<uint64_t> index_ids;
      bool is_exist = false;
      if (schema_filter.check_partition_exist(pkey, is_exist)) {
        LOG_WARN("failed to check partition exist", K(ret), K(pkey));
      } else if (!is_exist) {
        // do nothing
      } else if (OB_FAIL(partition_group->get_pg_partition(pkey, pg_partition_guard))) {
        STORAGE_LOG(WARN, "get pg partition error", K(ret), K(pkey));
      } else if (OB_ISNULL(pg_partition_guard.get_pg_partition())) {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN, "get pg partition error", K(ret), KP(pg_partition_guard.get_pg_partition()));
      } else if (OB_ISNULL(storage = static_cast<ObPartitionStorage*>(
                               pg_partition_guard.get_pg_partition()->get_storage()))) {
        ret = OB_ERR_UNEXPECTED;
        STORAGE_LOG(WARN, "partition storage must not be NULL", K(ret));
      } else if (OB_FAIL(storage->get_partition_store().get_all_table_ids(index_ids))) {
        STORAGE_LOG(WARN, "failed to get all table ids", K(ret));
      } else if (OB_FAIL(filter_tailored_tables(index_ids, schema_filter))) {
        LOG_WARN("failed to filter tailored tables", K(ret));
      } else if (OB_FAIL(schedule_restore_table_tailored_task_(index_ids, pkey, *storage, finish_task))) {
        STORAGE_LOG(WARN, "failed to schedule restore table tailored task", K(ret));
      }
    }
  }
  return ret;
}

int ObRestoreTailoredPrepareTask::schedule_restore_table_tailored_task_(const common::ObIArray<uint64_t>& index_ids,
    const ObPartitionKey& partition_key, ObPartitionStorage& storage, ObRestoreTailoredFinishTask& finish_task)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored prepare task do not init", K(ret));
  } else {
    const ObPGKey& pg_key = ctx_->replica_op_arg_.key_;
    for (int64_t i = 0; OB_SUCC(ret) && i < index_ids.count(); ++i) {
      const uint64_t index_id = index_ids.at(i);
      ObTablesHandle minor_tables_handle;
      ObTableHandle major_handle;
      ObRestoreTailoredTask* task = NULL;
      if (OB_FAIL(storage.get_partition_store().get_latest_minor_sstables(index_id, minor_tables_handle))) {
        LOG_WARN("failed to get latest minor sstables", K(ret), K(index_id));
      } else if (OB_FAIL(storage.get_partition_store().get_last_major_sstable(index_id, major_handle))) {
        LOG_WARN("failed to get lastest major sstable", K(ret), K(index_id));
      } else if (OB_FAIL(dag_->alloc_task(task))) {
        LOG_WARN("failed to alloc task", K(ret));
      } else if (OB_FAIL(task->init(index_id, minor_tables_handle, major_handle, pg_key, partition_key, finish_task))) {
        LOG_WARN("failed to init restore tailored prepare task", K(ret), K(partition_key));
      } else if (OB_FAIL(this->add_child(*task))) {
        LOG_WARN("failed to add child of task", K(ret));
      } else if (OB_FAIL(dag_->add_task(*task))) {
        LOG_WARN("failed to add task to dag", K(ret));
      } else if (OB_FAIL(task->add_child(finish_task))) {
        LOG_WARN("failed to add finish task", K(ret));
      }
    }
  }
  return ret;
}

int ObRestoreTailoredPrepareTask::filter_tailored_tables(
    common::ObIArray<uint64_t>& index_ids, ObRecoveryPointSchemaFilter& schema_filter)
{
  int ret = OB_SUCCESS;
  ObArray<uint64_t> tmp_index_ids;

  for (int64_t i = 0; OB_SUCC(ret) && i < index_ids.count(); ++i) {
    const uint64_t index_id = index_ids.at(i);
    bool is_exist = false;
    if (OB_FAIL(schema_filter.check_table_exist(index_id, is_exist))) {
      LOG_WARN("failed to check table exist", K(ret), K(index_id));
    } else if (!is_exist) {
      // do nothing
    } else if (OB_FAIL(tmp_index_ids.push_back(index_id))) {
      LOG_WARN("failed to push index id into array", K(ret), K(index_id));
    }
  }

  if (OB_SUCC(ret)) {
    index_ids.reset();
    if (OB_FAIL(index_ids.assign(tmp_index_ids))) {
      LOG_WARN("failed to assign index ids", K(ret));
    }
  }
  return ret;
}

int ObRestoreTailoredPrepareTask::update_restore_flag_cut_data()
{
  int ret = OB_SUCCESS;
  const int16_t flag = REPLICA_RESTORE_CUT_DATA;
O
obdev 已提交
12732 12733
  ObIPartitionGroup* partition_group = NULL;
  int16_t restore_status = ObReplicaRestoreStatus::REPLICA_NOT_RESTORE;
O
oceanbase-admin 已提交
12734 12735 12736 12737

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore failored prepare task do not init", K(ret));
O
obdev 已提交
12738 12739 12740 12741 12742 12743
  } else if (OB_ISNULL((partition_group = ctx_->partition_guard_.get_partition_group()))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition group should not be NULL", K(ret), KP(partition_group));
  } else if (FALSE_IT(restore_status = partition_group->get_pg_storage().get_restore_state())) {
  } else if (restore_status == flag) {
    // do nothing
O
oceanbase-admin 已提交
12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759
  } else {
    const ObPGKey& pg_key = ctx_->replica_op_arg_.key_;
    if (OB_FAIL(MIGRATOR.get_partition_service()->set_restore_flag(pg_key, flag))) {
      LOG_WARN("failed to set restore flag", K(ret), K(pg_key));
    }
  }
  return ret;
}

int ObRestoreTailoredPrepareTask::check_need_generate_task(bool& need_generate)
{
  int ret = OB_SUCCESS;
  need_generate = false;
  ObIPartitionGroup* partition_group = NULL;
  ObTablesHandle tables_handle;
  int64_t max_upper_trans_version = 0;
O
obdev 已提交
12760
  transaction::ObTransService* trans_service = NULL;
O
oceanbase-admin 已提交
12761 12762 12763 12764 12765 12766 12767 12768 12769

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore failored prepare task do not init", K(ret));
  } else if (OB_ISNULL(partition_group = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition group should not be NULL", K(ret), KP(partition_group));
  } else if (OB_FAIL(partition_group->get_all_tables(tables_handle))) {
    LOG_WARN("failed to get all tables", K(ret), KP(partition_group));
O
obdev 已提交
12770 12771 12772 12773 12774
  } else if (OB_ISNULL(trans_service = GCTX.par_ser_->get_trans_service())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("trans service should not be NULL", K(ret), KP(trans_service));
  } else if (RESTORE_STANDBY_OP == ctx_->replica_op_arg_.type_) {
    need_generate = true;
O
oceanbase-admin 已提交
12775 12776 12777 12778
  } else {
    const int64_t restore_snapshot_version =
        ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.restore_snapshot_version_;
    for (int64_t i = 0; OB_SUCC(ret) && i < tables_handle.get_count(); ++i) {
O
obdev 已提交
12779 12780
      ObITable* table = tables_handle.get_table(i);
      ObSSTable* sstable = NULL;
O
oceanbase-admin 已提交
12781 12782 12783 12784 12785
      if (OB_ISNULL(table)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table should not be NULL", K(ret), KP(table));
      } else if (table->is_major_sstable() || table->is_trans_sstable()) {
        // do nothing
O
obdev 已提交
12786 12787 12788
      } else if (OB_ISNULL(sstable = reinterpret_cast<ObSSTable*>(table))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("sstable should not be NULL", K(ret), KP(sstable));
O
oceanbase-admin 已提交
12789
      } else {
O
obdev 已提交
12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809
        int64_t max_trans_version = sstable->get_upper_trans_version();
        if (INT64_MAX == sstable->get_upper_trans_version()) {
          bool is_all_rollback_trans = false;
          // get_all_latest_minor_sstables return all minor except complement
          // all normal minor sstable consist of data between [start_log_ts, end_log_ts]
          if (OB_FAIL(trans_service->get_max_trans_version_before_given_log_ts(
                  sstable->get_partition_key(), sstable->get_end_log_ts(), max_trans_version, is_all_rollback_trans))) {
            LOG_WARN("failed to get_max_trans_version_before_given_log_id", K(ret), KPC(sstable));
          } else if (0 == max_trans_version && !is_all_rollback_trans) {
            ret = OB_ERR_UNEXPECTED;
            LOG_ERROR("max trans version should not be 0",
                K(sstable->get_partition_key()),
                "end_log_ts",
                sstable->get_end_log_ts());
          }
        }

        if (OB_SUCC(ret)) {
          max_upper_trans_version = std::max(max_trans_version, max_upper_trans_version);
        }
O
oceanbase-admin 已提交
12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875
      }
    }

    if (OB_SUCC(ret)) {
      need_generate = restore_snapshot_version < max_upper_trans_version;
      // do need generate task
      if (!need_generate) {
        LOG_INFO("restore snapshot version is larger than max upper trans version, no need cut",
            K(restore_snapshot_version),
            K(max_upper_trans_version),
            K(tables_handle));
      }
    }
  }
  return ret;
}

ObRestoreTailoredTask::ObRestoreTailoredTask()
    : ObITask(TASK_TYPE_RESTORE_TAILORED_PROCESS),
      is_inited_(false),
      ctx_(NULL),
      index_id_(OB_INVALID_ID),
      minor_tables_handle_(),
      major_table_handle_(),
      pg_key_(),
      finish_task_(NULL)
{}

ObRestoreTailoredTask::~ObRestoreTailoredTask()
{}

int ObRestoreTailoredTask::init(const uint64_t index_id, const ObTablesHandle& minor_tables_handle,
    const ObTableHandle& major_table_handle, const ObPGKey& pg_key, const ObPartitionKey& partition_key,
    ObRestoreTailoredFinishTask& finish_task)
{
  int ret = OB_SUCCESS;
  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_WARN("restore tailored task has already inited", K(ret));
  } else if (OB_INVALID_ID == index_id || !pg_key.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("init restore tailored task get invalid argument", K(ret), K(index_id), K(pg_key));
  } else if (OB_FAIL(minor_tables_handle_.add_tables(minor_tables_handle))) {
    LOG_WARN("failed to add table handle", K(ret), K(index_id));
  } else if (OB_FAIL(major_table_handle_.assign(major_table_handle))) {
    LOG_WARN("failed to add major tables handle", K(ret), K(index_id));
  } else {
    index_id_ = index_id;
    pg_key_ = pg_key;
    partition_key_ = partition_key;
    ctx_ = static_cast<ObMigrateDag*>(dag_)->get_ctx();
    finish_task_ = &finish_task;
    is_inited_ = true;
  }
  return ret;
}

int ObRestoreTailoredTask::process()
{
  int ret = OB_SUCCESS;
  ObITable::TableKey table_key;
  ObTailoredRowIterator row_iter;
  ObMigrateLogicRowWriter logic_row_writer;
  ObMacroBlocksWriteCtx block_write_ctx;
  ObMacroBlocksWriteCtx lob_block_write_ctx;
  const int64_t schema_version = OB_INVALID_VERSION;
O
obdev 已提交
12876
  int64_t restore_snapshot = 0;
O
oceanbase-admin 已提交
12877 12878 12879 12880 12881 12882 12883 12884 12885

  LOG_INFO("start ObRestoreTailoredTask process", "table_id", index_id_, "partition_key", partition_key_);

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored task do not init", K(ret));
  } else if (minor_tables_handle_.empty()) {
    // do nothing
    LOG_INFO("minor tables handle is empty, no need cut", K(partition_key_), K(index_id_));
O
obdev 已提交
12886 12887
  } else if (FALSE_IT(
                 restore_snapshot = ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.restore_snapshot_version_)) {
O
oceanbase-admin 已提交
12888 12889
  } else if (OB_FAIL(get_tailored_table_key(table_key))) {
    LOG_WARN("failed to get tailored table key", K(ret), K(index_id_), K(pg_key_));
O
obdev 已提交
12890 12891
  } else if (OB_FAIL(row_iter.init(
                 index_id_, pg_key_, schema_version, table_key, restore_snapshot, minor_tables_handle_))) {
O
oceanbase-admin 已提交
12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921
    LOG_WARN("failed to init tailored row iter", K(ret), K(index_id_), K(pg_key_), K(partition_key_));
  } else if (OB_FAIL(logic_row_writer.init(&row_iter, pg_key_, ctx_->get_partition()->get_storage_file_handle()))) {
    LOG_WARN("failed to init logic row writer", K(ret), K(pg_key_), K(partition_key_));
  } else if (OB_FAIL(logic_row_writer.process(block_write_ctx, lob_block_write_ctx))) {
    LOG_WARN("failed to process writer", K(ret));
  } else if (OB_FAIL(generate_new_minor_sstable(table_key, block_write_ctx, lob_block_write_ctx))) {
    LOG_WARN("failed to generate new sstable", K(ret), K(table_key));
  } else if (OB_FAIL(generate_major_sstable())) {
    LOG_WARN("failed to generate major sstable", K(ret), K(partition_key_), K(index_id_));
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    ctx_->set_result_code(ret);
  }

  LOG_INFO("end ObRestoreTailoredTask process", "table_id", index_id_, "partition key", partition_key_);

  return ret;
}

int ObRestoreTailoredTask::get_tailored_table_key(ObITable::TableKey& table_key)
{
  int ret = OB_SUCCESS;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored task do not init", K(ret));
  } else {
    int64_t base_version = INT64_MAX;
    int64_t multi_version_start = 0;
O
obdev 已提交
12922
    int64_t snapshot_version = 0;
O
oceanbase-admin 已提交
12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952
    int64_t start_log_ts = INT64_MAX;
    int64_t end_log_ts = 0;
    int64_t max_log_ts = 0;
    int64_t pre_log_ts = 0;
    for (int64_t i = 0; OB_SUCC(ret) && i < minor_tables_handle_.get_count(); ++i) {
      const ObITable* table = minor_tables_handle_.get_table(i);
      if (OB_ISNULL(table)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table should not be NULL", K(ret), KP(table), K(index_id_), K(partition_key_), K(pg_key_));
      } else if (!table->is_minor_sstable()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table type is unexpected", K(ret), KPC(table));
      } else if (0 == i) {
        pre_log_ts = table->get_end_log_ts();
        multi_version_start = table->get_multi_version_start();
      } else if (pre_log_ts > table->get_start_log_ts()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("minor table is not continue", K(ret), K(*table));
      } else {
        if (table->get_base_version() != table->get_multi_version_start()) {
          multi_version_start = table->get_multi_version_start();
        }
        pre_log_ts = table->get_end_log_ts();
      }

      if (OB_SUCC(ret)) {
        base_version = std::min(base_version, table->get_base_version());
        start_log_ts = std::min(start_log_ts, table->get_start_log_ts());
        end_log_ts = std::max(end_log_ts, table->get_end_log_ts());
        max_log_ts = std::max(max_log_ts, table->get_max_log_ts());
O
obdev 已提交
12953
        snapshot_version = std::max(snapshot_version, table->get_snapshot_version());
O
oceanbase-admin 已提交
12954 12955 12956 12957 12958 12959 12960 12961 12962 12963
      }
    }

    if (OB_SUCC(ret)) {
      table_key.pkey_ = partition_key_;
      table_key.table_id_ = index_id_;
      table_key.table_type_ = ObITable::MULTI_VERSION_MINOR_SSTABLE;
      table_key.trans_version_range_.base_version_ = base_version;
      table_key.trans_version_range_.multi_version_start_ = multi_version_start;
      table_key.trans_version_range_.snapshot_version_ =
O
obdev 已提交
12964
          std::min(ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.restore_snapshot_version_, snapshot_version);
O
oceanbase-admin 已提交
12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186
      table_key.version_.version_ = ctx_->replica_op_arg_.phy_restore_arg_.restore_data_version_ + 1;
      // table_key.upper_trans_version
      // table_key.max_merged_version
      // log ts
      table_key.log_ts_range_.start_log_ts_ = start_log_ts;
      table_key.log_ts_range_.end_log_ts_ = end_log_ts;
      table_key.log_ts_range_.max_log_ts_ = max_log_ts;
      if (!table_key.is_valid()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("tailored table key is invalid", K(ret), K(table_key));
      } else if (1 == minor_tables_handle_.get_count()) {
        const ObITable* table = minor_tables_handle_.get_table(0);
        if (table->get_key() == table_key) {
          // same table key not allowed because can not add in table mgr
          table_key.table_type_ = ObITable::MINI_MINOR_SSTABLE;
          if (!table_key.is_valid()) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("tailored table key is invalid", K(ret), K(table_key));
          }
        }
      }

      if (OB_FAIL(ret)) {
      } else {
        LOG_INFO("new cut table key", K(table_key));
      }
    }
  }
  return ret;
}

int ObRestoreTailoredTask::generate_new_minor_sstable(const ObITable::TableKey& table_key,
    ObMacroBlocksWriteCtx& block_write_ctx, ObMacroBlocksWriteCtx& lob_block_write_ctx)
{
  int ret = OB_SUCCESS;
  storage::ObCreateSSTableParamWithTable create_sstable_param;
  ObSSTable* sstable = NULL;
  ObSchemaGetterGuard schema_guard;
  ObTableHandle handle;
  bool has_lob_column = false;
  const uint64_t table_id = index_id_;
  const uint64_t tenant_id = is_inner_table(table_id) ? OB_SYS_TENANT_ID : extract_tenant_id(table_id);
  const bool check_formal =
      extract_pure_id(table_id) > OB_MAX_CORE_TABLE_ID;  // Avoid the problem of circular dependency

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored task do not init", K(ret));
  } else if (!table_key.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("generate new sstable get invalid argument", K(ret), K(table_key));
  } else {
    create_sstable_param.table_key_ = table_key;
    create_sstable_param.logical_data_version_ = table_key.trans_version_range_.snapshot_version_;
    if (OB_FAIL(MIGRATOR.get_schema_service()->get_tenant_schema_guard(tenant_id, schema_guard))) {
      LOG_WARN("failed to get schema guard", K(ret), K(tenant_id), K(table_key));
    } else if (check_formal && OB_FAIL(schema_guard.check_formal_guard())) {
      LOG_WARN("schema_guard is not formal", K(ret), K(tenant_id));
    } else if (OB_FAIL(schema_guard.get_table_schema(table_key.table_id_, create_sstable_param.schema_))) {
      LOG_WARN("Fail to get table schema, ", K(ret), K(partition_key_));
    } else if (OB_ISNULL(create_sstable_param.schema_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("Unexpected null table schema", K(ret), K(partition_key_));
    } else if (OB_FAIL(
                   schema_guard.get_table_schema_version(table_key.table_id_, create_sstable_param.schema_version_))) {
      LOG_WARN("failed to get table schema version", K(ret), K(table_key));
    } else if (OB_FAIL(create_sstable_param.schema_->has_lob_column(has_lob_column, true))) {
      LOG_WARN("Failed to check lob column in table schema", K(ret));
    } else {
      ObPGCreateSSTableParam param;
      param.with_table_param_ = &create_sstable_param;
      if (!block_write_ctx.file_handle_.is_valid() &&
          OB_FAIL(block_write_ctx.file_handle_.assign(
              ctx_->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
        LOG_WARN("fail to assign file handle", K(ret));
      } else if (!lob_block_write_ctx.file_handle_.is_valid() &&
                 OB_FAIL(lob_block_write_ctx.file_handle_.assign(
                     ctx_->partition_guard_.get_partition_group()->get_storage_file_handle()))) {
        LOG_WARN("fail to assign file handle", K(ret));
      } else if (OB_FAIL(param.data_blocks_.push_back(&block_write_ctx))) {
        LOG_WARN("fail to push back data block write ctx", K(ret));
      } else if (has_lob_column && lob_block_write_ctx.is_valid() && !lob_block_write_ctx.is_empty()) {
        if (OB_FAIL(param.lob_blocks_.push_back(&lob_block_write_ctx))) {
          LOG_WARN("fail to push back lob block write ctx", K(ret));
        }
      }

      if (OB_SUCC(ret)) {
        ObIPartitionGroup* pg = nullptr;
        if (OB_ISNULL(pg = ctx_->partition_guard_.get_partition_group())) {
          ret = OB_ERR_SYS;
          LOG_WARN("partition must not null", K(ret));
        } else if (OB_FAIL(pg->create_sstable(param, handle))) {
          LOG_WARN("fail to create sstable", K(ret));
        } else if (OB_FAIL(handle.get_sstable(sstable))) {
          LOG_WARN("fail to get sstable", K(ret));
        } else if (OB_FAIL(finish_task_->add_sstable_handle(partition_key_, handle))) {
          LOG_WARN("failed to add sstable handle", K(ret));
        }

        if (OB_SUCC(ret)) {
          if (OB_FAIL(finish_task_->set_schema_version(create_sstable_param.schema_version_))) {
            LOG_WARN("failed to set schema version", K(ret), K(create_sstable_param));
          }
        }
      }
    }
  }
  return ret;
}

int ObRestoreTailoredTask::generate_major_sstable()
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored task do not init", K(ret));
  } else if (OB_FAIL(finish_task_->add_sstable_handle(partition_key_, major_table_handle_))) {
    LOG_WARN("failed to add sstable handle", K(ret), K(partition_key_));
  }
  return ret;
}

ObRestoreTailoredFinishTask::ObRestoreTailoredFinishTask()
    : ObITask(TASK_TYPE_RESTORE_TAILORED_FINISH),
      is_inited_(false),
      ctx_(NULL),
      lock_(),
      part_ctx_array_(),
      schema_version_(OB_INVALID_VERSION)
{}

ObRestoreTailoredFinishTask::~ObRestoreTailoredFinishTask()
{}

int ObRestoreTailoredFinishTask::add_sstable_handle(const ObPartitionKey& pkey, ObTableHandle& handle)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored finish task do not init", K(ret));
  } else if (!pkey.is_valid() || !handle.is_valid()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("add sstable handle get invalid argument", K(ret), K(handle));
  } else {
    common::SpinWLockGuard guard(lock_);
    bool found = false;
    for (int64_t i = 0; OB_SUCC(ret) && i < part_ctx_array_.count() && !found; ++i) {
      ObPartitionMigrateCtx& part_ctx = part_ctx_array_.at(i);
      if (part_ctx.copy_info_.meta_.pkey_ == pkey) {
        if (OB_FAIL(part_ctx.handle_.add_table(handle))) {
          LOG_WARN("failed to add table handle", K(ret), K(handle));
        } else {
          found = true;
        }
      }
    }

    if (OB_SUCC(ret) && !found) {
      ObPartitionMigrateCtx part_ctx;
      part_ctx.is_partition_exist_ = true;
      part_ctx.need_reuse_local_minor_ = false;
      part_ctx.ctx_ = ctx_;
      if (OB_FAIL(ctx_->partition_guard_.get_partition_group()->get_pg_storage().get_pg_partition_store_meta(
              pkey, part_ctx.copy_info_.meta_))) {
        LOG_WARN("failed to get pg partition store meta", K(ret), K(pkey));
      } else if (OB_FAIL(part_ctx.handle_.add_table(handle))) {
        LOG_WARN("failed to add table handle", K(ret), K(handle));
      } else if (OB_FAIL(part_ctx_array_.push_back(part_ctx))) {
        LOG_WARN("failed to push part ctx into array", K(ret));
      }
    }
  }
  return ret;
}

int ObRestoreTailoredFinishTask::init()
{
  int ret = OB_SUCCESS;
  if (is_inited_) {
    ret = OB_INIT_TWICE;
    LOG_WARN("restore tailored finish task init twice", K(ret));
  } else {
    ctx_ = static_cast<ObMigrateDag*>(dag_)->get_ctx();
    is_inited_ = true;
  }
  return ret;
}

int ObRestoreTailoredFinishTask::process()
{
  int ret = OB_SUCCESS;
  const int64_t schema_version = OB_INVALID_VERSION;
  ObIPartitionGroup* partition_group = NULL;
  ObSavedStorageInfoV2 save_info;
  ObPGKey pg_key;

  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored finish task do not init", K(ret));
  } else {
    pg_key = ctx_->replica_op_arg_.key_;
    LOG_INFO("start ObRestoreTailoredFinishTask process", "pg key", pg_key);
  }

  if (OB_FAIL(ret)) {
    // do nothing
  } else if (OB_ISNULL(partition_group = ctx_->partition_guard_.get_partition_group())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("partition group should not be NULL", K(ret), KP(partition_group));
  } else {
    int64_t trans_table_seq = ctx_->partition_guard_.get_partition_group()->get_pg_storage().get_trans_table_seq();
    const int64_t restore_snapshot_version =
        ctx_->replica_op_arg_.phy_restore_arg_.restore_info_.restore_snapshot_version_;

    if (OB_FAIL(partition_group->get_pg_storage().batch_replace_store_map(
            part_ctx_array_, schema_version, ctx_->is_restore_, trans_table_seq))) {
      LOG_WARN("failed to batch replace store map", K(ret));
    } else if (OB_FAIL(partition_group->get_all_saved_info(save_info))) {
      LOG_WARN("failed to get all saved info", K(ret));
    } else {
      ObDataStorageInfo& storage_info = save_info.get_data_info();
O
obdev 已提交
13187 13188
      const int64_t publish_version = std::min(storage_info.get_publish_version(), restore_snapshot_version);
      storage_info.set_publish_version(publish_version);
O
oceanbase-admin 已提交
13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220
      storage_info.set_schema_version(schema_version_);
      if (OB_FAIL(partition_group->set_storage_info(save_info))) {
        LOG_WARN("failed to set storage info", K(ret), K(save_info));
      }
    }
  }

  if (OB_FAIL(ret) && NULL != ctx_) {
    ctx_->set_result_code(ret);
  }

  LOG_INFO("end ObRestoreTailoredFinishTask process", "pg key", pg_key);
  return ret;
}

int ObRestoreTailoredFinishTask::set_schema_version(const int64_t schema_version)
{
  int ret = OB_SUCCESS;
  if (!is_inited_) {
    ret = OB_NOT_INIT;
    LOG_WARN("restore tailored finish task do not init", K(ret));
  } else if (schema_version < 0) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("set schema version get invalid argument", K(ret), K(schema_version));
  } else {
    schema_version_ = std::max(schema_version_, schema_version);
  }
  return ret;
}

} /* namespace storage */
} /* namespace oceanbase */