Coverage Report

Created: 2026-08-24 15:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
constexpr size_t kRowsetBatchGetSize = 256;
89
90
0
int64_t packed_file_retry_sleep_ms() {
91
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
92
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
93
0
    thread_local std::mt19937_64 gen(std::random_device {}());
94
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
95
0
    return dist(gen);
96
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
97
98
0
void sleep_for_packed_file_retry() {
99
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
100
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
101
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
110
111
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
868k
    const auto& locations = rowset.packed_slice_locations();
113
868k
    auto it = locations.find(path);
114
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
868k
           !it->second.packed_file_path().empty();
116
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
7
    const auto& locations = rowset.packed_slice_locations();
113
7
    auto it = locations.find(path);
114
7
    return it != locations.end() && it->second.has_packed_file_path() &&
115
7
           !it->second.packed_file_path().empty();
116
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
868k
    const auto& locations = rowset.packed_slice_locations();
113
868k
    auto it = locations.find(path);
114
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
868k
           !it->second.packed_file_path().empty();
116
868k
}
117
118
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
119
                                      const std::string& path,
120
869k
                                      std::vector<std::string>* file_paths) {
121
870k
    if (!is_packed_slice_path(rowset, path)) {
122
870k
        file_paths->push_back(path);
123
870k
    }
124
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
7
                                      std::vector<std::string>* file_paths) {
121
7
    if (!is_packed_slice_path(rowset, path)) {
122
7
        file_paths->push_back(path);
123
7
    }
124
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
868k
                                      std::vector<std::string>* file_paths) {
121
870k
    if (!is_packed_slice_path(rowset, path)) {
122
870k
        file_paths->push_back(path);
123
870k
    }
124
868k
}
125
126
} // namespace
127
128
// return 0 for success get a key, 1 for key not found, negative for error
129
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
0
    std::unique_ptr<Transaction> txn;
131
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
0
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
0
    switch (txn->get(key, &val, true)) {
136
0
    case TxnErrorCode::TXN_OK:
137
0
        return 0;
138
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
0
        return 1;
140
0
    default:
141
0
        return -1;
142
0
    };
143
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
144
145
// 0 for success, negative for error
146
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
147
334
                   std::unique_ptr<RangeGetIterator>& it) {
148
334
    std::unique_ptr<Transaction> txn;
149
334
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
334
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
334
    switch (txn->get(begin, end, &it, true)) {
154
334
    case TxnErrorCode::TXN_OK:
155
334
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
334
    };
161
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
31
                   std::unique_ptr<RangeGetIterator>& it) {
148
31
    std::unique_ptr<Transaction> txn;
149
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
31
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
31
    switch (txn->get(begin, end, &it, true)) {
154
31
    case TxnErrorCode::TXN_OK:
155
31
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
31
    };
161
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
303
                   std::unique_ptr<RangeGetIterator>& it) {
148
303
    std::unique_ptr<Transaction> txn;
149
303
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
303
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
303
    switch (txn->get(begin, end, &it, true)) {
154
303
    case TxnErrorCode::TXN_OK:
155
303
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
303
    };
161
0
}
162
163
// return 0 for success otherwise error
164
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
6
    std::unique_ptr<Transaction> txn;
166
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
6
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
10
    for (auto k : keys) {
171
10
        txn->remove(k);
172
10
    }
173
6
    switch (txn->commit()) {
174
6
    case TxnErrorCode::TXN_OK:
175
6
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
6
    }
181
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
164
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
1
    std::unique_ptr<Transaction> txn;
166
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
1
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
1
    for (auto k : keys) {
171
1
        txn->remove(k);
172
1
    }
173
1
    switch (txn->commit()) {
174
1
    case TxnErrorCode::TXN_OK:
175
1
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
1
    }
181
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
164
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
5
    std::unique_ptr<Transaction> txn;
166
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
5
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
9
    for (auto k : keys) {
171
9
        txn->remove(k);
172
9
    }
173
5
    switch (txn->commit()) {
174
5
    case TxnErrorCode::TXN_OK:
175
5
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
5
    }
181
5
}
182
183
// return 0 for success otherwise error
184
385
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
385
    std::unique_ptr<Transaction> txn;
186
385
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
385
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
106k
    for (auto& k : keys) {
191
106k
        txn->remove(k);
192
106k
    }
193
385
    switch (txn->commit()) {
194
385
    case TxnErrorCode::TXN_OK:
195
385
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
385
    }
201
385
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
40
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
40
    std::unique_ptr<Transaction> txn;
186
40
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
40
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
40
    for (auto& k : keys) {
191
17
        txn->remove(k);
192
17
    }
193
40
    switch (txn->commit()) {
194
40
    case TxnErrorCode::TXN_OK:
195
40
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
40
    }
201
40
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
345
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
345
    std::unique_ptr<Transaction> txn;
186
345
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
345
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
106k
    for (auto& k : keys) {
191
106k
        txn->remove(k);
192
106k
    }
193
345
    switch (txn->commit()) {
194
345
    case TxnErrorCode::TXN_OK:
195
345
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
345
    }
201
345
}
202
203
// return 0 for success otherwise error
204
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
205
106k
                                       std::string_view end) {
206
106k
    std::unique_ptr<Transaction> txn;
207
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
106k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
106k
    txn->remove(begin, end);
212
106k
    switch (txn->commit()) {
213
106k
    case TxnErrorCode::TXN_OK:
214
106k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
106k
    }
220
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
17
                                       std::string_view end) {
206
17
    std::unique_ptr<Transaction> txn;
207
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
17
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
17
    txn->remove(begin, end);
212
17
    switch (txn->commit()) {
213
17
    case TxnErrorCode::TXN_OK:
214
17
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
17
    }
220
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
106k
                                       std::string_view end) {
206
106k
    std::unique_ptr<Transaction> txn;
207
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
106k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
106k
    txn->remove(begin, end);
212
106k
    switch (txn->commit()) {
213
106k
    case TxnErrorCode::TXN_OK:
214
106k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
106k
    }
220
106k
}
221
222
void scan_restore_job_rowset(
223
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
224
        std::string& msg,
225
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
226
227
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
228
                                      int64_t num_scanned, int64_t num_recycled,
229
52
                                      int64_t start_time) {
230
52
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
231
0
        int64_t cost =
232
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
233
0
        if (cost > config::recycle_task_threshold_seconds) {
234
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
235
0
                    .tag("instance_id", instance_id)
236
0
                    .tag("task", task_name)
237
0
                    .tag("num_scanned", num_scanned)
238
0
                    .tag("num_recycled", num_recycled);
239
0
        }
240
0
    }
241
52
    return;
242
52
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
229
2
                                      int64_t start_time) {
230
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
231
0
        int64_t cost =
232
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
233
0
        if (cost > config::recycle_task_threshold_seconds) {
234
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
235
0
                    .tag("instance_id", instance_id)
236
0
                    .tag("task", task_name)
237
0
                    .tag("num_scanned", num_scanned)
238
0
                    .tag("num_recycled", num_recycled);
239
0
        }
240
0
    }
241
2
    return;
242
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
229
50
                                      int64_t start_time) {
230
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
231
0
        int64_t cost =
232
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
233
0
        if (cost > config::recycle_task_threshold_seconds) {
234
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
235
0
                    .tag("instance_id", instance_id)
236
0
                    .tag("task", task_name)
237
0
                    .tag("num_scanned", num_scanned)
238
0
                    .tag("num_recycled", num_recycled);
239
0
        }
240
0
    }
241
50
    return;
242
50
}
243
244
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
245
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
246
247
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
248
6
                                                               "s3_producer_pool");
249
6
    s3_producer_pool->start();
250
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
251
6
                                                                  "recycle_tablet_pool");
252
6
    recycle_tablet_pool->start();
253
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
254
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
255
6
    group_recycle_function_pool->start();
256
6
    _thread_pool_group =
257
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
258
6
                                    std::move(group_recycle_function_pool));
259
260
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
261
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
262
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
263
6
}
264
265
6
Recycler::~Recycler() {
266
6
    if (!stopped()) {
267
0
        stop();
268
0
    }
269
6
}
270
271
5
void Recycler::instance_scanner_callback() {
272
    // sleep 60 seconds before scheduling for the launch procedure to complete:
273
    // some bad hdfs connection may cause some log to stdout stderr
274
    // which may pollute .out file and affect the script to check success
275
5
    std::this_thread::sleep_for(
276
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
277
1.18k
    while (!stopped()) {
278
1.18k
        if (config::enable_recycler) {
279
4
            std::vector<InstanceInfoPB> instances;
280
4
            get_all_instances(txn_kv_.get(), instances);
281
            // TODO(plat1ko): delete job recycle kv of non-existent instances
282
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
283
4
                std::stringstream ss;
284
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
285
4
                return ss.str();
286
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
282
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
283
4
                std::stringstream ss;
284
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
285
4
                return ss.str();
286
4
            }();
287
4
            if (!instances.empty()) {
288
                // enqueue instances
289
3
                std::lock_guard lock(mtx_);
290
30
                for (auto& instance : instances) {
291
30
                    if (filter_out_instance(instance.instance_id())) continue;
292
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
293
                    // skip instance already in pending queue
294
30
                    if (success) {
295
30
                        pending_instance_queue_.push_back(std::move(instance));
296
30
                    }
297
30
                }
298
3
                pending_instance_cond_.notify_all();
299
3
            }
300
1.17k
        } else {
301
1.17k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
302
1.17k
        }
303
1.18k
        {
304
1.18k
            std::unique_lock lock(mtx_);
305
1.18k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
306
2.36k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
306
2.36k
                               [&]() { return stopped(); });
307
1.18k
        }
308
1.18k
    }
309
5
}
310
311
9
void Recycler::recycle_callback() {
312
40
    while (!stopped()) {
313
37
        InstanceInfoPB instance;
314
37
        {
315
37
            std::unique_lock lock(mtx_);
316
37
            pending_instance_cond_.wait(
317
47
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
317
47
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
318
37
            if (stopped()) {
319
6
                return;
320
6
            }
321
31
            instance = std::move(pending_instance_queue_.front());
322
31
            pending_instance_queue_.pop_front();
323
31
            pending_instance_set_.erase(instance.instance_id());
324
31
        }
325
0
        auto& instance_id = instance.instance_id();
326
31
        {
327
31
            std::lock_guard lock(mtx_);
328
            // skip instance in recycling
329
31
            if (recycling_instance_map_.count(instance_id)) continue;
330
31
        }
331
31
        if (!config::enable_recycler) {
332
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
333
1
                         << " since enable_recycler is false";
334
1
            continue;
335
1
        }
336
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
337
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
338
339
30
        if (int r = instance_recycler->init(); r != 0) {
340
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
341
0
                         << " ret=" << r;
342
0
            continue;
343
0
        }
344
30
        std::string recycle_job_key;
345
30
        job_recycle_key({instance_id}, &recycle_job_key);
346
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
347
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
348
30
        if (ret != 0) { // Prepare failed
349
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
350
20
                         << " ret=" << ret;
351
20
            continue;
352
20
        } else {
353
10
            std::lock_guard lock(mtx_);
354
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
355
10
        }
356
10
        if (stopped()) return;
357
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
358
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
359
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
360
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
361
10
        ret = instance_recycler->do_recycle();
362
        // If instance recycler has been aborted, don't finish this job
363
364
10
        if (!instance_recycler->stopped()) {
365
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
366
10
                                        ret == 0, ctime_ms);
367
10
        }
368
10
        if (instance_recycler->stopped() || ret != 0) {
369
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
370
0
        }
371
10
        {
372
10
            std::lock_guard lock(mtx_);
373
10
            recycling_instance_map_.erase(instance_id);
374
10
        }
375
376
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
377
10
        auto elpased_ms = now - ctime_ms;
378
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
379
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
380
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
381
10
                                             now + config::recycle_interval_seconds * 1000);
382
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
383
10
        LOG(INFO) << "recycle instance done, "
384
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
385
10
                  << " now: " << now;
386
387
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
388
389
10
        LOG_WARNING("finish recycle instance")
390
10
                .tag("instance_id", instance_id)
391
10
                .tag("cost_ms", elpased_ms);
392
10
    }
393
9
}
394
395
4
void Recycler::lease_recycle_jobs() {
396
54
    while (!stopped()) {
397
50
        std::vector<std::string> instances;
398
50
        instances.reserve(recycling_instance_map_.size());
399
50
        {
400
50
            std::lock_guard lock(mtx_);
401
50
            for (auto& [id, _] : recycling_instance_map_) {
402
30
                instances.push_back(id);
403
30
            }
404
50
        }
405
50
        for (auto& i : instances) {
406
30
            std::string recycle_job_key;
407
30
            job_recycle_key({i}, &recycle_job_key);
408
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
409
30
            if (ret == 1) {
410
0
                std::lock_guard lock(mtx_);
411
0
                if (auto it = recycling_instance_map_.find(i);
412
0
                    it != recycling_instance_map_.end()) {
413
0
                    it->second->stop();
414
0
                }
415
0
            }
416
30
        }
417
50
        {
418
50
            std::unique_lock lock(mtx_);
419
50
            notifier_.wait_for(lock,
420
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
421
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
421
100
                               [&]() { return stopped(); });
422
50
        }
423
50
    }
424
4
}
425
426
4
void Recycler::check_recycle_tasks() {
427
7
    while (!stopped()) {
428
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
429
3
        {
430
3
            std::lock_guard lock(mtx_);
431
3
            recycling_instance_map = recycling_instance_map_;
432
3
        }
433
3
        for (auto& entry : recycling_instance_map) {
434
0
            entry.second->check_recycle_tasks();
435
0
        }
436
437
3
        std::unique_lock lock(mtx_);
438
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
439
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
439
6
                           [&]() { return stopped(); });
440
3
    }
441
4
}
442
443
4
int Recycler::start(brpc::Server* server) {
444
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
445
4
    S3Environment::getInstance();
446
447
4
    if (config::enable_checker) {
448
0
        checker_ = std::make_unique<Checker>(txn_kv_);
449
0
        int ret = checker_->start();
450
0
        std::string msg;
451
0
        if (ret != 0) {
452
0
            msg = "failed to start checker";
453
0
            LOG(ERROR) << msg;
454
0
            std::cerr << msg << std::endl;
455
0
            return ret;
456
0
        }
457
0
        msg = "checker started";
458
0
        LOG(INFO) << msg;
459
0
        std::cout << msg << std::endl;
460
0
    }
461
462
4
    if (server) {
463
        // Add service
464
1
        auto recycler_service =
465
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
466
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
467
1
    }
468
469
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
469
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
470
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
471
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
471
8
        workers_.emplace_back([this] { recycle_callback(); });
472
8
    }
473
474
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
475
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
476
477
4
    if (config::enable_snapshot_data_migrator) {
478
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
479
0
        int ret = snapshot_data_migrator_->start();
480
0
        if (ret != 0) {
481
0
            LOG(ERROR) << "failed to start snapshot data migrator";
482
0
            return ret;
483
0
        }
484
0
        LOG(INFO) << "snapshot data migrator started";
485
0
    }
486
487
4
    if (config::enable_snapshot_chain_compactor) {
488
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
489
0
        int ret = snapshot_chain_compactor_->start();
490
0
        if (ret != 0) {
491
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
492
0
            return ret;
493
0
        }
494
0
        LOG(INFO) << "snapshot chain compactor started";
495
0
    }
496
497
4
    return 0;
498
4
}
499
500
4
void Recycler::stop() {
501
4
    stopped_ = true;
502
4
    notifier_.notify_all();
503
4
    pending_instance_cond_.notify_all();
504
4
    {
505
4
        std::lock_guard lock(mtx_);
506
4
        for (auto& [_, recycler] : recycling_instance_map_) {
507
0
            recycler->stop();
508
0
        }
509
4
    }
510
20
    for (auto& w : workers_) {
511
20
        if (w.joinable()) w.join();
512
20
    }
513
4
    if (checker_) {
514
0
        checker_->stop();
515
0
    }
516
4
    if (snapshot_data_migrator_) {
517
0
        snapshot_data_migrator_->stop();
518
0
    }
519
4
    if (snapshot_chain_compactor_) {
520
0
        snapshot_chain_compactor_->stop();
521
0
    }
522
4
}
523
524
class InstanceRecycler::InvertedIndexIdCache {
525
public:
526
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
527
162
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
528
529
    // Return 0 if success, 1 if schema kv not found, negative for error
530
    // For the same index_id, schema_version, res, since `get` is not completely atomic
531
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
532
    // resulting in repeated addition and inaccuracy.
533
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
534
    // repeated addition does not affect correctness.
535
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
536
28.4k
        {
537
28.4k
            std::lock_guard lock(mtx_);
538
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
539
4.67k
                return 0;
540
4.67k
            }
541
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
542
23.7k
                it != inverted_index_id_map_.end()) {
543
18.1k
                res = it->second;
544
18.1k
                return 0;
545
18.1k
            }
546
23.7k
        }
547
        // Get schema from kv
548
        // TODO(plat1ko): Single flight
549
5.54k
        std::unique_ptr<Transaction> txn;
550
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
551
5.54k
        if (err != TxnErrorCode::TXN_OK) {
552
0
            LOG(WARNING) << "failed to create txn, err=" << err;
553
0
            return -1;
554
0
        }
555
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
556
5.54k
        ValueBuf val_buf;
557
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
558
5.54k
        if (err != TxnErrorCode::TXN_OK) {
559
500
            LOG(WARNING) << "failed to get schema, err=" << err;
560
500
            return static_cast<int>(err);
561
500
        }
562
5.04k
        doris::TabletSchemaCloudPB schema;
563
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
564
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
565
0
            return -1;
566
0
        }
567
5.04k
        if (schema.index_size() > 0) {
568
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
569
4.01k
            if (schema.has_inverted_index_storage_format()) {
570
4.00k
                index_format = schema.inverted_index_storage_format();
571
4.00k
            }
572
4.01k
            res.first = index_format;
573
4.01k
            res.second.reserve(schema.index_size());
574
10.0k
            for (auto& i : schema.index()) {
575
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
576
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
577
10.0k
                }
578
10.0k
            }
579
4.01k
        }
580
5.04k
        insert(index_id, schema_version, res);
581
5.04k
        return 0;
582
5.04k
    }
583
584
    // Empty `ids` means this schema has no inverted index
585
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
586
5.04k
        if (index_info.second.empty()) {
587
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
588
1.02k
            std::lock_guard lock(mtx_);
589
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
590
4.01k
        } else {
591
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
592
4.01k
            std::lock_guard lock(mtx_);
593
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
594
4.01k
        }
595
5.04k
    }
596
597
private:
598
    std::string instance_id_;
599
    std::shared_ptr<TxnKv> txn_kv_;
600
601
    std::mutex mtx_;
602
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
603
    struct HashOfKey {
604
57.1k
        size_t operator()(const Key& key) const {
605
57.1k
            size_t seed = 0;
606
57.1k
            seed = std::hash<int64_t> {}(key.first);
607
57.1k
            seed = std::hash<int32_t> {}(key.second);
608
57.1k
            return seed;
609
57.1k
        }
610
    };
611
    // <index_id, schema_version> -> inverted_index_ids
612
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
613
    // Store <index_id, schema_version> of schema which doesn't have inverted index
614
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
615
};
616
617
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
618
                                   RecyclerThreadPoolGroup thread_pool_group,
619
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
620
162
        : txn_kv_(std::move(txn_kv)),
621
162
          instance_id_(instance.instance_id()),
622
162
          instance_info_(instance),
623
162
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
624
162
          _thread_pool_group(std::move(thread_pool_group)),
625
162
          txn_lazy_committer_(std::move(txn_lazy_committer)),
626
162
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
627
162
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
628
162
    delete_bitmap_lock_white_list_->init();
629
162
    resource_mgr_->init();
630
631
162
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
632
633
    // Since the recycler's resource manager could not be notified when instance info changes,
634
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
635
162
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
636
162
};
637
638
162
InstanceRecycler::~InstanceRecycler() = default;
639
640
140
int InstanceRecycler::init_obj_store_accessors() {
641
140
    for (const auto& obj_info : instance_info_.obj_info()) {
642
98
#ifdef UNIT_TEST
643
98
        auto accessor = std::make_shared<MockAccessor>();
644
#else
645
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
646
        if (!s3_conf) {
647
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
648
            return -1;
649
        }
650
651
        std::shared_ptr<S3Accessor> accessor;
652
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
653
        if (ret != 0) {
654
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
655
                         << " resource_id=" << obj_info.id();
656
            return ret;
657
        }
658
#endif
659
98
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
660
98
    }
661
662
140
    return 0;
663
140
}
664
665
140
int InstanceRecycler::init_storage_vault_accessors() {
666
140
    if (instance_info_.resource_ids().empty()) {
667
133
        return 0;
668
133
    }
669
670
7
    FullRangeGetOptions opts(txn_kv_);
671
7
    opts.prefetch = true;
672
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
673
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
674
675
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
676
18
        auto [k, v] = *kv;
677
18
        StorageVaultPB vault;
678
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
679
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
680
0
            return -1;
681
0
        }
682
18
        std::string recycler_storage_vault_white_list = accumulate(
683
18
                config::recycler_storage_vault_white_list.begin(),
684
18
                config::recycler_storage_vault_white_list.end(), std::string(),
685
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
685
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
686
18
        LOG_INFO("config::recycler_storage_vault_white_list")
687
18
                .tag("", recycler_storage_vault_white_list);
688
18
        if (!config::recycler_storage_vault_white_list.empty()) {
689
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
690
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
691
8
                it == config::recycler_storage_vault_white_list.end()) {
692
2
                LOG_WARNING(
693
2
                        "failed to init accessor for vault because this vault is not in "
694
2
                        "config::recycler_storage_vault_white_list. ")
695
2
                        .tag(" vault name:", vault.name())
696
2
                        .tag(" config::recycler_storage_vault_white_list:",
697
2
                             recycler_storage_vault_white_list);
698
2
                continue;
699
2
            }
700
8
        }
701
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
702
16
                                 &accessor_map_, &vault);
703
16
        if (vault.has_hdfs_info()) {
704
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
705
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
706
9
            int ret = accessor->init();
707
9
            if (ret != 0) {
708
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
709
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
710
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
711
4
                continue;
712
4
            }
713
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
714
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
715
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
716
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
717
#else
718
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
719
                       << "but HDFS storage vaults were detected";
720
#endif
721
7
        } else if (vault.has_obj_info()) {
722
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
723
7
            if (!s3_conf) {
724
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
725
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
726
1
                continue;
727
1
            }
728
729
6
            std::shared_ptr<S3Accessor> accessor;
730
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
731
6
            if (ret != 0) {
732
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
733
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
734
0
                             << " ret=" << ret
735
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
736
0
                continue;
737
0
            }
738
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
739
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
740
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
741
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
742
6
        }
743
16
    }
744
745
7
    if (!it->is_valid()) {
746
0
        LOG_WARNING("failed to get storage vault kv");
747
0
        return -1;
748
0
    }
749
750
7
    if (accessor_map_.empty()) {
751
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
752
1
        return -2;
753
1
    }
754
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
755
6
             instance_id_);
756
757
6
    return 0;
758
7
}
759
760
141
int InstanceRecycler::init() {
761
141
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
762
141
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
763
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
764
1
        return 0;
765
1
    }
766
767
140
    int ret = init_obj_store_accessors();
768
140
    if (ret != 0) {
769
0
        return ret;
770
0
    }
771
772
140
    return init_storage_vault_accessors();
773
140
}
774
775
template <typename... Func>
776
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
120
    return [funcs...]() {
778
120
        return [](std::initializer_list<int> ret_vals) {
779
120
            int i = 0;
780
140
            for (int ret : ret_vals) {
781
140
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
140
            }
785
120
            return i;
786
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
20
            for (int ret : ret_vals) {
781
20
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
20
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
20
            for (int ret : ret_vals) {
781
20
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
20
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
789
790
11
int InstanceRecycler::do_recycle() {
791
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
792
11
    tablet_metrics_context_.reset();
793
11
    segment_metrics_context_.reset();
794
11
    DORIS_CLOUD_DEFER {
795
11
        tablet_metrics_context_.finish_report();
796
11
        segment_metrics_context_.finish_report();
797
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
794
11
    DORIS_CLOUD_DEFER {
795
11
        tablet_metrics_context_.finish_report();
796
11
        segment_metrics_context_.finish_report();
797
11
    };
798
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
799
1
        int res = recycle_cluster_snapshots();
800
1
        if (res != 0) {
801
0
            return -1;
802
0
        }
803
1
        return recycle_deleted_instance();
804
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
805
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
806
10
                                        fmt::format("instance id {}", instance_id_),
807
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
807
120
                                        [](int r) { return r != 0; });
808
10
        sync_executor
809
10
                .add(task_wrapper(
810
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
810
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
811
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
811
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
812
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
813
                                   // becase they may both recycle the same set of tablets
814
                        // recycle dropped table or idexes(mv, rollup)
815
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
815
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
816
                        // recycle dropped partitions
817
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
817
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
818
10
                .add(task_wrapper(
819
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
819
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
820
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
820
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
822
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
823
10
                .add(task_wrapper(
824
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
824
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
825
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
825
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
826
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
826
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
827
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
827
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
828
10
                .add(task_wrapper(
829
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
829
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
831
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
831
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
832
10
        bool finished = true;
833
10
        std::vector<int> rets = sync_executor.when_all(&finished);
834
120
        for (int ret : rets) {
835
120
            if (ret != 0) {
836
0
                return ret;
837
0
            }
838
120
        }
839
10
        return finished ? 0 : -1;
840
10
    } else {
841
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
842
0
                     << " instance_id=" << instance_id_;
843
0
        return -1;
844
0
    }
845
11
}
846
847
/**
848
* 1. delete all remote data
849
* 2. delete all kv
850
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
851
*/
852
13
int InstanceRecycler::recycle_deleted_instance() {
853
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
854
855
13
    int ret = 0;
856
13
    auto start_time = steady_clock::now();
857
13
    const auto recycle_state = instance_info_.recycle_state();
858
859
13
    if (config::retain_deleted_instance_tombstone &&
860
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
861
4
        return 0;
862
4
    }
863
864
9
    DORIS_CLOUD_DEFER {
865
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
866
9
        if (ret != 0) {
867
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
868
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
869
0
                         << "s, instance_id=" << instance_id_;
870
9
        } else if (recycle_state ==
871
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
872
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
873
0
                      << "s, instance_id=" << instance_id_;
874
9
        } else {
875
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
876
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
877
9
                      << "s, instance_id=" << instance_id_;
878
9
        }
879
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
864
9
    DORIS_CLOUD_DEFER {
865
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
866
9
        if (ret != 0) {
867
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
868
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
869
0
                         << "s, instance_id=" << instance_id_;
870
9
        } else if (recycle_state ==
871
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
872
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
873
0
                      << "s, instance_id=" << instance_id_;
874
9
        } else {
875
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
876
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
877
9
                      << "s, instance_id=" << instance_id_;
878
9
        }
879
9
    };
880
881
9
    switch (recycle_state) {
882
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
883
6
        ret = recycle_deleted_instance_data();
884
6
        break;
885
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
886
3
        ret = recycle_deleted_instance_metadata();
887
3
        break;
888
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
889
0
        ret = remove_instance_key();
890
0
        break;
891
0
    default:
892
0
        LOG_WARNING("invalid instance recycle state")
893
0
                .tag("instance_id", instance_id_)
894
0
                .tag("recycle_state", instance_info_.recycle_state());
895
0
        ret = -1;
896
0
        break;
897
9
    }
898
899
9
    return ret;
900
9
}
901
902
6
int InstanceRecycler::recycle_deleted_instance_data() {
903
6
    int ret = 0;
904
905
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
906
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
907
6
        int res = recycle_tmp_rowsets();
908
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
909
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
910
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
911
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
912
            // and cannot be recycled.
913
0
            res = recycle_tmp_rowsets();
914
0
        }
915
6
        return res;
916
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
906
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
907
6
        int res = recycle_tmp_rowsets();
908
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
909
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
910
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
911
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
912
            // and cannot be recycled.
913
0
            res = recycle_tmp_rowsets();
914
0
        }
915
6
        return res;
916
6
    };
917
918
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
919
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
920
0
        return -1;
921
0
    }
922
923
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
924
6
    if (recycle_versioned_rowsets() != 0) {
925
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
926
0
        return -1;
927
0
    }
928
929
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
930
6
    if (recycle_operation_logs() != 0) {
931
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
932
0
        return -1;
933
0
    }
934
935
    // Step 4: Check if there are still cluster snapshots
936
6
    bool has_snapshots = false;
937
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
938
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
939
0
        return -1;
940
6
    } else if (has_snapshots) {
941
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
942
1
        return 0;
943
1
    }
944
945
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
946
5
                            instance_info().snapshot_switch_status() !=
947
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
948
5
    if (snapshot_enabled) {
949
1
        bool has_unrecycled_rowsets = false;
950
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
951
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
952
0
            return -1;
953
1
        } else if (has_unrecycled_rowsets) {
954
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
955
0
                    .tag("instance_id", instance_id_);
956
0
            return ret;
957
0
        }
958
4
    } else { // delete all remote data if snapshot is disabled
959
4
        for (auto& [_, accessor] : accessor_map_) {
960
4
            if (stopped()) {
961
0
                return ret;
962
0
            }
963
964
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
965
4
            int del_ret = accessor->delete_all();
966
4
            if (del_ret == 0) {
967
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
968
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
969
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
970
                // so the recycling has been successful.
971
0
                ret = -1;
972
0
            }
973
4
        }
974
975
4
        if (ret != 0) {
976
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
977
0
            return ret;
978
0
        }
979
4
    }
980
981
5
    if (update_instance_recycle_state(
982
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
983
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
984
0
        return -1;
985
0
    }
986
987
5
    return 0;
988
5
}
989
990
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
991
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
992
7
    if (instance_info_.has_successor_instance_id() &&
993
7
        !instance_info_.successor_instance_id().empty()) {
994
4
        std::string key = instance_key(instance_info_.successor_instance_id());
995
4
        std::unique_ptr<Transaction> txn;
996
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
997
4
        if (err != TxnErrorCode::TXN_OK) {
998
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
999
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1000
0
                         << " err=" << err;
1001
0
            return -1;
1002
0
        }
1003
1004
4
        InstanceInfoPB successor_instance;
1005
4
        std::string value;
1006
4
        err = txn->get(key, &value);
1007
4
        if (err == TxnErrorCode::TXN_OK) {
1008
3
            InstanceInfoPB successor_instance;
1009
3
            if (!successor_instance.ParseFromString(value)) {
1010
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1011
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1012
0
                return -1;
1013
0
            }
1014
3
            if (!successor_instance.has_recycle_state() ||
1015
3
                successor_instance.recycle_state() !=
1016
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1017
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1018
2
                          << " instance_id=" << instance_id_
1019
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1020
2
                          << " successor_status=" << successor_instance.status()
1021
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1022
2
                return 0;
1023
2
            }
1024
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1025
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1026
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1027
0
                         << " err=" << err;
1028
0
            return -1;
1029
0
        }
1030
4
    }
1031
1032
    // delete all kv
1033
5
    std::unique_ptr<Transaction> txn;
1034
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1035
5
    if (err != TxnErrorCode::TXN_OK) {
1036
0
        LOG(WARNING) << "failed to create txn";
1037
0
        return -1;
1038
0
    }
1039
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1040
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1041
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1042
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1043
5
    txn->remove(start_txn_key, end_txn_key);
1044
5
    std::string start_version_key = version_key_prefix(instance_id_);
1045
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1046
5
    txn->remove(start_version_key, end_version_key);
1047
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1048
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1049
5
    txn->remove(start_meta_key, end_meta_key);
1050
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1051
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1052
5
    txn->remove(start_recycle_key, end_recycle_key);
1053
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1054
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1055
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1056
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1057
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1058
5
    txn->remove(start_copy_key, end_copy_key);
1059
    // should not remove job key range, because we need to reserve job recycle kv
1060
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1061
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1062
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1063
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1064
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1065
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1066
5
    std::string start_vault_key = storage_vault_key(key_info0);
1067
5
    std::string end_vault_key = storage_vault_key(key_info1);
1068
5
    txn->remove(start_vault_key, end_vault_key);
1069
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1070
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1071
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1072
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1073
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1074
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1075
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1076
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1077
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1078
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1079
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1080
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1081
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1082
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1083
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1084
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1085
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1086
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1087
1088
    // Updating the recycle state also commits this transaction, making the metadata deletions
1089
    // and state transition atomic.
1090
5
    if (update_instance_recycle_state(
1091
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1092
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1093
0
        return -1;
1094
0
    }
1095
1096
5
    return 0;
1097
5
}
1098
1099
0
int InstanceRecycler::remove_instance_key() {
1100
0
    std::unique_ptr<Transaction> txn;
1101
0
    std::string key = instance_key(instance_info_.instance_id());
1102
0
    std::string value;
1103
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1104
0
    if (err != TxnErrorCode::TXN_OK) {
1105
0
        LOG(WARNING) << "failed to create txn";
1106
0
        return -1;
1107
0
    }
1108
1109
0
    err = txn->get(key, &value);
1110
0
    if (err != TxnErrorCode::TXN_OK) {
1111
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1112
0
                     << ", err=" << err;
1113
0
        return -1;
1114
0
    }
1115
1116
0
    InstanceInfoPB instance;
1117
0
    if (!instance.ParseFromString(value)) {
1118
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1119
0
        return -1;
1120
0
    }
1121
1122
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1123
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1124
0
                     << instance_id_ << ", status=" << instance.status();
1125
0
        return -1;
1126
0
    }
1127
1128
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1129
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1130
0
                     << instance_id_
1131
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1132
0
                     << ", expected_state="
1133
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1134
0
        return -1;
1135
0
    }
1136
1137
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1138
0
    txn->remove(key);
1139
0
    err = txn->commit();
1140
0
    if (err != TxnErrorCode::TXN_OK) {
1141
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1142
0
                     << " err=" << err;
1143
0
        return -1;
1144
0
    }
1145
0
    return 0;
1146
0
}
1147
1148
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1149
7
                                                    InstanceRecycleState target_state) {
1150
7
    std::unique_ptr<Transaction> txn;
1151
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1152
7
    if (err != TxnErrorCode::TXN_OK) {
1153
0
        LOG(WARNING) << "failed to create txn";
1154
0
        return -1;
1155
0
    }
1156
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1157
7
}
1158
1159
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1160
                                                    InstanceRecycleState target_state,
1161
12
                                                    Transaction* txn) {
1162
12
    const bool valid_transition =
1163
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1164
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1165
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1166
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1167
1168
12
    if (!valid_transition) {
1169
1
        LOG_WARNING("invalid instance recycled state transition")
1170
1
                .tag("instance_id", instance_id_)
1171
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1172
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1173
1
        return -1;
1174
1
    }
1175
1176
11
    std::string key = instance_key({instance_id_});
1177
11
    std::string value;
1178
11
    TxnErrorCode err = txn->get(key, &value);
1179
11
    if (err != TxnErrorCode::TXN_OK) {
1180
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1181
0
                .tag("instance_id", instance_id_)
1182
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1183
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1184
0
                .tag("err", err);
1185
0
        return -1;
1186
0
    }
1187
1188
11
    InstanceInfoPB instance;
1189
11
    if (!instance.ParseFromString(value)) {
1190
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1191
0
                .tag("instance_id", instance_id_)
1192
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1193
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1194
0
        return -1;
1195
0
    }
1196
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1197
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1198
0
                .tag("instance_id", instance_id_)
1199
0
                .tag("status", instance.status())
1200
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1201
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1202
0
        return -1;
1203
0
    }
1204
11
    if (instance.recycle_state() != current_state) {
1205
1
        LOG_WARNING("instance recycled state changed before update")
1206
1
                .tag("instance_id", instance_id_)
1207
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1208
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1209
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1210
1
        return -1;
1211
1
    }
1212
1213
10
    instance.set_recycle_state(target_state);
1214
10
    instance.set_recycle_state_update_time_ms(
1215
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1216
10
    if (!instance.SerializeToString(&value)) {
1217
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1218
0
                .tag("instance_id", instance_id_)
1219
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1220
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1221
0
        return -1;
1222
0
    }
1223
1224
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1225
10
    txn->put(key, value);
1226
10
    err = txn->commit();
1227
10
    if (err != TxnErrorCode::TXN_OK) {
1228
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1229
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1230
0
        return -1;
1231
0
    }
1232
1233
10
    instance_info_.Swap(&instance);
1234
10
    LOG_INFO("updated instance recycled state")
1235
10
            .tag("instance_id", instance_id_)
1236
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1237
10
    return 0;
1238
10
}
1239
1240
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1241
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1242
9
    if (exists == nullptr) {
1243
0
        return -1;
1244
0
    }
1245
9
    *exists = false;
1246
1247
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1248
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1249
9
    std::string scan_begin = begin;
1250
1251
9
    while (true) {
1252
9
        std::unique_ptr<RangeGetIterator> it_range;
1253
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1254
9
        if (get_ret < 0) {
1255
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1256
0
                    .tag("instance_id", instance_id_)
1257
0
                    .tag("tablet_id", tablet_id)
1258
0
                    .tag("ret", get_ret);
1259
0
            return -1;
1260
0
        }
1261
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1262
6
            return 0;
1263
6
        }
1264
1265
3
        std::string last_key;
1266
3
        while (it_range->has_next()) {
1267
3
            auto [k, v] = it_range->next();
1268
3
            last_key.assign(k.data(), k.size());
1269
3
            doris::RowsetMetaCloudPB rowset_meta;
1270
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1271
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1272
0
                        .tag("instance_id", instance_id_)
1273
0
                        .tag("tablet_id", tablet_id)
1274
0
                        .tag("key", hex(k));
1275
0
                continue;
1276
0
            }
1277
3
            if (stats) {
1278
3
                ++stats->rowset_scan_count;
1279
3
            }
1280
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1281
3
                *exists = true;
1282
3
                return 0;
1283
3
            }
1284
3
        }
1285
1286
0
        if (!it_range->more()) {
1287
0
            return 0;
1288
0
        }
1289
1290
        // Continue scanning from the next key to keep each transaction short.
1291
0
        scan_begin = std::move(last_key);
1292
0
        scan_begin.push_back('\x00');
1293
0
    }
1294
9
}
1295
1296
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1297
                                                          const std::string& rowset_id,
1298
                                                          int64_t txn_id, bool* recycle_exists,
1299
11
                                                          bool* tmp_exists) {
1300
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1301
0
        return -1;
1302
0
    }
1303
11
    *recycle_exists = false;
1304
11
    *tmp_exists = false;
1305
1306
11
    if (txn_id <= 0) {
1307
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1308
0
                .tag("instance_id", instance_id_)
1309
0
                .tag("tablet_id", tablet_id)
1310
0
                .tag("rowset_id", rowset_id)
1311
0
                .tag("txn_id", txn_id);
1312
0
        return -1;
1313
0
    }
1314
1315
11
    std::unique_ptr<Transaction> txn;
1316
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1317
11
    if (err != TxnErrorCode::TXN_OK) {
1318
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1319
0
                .tag("instance_id", instance_id_)
1320
0
                .tag("tablet_id", tablet_id)
1321
0
                .tag("rowset_id", rowset_id)
1322
0
                .tag("txn_id", txn_id)
1323
0
                .tag("err", err);
1324
0
        return -1;
1325
0
    }
1326
1327
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1328
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1329
11
    if (ret == TxnErrorCode::TXN_OK) {
1330
1
        *recycle_exists = true;
1331
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1332
0
        LOG_WARNING("failed to check recycle rowset existence")
1333
0
                .tag("instance_id", instance_id_)
1334
0
                .tag("tablet_id", tablet_id)
1335
0
                .tag("rowset_id", rowset_id)
1336
0
                .tag("key", hex(recycle_key))
1337
0
                .tag("err", ret);
1338
0
        return -1;
1339
0
    }
1340
1341
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1342
11
    ret = key_exists(txn.get(), tmp_key, true);
1343
11
    if (ret == TxnErrorCode::TXN_OK) {
1344
1
        *tmp_exists = true;
1345
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1346
0
        LOG_WARNING("failed to check tmp rowset existence")
1347
0
                .tag("instance_id", instance_id_)
1348
0
                .tag("tablet_id", tablet_id)
1349
0
                .tag("txn_id", txn_id)
1350
0
                .tag("key", hex(tmp_key))
1351
0
                .tag("err", ret);
1352
0
        return -1;
1353
0
    }
1354
1355
11
    return 0;
1356
11
}
1357
1358
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1359
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1360
8
    if (!hint.empty()) {
1361
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1362
8
            return {hint, it->second};
1363
8
        }
1364
8
    }
1365
1366
0
    return {"", nullptr};
1367
8
}
1368
1369
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1370
                                               const std::string& packed_file_path,
1371
3
                                               PackedFileRecycleStats* stats) {
1372
3
    bool local_changed = false;
1373
3
    int64_t left_num = 0;
1374
3
    int64_t left_bytes = 0;
1375
3
    bool all_small_files_confirmed = true;
1376
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1377
1378
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1379
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1380
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1381
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1382
14
        LOG_INFO("packed slice correction status")
1383
14
                .tag("instance_id", instance_id_)
1384
14
                .tag("packed_file_path", packed_file_path)
1385
14
                .tag("small_file_path", file.path())
1386
14
                .tag("tablet_id", tablet_id)
1387
14
                .tag("rowset_id", rowset_id)
1388
14
                .tag("txn_id", txn_id)
1389
14
                .tag("size", file.size())
1390
14
                .tag("deleted", file.deleted())
1391
14
                .tag("corrected", file.corrected())
1392
14
                .tag("confirmed_this_round", confirmed_this_round);
1393
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1378
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1379
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1380
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1381
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1382
        LOG_INFO("packed slice correction status")
1383
14
                .tag("instance_id", instance_id_)
1384
14
                .tag("packed_file_path", packed_file_path)
1385
14
                .tag("small_file_path", file.path())
1386
14
                .tag("tablet_id", tablet_id)
1387
14
                .tag("rowset_id", rowset_id)
1388
14
                .tag("txn_id", txn_id)
1389
14
                .tag("size", file.size())
1390
14
                .tag("deleted", file.deleted())
1391
14
                .tag("corrected", file.corrected())
1392
14
                .tag("confirmed_this_round", confirmed_this_round);
1393
14
    };
1394
1395
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1396
14
        auto* small_file = packed_info->mutable_slices(i);
1397
14
        if (small_file->deleted()) {
1398
3
            log_small_file_status(*small_file, small_file->corrected());
1399
3
            continue;
1400
3
        }
1401
1402
11
        if (small_file->corrected()) {
1403
0
            left_num++;
1404
0
            left_bytes += small_file->size();
1405
0
            log_small_file_status(*small_file, true);
1406
0
            continue;
1407
0
        }
1408
1409
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1410
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1411
0
                    .tag("instance_id", instance_id_)
1412
0
                    .tag("small_file_path", small_file->path())
1413
0
                    .tag("index", i);
1414
0
            return -1;
1415
0
        }
1416
1417
11
        int64_t tablet_id = small_file->tablet_id();
1418
11
        const std::string& rowset_id = small_file->rowset_id();
1419
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1420
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1421
0
                    .tag("instance_id", instance_id_)
1422
0
                    .tag("small_file_path", small_file->path())
1423
0
                    .tag("index", i)
1424
0
                    .tag("tablet_id", tablet_id)
1425
0
                    .tag("rowset_id", rowset_id)
1426
0
                    .tag("has_txn_id", small_file->has_txn_id())
1427
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1428
0
            return -1;
1429
0
        }
1430
11
        int64_t txn_id = small_file->txn_id();
1431
11
        bool recycle_exists = false;
1432
11
        bool tmp_exists = false;
1433
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1434
11
                                                &tmp_exists) != 0) {
1435
0
            return -1;
1436
0
        }
1437
1438
11
        bool small_file_confirmed = false;
1439
11
        if (tmp_exists) {
1440
1
            left_num++;
1441
1
            left_bytes += small_file->size();
1442
1
            small_file_confirmed = true;
1443
10
        } else if (recycle_exists) {
1444
1
            left_num++;
1445
1
            left_bytes += small_file->size();
1446
            // keep small_file_confirmed=false so the packed file remains uncorrected
1447
9
        } else {
1448
9
            bool rowset_exists = false;
1449
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1450
0
                return -1;
1451
0
            }
1452
1453
9
            if (!rowset_exists) {
1454
6
                if (!small_file->deleted()) {
1455
6
                    small_file->set_deleted(true);
1456
6
                    local_changed = true;
1457
6
                }
1458
6
                if (!small_file->corrected()) {
1459
6
                    small_file->set_corrected(true);
1460
6
                    local_changed = true;
1461
6
                }
1462
6
                small_file_confirmed = true;
1463
6
            } else {
1464
3
                left_num++;
1465
3
                left_bytes += small_file->size();
1466
3
                small_file_confirmed = true;
1467
3
            }
1468
9
        }
1469
1470
11
        if (!small_file_confirmed) {
1471
1
            all_small_files_confirmed = false;
1472
1
        }
1473
1474
11
        if (small_file->corrected() != small_file_confirmed) {
1475
4
            small_file->set_corrected(small_file_confirmed);
1476
4
            local_changed = true;
1477
4
        }
1478
1479
11
        log_small_file_status(*small_file, small_file_confirmed);
1480
11
    }
1481
1482
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1483
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1484
3
        local_changed = true;
1485
3
    }
1486
3
    if (packed_info->ref_cnt() != left_num) {
1487
3
        auto old_ref_cnt = packed_info->ref_cnt();
1488
3
        packed_info->set_ref_cnt(left_num);
1489
3
        LOG_INFO("corrected packed file ref count")
1490
3
                .tag("instance_id", instance_id_)
1491
3
                .tag("resource_id", packed_info->resource_id())
1492
3
                .tag("packed_file_path", packed_file_path)
1493
3
                .tag("old_ref_cnt", old_ref_cnt)
1494
3
                .tag("new_ref_cnt", left_num);
1495
3
        local_changed = true;
1496
3
    }
1497
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1498
2
        packed_info->set_corrected(all_small_files_confirmed);
1499
2
        local_changed = true;
1500
2
    }
1501
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1502
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1503
1
        local_changed = true;
1504
1
    }
1505
1506
3
    if (changed != nullptr) {
1507
3
        *changed = local_changed;
1508
3
    }
1509
3
    return 0;
1510
3
}
1511
1512
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1513
                                                 const std::string& packed_file_path,
1514
4
                                                 PackedFileRecycleStats* stats) {
1515
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1516
4
    bool correction_ok = false;
1517
4
    cloud::PackedFileInfoPB packed_info;
1518
1519
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1520
4
        if (stopped()) {
1521
0
            LOG_WARNING("recycler stopped before processing packed file")
1522
0
                    .tag("instance_id", instance_id_)
1523
0
                    .tag("packed_file_path", packed_file_path)
1524
0
                    .tag("attempt", attempt);
1525
0
            return -1;
1526
0
        }
1527
1528
4
        std::unique_ptr<Transaction> txn;
1529
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1530
4
        if (err != TxnErrorCode::TXN_OK) {
1531
0
            LOG_WARNING("failed to create txn when processing packed file")
1532
0
                    .tag("instance_id", instance_id_)
1533
0
                    .tag("packed_file_path", packed_file_path)
1534
0
                    .tag("attempt", attempt)
1535
0
                    .tag("err", err);
1536
0
            return -1;
1537
0
        }
1538
1539
4
        std::string packed_val;
1540
4
        err = txn->get(packed_key, &packed_val);
1541
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1542
0
            return 0;
1543
0
        }
1544
4
        if (err != TxnErrorCode::TXN_OK) {
1545
0
            LOG_WARNING("failed to get packed file kv")
1546
0
                    .tag("instance_id", instance_id_)
1547
0
                    .tag("packed_file_path", packed_file_path)
1548
0
                    .tag("attempt", attempt)
1549
0
                    .tag("err", err);
1550
0
            return -1;
1551
0
        }
1552
1553
4
        if (!packed_info.ParseFromString(packed_val)) {
1554
0
            LOG_WARNING("failed to parse packed file info")
1555
0
                    .tag("instance_id", instance_id_)
1556
0
                    .tag("packed_file_path", packed_file_path)
1557
0
                    .tag("attempt", attempt);
1558
0
            return -1;
1559
0
        }
1560
1561
4
        int64_t now_sec = ::time(nullptr);
1562
4
        bool corrected = packed_info.corrected();
1563
4
        bool due = config::force_immediate_recycle ||
1564
4
                   now_sec - packed_info.created_at_sec() >=
1565
4
                           config::packed_file_correction_delay_seconds;
1566
1567
4
        if (!corrected && due) {
1568
3
            bool changed = false;
1569
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1570
0
                LOG_WARNING("correct_packed_file_info failed")
1571
0
                        .tag("instance_id", instance_id_)
1572
0
                        .tag("packed_file_path", packed_file_path)
1573
0
                        .tag("attempt", attempt);
1574
0
                return -1;
1575
0
            }
1576
3
            if (changed) {
1577
3
                std::string updated;
1578
3
                if (!packed_info.SerializeToString(&updated)) {
1579
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1580
0
                            .tag("instance_id", instance_id_)
1581
0
                            .tag("packed_file_path", packed_file_path)
1582
0
                            .tag("attempt", attempt);
1583
0
                    return -1;
1584
0
                }
1585
3
                txn->put(packed_key, updated);
1586
3
                err = txn->commit();
1587
3
                if (err == TxnErrorCode::TXN_OK) {
1588
3
                    if (stats) {
1589
3
                        ++stats->num_corrected;
1590
3
                    }
1591
3
                } else {
1592
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1593
0
                        LOG_WARNING(
1594
0
                                "failed to commit correction for packed file due to conflict, "
1595
0
                                "retrying")
1596
0
                                .tag("instance_id", instance_id_)
1597
0
                                .tag("packed_file_path", packed_file_path)
1598
0
                                .tag("attempt", attempt);
1599
0
                        sleep_for_packed_file_retry();
1600
0
                        packed_info.Clear();
1601
0
                        continue;
1602
0
                    }
1603
0
                    LOG_WARNING("failed to commit correction for packed file")
1604
0
                            .tag("instance_id", instance_id_)
1605
0
                            .tag("packed_file_path", packed_file_path)
1606
0
                            .tag("attempt", attempt)
1607
0
                            .tag("err", err);
1608
0
                    return -1;
1609
0
                }
1610
3
            }
1611
3
        }
1612
1613
4
        correction_ok = true;
1614
4
        break;
1615
4
    }
1616
1617
4
    if (!correction_ok) {
1618
0
        return -1;
1619
0
    }
1620
1621
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1622
4
          packed_info.ref_cnt() == 0)) {
1623
3
        return 0;
1624
3
    }
1625
1626
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1627
0
        LOG_WARNING("packed file missing resource id when recycling")
1628
0
                .tag("instance_id", instance_id_)
1629
0
                .tag("packed_file_path", packed_file_path);
1630
0
        return -1;
1631
0
    }
1632
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1633
1
    if (!accessor) {
1634
0
        LOG_WARNING("no accessor available to delete packed file")
1635
0
                .tag("instance_id", instance_id_)
1636
0
                .tag("packed_file_path", packed_file_path)
1637
0
                .tag("resource_id", packed_info.resource_id());
1638
0
        return -1;
1639
0
    }
1640
1
    int del_ret = accessor->delete_file(packed_file_path);
1641
1
    if (del_ret != 0 && del_ret != 1) {
1642
0
        LOG_WARNING("failed to delete packed file")
1643
0
                .tag("instance_id", instance_id_)
1644
0
                .tag("packed_file_path", packed_file_path)
1645
0
                .tag("resource_id", resource_id)
1646
0
                .tag("ret", del_ret);
1647
0
        return -1;
1648
0
    }
1649
1
    if (del_ret == 1) {
1650
0
        LOG_INFO("packed file already removed")
1651
0
                .tag("instance_id", instance_id_)
1652
0
                .tag("packed_file_path", packed_file_path)
1653
0
                .tag("resource_id", resource_id);
1654
1
    } else {
1655
1
        LOG_INFO("deleted packed file")
1656
1
                .tag("instance_id", instance_id_)
1657
1
                .tag("packed_file_path", packed_file_path)
1658
1
                .tag("resource_id", resource_id);
1659
1
    }
1660
1661
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1662
1
        std::unique_ptr<Transaction> del_txn;
1663
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1664
1
        if (err != TxnErrorCode::TXN_OK) {
1665
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1666
0
                    .tag("instance_id", instance_id_)
1667
0
                    .tag("packed_file_path", packed_file_path)
1668
0
                    .tag("del_attempt", del_attempt)
1669
0
                    .tag("err", err);
1670
0
            return -1;
1671
0
        }
1672
1673
1
        std::string latest_val;
1674
1
        err = del_txn->get(packed_key, &latest_val);
1675
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1676
0
            return 0;
1677
0
        }
1678
1
        if (err != TxnErrorCode::TXN_OK) {
1679
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1680
0
                    .tag("instance_id", instance_id_)
1681
0
                    .tag("packed_file_path", packed_file_path)
1682
0
                    .tag("del_attempt", del_attempt)
1683
0
                    .tag("err", err);
1684
0
            return -1;
1685
0
        }
1686
1687
1
        cloud::PackedFileInfoPB latest_info;
1688
1
        if (!latest_info.ParseFromString(latest_val)) {
1689
0
            LOG_WARNING("failed to parse packed file info before removal")
1690
0
                    .tag("instance_id", instance_id_)
1691
0
                    .tag("packed_file_path", packed_file_path)
1692
0
                    .tag("del_attempt", del_attempt);
1693
0
            return -1;
1694
0
        }
1695
1696
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1697
1
              latest_info.ref_cnt() == 0)) {
1698
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1699
0
                    .tag("instance_id", instance_id_)
1700
0
                    .tag("packed_file_path", packed_file_path)
1701
0
                    .tag("del_attempt", del_attempt);
1702
0
            return 0;
1703
0
        }
1704
1705
1
        del_txn->remove(packed_key);
1706
1
        err = del_txn->commit();
1707
1
        if (err == TxnErrorCode::TXN_OK) {
1708
1
            if (stats) {
1709
1
                ++stats->num_deleted;
1710
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1711
1
                                        static_cast<int64_t>(latest_val.size());
1712
1
                if (del_ret == 0 || del_ret == 1) {
1713
1
                    ++stats->num_object_deleted;
1714
1
                    int64_t object_size = latest_info.total_slice_bytes();
1715
1
                    if (object_size <= 0) {
1716
0
                        object_size = packed_info.total_slice_bytes();
1717
0
                    }
1718
1
                    stats->bytes_object_deleted += object_size;
1719
1
                }
1720
1
            }
1721
1
            LOG_INFO("removed packed file metadata")
1722
1
                    .tag("instance_id", instance_id_)
1723
1
                    .tag("packed_file_path", packed_file_path);
1724
1
            return 0;
1725
1
        }
1726
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1727
0
            if (del_attempt >= max_retry_times) {
1728
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1729
0
                        .tag("instance_id", instance_id_)
1730
0
                        .tag("packed_file_path", packed_file_path)
1731
0
                        .tag("del_attempt", del_attempt);
1732
0
                return -1;
1733
0
            }
1734
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1735
0
                    .tag("instance_id", instance_id_)
1736
0
                    .tag("packed_file_path", packed_file_path)
1737
0
                    .tag("del_attempt", del_attempt);
1738
0
            sleep_for_packed_file_retry();
1739
0
            continue;
1740
0
        }
1741
0
        LOG_WARNING("failed to remove packed file kv")
1742
0
                .tag("instance_id", instance_id_)
1743
0
                .tag("packed_file_path", packed_file_path)
1744
0
                .tag("del_attempt", del_attempt)
1745
0
                .tag("err", err);
1746
0
        return -1;
1747
0
    }
1748
1749
0
    return -1;
1750
1
}
1751
1752
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1753
4
                                            PackedFileRecycleStats* stats, int* ret) {
1754
4
    if (stats) {
1755
4
        ++stats->num_scanned;
1756
4
    }
1757
4
    std::string packed_file_path;
1758
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1759
0
        LOG_WARNING("failed to decode packed file key")
1760
0
                .tag("instance_id", instance_id_)
1761
0
                .tag("key", hex(key));
1762
0
        if (stats) {
1763
0
            ++stats->num_failed;
1764
0
        }
1765
0
        if (ret) {
1766
0
            *ret = -1;
1767
0
        }
1768
0
        return 0;
1769
0
    }
1770
1771
4
    std::string packed_key(key);
1772
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1773
4
    if (process_ret != 0) {
1774
0
        if (stats) {
1775
0
            ++stats->num_failed;
1776
0
        }
1777
0
        if (ret) {
1778
0
            *ret = -1;
1779
0
        }
1780
0
    }
1781
4
    return 0;
1782
4
}
1783
1784
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1785
6.30k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1786
6.30k
    if (config::force_immediate_recycle) {
1787
295
        return 0L;
1788
295
    }
1789
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1790
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1791
6.00k
    int64_t retention_seconds = config::retention_seconds;
1792
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1793
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1794
4.70k
    }
1795
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1796
6.00k
    if (*earlest_ts > final_expiration) {
1797
6
        *earlest_ts = final_expiration;
1798
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1799
6
    }
1800
6.00k
    return final_expiration;
1801
6.30k
}
1802
1803
int64_t calculate_partition_expired_time(
1804
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1805
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1806
9
    if (config::force_immediate_recycle) {
1807
3
        return 0L;
1808
3
    }
1809
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1810
6
                                                            : partition_meta_pb.creation_time();
1811
6
    int64_t retention_seconds = config::retention_seconds;
1812
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1813
6
        retention_seconds =
1814
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1815
6
    }
1816
6
    int64_t final_expiration = expiration + retention_seconds;
1817
6
    if (*earlest_ts > final_expiration) {
1818
2
        *earlest_ts = final_expiration;
1819
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1820
2
    }
1821
6
    return final_expiration;
1822
9
}
1823
1824
int64_t calculate_index_expired_time(const std::string& instance_id_,
1825
                                     const RecycleIndexPB& index_meta_pb,
1826
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1827
10
    if (config::force_immediate_recycle) {
1828
4
        return 0L;
1829
4
    }
1830
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1831
6
                                                        : index_meta_pb.creation_time();
1832
6
    int64_t retention_seconds = config::retention_seconds;
1833
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1834
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1835
6
    }
1836
6
    int64_t final_expiration = expiration + retention_seconds;
1837
6
    if (*earlest_ts > final_expiration) {
1838
2
        *earlest_ts = final_expiration;
1839
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1840
2
    }
1841
6
    return final_expiration;
1842
10
}
1843
1844
int64_t calculate_tmp_rowset_expired_time(
1845
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1846
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1847
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1848
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1849
    //  duration or timeout always < `retention_time` in practice.
1850
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1851
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1852
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1853
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1854
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1855
53.2k
    if (*earlest_ts > final_expiration) {
1856
20
        *earlest_ts = final_expiration;
1857
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1858
20
    }
1859
53.2k
    return final_expiration;
1860
53.2k
}
1861
1862
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1863
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1864
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1865
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1866
8
        *earlest_ts = final_expiration / 1000;
1867
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1868
8
    }
1869
30.0k
    return final_expiration;
1870
30.0k
}
1871
1872
int64_t calculate_restore_job_expired_time(
1873
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1874
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1875
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1876
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1877
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1878
        // final state, recycle immediately
1879
41
        return 0L;
1880
41
    }
1881
    // not final state, wait much longer than the FE's timeout(1 day)
1882
0
    int64_t last_modified_s =
1883
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1884
0
    int64_t expiration = restore_job.expired_at_s() > 0
1885
0
                                 ? last_modified_s + restore_job.expired_at_s()
1886
0
                                 : last_modified_s;
1887
0
    int64_t final_expiration = expiration + config::retention_seconds;
1888
0
    if (*earlest_ts > final_expiration) {
1889
0
        *earlest_ts = final_expiration;
1890
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1891
0
    }
1892
0
    return final_expiration;
1893
41
}
1894
1895
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1896
537
    AbortTxnRequest req;
1897
537
    TxnInfoPB txn_info;
1898
537
    MetaServiceCode code = MetaServiceCode::OK;
1899
537
    std::string msg;
1900
537
    std::stringstream ss;
1901
537
    std::unique_ptr<Transaction> txn;
1902
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1903
537
    if (err != TxnErrorCode::TXN_OK) {
1904
0
        LOG_WARNING("failed to create txn").tag("err", err);
1905
0
        return -1;
1906
0
    }
1907
1908
    // get txn index
1909
537
    TxnIndexPB txn_idx_pb;
1910
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1911
537
    std::string index_val;
1912
537
    err = txn->get(index_key, &index_val);
1913
537
    if (err != TxnErrorCode::TXN_OK) {
1914
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1915
            // maybe recycled
1916
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1917
2
                    .tag("key", hex(index_key))
1918
2
                    .tag("txn_id", txn_id);
1919
2
            return 0;
1920
2
        }
1921
0
        LOG_WARNING("failed to get txn index")
1922
0
                .tag("err", err)
1923
0
                .tag("key", hex(index_key))
1924
0
                .tag("txn_id", txn_id);
1925
0
        return -1;
1926
2
    }
1927
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
1928
1
        LOG_WARNING("failed to parse txn index")
1929
1
                .tag("err", err)
1930
1
                .tag("key", hex(index_key))
1931
1
                .tag("txn_id", txn_id);
1932
1
        return -1;
1933
1
    }
1934
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1935
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
1936
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1937
3
                .tag("key", hex(index_key))
1938
3
                .tag("txn_id", txn_id)
1939
3
                .tag("db_id",
1940
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1941
3
        return -1;
1942
3
    }
1943
1944
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1945
531
    const int64_t owner_txn_id =
1946
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1947
531
    if (owner_txn_id <= 0) {
1948
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
1949
1
                .tag("key", hex(index_key))
1950
1
                .tag("txn_id", txn_id)
1951
1
                .tag("owner_txn_id", owner_txn_id);
1952
1
        return -1;
1953
1
    }
1954
1955
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
1956
530
    std::string info_val;
1957
530
    err = txn->get(info_key, &info_val);
1958
530
    if (err != TxnErrorCode::TXN_OK) {
1959
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1960
            // maybe recycled
1961
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
1962
1
                        owner_txn_id, instance_id_)
1963
1
                    .tag("key", hex(info_key))
1964
1
                    .tag("txn_id", txn_id)
1965
1
                    .tag("owner_txn_id", owner_txn_id);
1966
1
            return 0;
1967
1
        }
1968
0
        LOG_WARNING("failed to get txn info")
1969
0
                .tag("err", err)
1970
0
                .tag("key", hex(info_key))
1971
0
                .tag("txn_id", txn_id)
1972
0
                .tag("owner_txn_id", owner_txn_id);
1973
0
        return -1;
1974
1
    }
1975
529
    if (!txn_info.ParseFromString(info_val)) {
1976
1
        LOG_WARNING("failed to parse txn info")
1977
1
                .tag("err", err)
1978
1
                .tag("key", hex(info_key))
1979
1
                .tag("txn_id", txn_id)
1980
1
                .tag("owner_txn_id", owner_txn_id);
1981
1
        return -1;
1982
1
    }
1983
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
1984
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
1985
1
                .tag("key", hex(info_key))
1986
1
                .tag("txn_id", txn_id)
1987
1
                .tag("owner_txn_id", owner_txn_id)
1988
1
                .tag("txn_info_txn_id", txn_info.txn_id());
1989
1
        return -1;
1990
1
    }
1991
1992
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
1993
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
1994
514
                .tag("key", hex(info_key))
1995
514
                .tag("txn_id", txn_id)
1996
514
                .tag("owner_txn_id", owner_txn_id);
1997
514
        return 0;
1998
514
    }
1999
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2000
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2001
4
                    owner_txn_id, txn_info.status())
2002
4
                .tag("key", hex(info_key))
2003
4
                .tag("txn_id", txn_id)
2004
4
                .tag("owner_txn_id", owner_txn_id);
2005
4
        return -1;
2006
4
    }
2007
2008
9
    req.set_txn_id(owner_txn_id);
2009
9
    req.set_db_id(db_id);
2010
2011
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2012
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2013
9
                 << " txn_info=" << txn_info.ShortDebugString();
2014
2015
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2016
9
    if (code != MetaServiceCode::OK) {
2017
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2018
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2019
0
                     << " code=" << code << " msg=" << msg;
2020
0
        return -1;
2021
0
    }
2022
2023
9
    err = txn->commit();
2024
9
    if (err != TxnErrorCode::TXN_OK) {
2025
0
        code = cast_as<ErrCategory::COMMIT>(err);
2026
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2027
0
        msg = ss.str();
2028
0
        return -1;
2029
0
    }
2030
2031
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2032
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2033
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2034
9
                 << " msg=" << msg;
2035
2036
9
    return 0;
2037
9
}
2038
2039
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2040
11
                                                   const std::string& job_id) {
2041
11
    FinishTabletJobRequest req;
2042
11
    FinishTabletJobResponse res;
2043
11
    req.set_action(FinishTabletJobRequest::ABORT);
2044
11
    MetaServiceCode code = MetaServiceCode::OK;
2045
11
    std::string msg;
2046
11
    std::stringstream ss;
2047
2048
11
    TabletIndexPB tablet_idx;
2049
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2050
11
    if (ret == 1) {
2051
        // tablet maybe recycled, directly return 0
2052
1
        return 0;
2053
10
    } else if (ret != 0) {
2054
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2055
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2056
0
        return ret;
2057
0
    }
2058
2059
10
    std::unique_ptr<Transaction> txn;
2060
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2061
10
    if (err != TxnErrorCode::TXN_OK) {
2062
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2063
0
        return -1;
2064
0
    }
2065
2066
10
    std::string job_key =
2067
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2068
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2069
10
    std::string job_val;
2070
10
    err = txn->get(job_key, &job_val);
2071
10
    if (err != TxnErrorCode::TXN_OK) {
2072
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2073
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2074
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2075
            // A previous recycler round may have aborted the job. The caller must recheck the
2076
            // recycle key before deleting object data.
2077
1
            return 0;
2078
1
        }
2079
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2080
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2081
0
                     << " key=" << hex(job_key);
2082
0
        return -1;
2083
1
    }
2084
2085
9
    TabletJobInfoPB job_pb;
2086
9
    if (!job_pb.ParseFromString(job_val)) {
2087
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2088
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2089
0
        return -1;
2090
0
    }
2091
2092
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2093
9
    for (const auto& compaction : job_pb.compaction()) {
2094
9
        if (compaction.id() == job_id) {
2095
5
            matched_compaction = &compaction;
2096
5
            break;
2097
5
        }
2098
9
    }
2099
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2100
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2101
9
        job_pb.schema_change().id() == job_id) {
2102
3
        matched_schema_change = &job_pb.schema_change();
2103
3
    }
2104
2105
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2106
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2107
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2108
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2109
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2110
        // both the base and mirrored schema-change records.
2111
8
        if (matched_compaction != nullptr) {
2112
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2113
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2114
5
        } else {
2115
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2116
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2117
3
        }
2118
8
        req.set_action(FinishTabletJobRequest::ABORT);
2119
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2120
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2121
8
                           ss);
2122
8
        if (code != MetaServiceCode::OK) {
2123
            // These two codes mean that the job cannot be aborted anymore.
2124
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2125
            // There is no running job that still owns the PREPARE rowset, so the caller may
2126
            // recheck the recycle key.
2127
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2128
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2129
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2130
            // job again and continue recycling only when the target job id no longer exists.
2131
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2132
0
                std::unique_ptr<Transaction> check_txn;
2133
0
                err = txn_kv_->create_txn(&check_txn);
2134
0
                if (err != TxnErrorCode::TXN_OK) {
2135
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2136
0
                                 << instance_id_ << " err=" << err;
2137
0
                    return -1;
2138
0
                }
2139
2140
0
                const auto& idx = req.job().idx();
2141
0
                std::string current_job_key =
2142
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2143
0
                                        idx.partition_id(), idx.tablet_id()});
2144
0
                std::string current_job_val;
2145
0
                err = check_txn->get(current_job_key, &current_job_val);
2146
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2147
0
                    no_job_to_abort = true;
2148
0
                } else if (err != TxnErrorCode::TXN_OK) {
2149
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2150
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2151
0
                                 << " key=" << hex(current_job_key);
2152
0
                    return -1;
2153
0
                } else {
2154
0
                    TabletJobInfoPB current_job;
2155
0
                    if (!current_job.ParseFromString(current_job_val)) {
2156
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2157
0
                                     << " tablet_id=" << idx.tablet_id()
2158
0
                                     << " key=" << hex(current_job_key);
2159
0
                        return -1;
2160
0
                    }
2161
0
                    if (matched_compaction != nullptr) {
2162
0
                        no_job_to_abort = true;
2163
0
                        for (const auto& compaction : current_job.compaction()) {
2164
0
                            if (compaction.id() == job_id) {
2165
0
                                no_job_to_abort = false;
2166
0
                                break;
2167
0
                            }
2168
0
                        }
2169
0
                    } else {
2170
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2171
0
                                          current_job.schema_change().id() != job_id;
2172
0
                    }
2173
0
                }
2174
0
            }
2175
0
            if (no_job_to_abort) {
2176
0
                return 0;
2177
0
            }
2178
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2179
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2180
0
                         << " msg=" << msg;
2181
0
            return -1;
2182
0
        }
2183
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2184
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2185
8
                     << " code=" << code << " msg=" << msg;
2186
8
    } else {
2187
        // clang-format off
2188
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2189
1
                  << ", instance_id=" << instance_id_ 
2190
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2191
1
                  << ", job_id=" << job_id
2192
1
                  << ", rowset_id=" << rowset_id;
2193
        // clang-format on
2194
1
    }
2195
2196
9
    return 0;
2197
9
}
2198
2199
template <typename T>
2200
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2201
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2202
13
        return rowset_meta_pb.mutable_rowset_meta();
2203
13
    } else {
2204
9
        return &rowset_meta_pb;
2205
9
    }
2206
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2200
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2201
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2202
13
        return rowset_meta_pb.mutable_rowset_meta();
2203
    } else {
2204
        return &rowset_meta_pb;
2205
    }
2206
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2200
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2201
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2202
        return rowset_meta_pb.mutable_rowset_meta();
2203
9
    } else {
2204
9
        return &rowset_meta_pb;
2205
9
    }
2206
9
}
2207
2208
template <typename T>
2209
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2210
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2211
833
        return rowset_meta_pb.rowset_meta();
2212
833
    } else {
2213
799
        return rowset_meta_pb;
2214
799
    }
2215
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2209
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2210
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2211
833
        return rowset_meta_pb.rowset_meta();
2212
    } else {
2213
        return rowset_meta_pb;
2214
    }
2215
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2209
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2210
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2211
        return rowset_meta_pb.rowset_meta();
2212
799
    } else {
2213
799
        return rowset_meta_pb;
2214
799
    }
2215
799
}
2216
2217
template <typename T>
2218
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2219
1.07k
        const T& rowset_meta_pb) {
2220
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2221
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2222
0
            return std::nullopt;
2223
0
        }
2224
545
    }
2225
2226
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2227
1.07k
    RelatedTxnOrJobAbortTask task;
2228
1.07k
    task.tablet_id = rs_meta.tablet_id();
2229
1.07k
    task.start_version = rs_meta.start_version();
2230
1.07k
    task.end_version = rs_meta.end_version();
2231
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2232
1.07k
    if (rs_meta.has_load_id()) {
2233
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2234
1.05k
        task.txn_id = rs_meta.txn_id();
2235
1.05k
        return task;
2236
1.05k
    }
2237
19
    if (rs_meta.has_job_id()) {
2238
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2239
14
        task.job_id = rs_meta.job_id();
2240
14
        return task;
2241
14
    }
2242
5
    return std::nullopt;
2243
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2219
545
        const T& rowset_meta_pb) {
2220
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2221
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2222
0
            return std::nullopt;
2223
0
        }
2224
545
    }
2225
2226
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2227
545
    RelatedTxnOrJobAbortTask task;
2228
545
    task.tablet_id = rs_meta.tablet_id();
2229
545
    task.start_version = rs_meta.start_version();
2230
545
    task.end_version = rs_meta.end_version();
2231
545
    task.rowset_id = rs_meta.rowset_id_v2();
2232
545
    if (rs_meta.has_load_id()) {
2233
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2234
534
        task.txn_id = rs_meta.txn_id();
2235
534
        return task;
2236
534
    }
2237
11
    if (rs_meta.has_job_id()) {
2238
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2239
10
        task.job_id = rs_meta.job_id();
2240
10
        return task;
2241
10
    }
2242
1
    return std::nullopt;
2243
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2219
526
        const T& rowset_meta_pb) {
2220
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2221
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2222
            return std::nullopt;
2223
        }
2224
    }
2225
2226
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2227
526
    RelatedTxnOrJobAbortTask task;
2228
526
    task.tablet_id = rs_meta.tablet_id();
2229
526
    task.start_version = rs_meta.start_version();
2230
526
    task.end_version = rs_meta.end_version();
2231
526
    task.rowset_id = rs_meta.rowset_id_v2();
2232
526
    if (rs_meta.has_load_id()) {
2233
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2234
518
        task.txn_id = rs_meta.txn_id();
2235
518
        return task;
2236
518
    }
2237
8
    if (rs_meta.has_job_id()) {
2238
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2239
4
        task.job_id = rs_meta.job_id();
2240
4
        return task;
2241
4
    }
2242
4
    return std::nullopt;
2243
8
}
2244
2245
template <typename T>
2246
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2247
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2248
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return false;
2251
0
        }
2252
268
    }
2253
2254
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2256
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2257
0
        return false;
2258
0
    }
2259
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2260
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2261
523
    }
2262
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2263
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2247
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2248
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return false;
2251
0
        }
2252
268
    }
2253
2254
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2256
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2257
0
        return false;
2258
0
    }
2259
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2260
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2261
264
    }
2262
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2263
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2247
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2248
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
            return false;
2251
        }
2252
    }
2253
2254
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2256
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2257
0
        return false;
2258
0
    }
2259
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2260
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2261
259
    }
2262
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2263
261
}
2264
2265
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2266
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2267
71
}
2268
2269
template <typename T>
2270
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2271
18
                                   const std::vector<std::string>& keys) {
2272
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2273
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2274
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2275
18
        std::unique_ptr<Transaction> txn;
2276
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2277
18
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2279
0
            return -1;
2280
0
        }
2281
18
        std::vector<std::optional<std::string>> values;
2282
18
        err = txn->batch_get(&values, batch_keys);
2283
18
        if (err != TxnErrorCode::TXN_OK) {
2284
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2285
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2286
0
            return -1;
2287
0
        }
2288
18
        DCHECK_EQ(values.size(), batch_keys.size());
2289
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2290
22
            if (!values[i].has_value()) {
2291
                // has already been removed by commit_rowset
2292
0
                continue;
2293
0
            }
2294
22
            const auto& key = batch_keys[i];
2295
22
            auto val = values[i].value();
2296
22
            T rowset_meta_pb;
2297
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2298
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2299
0
                             << " key=" << hex(key);
2300
0
                return -1;
2301
0
            }
2302
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2303
0
                continue;
2304
0
            }
2305
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2306
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2307
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2308
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2309
13
            }
2310
22
            val.clear();
2311
22
            rowset_meta_pb.SerializeToString(&val);
2312
22
            txn->put(key, val);
2313
22
        }
2314
18
        err = txn->commit();
2315
18
        if (err != TxnErrorCode::TXN_OK) {
2316
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2317
1
            return -1;
2318
1
        }
2319
18
    }
2320
2321
17
    return 0;
2322
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2271
11
                                   const std::vector<std::string>& keys) {
2272
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2273
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2274
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2275
11
        std::unique_ptr<Transaction> txn;
2276
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2277
11
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2279
0
            return -1;
2280
0
        }
2281
11
        std::vector<std::optional<std::string>> values;
2282
11
        err = txn->batch_get(&values, batch_keys);
2283
11
        if (err != TxnErrorCode::TXN_OK) {
2284
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2285
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2286
0
            return -1;
2287
0
        }
2288
11
        DCHECK_EQ(values.size(), batch_keys.size());
2289
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2290
13
            if (!values[i].has_value()) {
2291
                // has already been removed by commit_rowset
2292
0
                continue;
2293
0
            }
2294
13
            const auto& key = batch_keys[i];
2295
13
            auto val = values[i].value();
2296
13
            T rowset_meta_pb;
2297
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2298
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2299
0
                             << " key=" << hex(key);
2300
0
                return -1;
2301
0
            }
2302
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2303
0
                continue;
2304
0
            }
2305
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2306
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2307
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2308
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2309
13
            }
2310
13
            val.clear();
2311
13
            rowset_meta_pb.SerializeToString(&val);
2312
13
            txn->put(key, val);
2313
13
        }
2314
11
        err = txn->commit();
2315
11
        if (err != TxnErrorCode::TXN_OK) {
2316
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2317
1
            return -1;
2318
1
        }
2319
11
    }
2320
2321
10
    return 0;
2322
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2271
7
                                   const std::vector<std::string>& keys) {
2272
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2273
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2274
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2275
7
        std::unique_ptr<Transaction> txn;
2276
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2277
7
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2279
0
            return -1;
2280
0
        }
2281
7
        std::vector<std::optional<std::string>> values;
2282
7
        err = txn->batch_get(&values, batch_keys);
2283
7
        if (err != TxnErrorCode::TXN_OK) {
2284
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2285
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2286
0
            return -1;
2287
0
        }
2288
7
        DCHECK_EQ(values.size(), batch_keys.size());
2289
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2290
9
            if (!values[i].has_value()) {
2291
                // has already been removed by commit_rowset
2292
0
                continue;
2293
0
            }
2294
9
            const auto& key = batch_keys[i];
2295
9
            auto val = values[i].value();
2296
9
            T rowset_meta_pb;
2297
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2298
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2299
0
                             << " key=" << hex(key);
2300
0
                return -1;
2301
0
            }
2302
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2303
0
                continue;
2304
0
            }
2305
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2306
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2307
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2308
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2309
            }
2310
9
            val.clear();
2311
9
            rowset_meta_pb.SerializeToString(&val);
2312
9
            txn->put(key, val);
2313
9
        }
2314
7
        err = txn->commit();
2315
7
        if (err != TxnErrorCode::TXN_OK) {
2316
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2317
0
            return -1;
2318
0
        }
2319
7
    }
2320
2321
7
    return 0;
2322
7
}
2323
2324
template <typename T>
2325
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2326
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2327
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2328
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2329
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2330
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2331
1
        }
2332
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2327
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2328
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2329
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2330
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2331
1
        }
2332
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2327
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2328
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2329
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2330
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2331
0
        }
2332
7
    });
2333
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2326
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2327
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2328
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2329
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2330
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2331
11
        }
2332
11
    });
2333
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2326
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2327
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2328
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2329
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2330
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2331
7
        }
2332
7
    });
2333
7
}
2334
2335
template <typename T>
2336
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2337
                                 const std::vector<std::string>& keys,
2338
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2339
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2340
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2341
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2342
22
        std::unique_ptr<Transaction> txn;
2343
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2344
22
        if (err != TxnErrorCode::TXN_OK) {
2345
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2346
0
            return -1;
2347
0
        }
2348
22
        std::vector<std::optional<std::string>> values;
2349
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2350
22
        if (err != TxnErrorCode::TXN_OK) {
2351
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2352
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2353
0
            return -1;
2354
0
        }
2355
22
        DCHECK_EQ(values.size(), batch_keys.size());
2356
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2357
533
            const std::string& key = batch_keys[idx];
2358
533
            if (!values[idx].has_value()) {
2359
                // has already been removed
2360
0
                continue;
2361
0
            }
2362
533
            T rowset_meta_pb;
2363
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2364
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2365
0
                             << " key=" << hex(key);
2366
0
                return -1;
2367
0
            }
2368
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2369
533
                abort_task.has_value()) {
2370
533
                abort_task->key = key;
2371
533
                abort_tasks->emplace_back(std::move(*abort_task));
2372
533
            }
2373
533
        }
2374
22
    }
2375
20
    return 0;
2376
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2338
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2339
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2340
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2341
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2342
16
        std::unique_ptr<Transaction> txn;
2343
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2344
16
        if (err != TxnErrorCode::TXN_OK) {
2345
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2346
0
            return -1;
2347
0
        }
2348
16
        std::vector<std::optional<std::string>> values;
2349
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2350
16
        if (err != TxnErrorCode::TXN_OK) {
2351
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2352
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2353
0
            return -1;
2354
0
        }
2355
16
        DCHECK_EQ(values.size(), batch_keys.size());
2356
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2357
272
            const std::string& key = batch_keys[idx];
2358
272
            if (!values[idx].has_value()) {
2359
                // has already been removed
2360
0
                continue;
2361
0
            }
2362
272
            T rowset_meta_pb;
2363
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2364
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2365
0
                             << " key=" << hex(key);
2366
0
                return -1;
2367
0
            }
2368
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2369
272
                abort_task.has_value()) {
2370
272
                abort_task->key = key;
2371
272
                abort_tasks->emplace_back(std::move(*abort_task));
2372
272
            }
2373
272
        }
2374
16
    }
2375
15
    return 0;
2376
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2338
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2339
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2340
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2341
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2342
6
        std::unique_ptr<Transaction> txn;
2343
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2344
6
        if (err != TxnErrorCode::TXN_OK) {
2345
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2346
0
            return -1;
2347
0
        }
2348
6
        std::vector<std::optional<std::string>> values;
2349
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2350
6
        if (err != TxnErrorCode::TXN_OK) {
2351
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2352
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2353
0
            return -1;
2354
0
        }
2355
6
        DCHECK_EQ(values.size(), batch_keys.size());
2356
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2357
261
            const std::string& key = batch_keys[idx];
2358
261
            if (!values[idx].has_value()) {
2359
                // has already been removed
2360
0
                continue;
2361
0
            }
2362
261
            T rowset_meta_pb;
2363
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2364
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2365
0
                             << " key=" << hex(key);
2366
0
                return -1;
2367
0
            }
2368
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2369
261
                abort_task.has_value()) {
2370
261
                abort_task->key = key;
2371
261
                abort_tasks->emplace_back(std::move(*abort_task));
2372
261
            }
2373
261
        }
2374
6
    }
2375
5
    return 0;
2376
5
}
2377
2378
template <typename T>
2379
int batch_recheck_rowsets_after_abort(
2380
        TxnKv* txn_kv, const std::string& instance_id,
2381
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2382
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2383
18
    int ret = 0;
2384
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2385
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2386
20
        std::vector<std::string> batch_keys;
2387
20
        batch_keys.reserve(limit - offset);
2388
550
        for (size_t idx = offset; idx < limit; ++idx) {
2389
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2390
530
        }
2391
2392
20
        std::unique_ptr<Transaction> txn;
2393
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2394
20
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2396
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2397
0
            ret = -1;
2398
0
            continue;
2399
0
        }
2400
2401
20
        std::vector<std::optional<std::string>> values;
2402
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2403
20
        if (err != TxnErrorCode::TXN_OK) {
2404
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2405
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2406
0
            ret = -1;
2407
0
            continue;
2408
0
        }
2409
20
        DCHECK_EQ(values.size(), batch_keys.size());
2410
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2411
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2412
20
                                 &batch_size);
2413
2414
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2415
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2416
530
            if (!values[idx].has_value()) {
2417
1
                continue;
2418
1
            }
2419
2420
529
            T rowset_meta_pb;
2421
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2422
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2423
0
                             << instance_id << " key=" << hex(key);
2424
0
                ret = -1;
2425
0
                continue;
2426
0
            }
2427
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2428
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2429
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2430
0
                             << instance_id << " key=" << hex(key);
2431
0
                continue;
2432
0
            }
2433
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2434
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2435
1
                             << instance_id << " key=" << hex(key);
2436
1
                continue;
2437
1
            }
2438
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2439
528
        }
2440
20
    }
2441
18
    return ret;
2442
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2382
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2383
13
    int ret = 0;
2384
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2385
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2386
14
        std::vector<std::string> batch_keys;
2387
14
        batch_keys.reserve(limit - offset);
2388
283
        for (size_t idx = offset; idx < limit; ++idx) {
2389
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2390
269
        }
2391
2392
14
        std::unique_ptr<Transaction> txn;
2393
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2394
14
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2396
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2397
0
            ret = -1;
2398
0
            continue;
2399
0
        }
2400
2401
14
        std::vector<std::optional<std::string>> values;
2402
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2403
14
        if (err != TxnErrorCode::TXN_OK) {
2404
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2405
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2406
0
            ret = -1;
2407
0
            continue;
2408
0
        }
2409
14
        DCHECK_EQ(values.size(), batch_keys.size());
2410
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2411
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2412
14
                                 &batch_size);
2413
2414
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2415
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2416
269
            if (!values[idx].has_value()) {
2417
1
                continue;
2418
1
            }
2419
2420
268
            T rowset_meta_pb;
2421
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2422
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2423
0
                             << instance_id << " key=" << hex(key);
2424
0
                ret = -1;
2425
0
                continue;
2426
0
            }
2427
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2428
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2429
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2430
0
                             << instance_id << " key=" << hex(key);
2431
0
                continue;
2432
0
            }
2433
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2434
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2435
1
                             << instance_id << " key=" << hex(key);
2436
1
                continue;
2437
1
            }
2438
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2439
267
        }
2440
14
    }
2441
13
    return ret;
2442
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2382
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2383
5
    int ret = 0;
2384
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2385
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2386
6
        std::vector<std::string> batch_keys;
2387
6
        batch_keys.reserve(limit - offset);
2388
267
        for (size_t idx = offset; idx < limit; ++idx) {
2389
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2390
261
        }
2391
2392
6
        std::unique_ptr<Transaction> txn;
2393
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2394
6
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2396
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2397
0
            ret = -1;
2398
0
            continue;
2399
0
        }
2400
2401
6
        std::vector<std::optional<std::string>> values;
2402
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2403
6
        if (err != TxnErrorCode::TXN_OK) {
2404
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2405
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2406
0
            ret = -1;
2407
0
            continue;
2408
0
        }
2409
6
        DCHECK_EQ(values.size(), batch_keys.size());
2410
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2411
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2412
6
                                 &batch_size);
2413
2414
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2415
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2416
261
            if (!values[idx].has_value()) {
2417
0
                continue;
2418
0
            }
2419
2420
261
            T rowset_meta_pb;
2421
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2422
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2423
0
                             << instance_id << " key=" << hex(key);
2424
0
                ret = -1;
2425
0
                continue;
2426
0
            }
2427
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2428
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2429
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2430
0
                             << instance_id << " key=" << hex(key);
2431
0
                continue;
2432
0
            }
2433
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2434
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2435
0
                             << instance_id << " key=" << hex(key);
2436
0
                continue;
2437
0
            }
2438
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2439
261
        }
2440
6
    }
2441
5
    return ret;
2442
5
}
2443
2444
template <typename T>
2445
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2446
        const std::vector<std::string>& keys,
2447
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2448
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2449
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2450
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2451
0
        return -1;
2452
0
    }
2453
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2454
20
    int ret = 0;
2455
533
    for (const auto& abort_task : abort_tasks) {
2456
533
        int abort_ret = 0;
2457
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2458
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2459
526
        } else {
2460
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2461
7
                                                     abort_task.job_id);
2462
7
        }
2463
533
        if (abort_ret != 0) {
2464
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2465
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2466
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2467
3
            ret = abort_ret;
2468
3
            continue;
2469
3
        }
2470
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2471
530
    }
2472
20
    return ret;
2473
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2447
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2448
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2449
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2450
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2451
0
        return -1;
2452
0
    }
2453
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2454
15
    int ret = 0;
2455
272
    for (const auto& abort_task : abort_tasks) {
2456
272
        int abort_ret = 0;
2457
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2458
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2459
267
        } else {
2460
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2461
5
                                                     abort_task.job_id);
2462
5
        }
2463
272
        if (abort_ret != 0) {
2464
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2465
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2466
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2467
3
            ret = abort_ret;
2468
3
            continue;
2469
3
        }
2470
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2471
269
    }
2472
15
    return ret;
2473
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2447
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2448
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2449
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2450
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2451
0
        return -1;
2452
0
    }
2453
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2454
5
    int ret = 0;
2455
261
    for (const auto& abort_task : abort_tasks) {
2456
261
        int abort_ret = 0;
2457
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2458
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2459
259
        } else {
2460
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2461
2
                                                     abort_task.job_id);
2462
2
        }
2463
261
        if (abort_ret != 0) {
2464
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2465
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2466
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2467
0
            ret = abort_ret;
2468
0
            continue;
2469
0
        }
2470
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2471
261
    }
2472
5
    return ret;
2473
5
}
2474
2475
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2476
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2477
15
        std::atomic_long* num_recycled) {
2478
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2479
15
                                  num_recycled]() mutable {
2480
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2481
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2482
15
                                                                            keys_to_recheck);
2483
15
        if (abort_ret != 0) {
2484
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2485
2
                            "instance_id="
2486
2
                         << instance_id_;
2487
2
        }
2488
15
        if (keys_to_recheck.empty()) {
2489
2
            return;
2490
2
        }
2491
2492
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2493
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2494
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2495
13
        if (recheck_ret != 0) {
2496
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2497
0
                         << instance_id_;
2498
0
        }
2499
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2500
267
            const auto& current_meta = current_rowset.rowset_meta();
2501
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2502
267
                                   current_meta.rowset_id_v2()) != 0) {
2503
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2504
1
                continue;
2505
1
            }
2506
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2507
266
                                                   current_meta.rowset_id_v2()) != 0) {
2508
0
                continue;
2509
0
            }
2510
266
            std::vector<std::string> keys {key};
2511
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2512
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2513
0
                continue;
2514
0
            }
2515
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2516
266
        }
2517
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2479
2
                                  num_recycled]() mutable {
2480
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2481
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2482
2
                                                                            keys_to_recheck);
2483
2
        if (abort_ret != 0) {
2484
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2485
0
                            "instance_id="
2486
0
                         << instance_id_;
2487
0
        }
2488
2
        if (keys_to_recheck.empty()) {
2489
0
            return;
2490
0
        }
2491
2492
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2493
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2494
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2495
2
        if (recheck_ret != 0) {
2496
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2497
0
                         << instance_id_;
2498
0
        }
2499
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2500
2
            const auto& current_meta = current_rowset.rowset_meta();
2501
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2502
2
                                   current_meta.rowset_id_v2()) != 0) {
2503
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2504
0
                continue;
2505
0
            }
2506
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2507
2
                                                   current_meta.rowset_id_v2()) != 0) {
2508
0
                continue;
2509
0
            }
2510
2
            std::vector<std::string> keys {key};
2511
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2512
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2513
0
                continue;
2514
0
            }
2515
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2516
2
        }
2517
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2479
13
                                  num_recycled]() mutable {
2480
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2481
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2482
13
                                                                            keys_to_recheck);
2483
13
        if (abort_ret != 0) {
2484
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2485
2
                            "instance_id="
2486
2
                         << instance_id_;
2487
2
        }
2488
13
        if (keys_to_recheck.empty()) {
2489
2
            return;
2490
2
        }
2491
2492
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2493
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2494
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2495
11
        if (recheck_ret != 0) {
2496
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2497
0
                         << instance_id_;
2498
0
        }
2499
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2500
265
            const auto& current_meta = current_rowset.rowset_meta();
2501
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2502
265
                                   current_meta.rowset_id_v2()) != 0) {
2503
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2504
1
                continue;
2505
1
            }
2506
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2507
264
                                                   current_meta.rowset_id_v2()) != 0) {
2508
0
                continue;
2509
0
            }
2510
264
            std::vector<std::string> keys {key};
2511
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2512
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2513
0
                continue;
2514
0
            }
2515
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2516
264
        }
2517
11
    });
2518
15
    if (ret != 0) {
2519
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2520
0
    }
2521
15
}
2522
2523
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2524
                                                      std::vector<std::string> rowset_keys_to_abort,
2525
                                                      std::atomic_long* num_recycled,
2526
5
                                                      RecyclerMetricsContext* metrics_context) {
2527
5
    if (rowset_keys_to_abort.empty()) {
2528
0
        return;
2529
0
    }
2530
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2531
5
                        metrics_context]() mutable {
2532
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2533
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2534
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2535
5
        if (abort_ret != 0) {
2536
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2537
0
                            "instance_id="
2538
0
                         << instance_id_;
2539
0
        }
2540
2541
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2542
5
        std::vector<std::string> keys_to_delete;
2543
5
        std::vector<std::string> ref_count_keys_to_delete;
2544
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2545
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2546
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2547
5
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2552
261
            keys_to_delete.push_back(key);
2553
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2554
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2555
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2556
261
        }
2557
2558
5
        if (keys_to_delete.empty()) {
2559
0
            return;
2560
0
        }
2561
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2562
5
                               *metrics_context) != 0) {
2563
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2564
0
            return;
2565
0
        }
2566
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2567
261
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2568
261
                0) {
2569
0
                return;
2570
0
            }
2571
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2572
0
                return;
2573
0
            }
2574
261
        }
2575
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2576
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2577
0
            return;
2578
0
        }
2579
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2580
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2581
0
                         << instance_id_;
2582
0
            return;
2583
0
        }
2584
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2585
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2531
3
                        metrics_context]() mutable {
2532
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2533
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2534
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2535
3
        if (abort_ret != 0) {
2536
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2537
0
                            "instance_id="
2538
0
                         << instance_id_;
2539
0
        }
2540
2541
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2542
3
        std::vector<std::string> keys_to_delete;
2543
3
        std::vector<std::string> ref_count_keys_to_delete;
2544
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2545
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2546
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2547
3
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2552
3
            keys_to_delete.push_back(key);
2553
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2554
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2555
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2556
3
        }
2557
2558
3
        if (keys_to_delete.empty()) {
2559
0
            return;
2560
0
        }
2561
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2562
3
                               *metrics_context) != 0) {
2563
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2564
0
            return;
2565
0
        }
2566
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2567
3
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2568
3
                0) {
2569
0
                return;
2570
0
            }
2571
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2572
0
                return;
2573
0
            }
2574
3
        }
2575
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2576
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2577
0
            return;
2578
0
        }
2579
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2580
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2581
0
                         << instance_id_;
2582
0
            return;
2583
0
        }
2584
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2585
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2531
2
                        metrics_context]() mutable {
2532
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2533
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2534
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2535
2
        if (abort_ret != 0) {
2536
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2537
0
                            "instance_id="
2538
0
                         << instance_id_;
2539
0
        }
2540
2541
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2542
2
        std::vector<std::string> keys_to_delete;
2543
2
        std::vector<std::string> ref_count_keys_to_delete;
2544
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2545
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2546
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2547
2
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2552
258
            keys_to_delete.push_back(key);
2553
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2554
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2555
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2556
258
        }
2557
2558
2
        if (keys_to_delete.empty()) {
2559
0
            return;
2560
0
        }
2561
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2562
2
                               *metrics_context) != 0) {
2563
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2564
0
            return;
2565
0
        }
2566
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2567
258
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2568
258
                0) {
2569
0
                return;
2570
0
            }
2571
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2572
0
                return;
2573
0
            }
2574
258
        }
2575
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2576
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2577
0
            return;
2578
0
        }
2579
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2580
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2581
0
                         << instance_id_;
2582
0
            return;
2583
0
        }
2584
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2585
2
    });
2586
5
}
2587
2588
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2589
1
    const std::string task_name = "recycle_ref_rowsets";
2590
1
    *has_unrecycled_rowsets = false;
2591
2592
1
    std::string data_rowset_ref_count_key_start =
2593
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2594
1
    std::string data_rowset_ref_count_key_end =
2595
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2596
2597
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2598
2599
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2600
1
    register_recycle_task(task_name, start_time);
2601
2602
1
    DORIS_CLOUD_DEFER {
2603
1
        unregister_recycle_task(task_name);
2604
1
        int64_t cost =
2605
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2606
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2607
1
                .tag("instance_id", instance_id_);
2608
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2602
1
    DORIS_CLOUD_DEFER {
2603
1
        unregister_recycle_task(task_name);
2604
1
        int64_t cost =
2605
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2606
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2607
1
                .tag("instance_id", instance_id_);
2608
1
    };
2609
2610
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2611
1
    std::set<int64_t> tablets_with_refs;
2612
1
    int64_t num_scanned = 0;
2613
2614
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2615
0
        ++num_scanned;
2616
0
        int64_t tablet_id;
2617
0
        std::string rowset_id;
2618
0
        std::string_view key(k);
2619
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2620
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2621
0
            return 0; // Continue scanning
2622
0
        }
2623
2624
0
        tablets_with_refs.insert(tablet_id);
2625
0
        return 0;
2626
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2627
2628
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2629
1
                         std::move(scan_func)) != 0) {
2630
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2631
0
        return -1;
2632
0
    }
2633
2634
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2635
1
             tablets_with_refs.size(), num_scanned)
2636
1
            .tag("instance_id", instance_id_);
2637
2638
    // Phase 2: Recycle each tablet
2639
1
    int64_t num_recycled_tablets = 0;
2640
1
    for (int64_t tablet_id : tablets_with_refs) {
2641
0
        if (stopped()) {
2642
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2643
0
                    .tag("instance_id", instance_id_)
2644
0
                    .tag("tablets_processed", num_recycled_tablets)
2645
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2646
0
            break;
2647
0
        }
2648
2649
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2650
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2651
0
            LOG_WARNING("failed to recycle tablet")
2652
0
                    .tag("instance_id", instance_id_)
2653
0
                    .tag("tablet_id", tablet_id);
2654
0
            return -1;
2655
0
        }
2656
0
        ++num_recycled_tablets;
2657
0
    }
2658
2659
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2660
1
            .tag("instance_id", instance_id_)
2661
1
            .tag("total_tablets", tablets_with_refs.size());
2662
2663
    // Phase 3: Scan again to check if any ref count keys still exist
2664
1
    std::unique_ptr<Transaction> txn;
2665
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2666
1
    if (err != TxnErrorCode::TXN_OK) {
2667
0
        LOG_WARNING("failed to create txn for final check")
2668
0
                .tag("instance_id", instance_id_)
2669
0
                .tag("err", err);
2670
0
        return -1;
2671
0
    }
2672
2673
1
    std::unique_ptr<RangeGetIterator> iter;
2674
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2675
1
    if (err != TxnErrorCode::TXN_OK) {
2676
0
        LOG_WARNING("failed to create range iterator for final check")
2677
0
                .tag("instance_id", instance_id_)
2678
0
                .tag("err", err);
2679
0
        return -1;
2680
0
    }
2681
2682
1
    *has_unrecycled_rowsets = iter->has_next();
2683
1
    if (*has_unrecycled_rowsets) {
2684
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2685
0
                .tag("instance_id", instance_id_);
2686
0
    }
2687
2688
1
    return 0;
2689
1
}
2690
2691
17
int InstanceRecycler::recycle_indexes() {
2692
17
    const std::string task_name = "recycle_indexes";
2693
17
    int64_t num_scanned = 0;
2694
17
    int64_t num_expired = 0;
2695
17
    int64_t num_recycled = 0;
2696
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2697
2698
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2699
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2700
17
    std::string index_key0;
2701
17
    std::string index_key1;
2702
17
    recycle_index_key(index_key_info0, &index_key0);
2703
17
    recycle_index_key(index_key_info1, &index_key1);
2704
2705
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2706
2707
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2708
17
    register_recycle_task(task_name, start_time);
2709
2710
17
    DORIS_CLOUD_DEFER {
2711
17
        unregister_recycle_task(task_name);
2712
17
        int64_t cost =
2713
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2714
17
        metrics_context.finish_report();
2715
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2716
17
                .tag("instance_id", instance_id_)
2717
17
                .tag("num_scanned", num_scanned)
2718
17
                .tag("num_expired", num_expired)
2719
17
                .tag("num_recycled", num_recycled);
2720
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2710
2
    DORIS_CLOUD_DEFER {
2711
2
        unregister_recycle_task(task_name);
2712
2
        int64_t cost =
2713
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2714
2
        metrics_context.finish_report();
2715
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2716
2
                .tag("instance_id", instance_id_)
2717
2
                .tag("num_scanned", num_scanned)
2718
2
                .tag("num_expired", num_expired)
2719
2
                .tag("num_recycled", num_recycled);
2720
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2710
15
    DORIS_CLOUD_DEFER {
2711
15
        unregister_recycle_task(task_name);
2712
15
        int64_t cost =
2713
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2714
15
        metrics_context.finish_report();
2715
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2716
15
                .tag("instance_id", instance_id_)
2717
15
                .tag("num_scanned", num_scanned)
2718
15
                .tag("num_expired", num_expired)
2719
15
                .tag("num_recycled", num_recycled);
2720
15
    };
2721
2722
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2723
2724
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2725
17
    std::vector<std::string_view> index_keys;
2726
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2727
10
        ++num_scanned;
2728
10
        RecycleIndexPB index_pb;
2729
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2730
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2731
0
            return -1;
2732
0
        }
2733
10
        int64_t current_time = ::time(nullptr);
2734
10
        if (current_time <
2735
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2736
0
            return 0;
2737
0
        }
2738
10
        ++num_expired;
2739
        // decode index_id
2740
10
        auto k1 = k;
2741
10
        k1.remove_prefix(1);
2742
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2743
10
        decode_key(&k1, &out);
2744
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2745
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2746
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2747
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2748
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2749
        // Change state to RECYCLING
2750
10
        std::unique_ptr<Transaction> txn;
2751
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2752
10
        if (err != TxnErrorCode::TXN_OK) {
2753
0
            LOG_WARNING("failed to create txn").tag("err", err);
2754
0
            return -1;
2755
0
        }
2756
10
        std::string val;
2757
10
        err = txn->get(k, &val);
2758
10
        if (err ==
2759
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2760
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2761
0
            return 0;
2762
0
        }
2763
10
        if (err != TxnErrorCode::TXN_OK) {
2764
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2765
0
            return -1;
2766
0
        }
2767
10
        index_pb.Clear();
2768
10
        if (!index_pb.ParseFromString(val)) {
2769
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2770
0
            return -1;
2771
0
        }
2772
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2773
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2774
9
            txn->put(k, index_pb.SerializeAsString());
2775
9
            err = txn->commit();
2776
9
            if (err != TxnErrorCode::TXN_OK) {
2777
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2778
0
                return -1;
2779
0
            }
2780
9
        }
2781
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2782
1
            LOG_WARNING("failed to recycle tablets under index")
2783
1
                    .tag("table_id", index_pb.table_id())
2784
1
                    .tag("instance_id", instance_id_)
2785
1
                    .tag("index_id", index_id);
2786
1
            return -1;
2787
1
        }
2788
2789
9
        if (index_pb.has_db_id()) {
2790
            // Recycle the versioned keys
2791
3
            std::unique_ptr<Transaction> txn;
2792
3
            err = txn_kv_->create_txn(&txn);
2793
3
            if (err != TxnErrorCode::TXN_OK) {
2794
0
                LOG_WARNING("failed to create txn").tag("err", err);
2795
0
                return -1;
2796
0
            }
2797
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2798
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2799
3
            std::string index_inverted_key = versioned::index_inverted_key(
2800
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2801
3
            versioned_remove_all(txn.get(), meta_key);
2802
3
            txn->remove(index_key);
2803
3
            txn->remove(index_inverted_key);
2804
3
            err = txn->commit();
2805
3
            if (err != TxnErrorCode::TXN_OK) {
2806
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2807
0
                return -1;
2808
0
            }
2809
3
        }
2810
2811
9
        metrics_context.total_recycled_num = ++num_recycled;
2812
9
        metrics_context.report();
2813
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2814
9
        index_keys.push_back(k);
2815
9
        return 0;
2816
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2726
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2727
2
        ++num_scanned;
2728
2
        RecycleIndexPB index_pb;
2729
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2730
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2731
0
            return -1;
2732
0
        }
2733
2
        int64_t current_time = ::time(nullptr);
2734
2
        if (current_time <
2735
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2736
0
            return 0;
2737
0
        }
2738
2
        ++num_expired;
2739
        // decode index_id
2740
2
        auto k1 = k;
2741
2
        k1.remove_prefix(1);
2742
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2743
2
        decode_key(&k1, &out);
2744
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2745
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2746
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2747
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2748
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2749
        // Change state to RECYCLING
2750
2
        std::unique_ptr<Transaction> txn;
2751
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2752
2
        if (err != TxnErrorCode::TXN_OK) {
2753
0
            LOG_WARNING("failed to create txn").tag("err", err);
2754
0
            return -1;
2755
0
        }
2756
2
        std::string val;
2757
2
        err = txn->get(k, &val);
2758
2
        if (err ==
2759
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2760
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2761
0
            return 0;
2762
0
        }
2763
2
        if (err != TxnErrorCode::TXN_OK) {
2764
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2765
0
            return -1;
2766
0
        }
2767
2
        index_pb.Clear();
2768
2
        if (!index_pb.ParseFromString(val)) {
2769
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2770
0
            return -1;
2771
0
        }
2772
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2773
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2774
1
            txn->put(k, index_pb.SerializeAsString());
2775
1
            err = txn->commit();
2776
1
            if (err != TxnErrorCode::TXN_OK) {
2777
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2778
0
                return -1;
2779
0
            }
2780
1
        }
2781
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2782
1
            LOG_WARNING("failed to recycle tablets under index")
2783
1
                    .tag("table_id", index_pb.table_id())
2784
1
                    .tag("instance_id", instance_id_)
2785
1
                    .tag("index_id", index_id);
2786
1
            return -1;
2787
1
        }
2788
2789
1
        if (index_pb.has_db_id()) {
2790
            // Recycle the versioned keys
2791
1
            std::unique_ptr<Transaction> txn;
2792
1
            err = txn_kv_->create_txn(&txn);
2793
1
            if (err != TxnErrorCode::TXN_OK) {
2794
0
                LOG_WARNING("failed to create txn").tag("err", err);
2795
0
                return -1;
2796
0
            }
2797
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2798
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2799
1
            std::string index_inverted_key = versioned::index_inverted_key(
2800
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2801
1
            versioned_remove_all(txn.get(), meta_key);
2802
1
            txn->remove(index_key);
2803
1
            txn->remove(index_inverted_key);
2804
1
            err = txn->commit();
2805
1
            if (err != TxnErrorCode::TXN_OK) {
2806
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2807
0
                return -1;
2808
0
            }
2809
1
        }
2810
2811
1
        metrics_context.total_recycled_num = ++num_recycled;
2812
1
        metrics_context.report();
2813
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2814
1
        index_keys.push_back(k);
2815
1
        return 0;
2816
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2726
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2727
8
        ++num_scanned;
2728
8
        RecycleIndexPB index_pb;
2729
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2730
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2731
0
            return -1;
2732
0
        }
2733
8
        int64_t current_time = ::time(nullptr);
2734
8
        if (current_time <
2735
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2736
0
            return 0;
2737
0
        }
2738
8
        ++num_expired;
2739
        // decode index_id
2740
8
        auto k1 = k;
2741
8
        k1.remove_prefix(1);
2742
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2743
8
        decode_key(&k1, &out);
2744
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2745
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2746
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2747
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2748
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2749
        // Change state to RECYCLING
2750
8
        std::unique_ptr<Transaction> txn;
2751
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2752
8
        if (err != TxnErrorCode::TXN_OK) {
2753
0
            LOG_WARNING("failed to create txn").tag("err", err);
2754
0
            return -1;
2755
0
        }
2756
8
        std::string val;
2757
8
        err = txn->get(k, &val);
2758
8
        if (err ==
2759
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2760
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2761
0
            return 0;
2762
0
        }
2763
8
        if (err != TxnErrorCode::TXN_OK) {
2764
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2765
0
            return -1;
2766
0
        }
2767
8
        index_pb.Clear();
2768
8
        if (!index_pb.ParseFromString(val)) {
2769
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2770
0
            return -1;
2771
0
        }
2772
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2773
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2774
8
            txn->put(k, index_pb.SerializeAsString());
2775
8
            err = txn->commit();
2776
8
            if (err != TxnErrorCode::TXN_OK) {
2777
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2778
0
                return -1;
2779
0
            }
2780
8
        }
2781
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2782
0
            LOG_WARNING("failed to recycle tablets under index")
2783
0
                    .tag("table_id", index_pb.table_id())
2784
0
                    .tag("instance_id", instance_id_)
2785
0
                    .tag("index_id", index_id);
2786
0
            return -1;
2787
0
        }
2788
2789
8
        if (index_pb.has_db_id()) {
2790
            // Recycle the versioned keys
2791
2
            std::unique_ptr<Transaction> txn;
2792
2
            err = txn_kv_->create_txn(&txn);
2793
2
            if (err != TxnErrorCode::TXN_OK) {
2794
0
                LOG_WARNING("failed to create txn").tag("err", err);
2795
0
                return -1;
2796
0
            }
2797
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2798
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2799
2
            std::string index_inverted_key = versioned::index_inverted_key(
2800
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2801
2
            versioned_remove_all(txn.get(), meta_key);
2802
2
            txn->remove(index_key);
2803
2
            txn->remove(index_inverted_key);
2804
2
            err = txn->commit();
2805
2
            if (err != TxnErrorCode::TXN_OK) {
2806
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2807
0
                return -1;
2808
0
            }
2809
2
        }
2810
2811
8
        metrics_context.total_recycled_num = ++num_recycled;
2812
8
        metrics_context.report();
2813
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2814
8
        index_keys.push_back(k);
2815
8
        return 0;
2816
8
    };
2817
2818
17
    auto loop_done = [&index_keys, this]() -> int {
2819
6
        if (index_keys.empty()) return 0;
2820
5
        DORIS_CLOUD_DEFER {
2821
5
            index_keys.clear();
2822
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2820
1
        DORIS_CLOUD_DEFER {
2821
1
            index_keys.clear();
2822
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2820
4
        DORIS_CLOUD_DEFER {
2821
4
            index_keys.clear();
2822
4
        };
2823
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2824
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2825
0
            return -1;
2826
0
        }
2827
5
        return 0;
2828
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2818
2
    auto loop_done = [&index_keys, this]() -> int {
2819
2
        if (index_keys.empty()) return 0;
2820
1
        DORIS_CLOUD_DEFER {
2821
1
            index_keys.clear();
2822
1
        };
2823
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2824
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2825
0
            return -1;
2826
0
        }
2827
1
        return 0;
2828
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2818
4
    auto loop_done = [&index_keys, this]() -> int {
2819
4
        if (index_keys.empty()) return 0;
2820
4
        DORIS_CLOUD_DEFER {
2821
4
            index_keys.clear();
2822
4
        };
2823
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2824
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2825
0
            return -1;
2826
0
        }
2827
4
        return 0;
2828
4
    };
2829
2830
17
    if (config::enable_recycler_stats_metrics) {
2831
0
        scan_and_statistics_indexes();
2832
0
    }
2833
    // recycle_func and loop_done for scan and recycle
2834
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2835
17
}
2836
2837
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2838
8.25k
                             int64_t tablet_id) {
2839
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2840
2841
8.25k
    std::unique_ptr<Transaction> txn;
2842
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2843
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2844
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2845
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2846
0
        return false;
2847
0
    }
2848
2849
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2850
8.25k
    std::string tablet_idx_val;
2851
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2852
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2853
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2854
0
                     << " tablet_id=" << tablet_id << " err=" << err
2855
0
                     << " key=" << hex(tablet_idx_key);
2856
0
        return false;
2857
0
    }
2858
2859
8.25k
    TabletIndexPB tablet_idx_pb;
2860
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2861
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2862
0
                     << " tablet_id=" << tablet_id;
2863
0
        return false;
2864
0
    }
2865
2866
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2867
        // In the previous version, the db_id was not set in the index_pb.
2868
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2869
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2870
0
                  << " instance_id=" << instance_id
2871
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2872
0
        return true;
2873
0
    }
2874
2875
8.25k
    std::string ver_val;
2876
8.25k
    std::string ver_key =
2877
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2878
8.25k
                                   tablet_idx_pb.partition_id()});
2879
8.25k
    err = txn->get(ver_key, &ver_val);
2880
2881
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2882
214
        LOG(INFO) << ""
2883
214
                     "partition version not found, instance_id="
2884
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2885
214
                  << " table_id=" << tablet_idx_pb.table_id()
2886
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2887
214
                  << " key=" << hex(ver_key);
2888
214
        return true;
2889
214
    }
2890
2891
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2892
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2893
0
                     << " db_id=" << tablet_idx_pb.db_id()
2894
0
                     << " table_id=" << tablet_idx_pb.table_id()
2895
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2896
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2897
0
        return false;
2898
0
    }
2899
2900
8.03k
    VersionPB version_pb;
2901
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2902
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2903
0
                     << " db_id=" << tablet_idx_pb.db_id()
2904
0
                     << " table_id=" << tablet_idx_pb.table_id()
2905
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2906
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2907
0
        return false;
2908
0
    }
2909
2910
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2911
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2912
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2913
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2914
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2915
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2916
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2917
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2918
4.00k
                     << " key=" << hex(ver_key);
2919
4.00k
        return false;
2920
4.00k
    }
2921
4.03k
    return true;
2922
8.03k
}
2923
2924
15
int InstanceRecycler::recycle_partitions() {
2925
15
    const std::string task_name = "recycle_partitions";
2926
15
    int64_t num_scanned = 0;
2927
15
    int64_t num_expired = 0;
2928
15
    int64_t num_recycled = 0;
2929
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2930
2931
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2932
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2933
15
    std::string part_key0;
2934
15
    std::string part_key1;
2935
15
    recycle_partition_key(part_key_info0, &part_key0);
2936
15
    recycle_partition_key(part_key_info1, &part_key1);
2937
2938
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2939
2940
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2941
15
    register_recycle_task(task_name, start_time);
2942
2943
15
    DORIS_CLOUD_DEFER {
2944
15
        unregister_recycle_task(task_name);
2945
15
        int64_t cost =
2946
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2947
15
        metrics_context.finish_report();
2948
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2949
15
                .tag("instance_id", instance_id_)
2950
15
                .tag("num_scanned", num_scanned)
2951
15
                .tag("num_expired", num_expired)
2952
15
                .tag("num_recycled", num_recycled);
2953
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2943
2
    DORIS_CLOUD_DEFER {
2944
2
        unregister_recycle_task(task_name);
2945
2
        int64_t cost =
2946
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2947
2
        metrics_context.finish_report();
2948
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2949
2
                .tag("instance_id", instance_id_)
2950
2
                .tag("num_scanned", num_scanned)
2951
2
                .tag("num_expired", num_expired)
2952
2
                .tag("num_recycled", num_recycled);
2953
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2943
13
    DORIS_CLOUD_DEFER {
2944
13
        unregister_recycle_task(task_name);
2945
13
        int64_t cost =
2946
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2947
13
        metrics_context.finish_report();
2948
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2949
13
                .tag("instance_id", instance_id_)
2950
13
                .tag("num_scanned", num_scanned)
2951
13
                .tag("num_expired", num_expired)
2952
13
                .tag("num_recycled", num_recycled);
2953
13
    };
2954
2955
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2956
2957
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2958
15
    std::vector<std::string_view> partition_keys;
2959
15
    std::vector<std::string> partition_version_keys;
2960
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2961
9
        ++num_scanned;
2962
9
        RecyclePartitionPB part_pb;
2963
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2964
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2965
0
            return -1;
2966
0
        }
2967
9
        int64_t current_time = ::time(nullptr);
2968
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2969
9
                                                            &earlest_ts)) { // not expired
2970
0
            return 0;
2971
0
        }
2972
9
        ++num_expired;
2973
        // decode partition_id
2974
9
        auto k1 = k;
2975
9
        k1.remove_prefix(1);
2976
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2977
9
        decode_key(&k1, &out);
2978
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2979
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2980
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2981
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2982
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2983
        // Change state to RECYCLING
2984
9
        std::unique_ptr<Transaction> txn;
2985
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2986
9
        if (err != TxnErrorCode::TXN_OK) {
2987
0
            LOG_WARNING("failed to create txn").tag("err", err);
2988
0
            return -1;
2989
0
        }
2990
9
        std::string val;
2991
9
        err = txn->get(k, &val);
2992
9
        if (err ==
2993
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2994
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2995
0
            return 0;
2996
0
        }
2997
9
        if (err != TxnErrorCode::TXN_OK) {
2998
0
            LOG_WARNING("failed to get kv");
2999
0
            return -1;
3000
0
        }
3001
9
        part_pb.Clear();
3002
9
        if (!part_pb.ParseFromString(val)) {
3003
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3004
0
            return -1;
3005
0
        }
3006
        // Partitions with PREPARED state MUST have no data
3007
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3008
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3009
8
            txn->put(k, part_pb.SerializeAsString());
3010
8
            err = txn->commit();
3011
8
            if (err != TxnErrorCode::TXN_OK) {
3012
0
                LOG_WARNING("failed to commit txn: {}", err);
3013
0
                return -1;
3014
0
            }
3015
8
        }
3016
3017
9
        int ret = 0;
3018
33
        for (int64_t index_id : part_pb.index_id()) {
3019
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3020
1
                LOG_WARNING("failed to recycle tablets under partition")
3021
1
                        .tag("table_id", part_pb.table_id())
3022
1
                        .tag("instance_id", instance_id_)
3023
1
                        .tag("index_id", index_id)
3024
1
                        .tag("partition_id", partition_id);
3025
1
                ret = -1;
3026
1
            }
3027
33
        }
3028
9
        if (ret == 0 && part_pb.has_db_id()) {
3029
            // Recycle the versioned keys
3030
8
            std::unique_ptr<Transaction> txn;
3031
8
            err = txn_kv_->create_txn(&txn);
3032
8
            if (err != TxnErrorCode::TXN_OK) {
3033
0
                LOG_WARNING("failed to create txn").tag("err", err);
3034
0
                return -1;
3035
0
            }
3036
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3037
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3038
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3039
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3040
8
            std::string partition_version_key =
3041
8
                    versioned::partition_version_key({instance_id_, partition_id});
3042
8
            versioned_remove_all(txn.get(), meta_key);
3043
8
            txn->remove(index_key);
3044
8
            txn->remove(inverted_index_key);
3045
8
            versioned_remove_all(txn.get(), partition_version_key);
3046
8
            err = txn->commit();
3047
8
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
8
        }
3052
3053
9
        if (ret == 0) {
3054
8
            ++num_recycled;
3055
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3056
8
            partition_keys.push_back(k);
3057
8
            if (part_pb.db_id() > 0) {
3058
8
                partition_version_keys.push_back(partition_version_key(
3059
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3060
8
            }
3061
8
            metrics_context.total_recycled_num = num_recycled;
3062
8
            metrics_context.report();
3063
8
        }
3064
9
        return ret;
3065
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2960
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2961
2
        ++num_scanned;
2962
2
        RecyclePartitionPB part_pb;
2963
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2964
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2965
0
            return -1;
2966
0
        }
2967
2
        int64_t current_time = ::time(nullptr);
2968
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2969
2
                                                            &earlest_ts)) { // not expired
2970
0
            return 0;
2971
0
        }
2972
2
        ++num_expired;
2973
        // decode partition_id
2974
2
        auto k1 = k;
2975
2
        k1.remove_prefix(1);
2976
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2977
2
        decode_key(&k1, &out);
2978
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2979
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2980
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2981
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2982
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2983
        // Change state to RECYCLING
2984
2
        std::unique_ptr<Transaction> txn;
2985
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2986
2
        if (err != TxnErrorCode::TXN_OK) {
2987
0
            LOG_WARNING("failed to create txn").tag("err", err);
2988
0
            return -1;
2989
0
        }
2990
2
        std::string val;
2991
2
        err = txn->get(k, &val);
2992
2
        if (err ==
2993
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2994
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2995
0
            return 0;
2996
0
        }
2997
2
        if (err != TxnErrorCode::TXN_OK) {
2998
0
            LOG_WARNING("failed to get kv");
2999
0
            return -1;
3000
0
        }
3001
2
        part_pb.Clear();
3002
2
        if (!part_pb.ParseFromString(val)) {
3003
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3004
0
            return -1;
3005
0
        }
3006
        // Partitions with PREPARED state MUST have no data
3007
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3008
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3009
1
            txn->put(k, part_pb.SerializeAsString());
3010
1
            err = txn->commit();
3011
1
            if (err != TxnErrorCode::TXN_OK) {
3012
0
                LOG_WARNING("failed to commit txn: {}", err);
3013
0
                return -1;
3014
0
            }
3015
1
        }
3016
3017
2
        int ret = 0;
3018
2
        for (int64_t index_id : part_pb.index_id()) {
3019
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3020
1
                LOG_WARNING("failed to recycle tablets under partition")
3021
1
                        .tag("table_id", part_pb.table_id())
3022
1
                        .tag("instance_id", instance_id_)
3023
1
                        .tag("index_id", index_id)
3024
1
                        .tag("partition_id", partition_id);
3025
1
                ret = -1;
3026
1
            }
3027
2
        }
3028
2
        if (ret == 0 && part_pb.has_db_id()) {
3029
            // Recycle the versioned keys
3030
1
            std::unique_ptr<Transaction> txn;
3031
1
            err = txn_kv_->create_txn(&txn);
3032
1
            if (err != TxnErrorCode::TXN_OK) {
3033
0
                LOG_WARNING("failed to create txn").tag("err", err);
3034
0
                return -1;
3035
0
            }
3036
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3037
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3038
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3039
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3040
1
            std::string partition_version_key =
3041
1
                    versioned::partition_version_key({instance_id_, partition_id});
3042
1
            versioned_remove_all(txn.get(), meta_key);
3043
1
            txn->remove(index_key);
3044
1
            txn->remove(inverted_index_key);
3045
1
            versioned_remove_all(txn.get(), partition_version_key);
3046
1
            err = txn->commit();
3047
1
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
1
        }
3052
3053
2
        if (ret == 0) {
3054
1
            ++num_recycled;
3055
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3056
1
            partition_keys.push_back(k);
3057
1
            if (part_pb.db_id() > 0) {
3058
1
                partition_version_keys.push_back(partition_version_key(
3059
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3060
1
            }
3061
1
            metrics_context.total_recycled_num = num_recycled;
3062
1
            metrics_context.report();
3063
1
        }
3064
2
        return ret;
3065
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2960
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2961
7
        ++num_scanned;
2962
7
        RecyclePartitionPB part_pb;
2963
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2964
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2965
0
            return -1;
2966
0
        }
2967
7
        int64_t current_time = ::time(nullptr);
2968
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2969
7
                                                            &earlest_ts)) { // not expired
2970
0
            return 0;
2971
0
        }
2972
7
        ++num_expired;
2973
        // decode partition_id
2974
7
        auto k1 = k;
2975
7
        k1.remove_prefix(1);
2976
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2977
7
        decode_key(&k1, &out);
2978
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2979
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2980
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2981
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2982
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2983
        // Change state to RECYCLING
2984
7
        std::unique_ptr<Transaction> txn;
2985
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2986
7
        if (err != TxnErrorCode::TXN_OK) {
2987
0
            LOG_WARNING("failed to create txn").tag("err", err);
2988
0
            return -1;
2989
0
        }
2990
7
        std::string val;
2991
7
        err = txn->get(k, &val);
2992
7
        if (err ==
2993
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2994
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2995
0
            return 0;
2996
0
        }
2997
7
        if (err != TxnErrorCode::TXN_OK) {
2998
0
            LOG_WARNING("failed to get kv");
2999
0
            return -1;
3000
0
        }
3001
7
        part_pb.Clear();
3002
7
        if (!part_pb.ParseFromString(val)) {
3003
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3004
0
            return -1;
3005
0
        }
3006
        // Partitions with PREPARED state MUST have no data
3007
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3008
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3009
7
            txn->put(k, part_pb.SerializeAsString());
3010
7
            err = txn->commit();
3011
7
            if (err != TxnErrorCode::TXN_OK) {
3012
0
                LOG_WARNING("failed to commit txn: {}", err);
3013
0
                return -1;
3014
0
            }
3015
7
        }
3016
3017
7
        int ret = 0;
3018
31
        for (int64_t index_id : part_pb.index_id()) {
3019
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3020
0
                LOG_WARNING("failed to recycle tablets under partition")
3021
0
                        .tag("table_id", part_pb.table_id())
3022
0
                        .tag("instance_id", instance_id_)
3023
0
                        .tag("index_id", index_id)
3024
0
                        .tag("partition_id", partition_id);
3025
0
                ret = -1;
3026
0
            }
3027
31
        }
3028
7
        if (ret == 0 && part_pb.has_db_id()) {
3029
            // Recycle the versioned keys
3030
7
            std::unique_ptr<Transaction> txn;
3031
7
            err = txn_kv_->create_txn(&txn);
3032
7
            if (err != TxnErrorCode::TXN_OK) {
3033
0
                LOG_WARNING("failed to create txn").tag("err", err);
3034
0
                return -1;
3035
0
            }
3036
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3037
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3038
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3039
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3040
7
            std::string partition_version_key =
3041
7
                    versioned::partition_version_key({instance_id_, partition_id});
3042
7
            versioned_remove_all(txn.get(), meta_key);
3043
7
            txn->remove(index_key);
3044
7
            txn->remove(inverted_index_key);
3045
7
            versioned_remove_all(txn.get(), partition_version_key);
3046
7
            err = txn->commit();
3047
7
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
7
        }
3052
3053
7
        if (ret == 0) {
3054
7
            ++num_recycled;
3055
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3056
7
            partition_keys.push_back(k);
3057
7
            if (part_pb.db_id() > 0) {
3058
7
                partition_version_keys.push_back(partition_version_key(
3059
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3060
7
            }
3061
7
            metrics_context.total_recycled_num = num_recycled;
3062
7
            metrics_context.report();
3063
7
        }
3064
7
        return ret;
3065
7
    };
3066
3067
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3068
5
        if (partition_keys.empty()) return 0;
3069
4
        DORIS_CLOUD_DEFER {
3070
4
            partition_keys.clear();
3071
4
            partition_version_keys.clear();
3072
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3069
1
        DORIS_CLOUD_DEFER {
3070
1
            partition_keys.clear();
3071
1
            partition_version_keys.clear();
3072
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3069
3
        DORIS_CLOUD_DEFER {
3070
3
            partition_keys.clear();
3071
3
            partition_version_keys.clear();
3072
3
        };
3073
4
        std::unique_ptr<Transaction> txn;
3074
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3075
4
        if (err != TxnErrorCode::TXN_OK) {
3076
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3077
0
            return -1;
3078
0
        }
3079
8
        for (auto& k : partition_keys) {
3080
8
            txn->remove(k);
3081
8
        }
3082
8
        for (auto& k : partition_version_keys) {
3083
8
            txn->remove(k);
3084
8
        }
3085
4
        err = txn->commit();
3086
4
        if (err != TxnErrorCode::TXN_OK) {
3087
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3088
0
                         << " err=" << err;
3089
0
            return -1;
3090
0
        }
3091
4
        return 0;
3092
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3067
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3068
2
        if (partition_keys.empty()) return 0;
3069
1
        DORIS_CLOUD_DEFER {
3070
1
            partition_keys.clear();
3071
1
            partition_version_keys.clear();
3072
1
        };
3073
1
        std::unique_ptr<Transaction> txn;
3074
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3075
1
        if (err != TxnErrorCode::TXN_OK) {
3076
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3077
0
            return -1;
3078
0
        }
3079
1
        for (auto& k : partition_keys) {
3080
1
            txn->remove(k);
3081
1
        }
3082
1
        for (auto& k : partition_version_keys) {
3083
1
            txn->remove(k);
3084
1
        }
3085
1
        err = txn->commit();
3086
1
        if (err != TxnErrorCode::TXN_OK) {
3087
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3088
0
                         << " err=" << err;
3089
0
            return -1;
3090
0
        }
3091
1
        return 0;
3092
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3067
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3068
3
        if (partition_keys.empty()) return 0;
3069
3
        DORIS_CLOUD_DEFER {
3070
3
            partition_keys.clear();
3071
3
            partition_version_keys.clear();
3072
3
        };
3073
3
        std::unique_ptr<Transaction> txn;
3074
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3075
3
        if (err != TxnErrorCode::TXN_OK) {
3076
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3077
0
            return -1;
3078
0
        }
3079
7
        for (auto& k : partition_keys) {
3080
7
            txn->remove(k);
3081
7
        }
3082
7
        for (auto& k : partition_version_keys) {
3083
7
            txn->remove(k);
3084
7
        }
3085
3
        err = txn->commit();
3086
3
        if (err != TxnErrorCode::TXN_OK) {
3087
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3088
0
                         << " err=" << err;
3089
0
            return -1;
3090
0
        }
3091
3
        return 0;
3092
3
    };
3093
3094
15
    if (config::enable_recycler_stats_metrics) {
3095
0
        scan_and_statistics_partitions();
3096
0
    }
3097
    // recycle_func and loop_done for scan and recycle
3098
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3099
15
}
3100
3101
14
int InstanceRecycler::recycle_versions() {
3102
14
    if (should_recycle_versioned_keys()) {
3103
2
        return recycle_orphan_partitions();
3104
2
    }
3105
3106
12
    int64_t num_scanned = 0;
3107
12
    int64_t num_recycled = 0;
3108
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3109
3110
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3111
3112
12
    auto start_time = steady_clock::now();
3113
3114
12
    DORIS_CLOUD_DEFER {
3115
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3116
12
        metrics_context.finish_report();
3117
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3118
12
                .tag("instance_id", instance_id_)
3119
12
                .tag("num_scanned", num_scanned)
3120
12
                .tag("num_recycled", num_recycled);
3121
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3114
12
    DORIS_CLOUD_DEFER {
3115
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3116
12
        metrics_context.finish_report();
3117
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3118
12
                .tag("instance_id", instance_id_)
3119
12
                .tag("num_scanned", num_scanned)
3120
12
                .tag("num_recycled", num_recycled);
3121
12
    };
3122
3123
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3124
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3125
12
    int64_t last_scanned_table_id = 0;
3126
12
    bool is_recycled = false; // Is last scanned kv recycled
3127
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3128
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3129
2
        ++num_scanned;
3130
2
        auto k1 = k;
3131
2
        k1.remove_prefix(1);
3132
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3133
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3134
2
        decode_key(&k1, &out);
3135
2
        DCHECK_EQ(out.size(), 6) << k;
3136
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3137
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3138
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3139
0
            return 0;
3140
0
        }
3141
2
        last_scanned_table_id = table_id;
3142
2
        is_recycled = false;
3143
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3144
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3145
2
        std::unique_ptr<Transaction> txn;
3146
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3147
2
        if (err != TxnErrorCode::TXN_OK) {
3148
0
            return -1;
3149
0
        }
3150
2
        std::unique_ptr<RangeGetIterator> iter;
3151
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3152
2
        if (err != TxnErrorCode::TXN_OK) {
3153
0
            return -1;
3154
0
        }
3155
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3156
1
            return 0;
3157
1
        }
3158
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3159
        // 1. Remove all partition version kvs of this table
3160
1
        auto partition_version_key_begin =
3161
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3162
1
        auto partition_version_key_end =
3163
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3164
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3165
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3166
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3167
1
                     << " table_id=" << table_id;
3168
        // 2. Remove the table version kv of this table
3169
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3170
1
        txn->remove(tbl_version_key);
3171
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3172
        // 3. Remove mow delete bitmap update lock and tablet job lock
3173
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3174
1
        txn->remove(lock_key);
3175
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3176
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3177
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3178
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3179
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3180
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3181
1
                     << " table_id=" << table_id;
3182
1
        err = txn->commit();
3183
1
        if (err != TxnErrorCode::TXN_OK) {
3184
0
            return -1;
3185
0
        }
3186
1
        metrics_context.total_recycled_num = ++num_recycled;
3187
1
        metrics_context.report();
3188
1
        is_recycled = true;
3189
1
        return 0;
3190
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3128
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3129
2
        ++num_scanned;
3130
2
        auto k1 = k;
3131
2
        k1.remove_prefix(1);
3132
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3133
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3134
2
        decode_key(&k1, &out);
3135
2
        DCHECK_EQ(out.size(), 6) << k;
3136
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3137
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3138
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3139
0
            return 0;
3140
0
        }
3141
2
        last_scanned_table_id = table_id;
3142
2
        is_recycled = false;
3143
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3144
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3145
2
        std::unique_ptr<Transaction> txn;
3146
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3147
2
        if (err != TxnErrorCode::TXN_OK) {
3148
0
            return -1;
3149
0
        }
3150
2
        std::unique_ptr<RangeGetIterator> iter;
3151
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3152
2
        if (err != TxnErrorCode::TXN_OK) {
3153
0
            return -1;
3154
0
        }
3155
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3156
1
            return 0;
3157
1
        }
3158
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3159
        // 1. Remove all partition version kvs of this table
3160
1
        auto partition_version_key_begin =
3161
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3162
1
        auto partition_version_key_end =
3163
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3164
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3165
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3166
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3167
1
                     << " table_id=" << table_id;
3168
        // 2. Remove the table version kv of this table
3169
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3170
1
        txn->remove(tbl_version_key);
3171
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3172
        // 3. Remove mow delete bitmap update lock and tablet job lock
3173
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3174
1
        txn->remove(lock_key);
3175
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3176
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3177
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3178
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3179
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3180
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3181
1
                     << " table_id=" << table_id;
3182
1
        err = txn->commit();
3183
1
        if (err != TxnErrorCode::TXN_OK) {
3184
0
            return -1;
3185
0
        }
3186
1
        metrics_context.total_recycled_num = ++num_recycled;
3187
1
        metrics_context.report();
3188
1
        is_recycled = true;
3189
1
        return 0;
3190
1
    };
3191
3192
12
    if (config::enable_recycler_stats_metrics) {
3193
0
        scan_and_statistics_versions();
3194
0
    }
3195
    // recycle_func and loop_done for scan and recycle
3196
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3197
14
}
3198
3199
3
int InstanceRecycler::recycle_orphan_partitions() {
3200
3
    int64_t num_scanned = 0;
3201
3
    int64_t num_recycled = 0;
3202
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3203
3204
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3205
3
            .tag("instance_id", instance_id_);
3206
3207
3
    auto start_time = steady_clock::now();
3208
3209
3
    DORIS_CLOUD_DEFER {
3210
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3211
3
        metrics_context.finish_report();
3212
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3213
3
                .tag("instance_id", instance_id_)
3214
3
                .tag("num_scanned", num_scanned)
3215
3
                .tag("num_recycled", num_recycled);
3216
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3209
3
    DORIS_CLOUD_DEFER {
3210
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3211
3
        metrics_context.finish_report();
3212
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3213
3
                .tag("instance_id", instance_id_)
3214
3
                .tag("num_scanned", num_scanned)
3215
3
                .tag("num_recycled", num_recycled);
3216
3
    };
3217
3218
3
    bool is_empty_table = false;        // whether the table has no indexes
3219
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3220
3
    int64_t current_table_id = 0;       // current scanning table id
3221
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3222
3
                         &current_table_id, &is_table_kvs_recycled,
3223
3
                         this](std::string_view k, std::string_view) {
3224
2
        ++num_scanned;
3225
3226
2
        std::string_view k1(k);
3227
2
        int64_t db_id, table_id, partition_id;
3228
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3229
2
                                                            &partition_id)) {
3230
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3231
0
            return -1;
3232
2
        } else if (table_id != current_table_id) {
3233
2
            current_table_id = table_id;
3234
2
            is_table_kvs_recycled = false;
3235
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3236
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3237
2
            if (err != TxnErrorCode::TXN_OK) {
3238
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3239
0
                             << " table_id=" << table_id << " err=" << err;
3240
0
                return -1;
3241
0
            }
3242
2
        }
3243
3244
2
        if (!is_empty_table) {
3245
            // table is not empty, skip recycle
3246
1
            return 0;
3247
1
        }
3248
3249
1
        std::unique_ptr<Transaction> txn;
3250
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3251
1
        if (err != TxnErrorCode::TXN_OK) {
3252
0
            return -1;
3253
0
        }
3254
3255
        // 1. Remove all partition related kvs
3256
1
        std::string partition_meta_key =
3257
1
                versioned::meta_partition_key({instance_id_, partition_id});
3258
1
        std::string partition_index_key =
3259
1
                versioned::partition_index_key({instance_id_, partition_id});
3260
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3261
1
                {instance_id_, db_id, table_id, partition_id});
3262
1
        std::string partition_version_key =
3263
1
                versioned::partition_version_key({instance_id_, partition_id});
3264
1
        txn->remove(partition_index_key);
3265
1
        txn->remove(partition_inverted_key);
3266
1
        versioned_remove_all(txn.get(), partition_meta_key);
3267
1
        versioned_remove_all(txn.get(), partition_version_key);
3268
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3269
1
                     << " table_id=" << table_id << " db_id=" << db_id
3270
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3271
1
                     << " partition_version_key=" << hex(partition_version_key);
3272
3273
1
        if (!is_table_kvs_recycled) {
3274
1
            is_table_kvs_recycled = true;
3275
3276
            // 2. Remove the table version kv of this table
3277
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3278
1
            versioned_remove_all(txn.get(), table_version_key);
3279
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3280
            // 3. Remove mow delete bitmap update lock and tablet job lock
3281
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3282
1
            txn->remove(lock_key);
3283
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3284
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3285
1
            std::string tablet_job_key_end =
3286
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3287
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3288
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3289
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3290
1
                         << " table_id=" << table_id;
3291
1
        }
3292
3293
1
        err = txn->commit();
3294
1
        if (err != TxnErrorCode::TXN_OK) {
3295
0
            return -1;
3296
0
        }
3297
1
        metrics_context.total_recycled_num = ++num_recycled;
3298
1
        metrics_context.report();
3299
1
        return 0;
3300
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3223
2
                         this](std::string_view k, std::string_view) {
3224
2
        ++num_scanned;
3225
3226
2
        std::string_view k1(k);
3227
2
        int64_t db_id, table_id, partition_id;
3228
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3229
2
                                                            &partition_id)) {
3230
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3231
0
            return -1;
3232
2
        } else if (table_id != current_table_id) {
3233
2
            current_table_id = table_id;
3234
2
            is_table_kvs_recycled = false;
3235
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3236
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3237
2
            if (err != TxnErrorCode::TXN_OK) {
3238
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3239
0
                             << " table_id=" << table_id << " err=" << err;
3240
0
                return -1;
3241
0
            }
3242
2
        }
3243
3244
2
        if (!is_empty_table) {
3245
            // table is not empty, skip recycle
3246
1
            return 0;
3247
1
        }
3248
3249
1
        std::unique_ptr<Transaction> txn;
3250
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3251
1
        if (err != TxnErrorCode::TXN_OK) {
3252
0
            return -1;
3253
0
        }
3254
3255
        // 1. Remove all partition related kvs
3256
1
        std::string partition_meta_key =
3257
1
                versioned::meta_partition_key({instance_id_, partition_id});
3258
1
        std::string partition_index_key =
3259
1
                versioned::partition_index_key({instance_id_, partition_id});
3260
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3261
1
                {instance_id_, db_id, table_id, partition_id});
3262
1
        std::string partition_version_key =
3263
1
                versioned::partition_version_key({instance_id_, partition_id});
3264
1
        txn->remove(partition_index_key);
3265
1
        txn->remove(partition_inverted_key);
3266
1
        versioned_remove_all(txn.get(), partition_meta_key);
3267
1
        versioned_remove_all(txn.get(), partition_version_key);
3268
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3269
1
                     << " table_id=" << table_id << " db_id=" << db_id
3270
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3271
1
                     << " partition_version_key=" << hex(partition_version_key);
3272
3273
1
        if (!is_table_kvs_recycled) {
3274
1
            is_table_kvs_recycled = true;
3275
3276
            // 2. Remove the table version kv of this table
3277
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3278
1
            versioned_remove_all(txn.get(), table_version_key);
3279
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3280
            // 3. Remove mow delete bitmap update lock and tablet job lock
3281
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3282
1
            txn->remove(lock_key);
3283
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3284
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3285
1
            std::string tablet_job_key_end =
3286
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3287
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3288
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3289
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3290
1
                         << " table_id=" << table_id;
3291
1
        }
3292
3293
1
        err = txn->commit();
3294
1
        if (err != TxnErrorCode::TXN_OK) {
3295
0
            return -1;
3296
0
        }
3297
1
        metrics_context.total_recycled_num = ++num_recycled;
3298
1
        metrics_context.report();
3299
1
        return 0;
3300
1
    };
3301
3302
    // recycle_func and loop_done for scan and recycle
3303
3
    return scan_and_recycle(
3304
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3305
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3306
3
            std::move(recycle_func));
3307
3
}
3308
3309
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3310
                                      RecyclerMetricsContext& metrics_context,
3311
52
                                      int64_t partition_id) {
3312
52
    bool is_multi_version =
3313
52
            instance_info_.has_multi_version_status() &&
3314
52
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3315
52
    int64_t num_scanned = 0;
3316
52
    std::atomic_long num_recycled = 0;
3317
3318
52
    std::string tablet_key_begin, tablet_key_end;
3319
52
    std::string stats_key_begin, stats_key_end;
3320
52
    std::string job_key_begin, job_key_end;
3321
3322
52
    std::string tablet_belongs;
3323
52
    if (partition_id > 0) {
3324
        // recycle tablets in a partition belonging to the index
3325
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3326
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3327
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3328
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3329
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3330
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3331
33
        tablet_belongs = "partition";
3332
33
    } else {
3333
        // recycle tablets in the index
3334
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3335
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3336
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3337
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3338
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3339
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3340
19
        tablet_belongs = "index";
3341
19
    }
3342
3343
52
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3344
52
            .tag("table_id", table_id)
3345
52
            .tag("index_id", index_id)
3346
52
            .tag("partition_id", partition_id);
3347
3348
52
    auto start_time = steady_clock::now();
3349
3350
52
    DORIS_CLOUD_DEFER {
3351
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3352
52
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3353
52
                .tag("instance_id", instance_id_)
3354
52
                .tag("table_id", table_id)
3355
52
                .tag("index_id", index_id)
3356
52
                .tag("partition_id", partition_id)
3357
52
                .tag("num_scanned", num_scanned)
3358
52
                .tag("num_recycled", num_recycled);
3359
52
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3350
4
    DORIS_CLOUD_DEFER {
3351
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3352
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3353
4
                .tag("instance_id", instance_id_)
3354
4
                .tag("table_id", table_id)
3355
4
                .tag("index_id", index_id)
3356
4
                .tag("partition_id", partition_id)
3357
4
                .tag("num_scanned", num_scanned)
3358
4
                .tag("num_recycled", num_recycled);
3359
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3350
48
    DORIS_CLOUD_DEFER {
3351
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3352
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3353
48
                .tag("instance_id", instance_id_)
3354
48
                .tag("table_id", table_id)
3355
48
                .tag("index_id", index_id)
3356
48
                .tag("partition_id", partition_id)
3357
48
                .tag("num_scanned", num_scanned)
3358
48
                .tag("num_recycled", num_recycled);
3359
48
    };
3360
3361
    // The tablet key and id which have been recycled.
3362
52
    struct TabletInfo {
3363
52
        std::string_view tablet_meta_key;
3364
52
        int64_t tablet_id;
3365
52
    };
3366
52
    SyncExecutor<TabletInfo> sync_executor(
3367
52
            _thread_pool_group.recycle_tablet_pool,
3368
52
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3369
52
                        index_id, partition_id),
3370
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3370
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3370
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3371
3372
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3373
52
    std::vector<std::string> init_rs_keys;
3374
52
    bool has_failure = false;
3375
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3376
8.25k
        ++num_scanned;
3377
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3378
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3379
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3380
0
            has_failure = true;
3381
0
            return -1;
3382
0
        }
3383
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3384
3385
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3386
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3387
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3388
4.00k
            has_failure = true;
3389
4.00k
            return -1;
3390
4.00k
        }
3391
3392
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3393
4.25k
        sync_executor.add(
3394
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3395
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3396
2
                        LOG_WARNING("failed to recycle tablet")
3397
2
                                .tag("instance_id", instance_id_)
3398
2
                                .tag("tablet_id", tid);
3399
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3400
2
                    }
3401
4.25k
                    ++num_recycled;
3402
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3403
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3404
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3394
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3395
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3396
0
                        LOG_WARNING("failed to recycle tablet")
3397
0
                                .tag("instance_id", instance_id_)
3398
0
                                .tag("tablet_id", tid);
3399
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3400
0
                    }
3401
4.00k
                    ++num_recycled;
3402
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3403
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3404
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3394
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3395
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3396
2
                        LOG_WARNING("failed to recycle tablet")
3397
2
                                .tag("instance_id", instance_id_)
3398
2
                                .tag("tablet_id", tid);
3399
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3400
2
                    }
3401
248
                    ++num_recycled;
3402
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3403
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3404
250
                });
3405
4.25k
        return 0;
3406
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3375
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3376
8.00k
        ++num_scanned;
3377
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3378
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3379
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3380
0
            has_failure = true;
3381
0
            return -1;
3382
0
        }
3383
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3384
3385
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3386
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3387
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3388
4.00k
            has_failure = true;
3389
4.00k
            return -1;
3390
4.00k
        }
3391
3392
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3393
4.00k
        sync_executor.add(
3394
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3395
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3396
4.00k
                        LOG_WARNING("failed to recycle tablet")
3397
4.00k
                                .tag("instance_id", instance_id_)
3398
4.00k
                                .tag("tablet_id", tid);
3399
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3400
4.00k
                    }
3401
4.00k
                    ++num_recycled;
3402
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3403
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3404
4.00k
                });
3405
4.00k
        return 0;
3406
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3375
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3376
251
        ++num_scanned;
3377
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3378
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3379
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3380
0
            has_failure = true;
3381
0
            return -1;
3382
0
        }
3383
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3384
3385
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3386
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3387
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3388
1
            has_failure = true;
3389
1
            return -1;
3390
1
        }
3391
3392
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3393
250
        sync_executor.add(
3394
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3395
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3396
250
                        LOG_WARNING("failed to recycle tablet")
3397
250
                                .tag("instance_id", instance_id_)
3398
250
                                .tag("tablet_id", tid);
3399
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3400
250
                    }
3401
250
                    ++num_recycled;
3402
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3403
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3404
250
                });
3405
250
        return 0;
3406
250
    };
3407
3408
52
    auto loop_done = [&, this]() -> int {
3409
52
        int ret = 0;
3410
52
        bool finished = true;
3411
52
        bool has_empty_key = false;
3412
52
        DORIS_CLOUD_DEFER {
3413
52
            init_rs_keys.clear();
3414
52
            has_failure = false;
3415
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3412
4
        DORIS_CLOUD_DEFER {
3413
4
            init_rs_keys.clear();
3414
4
            has_failure = false;
3415
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3412
48
        DORIS_CLOUD_DEFER {
3413
48
            init_rs_keys.clear();
3414
48
            has_failure = false;
3415
48
        };
3416
52
        auto tablets_info = sync_executor.when_all(&finished);
3417
52
        if (!finished) {
3418
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3419
1
            return -1;
3420
1
        }
3421
3422
51
        size_t size_before_erase = tablets_info.size();
3423
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3423
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3423
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3424
51
        if (tablets_info.empty()) {
3425
2
            return size_before_erase == 0 ? 0 : -1;
3426
49
        } else if (size_before_erase != tablets_info.size()) {
3427
1
            has_empty_key = true;
3428
1
        }
3429
3430
49
        ret = has_empty_key ? -1 : 0;
3431
        // sort the vector using key's order
3432
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3433
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3434
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3432
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3433
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3434
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3432
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3433
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3434
958
        });
3435
49
        std::unique_ptr<Transaction> txn;
3436
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3437
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3438
0
            return -1;
3439
0
        }
3440
49
        std::string tablet_key_end;
3441
49
        if (!tablets_info.empty()) {
3442
49
            if (!has_empty_key && !has_failure) {
3443
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3444
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3445
47
            } else {
3446
8
                for (auto& tablet_info : tablets_info) {
3447
8
                    txn->remove(tablet_info.tablet_meta_key);
3448
8
                }
3449
2
            }
3450
49
        }
3451
49
        if (is_multi_version) {
3452
6
            for (auto& tablet_info : tablets_info) {
3453
                // Remove all versions of tablet compact stats for recycled tablet
3454
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3455
6
                LOG_INFO("remove versioned tablet compact stats key")
3456
6
                        .tag("compact_stats_key", hex(k));
3457
6
                versioned_remove_all(txn.get(), k);
3458
6
            }
3459
6
            for (auto& tablet_info : tablets_info) {
3460
                // Remove all versions of tablet load stats for recycled tablet
3461
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3462
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3463
6
                versioned_remove_all(txn.get(), k);
3464
6
            }
3465
6
            for (auto& tablet_info : tablets_info) {
3466
                // Remove all versions of meta tablet for recycled tablet
3467
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3468
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3469
6
                versioned_remove_all(txn.get(), k);
3470
6
            }
3471
5
        }
3472
4.25k
        for (auto& tablet_info : tablets_info) {
3473
4.25k
            std::string k;
3474
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3475
4.25k
            txn->remove(k);
3476
4.25k
        }
3477
4.25k
        for (auto& tablet_info : tablets_info) {
3478
4.25k
            std::string k;
3479
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3480
4.25k
            txn->remove(k);
3481
4.25k
        }
3482
49
        for (auto& k : init_rs_keys) {
3483
0
            txn->remove(k);
3484
0
        }
3485
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3487
0
                         << ", err=" << err;
3488
0
            return -1;
3489
0
        }
3490
49
        return ret;
3491
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3408
4
    auto loop_done = [&, this]() -> int {
3409
4
        int ret = 0;
3410
4
        bool finished = true;
3411
4
        bool has_empty_key = false;
3412
4
        DORIS_CLOUD_DEFER {
3413
4
            init_rs_keys.clear();
3414
4
            has_failure = false;
3415
4
        };
3416
4
        auto tablets_info = sync_executor.when_all(&finished);
3417
4
        if (!finished) {
3418
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3419
0
            return -1;
3420
0
        }
3421
3422
4
        size_t size_before_erase = tablets_info.size();
3423
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3424
4
        if (tablets_info.empty()) {
3425
2
            return size_before_erase == 0 ? 0 : -1;
3426
2
        } else if (size_before_erase != tablets_info.size()) {
3427
0
            has_empty_key = true;
3428
0
        }
3429
3430
2
        ret = has_empty_key ? -1 : 0;
3431
        // sort the vector using key's order
3432
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3433
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3434
2
        });
3435
2
        std::unique_ptr<Transaction> txn;
3436
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3437
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3438
0
            return -1;
3439
0
        }
3440
2
        std::string tablet_key_end;
3441
2
        if (!tablets_info.empty()) {
3442
2
            if (!has_empty_key && !has_failure) {
3443
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3444
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3445
2
            } else {
3446
0
                for (auto& tablet_info : tablets_info) {
3447
0
                    txn->remove(tablet_info.tablet_meta_key);
3448
0
                }
3449
0
            }
3450
2
        }
3451
2
        if (is_multi_version) {
3452
0
            for (auto& tablet_info : tablets_info) {
3453
                // Remove all versions of tablet compact stats for recycled tablet
3454
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3455
0
                LOG_INFO("remove versioned tablet compact stats key")
3456
0
                        .tag("compact_stats_key", hex(k));
3457
0
                versioned_remove_all(txn.get(), k);
3458
0
            }
3459
0
            for (auto& tablet_info : tablets_info) {
3460
                // Remove all versions of tablet load stats for recycled tablet
3461
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3462
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3463
0
                versioned_remove_all(txn.get(), k);
3464
0
            }
3465
0
            for (auto& tablet_info : tablets_info) {
3466
                // Remove all versions of meta tablet for recycled tablet
3467
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3468
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3469
0
                versioned_remove_all(txn.get(), k);
3470
0
            }
3471
0
        }
3472
4.00k
        for (auto& tablet_info : tablets_info) {
3473
4.00k
            std::string k;
3474
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3475
4.00k
            txn->remove(k);
3476
4.00k
        }
3477
4.00k
        for (auto& tablet_info : tablets_info) {
3478
4.00k
            std::string k;
3479
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3480
4.00k
            txn->remove(k);
3481
4.00k
        }
3482
2
        for (auto& k : init_rs_keys) {
3483
0
            txn->remove(k);
3484
0
        }
3485
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3487
0
                         << ", err=" << err;
3488
0
            return -1;
3489
0
        }
3490
2
        return ret;
3491
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3408
48
    auto loop_done = [&, this]() -> int {
3409
48
        int ret = 0;
3410
48
        bool finished = true;
3411
48
        bool has_empty_key = false;
3412
48
        DORIS_CLOUD_DEFER {
3413
48
            init_rs_keys.clear();
3414
48
            has_failure = false;
3415
48
        };
3416
48
        auto tablets_info = sync_executor.when_all(&finished);
3417
48
        if (!finished) {
3418
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3419
1
            return -1;
3420
1
        }
3421
3422
47
        size_t size_before_erase = tablets_info.size();
3423
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3424
47
        if (tablets_info.empty()) {
3425
0
            return size_before_erase == 0 ? 0 : -1;
3426
47
        } else if (size_before_erase != tablets_info.size()) {
3427
1
            has_empty_key = true;
3428
1
        }
3429
3430
47
        ret = has_empty_key ? -1 : 0;
3431
        // sort the vector using key's order
3432
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3433
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3434
47
        });
3435
47
        std::unique_ptr<Transaction> txn;
3436
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3437
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3438
0
            return -1;
3439
0
        }
3440
47
        std::string tablet_key_end;
3441
47
        if (!tablets_info.empty()) {
3442
47
            if (!has_empty_key && !has_failure) {
3443
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3444
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3445
45
            } else {
3446
8
                for (auto& tablet_info : tablets_info) {
3447
8
                    txn->remove(tablet_info.tablet_meta_key);
3448
8
                }
3449
2
            }
3450
47
        }
3451
47
        if (is_multi_version) {
3452
6
            for (auto& tablet_info : tablets_info) {
3453
                // Remove all versions of tablet compact stats for recycled tablet
3454
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3455
6
                LOG_INFO("remove versioned tablet compact stats key")
3456
6
                        .tag("compact_stats_key", hex(k));
3457
6
                versioned_remove_all(txn.get(), k);
3458
6
            }
3459
6
            for (auto& tablet_info : tablets_info) {
3460
                // Remove all versions of tablet load stats for recycled tablet
3461
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3462
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3463
6
                versioned_remove_all(txn.get(), k);
3464
6
            }
3465
6
            for (auto& tablet_info : tablets_info) {
3466
                // Remove all versions of meta tablet for recycled tablet
3467
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3468
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3469
6
                versioned_remove_all(txn.get(), k);
3470
6
            }
3471
5
        }
3472
248
        for (auto& tablet_info : tablets_info) {
3473
248
            std::string k;
3474
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3475
248
            txn->remove(k);
3476
248
        }
3477
248
        for (auto& tablet_info : tablets_info) {
3478
248
            std::string k;
3479
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3480
248
            txn->remove(k);
3481
248
        }
3482
47
        for (auto& k : init_rs_keys) {
3483
0
            txn->remove(k);
3484
0
        }
3485
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3487
0
                         << ", err=" << err;
3488
0
            return -1;
3489
0
        }
3490
47
        return ret;
3491
47
    };
3492
3493
52
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3494
52
                               std::move(loop_done));
3495
52
    if (ret != 0) {
3496
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3497
5
        return ret;
3498
5
    }
3499
3500
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3501
47
    std::unique_ptr<Transaction> txn;
3502
47
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3503
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3504
0
        return -1;
3505
0
    }
3506
47
    txn->remove(stats_key_begin, stats_key_end);
3507
47
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3508
47
                 << " end=" << hex(stats_key_end);
3509
47
    txn->remove(job_key_begin, job_key_end);
3510
47
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3511
47
    std::string schema_key_begin, schema_key_end;
3512
47
    std::string schema_dict_key;
3513
47
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3514
47
    if (partition_id <= 0) {
3515
        // Delete schema kv of this index
3516
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3517
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3518
15
        txn->remove(schema_key_begin, schema_key_end);
3519
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3520
15
                     << " end=" << hex(schema_key_end);
3521
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3522
15
        txn->remove(schema_dict_key);
3523
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3524
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3525
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3526
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3527
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3528
15
                     << " end=" << hex(versioned_schema_key_end);
3529
15
    }
3530
3531
47
    TxnErrorCode err = txn->commit();
3532
47
    if (err != TxnErrorCode::TXN_OK) {
3533
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3534
0
                     << " err=" << err;
3535
0
        return -1;
3536
0
    }
3537
3538
47
    return ret;
3539
47
}
3540
3541
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3542
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3543
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3544
5.61k
    if (num_segments <= 0) return 0;
3545
3546
5.61k
    std::vector<std::string> file_paths;
3547
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3548
0
        return -1;
3549
0
    }
3550
3551
    // Process inverted indexes
3552
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3553
    // default format as v1.
3554
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3555
5.61k
    bool delete_rowset_data_by_prefix = false;
3556
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3557
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3558
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3559
0
        delete_rowset_data_by_prefix = true;
3560
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3561
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3562
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3563
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3564
10.0k
            }
3565
10.0k
        }
3566
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3567
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3568
2.00k
        }
3569
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3570
        // schema version and index id are not found, delete rowset data by prefix directly.
3571
0
        delete_rowset_data_by_prefix = true;
3572
809
    } else {
3573
        // otherwise, try to get schema kv
3574
809
        InvertedIndexInfo index_info;
3575
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3576
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3577
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3578
809
                                 &inverted_index_get_ret);
3579
809
        if (inverted_index_get_ret == 0) {
3580
809
            index_format = index_info.first;
3581
809
            index_ids = index_info.second;
3582
809
        } else if (inverted_index_get_ret == 1) {
3583
            // 1. Schema kv not found means tablet has been recycled
3584
            // Maybe some tablet recycle failed by some bugs
3585
            // We need to delete again to double check
3586
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3587
            // because we are uncertain about the inverted index information.
3588
            // If there are inverted indexes, some data might not be deleted,
3589
            // but this is acceptable as we have made our best effort to delete the data.
3590
0
            LOG_INFO(
3591
0
                    "delete rowset data schema kv not found, need to delete again to double "
3592
0
                    "check")
3593
0
                    .tag("instance_id", instance_id_)
3594
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3595
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3596
            // Currently index_ids is guaranteed to be empty,
3597
            // but we clear it again here as a safeguard against future code changes
3598
            // that might cause index_ids to no longer be empty
3599
0
            index_format = InvertedIndexStorageFormatPB::V2;
3600
0
            index_ids.clear();
3601
0
        } else {
3602
            // failed to get schema kv, delete rowset data by prefix directly.
3603
0
            delete_rowset_data_by_prefix = true;
3604
0
        }
3605
809
    }
3606
3607
5.61k
    if (delete_rowset_data_by_prefix) {
3608
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3609
0
                                  rs_meta_pb.rowset_id_v2());
3610
0
    }
3611
3612
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3613
5.61k
    if (it == accessor_map_.end()) {
3614
1.59k
        LOG_WARNING("instance has no such resource id")
3615
1.59k
                .tag("instance_id", instance_id_)
3616
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3617
1.59k
        return -1;
3618
1.59k
    }
3619
4.01k
    auto& accessor = it->second;
3620
3621
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3622
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3623
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3624
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3625
20.0k
                                         &file_paths);
3626
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3627
40.0k
            for (const auto& index_id : index_ids) {
3628
40.0k
                add_file_to_delete_if_not_packed(
3629
40.0k
                        rs_meta_pb,
3630
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3631
40.0k
                                               index_id.second),
3632
40.0k
                        &file_paths);
3633
40.0k
            }
3634
20.0k
        } else if (!index_ids.empty()) {
3635
0
            add_file_to_delete_if_not_packed(
3636
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3637
0
        }
3638
20.0k
    }
3639
3640
    // Process delete bitmap - check where it's stored.
3641
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3642
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3643
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3644
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3645
0
                .tag("instance_id", instance_id_)
3646
0
                .tag("tablet_id", tablet_id)
3647
0
                .tag("rowset_id", rowset_id);
3648
0
        return -1;
3649
0
    }
3650
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3651
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3652
2.00k
    }
3653
    // TODO(AlexYue): seems could do do batch
3654
4.01k
    return accessor->delete_files(file_paths);
3655
4.01k
}
3656
3657
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3658
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3659
62.6k
            .tag("instance_id", instance_id_)
3660
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3661
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3662
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3663
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3664
62.6k
    if (index_map.empty()) {
3665
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3666
62.6k
                .tag("instance_id", instance_id_)
3667
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3668
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3669
62.6k
        return 0;
3670
62.6k
    }
3671
3672
18
    struct PackedSmallFileInfo {
3673
18
        std::string small_file_path;
3674
18
    };
3675
18
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3676
18
    packed_file_updates.reserve(index_map.size());
3677
27
    for (const auto& [small_path, index_pb] : index_map) {
3678
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3679
0
            continue;
3680
0
        }
3681
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3682
27
                PackedSmallFileInfo {small_path});
3683
27
    }
3684
18
    if (packed_file_updates.empty()) {
3685
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3686
0
                .tag("instance_id", instance_id_)
3687
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3688
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3689
0
                .tag("index_map_size", index_map.size());
3690
0
        return 0;
3691
0
    }
3692
3693
18
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3694
18
    int ret = 0;
3695
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3696
24
        if (small_files.empty()) {
3697
0
            continue;
3698
0
        }
3699
3700
24
        bool success = false;
3701
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3702
24
            std::unique_ptr<Transaction> txn;
3703
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3704
24
            if (err != TxnErrorCode::TXN_OK) {
3705
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3706
0
                        .tag("instance_id", instance_id_)
3707
0
                        .tag("packed_file_path", packed_file_path)
3708
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3709
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3710
0
                        .tag("err", err);
3711
0
                ret = -1;
3712
0
                break;
3713
0
            }
3714
3715
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3716
24
            std::string packed_val;
3717
24
            err = txn->get(packed_key, &packed_val);
3718
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3719
0
                LOG_WARNING("packed file info not found when recycling rowset")
3720
0
                        .tag("instance_id", instance_id_)
3721
0
                        .tag("packed_file_path", packed_file_path)
3722
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3723
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3724
0
                        .tag("key", hex(packed_key))
3725
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3726
                // Skip this packed file entry and continue with others
3727
0
                success = true;
3728
0
                break;
3729
0
            }
3730
24
            if (err != TxnErrorCode::TXN_OK) {
3731
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3732
0
                        .tag("instance_id", instance_id_)
3733
0
                        .tag("packed_file_path", packed_file_path)
3734
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3735
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3736
0
                        .tag("err", err);
3737
0
                ret = -1;
3738
0
                break;
3739
0
            }
3740
3741
24
            cloud::PackedFileInfoPB packed_info;
3742
24
            if (!packed_info.ParseFromString(packed_val)) {
3743
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3744
0
                        .tag("instance_id", instance_id_)
3745
0
                        .tag("packed_file_path", packed_file_path)
3746
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3747
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3748
0
                ret = -1;
3749
0
                break;
3750
0
            }
3751
3752
24
            LOG_INFO("packed file update check")
3753
24
                    .tag("instance_id", instance_id_)
3754
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3755
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3756
24
                    .tag("merged_file_path", packed_file_path)
3757
24
                    .tag("requested_small_files", small_files.size())
3758
24
                    .tag("merge_entries", packed_info.slices_size());
3759
3760
24
            auto* small_file_entries = packed_info.mutable_slices();
3761
24
            int64_t changed_files = 0;
3762
24
            int64_t missing_entries = 0;
3763
24
            int64_t already_deleted = 0;
3764
27
            for (const auto& small_file_info : small_files) {
3765
27
                bool found = false;
3766
87
                for (auto& small_file_entry : *small_file_entries) {
3767
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3768
27
                        if (!small_file_entry.deleted()) {
3769
27
                            small_file_entry.set_deleted(true);
3770
27
                            if (!small_file_entry.corrected()) {
3771
27
                                small_file_entry.set_corrected(true);
3772
27
                            }
3773
27
                            ++changed_files;
3774
27
                        } else {
3775
0
                            ++already_deleted;
3776
0
                        }
3777
27
                        found = true;
3778
27
                        break;
3779
27
                    }
3780
87
                }
3781
27
                if (!found) {
3782
0
                    ++missing_entries;
3783
0
                    LOG_WARNING("packed file info missing small file entry")
3784
0
                            .tag("instance_id", instance_id_)
3785
0
                            .tag("packed_file_path", packed_file_path)
3786
0
                            .tag("small_file_path", small_file_info.small_file_path)
3787
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3788
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3789
0
                }
3790
27
            }
3791
3792
24
            if (changed_files == 0) {
3793
0
                LOG_INFO("skip merge file update: no merge entries changed")
3794
0
                        .tag("instance_id", instance_id_)
3795
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3796
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3797
0
                        .tag("merged_file_path", packed_file_path)
3798
0
                        .tag("missing_entries", missing_entries)
3799
0
                        .tag("already_deleted", already_deleted)
3800
0
                        .tag("requested_small_files", small_files.size())
3801
0
                        .tag("merge_entries", packed_info.slices_size());
3802
0
                success = true;
3803
0
                break;
3804
0
            }
3805
3806
            // Calculate remaining files
3807
24
            int64_t left_file_count = 0;
3808
24
            int64_t left_file_bytes = 0;
3809
141
            for (const auto& small_file_entry : packed_info.slices()) {
3810
141
                if (!small_file_entry.deleted()) {
3811
57
                    ++left_file_count;
3812
57
                    left_file_bytes += small_file_entry.size();
3813
57
                }
3814
141
            }
3815
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3816
24
            packed_info.set_ref_cnt(left_file_count);
3817
24
            LOG_INFO("updated packed file reference info")
3818
24
                    .tag("instance_id", instance_id_)
3819
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3820
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3821
24
                    .tag("packed_file_path", packed_file_path)
3822
24
                    .tag("ref_cnt", left_file_count)
3823
24
                    .tag("left_file_bytes", left_file_bytes);
3824
3825
24
            if (left_file_count == 0) {
3826
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3827
7
            }
3828
3829
24
            std::string updated_val;
3830
24
            if (!packed_info.SerializeToString(&updated_val)) {
3831
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3832
0
                        .tag("instance_id", instance_id_)
3833
0
                        .tag("packed_file_path", packed_file_path)
3834
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3835
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3836
0
                ret = -1;
3837
0
                break;
3838
0
            }
3839
3840
24
            txn->put(packed_key, updated_val);
3841
24
            err = txn->commit();
3842
24
            if (err == TxnErrorCode::TXN_OK) {
3843
24
                success = true;
3844
24
                if (left_file_count == 0) {
3845
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3846
7
                            .tag("instance_id", instance_id_)
3847
7
                            .tag("packed_file_path", packed_file_path);
3848
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3849
0
                        ret = -1;
3850
0
                    }
3851
7
                }
3852
24
                break;
3853
24
            }
3854
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3855
0
                if (attempt >= max_retry_times) {
3856
0
                    LOG_WARNING("packed file info update conflict after max retry")
3857
0
                            .tag("instance_id", instance_id_)
3858
0
                            .tag("packed_file_path", packed_file_path)
3859
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3860
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3861
0
                            .tag("changed_files", changed_files)
3862
0
                            .tag("attempt", attempt);
3863
0
                    ret = -1;
3864
0
                    break;
3865
0
                }
3866
0
                LOG_WARNING("packed file info update conflict, retrying")
3867
0
                        .tag("instance_id", instance_id_)
3868
0
                        .tag("packed_file_path", packed_file_path)
3869
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3870
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3871
0
                        .tag("changed_files", changed_files)
3872
0
                        .tag("attempt", attempt);
3873
0
                sleep_for_packed_file_retry();
3874
0
                continue;
3875
0
            }
3876
3877
0
            LOG_WARNING("failed to commit packed file info update")
3878
0
                    .tag("instance_id", instance_id_)
3879
0
                    .tag("packed_file_path", packed_file_path)
3880
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3881
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3882
0
                    .tag("err", err)
3883
0
                    .tag("changed_files", changed_files);
3884
0
            ret = -1;
3885
0
            break;
3886
0
        }
3887
3888
24
        if (!success) {
3889
0
            ret = -1;
3890
0
        }
3891
24
    }
3892
3893
18
    return ret;
3894
18
}
3895
3896
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3897
        int64_t tablet_id, const std::string& rowset_id,
3898
58.4k
        DeleteBitmapStorageType* out_storage_type) {
3899
58.4k
    if (out_storage_type) {
3900
58.4k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3901
58.4k
    }
3902
3903
    // Get delete bitmap storage info from FDB
3904
58.4k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3905
58.4k
    std::unique_ptr<Transaction> txn;
3906
58.4k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3907
58.4k
    if (err != TxnErrorCode::TXN_OK) {
3908
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3909
0
                .tag("instance_id", instance_id_)
3910
0
                .tag("tablet_id", tablet_id)
3911
0
                .tag("rowset_id", rowset_id)
3912
0
                .tag("err", err);
3913
0
        return -1;
3914
0
    }
3915
3916
58.4k
    ValueBuf dbm_val;
3917
58.4k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
3918
58.4k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3919
        // No delete bitmap for this rowset, nothing to do
3920
4.89k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3921
4.89k
                .tag("instance_id", instance_id_)
3922
4.89k
                .tag("tablet_id", tablet_id)
3923
4.89k
                .tag("rowset_id", rowset_id);
3924
4.89k
        return 0;
3925
4.89k
    }
3926
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3927
0
        LOG_WARNING("failed to get delete bitmap storage")
3928
0
                .tag("instance_id", instance_id_)
3929
0
                .tag("tablet_id", tablet_id)
3930
0
                .tag("rowset_id", rowset_id)
3931
0
                .tag("err", err);
3932
0
        return -1;
3933
0
    }
3934
3935
53.5k
    DeleteBitmapStoragePB storage;
3936
53.5k
    if (!dbm_val.to_pb(&storage)) {
3937
0
        LOG_WARNING("failed to parse delete bitmap storage")
3938
0
                .tag("instance_id", instance_id_)
3939
0
                .tag("tablet_id", tablet_id)
3940
0
                .tag("rowset_id", rowset_id);
3941
0
        return -1;
3942
0
    }
3943
3944
53.5k
    if (storage.store_in_fdb()) {
3945
0
        if (out_storage_type) {
3946
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3947
0
        }
3948
0
        return 0;
3949
0
    }
3950
3951
    // Check if delete bitmap is stored in standalone file.
3952
53.5k
    if (!storage.has_packed_slice_location() ||
3953
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3954
53.5k
        if (out_storage_type) {
3955
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3956
53.5k
        }
3957
53.5k
        return 0;
3958
53.5k
    }
3959
3960
18.4E
    if (out_storage_type) {
3961
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3962
0
    }
3963
3964
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3965
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3966
3967
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3968
18.4E
            .tag("instance_id", instance_id_)
3969
18.4E
            .tag("tablet_id", tablet_id)
3970
18.4E
            .tag("rowset_id", rowset_id)
3971
18.4E
            .tag("packed_file_path", packed_file_path);
3972
3973
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3974
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3975
0
        std::unique_ptr<Transaction> update_txn;
3976
0
        err = txn_kv_->create_txn(&update_txn);
3977
0
        if (err != TxnErrorCode::TXN_OK) {
3978
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3979
0
                    .tag("instance_id", instance_id_)
3980
0
                    .tag("tablet_id", tablet_id)
3981
0
                    .tag("rowset_id", rowset_id)
3982
0
                    .tag("err", err);
3983
0
            return -1;
3984
0
        }
3985
3986
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3987
0
        std::string packed_val;
3988
0
        err = update_txn->get(packed_key, &packed_val);
3989
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3990
0
            LOG_WARNING("packed file info not found for delete bitmap")
3991
0
                    .tag("instance_id", instance_id_)
3992
0
                    .tag("tablet_id", tablet_id)
3993
0
                    .tag("rowset_id", rowset_id)
3994
0
                    .tag("packed_file_path", packed_file_path);
3995
0
            return 0;
3996
0
        }
3997
0
        if (err != TxnErrorCode::TXN_OK) {
3998
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3999
0
                    .tag("instance_id", instance_id_)
4000
0
                    .tag("tablet_id", tablet_id)
4001
0
                    .tag("rowset_id", rowset_id)
4002
0
                    .tag("packed_file_path", packed_file_path)
4003
0
                    .tag("err", err);
4004
0
            return -1;
4005
0
        }
4006
4007
0
        cloud::PackedFileInfoPB packed_info;
4008
0
        if (!packed_info.ParseFromString(packed_val)) {
4009
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4010
0
                    .tag("instance_id", instance_id_)
4011
0
                    .tag("tablet_id", tablet_id)
4012
0
                    .tag("rowset_id", rowset_id)
4013
0
                    .tag("packed_file_path", packed_file_path);
4014
0
            return -1;
4015
0
        }
4016
4017
        // Find and mark the small file entry as deleted
4018
        // Use tablet_id and rowset_id to match entry instead of path,
4019
        // because path format may vary with path_version (with or without shard prefix)
4020
0
        auto* entries = packed_info.mutable_slices();
4021
0
        bool found = false;
4022
0
        bool already_deleted = false;
4023
0
        for (auto& entry : *entries) {
4024
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4025
0
                if (!entry.deleted()) {
4026
0
                    entry.set_deleted(true);
4027
0
                    if (!entry.corrected()) {
4028
0
                        entry.set_corrected(true);
4029
0
                    }
4030
0
                } else {
4031
0
                    already_deleted = true;
4032
0
                }
4033
0
                found = true;
4034
0
                break;
4035
0
            }
4036
0
        }
4037
4038
0
        if (!found) {
4039
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4040
0
                    .tag("instance_id", instance_id_)
4041
0
                    .tag("tablet_id", tablet_id)
4042
0
                    .tag("rowset_id", rowset_id)
4043
0
                    .tag("packed_file_path", packed_file_path);
4044
0
            return 0;
4045
0
        }
4046
4047
0
        if (already_deleted) {
4048
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4049
0
                    .tag("instance_id", instance_id_)
4050
0
                    .tag("tablet_id", tablet_id)
4051
0
                    .tag("rowset_id", rowset_id)
4052
0
                    .tag("packed_file_path", packed_file_path);
4053
0
            return 0;
4054
0
        }
4055
4056
        // Calculate remaining files
4057
0
        int64_t left_file_count = 0;
4058
0
        int64_t left_file_bytes = 0;
4059
0
        for (const auto& entry : packed_info.slices()) {
4060
0
            if (!entry.deleted()) {
4061
0
                ++left_file_count;
4062
0
                left_file_bytes += entry.size();
4063
0
            }
4064
0
        }
4065
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4066
0
        packed_info.set_ref_cnt(left_file_count);
4067
4068
0
        if (left_file_count == 0) {
4069
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4070
0
        }
4071
4072
0
        std::string updated_val;
4073
0
        if (!packed_info.SerializeToString(&updated_val)) {
4074
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4075
0
                    .tag("instance_id", instance_id_)
4076
0
                    .tag("tablet_id", tablet_id)
4077
0
                    .tag("rowset_id", rowset_id)
4078
0
                    .tag("packed_file_path", packed_file_path);
4079
0
            return -1;
4080
0
        }
4081
4082
0
        update_txn->put(packed_key, updated_val);
4083
0
        err = update_txn->commit();
4084
0
        if (err == TxnErrorCode::TXN_OK) {
4085
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4086
0
                    .tag("instance_id", instance_id_)
4087
0
                    .tag("tablet_id", tablet_id)
4088
0
                    .tag("rowset_id", rowset_id)
4089
0
                    .tag("packed_file_path", packed_file_path)
4090
0
                    .tag("left_file_count", left_file_count);
4091
0
            if (left_file_count == 0) {
4092
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4093
0
                    return -1;
4094
0
                }
4095
0
            }
4096
0
            return 0;
4097
0
        }
4098
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4099
0
            if (attempt >= max_retry_times) {
4100
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4101
0
                        .tag("instance_id", instance_id_)
4102
0
                        .tag("tablet_id", tablet_id)
4103
0
                        .tag("rowset_id", rowset_id)
4104
0
                        .tag("packed_file_path", packed_file_path)
4105
0
                        .tag("attempt", attempt);
4106
0
                return -1;
4107
0
            }
4108
0
            sleep_for_packed_file_retry();
4109
0
            continue;
4110
0
        }
4111
4112
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4113
0
                .tag("instance_id", instance_id_)
4114
0
                .tag("tablet_id", tablet_id)
4115
0
                .tag("rowset_id", rowset_id)
4116
0
                .tag("packed_file_path", packed_file_path)
4117
0
                .tag("err", err);
4118
0
        return -1;
4119
0
    }
4120
4121
18.4E
    return -1;
4122
18.4E
}
4123
4124
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4125
                                                const std::string& packed_key,
4126
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4127
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4128
0
        LOG_WARNING("packed file missing resource id when recycling")
4129
0
                .tag("instance_id", instance_id_)
4130
0
                .tag("packed_file_path", packed_file_path);
4131
0
        return -1;
4132
0
    }
4133
4134
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4135
7
    if (!accessor) {
4136
0
        LOG_WARNING("no accessor available to delete packed file")
4137
0
                .tag("instance_id", instance_id_)
4138
0
                .tag("packed_file_path", packed_file_path)
4139
0
                .tag("resource_id", packed_info.resource_id());
4140
0
        return -1;
4141
0
    }
4142
4143
7
    int del_ret = accessor->delete_file(packed_file_path);
4144
7
    if (del_ret != 0 && del_ret != 1) {
4145
0
        LOG_WARNING("failed to delete packed file")
4146
0
                .tag("instance_id", instance_id_)
4147
0
                .tag("packed_file_path", packed_file_path)
4148
0
                .tag("resource_id", resource_id)
4149
0
                .tag("ret", del_ret);
4150
0
        return -1;
4151
0
    }
4152
7
    if (del_ret == 1) {
4153
0
        LOG_INFO("packed file already removed")
4154
0
                .tag("instance_id", instance_id_)
4155
0
                .tag("packed_file_path", packed_file_path)
4156
0
                .tag("resource_id", resource_id);
4157
7
    } else {
4158
7
        LOG_INFO("deleted packed file")
4159
7
                .tag("instance_id", instance_id_)
4160
7
                .tag("packed_file_path", packed_file_path)
4161
7
                .tag("resource_id", resource_id);
4162
7
    }
4163
4164
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4165
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4166
7
        std::unique_ptr<Transaction> del_txn;
4167
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4168
7
        if (err != TxnErrorCode::TXN_OK) {
4169
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4170
0
                    .tag("instance_id", instance_id_)
4171
0
                    .tag("packed_file_path", packed_file_path)
4172
0
                    .tag("attempt", attempt)
4173
0
                    .tag("err", err);
4174
0
            return -1;
4175
0
        }
4176
4177
7
        std::string latest_val;
4178
7
        err = del_txn->get(packed_key, &latest_val);
4179
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4180
0
            return 0;
4181
0
        }
4182
7
        if (err != TxnErrorCode::TXN_OK) {
4183
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4184
0
                    .tag("instance_id", instance_id_)
4185
0
                    .tag("packed_file_path", packed_file_path)
4186
0
                    .tag("attempt", attempt)
4187
0
                    .tag("err", err);
4188
0
            return -1;
4189
0
        }
4190
4191
7
        cloud::PackedFileInfoPB latest_info;
4192
7
        if (!latest_info.ParseFromString(latest_val)) {
4193
0
            LOG_WARNING("failed to parse packed file info before removal")
4194
0
                    .tag("instance_id", instance_id_)
4195
0
                    .tag("packed_file_path", packed_file_path)
4196
0
                    .tag("attempt", attempt);
4197
0
            return -1;
4198
0
        }
4199
4200
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4201
7
              latest_info.ref_cnt() == 0)) {
4202
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4203
0
                    .tag("instance_id", instance_id_)
4204
0
                    .tag("packed_file_path", packed_file_path)
4205
0
                    .tag("attempt", attempt);
4206
0
            return 0;
4207
0
        }
4208
4209
7
        del_txn->remove(packed_key);
4210
7
        err = del_txn->commit();
4211
7
        if (err == TxnErrorCode::TXN_OK) {
4212
7
            LOG_INFO("removed packed file metadata")
4213
7
                    .tag("instance_id", instance_id_)
4214
7
                    .tag("packed_file_path", packed_file_path);
4215
7
            return 0;
4216
7
        }
4217
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4218
0
            if (attempt >= max_retry_times) {
4219
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4220
0
                        .tag("instance_id", instance_id_)
4221
0
                        .tag("packed_file_path", packed_file_path)
4222
0
                        .tag("attempt", attempt);
4223
0
                return -1;
4224
0
            }
4225
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4226
0
                    .tag("instance_id", instance_id_)
4227
0
                    .tag("packed_file_path", packed_file_path)
4228
0
                    .tag("attempt", attempt);
4229
0
            sleep_for_packed_file_retry();
4230
0
            continue;
4231
0
        }
4232
0
        LOG_WARNING("failed to remove packed file kv")
4233
0
                .tag("instance_id", instance_id_)
4234
0
                .tag("packed_file_path", packed_file_path)
4235
0
                .tag("attempt", attempt)
4236
0
                .tag("err", err);
4237
0
        return -1;
4238
0
    }
4239
0
    return -1;
4240
7
}
4241
4242
int InstanceRecycler::delete_rowset_data(
4243
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4244
94
        RecyclerMetricsContext& metrics_context) {
4245
94
    int ret = 0;
4246
    // resource_id -> file_paths
4247
94
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4248
    // (resource_id, tablet_id, rowset_id)
4249
94
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4250
94
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4251
4252
56.4k
    for (const auto& [_, rs] : rowsets) {
4253
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4254
        // due to aborted schema change.
4255
56.4k
        if (is_formal_rowset) {
4256
3.16k
            std::lock_guard lock(recycled_tablets_mtx_);
4257
3.16k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4258
                // Tablet has been recycled and this rowset has no packed slices, so file data
4259
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4260
                // slice info must still run to decrement packed file ref counts.
4261
0
                continue;
4262
0
            }
4263
3.16k
        }
4264
4265
56.4k
        int64_t num_segments = rs.num_segments();
4266
        // Check num_segments before accessor lookup, because empty rowsets
4267
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4268
        // set. Skipping them early avoids a spurious "no such resource id" error
4269
        // that marks the entire batch as failed and prevents txn_remove from
4270
        // cleaning up recycle KV keys.
4271
56.4k
        if (num_segments <= 0) {
4272
0
            metrics_context.total_recycled_num++;
4273
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4274
0
            continue;
4275
0
        }
4276
4277
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4278
        // possible if the accessor is not initilized correctly
4279
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4280
2.00k
            LOG_WARNING("instance has no such resource id")
4281
2.00k
                    .tag("instance_id", instance_id_)
4282
2.00k
                    .tag("resource_id", rs.resource_id());
4283
2.00k
            ret = -1;
4284
2.00k
            continue;
4285
2.00k
        }
4286
4287
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4288
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4289
54.4k
        int64_t tablet_id = rs.tablet_id();
4290
54.4k
        LOG_INFO("recycle rowset merge index size")
4291
54.4k
                .tag("instance_id", instance_id_)
4292
54.4k
                .tag("tablet_id", tablet_id)
4293
54.4k
                .tag("rowset_id", rowset_id)
4294
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4295
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4296
0
            ret = -1;
4297
0
            continue;
4298
0
        }
4299
4300
        // Process delete bitmap - check where it's stored.
4301
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4302
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4303
54.4k
                                                           &delete_bitmap_storage_type) != 0) {
4304
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4305
0
                    .tag("instance_id", instance_id_)
4306
0
                    .tag("tablet_id", tablet_id)
4307
0
                    .tag("rowset_id", rowset_id);
4308
0
            ret = -1;
4309
0
            continue;
4310
0
        }
4311
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4312
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4313
51.5k
        }
4314
4315
        // Process inverted indexes
4316
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4317
        // default format as v1.
4318
54.4k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4319
54.4k
        int inverted_index_get_ret = 0;
4320
54.4k
        if (rs.has_tablet_schema()) {
4321
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4322
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4323
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4324
53.5k
                }
4325
53.5k
            }
4326
26.8k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4327
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4328
26.5k
            }
4329
27.5k
        } else {
4330
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4331
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4332
0
                                "instance_id="
4333
0
                             << instance_id_ << " tablet_id=" << tablet_id
4334
0
                             << " rowset_id=" << rowset_id;
4335
0
                ret = -1;
4336
0
                continue;
4337
0
            }
4338
27.5k
            InvertedIndexInfo index_info;
4339
27.5k
            inverted_index_get_ret =
4340
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4341
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4342
27.5k
                                     &inverted_index_get_ret);
4343
27.5k
            if (inverted_index_get_ret == 0) {
4344
27.0k
                index_format = index_info.first;
4345
27.0k
                index_ids = index_info.second;
4346
27.0k
            } else if (inverted_index_get_ret == 1) {
4347
                // 1. Schema kv not found means tablet has been recycled
4348
                // Maybe some tablet recycle failed by some bugs
4349
                // We need to delete again to double check
4350
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4351
                // because we are uncertain about the inverted index information.
4352
                // If there are inverted indexes, some data might not be deleted,
4353
                // but this is acceptable as we have made our best effort to delete the data.
4354
503
                LOG_INFO(
4355
503
                        "delete rowset data schema kv not found, need to delete again to "
4356
503
                        "double "
4357
503
                        "check")
4358
503
                        .tag("instance_id", instance_id_)
4359
503
                        .tag("tablet_id", tablet_id)
4360
503
                        .tag("rowset", rs.ShortDebugString());
4361
                // Currently index_ids is guaranteed to be empty,
4362
                // but we clear it again here as a safeguard against future code changes
4363
                // that might cause index_ids to no longer be empty
4364
503
                index_format = InvertedIndexStorageFormatPB::V2;
4365
503
                index_ids.clear();
4366
18.4E
            } else {
4367
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4368
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4369
18.4E
                ret = -1;
4370
18.4E
                continue;
4371
18.4E
            }
4372
27.5k
        }
4373
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4374
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4375
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4376
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4377
5
            continue;
4378
5
        }
4379
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4380
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4381
270k
                                             &file_paths);
4382
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4383
537k
                for (const auto& index_id : index_ids) {
4384
537k
                    add_file_to_delete_if_not_packed(
4385
537k
                            rs,
4386
537k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4387
537k
                                                   index_id.second),
4388
537k
                            &file_paths);
4389
537k
                }
4390
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4391
                // try to recycle inverted index v2 when get_ret == 1
4392
                // we treat schema not found as if it has a v2 format inverted index
4393
                // to reduce chance of data leakage
4394
2.50k
                if (inverted_index_get_ret == 1) {
4395
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4396
2.50k
                            .tag("instance_id", instance_id_)
4397
2.50k
                            .tag("inverted index v2 path",
4398
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4399
2.50k
                }
4400
2.50k
                add_file_to_delete_if_not_packed(
4401
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4402
2.50k
            }
4403
270k
        }
4404
54.4k
    }
4405
4406
94
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4407
94
                                                 "delete_rowset_data",
4408
94
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4408
6
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4408
54
                                                 [](const int& ret) { return ret != 0; });
4409
94
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4410
55
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4411
55
            DCHECK(accessor_map_.count(*rid))
4412
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4413
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4414
55
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4415
55
                                     &accessor_map_);
4416
55
            if (!accessor_map_.contains(*rid)) {
4417
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4418
0
                        .tag("resource_id", resource_id)
4419
0
                        .tag("instance_id", instance_id_);
4420
0
                return -1;
4421
0
            }
4422
55
            auto& accessor = accessor_map_[*rid];
4423
55
            int ret = accessor->delete_files(*paths);
4424
55
            if (!ret) {
4425
                // deduplication of different files with the same rowset id
4426
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4427
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4428
55
                std::set<std::string> deleted_rowset_id;
4429
4430
55
                std::for_each(paths->begin(), paths->end(),
4431
55
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4432
862k
                               this](const std::string& path) {
4433
862k
                                  std::vector<std::string> str;
4434
862k
                                  butil::SplitString(path, '/', &str);
4435
862k
                                  std::string rowset_id;
4436
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4437
860k
                                      rowset_id = str.back().substr(0, pos);
4438
860k
                                  } else {
4439
1.90k
                                      if (path.find("packed_file/") != std::string::npos) {
4440
0
                                          return; // packed files do not have rowset_id encoded
4441
0
                                      }
4442
1.90k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4443
1.90k
                                      return;
4444
1.90k
                                  }
4445
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4446
860k
                                  if (rs_meta != rowsets.end() &&
4447
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4448
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4449
54.4k
                                      metrics_context.total_recycled_data_size +=
4450
54.4k
                                              rs_meta->second.total_disk_size();
4451
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4452
54.4k
                                              rs_meta->second.num_segments();
4453
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4454
54.4k
                                              rs_meta->second.total_disk_size();
4455
54.4k
                                      metrics_context.total_recycled_num++;
4456
54.4k
                                  }
4457
860k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4432
7
                               this](const std::string& path) {
4433
7
                                  std::vector<std::string> str;
4434
7
                                  butil::SplitString(path, '/', &str);
4435
7
                                  std::string rowset_id;
4436
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4437
7
                                      rowset_id = str.back().substr(0, pos);
4438
7
                                  } else {
4439
0
                                      if (path.find("packed_file/") != std::string::npos) {
4440
0
                                          return; // packed files do not have rowset_id encoded
4441
0
                                      }
4442
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4443
0
                                      return;
4444
0
                                  }
4445
7
                                  auto rs_meta = rowsets.find(rowset_id);
4446
7
                                  if (rs_meta != rowsets.end() &&
4447
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4448
7
                                      deleted_rowset_id.emplace(rowset_id);
4449
7
                                      metrics_context.total_recycled_data_size +=
4450
7
                                              rs_meta->second.total_disk_size();
4451
7
                                      segment_metrics_context_.total_recycled_num +=
4452
7
                                              rs_meta->second.num_segments();
4453
7
                                      segment_metrics_context_.total_recycled_data_size +=
4454
7
                                              rs_meta->second.total_disk_size();
4455
7
                                      metrics_context.total_recycled_num++;
4456
7
                                  }
4457
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4432
862k
                               this](const std::string& path) {
4433
862k
                                  std::vector<std::string> str;
4434
862k
                                  butil::SplitString(path, '/', &str);
4435
862k
                                  std::string rowset_id;
4436
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4437
860k
                                      rowset_id = str.back().substr(0, pos);
4438
860k
                                  } else {
4439
1.90k
                                      if (path.find("packed_file/") != std::string::npos) {
4440
0
                                          return; // packed files do not have rowset_id encoded
4441
0
                                      }
4442
1.90k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4443
1.90k
                                      return;
4444
1.90k
                                  }
4445
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4446
860k
                                  if (rs_meta != rowsets.end() &&
4447
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4448
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4449
54.4k
                                      metrics_context.total_recycled_data_size +=
4450
54.4k
                                              rs_meta->second.total_disk_size();
4451
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4452
54.4k
                                              rs_meta->second.num_segments();
4453
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4454
54.4k
                                              rs_meta->second.total_disk_size();
4455
54.4k
                                      metrics_context.total_recycled_num++;
4456
54.4k
                                  }
4457
860k
                              });
4458
55
            }
4459
55
            return ret;
4460
55
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4410
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4411
6
            DCHECK(accessor_map_.count(*rid))
4412
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4413
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4414
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4415
6
                                     &accessor_map_);
4416
6
            if (!accessor_map_.contains(*rid)) {
4417
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4418
0
                        .tag("resource_id", resource_id)
4419
0
                        .tag("instance_id", instance_id_);
4420
0
                return -1;
4421
0
            }
4422
6
            auto& accessor = accessor_map_[*rid];
4423
6
            int ret = accessor->delete_files(*paths);
4424
6
            if (!ret) {
4425
                // deduplication of different files with the same rowset id
4426
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4427
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4428
6
                std::set<std::string> deleted_rowset_id;
4429
4430
6
                std::for_each(paths->begin(), paths->end(),
4431
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4432
6
                               this](const std::string& path) {
4433
6
                                  std::vector<std::string> str;
4434
6
                                  butil::SplitString(path, '/', &str);
4435
6
                                  std::string rowset_id;
4436
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4437
6
                                      rowset_id = str.back().substr(0, pos);
4438
6
                                  } else {
4439
6
                                      if (path.find("packed_file/") != std::string::npos) {
4440
6
                                          return; // packed files do not have rowset_id encoded
4441
6
                                      }
4442
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4443
6
                                      return;
4444
6
                                  }
4445
6
                                  auto rs_meta = rowsets.find(rowset_id);
4446
6
                                  if (rs_meta != rowsets.end() &&
4447
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4448
6
                                      deleted_rowset_id.emplace(rowset_id);
4449
6
                                      metrics_context.total_recycled_data_size +=
4450
6
                                              rs_meta->second.total_disk_size();
4451
6
                                      segment_metrics_context_.total_recycled_num +=
4452
6
                                              rs_meta->second.num_segments();
4453
6
                                      segment_metrics_context_.total_recycled_data_size +=
4454
6
                                              rs_meta->second.total_disk_size();
4455
6
                                      metrics_context.total_recycled_num++;
4456
6
                                  }
4457
6
                              });
4458
6
            }
4459
6
            return ret;
4460
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4410
49
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4411
49
            DCHECK(accessor_map_.count(*rid))
4412
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4413
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4414
49
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4415
49
                                     &accessor_map_);
4416
49
            if (!accessor_map_.contains(*rid)) {
4417
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4418
0
                        .tag("resource_id", resource_id)
4419
0
                        .tag("instance_id", instance_id_);
4420
0
                return -1;
4421
0
            }
4422
49
            auto& accessor = accessor_map_[*rid];
4423
49
            int ret = accessor->delete_files(*paths);
4424
49
            if (!ret) {
4425
                // deduplication of different files with the same rowset id
4426
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4427
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4428
49
                std::set<std::string> deleted_rowset_id;
4429
4430
49
                std::for_each(paths->begin(), paths->end(),
4431
49
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4432
49
                               this](const std::string& path) {
4433
49
                                  std::vector<std::string> str;
4434
49
                                  butil::SplitString(path, '/', &str);
4435
49
                                  std::string rowset_id;
4436
49
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4437
49
                                      rowset_id = str.back().substr(0, pos);
4438
49
                                  } else {
4439
49
                                      if (path.find("packed_file/") != std::string::npos) {
4440
49
                                          return; // packed files do not have rowset_id encoded
4441
49
                                      }
4442
49
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4443
49
                                      return;
4444
49
                                  }
4445
49
                                  auto rs_meta = rowsets.find(rowset_id);
4446
49
                                  if (rs_meta != rowsets.end() &&
4447
49
                                      !deleted_rowset_id.contains(rowset_id)) {
4448
49
                                      deleted_rowset_id.emplace(rowset_id);
4449
49
                                      metrics_context.total_recycled_data_size +=
4450
49
                                              rs_meta->second.total_disk_size();
4451
49
                                      segment_metrics_context_.total_recycled_num +=
4452
49
                                              rs_meta->second.num_segments();
4453
49
                                      segment_metrics_context_.total_recycled_data_size +=
4454
49
                                              rs_meta->second.total_disk_size();
4455
49
                                      metrics_context.total_recycled_num++;
4456
49
                                  }
4457
49
                              });
4458
49
            }
4459
49
            return ret;
4460
49
        });
4461
55
    }
4462
94
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4463
5
        LOG_INFO(
4464
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4465
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4466
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4467
5
        concurrent_delete_executor.add([&]() -> int {
4468
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4469
5
            if (!ret) {
4470
5
                auto rs = rowsets.at(rowset_id);
4471
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4472
5
                metrics_context.total_recycled_num++;
4473
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4474
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4475
5
            }
4476
5
            return ret;
4477
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
4467
5
        concurrent_delete_executor.add([&]() -> int {
4468
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4469
5
            if (!ret) {
4470
5
                auto rs = rowsets.at(rowset_id);
4471
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4472
5
                metrics_context.total_recycled_num++;
4473
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4474
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4475
5
            }
4476
5
            return ret;
4477
5
        });
4478
5
    }
4479
4480
94
    bool finished = true;
4481
94
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4482
94
    for (int r : rets) {
4483
60
        if (r != 0) {
4484
0
            ret = -1;
4485
0
            break;
4486
0
        }
4487
60
    }
4488
94
    ret = finished ? ret : -1;
4489
94
    return ret;
4490
94
}
4491
4492
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4493
3.57k
                                         const std::string& rowset_id) {
4494
3.57k
    auto it = accessor_map_.find(resource_id);
4495
3.57k
    if (it == accessor_map_.end()) {
4496
400
        LOG_WARNING("instance has no such resource id")
4497
400
                .tag("instance_id", instance_id_)
4498
400
                .tag("resource_id", resource_id)
4499
400
                .tag("tablet_id", tablet_id)
4500
400
                .tag("rowset_id", rowset_id);
4501
400
        return -1;
4502
400
    }
4503
3.17k
    auto& accessor = it->second;
4504
3.17k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4505
3.57k
}
4506
4507
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t tablet_id,
4508
55.5k
                                                         const std::string& rowset_id) {
4509
55.5k
    std::string dbm_start_key =
4510
55.5k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4511
55.5k
    std::string dbm_end_key = dbm_start_key;
4512
55.5k
    encode_int64(INT64_MAX, &dbm_end_key);
4513
55.5k
    int ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4514
55.5k
    if (ret != 0) {
4515
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4516
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4517
0
    }
4518
55.5k
    return ret;
4519
55.5k
}
4520
4521
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4522
51.2k
    std::string delete_bitmap_start =
4523
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4524
51.2k
    std::string delete_bitmap_end =
4525
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4526
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4527
51.2k
    if (ret != 0) {
4528
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4529
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4530
0
    }
4531
51.2k
    return ret;
4532
51.2k
}
4533
4534
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4535
4
    if (key.empty()) {
4536
0
        return false;
4537
0
    }
4538
4
    std::string_view key_view = key;
4539
4
    key_view.remove_prefix(1); // remove keyspace prefix
4540
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4541
4
    if (decode_key(&key_view, &decoded) != 0) {
4542
0
        return false;
4543
0
    }
4544
4
    if (decoded.size() < 4) {
4545
0
        return false;
4546
0
    }
4547
4
    try {
4548
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4549
4
    } catch (const std::bad_variant_access&) {
4550
0
        return false;
4551
0
    }
4552
4
    return true;
4553
4
}
4554
4555
14
int InstanceRecycler::recycle_packed_files() {
4556
14
    const std::string task_name = "recycle_packed_files";
4557
14
    auto start_tp = steady_clock::now();
4558
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4559
14
    int ret = 0;
4560
14
    PackedFileRecycleStats stats;
4561
4562
14
    register_recycle_task(task_name, start_time);
4563
14
    DORIS_CLOUD_DEFER {
4564
14
        unregister_recycle_task(task_name);
4565
14
        int64_t cost =
4566
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4567
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4568
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4569
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4570
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4571
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4572
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4573
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4574
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4575
14
                                                             stats.bytes_object_deleted);
4576
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4577
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4578
14
                .tag("instance_id", instance_id_)
4579
14
                .tag("num_scanned", stats.num_scanned)
4580
14
                .tag("num_corrected", stats.num_corrected)
4581
14
                .tag("num_deleted", stats.num_deleted)
4582
14
                .tag("num_failed", stats.num_failed)
4583
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4584
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4585
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4586
14
                .tag("bytes_deleted", stats.bytes_deleted)
4587
14
                .tag("ret", ret);
4588
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4563
14
    DORIS_CLOUD_DEFER {
4564
14
        unregister_recycle_task(task_name);
4565
14
        int64_t cost =
4566
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4567
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4568
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4569
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4570
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4571
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4572
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4573
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4574
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4575
14
                                                             stats.bytes_object_deleted);
4576
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4577
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4578
14
                .tag("instance_id", instance_id_)
4579
14
                .tag("num_scanned", stats.num_scanned)
4580
14
                .tag("num_corrected", stats.num_corrected)
4581
14
                .tag("num_deleted", stats.num_deleted)
4582
14
                .tag("num_failed", stats.num_failed)
4583
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4584
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4585
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4586
14
                .tag("bytes_deleted", stats.bytes_deleted)
4587
14
                .tag("ret", ret);
4588
14
    };
4589
4590
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4591
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4592
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4593
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
Line
Count
Source
4590
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4591
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4592
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4593
4
    };
4594
4595
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4596
4597
14
    std::string begin = packed_file_key({instance_id_, ""});
4598
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4599
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4600
0
        ret = -1;
4601
0
    }
4602
4603
14
    return ret;
4604
14
}
4605
4606
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4607
                                                  RecyclerMetricsContext& metrics_context,
4608
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4609
0
    std::string tablet_key_begin, tablet_key_end;
4610
4611
0
    if (partition_id > 0) {
4612
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4613
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4614
0
    } else {
4615
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4616
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4617
0
    }
4618
    // for calculate the total num or bytes of recyled objects
4619
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4620
0
                                                          std::string_view v) -> int {
4621
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4622
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4623
0
            return 0;
4624
0
        }
4625
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4626
4627
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4628
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4629
0
            return 0;
4630
0
        }
4631
4632
0
        if (!is_empty_tablet) {
4633
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4634
0
                return 0;
4635
0
            }
4636
0
            tablet_metrics_context_.total_need_recycle_num++;
4637
0
        }
4638
0
        return 0;
4639
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
4640
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4641
0
    metrics_context.report(true);
4642
0
    tablet_metrics_context_.report(true);
4643
0
    segment_metrics_context_.report(true);
4644
0
    return ret;
4645
0
}
4646
4647
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4648
0
                                                 RecyclerMetricsContext& metrics_context) {
4649
0
    int ret = 0;
4650
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4651
0
    std::unique_ptr<Transaction> txn;
4652
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4653
0
        LOG_WARNING("failed to recycle tablet ")
4654
0
                .tag("tablet id", tablet_id)
4655
0
                .tag("instance_id", instance_id_)
4656
0
                .tag("reason", "failed to create txn");
4657
0
        ret = -1;
4658
0
    }
4659
0
    GetRowsetResponse resp;
4660
0
    std::string msg;
4661
0
    MetaServiceCode code = MetaServiceCode::OK;
4662
    // get rowsets in tablet
4663
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4664
0
                        tablet_id, code, msg, &resp);
4665
0
    if (code != MetaServiceCode::OK) {
4666
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4667
0
                .tag("tablet id", tablet_id)
4668
0
                .tag("msg", msg)
4669
0
                .tag("code", code)
4670
0
                .tag("instance id", instance_id_);
4671
0
        ret = -1;
4672
0
    }
4673
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4674
        /*
4675
        * For compatibility, we skip the loop for [0-1] here.
4676
        * The purpose of this loop is to delete object files,
4677
        * and since [0-1] only has meta and doesn't have object files,
4678
        * skipping it doesn't affect system correctness.
4679
        *
4680
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4681
        * would return error -1 directly, causing the recycle operation to fail.
4682
        *
4683
        * [0-1] doesn't have resource id is a bug.
4684
        * In the future, we will fix this problem, after that,
4685
        * we can remove this if statement.
4686
        *
4687
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4688
        */
4689
4690
0
        if (rs_meta.end_version() == 1) {
4691
            // Assert that [0-1] has no resource_id to make sure
4692
            // this if statement will not be forgetted to remove
4693
            // when the resource id bug is fixed
4694
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4695
0
            continue;
4696
0
        }
4697
0
        if (!rs_meta.has_resource_id()) {
4698
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4699
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4700
0
                    .tag("instance_id", instance_id_)
4701
0
                    .tag("tablet_id", tablet_id);
4702
0
            continue;
4703
0
        }
4704
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4705
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4706
        // possible if the accessor is not initilized correctly
4707
0
        if (it == accessor_map_.end()) [[unlikely]] {
4708
0
            LOG_WARNING(
4709
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4710
0
                    "recycle process")
4711
0
                    .tag("tablet id", tablet_id)
4712
0
                    .tag("instance_id", instance_id_)
4713
0
                    .tag("resource_id", rs_meta.resource_id())
4714
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4715
0
            continue;
4716
0
        }
4717
4718
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4719
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4720
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4721
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4722
0
    }
4723
0
    return ret;
4724
0
}
4725
4726
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4727
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4728
4.26k
            .tag("instance_id", instance_id_)
4729
4.26k
            .tag("tablet_id", tablet_id);
4730
4731
4.26k
    if (should_recycle_versioned_keys()) {
4732
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4733
14
        if (ret != 0) {
4734
0
            return ret;
4735
0
        }
4736
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4737
        // during the recycle_versioned_tablet process.
4738
        //
4739
        // .. And remove restore job rowsets of this tablet too
4740
14
    }
4741
4742
4.26k
    int ret = 0;
4743
4.26k
    auto start_time = steady_clock::now();
4744
4745
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4746
4747
    // collect resource ids
4748
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4749
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4750
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4751
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4752
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4753
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4754
4755
260
    std::set<std::string> resource_ids;
4756
260
    int64_t recycle_rowsets_number = 0;
4757
260
    int64_t recycle_segments_number = 0;
4758
260
    int64_t recycle_rowsets_data_size = 0;
4759
260
    int64_t recycle_rowsets_index_size = 0;
4760
260
    int64_t recycle_restore_job_rowsets_number = 0;
4761
260
    int64_t recycle_restore_job_segments_number = 0;
4762
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4763
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4764
260
    int64_t max_rowset_version = 0;
4765
260
    int64_t min_rowset_creation_time = INT64_MAX;
4766
260
    int64_t max_rowset_creation_time = 0;
4767
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4768
260
    int64_t max_rowset_expiration_time = 0;
4769
4770
260
    DORIS_CLOUD_DEFER {
4771
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4772
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4773
260
                .tag("instance_id", instance_id_)
4774
260
                .tag("tablet_id", tablet_id)
4775
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4776
260
                .tag("recycle segments number", recycle_segments_number)
4777
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4778
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4779
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4780
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4781
260
                .tag("all restore job rowsets recycle data size",
4782
260
                     recycle_restore_job_rowsets_data_size)
4783
260
                .tag("all restore job rowsets recycle index size",
4784
260
                     recycle_restore_job_rowsets_index_size)
4785
260
                .tag("max rowset version", max_rowset_version)
4786
260
                .tag("min rowset creation time", min_rowset_creation_time)
4787
260
                .tag("max rowset creation time", max_rowset_creation_time)
4788
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4789
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4790
260
                .tag("task type", metrics_context.operation_type)
4791
260
                .tag("ret", ret);
4792
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4770
260
    DORIS_CLOUD_DEFER {
4771
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4772
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4773
260
                .tag("instance_id", instance_id_)
4774
260
                .tag("tablet_id", tablet_id)
4775
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4776
260
                .tag("recycle segments number", recycle_segments_number)
4777
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4778
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4779
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4780
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4781
260
                .tag("all restore job rowsets recycle data size",
4782
260
                     recycle_restore_job_rowsets_data_size)
4783
260
                .tag("all restore job rowsets recycle index size",
4784
260
                     recycle_restore_job_rowsets_index_size)
4785
260
                .tag("max rowset version", max_rowset_version)
4786
260
                .tag("min rowset creation time", min_rowset_creation_time)
4787
260
                .tag("max rowset creation time", max_rowset_creation_time)
4788
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4789
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4790
260
                .tag("task type", metrics_context.operation_type)
4791
260
                .tag("ret", ret);
4792
260
    };
4793
4794
260
    std::unique_ptr<Transaction> txn;
4795
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4796
0
        LOG_WARNING("failed to recycle tablet ")
4797
0
                .tag("tablet id", tablet_id)
4798
0
                .tag("instance_id", instance_id_)
4799
0
                .tag("reason", "failed to create txn");
4800
0
        ret = -1;
4801
0
    }
4802
260
    GetRowsetResponse resp;
4803
260
    std::string msg;
4804
260
    MetaServiceCode code = MetaServiceCode::OK;
4805
    // get rowsets in tablet
4806
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4807
260
                        tablet_id, code, msg, &resp);
4808
260
    if (code != MetaServiceCode::OK) {
4809
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4810
0
                .tag("tablet id", tablet_id)
4811
0
                .tag("msg", msg)
4812
0
                .tag("code", code)
4813
0
                .tag("instance id", instance_id_);
4814
0
        ret = -1;
4815
0
    }
4816
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4817
4818
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4819
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4820
3
            if (rs_meta.num_segments() <= 0) {
4821
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4822
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4823
2
                        .tag("instance_id", instance_id_)
4824
2
                        .tag("tablet_id", tablet_id);
4825
2
                recycle_rowsets_number += 1;
4826
2
                continue;
4827
2
            }
4828
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4829
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4830
1
                    .tag("instance_id", instance_id_)
4831
1
                    .tag("tablet_id", tablet_id);
4832
1
            return -1;
4833
3
        }
4834
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4835
0
                << "rs_meta" << rs_meta.ShortDebugString();
4836
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4837
        // possible if the accessor is not initilized correctly
4838
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4839
1
            LOG_WARNING(
4840
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4841
1
                    "recycle process")
4842
1
                    .tag("tablet id", tablet_id)
4843
1
                    .tag("instance_id", instance_id_)
4844
1
                    .tag("resource_id", rs_meta.resource_id())
4845
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4846
1
            return -1;
4847
1
        }
4848
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4849
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4850
0
                    .tag("instance_id", instance_id_)
4851
0
                    .tag("tablet_id", tablet_id)
4852
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4853
0
            return -1;
4854
0
        }
4855
2.54k
        recycle_rowsets_number += 1;
4856
2.54k
        recycle_segments_number += rs_meta.num_segments();
4857
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4858
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4859
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4860
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4861
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4862
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4863
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4864
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4865
2.54k
    }
4866
4867
    // get restore job rowset in tablet
4868
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4869
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4870
258
    if (code != MetaServiceCode::OK) {
4871
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4872
0
                .tag("tablet id", tablet_id)
4873
0
                .tag("msg", msg)
4874
0
                .tag("code", code)
4875
0
                .tag("instance id", instance_id_);
4876
0
        return -1;
4877
0
    }
4878
4879
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4880
0
        if (!rs_meta.has_resource_id()) {
4881
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4882
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4883
0
                    .tag("instance_id", instance_id_)
4884
0
                    .tag("tablet_id", tablet_id);
4885
0
            return -1;
4886
0
        }
4887
4888
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4889
        // possible if the accessor is not initilized correctly
4890
0
        if (it == accessor_map_.end()) [[unlikely]] {
4891
0
            LOG_WARNING(
4892
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4893
0
                    "recycle process")
4894
0
                    .tag("tablet id", tablet_id)
4895
0
                    .tag("instance_id", instance_id_)
4896
0
                    .tag("resource_id", rs_meta.resource_id())
4897
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4898
0
            return -1;
4899
0
        }
4900
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4901
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4902
0
                    .tag("instance_id", instance_id_)
4903
0
                    .tag("tablet_id", tablet_id)
4904
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4905
0
            return -1;
4906
0
        }
4907
0
        recycle_restore_job_rowsets_number += 1;
4908
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4909
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4910
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4911
0
        resource_ids.emplace(rs_meta.resource_id());
4912
0
    }
4913
4914
258
    LOG_INFO("recycle tablet start to delete object")
4915
258
            .tag("instance id", instance_id_)
4916
258
            .tag("tablet id", tablet_id)
4917
258
            .tag("recycle tablet resource ids are",
4918
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4919
258
                                 [](std::string rs_id, const auto& it) {
4920
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4921
217
                                 }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
Line
Count
Source
4919
217
                                 [](std::string rs_id, const auto& it) {
4920
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4921
217
                                 }));
4922
4923
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4924
258
            _thread_pool_group.s3_producer_pool,
4925
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4926
258
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
4926
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4927
4928
    // delete all rowset data in this tablet
4929
    // ATTN: there may be data leak if not all accessor initilized successfully
4930
    //       partial data deleted if the tablet is stored cross-storage vault
4931
    //       vault id is not attached to TabletMeta...
4932
258
    for (const auto& resource_id : resource_ids) {
4933
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4934
217
        concurrent_delete_executor.add(
4935
217
                [&, rs_id = resource_id,
4936
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4937
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4938
217
                    if (res != 0) {
4939
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4940
3
                                     << " path=" << accessor_ptr->uri()
4941
3
                                     << " task type=" << metrics_context.operation_type;
4942
3
                        return std::make_pair(-1, rs_id);
4943
3
                    }
4944
214
                    return std::make_pair(0, rs_id);
4945
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4936
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4937
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4938
217
                    if (res != 0) {
4939
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4940
3
                                     << " path=" << accessor_ptr->uri()
4941
3
                                     << " task type=" << metrics_context.operation_type;
4942
3
                        return std::make_pair(-1, rs_id);
4943
3
                    }
4944
214
                    return std::make_pair(0, rs_id);
4945
217
                });
4946
217
    }
4947
4948
258
    bool finished = true;
4949
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4950
258
    for (auto& r : rets) {
4951
217
        if (r.first != 0) {
4952
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4953
3
            ret = -1;
4954
3
        }
4955
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4956
217
    }
4957
258
    ret = finished ? ret : -1;
4958
4959
258
    if (ret != 0) { // failed recycle tablet data
4960
3
        LOG_WARNING("ret!=0")
4961
3
                .tag("finished", finished)
4962
3
                .tag("ret", ret)
4963
3
                .tag("instance_id", instance_id_)
4964
3
                .tag("tablet_id", tablet_id);
4965
3
        return ret;
4966
3
    }
4967
4968
255
    tablet_metrics_context_.total_recycled_data_size +=
4969
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4970
255
    tablet_metrics_context_.total_recycled_num += 1;
4971
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4972
255
    segment_metrics_context_.total_recycled_data_size +=
4973
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4974
255
    metrics_context.total_recycled_data_size +=
4975
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4976
255
    tablet_metrics_context_.report();
4977
255
    segment_metrics_context_.report();
4978
255
    metrics_context.report();
4979
4980
255
    txn.reset();
4981
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4982
0
        LOG_WARNING("failed to recycle tablet ")
4983
0
                .tag("tablet id", tablet_id)
4984
0
                .tag("instance_id", instance_id_)
4985
0
                .tag("reason", "failed to create txn");
4986
0
        ret = -1;
4987
0
    }
4988
    // delete all rowset kv in this tablet
4989
255
    txn->remove(rs_key0, rs_key1);
4990
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4991
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4992
4993
    // remove delete bitmap for MoW table
4994
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4995
255
    txn->remove(pending_key);
4996
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4997
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4998
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4999
5000
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5001
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5002
255
    txn->remove(dbm_start_key, dbm_end_key);
5003
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5004
255
              << " end=" << hex(dbm_end_key);
5005
5006
255
    TxnErrorCode err = txn->commit();
5007
255
    if (err != TxnErrorCode::TXN_OK) {
5008
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5009
0
        ret = -1;
5010
0
    }
5011
5012
255
    if (ret == 0) {
5013
        // All object files under tablet have been deleted
5014
255
        std::lock_guard lock(recycled_tablets_mtx_);
5015
255
        recycled_tablets_.insert(tablet_id);
5016
255
    }
5017
5018
255
    return ret;
5019
258
}
5020
5021
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5022
14
                                               RecyclerMetricsContext& metrics_context) {
5023
14
    int ret = 0;
5024
14
    auto start_time = steady_clock::now();
5025
5026
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5027
5028
    // collect resource ids
5029
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5030
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5031
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5032
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5033
5034
11
    int64_t recycle_rowsets_number = 0;
5035
11
    int64_t recycle_segments_number = 0;
5036
11
    int64_t recycle_rowsets_data_size = 0;
5037
11
    int64_t recycle_rowsets_index_size = 0;
5038
11
    int64_t max_rowset_version = 0;
5039
11
    int64_t min_rowset_creation_time = INT64_MAX;
5040
11
    int64_t max_rowset_creation_time = 0;
5041
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5042
11
    int64_t max_rowset_expiration_time = 0;
5043
5044
11
    DORIS_CLOUD_DEFER {
5045
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5046
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5047
11
                .tag("instance_id", instance_id_)
5048
11
                .tag("tablet_id", tablet_id)
5049
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5050
11
                .tag("recycle segments number", recycle_segments_number)
5051
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5052
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5053
11
                .tag("max rowset version", max_rowset_version)
5054
11
                .tag("min rowset creation time", min_rowset_creation_time)
5055
11
                .tag("max rowset creation time", max_rowset_creation_time)
5056
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5057
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5058
11
                .tag("ret", ret);
5059
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5044
11
    DORIS_CLOUD_DEFER {
5045
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5046
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5047
11
                .tag("instance_id", instance_id_)
5048
11
                .tag("tablet_id", tablet_id)
5049
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5050
11
                .tag("recycle segments number", recycle_segments_number)
5051
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5052
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5053
11
                .tag("max rowset version", max_rowset_version)
5054
11
                .tag("min rowset creation time", min_rowset_creation_time)
5055
11
                .tag("max rowset creation time", max_rowset_creation_time)
5056
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5057
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5058
11
                .tag("ret", ret);
5059
11
    };
5060
5061
11
    std::unique_ptr<Transaction> txn;
5062
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5063
0
        LOG_WARNING("failed to recycle tablet ")
5064
0
                .tag("tablet id", tablet_id)
5065
0
                .tag("instance_id", instance_id_)
5066
0
                .tag("reason", "failed to create txn");
5067
0
        ret = -1;
5068
0
    }
5069
5070
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5071
    // by the related operation logs.
5072
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5073
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5074
11
    MetaReader meta_reader(instance_id_);
5075
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5076
11
    if (err == TxnErrorCode::TXN_OK) {
5077
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5078
11
    }
5079
11
    if (err != TxnErrorCode::TXN_OK) {
5080
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5081
0
                .tag("tablet id", tablet_id)
5082
0
                .tag("err", err)
5083
0
                .tag("instance id", instance_id_);
5084
0
        ret = -1;
5085
0
    }
5086
5087
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5088
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5089
11
            .tag("instance_id", instance_id_)
5090
11
            .tag("tablet_id", tablet_id);
5091
5092
11
    SyncExecutor<int> concurrent_delete_executor(
5093
11
            _thread_pool_group.s3_producer_pool,
5094
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5095
11
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
5096
5097
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5098
60
        recycle_rowsets_number += 1;
5099
60
        recycle_segments_number += rs_meta.num_segments();
5100
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5101
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5102
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5103
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5104
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5105
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5106
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5107
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5097
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5098
60
        recycle_rowsets_number += 1;
5099
60
        recycle_segments_number += rs_meta.num_segments();
5100
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5101
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5102
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5103
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5104
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5105
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5106
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5107
60
    };
5108
5109
11
    std::vector<RowsetDeleteTask> all_tasks;
5110
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5111
60
        update_rowset_stats(rs_meta);
5112
        // Version 0-1 rowset has no resource_id and no actual data files,
5113
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5114
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5115
60
        RowsetDeleteTask task;
5116
60
        task.rowset_meta = rs_meta;
5117
60
        task.versioned_rowset_key =
5118
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5119
60
        task.non_versioned_rowset_key =
5120
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5121
60
        task.versionstamp = versionstamp;
5122
60
        all_tasks.push_back(std::move(task));
5123
60
    }
5124
5125
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5126
0
        update_rowset_stats(rs_meta);
5127
        // Version 0-1 rowset has no resource_id and no actual data files,
5128
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5129
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5130
0
        RowsetDeleteTask task;
5131
0
        task.rowset_meta = rs_meta;
5132
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5133
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5134
0
        task.non_versioned_rowset_key =
5135
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5136
0
        task.versionstamp = versionstamp;
5137
0
        all_tasks.push_back(std::move(task));
5138
0
    }
5139
5140
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5141
0
        RecycleRowsetPB recycle_rowset;
5142
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5143
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5144
0
            return -1;
5145
0
        }
5146
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5147
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5148
                // in old version, keep this key-value pair and it needs to be checked manually
5149
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5150
0
                return -1;
5151
0
            }
5152
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5153
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5154
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5155
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5156
0
                return -1;
5157
0
            }
5158
            // decode rowset_id
5159
0
            auto k1 = k;
5160
0
            k1.remove_prefix(1);
5161
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5162
0
            decode_key(&k1, &out);
5163
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5164
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5165
0
            LOG_INFO("delete old-version rowset data")
5166
0
                    .tag("instance_id", instance_id_)
5167
0
                    .tag("tablet_id", tablet_id)
5168
0
                    .tag("rowset_id", rowset_id);
5169
5170
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5171
            // so we must use prefix deletion directly instead of batch delete.
5172
0
            concurrent_delete_executor.add(
5173
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5174
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5175
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5176
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
5177
0
        } else {
5178
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5179
            // Version 0-1 rowset has no resource_id and no actual data files,
5180
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5181
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5182
0
            RowsetDeleteTask task;
5183
0
            task.rowset_meta = rowset_meta;
5184
0
            task.recycle_rowset_key = k;
5185
0
            all_tasks.push_back(std::move(task));
5186
0
        }
5187
0
        return 0;
5188
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
5189
5190
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5191
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5192
0
                .tag("tablet id", tablet_id)
5193
0
                .tag("instance_id", instance_id_)
5194
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5195
0
        ret = -1;
5196
0
    }
5197
5198
    // Phase 1: Classify tasks by ref_count
5199
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5200
60
    for (auto& task : all_tasks) {
5201
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5202
60
        if (classify_ret < 0) {
5203
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5204
0
                    .tag("instance_id", instance_id_)
5205
0
                    .tag("tablet_id", tablet_id)
5206
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5207
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5208
0
                return recycle_rowset_meta_and_data(t);
5209
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5210
0
        }
5211
60
    }
5212
5213
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5214
5215
11
    LOG_INFO("batch delete plan created")
5216
11
            .tag("instance_id", instance_id_)
5217
11
            .tag("tablet_id", tablet_id)
5218
11
            .tag("plan_count", batch_delete_tasks.size());
5219
5220
    // Phase 2: Execute batch delete using existing delete_rowset_data
5221
11
    if (!batch_delete_tasks.empty()) {
5222
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5223
49
        for (const auto& task : batch_delete_tasks) {
5224
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5225
49
            if (task.rowset_meta.resource_id().empty()) {
5226
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5227
10
                        .tag("instance_id", instance_id_)
5228
10
                        .tag("tablet_id", tablet_id)
5229
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5230
10
                continue;
5231
10
            }
5232
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5233
39
        }
5234
5235
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5236
10
        bool delete_success = true;
5237
10
        if (!rowsets_to_delete.empty()) {
5238
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5239
9
                                                         "batch_delete_versioned_tablet");
5240
9
            int delete_ret = delete_rowset_data(
5241
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5242
9
            if (delete_ret != 0) {
5243
0
                LOG_WARNING("batch delete execution failed")
5244
0
                        .tag("instance_id", instance_id_)
5245
0
                        .tag("tablet_id", tablet_id);
5246
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5247
0
                ret = -1;
5248
0
                delete_success = false;
5249
0
            }
5250
9
        }
5251
5252
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5253
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5254
10
        if (delete_success) {
5255
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5256
10
            if (cleanup_ret != 0) {
5257
0
                LOG_WARNING("batch delete cleanup failed")
5258
0
                        .tag("instance_id", instance_id_)
5259
0
                        .tag("tablet_id", tablet_id);
5260
0
                ret = -1;
5261
0
            }
5262
10
        }
5263
10
    }
5264
5265
    // Always wait for fallback tasks to complete before returning
5266
11
    bool finished = true;
5267
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5268
11
    for (int r : rets) {
5269
0
        if (r != 0) {
5270
0
            ret = -1;
5271
0
        }
5272
0
    }
5273
5274
11
    ret = finished ? ret : -1;
5275
5276
11
    if (ret != 0) { // failed recycle tablet data
5277
0
        LOG_WARNING("recycle versioned tablet failed")
5278
0
                .tag("finished", finished)
5279
0
                .tag("ret", ret)
5280
0
                .tag("instance_id", instance_id_)
5281
0
                .tag("tablet_id", tablet_id);
5282
0
        return ret;
5283
0
    }
5284
5285
11
    tablet_metrics_context_.total_recycled_data_size +=
5286
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5287
11
    tablet_metrics_context_.total_recycled_num += 1;
5288
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5289
11
    segment_metrics_context_.total_recycled_data_size +=
5290
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5291
11
    metrics_context.total_recycled_data_size +=
5292
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5293
11
    tablet_metrics_context_.report();
5294
11
    segment_metrics_context_.report();
5295
11
    metrics_context.report();
5296
5297
11
    txn.reset();
5298
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5299
0
        LOG_WARNING("failed to recycle tablet ")
5300
0
                .tag("tablet id", tablet_id)
5301
0
                .tag("instance_id", instance_id_)
5302
0
                .tag("reason", "failed to create txn");
5303
0
        ret = -1;
5304
0
    }
5305
    // delete all rowset kv in this tablet
5306
11
    txn->remove(rs_key0, rs_key1);
5307
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5308
5309
    // remove delete bitmap for MoW table
5310
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5311
11
    txn->remove(pending_key);
5312
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5313
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5314
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5315
5316
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5317
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5318
11
    txn->remove(dbm_start_key, dbm_end_key);
5319
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5320
11
              << " end=" << hex(dbm_end_key);
5321
5322
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5323
11
    std::string tablet_index_val;
5324
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5325
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5326
0
        LOG_WARNING("failed to get tablet index kv")
5327
0
                .tag("instance_id", instance_id_)
5328
0
                .tag("tablet_id", tablet_id)
5329
0
                .tag("err", err);
5330
0
        ret = -1;
5331
11
    } else if (err == TxnErrorCode::TXN_OK) {
5332
        // If the tablet index kv exists, we need to delete it
5333
10
        TabletIndexPB tablet_index_pb;
5334
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5335
0
            LOG_WARNING("failed to parse tablet index pb")
5336
0
                    .tag("instance_id", instance_id_)
5337
0
                    .tag("tablet_id", tablet_id);
5338
0
            ret = -1;
5339
10
        } else {
5340
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5341
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5342
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5343
10
            txn->remove(versioned_inverted_idx_key);
5344
10
            txn->remove(versioned_idx_key);
5345
10
        }
5346
10
    }
5347
5348
11
    err = txn->commit();
5349
11
    if (err != TxnErrorCode::TXN_OK) {
5350
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5351
0
        ret = -1;
5352
0
    }
5353
5354
11
    if (ret == 0) {
5355
        // All object files under tablet have been deleted
5356
11
        std::lock_guard lock(recycled_tablets_mtx_);
5357
11
        recycled_tablets_.insert(tablet_id);
5358
11
    }
5359
5360
11
    return ret;
5361
11
}
5362
5363
47
int InstanceRecycler::recycle_rowsets() {
5364
47
    if (should_recycle_versioned_keys()) {
5365
5
        return recycle_versioned_rowsets();
5366
5
    }
5367
5368
42
    const std::string task_name = "recycle_rowsets";
5369
42
    int64_t num_scanned = 0;
5370
42
    int64_t num_expired = 0;
5371
42
    int64_t num_prepare = 0;
5372
42
    int64_t num_compacted = 0;
5373
42
    int64_t num_empty_rowset = 0;
5374
42
    size_t total_rowset_key_size = 0;
5375
42
    size_t total_rowset_value_size = 0;
5376
42
    size_t expired_rowset_size = 0;
5377
42
    std::atomic_long num_recycled = 0;
5378
42
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5379
5380
42
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5381
42
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5382
42
    std::string recyc_rs_key0;
5383
42
    std::string recyc_rs_key1;
5384
42
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5385
42
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5386
5387
42
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5388
5389
42
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5390
42
    register_recycle_task(task_name, start_time);
5391
5392
42
    DORIS_CLOUD_DEFER {
5393
42
        unregister_recycle_task(task_name);
5394
42
        int64_t cost =
5395
42
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5396
42
        metrics_context.finish_report();
5397
42
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5398
42
                .tag("instance_id", instance_id_)
5399
42
                .tag("num_scanned", num_scanned)
5400
42
                .tag("num_expired", num_expired)
5401
42
                .tag("num_recycled", num_recycled)
5402
42
                .tag("num_recycled.prepare", num_prepare)
5403
42
                .tag("num_recycled.compacted", num_compacted)
5404
42
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5405
42
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5406
42
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5407
42
                .tag("expired_rowset_meta_size", expired_rowset_size);
5408
42
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5392
7
    DORIS_CLOUD_DEFER {
5393
7
        unregister_recycle_task(task_name);
5394
7
        int64_t cost =
5395
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5396
7
        metrics_context.finish_report();
5397
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5398
7
                .tag("instance_id", instance_id_)
5399
7
                .tag("num_scanned", num_scanned)
5400
7
                .tag("num_expired", num_expired)
5401
7
                .tag("num_recycled", num_recycled)
5402
7
                .tag("num_recycled.prepare", num_prepare)
5403
7
                .tag("num_recycled.compacted", num_compacted)
5404
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5405
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5406
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5407
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5408
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5392
35
    DORIS_CLOUD_DEFER {
5393
35
        unregister_recycle_task(task_name);
5394
35
        int64_t cost =
5395
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5396
35
        metrics_context.finish_report();
5397
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5398
35
                .tag("instance_id", instance_id_)
5399
35
                .tag("num_scanned", num_scanned)
5400
35
                .tag("num_expired", num_expired)
5401
35
                .tag("num_recycled", num_recycled)
5402
35
                .tag("num_recycled.prepare", num_prepare)
5403
35
                .tag("num_recycled.compacted", num_compacted)
5404
35
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5405
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5406
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5407
35
                .tag("expired_rowset_meta_size", expired_rowset_size);
5408
35
    };
5409
5410
42
    std::vector<std::string> rowset_keys;
5411
42
    std::vector<std::string> rowset_keys_to_mark_recycled;
5412
42
    std::vector<std::string> rowset_keys_to_abort_job;
5413
    // rowset_id -> rowset_meta
5414
    // store rowset id and meta for statistics rs size when delete
5415
42
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5416
5417
42
    std::mutex async_recycled_rowset_keys_mutex;
5418
42
    std::vector<std::string> async_recycled_rowset_keys;
5419
42
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5420
42
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5421
42
    worker_pool->start();
5422
42
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5423
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5424
        // Try to delete rowset data in background thread
5425
903
        int ret = worker_pool->submit_with_timeout(
5426
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5427
785
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5429
0
                        return;
5430
0
                    }
5431
785
                    std::vector<std::string> keys;
5432
785
                    {
5433
785
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5434
785
                        async_recycled_rowset_keys.push_back(std::move(key));
5435
785
                        if (async_recycled_rowset_keys.size() > 100) {
5436
7
                            keys.swap(async_recycled_rowset_keys);
5437
7
                        }
5438
785
                    }
5439
785
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5440
785
                    if (keys.empty()) return;
5441
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5442
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5443
0
                                     << instance_id_;
5444
7
                    } else {
5445
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5446
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5447
7
                                           num_recycled, start_time);
5448
7
                    }
5449
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5426
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5427
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5429
0
                        return;
5430
0
                    }
5431
1
                    std::vector<std::string> keys;
5432
1
                    {
5433
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5434
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5435
1
                        if (async_recycled_rowset_keys.size() > 100) {
5436
0
                            keys.swap(async_recycled_rowset_keys);
5437
0
                        }
5438
1
                    }
5439
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5440
1
                    if (keys.empty()) return;
5441
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5442
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5443
0
                                     << instance_id_;
5444
0
                    } else {
5445
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5446
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5447
0
                                           num_recycled, start_time);
5448
0
                    }
5449
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5426
784
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5427
784
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5429
0
                        return;
5430
0
                    }
5431
784
                    std::vector<std::string> keys;
5432
784
                    {
5433
784
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5434
784
                        async_recycled_rowset_keys.push_back(std::move(key));
5435
784
                        if (async_recycled_rowset_keys.size() > 100) {
5436
7
                            keys.swap(async_recycled_rowset_keys);
5437
7
                        }
5438
784
                    }
5439
784
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5440
784
                    if (keys.empty()) return;
5441
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5442
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5443
0
                                     << instance_id_;
5444
7
                    } else {
5445
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5446
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5447
7
                                           num_recycled, start_time);
5448
7
                    }
5449
7
                },
5450
903
                0);
5451
903
        if (ret == 0) return 0;
5452
        // Submit task failed, delete rowset data in current thread
5453
118
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5454
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5455
0
            return -1;
5456
0
        }
5457
118
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5458
0
            return -1;
5459
0
        }
5460
118
        rowset_keys.push_back(std::move(key));
5461
118
        return 0;
5462
118
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5423
1
                                            int64_t tablet_id, const std::string& rowset_id) {
5424
        // Try to delete rowset data in background thread
5425
1
        int ret = worker_pool->submit_with_timeout(
5426
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5427
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5428
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5429
1
                        return;
5430
1
                    }
5431
1
                    std::vector<std::string> keys;
5432
1
                    {
5433
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5434
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5435
1
                        if (async_recycled_rowset_keys.size() > 100) {
5436
1
                            keys.swap(async_recycled_rowset_keys);
5437
1
                        }
5438
1
                    }
5439
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5440
1
                    if (keys.empty()) return;
5441
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5442
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5443
1
                                     << instance_id_;
5444
1
                    } else {
5445
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5446
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5447
1
                                           num_recycled, start_time);
5448
1
                    }
5449
1
                },
5450
1
                0);
5451
1
        if (ret == 0) return 0;
5452
        // Submit task failed, delete rowset data in current thread
5453
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5454
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5455
0
            return -1;
5456
0
        }
5457
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5458
0
            return -1;
5459
0
        }
5460
0
        rowset_keys.push_back(std::move(key));
5461
0
        return 0;
5462
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5423
902
                                            int64_t tablet_id, const std::string& rowset_id) {
5424
        // Try to delete rowset data in background thread
5425
902
        int ret = worker_pool->submit_with_timeout(
5426
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5427
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5428
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5429
902
                        return;
5430
902
                    }
5431
902
                    std::vector<std::string> keys;
5432
902
                    {
5433
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5434
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5435
902
                        if (async_recycled_rowset_keys.size() > 100) {
5436
902
                            keys.swap(async_recycled_rowset_keys);
5437
902
                        }
5438
902
                    }
5439
902
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5440
902
                    if (keys.empty()) return;
5441
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5442
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5443
902
                                     << instance_id_;
5444
902
                    } else {
5445
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5446
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5447
902
                                           num_recycled, start_time);
5448
902
                    }
5449
902
                },
5450
902
                0);
5451
902
        if (ret == 0) return 0;
5452
        // Submit task failed, delete rowset data in current thread
5453
118
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5454
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5455
0
            return -1;
5456
0
        }
5457
118
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5458
0
            return -1;
5459
0
        }
5460
118
        rowset_keys.push_back(std::move(key));
5461
118
        return 0;
5462
118
    };
5463
5464
42
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5465
5466
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5467
4.28k
        ++num_scanned;
5468
4.28k
        total_rowset_key_size += k.size();
5469
4.28k
        total_rowset_value_size += v.size();
5470
4.28k
        RecycleRowsetPB rowset;
5471
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5472
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5473
0
            return -1;
5474
0
        }
5475
5476
4.28k
        int64_t current_time = ::time(nullptr);
5477
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5478
5479
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5480
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5481
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5482
4.28k
        if (current_time < expiration) { // not expired
5483
0
            return 0;
5484
0
        }
5485
4.28k
        ++num_expired;
5486
4.28k
        expired_rowset_size += v.size();
5487
5488
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5489
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5490
                // in old version, keep this key-value pair and it needs to be checked manually
5491
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5492
0
                return -1;
5493
0
            }
5494
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5495
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5496
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5497
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5498
0
                rowset_keys.emplace_back(k);
5499
0
                return -1;
5500
0
            }
5501
            // decode rowset_id
5502
250
            auto k1 = k;
5503
250
            k1.remove_prefix(1);
5504
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5505
250
            decode_key(&k1, &out);
5506
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5507
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5508
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5509
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5510
250
                      << " task_type=" << metrics_context.operation_type;
5511
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5512
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5513
0
                return -1;
5514
0
            }
5515
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5516
250
            metrics_context.total_recycled_num++;
5517
250
            segment_metrics_context_.total_recycled_data_size +=
5518
250
                    rowset.rowset_meta().total_disk_size();
5519
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5520
250
            return 0;
5521
250
        }
5522
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5523
5524
        // TODO(plat1ko): check rowset not referenced
5525
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5526
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5527
0
                LOG_INFO("recycle rowset that has empty resource id");
5528
0
            } else {
5529
                // other situations, keep this key-value pair and it needs to be checked manually
5530
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5531
0
                return -1;
5532
0
            }
5533
0
        }
5534
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5535
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5536
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5537
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5538
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5539
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5540
4.03k
                  << " rowset_meta_size=" << v.size()
5541
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5542
4.03k
                  << " task_type=" << metrics_context.operation_type;
5543
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5544
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5545
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5546
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5547
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5548
13
                                 "kv "
5549
13
                                 "at next turn, instance_id="
5550
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5551
13
                              << " version=[" << rowset_meta->start_version() << '-'
5552
13
                              << rowset_meta->end_version() << "]";
5553
13
                    return 0;
5554
13
                }
5555
23
            }
5556
5557
925
            num_prepare += 1;
5558
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5559
925
                rowset_meta->end_version() != 1) {
5560
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5561
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5562
272
                                 "instance_id="
5563
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5564
272
                              << " version=[" << rowset_meta->start_version() << '-'
5565
272
                              << rowset_meta->end_version() << "]";
5566
272
                    rowset_keys_to_abort_job.emplace_back(k);
5567
272
                    return 0;
5568
272
                }
5569
273
            }
5570
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5571
653
                                             rowset_meta->tablet_id(),
5572
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5573
0
                return -1;
5574
0
            }
5575
3.10k
        } else {
5576
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5577
3.10k
            rowset_keys.emplace_back(k);
5578
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5579
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5580
3.10k
                ++num_empty_rowset;
5581
3.10k
            }
5582
3.10k
        }
5583
3.75k
        return 0;
5584
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5466
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5467
7
        ++num_scanned;
5468
7
        total_rowset_key_size += k.size();
5469
7
        total_rowset_value_size += v.size();
5470
7
        RecycleRowsetPB rowset;
5471
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5472
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5473
0
            return -1;
5474
0
        }
5475
5476
7
        int64_t current_time = ::time(nullptr);
5477
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5478
5479
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5480
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5481
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5482
7
        if (current_time < expiration) { // not expired
5483
0
            return 0;
5484
0
        }
5485
7
        ++num_expired;
5486
7
        expired_rowset_size += v.size();
5487
5488
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5489
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5490
                // in old version, keep this key-value pair and it needs to be checked manually
5491
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5492
0
                return -1;
5493
0
            }
5494
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5495
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5496
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5497
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5498
0
                rowset_keys.emplace_back(k);
5499
0
                return -1;
5500
0
            }
5501
            // decode rowset_id
5502
0
            auto k1 = k;
5503
0
            k1.remove_prefix(1);
5504
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5505
0
            decode_key(&k1, &out);
5506
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5507
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5508
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5509
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5510
0
                      << " task_type=" << metrics_context.operation_type;
5511
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5512
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5513
0
                return -1;
5514
0
            }
5515
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5516
0
            metrics_context.total_recycled_num++;
5517
0
            segment_metrics_context_.total_recycled_data_size +=
5518
0
                    rowset.rowset_meta().total_disk_size();
5519
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5520
0
            return 0;
5521
0
        }
5522
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5523
5524
        // TODO(plat1ko): check rowset not referenced
5525
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5526
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5527
0
                LOG_INFO("recycle rowset that has empty resource id");
5528
0
            } else {
5529
                // other situations, keep this key-value pair and it needs to be checked manually
5530
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5531
0
                return -1;
5532
0
            }
5533
0
        }
5534
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5535
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5536
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5537
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5538
7
                  << "] txn_id=" << rowset_meta->txn_id()
5539
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5540
7
                  << " rowset_meta_size=" << v.size()
5541
7
                  << " creation_time=" << rowset_meta->creation_time()
5542
7
                  << " task_type=" << metrics_context.operation_type;
5543
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5544
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5545
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5546
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5547
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5548
4
                                 "kv "
5549
4
                                 "at next turn, instance_id="
5550
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5551
4
                              << " version=[" << rowset_meta->start_version() << '-'
5552
4
                              << rowset_meta->end_version() << "]";
5553
4
                    return 0;
5554
4
                }
5555
6
            }
5556
5557
3
            num_prepare += 1;
5558
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5559
3
                rowset_meta->end_version() != 1) {
5560
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5561
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5562
2
                                 "instance_id="
5563
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5564
2
                              << " version=[" << rowset_meta->start_version() << '-'
5565
2
                              << rowset_meta->end_version() << "]";
5566
2
                    rowset_keys_to_abort_job.emplace_back(k);
5567
2
                    return 0;
5568
2
                }
5569
2
            }
5570
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5571
1
                                             rowset_meta->tablet_id(),
5572
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5573
0
                return -1;
5574
0
            }
5575
1
        } else {
5576
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5577
0
            rowset_keys.emplace_back(k);
5578
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5579
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5580
0
                ++num_empty_rowset;
5581
0
            }
5582
0
        }
5583
1
        return 0;
5584
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5466
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5467
4.28k
        ++num_scanned;
5468
4.28k
        total_rowset_key_size += k.size();
5469
4.28k
        total_rowset_value_size += v.size();
5470
4.28k
        RecycleRowsetPB rowset;
5471
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5472
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5473
0
            return -1;
5474
0
        }
5475
5476
4.28k
        int64_t current_time = ::time(nullptr);
5477
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5478
5479
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5480
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5481
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5482
4.28k
        if (current_time < expiration) { // not expired
5483
0
            return 0;
5484
0
        }
5485
4.28k
        ++num_expired;
5486
4.28k
        expired_rowset_size += v.size();
5487
5488
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5489
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5490
                // in old version, keep this key-value pair and it needs to be checked manually
5491
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5492
0
                return -1;
5493
0
            }
5494
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5495
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5496
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5497
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5498
0
                rowset_keys.emplace_back(k);
5499
0
                return -1;
5500
0
            }
5501
            // decode rowset_id
5502
250
            auto k1 = k;
5503
250
            k1.remove_prefix(1);
5504
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5505
250
            decode_key(&k1, &out);
5506
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5507
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5508
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5509
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5510
250
                      << " task_type=" << metrics_context.operation_type;
5511
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5512
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5513
0
                return -1;
5514
0
            }
5515
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5516
250
            metrics_context.total_recycled_num++;
5517
250
            segment_metrics_context_.total_recycled_data_size +=
5518
250
                    rowset.rowset_meta().total_disk_size();
5519
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5520
250
            return 0;
5521
250
        }
5522
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5523
5524
        // TODO(plat1ko): check rowset not referenced
5525
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5526
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5527
0
                LOG_INFO("recycle rowset that has empty resource id");
5528
0
            } else {
5529
                // other situations, keep this key-value pair and it needs to be checked manually
5530
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5531
0
                return -1;
5532
0
            }
5533
0
        }
5534
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5535
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5536
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5537
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5538
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5539
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5540
4.03k
                  << " rowset_meta_size=" << v.size()
5541
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5542
4.03k
                  << " task_type=" << metrics_context.operation_type;
5543
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5544
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5545
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5546
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5547
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5548
9
                                 "kv "
5549
9
                                 "at next turn, instance_id="
5550
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5551
9
                              << " version=[" << rowset_meta->start_version() << '-'
5552
9
                              << rowset_meta->end_version() << "]";
5553
9
                    return 0;
5554
9
                }
5555
17
            }
5556
5557
922
            num_prepare += 1;
5558
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5559
922
                rowset_meta->end_version() != 1) {
5560
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5561
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5562
270
                                 "instance_id="
5563
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5564
270
                              << " version=[" << rowset_meta->start_version() << '-'
5565
270
                              << rowset_meta->end_version() << "]";
5566
270
                    rowset_keys_to_abort_job.emplace_back(k);
5567
270
                    return 0;
5568
270
                }
5569
271
            }
5570
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5571
652
                                             rowset_meta->tablet_id(),
5572
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5573
0
                return -1;
5574
0
            }
5575
3.10k
        } else {
5576
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5577
3.10k
            rowset_keys.emplace_back(k);
5578
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5579
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5580
3.10k
                ++num_empty_rowset;
5581
3.10k
            }
5582
3.10k
        }
5583
3.75k
        return 0;
5584
4.03k
    };
5585
5586
48
    auto loop_done = [&]() -> int {
5587
48
        std::vector<std::string> rowset_keys_to_delete;
5588
        // rowset_id -> rowset_meta
5589
        // store rowset id and meta for statistics rs size when delete
5590
48
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5591
48
        std::vector<std::string> mark_keys_to_process;
5592
48
        std::vector<std::string> abort_job_keys_to_process;
5593
48
        rowset_keys_to_delete.swap(rowset_keys);
5594
48
        rowsets_to_delete.swap(rowsets);
5595
48
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5596
48
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5597
48
        if (!mark_keys_to_process.empty()) {
5598
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5599
11
                    *worker_pool, std::move(mark_keys_to_process));
5600
11
        }
5601
48
        if (!abort_job_keys_to_process.empty()) {
5602
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5603
15
                                               &num_recycled);
5604
15
        }
5605
48
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5606
48
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5607
48
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5608
48
                                   metrics_context) != 0) {
5609
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5610
0
                return;
5611
0
            }
5612
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5613
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5614
0
                    return;
5615
0
                }
5616
3.10k
            }
5617
48
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5618
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5619
0
                return;
5620
0
            }
5621
48
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5622
48
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5606
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5607
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5608
7
                                   metrics_context) != 0) {
5609
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5610
0
                return;
5611
0
            }
5612
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5613
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5614
0
                    return;
5615
0
                }
5616
0
            }
5617
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5618
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5619
0
                return;
5620
0
            }
5621
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5622
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5606
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5607
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5608
41
                                   metrics_context) != 0) {
5609
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5610
0
                return;
5611
0
            }
5612
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5613
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5614
0
                    return;
5615
0
                }
5616
3.10k
            }
5617
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5618
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5619
0
                return;
5620
0
            }
5621
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5622
41
        });
5623
48
        return 0;
5624
48
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5586
7
    auto loop_done = [&]() -> int {
5587
7
        std::vector<std::string> rowset_keys_to_delete;
5588
        // rowset_id -> rowset_meta
5589
        // store rowset id and meta for statistics rs size when delete
5590
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5591
7
        std::vector<std::string> mark_keys_to_process;
5592
7
        std::vector<std::string> abort_job_keys_to_process;
5593
7
        rowset_keys_to_delete.swap(rowset_keys);
5594
7
        rowsets_to_delete.swap(rowsets);
5595
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5596
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5597
7
        if (!mark_keys_to_process.empty()) {
5598
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5599
4
                    *worker_pool, std::move(mark_keys_to_process));
5600
4
        }
5601
7
        if (!abort_job_keys_to_process.empty()) {
5602
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5603
2
                                               &num_recycled);
5604
2
        }
5605
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5606
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5607
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5608
7
                                   metrics_context) != 0) {
5609
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5610
7
                return;
5611
7
            }
5612
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5613
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5614
7
                    return;
5615
7
                }
5616
7
            }
5617
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5618
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5619
7
                return;
5620
7
            }
5621
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5622
7
        });
5623
7
        return 0;
5624
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5586
41
    auto loop_done = [&]() -> int {
5587
41
        std::vector<std::string> rowset_keys_to_delete;
5588
        // rowset_id -> rowset_meta
5589
        // store rowset id and meta for statistics rs size when delete
5590
41
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5591
41
        std::vector<std::string> mark_keys_to_process;
5592
41
        std::vector<std::string> abort_job_keys_to_process;
5593
41
        rowset_keys_to_delete.swap(rowset_keys);
5594
41
        rowsets_to_delete.swap(rowsets);
5595
41
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5596
41
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5597
41
        if (!mark_keys_to_process.empty()) {
5598
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5599
7
                    *worker_pool, std::move(mark_keys_to_process));
5600
7
        }
5601
41
        if (!abort_job_keys_to_process.empty()) {
5602
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5603
13
                                               &num_recycled);
5604
13
        }
5605
41
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5606
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5607
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5608
41
                                   metrics_context) != 0) {
5609
41
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5610
41
                return;
5611
41
            }
5612
41
            for (const auto& [_, rs] : rowsets_to_delete) {
5613
41
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5614
41
                    return;
5615
41
                }
5616
41
            }
5617
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5618
41
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5619
41
                return;
5620
41
            }
5621
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5622
41
        });
5623
41
        return 0;
5624
41
    };
5625
5626
42
    if (config::enable_recycler_stats_metrics) {
5627
0
        scan_and_statistics_rowsets();
5628
0
    }
5629
    // recycle_func and loop_done for scan and recycle
5630
42
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5631
42
                               std::move(loop_done));
5632
5633
42
    worker_pool->stop();
5634
5635
42
    if (!async_recycled_rowset_keys.empty()) {
5636
4
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5637
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5638
0
            return -1;
5639
4
        } else {
5640
4
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5641
4
        }
5642
4
    }
5643
5644
    // Report final metrics after all concurrent tasks completed
5645
42
    segment_metrics_context_.report();
5646
42
    metrics_context.report();
5647
5648
42
    return ret;
5649
42
}
5650
5651
13
int InstanceRecycler::recycle_restore_jobs() {
5652
13
    const std::string task_name = "recycle_restore_jobs";
5653
13
    int64_t num_scanned = 0;
5654
13
    int64_t num_expired = 0;
5655
13
    int64_t num_recycled = 0;
5656
13
    int64_t num_aborted = 0;
5657
5658
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5659
5660
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5661
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5662
13
    std::string restore_job_key0;
5663
13
    std::string restore_job_key1;
5664
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5665
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5666
5667
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5668
5669
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5670
13
    register_recycle_task(task_name, start_time);
5671
5672
13
    DORIS_CLOUD_DEFER {
5673
13
        unregister_recycle_task(task_name);
5674
13
        int64_t cost =
5675
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5676
13
        metrics_context.finish_report();
5677
5678
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5679
13
                .tag("instance_id", instance_id_)
5680
13
                .tag("num_scanned", num_scanned)
5681
13
                .tag("num_expired", num_expired)
5682
13
                .tag("num_recycled", num_recycled)
5683
13
                .tag("num_aborted", num_aborted);
5684
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5672
13
    DORIS_CLOUD_DEFER {
5673
13
        unregister_recycle_task(task_name);
5674
13
        int64_t cost =
5675
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5676
13
        metrics_context.finish_report();
5677
5678
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5679
13
                .tag("instance_id", instance_id_)
5680
13
                .tag("num_scanned", num_scanned)
5681
13
                .tag("num_expired", num_expired)
5682
13
                .tag("num_recycled", num_recycled)
5683
13
                .tag("num_aborted", num_aborted);
5684
13
    };
5685
5686
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5687
5688
13
    std::vector<std::string_view> restore_job_keys;
5689
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5690
41
        ++num_scanned;
5691
41
        RestoreJobCloudPB restore_job_pb;
5692
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5693
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5694
0
            return -1;
5695
0
        }
5696
41
        int64_t expiration =
5697
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5698
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5699
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5700
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5701
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5702
0
                   << " state=" << restore_job_pb.state();
5703
41
        int64_t current_time = ::time(nullptr);
5704
41
        if (current_time < expiration) { // not expired
5705
0
            return 0;
5706
0
        }
5707
41
        ++num_expired;
5708
5709
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5710
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5711
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5712
5713
41
        std::unique_ptr<Transaction> txn;
5714
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5715
41
        if (err != TxnErrorCode::TXN_OK) {
5716
0
            LOG_WARNING("failed to recycle restore job")
5717
0
                    .tag("err", err)
5718
0
                    .tag("tablet id", tablet_id)
5719
0
                    .tag("instance_id", instance_id_)
5720
0
                    .tag("reason", "failed to create txn");
5721
0
            return -1;
5722
0
        }
5723
5724
41
        std::string val;
5725
41
        err = txn->get(k, &val);
5726
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5727
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5728
0
            return 0;
5729
0
        }
5730
41
        if (err != TxnErrorCode::TXN_OK) {
5731
0
            LOG_WARNING("failed to get kv");
5732
0
            return -1;
5733
0
        }
5734
41
        restore_job_pb.Clear();
5735
41
        if (!restore_job_pb.ParseFromString(val)) {
5736
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5737
0
            return -1;
5738
0
        }
5739
5740
        // PREPARED or COMMITTED, change state to DROPPED and return
5741
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5742
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5743
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5744
0
            restore_job_pb.set_need_recycle_data(true);
5745
0
            txn->put(k, restore_job_pb.SerializeAsString());
5746
0
            err = txn->commit();
5747
0
            if (err != TxnErrorCode::TXN_OK) {
5748
0
                LOG_WARNING("failed to commit txn: {}", err);
5749
0
                return -1;
5750
0
            }
5751
0
            num_aborted++;
5752
0
            return 0;
5753
0
        }
5754
5755
        // Change state to RECYCLING
5756
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5757
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5758
21
            txn->put(k, restore_job_pb.SerializeAsString());
5759
21
            err = txn->commit();
5760
21
            if (err != TxnErrorCode::TXN_OK) {
5761
0
                LOG_WARNING("failed to commit txn: {}", err);
5762
0
                return -1;
5763
0
            }
5764
21
            return 0;
5765
21
        }
5766
5767
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5768
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5769
5770
        // Recycle all data associated with the restore job.
5771
        // This includes rowsets, segments, and related resources.
5772
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5773
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5774
0
            LOG_WARNING("failed to recycle tablet")
5775
0
                    .tag("tablet_id", tablet_id)
5776
0
                    .tag("instance_id", instance_id_);
5777
0
            return -1;
5778
0
        }
5779
5780
        // delete all restore job rowset kv
5781
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5782
5783
20
        err = txn->commit();
5784
20
        if (err != TxnErrorCode::TXN_OK) {
5785
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5786
0
                    .tag("err", err)
5787
0
                    .tag("tablet id", tablet_id)
5788
0
                    .tag("instance_id", instance_id_)
5789
0
                    .tag("reason", "failed to commit txn");
5790
0
            return -1;
5791
0
        }
5792
5793
20
        metrics_context.total_recycled_num = ++num_recycled;
5794
20
        metrics_context.report();
5795
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5796
20
        restore_job_keys.push_back(k);
5797
5798
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5799
20
                  << " tablet_id=" << tablet_id;
5800
20
        return 0;
5801
20
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5689
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5690
41
        ++num_scanned;
5691
41
        RestoreJobCloudPB restore_job_pb;
5692
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5693
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5694
0
            return -1;
5695
0
        }
5696
41
        int64_t expiration =
5697
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5698
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5699
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5700
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5701
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5702
0
                   << " state=" << restore_job_pb.state();
5703
41
        int64_t current_time = ::time(nullptr);
5704
41
        if (current_time < expiration) { // not expired
5705
0
            return 0;
5706
0
        }
5707
41
        ++num_expired;
5708
5709
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5710
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5711
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5712
5713
41
        std::unique_ptr<Transaction> txn;
5714
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5715
41
        if (err != TxnErrorCode::TXN_OK) {
5716
0
            LOG_WARNING("failed to recycle restore job")
5717
0
                    .tag("err", err)
5718
0
                    .tag("tablet id", tablet_id)
5719
0
                    .tag("instance_id", instance_id_)
5720
0
                    .tag("reason", "failed to create txn");
5721
0
            return -1;
5722
0
        }
5723
5724
41
        std::string val;
5725
41
        err = txn->get(k, &val);
5726
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5727
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5728
0
            return 0;
5729
0
        }
5730
41
        if (err != TxnErrorCode::TXN_OK) {
5731
0
            LOG_WARNING("failed to get kv");
5732
0
            return -1;
5733
0
        }
5734
41
        restore_job_pb.Clear();
5735
41
        if (!restore_job_pb.ParseFromString(val)) {
5736
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5737
0
            return -1;
5738
0
        }
5739
5740
        // PREPARED or COMMITTED, change state to DROPPED and return
5741
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5742
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5743
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5744
0
            restore_job_pb.set_need_recycle_data(true);
5745
0
            txn->put(k, restore_job_pb.SerializeAsString());
5746
0
            err = txn->commit();
5747
0
            if (err != TxnErrorCode::TXN_OK) {
5748
0
                LOG_WARNING("failed to commit txn: {}", err);
5749
0
                return -1;
5750
0
            }
5751
0
            num_aborted++;
5752
0
            return 0;
5753
0
        }
5754
5755
        // Change state to RECYCLING
5756
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5757
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5758
21
            txn->put(k, restore_job_pb.SerializeAsString());
5759
21
            err = txn->commit();
5760
21
            if (err != TxnErrorCode::TXN_OK) {
5761
0
                LOG_WARNING("failed to commit txn: {}", err);
5762
0
                return -1;
5763
0
            }
5764
21
            return 0;
5765
21
        }
5766
5767
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5768
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5769
5770
        // Recycle all data associated with the restore job.
5771
        // This includes rowsets, segments, and related resources.
5772
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5773
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5774
0
            LOG_WARNING("failed to recycle tablet")
5775
0
                    .tag("tablet_id", tablet_id)
5776
0
                    .tag("instance_id", instance_id_);
5777
0
            return -1;
5778
0
        }
5779
5780
        // delete all restore job rowset kv
5781
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5782
5783
20
        err = txn->commit();
5784
20
        if (err != TxnErrorCode::TXN_OK) {
5785
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5786
0
                    .tag("err", err)
5787
0
                    .tag("tablet id", tablet_id)
5788
0
                    .tag("instance_id", instance_id_)
5789
0
                    .tag("reason", "failed to commit txn");
5790
0
            return -1;
5791
0
        }
5792
5793
20
        metrics_context.total_recycled_num = ++num_recycled;
5794
20
        metrics_context.report();
5795
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5796
20
        restore_job_keys.push_back(k);
5797
5798
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5799
20
                  << " tablet_id=" << tablet_id;
5800
20
        return 0;
5801
20
    };
5802
5803
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5804
3
        if (restore_job_keys.empty()) return 0;
5805
1
        DORIS_CLOUD_DEFER {
5806
1
            restore_job_keys.clear();
5807
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5805
1
        DORIS_CLOUD_DEFER {
5806
1
            restore_job_keys.clear();
5807
1
        };
5808
5809
1
        std::unique_ptr<Transaction> txn;
5810
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5811
1
        if (err != TxnErrorCode::TXN_OK) {
5812
0
            LOG_WARNING("failed to recycle restore job")
5813
0
                    .tag("err", err)
5814
0
                    .tag("instance_id", instance_id_)
5815
0
                    .tag("reason", "failed to create txn");
5816
0
            return -1;
5817
0
        }
5818
20
        for (auto& k : restore_job_keys) {
5819
20
            txn->remove(k);
5820
20
        }
5821
1
        err = txn->commit();
5822
1
        if (err != TxnErrorCode::TXN_OK) {
5823
0
            LOG_WARNING("failed to recycle restore job")
5824
0
                    .tag("err", err)
5825
0
                    .tag("instance_id", instance_id_)
5826
0
                    .tag("reason", "failed to commit txn");
5827
0
            return -1;
5828
0
        }
5829
1
        return 0;
5830
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5803
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5804
3
        if (restore_job_keys.empty()) return 0;
5805
1
        DORIS_CLOUD_DEFER {
5806
1
            restore_job_keys.clear();
5807
1
        };
5808
5809
1
        std::unique_ptr<Transaction> txn;
5810
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5811
1
        if (err != TxnErrorCode::TXN_OK) {
5812
0
            LOG_WARNING("failed to recycle restore job")
5813
0
                    .tag("err", err)
5814
0
                    .tag("instance_id", instance_id_)
5815
0
                    .tag("reason", "failed to create txn");
5816
0
            return -1;
5817
0
        }
5818
20
        for (auto& k : restore_job_keys) {
5819
20
            txn->remove(k);
5820
20
        }
5821
1
        err = txn->commit();
5822
1
        if (err != TxnErrorCode::TXN_OK) {
5823
0
            LOG_WARNING("failed to recycle restore job")
5824
0
                    .tag("err", err)
5825
0
                    .tag("instance_id", instance_id_)
5826
0
                    .tag("reason", "failed to commit txn");
5827
0
            return -1;
5828
0
        }
5829
1
        return 0;
5830
1
    };
5831
5832
13
    if (config::enable_recycler_stats_metrics) {
5833
0
        scan_and_statistics_restore_jobs();
5834
0
    }
5835
5836
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5837
13
                            std::move(loop_done));
5838
13
}
5839
5840
11
int InstanceRecycler::recycle_versioned_rowsets() {
5841
11
    const std::string task_name = "recycle_rowsets";
5842
11
    int64_t num_scanned = 0;
5843
11
    int64_t num_expired = 0;
5844
11
    int64_t num_prepare = 0;
5845
11
    int64_t num_compacted = 0;
5846
11
    int64_t num_empty_rowset = 0;
5847
11
    size_t total_rowset_key_size = 0;
5848
11
    size_t total_rowset_value_size = 0;
5849
11
    size_t expired_rowset_size = 0;
5850
11
    std::atomic_long num_recycled = 0;
5851
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5852
5853
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5854
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5855
11
    std::string recyc_rs_key0;
5856
11
    std::string recyc_rs_key1;
5857
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5858
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5859
5860
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5861
5862
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5863
11
    register_recycle_task(task_name, start_time);
5864
5865
11
    DORIS_CLOUD_DEFER {
5866
11
        unregister_recycle_task(task_name);
5867
11
        int64_t cost =
5868
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5869
11
        metrics_context.finish_report();
5870
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5871
11
                .tag("instance_id", instance_id_)
5872
11
                .tag("num_scanned", num_scanned)
5873
11
                .tag("num_expired", num_expired)
5874
11
                .tag("num_recycled", num_recycled)
5875
11
                .tag("num_recycled.prepare", num_prepare)
5876
11
                .tag("num_recycled.compacted", num_compacted)
5877
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5878
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5879
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5880
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5881
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5865
11
    DORIS_CLOUD_DEFER {
5866
11
        unregister_recycle_task(task_name);
5867
11
        int64_t cost =
5868
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5869
11
        metrics_context.finish_report();
5870
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5871
11
                .tag("instance_id", instance_id_)
5872
11
                .tag("num_scanned", num_scanned)
5873
11
                .tag("num_expired", num_expired)
5874
11
                .tag("num_recycled", num_recycled)
5875
11
                .tag("num_recycled.prepare", num_prepare)
5876
11
                .tag("num_recycled.compacted", num_compacted)
5877
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5878
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5879
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5880
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5881
11
    };
5882
5883
11
    std::vector<std::string> orphan_rowset_keys;
5884
5885
    // Store keys of rowset recycled by background workers
5886
11
    std::mutex async_recycled_rowset_keys_mutex;
5887
11
    std::vector<std::string> async_recycled_rowset_keys;
5888
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5889
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5890
11
    worker_pool->start();
5891
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5892
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5893
        // Try to delete rowset data in background thread
5894
400
        int ret = worker_pool->submit_with_timeout(
5895
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5896
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5897
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5898
400
                        return;
5899
400
                    }
5900
                    // The async recycled rowsets are staled format or has not been used,
5901
                    // so we don't need to check the rowset ref count key.
5902
0
                    std::vector<std::string> keys;
5903
0
                    {
5904
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5905
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5906
0
                        if (async_recycled_rowset_keys.size() > 100) {
5907
0
                            keys.swap(async_recycled_rowset_keys);
5908
0
                        }
5909
0
                    }
5910
0
                    if (keys.empty()) return;
5911
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5912
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5913
0
                                     << instance_id_;
5914
0
                    } else {
5915
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5916
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5917
0
                                           num_recycled, start_time);
5918
0
                    }
5919
0
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5895
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5896
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5897
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5898
400
                        return;
5899
400
                    }
5900
                    // The async recycled rowsets are staled format or has not been used,
5901
                    // so we don't need to check the rowset ref count key.
5902
0
                    std::vector<std::string> keys;
5903
0
                    {
5904
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5905
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5906
0
                        if (async_recycled_rowset_keys.size() > 100) {
5907
0
                            keys.swap(async_recycled_rowset_keys);
5908
0
                        }
5909
0
                    }
5910
0
                    if (keys.empty()) return;
5911
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5912
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5913
0
                                     << instance_id_;
5914
0
                    } else {
5915
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5916
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5917
0
                                           num_recycled, start_time);
5918
0
                    }
5919
0
                },
5920
400
                0);
5921
400
        if (ret == 0) return 0;
5922
        // Submit task failed, delete rowset data in current thread
5923
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5924
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5925
0
            return -1;
5926
0
        }
5927
0
        orphan_rowset_keys.push_back(std::move(key));
5928
0
        return 0;
5929
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5892
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5893
        // Try to delete rowset data in background thread
5894
400
        int ret = worker_pool->submit_with_timeout(
5895
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5896
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5897
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5898
400
                        return;
5899
400
                    }
5900
                    // The async recycled rowsets are staled format or has not been used,
5901
                    // so we don't need to check the rowset ref count key.
5902
400
                    std::vector<std::string> keys;
5903
400
                    {
5904
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5905
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5906
400
                        if (async_recycled_rowset_keys.size() > 100) {
5907
400
                            keys.swap(async_recycled_rowset_keys);
5908
400
                        }
5909
400
                    }
5910
400
                    if (keys.empty()) return;
5911
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5912
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5913
400
                                     << instance_id_;
5914
400
                    } else {
5915
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5916
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5917
400
                                           num_recycled, start_time);
5918
400
                    }
5919
400
                },
5920
400
                0);
5921
400
        if (ret == 0) return 0;
5922
        // Submit task failed, delete rowset data in current thread
5923
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5924
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5925
0
            return -1;
5926
0
        }
5927
0
        orphan_rowset_keys.push_back(std::move(key));
5928
0
        return 0;
5929
0
    };
5930
5931
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5932
5933
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5934
2.01k
        ++num_scanned;
5935
2.01k
        total_rowset_key_size += k.size();
5936
2.01k
        total_rowset_value_size += v.size();
5937
2.01k
        RecycleRowsetPB rowset;
5938
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5939
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5940
0
            return -1;
5941
0
        }
5942
5943
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5944
5945
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5946
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5947
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5948
2.01k
        int64_t current_time = ::time(nullptr);
5949
2.01k
        if (current_time < final_expiration) { // not expired
5950
0
            return 0;
5951
0
        }
5952
2.01k
        ++num_expired;
5953
2.01k
        expired_rowset_size += v.size();
5954
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5955
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5956
                // in old version, keep this key-value pair and it needs to be checked manually
5957
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5958
0
                return -1;
5959
0
            }
5960
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5961
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5962
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5963
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5964
0
                orphan_rowset_keys.emplace_back(k);
5965
0
                return -1;
5966
0
            }
5967
            // decode rowset_id
5968
0
            auto k1 = k;
5969
0
            k1.remove_prefix(1);
5970
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5971
0
            decode_key(&k1, &out);
5972
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5973
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5974
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5975
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5976
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5977
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5978
0
                return -1;
5979
0
            }
5980
0
            return 0;
5981
0
        }
5982
        // TODO(plat1ko): check rowset not referenced
5983
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5984
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5985
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5986
0
                LOG_INFO("recycle rowset that has empty resource id");
5987
0
            } else {
5988
                // other situations, keep this key-value pair and it needs to be checked manually
5989
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5990
0
                return -1;
5991
0
            }
5992
0
        }
5993
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5994
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5995
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5996
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5997
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5998
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5999
2.01k
                  << " rowset_meta_size=" << v.size()
6000
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6001
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6002
            // unable to calculate file path, can only be deleted by rowset id prefix
6003
400
            num_prepare += 1;
6004
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6005
400
                                             rowset_meta->tablet_id(),
6006
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6007
0
                return -1;
6008
0
            }
6009
1.61k
        } else {
6010
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6011
1.61k
            worker_pool->submit(
6012
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6013
                        // The load & compact rowset keys are recycled during recycling operation logs.
6014
1.61k
                        RowsetDeleteTask task;
6015
1.61k
                        task.rowset_meta = rowset_meta;
6016
1.61k
                        task.recycle_rowset_key = k;
6017
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6018
1.60k
                            return;
6019
1.60k
                        }
6020
13
                        num_compacted += is_compacted;
6021
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6022
13
                        if (rowset_meta.num_segments() == 0) {
6023
0
                            ++num_empty_rowset;
6024
0
                        }
6025
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
6012
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6013
                        // The load & compact rowset keys are recycled during recycling operation logs.
6014
1.61k
                        RowsetDeleteTask task;
6015
1.61k
                        task.rowset_meta = rowset_meta;
6016
1.61k
                        task.recycle_rowset_key = k;
6017
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6018
1.60k
                            return;
6019
1.60k
                        }
6020
13
                        num_compacted += is_compacted;
6021
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6022
13
                        if (rowset_meta.num_segments() == 0) {
6023
0
                            ++num_empty_rowset;
6024
0
                        }
6025
13
                    });
6026
1.61k
        }
6027
2.01k
        return 0;
6028
2.01k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5933
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5934
2.01k
        ++num_scanned;
5935
2.01k
        total_rowset_key_size += k.size();
5936
2.01k
        total_rowset_value_size += v.size();
5937
2.01k
        RecycleRowsetPB rowset;
5938
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5939
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5940
0
            return -1;
5941
0
        }
5942
5943
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5944
5945
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5946
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5947
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5948
2.01k
        int64_t current_time = ::time(nullptr);
5949
2.01k
        if (current_time < final_expiration) { // not expired
5950
0
            return 0;
5951
0
        }
5952
2.01k
        ++num_expired;
5953
2.01k
        expired_rowset_size += v.size();
5954
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5955
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5956
                // in old version, keep this key-value pair and it needs to be checked manually
5957
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5958
0
                return -1;
5959
0
            }
5960
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5961
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5962
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5963
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5964
0
                orphan_rowset_keys.emplace_back(k);
5965
0
                return -1;
5966
0
            }
5967
            // decode rowset_id
5968
0
            auto k1 = k;
5969
0
            k1.remove_prefix(1);
5970
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5971
0
            decode_key(&k1, &out);
5972
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5973
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5974
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5975
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5976
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5977
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5978
0
                return -1;
5979
0
            }
5980
0
            return 0;
5981
0
        }
5982
        // TODO(plat1ko): check rowset not referenced
5983
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5984
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5985
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5986
0
                LOG_INFO("recycle rowset that has empty resource id");
5987
0
            } else {
5988
                // other situations, keep this key-value pair and it needs to be checked manually
5989
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5990
0
                return -1;
5991
0
            }
5992
0
        }
5993
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5994
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5995
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5996
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5997
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5998
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5999
2.01k
                  << " rowset_meta_size=" << v.size()
6000
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6001
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6002
            // unable to calculate file path, can only be deleted by rowset id prefix
6003
400
            num_prepare += 1;
6004
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6005
400
                                             rowset_meta->tablet_id(),
6006
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6007
0
                return -1;
6008
0
            }
6009
1.61k
        } else {
6010
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6011
1.61k
            worker_pool->submit(
6012
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6013
                        // The load & compact rowset keys are recycled during recycling operation logs.
6014
1.61k
                        RowsetDeleteTask task;
6015
1.61k
                        task.rowset_meta = rowset_meta;
6016
1.61k
                        task.recycle_rowset_key = k;
6017
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6018
1.61k
                            return;
6019
1.61k
                        }
6020
1.61k
                        num_compacted += is_compacted;
6021
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6022
1.61k
                        if (rowset_meta.num_segments() == 0) {
6023
1.61k
                            ++num_empty_rowset;
6024
1.61k
                        }
6025
1.61k
                    });
6026
1.61k
        }
6027
2.01k
        return 0;
6028
2.01k
    };
6029
6030
11
    if (config::enable_recycler_stats_metrics) {
6031
0
        scan_and_statistics_rowsets();
6032
0
    }
6033
6034
11
    auto loop_done = [&]() -> int {
6035
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6036
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6037
0
        }
6038
6
        orphan_rowset_keys.clear();
6039
6
        return 0;
6040
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6034
6
    auto loop_done = [&]() -> int {
6035
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6036
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6037
0
        }
6038
6
        orphan_rowset_keys.clear();
6039
6
        return 0;
6040
6
    };
6041
6042
    // recycle_func and loop_done for scan and recycle
6043
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6044
11
                               std::move(loop_done));
6045
6046
11
    worker_pool->stop();
6047
6048
11
    if (!async_recycled_rowset_keys.empty()) {
6049
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6050
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6051
0
            return -1;
6052
0
        } else {
6053
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6054
0
        }
6055
0
    }
6056
6057
    // Report final metrics after all concurrent tasks completed
6058
11
    segment_metrics_context_.report();
6059
11
    metrics_context.report();
6060
6061
11
    return ret;
6062
11
}
6063
6064
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6065
1.61k
    constexpr int MAX_RETRY = 10;
6066
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6067
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6068
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6069
1.61k
    std::string_view reference_instance_id = instance_id_;
6070
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6071
8
        reference_instance_id = rowset_meta.reference_instance_id();
6072
8
    }
6073
6074
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6075
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6076
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6077
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6078
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6079
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6080
1.61k
        std::unique_ptr<Transaction> txn;
6081
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6082
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6083
0
            LOG_WARNING("failed to create txn").tag("err", err);
6084
0
            return -1;
6085
0
        }
6086
6087
1.61k
        std::string rowset_ref_count_key =
6088
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6089
1.61k
        int64_t ref_count = 0;
6090
1.61k
        {
6091
1.61k
            std::string value;
6092
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6093
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6094
                // This is the old version rowset, we could recycle it directly.
6095
1.60k
                ref_count = 1;
6096
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6097
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6098
0
                return -1;
6099
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6100
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6101
0
                return -1;
6102
0
            }
6103
1.61k
        }
6104
6105
1.61k
        if (ref_count == 1) {
6106
            // It would not be added since it is recycling.
6107
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6108
1.60k
                LOG_WARNING("failed to delete rowset data");
6109
1.60k
                return -1;
6110
1.60k
            }
6111
6112
            // Reset the transaction to avoid timeout.
6113
10
            err = txn_kv_->create_txn(&txn);
6114
10
            if (err != TxnErrorCode::TXN_OK) {
6115
0
                LOG_WARNING("failed to create txn").tag("err", err);
6116
0
                return -1;
6117
0
            }
6118
10
            txn->remove(rowset_ref_count_key);
6119
10
            LOG_INFO("delete rowset data ref count key")
6120
10
                    .tag("txn_id", rowset_meta.txn_id())
6121
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6122
6123
10
            std::string dbm_start_key =
6124
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6125
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6126
10
                    {reference_instance_id, tablet_id, rowset_id,
6127
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6128
10
            txn->remove(dbm_start_key, dbm_end_key);
6129
10
            LOG_INFO("remove delete bitmap kv")
6130
10
                    .tag("begin", hex(dbm_start_key))
6131
10
                    .tag("end", hex(dbm_end_key));
6132
6133
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6134
10
                    {reference_instance_id, tablet_id, rowset_id});
6135
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6136
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6137
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6138
10
            LOG_INFO("remove versioned delete bitmap kv")
6139
10
                    .tag("begin", hex(versioned_dbm_start_key))
6140
10
                    .tag("end", hex(versioned_dbm_end_key));
6141
10
        } else {
6142
            // Decrease the rowset ref count.
6143
            //
6144
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6145
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6146
2
            txn->atomic_add(rowset_ref_count_key, -1);
6147
2
            LOG_INFO("decrease rowset data ref count")
6148
2
                    .tag("txn_id", rowset_meta.txn_id())
6149
2
                    .tag("ref_count", ref_count - 1)
6150
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6151
2
        }
6152
6153
12
        if (!task.versioned_rowset_key.empty()) {
6154
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6155
0
                                                          task.versionstamp);
6156
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6157
0
        }
6158
6159
12
        if (!task.non_versioned_rowset_key.empty()) {
6160
0
            txn->remove(task.non_versioned_rowset_key);
6161
0
            LOG_INFO("remove non versioned rowset key")
6162
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6163
0
        }
6164
6165
        // empty when recycle ref rowsets for deleted instance
6166
13
        if (!task.recycle_rowset_key.empty()) {
6167
13
            txn->remove(task.recycle_rowset_key);
6168
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6169
13
        }
6170
6171
12
        err = txn->commit();
6172
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6173
            // The rowset ref count key has been changed, we need to retry.
6174
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6175
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6176
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6177
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6178
0
            continue;
6179
12
        } else if (err != TxnErrorCode::TXN_OK) {
6180
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6181
0
            return -1;
6182
0
        }
6183
12
        LOG_INFO("recycle rowset meta and data success");
6184
12
        return 0;
6185
12
    }
6186
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6187
1
            .tag("tablet_id", tablet_id)
6188
1
            .tag("rowset_id", rowset_id)
6189
1
            .tag("retry", MAX_RETRY);
6190
1
    return -1;
6191
1.61k
}
6192
6193
37
int InstanceRecycler::recycle_tmp_rowsets() {
6194
37
    const std::string task_name = "recycle_tmp_rowsets";
6195
37
    int64_t num_scanned = 0;
6196
37
    int64_t num_expired = 0;
6197
37
    std::atomic_long num_recycled = 0;
6198
37
    size_t expired_rowset_size = 0;
6199
37
    size_t total_rowset_key_size = 0;
6200
37
    size_t total_rowset_value_size = 0;
6201
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6202
6203
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6204
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6205
37
    std::string tmp_rs_key0;
6206
37
    std::string tmp_rs_key1;
6207
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6208
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6209
6210
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6211
6212
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6213
37
    register_recycle_task(task_name, start_time);
6214
6215
37
    DORIS_CLOUD_DEFER {
6216
37
        unregister_recycle_task(task_name);
6217
37
        int64_t cost =
6218
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6219
37
        metrics_context.finish_report();
6220
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6221
37
                .tag("instance_id", instance_id_)
6222
37
                .tag("num_scanned", num_scanned)
6223
37
                .tag("num_expired", num_expired)
6224
37
                .tag("num_recycled", num_recycled)
6225
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6226
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6227
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6228
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6215
12
    DORIS_CLOUD_DEFER {
6216
12
        unregister_recycle_task(task_name);
6217
12
        int64_t cost =
6218
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6219
12
        metrics_context.finish_report();
6220
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6221
12
                .tag("instance_id", instance_id_)
6222
12
                .tag("num_scanned", num_scanned)
6223
12
                .tag("num_expired", num_expired)
6224
12
                .tag("num_recycled", num_recycled)
6225
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6226
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6227
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6228
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6215
25
    DORIS_CLOUD_DEFER {
6216
25
        unregister_recycle_task(task_name);
6217
25
        int64_t cost =
6218
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6219
25
        metrics_context.finish_report();
6220
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6221
25
                .tag("instance_id", instance_id_)
6222
25
                .tag("num_scanned", num_scanned)
6223
25
                .tag("num_expired", num_expired)
6224
25
                .tag("num_recycled", num_recycled)
6225
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6226
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6227
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6228
25
    };
6229
6230
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6231
37
    std::vector<std::string> tmp_rowset_keys;
6232
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6233
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6234
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6235
6236
    // rowset_id -> rowset_meta
6237
    // store tmp_rowset id and meta for statistics rs size when delete
6238
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6239
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6240
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6241
37
    worker_pool->start();
6242
6243
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6244
6245
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6246
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6247
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6248
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6249
53.2k
                                    std::string_view k, std::string_view v) -> int {
6250
53.2k
        ++num_scanned;
6251
53.2k
        total_rowset_key_size += k.size();
6252
53.2k
        total_rowset_value_size += v.size();
6253
53.2k
        doris::RowsetMetaCloudPB rowset;
6254
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6255
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6256
0
            return -1;
6257
0
        }
6258
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6259
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6260
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6261
0
                   << " txn_expiration=" << rowset.txn_expiration()
6262
0
                   << " rowset_creation_time=" << rowset.creation_time();
6263
53.2k
        int64_t current_time = ::time(nullptr);
6264
53.2k
        if (current_time < expiration) { // not expired
6265
0
            return 0;
6266
0
        }
6267
53.2k
        ++num_expired;
6268
53.2k
        expired_rowset_size += v.size();
6269
53.2k
        if (!rowset.has_resource_id()) {
6270
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6271
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6272
0
                return -1;
6273
0
            }
6274
            // might be a delete pred rowset
6275
0
            tmp_rowset_keys.emplace_back(k);
6276
0
            return 0;
6277
0
        }
6278
6279
        // TODO(plat1ko): check rowset not referenced
6280
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6281
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6282
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6283
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6284
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6285
53.2k
                  << " num_expired=" << num_expired
6286
53.2k
                  << " task_type=" << metrics_context.operation_type;
6287
6288
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6289
16
            if (need_mark_rowset_as_recycled(rowset)) {
6290
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6291
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6292
9
                             "at next turn, instance_id="
6293
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6294
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6295
9
                return 0;
6296
9
            }
6297
16
        }
6298
6299
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6300
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6301
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6302
261
                             "instance_id="
6303
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6304
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6305
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6306
261
                return 0;
6307
261
            }
6308
265
        }
6309
6310
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6311
        // Remove the rowset ref count key directly since it has not been used.
6312
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6313
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6314
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6315
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6316
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6317
6318
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6319
53.0k
        return 0;
6320
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6249
16
                                    std::string_view k, std::string_view v) -> int {
6250
16
        ++num_scanned;
6251
16
        total_rowset_key_size += k.size();
6252
16
        total_rowset_value_size += v.size();
6253
16
        doris::RowsetMetaCloudPB rowset;
6254
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6255
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6256
0
            return -1;
6257
0
        }
6258
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6259
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6260
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6261
0
                   << " txn_expiration=" << rowset.txn_expiration()
6262
0
                   << " rowset_creation_time=" << rowset.creation_time();
6263
16
        int64_t current_time = ::time(nullptr);
6264
16
        if (current_time < expiration) { // not expired
6265
0
            return 0;
6266
0
        }
6267
16
        ++num_expired;
6268
16
        expired_rowset_size += v.size();
6269
16
        if (!rowset.has_resource_id()) {
6270
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6271
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6272
0
                return -1;
6273
0
            }
6274
            // might be a delete pred rowset
6275
0
            tmp_rowset_keys.emplace_back(k);
6276
0
            return 0;
6277
0
        }
6278
6279
        // TODO(plat1ko): check rowset not referenced
6280
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6281
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6282
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6283
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6284
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6285
16
                  << " num_expired=" << num_expired
6286
16
                  << " task_type=" << metrics_context.operation_type;
6287
6288
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6289
16
            if (need_mark_rowset_as_recycled(rowset)) {
6290
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6291
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6292
9
                             "at next turn, instance_id="
6293
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6294
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6295
9
                return 0;
6296
9
            }
6297
16
        }
6298
6299
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6300
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6301
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6302
3
                             "instance_id="
6303
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6304
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6305
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6306
3
                return 0;
6307
3
            }
6308
7
        }
6309
6310
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6311
        // Remove the rowset ref count key directly since it has not been used.
6312
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6313
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6314
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6315
4
                  << "key=" << hex(rowset_ref_count_key);
6316
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6317
6318
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6319
4
        return 0;
6320
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6249
53.2k
                                    std::string_view k, std::string_view v) -> int {
6250
53.2k
        ++num_scanned;
6251
53.2k
        total_rowset_key_size += k.size();
6252
53.2k
        total_rowset_value_size += v.size();
6253
53.2k
        doris::RowsetMetaCloudPB rowset;
6254
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6255
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6256
0
            return -1;
6257
0
        }
6258
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6259
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6260
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6261
0
                   << " txn_expiration=" << rowset.txn_expiration()
6262
0
                   << " rowset_creation_time=" << rowset.creation_time();
6263
53.2k
        int64_t current_time = ::time(nullptr);
6264
53.2k
        if (current_time < expiration) { // not expired
6265
0
            return 0;
6266
0
        }
6267
53.2k
        ++num_expired;
6268
53.2k
        expired_rowset_size += v.size();
6269
53.2k
        if (!rowset.has_resource_id()) {
6270
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6271
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6272
0
                return -1;
6273
0
            }
6274
            // might be a delete pred rowset
6275
0
            tmp_rowset_keys.emplace_back(k);
6276
0
            return 0;
6277
0
        }
6278
6279
        // TODO(plat1ko): check rowset not referenced
6280
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6281
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6282
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6283
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6284
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6285
53.2k
                  << " num_expired=" << num_expired
6286
53.2k
                  << " task_type=" << metrics_context.operation_type;
6287
6288
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6289
0
            if (need_mark_rowset_as_recycled(rowset)) {
6290
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6291
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6292
0
                             "at next turn, instance_id="
6293
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6294
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6295
0
                return 0;
6296
0
            }
6297
0
        }
6298
6299
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6300
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6301
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6302
258
                             "instance_id="
6303
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6304
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6305
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6306
258
                return 0;
6307
258
            }
6308
258
        }
6309
6310
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6311
        // Remove the rowset ref count key directly since it has not been used.
6312
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6313
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6314
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6315
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6316
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6317
6318
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6319
53.0k
        return 0;
6320
53.2k
    };
6321
6322
37
    auto loop_done = [&]() -> int {
6323
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6324
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6325
24
        std::vector<std::string> mark_keys_to_process;
6326
24
        std::vector<std::string> abort_keys_to_process;
6327
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6328
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6329
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6330
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6331
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6332
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6333
24
        if (!mark_keys_to_process.empty()) {
6334
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6335
7
                    *worker_pool, std::move(mark_keys_to_process));
6336
7
        }
6337
24
        if (!abort_keys_to_process.empty()) {
6338
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6339
5
                                           &num_recycled, &metrics_context);
6340
5
        }
6341
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6342
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6343
24
                             tmp_rowset_ref_count_keys_to_delete =
6344
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6345
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6346
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6347
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6348
24
                                   metrics_context) != 0) {
6349
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6350
2
                return;
6351
2
            }
6352
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6353
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6354
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6355
0
                                 << rs.ShortDebugString();
6356
0
                    return;
6357
0
                }
6358
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6359
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6360
0
                                 << rs.ShortDebugString();
6361
0
                    return;
6362
0
                }
6363
51.0k
            }
6364
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6365
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6366
0
                return;
6367
0
            }
6368
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6369
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6370
0
                return;
6371
0
            }
6372
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6373
22
            return;
6374
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6346
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6347
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6348
12
                                   metrics_context) != 0) {
6349
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6350
0
                return;
6351
0
            }
6352
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6353
4
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6354
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6355
0
                                 << rs.ShortDebugString();
6356
0
                    return;
6357
0
                }
6358
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6359
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6360
0
                                 << rs.ShortDebugString();
6361
0
                    return;
6362
0
                }
6363
4
            }
6364
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6365
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6366
0
                return;
6367
0
            }
6368
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6369
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6370
0
                return;
6371
0
            }
6372
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6373
12
            return;
6374
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6346
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6347
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6348
12
                                   metrics_context) != 0) {
6349
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6350
2
                return;
6351
2
            }
6352
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6353
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6354
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6355
0
                                 << rs.ShortDebugString();
6356
0
                    return;
6357
0
                }
6358
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6359
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6360
0
                                 << rs.ShortDebugString();
6361
0
                    return;
6362
0
                }
6363
51.0k
            }
6364
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6365
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6366
0
                return;
6367
0
            }
6368
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6369
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6370
0
                return;
6371
0
            }
6372
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6373
10
            return;
6374
10
        });
6375
24
        return 0;
6376
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6322
12
    auto loop_done = [&]() -> int {
6323
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6324
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6325
12
        std::vector<std::string> mark_keys_to_process;
6326
12
        std::vector<std::string> abort_keys_to_process;
6327
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6328
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6329
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6330
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6331
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6332
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6333
12
        if (!mark_keys_to_process.empty()) {
6334
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6335
7
                    *worker_pool, std::move(mark_keys_to_process));
6336
7
        }
6337
12
        if (!abort_keys_to_process.empty()) {
6338
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6339
3
                                           &num_recycled, &metrics_context);
6340
3
        }
6341
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6342
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6343
12
                             tmp_rowset_ref_count_keys_to_delete =
6344
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6345
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6346
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6347
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6348
12
                                   metrics_context) != 0) {
6349
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6350
12
                return;
6351
12
            }
6352
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6353
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6354
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6355
12
                                 << rs.ShortDebugString();
6356
12
                    return;
6357
12
                }
6358
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6359
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6360
12
                                 << rs.ShortDebugString();
6361
12
                    return;
6362
12
                }
6363
12
            }
6364
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6365
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6366
12
                return;
6367
12
            }
6368
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6369
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6370
12
                return;
6371
12
            }
6372
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6373
12
            return;
6374
12
        });
6375
12
        return 0;
6376
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6322
12
    auto loop_done = [&]() -> int {
6323
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6324
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6325
12
        std::vector<std::string> mark_keys_to_process;
6326
12
        std::vector<std::string> abort_keys_to_process;
6327
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6328
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6329
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6330
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6331
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6332
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6333
12
        if (!mark_keys_to_process.empty()) {
6334
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6335
0
                    *worker_pool, std::move(mark_keys_to_process));
6336
0
        }
6337
12
        if (!abort_keys_to_process.empty()) {
6338
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6339
2
                                           &num_recycled, &metrics_context);
6340
2
        }
6341
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6342
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6343
12
                             tmp_rowset_ref_count_keys_to_delete =
6344
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6345
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6346
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6347
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6348
12
                                   metrics_context) != 0) {
6349
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6350
12
                return;
6351
12
            }
6352
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6353
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6354
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6355
12
                                 << rs.ShortDebugString();
6356
12
                    return;
6357
12
                }
6358
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6359
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6360
12
                                 << rs.ShortDebugString();
6361
12
                    return;
6362
12
                }
6363
12
            }
6364
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6365
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6366
12
                return;
6367
12
            }
6368
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6369
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6370
12
                return;
6371
12
            }
6372
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6373
12
            return;
6374
12
        });
6375
12
        return 0;
6376
12
    };
6377
6378
37
    if (config::enable_recycler_stats_metrics) {
6379
0
        scan_and_statistics_tmp_rowsets();
6380
0
    }
6381
    // recycle_func and loop_done for scan and recycle
6382
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6383
37
                               std::move(loop_done));
6384
6385
37
    worker_pool->stop();
6386
6387
    // Report final metrics after all concurrent tasks completed
6388
37
    segment_metrics_context_.report();
6389
37
    metrics_context.report();
6390
6391
37
    return ret;
6392
37
}
6393
6394
int InstanceRecycler::scan_and_recycle(
6395
        std::string begin, std::string_view end,
6396
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6397
290
        std::function<int()> loop_done) {
6398
290
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6399
290
    int ret = 0;
6400
290
    int64_t cnt = 0;
6401
290
    int get_range_retried = 0;
6402
290
    std::string err;
6403
290
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6404
290
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6405
290
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6406
290
                  << " ret=" << ret << " err=" << err;
6407
290
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6403
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6404
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6405
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6406
31
                  << " ret=" << ret << " err=" << err;
6407
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6403
259
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6404
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6405
259
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6406
259
                  << " ret=" << ret << " err=" << err;
6407
259
    };
6408
6409
290
    std::unique_ptr<RangeGetIterator> it;
6410
465
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6411
318
        if (get_range_retried > 1000) {
6412
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6413
0
            ret = -3;
6414
0
            return ret;
6415
0
        }
6416
318
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6417
318
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6418
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6419
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6420
0
                         << " get_range_retried=" << get_range_retried;
6421
0
            ++get_range_retried;
6422
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6423
0
            continue; // try again
6424
0
        }
6425
318
        if (!it->has_next()) {
6426
143
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6427
143
            break; // scan finished
6428
143
        }
6429
98.1k
        while (it->has_next()) {
6430
97.9k
            ++cnt;
6431
            // recycle corresponding resources
6432
97.9k
            auto [k, v] = it->next();
6433
97.9k
            if (!it->has_next()) {
6434
175
                begin = k;
6435
175
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6436
175
            }
6437
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6438
97.9k
            if (recycle_func(k, v) != 0) {
6439
4.00k
                err = "recycle_func error";
6440
4.00k
                ret = -1;
6441
4.00k
            }
6442
97.9k
        }
6443
175
        begin.push_back('\x00'); // Update to next smallest key for iteration
6444
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6445
175
        if (loop_done && loop_done() != 0) {
6446
5
            err = "loop_done error";
6447
5
            ret = -1;
6448
5
        }
6449
175
    }
6450
290
    return ret;
6451
290
}
6452
6453
19
int InstanceRecycler::abort_timeout_txn() {
6454
19
    const std::string task_name = "abort_timeout_txn";
6455
19
    int64_t num_scanned = 0;
6456
19
    int64_t num_timeout = 0;
6457
19
    int64_t num_abort = 0;
6458
19
    int64_t num_advance = 0;
6459
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6460
6461
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6462
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6463
19
    std::string begin_txn_running_key;
6464
19
    std::string end_txn_running_key;
6465
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6466
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6467
6468
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6469
6470
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6471
19
    register_recycle_task(task_name, start_time);
6472
6473
19
    DORIS_CLOUD_DEFER {
6474
19
        unregister_recycle_task(task_name);
6475
19
        int64_t cost =
6476
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6477
19
        metrics_context.finish_report();
6478
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6479
19
                .tag("instance_id", instance_id_)
6480
19
                .tag("num_scanned", num_scanned)
6481
19
                .tag("num_timeout", num_timeout)
6482
19
                .tag("num_abort", num_abort)
6483
19
                .tag("num_advance", num_advance);
6484
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6473
3
    DORIS_CLOUD_DEFER {
6474
3
        unregister_recycle_task(task_name);
6475
3
        int64_t cost =
6476
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6477
3
        metrics_context.finish_report();
6478
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6479
3
                .tag("instance_id", instance_id_)
6480
3
                .tag("num_scanned", num_scanned)
6481
3
                .tag("num_timeout", num_timeout)
6482
3
                .tag("num_abort", num_abort)
6483
3
                .tag("num_advance", num_advance);
6484
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6473
16
    DORIS_CLOUD_DEFER {
6474
16
        unregister_recycle_task(task_name);
6475
16
        int64_t cost =
6476
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6477
16
        metrics_context.finish_report();
6478
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6479
16
                .tag("instance_id", instance_id_)
6480
16
                .tag("num_scanned", num_scanned)
6481
16
                .tag("num_timeout", num_timeout)
6482
16
                .tag("num_abort", num_abort)
6483
16
                .tag("num_advance", num_advance);
6484
16
    };
6485
6486
19
    int64_t current_time =
6487
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6488
6489
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6490
19
                                  &current_time, &metrics_context,
6491
19
                                  this](std::string_view k, std::string_view v) -> int {
6492
9
        ++num_scanned;
6493
6494
9
        std::unique_ptr<Transaction> txn;
6495
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6496
9
        if (err != TxnErrorCode::TXN_OK) {
6497
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6498
0
            return -1;
6499
0
        }
6500
9
        std::string_view k1 = k;
6501
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6502
9
        k1.remove_prefix(1); // Remove key space
6503
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6504
9
        if (decode_key(&k1, &out) != 0) {
6505
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6506
0
            return -1;
6507
0
        }
6508
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6509
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6510
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6511
        // Update txn_info
6512
9
        std::string txn_inf_key, txn_inf_val;
6513
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6514
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6515
9
        if (err != TxnErrorCode::TXN_OK) {
6516
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6517
0
            return -1;
6518
0
        }
6519
9
        TxnInfoPB txn_info;
6520
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6521
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6522
0
            return -1;
6523
0
        }
6524
6525
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6526
3
            txn.reset();
6527
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6528
3
            std::shared_ptr<TxnLazyCommitTask> task =
6529
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6530
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6531
3
            if (ret.first != MetaServiceCode::OK) {
6532
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6533
0
                             << "msg=" << ret.second;
6534
0
                return -1;
6535
0
            }
6536
3
            ++num_advance;
6537
3
            return 0;
6538
6
        } else {
6539
6
            TxnRunningPB txn_running_pb;
6540
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6541
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6542
0
                return -1;
6543
0
            }
6544
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6545
4
                return 0;
6546
4
            }
6547
2
            ++num_timeout;
6548
6549
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6550
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6551
2
            txn_info.set_finish_time(current_time);
6552
2
            txn_info.set_reason("timeout");
6553
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6554
2
            txn_inf_val.clear();
6555
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6556
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6557
0
                return -1;
6558
0
            }
6559
2
            txn->put(txn_inf_key, txn_inf_val);
6560
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6561
            // Put recycle txn key
6562
2
            std::string recyc_txn_key, recyc_txn_val;
6563
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6564
2
            RecycleTxnPB recycle_txn_pb;
6565
2
            recycle_txn_pb.set_creation_time(current_time);
6566
2
            recycle_txn_pb.set_label(txn_info.label());
6567
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6568
0
                LOG_WARNING("failed to serialize txn recycle info")
6569
0
                        .tag("key", hex(k))
6570
0
                        .tag("db_id", db_id)
6571
0
                        .tag("txn_id", txn_id);
6572
0
                return -1;
6573
0
            }
6574
2
            txn->put(recyc_txn_key, recyc_txn_val);
6575
            // Remove txn running key
6576
2
            txn->remove(k);
6577
2
            err = txn->commit();
6578
2
            if (err != TxnErrorCode::TXN_OK) {
6579
0
                LOG_WARNING("failed to commit txn err={}", err)
6580
0
                        .tag("key", hex(k))
6581
0
                        .tag("db_id", db_id)
6582
0
                        .tag("txn_id", txn_id);
6583
0
                return -1;
6584
0
            }
6585
2
            metrics_context.total_recycled_num = ++num_abort;
6586
2
            metrics_context.report();
6587
2
        }
6588
6589
2
        return 0;
6590
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6491
3
                                  this](std::string_view k, std::string_view v) -> int {
6492
3
        ++num_scanned;
6493
6494
3
        std::unique_ptr<Transaction> txn;
6495
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6496
3
        if (err != TxnErrorCode::TXN_OK) {
6497
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6498
0
            return -1;
6499
0
        }
6500
3
        std::string_view k1 = k;
6501
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6502
3
        k1.remove_prefix(1); // Remove key space
6503
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6504
3
        if (decode_key(&k1, &out) != 0) {
6505
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6506
0
            return -1;
6507
0
        }
6508
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6509
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6510
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6511
        // Update txn_info
6512
3
        std::string txn_inf_key, txn_inf_val;
6513
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6514
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6515
3
        if (err != TxnErrorCode::TXN_OK) {
6516
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6517
0
            return -1;
6518
0
        }
6519
3
        TxnInfoPB txn_info;
6520
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6521
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6522
0
            return -1;
6523
0
        }
6524
6525
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6526
3
            txn.reset();
6527
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6528
3
            std::shared_ptr<TxnLazyCommitTask> task =
6529
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6530
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6531
3
            if (ret.first != MetaServiceCode::OK) {
6532
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6533
0
                             << "msg=" << ret.second;
6534
0
                return -1;
6535
0
            }
6536
3
            ++num_advance;
6537
3
            return 0;
6538
3
        } else {
6539
0
            TxnRunningPB txn_running_pb;
6540
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6541
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6542
0
                return -1;
6543
0
            }
6544
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6545
0
                return 0;
6546
0
            }
6547
0
            ++num_timeout;
6548
6549
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6550
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6551
0
            txn_info.set_finish_time(current_time);
6552
0
            txn_info.set_reason("timeout");
6553
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6554
0
            txn_inf_val.clear();
6555
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6556
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6557
0
                return -1;
6558
0
            }
6559
0
            txn->put(txn_inf_key, txn_inf_val);
6560
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6561
            // Put recycle txn key
6562
0
            std::string recyc_txn_key, recyc_txn_val;
6563
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6564
0
            RecycleTxnPB recycle_txn_pb;
6565
0
            recycle_txn_pb.set_creation_time(current_time);
6566
0
            recycle_txn_pb.set_label(txn_info.label());
6567
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6568
0
                LOG_WARNING("failed to serialize txn recycle info")
6569
0
                        .tag("key", hex(k))
6570
0
                        .tag("db_id", db_id)
6571
0
                        .tag("txn_id", txn_id);
6572
0
                return -1;
6573
0
            }
6574
0
            txn->put(recyc_txn_key, recyc_txn_val);
6575
            // Remove txn running key
6576
0
            txn->remove(k);
6577
0
            err = txn->commit();
6578
0
            if (err != TxnErrorCode::TXN_OK) {
6579
0
                LOG_WARNING("failed to commit txn err={}", err)
6580
0
                        .tag("key", hex(k))
6581
0
                        .tag("db_id", db_id)
6582
0
                        .tag("txn_id", txn_id);
6583
0
                return -1;
6584
0
            }
6585
0
            metrics_context.total_recycled_num = ++num_abort;
6586
0
            metrics_context.report();
6587
0
        }
6588
6589
0
        return 0;
6590
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6491
6
                                  this](std::string_view k, std::string_view v) -> int {
6492
6
        ++num_scanned;
6493
6494
6
        std::unique_ptr<Transaction> txn;
6495
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6496
6
        if (err != TxnErrorCode::TXN_OK) {
6497
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6498
0
            return -1;
6499
0
        }
6500
6
        std::string_view k1 = k;
6501
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6502
6
        k1.remove_prefix(1); // Remove key space
6503
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6504
6
        if (decode_key(&k1, &out) != 0) {
6505
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6506
0
            return -1;
6507
0
        }
6508
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6509
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6510
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6511
        // Update txn_info
6512
6
        std::string txn_inf_key, txn_inf_val;
6513
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6514
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6515
6
        if (err != TxnErrorCode::TXN_OK) {
6516
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6517
0
            return -1;
6518
0
        }
6519
6
        TxnInfoPB txn_info;
6520
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6521
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6522
0
            return -1;
6523
0
        }
6524
6525
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6526
0
            txn.reset();
6527
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6528
0
            std::shared_ptr<TxnLazyCommitTask> task =
6529
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6530
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6531
0
            if (ret.first != MetaServiceCode::OK) {
6532
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6533
0
                             << "msg=" << ret.second;
6534
0
                return -1;
6535
0
            }
6536
0
            ++num_advance;
6537
0
            return 0;
6538
6
        } else {
6539
6
            TxnRunningPB txn_running_pb;
6540
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6541
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6542
0
                return -1;
6543
0
            }
6544
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6545
4
                return 0;
6546
4
            }
6547
2
            ++num_timeout;
6548
6549
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6550
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6551
2
            txn_info.set_finish_time(current_time);
6552
2
            txn_info.set_reason("timeout");
6553
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6554
2
            txn_inf_val.clear();
6555
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6556
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6557
0
                return -1;
6558
0
            }
6559
2
            txn->put(txn_inf_key, txn_inf_val);
6560
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6561
            // Put recycle txn key
6562
2
            std::string recyc_txn_key, recyc_txn_val;
6563
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6564
2
            RecycleTxnPB recycle_txn_pb;
6565
2
            recycle_txn_pb.set_creation_time(current_time);
6566
2
            recycle_txn_pb.set_label(txn_info.label());
6567
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6568
0
                LOG_WARNING("failed to serialize txn recycle info")
6569
0
                        .tag("key", hex(k))
6570
0
                        .tag("db_id", db_id)
6571
0
                        .tag("txn_id", txn_id);
6572
0
                return -1;
6573
0
            }
6574
2
            txn->put(recyc_txn_key, recyc_txn_val);
6575
            // Remove txn running key
6576
2
            txn->remove(k);
6577
2
            err = txn->commit();
6578
2
            if (err != TxnErrorCode::TXN_OK) {
6579
0
                LOG_WARNING("failed to commit txn err={}", err)
6580
0
                        .tag("key", hex(k))
6581
0
                        .tag("db_id", db_id)
6582
0
                        .tag("txn_id", txn_id);
6583
0
                return -1;
6584
0
            }
6585
2
            metrics_context.total_recycled_num = ++num_abort;
6586
2
            metrics_context.report();
6587
2
        }
6588
6589
2
        return 0;
6590
6
    };
6591
6592
19
    if (config::enable_recycler_stats_metrics) {
6593
0
        scan_and_statistics_abort_timeout_txn();
6594
0
    }
6595
    // recycle_func and loop_done for scan and recycle
6596
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6597
19
                            std::move(handle_txn_running_kv));
6598
19
}
6599
6600
19
int InstanceRecycler::recycle_expired_txn_label() {
6601
19
    const std::string task_name = "recycle_expired_txn_label";
6602
19
    int64_t num_scanned = 0;
6603
19
    int64_t num_expired = 0;
6604
19
    std::atomic_long num_recycled = 0;
6605
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6606
19
    int ret = 0;
6607
6608
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6609
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6610
19
    std::string begin_recycle_txn_key;
6611
19
    std::string end_recycle_txn_key;
6612
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6613
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6614
19
    std::vector<std::string> recycle_txn_info_keys;
6615
6616
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6617
6618
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6619
19
    register_recycle_task(task_name, start_time);
6620
19
    DORIS_CLOUD_DEFER {
6621
19
        unregister_recycle_task(task_name);
6622
19
        int64_t cost =
6623
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
19
        metrics_context.finish_report();
6625
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6626
19
                .tag("instance_id", instance_id_)
6627
19
                .tag("num_scanned", num_scanned)
6628
19
                .tag("num_expired", num_expired)
6629
19
                .tag("num_recycled", num_recycled);
6630
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6620
1
    DORIS_CLOUD_DEFER {
6621
1
        unregister_recycle_task(task_name);
6622
1
        int64_t cost =
6623
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
1
        metrics_context.finish_report();
6625
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6626
1
                .tag("instance_id", instance_id_)
6627
1
                .tag("num_scanned", num_scanned)
6628
1
                .tag("num_expired", num_expired)
6629
1
                .tag("num_recycled", num_recycled);
6630
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6620
18
    DORIS_CLOUD_DEFER {
6621
18
        unregister_recycle_task(task_name);
6622
18
        int64_t cost =
6623
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
18
        metrics_context.finish_report();
6625
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6626
18
                .tag("instance_id", instance_id_)
6627
18
                .tag("num_scanned", num_scanned)
6628
18
                .tag("num_expired", num_expired)
6629
18
                .tag("num_recycled", num_recycled);
6630
18
    };
6631
6632
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6633
6634
19
    SyncExecutor<int> concurrent_delete_executor(
6635
19
            _thread_pool_group.s3_producer_pool,
6636
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6637
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6637
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6637
23.0k
            [](const int& ret) { return ret != 0; });
6638
6639
19
    int64_t current_time_ms =
6640
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6641
6642
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6643
30.0k
        ++num_scanned;
6644
30.0k
        RecycleTxnPB recycle_txn_pb;
6645
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6646
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6647
0
            return -1;
6648
0
        }
6649
30.0k
        if ((config::force_immediate_recycle) ||
6650
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6651
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6652
30.0k
             current_time_ms)) {
6653
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6654
23.0k
            num_expired++;
6655
23.0k
            recycle_txn_info_keys.emplace_back(k);
6656
23.0k
        }
6657
30.0k
        return 0;
6658
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6642
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6643
1
        ++num_scanned;
6644
1
        RecycleTxnPB recycle_txn_pb;
6645
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6646
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6647
0
            return -1;
6648
0
        }
6649
1
        if ((config::force_immediate_recycle) ||
6650
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6651
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6652
1
             current_time_ms)) {
6653
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6654
1
            num_expired++;
6655
1
            recycle_txn_info_keys.emplace_back(k);
6656
1
        }
6657
1
        return 0;
6658
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6642
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6643
30.0k
        ++num_scanned;
6644
30.0k
        RecycleTxnPB recycle_txn_pb;
6645
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6646
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6647
0
            return -1;
6648
0
        }
6649
30.0k
        if ((config::force_immediate_recycle) ||
6650
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6651
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6652
30.0k
             current_time_ms)) {
6653
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6654
23.0k
            num_expired++;
6655
23.0k
            recycle_txn_info_keys.emplace_back(k);
6656
23.0k
        }
6657
30.0k
        return 0;
6658
30.0k
    };
6659
6660
    // int 0 for success, 1 for conflict, -1 for error
6661
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6662
23.0k
        std::string_view k1 = k;
6663
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6664
23.0k
        k1.remove_prefix(1); // Remove key space
6665
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6666
23.0k
        int ret = decode_key(&k1, &out);
6667
23.0k
        if (ret != 0) {
6668
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6669
0
            return -1;
6670
0
        }
6671
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6672
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6673
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6674
23.0k
        std::unique_ptr<Transaction> txn;
6675
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6676
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6677
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6678
0
            return -1;
6679
0
        }
6680
        // Remove txn index kv
6681
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6682
23.0k
        txn->remove(index_key);
6683
        // Remove txn info kv
6684
23.0k
        std::string info_key, info_val;
6685
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6686
23.0k
        err = txn->get(info_key, &info_val);
6687
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6688
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6689
0
            return -1;
6690
0
        }
6691
23.0k
        TxnInfoPB txn_info;
6692
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6693
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6694
0
            return -1;
6695
0
        }
6696
23.0k
        txn->remove(info_key);
6697
        // Remove sub txn index kvs
6698
23.0k
        std::vector<std::string> sub_txn_index_keys;
6699
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6700
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6701
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6702
22.9k
        }
6703
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6704
22.9k
            txn->remove(sub_txn_index_key);
6705
22.9k
        }
6706
        // Update txn label
6707
23.0k
        std::string label_key, label_val;
6708
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6709
23.0k
        err = txn->get(label_key, &label_val);
6710
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6711
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6712
0
                         << " err=" << err;
6713
0
            return -1;
6714
0
        }
6715
23.0k
        TxnLabelPB txn_label;
6716
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6717
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6718
0
            return -1;
6719
0
        }
6720
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6721
23.0k
        if (it != txn_label.txn_ids().end()) {
6722
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6723
23.0k
        }
6724
23.0k
        if (txn_label.txn_ids().empty()) {
6725
23.0k
            txn->remove(label_key);
6726
23.0k
            TEST_SYNC_POINT_CALLBACK(
6727
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6728
23.0k
        } else {
6729
73
            if (!txn_label.SerializeToString(&label_val)) {
6730
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6731
0
                return -1;
6732
0
            }
6733
73
            TEST_SYNC_POINT_CALLBACK(
6734
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6735
73
            txn->atomic_set_ver_value(label_key, label_val);
6736
73
            TEST_SYNC_POINT_CALLBACK(
6737
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6738
73
        }
6739
        // Remove recycle txn kv
6740
23.0k
        txn->remove(k);
6741
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6742
23.0k
        err = txn->commit();
6743
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6744
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6745
62
                TEST_SYNC_POINT_CALLBACK(
6746
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6747
                // log the txn_id and label
6748
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6749
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6750
62
                             << " txn_label=" << txn_info.label();
6751
62
                return 1;
6752
62
            }
6753
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6754
0
            return -1;
6755
62
        }
6756
23.0k
        ++num_recycled;
6757
6758
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6759
23.0k
        return 0;
6760
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6661
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6662
1
        std::string_view k1 = k;
6663
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6664
1
        k1.remove_prefix(1); // Remove key space
6665
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6666
1
        int ret = decode_key(&k1, &out);
6667
1
        if (ret != 0) {
6668
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6669
0
            return -1;
6670
0
        }
6671
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6672
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6673
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6674
1
        std::unique_ptr<Transaction> txn;
6675
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6676
1
        if (err != TxnErrorCode::TXN_OK) {
6677
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6678
0
            return -1;
6679
0
        }
6680
        // Remove txn index kv
6681
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6682
1
        txn->remove(index_key);
6683
        // Remove txn info kv
6684
1
        std::string info_key, info_val;
6685
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6686
1
        err = txn->get(info_key, &info_val);
6687
1
        if (err != TxnErrorCode::TXN_OK) {
6688
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6689
0
            return -1;
6690
0
        }
6691
1
        TxnInfoPB txn_info;
6692
1
        if (!txn_info.ParseFromString(info_val)) {
6693
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6694
0
            return -1;
6695
0
        }
6696
1
        txn->remove(info_key);
6697
        // Remove sub txn index kvs
6698
1
        std::vector<std::string> sub_txn_index_keys;
6699
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6700
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6701
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6702
0
        }
6703
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6704
0
            txn->remove(sub_txn_index_key);
6705
0
        }
6706
        // Update txn label
6707
1
        std::string label_key, label_val;
6708
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6709
1
        err = txn->get(label_key, &label_val);
6710
1
        if (err != TxnErrorCode::TXN_OK) {
6711
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6712
0
                         << " err=" << err;
6713
0
            return -1;
6714
0
        }
6715
1
        TxnLabelPB txn_label;
6716
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6717
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6718
0
            return -1;
6719
0
        }
6720
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6721
1
        if (it != txn_label.txn_ids().end()) {
6722
1
            txn_label.mutable_txn_ids()->erase(it);
6723
1
        }
6724
1
        if (txn_label.txn_ids().empty()) {
6725
1
            txn->remove(label_key);
6726
1
            TEST_SYNC_POINT_CALLBACK(
6727
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6728
1
        } else {
6729
0
            if (!txn_label.SerializeToString(&label_val)) {
6730
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6731
0
                return -1;
6732
0
            }
6733
0
            TEST_SYNC_POINT_CALLBACK(
6734
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6735
0
            txn->atomic_set_ver_value(label_key, label_val);
6736
0
            TEST_SYNC_POINT_CALLBACK(
6737
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6738
0
        }
6739
        // Remove recycle txn kv
6740
1
        txn->remove(k);
6741
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6742
1
        err = txn->commit();
6743
1
        if (err != TxnErrorCode::TXN_OK) {
6744
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6745
0
                TEST_SYNC_POINT_CALLBACK(
6746
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6747
                // log the txn_id and label
6748
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6749
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6750
0
                             << " txn_label=" << txn_info.label();
6751
0
                return 1;
6752
0
            }
6753
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6754
0
            return -1;
6755
0
        }
6756
1
        ++num_recycled;
6757
6758
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6759
1
        return 0;
6760
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6661
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6662
23.0k
        std::string_view k1 = k;
6663
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6664
23.0k
        k1.remove_prefix(1); // Remove key space
6665
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6666
23.0k
        int ret = decode_key(&k1, &out);
6667
23.0k
        if (ret != 0) {
6668
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6669
0
            return -1;
6670
0
        }
6671
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6672
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6673
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6674
23.0k
        std::unique_ptr<Transaction> txn;
6675
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6676
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6677
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6678
0
            return -1;
6679
0
        }
6680
        // Remove txn index kv
6681
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6682
23.0k
        txn->remove(index_key);
6683
        // Remove txn info kv
6684
23.0k
        std::string info_key, info_val;
6685
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6686
23.0k
        err = txn->get(info_key, &info_val);
6687
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6688
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6689
0
            return -1;
6690
0
        }
6691
23.0k
        TxnInfoPB txn_info;
6692
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6693
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6694
0
            return -1;
6695
0
        }
6696
23.0k
        txn->remove(info_key);
6697
        // Remove sub txn index kvs
6698
23.0k
        std::vector<std::string> sub_txn_index_keys;
6699
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6700
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6701
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6702
22.9k
        }
6703
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6704
22.9k
            txn->remove(sub_txn_index_key);
6705
22.9k
        }
6706
        // Update txn label
6707
23.0k
        std::string label_key, label_val;
6708
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6709
23.0k
        err = txn->get(label_key, &label_val);
6710
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6711
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6712
0
                         << " err=" << err;
6713
0
            return -1;
6714
0
        }
6715
23.0k
        TxnLabelPB txn_label;
6716
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6717
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6718
0
            return -1;
6719
0
        }
6720
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6721
23.0k
        if (it != txn_label.txn_ids().end()) {
6722
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6723
23.0k
        }
6724
23.0k
        if (txn_label.txn_ids().empty()) {
6725
23.0k
            txn->remove(label_key);
6726
23.0k
            TEST_SYNC_POINT_CALLBACK(
6727
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6728
23.0k
        } else {
6729
73
            if (!txn_label.SerializeToString(&label_val)) {
6730
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6731
0
                return -1;
6732
0
            }
6733
73
            TEST_SYNC_POINT_CALLBACK(
6734
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6735
73
            txn->atomic_set_ver_value(label_key, label_val);
6736
73
            TEST_SYNC_POINT_CALLBACK(
6737
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6738
73
        }
6739
        // Remove recycle txn kv
6740
23.0k
        txn->remove(k);
6741
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6742
23.0k
        err = txn->commit();
6743
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6744
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6745
62
                TEST_SYNC_POINT_CALLBACK(
6746
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6747
                // log the txn_id and label
6748
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6749
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6750
62
                             << " txn_label=" << txn_info.label();
6751
62
                return 1;
6752
62
            }
6753
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6754
0
            return -1;
6755
62
        }
6756
23.0k
        ++num_recycled;
6757
6758
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6759
23.0k
        return 0;
6760
23.0k
    };
6761
6762
19
    auto loop_done = [&]() -> int {
6763
10
        DORIS_CLOUD_DEFER {
6764
10
            recycle_txn_info_keys.clear();
6765
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6763
1
        DORIS_CLOUD_DEFER {
6764
1
            recycle_txn_info_keys.clear();
6765
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6763
9
        DORIS_CLOUD_DEFER {
6764
9
            recycle_txn_info_keys.clear();
6765
9
        };
6766
10
        TEST_SYNC_POINT_CALLBACK(
6767
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6768
10
                &recycle_txn_info_keys);
6769
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6770
23.0k
            concurrent_delete_executor.add([&]() {
6771
23.0k
                int ret = delete_recycle_txn_kv(k);
6772
23.0k
                if (ret == 1) {
6773
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6774
54
                    for (int i = 1; i <= max_retry; ++i) {
6775
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6776
54
                        ret = delete_recycle_txn_kv(k);
6777
                        // clang-format off
6778
54
                        TEST_SYNC_POINT_CALLBACK(
6779
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6780
                        // clang-format off
6781
54
                        if (ret != 1) {
6782
18
                            break;
6783
18
                        }
6784
                        // random sleep 0-100 ms to retry
6785
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6786
36
                    }
6787
18
                }
6788
23.0k
                if (ret != 0) {
6789
9
                    LOG_WARNING("failed to delete recycle txn kv")
6790
9
                            .tag("instance id", instance_id_)
6791
9
                            .tag("key", hex(k));
6792
9
                    return -1;
6793
9
                }
6794
23.0k
                return 0;
6795
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6770
1
            concurrent_delete_executor.add([&]() {
6771
1
                int ret = delete_recycle_txn_kv(k);
6772
1
                if (ret == 1) {
6773
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6774
0
                    for (int i = 1; i <= max_retry; ++i) {
6775
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6776
0
                        ret = delete_recycle_txn_kv(k);
6777
                        // clang-format off
6778
0
                        TEST_SYNC_POINT_CALLBACK(
6779
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6780
                        // clang-format off
6781
0
                        if (ret != 1) {
6782
0
                            break;
6783
0
                        }
6784
                        // random sleep 0-100 ms to retry
6785
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6786
0
                    }
6787
0
                }
6788
1
                if (ret != 0) {
6789
0
                    LOG_WARNING("failed to delete recycle txn kv")
6790
0
                            .tag("instance id", instance_id_)
6791
0
                            .tag("key", hex(k));
6792
0
                    return -1;
6793
0
                }
6794
1
                return 0;
6795
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6770
23.0k
            concurrent_delete_executor.add([&]() {
6771
23.0k
                int ret = delete_recycle_txn_kv(k);
6772
23.0k
                if (ret == 1) {
6773
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6774
54
                    for (int i = 1; i <= max_retry; ++i) {
6775
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6776
54
                        ret = delete_recycle_txn_kv(k);
6777
                        // clang-format off
6778
54
                        TEST_SYNC_POINT_CALLBACK(
6779
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6780
                        // clang-format off
6781
54
                        if (ret != 1) {
6782
18
                            break;
6783
18
                        }
6784
                        // random sleep 0-100 ms to retry
6785
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6786
36
                    }
6787
18
                }
6788
23.0k
                if (ret != 0) {
6789
9
                    LOG_WARNING("failed to delete recycle txn kv")
6790
9
                            .tag("instance id", instance_id_)
6791
9
                            .tag("key", hex(k));
6792
9
                    return -1;
6793
9
                }
6794
23.0k
                return 0;
6795
23.0k
            });
6796
23.0k
        }
6797
10
        bool finished = true;
6798
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6799
23.0k
        for (int r : rets) {
6800
23.0k
            if (r != 0) {
6801
9
                ret = -1;
6802
9
            }
6803
23.0k
        }
6804
6805
10
        ret = finished ? ret : -1;
6806
6807
        // Update metrics after all concurrent tasks completed
6808
10
        metrics_context.total_recycled_num = num_recycled.load();
6809
10
        metrics_context.report();
6810
6811
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6812
6813
10
        if (ret != 0) {
6814
3
            LOG_WARNING("recycle txn kv ret!=0")
6815
3
                    .tag("finished", finished)
6816
3
                    .tag("ret", ret)
6817
3
                    .tag("instance_id", instance_id_);
6818
3
            return ret;
6819
3
        }
6820
7
        return ret;
6821
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6762
1
    auto loop_done = [&]() -> int {
6763
1
        DORIS_CLOUD_DEFER {
6764
1
            recycle_txn_info_keys.clear();
6765
1
        };
6766
1
        TEST_SYNC_POINT_CALLBACK(
6767
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6768
1
                &recycle_txn_info_keys);
6769
1
        for (const auto& k : recycle_txn_info_keys) {
6770
1
            concurrent_delete_executor.add([&]() {
6771
1
                int ret = delete_recycle_txn_kv(k);
6772
1
                if (ret == 1) {
6773
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6774
1
                    for (int i = 1; i <= max_retry; ++i) {
6775
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6776
1
                        ret = delete_recycle_txn_kv(k);
6777
                        // clang-format off
6778
1
                        TEST_SYNC_POINT_CALLBACK(
6779
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6780
                        // clang-format off
6781
1
                        if (ret != 1) {
6782
1
                            break;
6783
1
                        }
6784
                        // random sleep 0-100 ms to retry
6785
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6786
1
                    }
6787
1
                }
6788
1
                if (ret != 0) {
6789
1
                    LOG_WARNING("failed to delete recycle txn kv")
6790
1
                            .tag("instance id", instance_id_)
6791
1
                            .tag("key", hex(k));
6792
1
                    return -1;
6793
1
                }
6794
1
                return 0;
6795
1
            });
6796
1
        }
6797
1
        bool finished = true;
6798
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6799
1
        for (int r : rets) {
6800
1
            if (r != 0) {
6801
0
                ret = -1;
6802
0
            }
6803
1
        }
6804
6805
1
        ret = finished ? ret : -1;
6806
6807
        // Update metrics after all concurrent tasks completed
6808
1
        metrics_context.total_recycled_num = num_recycled.load();
6809
1
        metrics_context.report();
6810
6811
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6812
6813
1
        if (ret != 0) {
6814
0
            LOG_WARNING("recycle txn kv ret!=0")
6815
0
                    .tag("finished", finished)
6816
0
                    .tag("ret", ret)
6817
0
                    .tag("instance_id", instance_id_);
6818
0
            return ret;
6819
0
        }
6820
1
        return ret;
6821
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6762
9
    auto loop_done = [&]() -> int {
6763
9
        DORIS_CLOUD_DEFER {
6764
9
            recycle_txn_info_keys.clear();
6765
9
        };
6766
9
        TEST_SYNC_POINT_CALLBACK(
6767
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6768
9
                &recycle_txn_info_keys);
6769
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6770
23.0k
            concurrent_delete_executor.add([&]() {
6771
23.0k
                int ret = delete_recycle_txn_kv(k);
6772
23.0k
                if (ret == 1) {
6773
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6774
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6775
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6776
23.0k
                        ret = delete_recycle_txn_kv(k);
6777
                        // clang-format off
6778
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6779
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6780
                        // clang-format off
6781
23.0k
                        if (ret != 1) {
6782
23.0k
                            break;
6783
23.0k
                        }
6784
                        // random sleep 0-100 ms to retry
6785
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6786
23.0k
                    }
6787
23.0k
                }
6788
23.0k
                if (ret != 0) {
6789
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6790
23.0k
                            .tag("instance id", instance_id_)
6791
23.0k
                            .tag("key", hex(k));
6792
23.0k
                    return -1;
6793
23.0k
                }
6794
23.0k
                return 0;
6795
23.0k
            });
6796
23.0k
        }
6797
9
        bool finished = true;
6798
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6799
23.0k
        for (int r : rets) {
6800
23.0k
            if (r != 0) {
6801
9
                ret = -1;
6802
9
            }
6803
23.0k
        }
6804
6805
9
        ret = finished ? ret : -1;
6806
6807
        // Update metrics after all concurrent tasks completed
6808
9
        metrics_context.total_recycled_num = num_recycled.load();
6809
9
        metrics_context.report();
6810
6811
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6812
6813
9
        if (ret != 0) {
6814
3
            LOG_WARNING("recycle txn kv ret!=0")
6815
3
                    .tag("finished", finished)
6816
3
                    .tag("ret", ret)
6817
3
                    .tag("instance_id", instance_id_);
6818
3
            return ret;
6819
3
        }
6820
6
        return ret;
6821
9
    };
6822
6823
19
    if (config::enable_recycler_stats_metrics) {
6824
0
        scan_and_statistics_expired_txn_label();
6825
0
    }
6826
    // recycle_func and loop_done for scan and recycle
6827
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6828
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6829
19
}
6830
6831
struct CopyJobIdTuple {
6832
    std::string instance_id;
6833
    std::string stage_id;
6834
    long table_id;
6835
    std::string copy_id;
6836
    std::string stage_path;
6837
};
6838
struct BatchObjStoreAccessor {
6839
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6840
                          TxnKv* txn_kv)
6841
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6842
3
    ~BatchObjStoreAccessor() {
6843
3
        if (!paths_.empty()) {
6844
3
            consume();
6845
3
        }
6846
3
    }
6847
6848
    /**
6849
    * To implicitely do batch work and submit the batch delete task to s3
6850
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6851
    *
6852
    * @param copy_job The protubuf struct consists of the copy job files.
6853
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6854
    *            it would last until we finish the delete task, here we need pass one string value
6855
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6856
    */
6857
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6858
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6859
5
        auto& file_keys = copy_file_keys_[key];
6860
5
        file_keys.log_trace =
6861
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6862
5
                            instance_id, stage_id, table_id, copy_id, path);
6863
5
        std::string_view log_trace = file_keys.log_trace;
6864
2.03k
        for (const auto& file : copy_job.object_files()) {
6865
2.03k
            auto relative_path = file.relative_path();
6866
2.03k
            paths_.push_back(relative_path);
6867
2.03k
            file_keys.keys.push_back(copy_file_key(
6868
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6869
2.03k
            LOG_INFO(log_trace)
6870
2.03k
                    .tag("relative_path", relative_path)
6871
2.03k
                    .tag("batch_count", batch_count_);
6872
2.03k
        }
6873
5
        LOG_INFO(log_trace)
6874
5
                .tag("objects_num", copy_job.object_files().size())
6875
5
                .tag("batch_count", batch_count_);
6876
        // TODO(AlexYue): If the size is 1001, it would be one delete with 1000 objects and one delete request with only one object(**ATTN**: DOESN'T
6877
        // recommend using delete objects when objects num is less than 10)
6878
5
        if (paths_.size() < 1000) {
6879
3
            return;
6880
3
        }
6881
2
        consume();
6882
2
    }
6883
6884
private:
6885
5
    void consume() {
6886
5
        DORIS_CLOUD_DEFER {
6887
5
            paths_.clear();
6888
5
            copy_file_keys_.clear();
6889
5
            batch_count_++;
6890
6891
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6892
5
                        batch_count_);
6893
5
        };
6894
6895
5
        StopWatch sw;
6896
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6897
5
        if (0 != accessor_->delete_files(paths_)) {
6898
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6899
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6900
2
            return;
6901
2
        }
6902
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6903
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6904
        // delete fdb's keys
6905
3
        for (auto& file_keys : copy_file_keys_) {
6906
3
            auto& [log_trace, keys] = file_keys.second;
6907
3
            std::unique_ptr<Transaction> txn;
6908
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6909
0
                LOG(WARNING) << "failed to create txn";
6910
0
                continue;
6911
0
            }
6912
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6913
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6914
            // limited, should not cause the txn commit failed.
6915
1.02k
            for (const auto& key : keys) {
6916
1.02k
                txn->remove(key);
6917
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6918
1.02k
            }
6919
3
            txn->remove(file_keys.first);
6920
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6921
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6922
0
                continue;
6923
0
            }
6924
3
        }
6925
3
    }
6926
    std::shared_ptr<StorageVaultAccessor> accessor_;
6927
    // the path of the s3 files to be deleted
6928
    std::vector<std::string> paths_;
6929
    struct CopyFiles {
6930
        std::string log_trace;
6931
        std::vector<std::string> keys;
6932
    };
6933
    // pair<std::string, std::vector<std::string>>
6934
    // first: instance_id_ stage_id table_id query_id
6935
    // second: keys to be deleted
6936
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6937
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6938
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6939
    // which can together uniquely identifies different tasks for tracing log
6940
    uint64_t& batch_count_;
6941
    TxnKv* txn_kv_;
6942
};
6943
6944
13
int InstanceRecycler::recycle_copy_jobs() {
6945
13
    int64_t num_scanned = 0;
6946
13
    int64_t num_finished = 0;
6947
13
    int64_t num_expired = 0;
6948
13
    int64_t num_recycled = 0;
6949
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6950
13
    uint64_t batch_count = 0;
6951
13
    const std::string task_name = "recycle_copy_jobs";
6952
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6953
6954
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6955
6956
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6957
13
    register_recycle_task(task_name, start_time);
6958
6959
13
    DORIS_CLOUD_DEFER {
6960
13
        unregister_recycle_task(task_name);
6961
13
        int64_t cost =
6962
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6963
13
        metrics_context.finish_report();
6964
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6965
13
                .tag("instance_id", instance_id_)
6966
13
                .tag("num_scanned", num_scanned)
6967
13
                .tag("num_finished", num_finished)
6968
13
                .tag("num_expired", num_expired)
6969
13
                .tag("num_recycled", num_recycled);
6970
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6959
13
    DORIS_CLOUD_DEFER {
6960
13
        unregister_recycle_task(task_name);
6961
13
        int64_t cost =
6962
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6963
13
        metrics_context.finish_report();
6964
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6965
13
                .tag("instance_id", instance_id_)
6966
13
                .tag("num_scanned", num_scanned)
6967
13
                .tag("num_finished", num_finished)
6968
13
                .tag("num_expired", num_expired)
6969
13
                .tag("num_recycled", num_recycled);
6970
13
    };
6971
6972
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6973
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6974
13
    std::string key0;
6975
13
    std::string key1;
6976
13
    copy_job_key(key_info0, &key0);
6977
13
    copy_job_key(key_info1, &key1);
6978
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6979
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6980
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6981
16
                         this](std::string_view k, std::string_view v) -> int {
6982
16
        ++num_scanned;
6983
16
        CopyJobPB copy_job;
6984
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6985
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6986
0
            return -1;
6987
0
        }
6988
6989
        // decode copy job key
6990
16
        auto k1 = k;
6991
16
        k1.remove_prefix(1);
6992
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6993
16
        decode_key(&k1, &out);
6994
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6995
        // -> CopyJobPB
6996
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6997
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6998
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6999
7000
16
        bool check_storage = true;
7001
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7002
12
            ++num_finished;
7003
7004
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7005
7
                auto it = stage_accessor_map.find(stage_id);
7006
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7007
7
                std::string_view path;
7008
7
                if (it != stage_accessor_map.end()) {
7009
2
                    accessor = it->second;
7010
5
                } else {
7011
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7012
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7013
5
                                                      &inner_accessor);
7014
5
                    if (ret < 0) { // error
7015
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7016
0
                        return -1;
7017
5
                    } else if (ret == 0) {
7018
3
                        path = inner_accessor->uri();
7019
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7020
3
                                inner_accessor, batch_count, txn_kv_.get());
7021
3
                        stage_accessor_map.emplace(stage_id, accessor);
7022
3
                    } else { // stage not found, skip check storage
7023
2
                        check_storage = false;
7024
2
                    }
7025
5
                }
7026
7
                if (check_storage) {
7027
                    // TODO delete objects with key and etag is not supported
7028
5
                    accessor->add(std::move(copy_job), std::string(k),
7029
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7030
5
                    return 0;
7031
5
                }
7032
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7033
5
                int64_t current_time =
7034
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7035
5
                if (copy_job.finish_time_ms() > 0) {
7036
2
                    if (!config::force_immediate_recycle &&
7037
2
                        current_time < copy_job.finish_time_ms() +
7038
2
                                               config::copy_job_max_retention_second * 1000) {
7039
1
                        return 0;
7040
1
                    }
7041
3
                } else {
7042
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7043
3
                    if (!config::force_immediate_recycle &&
7044
3
                        current_time < copy_job.start_time_ms() +
7045
3
                                               config::copy_job_max_retention_second * 1000) {
7046
1
                        return 0;
7047
1
                    }
7048
3
                }
7049
5
            }
7050
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7051
4
            int64_t current_time =
7052
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7053
            // if copy job is timeout: delete all copy file kvs and copy job kv
7054
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7055
2
                return 0;
7056
2
            }
7057
2
            ++num_expired;
7058
2
        }
7059
7060
        // delete all copy files
7061
7
        std::vector<std::string> copy_file_keys;
7062
70
        for (auto& file : copy_job.object_files()) {
7063
70
            copy_file_keys.push_back(copy_file_key(
7064
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7065
70
        }
7066
7
        std::unique_ptr<Transaction> txn;
7067
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7068
0
            LOG(WARNING) << "failed to create txn";
7069
0
            return -1;
7070
0
        }
7071
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7072
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7073
        // limited, should not cause the txn commit failed.
7074
70
        for (const auto& key : copy_file_keys) {
7075
70
            txn->remove(key);
7076
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7077
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7078
70
                      << ", query_id=" << copy_id;
7079
70
        }
7080
7
        txn->remove(k);
7081
7
        TxnErrorCode err = txn->commit();
7082
7
        if (err != TxnErrorCode::TXN_OK) {
7083
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7084
0
            return -1;
7085
0
        }
7086
7087
7
        metrics_context.total_recycled_num = ++num_recycled;
7088
7
        metrics_context.report();
7089
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7090
7
        return 0;
7091
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6981
16
                         this](std::string_view k, std::string_view v) -> int {
6982
16
        ++num_scanned;
6983
16
        CopyJobPB copy_job;
6984
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6985
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6986
0
            return -1;
6987
0
        }
6988
6989
        // decode copy job key
6990
16
        auto k1 = k;
6991
16
        k1.remove_prefix(1);
6992
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6993
16
        decode_key(&k1, &out);
6994
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6995
        // -> CopyJobPB
6996
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6997
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6998
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6999
7000
16
        bool check_storage = true;
7001
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7002
12
            ++num_finished;
7003
7004
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7005
7
                auto it = stage_accessor_map.find(stage_id);
7006
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7007
7
                std::string_view path;
7008
7
                if (it != stage_accessor_map.end()) {
7009
2
                    accessor = it->second;
7010
5
                } else {
7011
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7012
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7013
5
                                                      &inner_accessor);
7014
5
                    if (ret < 0) { // error
7015
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7016
0
                        return -1;
7017
5
                    } else if (ret == 0) {
7018
3
                        path = inner_accessor->uri();
7019
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7020
3
                                inner_accessor, batch_count, txn_kv_.get());
7021
3
                        stage_accessor_map.emplace(stage_id, accessor);
7022
3
                    } else { // stage not found, skip check storage
7023
2
                        check_storage = false;
7024
2
                    }
7025
5
                }
7026
7
                if (check_storage) {
7027
                    // TODO delete objects with key and etag is not supported
7028
5
                    accessor->add(std::move(copy_job), std::string(k),
7029
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7030
5
                    return 0;
7031
5
                }
7032
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7033
5
                int64_t current_time =
7034
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7035
5
                if (copy_job.finish_time_ms() > 0) {
7036
2
                    if (!config::force_immediate_recycle &&
7037
2
                        current_time < copy_job.finish_time_ms() +
7038
2
                                               config::copy_job_max_retention_second * 1000) {
7039
1
                        return 0;
7040
1
                    }
7041
3
                } else {
7042
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7043
3
                    if (!config::force_immediate_recycle &&
7044
3
                        current_time < copy_job.start_time_ms() +
7045
3
                                               config::copy_job_max_retention_second * 1000) {
7046
1
                        return 0;
7047
1
                    }
7048
3
                }
7049
5
            }
7050
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7051
4
            int64_t current_time =
7052
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7053
            // if copy job is timeout: delete all copy file kvs and copy job kv
7054
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7055
2
                return 0;
7056
2
            }
7057
2
            ++num_expired;
7058
2
        }
7059
7060
        // delete all copy files
7061
7
        std::vector<std::string> copy_file_keys;
7062
70
        for (auto& file : copy_job.object_files()) {
7063
70
            copy_file_keys.push_back(copy_file_key(
7064
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7065
70
        }
7066
7
        std::unique_ptr<Transaction> txn;
7067
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7068
0
            LOG(WARNING) << "failed to create txn";
7069
0
            return -1;
7070
0
        }
7071
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7072
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7073
        // limited, should not cause the txn commit failed.
7074
70
        for (const auto& key : copy_file_keys) {
7075
70
            txn->remove(key);
7076
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7077
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7078
70
                      << ", query_id=" << copy_id;
7079
70
        }
7080
7
        txn->remove(k);
7081
7
        TxnErrorCode err = txn->commit();
7082
7
        if (err != TxnErrorCode::TXN_OK) {
7083
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7084
0
            return -1;
7085
0
        }
7086
7087
7
        metrics_context.total_recycled_num = ++num_recycled;
7088
7
        metrics_context.report();
7089
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7090
7
        return 0;
7091
7
    };
7092
7093
13
    if (config::enable_recycler_stats_metrics) {
7094
0
        scan_and_statistics_copy_jobs();
7095
0
    }
7096
    // recycle_func and loop_done for scan and recycle
7097
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7098
13
}
7099
7100
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7101
                                             const StagePB::StageType& stage_type,
7102
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7103
5
#ifdef UNIT_TEST
7104
    // In unit test, external use the same accessor as the internal stage
7105
5
    auto it = accessor_map_.find(stage_id);
7106
5
    if (it != accessor_map_.end()) {
7107
3
        *accessor = it->second;
7108
3
    } else {
7109
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7110
2
        return 1;
7111
2
    }
7112
#else
7113
    // init s3 accessor and add to accessor map
7114
    auto stage_it =
7115
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7116
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7117
7118
    if (stage_it == instance_info_.stages().end()) {
7119
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7120
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7121
        return 1;
7122
    }
7123
7124
    const auto& object_store_info = stage_it->obj_info();
7125
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7126
7127
    S3Conf s3_conf;
7128
    if (stage_type == StagePB::EXTERNAL) {
7129
        if (stage_access_type == StagePB::AKSK) {
7130
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7131
            if (!conf) {
7132
                return -1;
7133
            }
7134
7135
            s3_conf = std::move(*conf);
7136
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7137
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7138
            if (!conf) {
7139
                return -1;
7140
            }
7141
7142
            s3_conf = std::move(*conf);
7143
            if (instance_info_.ram_user().has_encryption_info()) {
7144
                AkSkPair plain_ak_sk_pair;
7145
                int ret = decrypt_ak_sk_helper(
7146
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7147
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7148
                if (ret != 0) {
7149
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7150
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7151
                    return -1;
7152
                }
7153
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7154
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7155
            } else {
7156
                s3_conf.ak = instance_info_.ram_user().ak();
7157
                s3_conf.sk = instance_info_.ram_user().sk();
7158
            }
7159
        } else {
7160
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7161
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7162
            return -1;
7163
        }
7164
    } else if (stage_type == StagePB::INTERNAL) {
7165
        int idx = stoi(object_store_info.id());
7166
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7167
            LOG(WARNING) << "invalid idx: " << idx;
7168
            return -1;
7169
        }
7170
7171
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7172
        auto conf = S3Conf::from_obj_store_info(old_obj);
7173
        if (!conf) {
7174
            return -1;
7175
        }
7176
7177
        s3_conf = std::move(*conf);
7178
        s3_conf.prefix = object_store_info.prefix();
7179
    } else {
7180
        LOG(WARNING) << "unknown stage type " << stage_type;
7181
        return -1;
7182
    }
7183
7184
    std::shared_ptr<S3Accessor> s3_accessor;
7185
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7186
    if (ret != 0) {
7187
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7188
        return -1;
7189
    }
7190
7191
    *accessor = std::move(s3_accessor);
7192
#endif
7193
3
    return 0;
7194
5
}
7195
7196
11
int InstanceRecycler::recycle_stage() {
7197
11
    int64_t num_scanned = 0;
7198
11
    int64_t num_recycled = 0;
7199
11
    const std::string task_name = "recycle_stage";
7200
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7201
7202
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7203
7204
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7205
11
    register_recycle_task(task_name, start_time);
7206
7207
11
    DORIS_CLOUD_DEFER {
7208
11
        unregister_recycle_task(task_name);
7209
11
        int64_t cost =
7210
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7211
11
        metrics_context.finish_report();
7212
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7213
11
                .tag("instance_id", instance_id_)
7214
11
                .tag("num_scanned", num_scanned)
7215
11
                .tag("num_recycled", num_recycled);
7216
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7207
11
    DORIS_CLOUD_DEFER {
7208
11
        unregister_recycle_task(task_name);
7209
11
        int64_t cost =
7210
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7211
11
        metrics_context.finish_report();
7212
        LOG_WARNING("recycle stage, cost={}s", cost)
7213
11
                .tag("instance_id", instance_id_)
7214
11
                .tag("num_scanned", num_scanned)
7215
11
                .tag("num_recycled", num_recycled);
7216
11
    };
7217
7218
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7219
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7220
11
    std::string key0 = recycle_stage_key(key_info0);
7221
11
    std::string key1 = recycle_stage_key(key_info1);
7222
7223
11
    std::vector<std::string_view> stage_keys;
7224
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7225
11
                         this](std::string_view k, std::string_view v) -> int {
7226
1
        ++num_scanned;
7227
1
        RecycleStagePB recycle_stage;
7228
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7229
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7230
0
            return -1;
7231
0
        }
7232
7233
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7234
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7235
0
            LOG(WARNING) << "invalid idx: " << idx;
7236
0
            return -1;
7237
0
        }
7238
7239
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7240
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7241
1
                [&] {
7242
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7243
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7244
1
                    if (!s3_conf) {
7245
1
                        return -1;
7246
1
                    }
7247
7248
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7249
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7250
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7251
1
                    if (ret != 0) {
7252
1
                        return -1;
7253
1
                    }
7254
7255
1
                    accessor = std::move(s3_accessor);
7256
1
                    return 0;
7257
1
                }(),
7258
1
                "recycle_stage:get_accessor", &accessor);
7259
7260
1
        if (ret != 0) {
7261
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7262
0
            return ret;
7263
0
        }
7264
7265
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7266
1
                .tag("instance_id", instance_id_)
7267
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7268
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7269
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7270
1
                .tag("obj_info_id", idx)
7271
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7272
1
        ret = accessor->delete_all();
7273
1
        if (ret != 0) {
7274
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7275
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7276
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7277
0
                         << ", ret=" << ret;
7278
0
            return -1;
7279
0
        }
7280
1
        metrics_context.total_recycled_num = ++num_recycled;
7281
1
        metrics_context.report();
7282
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7283
1
        stage_keys.push_back(k);
7284
1
        return 0;
7285
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7225
1
                         this](std::string_view k, std::string_view v) -> int {
7226
1
        ++num_scanned;
7227
1
        RecycleStagePB recycle_stage;
7228
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7229
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7230
0
            return -1;
7231
0
        }
7232
7233
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7234
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7235
0
            LOG(WARNING) << "invalid idx: " << idx;
7236
0
            return -1;
7237
0
        }
7238
7239
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7240
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7241
1
                [&] {
7242
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7243
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7244
1
                    if (!s3_conf) {
7245
1
                        return -1;
7246
1
                    }
7247
7248
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7249
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7250
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7251
1
                    if (ret != 0) {
7252
1
                        return -1;
7253
1
                    }
7254
7255
1
                    accessor = std::move(s3_accessor);
7256
1
                    return 0;
7257
1
                }(),
7258
1
                "recycle_stage:get_accessor", &accessor);
7259
7260
1
        if (ret != 0) {
7261
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7262
0
            return ret;
7263
0
        }
7264
7265
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7266
1
                .tag("instance_id", instance_id_)
7267
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7268
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7269
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7270
1
                .tag("obj_info_id", idx)
7271
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7272
1
        ret = accessor->delete_all();
7273
1
        if (ret != 0) {
7274
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7275
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7276
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7277
0
                         << ", ret=" << ret;
7278
0
            return -1;
7279
0
        }
7280
1
        metrics_context.total_recycled_num = ++num_recycled;
7281
1
        metrics_context.report();
7282
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7283
1
        stage_keys.push_back(k);
7284
1
        return 0;
7285
1
    };
7286
7287
11
    auto loop_done = [&stage_keys, this]() -> int {
7288
1
        if (stage_keys.empty()) return 0;
7289
1
        DORIS_CLOUD_DEFER {
7290
1
            stage_keys.clear();
7291
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7289
1
        DORIS_CLOUD_DEFER {
7290
1
            stage_keys.clear();
7291
1
        };
7292
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7293
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7294
0
            return -1;
7295
0
        }
7296
1
        return 0;
7297
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7287
1
    auto loop_done = [&stage_keys, this]() -> int {
7288
1
        if (stage_keys.empty()) return 0;
7289
1
        DORIS_CLOUD_DEFER {
7290
1
            stage_keys.clear();
7291
1
        };
7292
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7293
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7294
0
            return -1;
7295
0
        }
7296
1
        return 0;
7297
1
    };
7298
11
    if (config::enable_recycler_stats_metrics) {
7299
0
        scan_and_statistics_stage();
7300
0
    }
7301
    // recycle_func and loop_done for scan and recycle
7302
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7303
11
}
7304
7305
10
int InstanceRecycler::recycle_expired_stage_objects() {
7306
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7307
7308
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7309
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7310
7311
10
    DORIS_CLOUD_DEFER {
7312
10
        int64_t cost =
7313
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7314
10
        metrics_context.finish_report();
7315
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7316
10
                .tag("instance_id", instance_id_);
7317
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7311
10
    DORIS_CLOUD_DEFER {
7312
10
        int64_t cost =
7313
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7314
10
        metrics_context.finish_report();
7315
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7316
10
                .tag("instance_id", instance_id_);
7317
10
    };
7318
7319
10
    int ret = 0;
7320
7321
10
    if (config::enable_recycler_stats_metrics) {
7322
0
        scan_and_statistics_expired_stage_objects();
7323
0
    }
7324
7325
10
    for (const auto& stage : instance_info_.stages()) {
7326
0
        std::stringstream ss;
7327
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7328
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7329
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7330
0
           << ", prefix=" << stage.obj_info().prefix();
7331
7332
0
        if (stopped()) {
7333
0
            break;
7334
0
        }
7335
0
        if (stage.type() == StagePB::EXTERNAL) {
7336
0
            continue;
7337
0
        }
7338
0
        int idx = stoi(stage.obj_info().id());
7339
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7340
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7341
0
            continue;
7342
0
        }
7343
7344
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7345
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7346
0
        if (!s3_conf) {
7347
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7348
0
            continue;
7349
0
        }
7350
7351
0
        s3_conf->prefix = stage.obj_info().prefix();
7352
0
        std::shared_ptr<S3Accessor> accessor;
7353
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7354
0
        if (ret1 != 0) {
7355
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7356
0
            ret = -1;
7357
0
            continue;
7358
0
        }
7359
7360
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7361
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7362
0
            ret = -1;
7363
0
            continue;
7364
0
        }
7365
7366
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7367
0
        int64_t expiration_time =
7368
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7369
0
                config::internal_stage_objects_expire_time_second;
7370
0
        if (config::force_immediate_recycle) {
7371
0
            expiration_time = INT64_MAX;
7372
0
        }
7373
0
        ret1 = accessor->delete_all(expiration_time);
7374
0
        if (ret1 != 0) {
7375
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7376
0
                         << ss.str();
7377
0
            ret = -1;
7378
0
            continue;
7379
0
        }
7380
0
        metrics_context.total_recycled_num++;
7381
0
        metrics_context.report();
7382
0
    }
7383
10
    return ret;
7384
10
}
7385
7386
212
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7387
212
    std::lock_guard lock(recycle_tasks_mutex);
7388
212
    running_recycle_tasks[task_name] = start_time;
7389
212
}
7390
7391
212
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7392
212
    std::lock_guard lock(recycle_tasks_mutex);
7393
212
    DCHECK(running_recycle_tasks[task_name] > 0);
7394
212
    running_recycle_tasks.erase(task_name);
7395
212
}
7396
7397
21
bool InstanceRecycler::check_recycle_tasks() {
7398
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7399
21
    {
7400
21
        std::lock_guard lock(recycle_tasks_mutex);
7401
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7402
21
    }
7403
7404
21
    bool found = false;
7405
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7406
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7407
20
        int64_t cost = now - start_time;
7408
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7409
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7410
20
                    .tag("instance_id", instance_id_)
7411
20
                    .tag("task", task_name);
7412
20
            found = true;
7413
20
        }
7414
20
    }
7415
7416
21
    return found;
7417
21
}
7418
7419
// Scan and statistics indexes that need to be recycled
7420
0
int InstanceRecycler::scan_and_statistics_indexes() {
7421
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7422
7423
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7424
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7425
0
    std::string index_key0;
7426
0
    std::string index_key1;
7427
0
    recycle_index_key(index_key_info0, &index_key0);
7428
0
    recycle_index_key(index_key_info1, &index_key1);
7429
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7430
7431
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7432
0
        RecycleIndexPB index_pb;
7433
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7434
0
            return 0;
7435
0
        }
7436
0
        int64_t current_time = ::time(nullptr);
7437
0
        if (current_time <
7438
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7439
0
            return 0;
7440
0
        }
7441
        // decode index_id
7442
0
        auto k1 = k;
7443
0
        k1.remove_prefix(1);
7444
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7445
0
        decode_key(&k1, &out);
7446
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7447
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7448
0
        std::unique_ptr<Transaction> txn;
7449
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7450
0
        if (err != TxnErrorCode::TXN_OK) {
7451
0
            return 0;
7452
0
        }
7453
0
        std::string val;
7454
0
        err = txn->get(k, &val);
7455
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7456
0
            return 0;
7457
0
        }
7458
0
        if (err != TxnErrorCode::TXN_OK) {
7459
0
            return 0;
7460
0
        }
7461
0
        index_pb.Clear();
7462
0
        if (!index_pb.ParseFromString(val)) {
7463
0
            return 0;
7464
0
        }
7465
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7466
0
            return 0;
7467
0
        }
7468
0
        metrics_context.total_need_recycle_num++;
7469
0
        return 0;
7470
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7471
7472
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7473
0
    metrics_context.report(true);
7474
0
    segment_metrics_context_.report(true);
7475
0
    tablet_metrics_context_.report(true);
7476
0
    return ret;
7477
0
}
7478
7479
// Scan and statistics partitions that need to be recycled
7480
0
int InstanceRecycler::scan_and_statistics_partitions() {
7481
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7482
7483
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7484
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7485
0
    std::string part_key0;
7486
0
    std::string part_key1;
7487
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7488
7489
0
    recycle_partition_key(part_key_info0, &part_key0);
7490
0
    recycle_partition_key(part_key_info1, &part_key1);
7491
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7492
0
        RecyclePartitionPB part_pb;
7493
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7494
0
            return 0;
7495
0
        }
7496
0
        int64_t current_time = ::time(nullptr);
7497
0
        if (current_time <
7498
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7499
0
            return 0;
7500
0
        }
7501
        // decode partition_id
7502
0
        auto k1 = k;
7503
0
        k1.remove_prefix(1);
7504
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7505
0
        decode_key(&k1, &out);
7506
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7507
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7508
        // Change state to RECYCLING
7509
0
        std::unique_ptr<Transaction> txn;
7510
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7511
0
        if (err != TxnErrorCode::TXN_OK) {
7512
0
            return 0;
7513
0
        }
7514
0
        std::string val;
7515
0
        err = txn->get(k, &val);
7516
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7517
0
            return 0;
7518
0
        }
7519
0
        if (err != TxnErrorCode::TXN_OK) {
7520
0
            return 0;
7521
0
        }
7522
0
        part_pb.Clear();
7523
0
        if (!part_pb.ParseFromString(val)) {
7524
0
            return 0;
7525
0
        }
7526
        // Partitions with PREPARED state MUST have no data
7527
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7528
0
        int ret = 0;
7529
0
        for (int64_t index_id : part_pb.index_id()) {
7530
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7531
0
                                            partition_id, is_empty_tablet) != 0) {
7532
0
                ret = 0;
7533
0
            }
7534
0
        }
7535
0
        metrics_context.total_need_recycle_num++;
7536
0
        return ret;
7537
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7538
7539
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7540
0
    metrics_context.report(true);
7541
0
    segment_metrics_context_.report(true);
7542
0
    tablet_metrics_context_.report(true);
7543
0
    return ret;
7544
0
}
7545
7546
// Scan and statistics rowsets that need to be recycled
7547
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7548
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7549
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7550
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7551
0
    std::string recyc_rs_key0;
7552
0
    std::string recyc_rs_key1;
7553
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7554
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7555
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7556
7557
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7558
0
        RecycleRowsetPB rowset;
7559
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7560
0
            return 0;
7561
0
        }
7562
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7563
0
        int64_t current_time = ::time(nullptr);
7564
0
        if (current_time <
7565
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7566
0
            return 0;
7567
0
        }
7568
7569
0
        if (!rowset.has_type()) {
7570
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7571
0
                return 0;
7572
0
            }
7573
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7574
0
                return 0;
7575
0
            }
7576
0
            metrics_context.total_need_recycle_num++;
7577
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7578
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7579
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7580
0
            return 0;
7581
0
        }
7582
7583
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7584
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7585
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7586
0
            return 0;
7587
0
        }
7588
7589
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7590
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7591
0
                return 0;
7592
0
            }
7593
0
        }
7594
0
        metrics_context.total_need_recycle_num++;
7595
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7596
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7597
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7598
0
        return 0;
7599
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7600
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7601
0
    metrics_context.report(true);
7602
0
    segment_metrics_context_.report(true);
7603
0
    return ret;
7604
0
}
7605
7606
// Scan and statistics tmp_rowsets that need to be recycled
7607
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7608
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7609
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7610
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7611
0
    std::string tmp_rs_key0;
7612
0
    std::string tmp_rs_key1;
7613
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7614
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7615
7616
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7617
7618
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7619
0
        doris::RowsetMetaCloudPB rowset;
7620
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7621
0
            return 0;
7622
0
        }
7623
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7624
0
        int64_t current_time = ::time(nullptr);
7625
0
        if (current_time < expiration) {
7626
0
            return 0;
7627
0
        }
7628
7629
0
        DCHECK_GT(rowset.txn_id(), 0)
7630
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7631
7632
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7633
0
            return 0;
7634
0
        }
7635
7636
0
        if (!rowset.has_resource_id()) {
7637
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7638
0
                return 0;
7639
0
            }
7640
0
            return 0;
7641
0
        }
7642
7643
0
        metrics_context.total_need_recycle_num++;
7644
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7645
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7646
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7647
0
        return 0;
7648
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7649
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7650
0
    metrics_context.report(true);
7651
0
    segment_metrics_context_.report(true);
7652
0
    return ret;
7653
0
}
7654
7655
// Scan and statistics abort_timeout_txn that need to be recycled
7656
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7657
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7658
7659
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7660
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7661
0
    std::string begin_txn_running_key;
7662
0
    std::string end_txn_running_key;
7663
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7664
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7665
7666
0
    int64_t current_time =
7667
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7668
7669
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7670
0
                                               std::string_view k, std::string_view v) -> int {
7671
0
        std::unique_ptr<Transaction> txn;
7672
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7673
0
        if (err != TxnErrorCode::TXN_OK) {
7674
0
            return 0;
7675
0
        }
7676
0
        std::string_view k1 = k;
7677
0
        k1.remove_prefix(1);
7678
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7679
0
        if (decode_key(&k1, &out) != 0) {
7680
0
            return 0;
7681
0
        }
7682
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7683
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7684
        // Update txn_info
7685
0
        std::string txn_inf_key, txn_inf_val;
7686
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7687
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7688
0
        if (err != TxnErrorCode::TXN_OK) {
7689
0
            return 0;
7690
0
        }
7691
0
        TxnInfoPB txn_info;
7692
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7693
0
            return 0;
7694
0
        }
7695
7696
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7697
0
            TxnRunningPB txn_running_pb;
7698
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7699
0
                return 0;
7700
0
            }
7701
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7702
0
                return 0;
7703
0
            }
7704
0
            metrics_context.total_need_recycle_num++;
7705
0
        }
7706
0
        return 0;
7707
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7708
7709
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7710
0
    metrics_context.report(true);
7711
0
    return ret;
7712
0
}
7713
7714
// Scan and statistics expired_txn_label that need to be recycled
7715
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7716
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7717
7718
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7719
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7720
0
    std::string begin_recycle_txn_key;
7721
0
    std::string end_recycle_txn_key;
7722
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7723
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7724
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7725
0
    int64_t current_time_ms =
7726
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7727
7728
    // for calculate the total num or bytes of recyled objects
7729
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7730
0
        RecycleTxnPB recycle_txn_pb;
7731
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7732
0
            return 0;
7733
0
        }
7734
0
        if ((config::force_immediate_recycle) ||
7735
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7736
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7737
0
             current_time_ms)) {
7738
0
            metrics_context.total_need_recycle_num++;
7739
0
        }
7740
0
        return 0;
7741
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7742
7743
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7744
0
    metrics_context.report(true);
7745
0
    return ret;
7746
0
}
7747
7748
// Scan and statistics copy_jobs that need to be recycled
7749
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7750
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7751
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7752
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7753
0
    std::string key0;
7754
0
    std::string key1;
7755
0
    copy_job_key(key_info0, &key0);
7756
0
    copy_job_key(key_info1, &key1);
7757
7758
    // for calculate the total num or bytes of recyled objects
7759
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7760
0
        CopyJobPB copy_job;
7761
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7762
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7763
0
            return 0;
7764
0
        }
7765
7766
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7767
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7768
0
                int64_t current_time =
7769
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7770
0
                if (copy_job.finish_time_ms() > 0) {
7771
0
                    if (!config::force_immediate_recycle &&
7772
0
                        current_time < copy_job.finish_time_ms() +
7773
0
                                               config::copy_job_max_retention_second * 1000) {
7774
0
                        return 0;
7775
0
                    }
7776
0
                } else {
7777
0
                    if (!config::force_immediate_recycle &&
7778
0
                        current_time < copy_job.start_time_ms() +
7779
0
                                               config::copy_job_max_retention_second * 1000) {
7780
0
                        return 0;
7781
0
                    }
7782
0
                }
7783
0
            }
7784
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7785
0
            int64_t current_time =
7786
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7787
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7788
0
                return 0;
7789
0
            }
7790
0
        }
7791
0
        metrics_context.total_need_recycle_num++;
7792
0
        return 0;
7793
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7794
7795
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7796
0
    metrics_context.report(true);
7797
0
    return ret;
7798
0
}
7799
7800
// Scan and statistics stage that need to be recycled
7801
0
int InstanceRecycler::scan_and_statistics_stage() {
7802
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7803
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7804
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7805
0
    std::string key0 = recycle_stage_key(key_info0);
7806
0
    std::string key1 = recycle_stage_key(key_info1);
7807
7808
    // for calculate the total num or bytes of recyled objects
7809
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7810
0
                                                        std::string_view v) -> int {
7811
0
        RecycleStagePB recycle_stage;
7812
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7813
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7814
0
            return 0;
7815
0
        }
7816
7817
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7818
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7819
0
            LOG(WARNING) << "invalid idx: " << idx;
7820
0
            return 0;
7821
0
        }
7822
7823
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7824
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7825
0
                [&] {
7826
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7827
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7828
0
                    if (!s3_conf) {
7829
0
                        return 0;
7830
0
                    }
7831
7832
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7833
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7834
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7835
0
                    if (ret != 0) {
7836
0
                        return 0;
7837
0
                    }
7838
7839
0
                    accessor = std::move(s3_accessor);
7840
0
                    return 0;
7841
0
                }(),
7842
0
                "recycle_stage:get_accessor", &accessor);
7843
7844
0
        if (ret != 0) {
7845
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7846
0
            return 0;
7847
0
        }
7848
7849
0
        metrics_context.total_need_recycle_num++;
7850
0
        return 0;
7851
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7852
7853
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7854
0
    metrics_context.report(true);
7855
0
    return ret;
7856
0
}
7857
7858
// Scan and statistics expired_stage_objects that need to be recycled
7859
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7860
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7861
7862
    // for calculate the total num or bytes of recyled objects
7863
0
    auto scan_and_statistics = [&metrics_context, this]() {
7864
0
        for (const auto& stage : instance_info_.stages()) {
7865
0
            if (stopped()) {
7866
0
                break;
7867
0
            }
7868
0
            if (stage.type() == StagePB::EXTERNAL) {
7869
0
                continue;
7870
0
            }
7871
0
            int idx = stoi(stage.obj_info().id());
7872
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7873
0
                continue;
7874
0
            }
7875
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7876
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7877
0
            if (!s3_conf) {
7878
0
                continue;
7879
0
            }
7880
0
            s3_conf->prefix = stage.obj_info().prefix();
7881
0
            std::shared_ptr<S3Accessor> accessor;
7882
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7883
0
            if (ret1 != 0) {
7884
0
                continue;
7885
0
            }
7886
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7887
0
                continue;
7888
0
            }
7889
0
            metrics_context.total_need_recycle_num++;
7890
0
        }
7891
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7892
7893
0
    scan_and_statistics();
7894
0
    metrics_context.report(true);
7895
0
    return 0;
7896
0
}
7897
7898
// Scan and statistics versions that need to be recycled
7899
0
int InstanceRecycler::scan_and_statistics_versions() {
7900
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7901
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7902
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7903
7904
0
    int64_t last_scanned_table_id = 0;
7905
0
    bool is_recycled = false; // Is last scanned kv recycled
7906
    // for calculate the total num or bytes of recyled objects
7907
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7908
0
                                       std::string_view k, std::string_view) {
7909
0
        auto k1 = k;
7910
0
        k1.remove_prefix(1);
7911
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7912
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7913
0
        decode_key(&k1, &out);
7914
0
        DCHECK_EQ(out.size(), 6) << k;
7915
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7916
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7917
0
            metrics_context.total_need_recycle_num +=
7918
0
                    is_recycled; // Version kv of this table has been recycled
7919
0
            return 0;
7920
0
        }
7921
0
        last_scanned_table_id = table_id;
7922
0
        is_recycled = false;
7923
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7924
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7925
0
        std::unique_ptr<Transaction> txn;
7926
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7927
0
        if (err != TxnErrorCode::TXN_OK) {
7928
0
            return 0;
7929
0
        }
7930
0
        std::unique_ptr<RangeGetIterator> iter;
7931
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7932
0
        if (err != TxnErrorCode::TXN_OK) {
7933
0
            return 0;
7934
0
        }
7935
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7936
0
            return 0;
7937
0
        }
7938
0
        metrics_context.total_need_recycle_num++;
7939
0
        is_recycled = true;
7940
0
        return 0;
7941
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7942
7943
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7944
0
    metrics_context.report(true);
7945
0
    return ret;
7946
0
}
7947
7948
// Scan and statistics restore jobs that need to be recycled
7949
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7950
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7951
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7952
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7953
0
    std::string restore_job_key0;
7954
0
    std::string restore_job_key1;
7955
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7956
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7957
7958
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7959
7960
    // for calculate the total num or bytes of recyled objects
7961
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7962
0
        RestoreJobCloudPB restore_job_pb;
7963
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7964
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7965
0
            return 0;
7966
0
        }
7967
0
        int64_t expiration =
7968
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7969
0
        int64_t current_time = ::time(nullptr);
7970
0
        if (current_time < expiration) { // not expired
7971
0
            return 0;
7972
0
        }
7973
0
        metrics_context.total_need_recycle_num++;
7974
0
        if(restore_job_pb.need_recycle_data()) {
7975
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7976
0
        }
7977
0
        return 0;
7978
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7979
7980
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7981
0
    metrics_context.report(true);
7982
0
    return ret;
7983
0
}
7984
7985
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7986
3
    if (!should_recycle_versioned_keys()) {
7987
0
        return;
7988
0
    }
7989
7990
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7991
7992
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7993
3
    if (recycle_checker.init() != 0) {
7994
0
        return;
7995
0
    }
7996
7997
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7998
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7999
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8000
8001
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8002
8
    for (; iter->valid(); iter->next()) {
8003
5
        OperationLogPB operation_log;
8004
5
        if (!iter->parse_value(&operation_log)) {
8005
0
            continue;
8006
0
        }
8007
8008
5
        std::string_view key = iter->key();
8009
5
        Versionstamp log_versionstamp;
8010
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8011
0
            continue;
8012
0
        }
8013
8014
5
        OperationLogReferenceInfo ref_info;
8015
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8016
5
                                         &ref_info)) {
8017
4
            metrics_context.total_need_recycle_num++;
8018
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8019
4
        }
8020
5
    }
8021
8022
3
    metrics_context.report(true);
8023
3
}
8024
8025
int InstanceRecycler::classify_rowset_task_by_ref_count(
8026
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8027
60
    constexpr int MAX_RETRY = 10;
8028
60
    const auto& rowset_meta = task.rowset_meta;
8029
60
    int64_t tablet_id = rowset_meta.tablet_id();
8030
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8031
60
    std::string_view reference_instance_id = instance_id_;
8032
60
    if (rowset_meta.has_reference_instance_id()) {
8033
5
        reference_instance_id = rowset_meta.reference_instance_id();
8034
5
    }
8035
8036
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8037
61
        std::unique_ptr<Transaction> txn;
8038
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8039
61
        if (err != TxnErrorCode::TXN_OK) {
8040
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8041
0
                    .tag("instance_id", instance_id_)
8042
0
                    .tag("tablet_id", tablet_id)
8043
0
                    .tag("rowset_id", rowset_id)
8044
0
                    .tag("err", err);
8045
0
            return -1;
8046
0
        }
8047
8048
61
        std::string rowset_ref_count_key =
8049
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8050
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8051
8052
61
        int64_t ref_count = 0;
8053
61
        {
8054
61
            std::string value;
8055
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8056
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8057
0
                ref_count = 1;
8058
61
            } else if (err != TxnErrorCode::TXN_OK) {
8059
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8060
0
                        .tag("instance_id", instance_id_)
8061
0
                        .tag("tablet_id", tablet_id)
8062
0
                        .tag("rowset_id", rowset_id)
8063
0
                        .tag("err", err);
8064
0
                return -1;
8065
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8066
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8067
0
                        .tag("instance_id", instance_id_)
8068
0
                        .tag("tablet_id", tablet_id)
8069
0
                        .tag("rowset_id", rowset_id)
8070
0
                        .tag("value", hex(value));
8071
0
                return -1;
8072
0
            }
8073
61
        }
8074
8075
61
        if (ref_count > 1) {
8076
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8077
12
            txn->atomic_add(rowset_ref_count_key, -1);
8078
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8079
12
                    .tag("instance_id", instance_id_)
8080
12
                    .tag("tablet_id", tablet_id)
8081
12
                    .tag("rowset_id", rowset_id)
8082
12
                    .tag("ref_count", ref_count - 1)
8083
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8084
8085
12
            if (!task.recycle_rowset_key.empty()) {
8086
0
                txn->remove(task.recycle_rowset_key);
8087
0
                LOG_INFO("remove recycle rowset key in classification phase")
8088
0
                        .tag("key", hex(task.recycle_rowset_key));
8089
0
            }
8090
12
            if (!task.non_versioned_rowset_key.empty()) {
8091
12
                txn->remove(task.non_versioned_rowset_key);
8092
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8093
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8094
12
            }
8095
8096
12
            err = txn->commit();
8097
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8098
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8099
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8100
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8101
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8102
1
                continue;
8103
11
            } else if (err != TxnErrorCode::TXN_OK) {
8104
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8105
0
                        .tag("instance_id", instance_id_)
8106
0
                        .tag("tablet_id", tablet_id)
8107
0
                        .tag("rowset_id", rowset_id)
8108
0
                        .tag("err", err);
8109
0
                return -1;
8110
0
            }
8111
11
            return 1; // handled, not added to batch delete
8112
49
        } else {
8113
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8114
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8115
49
            LOG_INFO("add rowset to batch delete plan")
8116
49
                    .tag("instance_id", instance_id_)
8117
49
                    .tag("tablet_id", tablet_id)
8118
49
                    .tag("rowset_id", rowset_id)
8119
49
                    .tag("resource_id", rowset_meta.resource_id())
8120
49
                    .tag("ref_count", ref_count);
8121
8122
49
            batch_delete_tasks.push_back(std::move(task));
8123
49
            return 0; // added to batch delete
8124
49
        }
8125
61
    }
8126
8127
0
    LOG_WARNING("failed to classify rowset task after retry")
8128
0
            .tag("instance_id", instance_id_)
8129
0
            .tag("tablet_id", tablet_id)
8130
0
            .tag("rowset_id", rowset_id)
8131
0
            .tag("retry", MAX_RETRY);
8132
0
    return -1;
8133
60
}
8134
8135
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8136
10
    int ret = 0;
8137
49
    for (const auto& task : tasks) {
8138
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8139
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8140
8141
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8142
        // so we don't need to call it again here.
8143
8144
        // Remove all metadata keys in one transaction
8145
49
        std::unique_ptr<Transaction> txn;
8146
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8147
49
        if (err != TxnErrorCode::TXN_OK) {
8148
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8149
0
                    .tag("instance_id", instance_id_)
8150
0
                    .tag("tablet_id", tablet_id)
8151
0
                    .tag("rowset_id", rowset_id)
8152
0
                    .tag("err", err);
8153
0
            ret = -1;
8154
0
            continue;
8155
0
        }
8156
8157
49
        std::string_view reference_instance_id = instance_id_;
8158
49
        if (task.rowset_meta.has_reference_instance_id()) {
8159
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8160
0
        }
8161
8162
49
        txn->remove(task.rowset_ref_count_key);
8163
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8164
49
                .tag("instance_id", instance_id_)
8165
49
                .tag("tablet_id", tablet_id)
8166
49
                .tag("rowset_id", rowset_id)
8167
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8168
8169
49
        std::string dbm_start_key =
8170
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8171
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8172
49
                {reference_instance_id, tablet_id, rowset_id,
8173
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8174
49
        txn->remove(dbm_start_key, dbm_end_key);
8175
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8176
49
                .tag("instance_id", instance_id_)
8177
49
                .tag("tablet_id", tablet_id)
8178
49
                .tag("rowset_id", rowset_id)
8179
49
                .tag("begin", hex(dbm_start_key))
8180
49
                .tag("end", hex(dbm_end_key));
8181
8182
49
        std::string versioned_dbm_start_key =
8183
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8184
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8185
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8186
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8187
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8188
49
                .tag("instance_id", instance_id_)
8189
49
                .tag("tablet_id", tablet_id)
8190
49
                .tag("rowset_id", rowset_id)
8191
49
                .tag("begin", hex(versioned_dbm_start_key))
8192
49
                .tag("end", hex(versioned_dbm_end_key));
8193
8194
        // Remove versioned meta rowset key
8195
49
        if (!task.versioned_rowset_key.empty()) {
8196
49
            versioned::document_remove<RowsetMetaCloudPB>(
8197
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8198
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8199
49
                    .tag("instance_id", instance_id_)
8200
49
                    .tag("tablet_id", tablet_id)
8201
49
                    .tag("rowset_id", rowset_id)
8202
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8203
49
        }
8204
8205
49
        if (!task.non_versioned_rowset_key.empty()) {
8206
49
            txn->remove(task.non_versioned_rowset_key);
8207
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8208
49
                    .tag("instance_id", instance_id_)
8209
49
                    .tag("tablet_id", tablet_id)
8210
49
                    .tag("rowset_id", rowset_id)
8211
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8212
49
        }
8213
8214
        // Remove recycle_rowset_key last to ensure retry safety:
8215
        // if cleanup fails, this key remains and triggers next round retry.
8216
49
        if (!task.recycle_rowset_key.empty()) {
8217
0
            txn->remove(task.recycle_rowset_key);
8218
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8219
0
                    .tag("instance_id", instance_id_)
8220
0
                    .tag("tablet_id", tablet_id)
8221
0
                    .tag("rowset_id", rowset_id)
8222
0
                    .tag("key", hex(task.recycle_rowset_key));
8223
0
        }
8224
8225
49
        err = txn->commit();
8226
49
        if (err != TxnErrorCode::TXN_OK) {
8227
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8228
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8229
0
                    .tag("instance_id", instance_id_)
8230
0
                    .tag("tablet_id", tablet_id)
8231
0
                    .tag("rowset_id", rowset_id)
8232
0
                    .tag("err", err);
8233
0
            ret = -1;
8234
0
            continue;
8235
0
        }
8236
8237
49
        LOG_INFO("cleanup rowset metadata success")
8238
49
                .tag("instance_id", instance_id_)
8239
49
                .tag("tablet_id", tablet_id)
8240
49
                .tag("rowset_id", rowset_id);
8241
49
    }
8242
10
    return ret;
8243
10
}
8244
8245
} // namespace doris::cloud